text:
import pytest
pytestmark = pytest.mark.needs_ipywe

interactive = False

import os
here = os.path.abspath(os.path.dirname(__file__))
datadir = os.path.join(here, '..', "data")

import numpy as np, histogram.hdf as hh
from multiphonon.ui import batch

import unittest
class TestCase(unittest.TestCase):

    def test1(self):
        "multiphonon.ui.getdos0"
        from multiphonon.ui import getdos0
        getdos0.notebookUI('sample.nxs', 'mt.nxs')
        getdos0.log_progress('message')
        return

    pass  # end of TestCase

def exec_cmd(cmd):
    if os.system(cmd):
        raise RuntimeError("%s failed" % cmd)

if __name__ == "__main__":
    interactive = True
    unittest.main()

# End of file


text:
To run the samples, please execute `npm start` from the root directory. Make sure you updated all dependencies by running `npm install` beforehand.

### Analyze Deep Learning structures

[The sample `models.html`](https://chaosmail.github.io/caffejs/models.html) loads famous Deep Learning Models such as AlexNet, VGG, GoogLeNet, etc. directly in your browser and visualizes the layer graph. It also analyzes their structure and prints detailed information such as the network dimension, number of parameters and network size in memory to the console.

Here is a break-down of **AlexNet** computed with CaffeJS. The dimensions on the left side define the output dimensions of the current layer `d, h, w`. The memory size is computed using Float32 (4 byte).

```
3x227x227 :: INPUT data
96x55x55 :: CONV conv1 96x11x11 Stride 4 Pad 0 => 34,944 parameters
96x55x55 :: RELU relu1
96x55x55 :: LRN norm1 alpha 0.0001 beta 0.75 k 1 n 5
96x27x27 :: MAX POOL pool1 3x3 Stride 2 Pad 0
256x27x27 :: CONV conv2 256x5x5 Stride 1 Pad 2 => 614,656 parameters
256x27x27 :: RELU relu2
256x27x27 :: LRN norm2 alpha 0.0001 beta 0.75 k 1 n 5
256x13x13 :: MAX POOL pool2 3x3 Stride 2 Pad 0
384x13x13 :: CONV conv3 384x3x3 Stride 1 Pad 1 => 885,120 parameters
384x13x13 :: RELU relu3
384x13x13 :: CONV conv4 384x3x3 Stride 1 Pad 1 => 1,327,488 parameters
384x13x13 :: RELU relu4
256x13x13 :: CONV conv5 256x3x3 Stride 1 Pad 1 => 884,992 parameters
256x13x13 :: RELU relu5
256x6x6 :: MAX POOL pool5 3x3 Stride 2 Pad 0
4096x1x1 :: FC fc6 => 37,752,832 parameters
4096x1x1 :: DROPOUT drop6
4096x1x1 :: RELU relu6
4096x1x1 :: FC fc7 => 16,781,312 parameters
4096x1x1 :: DROPOUT drop7
4096x1x1 :: RELU relu7
1000x1x1 :: FC fc8 => 4,097,000 parameters
1000x1x1 :: SOFTMAX prob
---
Total number of layers 24
Total number of params 62,378,344 (memory: 249.513376Mb):
```

Here is a break-down of **GoogLeNet** computed with CaffeJS (please note, that the layers of each inception module are not sequential as shown here but parallel).

```
3x224x224 :: INPUT data
64x113x113 :: CONV conv1/7x7_s2 64x7x7 Stride 2 Pad 3 => 9,472 parameters
64x113x113 :: RELU conv1/relu_7x7
64x56x56 :: MAX POOL pool1/3x3_s2 3x3 Stride 2 Pad 0
64x56x56 :: LRN pool1/norm1 alpha 0.0001 beta 0.75 k 1 n 5
64x56x56 :: CONV conv2/3x3_reduce 64x1x1 Stride 1 Pad 0 => 4,160 parameters
64x56x56 :: RELU conv2/relu_3x3_reduce
192x56x56 :: CONV conv2/3x3 192x3x3 Stride 1 Pad 1 => 110,784 parameters
192x56x56 :: RELU conv2/relu_3x3
192x56x56 :: LRN conv2/norm2 alpha 0.0001 beta 0.75 k 1 n 5
192x28x28 :: MAX POOL pool2/3x3_s2 3x3 Stride 2 Pad 0
...
1024x7x7 :: CONCAT inception_5b/output
1024x1x1 :: AVE POOL pool5/7x7_s1 7x7 Stride 1 Pad 0
1024x1x1 :: DROPOUT pool5/drop_7x7_s1
1000x1x1 :: FC loss3/classifier => 1,025,000 parameters
1000x1x1 :: SOFTMAX prob
---
Total number of layers 143
Total number of params 6,998,552 (memory: 27.994208Mb):
```

Please note that these samples don't load the networks' weights but only the structure with default initialization.

### Webcam Classification using GoogLeNet

[The demo `webcam.html`](https://chaosmail.github.io/caffejs/webcam.html) uses the pretrained GoogLeNet model from Caffe (trained on ImageNet) to perform classification entirely in your browser using images from your webcam.

### ImageNet Classification using SqueezeNet

[The demo `imagenet.html`](https://chaosmail.github.io/caffejs/imagenet.html) uses the pretrained SqueezeNet model (trained on ImageNet) to perform classification entirely in your browser using images from the ImageNet 2011 dataset.

### DeepDream

[The `deepdream.html`](https://chaosmail.github.io/caffejs/deepdream.html) is a cool example that runs the famous [DeepDream](https://github.com/google/deepdream/blob/master/dream.ipynb) demo entirely in your browser - entirely in JavaScript of course. It uses the pretrained GoogLeNet from Caffe and runs the computation as webworker.

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * Sends the notification to the specified host in a UDP packet.
 * @since 1.22
 */

class UDPRCFeedEngine implements RCFeedEngine {
	/**
	 * @see RCFeedEngine::send
	 */
	public function send( array $feed, $line ) {
		wfErrorLog( $line, $feed['uri'] );
	}
}


text:
Spree::Admin::NavigationHelper.class_eval do
  def link_to_blog_in_store(resource, options={})
    url = options[:url] || blog_entry_permalink(resource)
    #options[:data] = {:action => 'show'}
    link_to_with_icon('icon-view', Spree.t(:view_in_store), url, options)
  end
end


text:
set -e

OS_ARCH="linux-amd64"
VM_DRIVER="kvm2"
JOB_NAME="KVM_Linux"
EXPECTED_DEFAULT_DRIVER="kvm2"

# We pick kvm as our gvisor testbed because it is fast & reliable
EXTRA_TEST_ARGS="-gvisor"

mkdir -p cron && gsutil -qm rsync "gs://minikube-builds/${MINIKUBE_LOCATION}/cron" cron || echo "FAILED TO GET CRON FILES"
sudo install cron/cleanup_and_reboot_Linux.sh /etc/cron.hourly/cleanup_and_reboot || echo "FAILED TO INSTALL CLEANUP"

source ./common.sh


text:
using System;
using System.Collections.Generic;
using Microsoft.IdentityModel.TestUtils;
using Xunit;

namespace Microsoft.IdentityModel.Protocols.Tests
{
    /// <summary>
    /// Tests for AuthenticationProtocolMessage.
    /// </summary>
    public class AuthenticationProtocolMessageTests
    {
        [Fact]
        public void Defaults()
        {
            var context = new CompareContext();
            string issuerAddress = "http://www.gotjwt.com";
            var script = "<script language=\"javascript\">window.setTimeout(function() {document.forms[0].submit();}, 0);</script>";

            AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage();
            IdentityComparer.AreStringsEqual(authenticationProtocolMessage.IssuerAddress, string.Empty, context);

            authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = issuerAddress };
            IdentityComparer.AreStringsEqual(authenticationProtocolMessage.IssuerAddress, issuerAddress, context);

            if (!authenticationProtocolMessage.Script.Equals(script))
                context.Diffs.Add("The value of authenticationProtocolMessage.Script should be '" + script + "'.");

            if (authenticationProtocolMessage.Parameters == null)
                context.Diffs.Add("authenticationProtocolMessage.Parameters == null");

            if (authenticationProtocolMessage.Parameters.Count != 0)
                context.Diffs.Add("authenticationProtocolMessage.Parameters.Count != 0");

            TestUtilities.AssertFailIfErrors(context);
        }

        [Fact]
        public void GetSets()
        {
            var authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = "http://www.gotjwt.com" };

            var properties = new List<string>()
            {
                "IssuerAddress",
                "PostTitle",
                "Script",
                "ScriptButtonText",
                "ScriptDisabledText",
            };

            var context = new GetSetContext();
            foreach(string property in properties)
            {
                TestUtilities.SetGet(authenticationProtocolMessage, property, null, ExpectedException.ArgumentNullException(substringExpected: property), context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "", ExpectedException.NoExceptionExpected, context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, property, ExpectedException.NoExceptionExpected, context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "    ", ExpectedException.NoExceptionExpected, context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "\t\n\r", ExpectedException.NoExceptionExpected, context);
            }

            TestUtilities.AssertFailIfErrors(context.Errors);
        }

        [Fact]
        public void Publics()
        {
            string value1 = "value1";
            string value2 = "value2";
            string param1 = "param1";
            string param2 = "param2";

            AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = "http://www.gotjwt.com" };
            ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.GetParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.RemoveParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.SetParameter(null, null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.RemoveParameter(param2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value1);

            authenticationProtocolMessage.RemoveParameter(param1);
            Assert.Null(authenticationProtocolMessage.GetParameter(param1));

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.SetParameter(param1, value2);
            authenticationProtocolMessage.SetParameter(param2, value2);
            authenticationProtocolMessage.SetParameter(param2, value1);

            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param2), value1);

            authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = "http://www.gotjwt.com" };
            authenticationProtocolMessage.SetParameter("bob", "     ");

            string queryString = authenticationProtocolMessage.BuildRedirectUrl();
            Assert.NotNull(queryString);
            Assert.Contains("bob", queryString);

            authenticationProtocolMessage.IssuerAddress = string.Empty;
            queryString = authenticationProtocolMessage.BuildRedirectUrl();
            Assert.NotNull(queryString);
        }

        /// <summary>
        /// AuthenticationProtocolMessage is abstract use this to test.
        /// </summary>
        private class DerivedAuthenticationProtocolMessage : AuthenticationProtocolMessage
        {
            public DerivedAuthenticationProtocolMessage()
            { }
        }
    }
}


text:
* Before reporting a problem, always make sure that you have examined the existing documentation. Check the installation manuals and user guides of the relevant tool(s), and also check this repository for helpful information first.

# How to report technical problems

* Always write specifically what you are trying to accomplish, and what you are doing to accomplish it.
* Copy/paste a direct screenshot, command list or code fragment of the stuff you are doing.
* Copy/paste error output *directly*, or take a screenshot if that is not possible.
* Raise technical problems in the #technicalissues channel on the 42Brunel slack, raise them as "Issues" on GitHub only if you are 100% certain that it's a code issue.


text:
<?php
namespace Seven\FEBundle\Entity;

use Seven\FEBundle\Entity\Partial\BookingInfo;
use Seven\FEBundle\Entity\Partial\ExpirationCheck;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Seven\FEBundle\Entity\Partial\BasicInfo;

/**
 * @ORM\Entity(repositoryClass="Seven\FEBundle\Repository\MiscRepository")
 * @ORM\Table(name="miscellaneous")
 * @ORM\HasLifecycleCallbacks
 */
class Miscellaneous
{
    use BasicInfo;
    use BookingInfo;
    use ExpirationCheck;

    /**
     * @ORM\ManyToOne(targetEntity="Client", inversedBy="maintenance")
     */
    protected $client;

    /**
     * @ORM\ManyToOne(targetEntity="ProviderAccount", inversedBy="miscellaneouses")
     */
    protected $provider_account;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $username;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $password;

    /**
     * Set client
     *
     * @param \Seven\FEBundle\Entity\Client $client
     * @return Domain
     */
    public function setClient(\Seven\FEBundle\Entity\Client $client = null)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * Get client
     *
     * @return \Seven\FEBundle\Entity\Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return Miscellaneous
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return Miscellaneous
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set provider_account
     *
     * @param \Seven\FEBundle\Entity\ProviderAccount $providerAccount
     * @return Miscellaneous
     */
    public function setProviderAccount(\Seven\FEBundle\Entity\ProviderAccount $providerAccount = null)
    {
        $this->provider_account = $providerAccount;

        return $this;
    }

    /**
     * Get provider_account
     *
     * @return \Seven\FEBundle\Entity\ProviderAccount
     */
    public function getProviderAccount()
    {
        return $this->provider_account;
    }
}


text:
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
#include <utility>

/*
 * Solutions:
 *
 * 1. Using three for loops, we generate all triplets of numbers and store each sum in the vector<int> sums.
 * Then, we loop over all the sums and choose the one that is the closest to the target sum.
 *
 * Time complexity: O(n-cubed) [where n is the length of the input vector]
 * Space complexity: O(s) [where s is the number of triplet sums]
 *
 * 2. We sort the input vector and then for each number in the vector, we perform a bi-directional search
 * of the vector (starting from the left and right ends and moving towards the middle)to find the other
 * two numbers in our triplet. If the sum of the current triplet is the target value, then we return the sum.
 * If the sum is less than the target sum or the sum is greater than the target, we add it to our vector<int> sums.
 * Then, increment left or decrement right accordingly. After we having finished traversing the input vector,
 * we loop over all the sums and choose the one that is the closest to the target sum.
 *
 * Time complexity: O(n-squared) [where n is the length of the input vector]
 * Space complexity: O(s) [where s is the number of triplet sums]
 *
 * 3. Similar idea to the second solution except that we keep track of the closest sum as we traverse the input vector
 * and thus, don't need to allocate extra space for the sums vector.
 *
 * Time complexity: O(n-squared) [where n is the length of the input vector]
 * Space complexity: O(1)
 */

int threeSumClosest(std::vector<int> & nums, int target)
{
    if(nums.size() < 3)
    {
        return target;
    }

    auto n=nums.size();

    std::vector<int> sums;

    for(auto i=0;i<n-2;++i)
    {
        for(auto j=i+1;j<n-1;++j)
        {
            for(auto k=j+1;k<n;++k)
            {
                int sum=nums[i] + nums[j] + nums[k];

                sums.push_back(sum);
            }
        }
    }

    auto dist=std::abs(target - sums[0]);

    auto sum=sums[0];

    for(auto i=1;i<sums.size();++i)
    {
        auto currentDist=abs(target - sums[i]);

        if(currentDist < dist)
        {
            dist=currentDist;

            sum=sums[i];
        }
    }

    return sum;
}

int threeSumClosest(std::vector<int>& nums, int target)
{
    if(nums.size() < 3)
    {
        return target;
    }

    auto n=nums.size();

    int result=0;

    std::sort(nums.begin(), nums.end());

    std::vector<int> sums;

    for(auto i=0;i<n;++i)
    {
        auto left=i+1;

        auto right=n-1;

        while(left < right)
        {
            int sum=nums[i] + nums[left] + nums[right];

            if(sum==target)
            {
                return sum;
            }
            else if(sum < target)
            {
                sums.push_back(sum);

                left++;
            }
            else
            {
                sums.push_back(sum);

                right--;
            }
        }
    }

    result=sums[0];

    auto dist=std::abs(target - sums[0]);

    for(auto i=1;i<sums.size();++i)
    {
        auto currentDist=std::abs(target - sums[i]);

        if(currentDist < dist)
        {
            result=sums[i];

            dist=currentDist;
        }
    }

    return result;
}

int threeSumClosest(std::vector<int> & nums, int target)
{
    if(nums.size() < 3)
    {
        return target;
    }

    auto n=nums.size();

    std::sort(nums.begin(), nums.end());

    int result=nums[0] + nums[1] + nums[2];

    for(auto i=0;i<n;++i)
    {
        auto left=i+1;

        auto right=n-1;

        while(left < right)
        {
            int sum=nums[i] + nums[left] + nums[right];

            if(sum==target)
            {
                return sum;
            }
            else
            {
                if(std::abs(sum-target) < std::abs(result-target))
                {
                    result=sum;
                }

                if(sum < target)
                {
                    left++;
                }
                else
                {
                    right--;
                }
            }
        }
    }

    return result;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SpanInterpolator</title>
<meta name="date" content="2013-08-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.math.sample

Class SpanInterpolator

java.lang.Object

org.drip.math.sample.SpanInterpolator

public class SpanInterpolator
extends java.lang.Object

This class demonstrates the Span builder and usage API.

Constructor Summary

Constructors

Constructor and Description

SpanInterpolator()

Method Summary

Methods

Modifier and Type
Method and Description

static void
BasisSplineSpanTest(double[] adblX,
                   double[] adblY,
                   SegmentControlParams segControlParams)

Perform the following sequence of tests for a given segment control for a predictor/response range
        - Interpolate
  - Compute the segment-by-segment monotonicity
  - Span Jacobian
  - Span knot insertion

static SegmentControlParams
BernsteinPolynomialSegmentControlParams(int iNumBasis,
                                       SegmentInelasticParams segParams,
                                       AbstractUnivariate rsc)

Build Bernstein Polynomial Segment Control Parameters

static SegmentControlParams
ExponentialTensionSegmentControlParams(double dblTension,
                                      SegmentInelasticParams segParams,
                                      AbstractUnivariate rsc)

Build Exponential Tension Segment Control Parameters

static SegmentControlParams
HyperbolicTensionSegmentControlParams(double dblTension,
                                     SegmentInelasticParams segParams,
                                     AbstractUnivariate rsc)

Build Hyperbolic Tension Segment Control Parameters

static SegmentControlParams
KaklisPandelisSegmentControlParams(int iKPTensionDegree,
                                  SegmentInelasticParams segParams,
                                  AbstractUnivariate rsc)

Build Kaklis-Pandelis Segment Control Parameters

static void
main(java.lang.String[] astrArgs)

static SegmentControlParams
PolynomialSegmentControlParams(int iNumBasis,
                              SegmentInelasticParams segParams,
                              AbstractUnivariate rsc)

Build Polynomial Segment Control Parameters

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SpanInterpolator

public SpanInterpolator()

Method Detail

PolynomialSegmentControlParams

public static final SegmentControlParams PolynomialSegmentControlParams(int iNumBasis,
                                                  SegmentInelasticParams segParams,
                                                  AbstractUnivariate rsc)
                                                                 throws java.lang.Exception

Build Polynomial Segment Control Parameters

Parameters:

iNumBasis - Number of Polynomial Basis Functions

segParams - Inelastic Segment Parameters

rsc - Shape Controller

        WARNING: Insufficient Error Checking, so use caution

Returns:

Polynomial Segment Control Parameters

Throws:

java.lang.Exception

BernsteinPolynomialSegmentControlParams

public static final SegmentControlParams BernsteinPolynomialSegmentControlParams(int iNumBasis,
                                                           SegmentInelasticParams segParams,
                                                           AbstractUnivariate rsc)
                                                                          throws java.lang.Exception

Build Bernstein Polynomial Segment Control Parameters

Parameters:

iNumBasis - Number of Polynomial Basis Functions

segParams - Inelastic Segment Parameters

rsc - Shape Controller

        WARNING: Insufficient Error Checking, so use caution

Returns:

Bernstein Polynomial Segment Control Parameters

Throws:

java.lang.Exception

ExponentialTensionSegmentControlParams

public static final SegmentControlParams ExponentialTensionSegmentControlParams(double dblTension,
                                                          SegmentInelasticParams segParams,
                                                          AbstractUnivariate rsc)
                                                                         throws java.lang.Exception

Build Exponential Tension Segment Control Parameters

Parameters:

dblTension - Segment Tension

segParams - Inelastic Segment Parameters

rsc - Shape Controller

        WARNING: Insufficient Error Checking, so use caution

Returns:

Exponential Tension Segment Control Parameters

Throws:

java.lang.Exception

HyperbolicTensionSegmentControlParams

public static final SegmentControlParams HyperbolicTensionSegmentControlParams(double dblTension,
                                                         SegmentInelasticParams segParams,
                                                         AbstractUnivariate rsc)
                                                                        throws java.lang.Exception

Build Hyperbolic Tension Segment Control Parameters

Parameters:

dblTension - Segment Tension

segParams - Inelastic Segment Parameters

rsc - Shape Controller

        WARNING: Insufficient Error Checking, so use caution

Returns:

Hyperbolic Tension Segment Control Parameters

Throws:

java.lang.Exception

KaklisPandelisSegmentControlParams

public static final SegmentControlParams KaklisPandelisSegmentControlParams(int iKPTensionDegree,
                                                      SegmentInelasticParams segParams,
                                                      AbstractUnivariate rsc)
                                                                     throws java.lang.Exception

Build Kaklis-Pandelis Segment Control Parameters

Parameters:

iKPTensionDegree - KP Polynomial Tension Degree

segParams - Inelastic Segment Parameters

rsc - Shape Controller

        WARNING: Insufficient Error Checking, so use caution

Returns:

Kaklis-Pandelis Segment Control Parameters

Throws:

java.lang.Exception

BasisSplineSpanTest

public static final void BasisSplineSpanTest(double[] adblX,
                       double[] adblY,
                       SegmentControlParams segControlParams)
                                      throws java.lang.Exception

Perform the following sequence of tests for a given segment control for a predictor/response range
        - Interpolate
  - Compute the segment-by-segment monotonicity
  - Span Jacobian
  - Span knot insertion

Parameters:

adblX - The Predictor Array

adblY - The Response Array

segControlParams - The Segment Control Parameters

        WARNING: Insufficient Error Checking, so use caution

Throws:

java.lang.Exception

main

public static final void main(java.lang.String[] astrArgs)
                       throws java.lang.Exception

Throws:

java.lang.Exception

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include <aws/ram/model/RejectResourceShareInvitationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::RAM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

RejectResourceShareInvitationRequest::RejectResourceShareInvitationRequest() :
    m_resourceShareInvitationArnHasBeenSet(false),
    m_clientTokenHasBeenSet(false)
{
}

Aws::String RejectResourceShareInvitationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_resourceShareInvitationArnHasBeenSet)
  {
   payload.WithString("resourceShareInvitationArn", m_resourceShareInvitationArn);

  }

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("clientToken", m_clientToken);

  }

  return payload.View().WriteReadable();
}


text:
package net.greghaines.jesque.worker;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * WorkerPool creates a fixed number of identical Workers, each on a separate Thread.
 */
public class WorkerPool implements Worker {

    private final List<Worker> workers;
    private final List<Thread> threads;
    private final WorkerEventEmitter eventEmitter;

    /**
     * Create a WorkerPool with the given number of Workers and the default ThreadFactory.
     * @param workerFactory a Callable that returns an implementation of Worker
     * @param numWorkers the number of Workers to create
     */
    public WorkerPool(final Callable<? extends Worker> workerFactory, final int numWorkers) {
        this(workerFactory, numWorkers, Executors.defaultThreadFactory());
    }

    /**
     * Create a WorkerPool with the given number of Workers and the given ThreadFactory.
     * @param workerFactory a Callable that returns an implementation of Worker
     * @param numWorkers the number of Workers to create
     * @param threadFactory the factory to create pre-configured Threads
     */
    public WorkerPool(final Callable<? extends Worker> workerFactory, final int numWorkers,
            final ThreadFactory threadFactory) {
        this.workers = new ArrayList<>(numWorkers);
        this.threads = new ArrayList<>(numWorkers);
        this.eventEmitter = new WorkerPoolEventEmitter(this.workers);
        for (int i = 0; i < numWorkers; i++) {
            try {
                final Worker worker = workerFactory.call();
                this.workers.add(worker);
                this.threads.add(threadFactory.newThread(worker));
            } catch (RuntimeException re) {
                throw re;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Shutdown this pool and wait millis time per thread or until all threads are finished if millis is 0.
     * @param now if true, an effort will be made to stop any jobs in progress
     * @param millis the time to wait in milliseconds for the threads to join; a timeout of 0 means to wait forever.
     * @throws InterruptedException if any thread has interrupted the current thread.
     * The interrupted status of the current thread is cleared when this exception is thrown.
     */
    public void endAndJoin(final boolean now, final long millis) throws InterruptedException {
        end(now);
        join(millis);
    }

    /**
     * @return the number of total workers
     */
    public int getWorkerCount() {
        return this.workers.size();
    }

    /**
     * @return the number of workers processing jobs
     */
    public int getActiveWorkerCount() {
        int activeWorkers = 0;
        for (final Worker worker : this.workers) {
            if (worker.isProcessingJob()) {
                activeWorkers++;
            }
        }
        return activeWorkers;
    }

    /**
     * @return the number of workers not processing jobs
     */
    public int getIdleWorkerCount() {
        return getWorkerCount() - getActiveWorkerCount();
    }

    /**
     * Join to internal threads and wait millis time per thread or until all
     * threads are finished if millis is 0.
     *
     * @param millis the time to wait in milliseconds for the threads to join; a timeout of 0 means to wait forever.
     * @throws InterruptedException if any thread has interrupted the current thread.
     * The interrupted status of the current thread is cleared when this exception is thrown.
     */
    @Override
    public void join(final long millis) throws InterruptedException {
        for (final Thread thread : this.threads) {
            thread.join(millis);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        final StringBuilder sb = new StringBuilder(128 * this.threads.size());
        String prefix = "";
        for (final Worker worker : this.workers) {
            sb.append(prefix).append(worker.getName());
            prefix = " | ";
        }
        return sb.toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WorkerEventEmitter getWorkerEventEmitter() {
        return this.eventEmitter;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void run() {
        for (final Thread thread : this.threads) {
            thread.start();
        }
        Thread.yield();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void end(final boolean now) {
        for (final Worker worker : this.workers) {
            worker.end(now);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isShutdown() {
        return this.workers.get(0).isShutdown();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isPaused() {
        return this.workers.get(0).isPaused();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void togglePause(final boolean paused) {
        for (final Worker worker : this.workers) {
            worker.togglePause(paused);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isProcessingJob() {
        boolean processingJob = false;
        for (final Worker worker : this.workers) {
            processingJob |= worker.isProcessingJob();
            if (processingJob) {
                break;
            }
        }
        return processingJob;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public JobFactory getJobFactory() {
        return this.workers.get(0).getJobFactory();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<String> getQueues() {
        return this.workers.get(0).getQueues();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addQueue(final String queueName) {
        for (final Worker worker : this.workers) {
            worker.addQueue(queueName);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeQueue(final String queueName, final boolean all) {
        for (final Worker worker : this.workers) {
            worker.removeQueue(queueName, all);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeAllQueues() {
        for (final Worker worker : this.workers) {
            worker.removeAllQueues();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setQueues(final Collection<String> queues) {
        for (final Worker worker : this.workers) {
            worker.setQueues(queues);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ExceptionHandler getExceptionHandler() {
        return this.workers.get(0).getExceptionHandler();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setExceptionHandler(final ExceptionHandler exceptionHandler) {
        for (final Worker worker : this.workers) {
            worker.setExceptionHandler(exceptionHandler);
        }
    }

    private static class WorkerPoolEventEmitter implements WorkerEventEmitter {

        private final List<Worker> workers;

        /**
         * Constructor.
         * @param workers the workers to manage
         */
        public WorkerPoolEventEmitter(final List<Worker> workers) {
            this.workers = workers;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void addListener(final WorkerListener listener) {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().addListener(listener);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void addListener(final WorkerListener listener, final WorkerEvent... events) {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().addListener(listener, events);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void removeListener(final WorkerListener listener) {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().removeListener(listener);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void removeListener(final WorkerListener listener, final WorkerEvent... events) {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().removeListener(listener, events);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void removeAllListeners() {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().removeAllListeners();
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void removeAllListeners(final WorkerEvent... events) {
            for (final Worker worker : this.workers) {
                worker.getWorkerEventEmitter().removeAllListeners(events);
            }
        }
    }
}


text:
package org.apache.dubbo.rpc.protocol.grpc;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceRepository;
import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol;

import io.grpc.BindableService;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 *
 */
public class GrpcProtocol extends AbstractProxyProtocol {

    public static final int DEFAULT_PORT = 50051;

    /* <address, gRPC channels> */
    private final ConcurrentMap<String, ReferenceCountManagedChannel> channelMap = new ConcurrentHashMap<>();
    private final Object lock = new Object();

    @Override
    protected <T> Runnable doExport(T proxiedImpl, Class<T> type, URL url) throws RpcException {
        String key = url.getAddress();
        ProtocolServer protocolServer = serverMap.computeIfAbsent(key, k -> {
            DubboHandlerRegistry registry = new DubboHandlerRegistry();

            NettyServerBuilder builder =
                    NettyServerBuilder
                    .forPort(url.getPort())
                            .fallbackHandlerRegistry(registry);

            Server originalServer = GrpcOptionsUtils.buildServerBuilder(url, builder).build();
            GrpcRemotingServer remotingServer = new GrpcRemotingServer(originalServer, registry);
            return new ProxyProtocolServer(remotingServer);
        });

        GrpcRemotingServer grpcServer = (GrpcRemotingServer) protocolServer.getRemotingServer();

        ServiceRepository serviceRepository = ApplicationModel.getServiceRepository();
        ProviderModel providerModel = serviceRepository.lookupExportedService(url.getServiceKey());
        if (providerModel == null) {
            throw new IllegalStateException("Service " + url.getServiceKey() + "should have already been stored in service repository, " +
                    "but failed to find it.");
        }
        Object originalImpl = providerModel.getServiceInstance();

        Class<?> implClass = originalImpl.getClass();
        try {
            Method method = implClass.getMethod("setProxiedImpl", type);
            method.invoke(originalImpl, proxiedImpl);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to set dubbo proxied service impl to stub, please make sure your stub " +
                    "was generated by the dubbo-protoc-compiler.", e);
        }
        grpcServer.getRegistry().addService((BindableService) originalImpl, url.getServiceKey());

        if (!grpcServer.isStarted()) {
            grpcServer.start();
        }

        return () -> grpcServer.getRegistry().removeService(url.getServiceKey());
    }

    @Override
    protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
        Class<?> enclosingClass = type.getEnclosingClass();

        if (enclosingClass == null) {
            throw new IllegalArgumentException(type.getName() + " must be declared inside protobuf generated classes, " +
                    "should be something like ServiceNameGrpc.IServiceName.");
        }

        final Method dubboStubMethod;
        try {
            dubboStubMethod = enclosingClass.getDeclaredMethod("getDubboStub", Channel.class, CallOptions.class,
                    URL.class, ReferenceConfigBase.class);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Does not find getDubboStub in " + enclosingClass.getName() + ", please use the customized protoc-gen-dubbo-java to update the generated classes.");
        }

        // Channel
        ReferenceCountManagedChannel channel = getSharedChannel(url);

        // CallOptions
        try {
            @SuppressWarnings("unchecked") final T stub = (T) dubboStubMethod.invoke(null,
                    channel,
                    GrpcOptionsUtils.buildCallOptions(url),
                    url,
                    ApplicationModel.getConsumerModel(url.getServiceKey()).getReferenceConfig()
            );
            final Invoker<T> target = proxyFactory.getInvoker(stub, type, url);
            GrpcInvoker<T> grpcInvoker = new GrpcInvoker<>(type, url, target, channel);
            invokers.add(grpcInvoker);
            return grpcInvoker;
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new IllegalStateException("Could not create stub through reflection.", e);
        }
    }

    /**
     * not used
     *
     * @param type
     * @param url
     * @param <T>
     * @return
     * @throws RpcException
     */
    @Override
    protected <T> T doRefer(Class<T> type, URL url) throws RpcException {
        throw new UnsupportedOperationException("not used");
    }

    /**
     * Get shared channel connection
     */
    private ReferenceCountManagedChannel getSharedChannel(URL url) {
        String key = url.getAddress();
        ReferenceCountManagedChannel channel = channelMap.get(key);

        if (channel != null && !channel.isTerminated()) {
            channel.incrementAndGetCount();
            return channel;
        }

        synchronized (lock) {
            channel = channelMap.get(key);
            // dubbo check
            if (channel != null && !channel.isTerminated()) {
                channel.incrementAndGetCount();
            } else {
                channel = new ReferenceCountManagedChannel(initChannel(url));
                channelMap.put(key, channel);
            }
        }

        return channel;
    }

    /**
     * Create new connection
     *
     * @param url
     */
    private ManagedChannel initChannel(URL url) {
        return GrpcOptionsUtils.buildManagedChannel(url);
    }

    @Override
    public int getDefaultPort() {
        return DEFAULT_PORT;
    }

    @Override
    public void destroy() {
        serverMap.values().forEach(ProtocolServer::close);
        channelMap.values().forEach(ReferenceCountManagedChannel::shutdown);
        serverMap.clear();
        channelMap.clear();
        super.destroy();
    }

    public class GrpcRemotingServer extends RemotingServerAdapter {

        private Server originalServer;
        private DubboHandlerRegistry handlerRegistry;
        private volatile boolean started;

        public GrpcRemotingServer(Server server, DubboHandlerRegistry handlerRegistry) {
            this.originalServer = server;
            this.handlerRegistry = handlerRegistry;
        }

        public void start() throws RpcException {
            try {
                originalServer.start();
                started = true;
            } catch (IOException e) {
                throw new RpcException("Starting gRPC server failed. ", e);
            }
        }

        public DubboHandlerRegistry getRegistry() {
            return handlerRegistry;
        }

        @Override
        public Object getDelegateServer() {
            return originalServer;
        }

        public boolean isStarted() {
            return started;
        }

        @Override
        public void close() {
            originalServer.shutdown();
        }
    }

}


text:
@interface ProductDetailViewController : UIViewController
- (IBAction)saveProduct:(id)sender;
@property (nonatomic, strong) Product* selectedProduct;
@end


text:
<?php ini_set('display_errors','off');
/**
 * @version   2.2a, dernière révision le 17 mars 2008
 * @author    Olivier VEUJOZ
 *
 * Modifications version 2.2a
 *   - Correction du paramètrage par défaut de la propriété $Permission (string => integer)
 *
 * Modifications version 2.2 :
 *   - Ajout des derniers messages d'erreurs retournés par PHP (UPLOAD_ERR_EXTENSION, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_NO_TMP_DIR)
 *   - Ajout de la propriété 'octets' dans le tableau des informations sur un fichier (taille du fichier en octets)
 *   - Ajout du test sur la présence du tableau $_FILES
 *   - Modifications mineures sur la logique de la classe (fonction checkUpload() et sur la fonction de nettoyage du nom de fichier, qui supprime tout caractère de fichier Windows invalide.
 *
 * SECURITY CONSIDERATION: If you are saving all uploaded files to a directory accesible with an URL, remember to filter files not only by mime-type (e.g. image/gif), but also by extension. The mime-type is reported by the client, if you trust him, he can upload a php file as an image and then request it, executing malicious code.
 * I hope I am not giving hackers a good idea anymore than I am giving it to good-intended developers. Cheers.
 * Some restrictive firewalls may not let file uploads happen via a form with enctype="multipart/form-data".
 * We were having problems with an upload script hanging (not returning content) when a file was uploaded through a remote office firewall. Removing the enctype parameter of the form allowed the form submit to happen but then broke the file upload capability. Everything but the file came through. Using a dial-in or other Internet connection (bypassing the bad firewall) allowed everything to function correctly.
 * So if your upload script does not respond when uploading a file, it may be a firewall issue.
 *
 * Compatibilité :
 *  - compatible safe_mode
 *  - compatible open_basedir pour peu que les droits sur le répertoire temporaire d'upload soient alloués
 *  - Version minimum de php : 5.x
 *
 * Par défaut :
 *  - autorise tout type de fichier
 *  - autorise les fichier allant jusqu'à la taille maximale spécifiée dans le php.ini
 *  - envoie le(s) fichier(s) dans le répertoire de la classe
 *  - n'affiche qu'un champ de type file
 *  - permet de laisser les champs de fichiers vides
 *  - écrase le fichier s'il existe déjà
 *  - n'exécute aucune vérification
 *  - utilise les entêtes renvoyés par le navigateur pour vérifier le type mime.
 *
 * Notes :
 *  - le chemin de destination peut être défini en absolu ou en relatif
 *  - set_time_limit n'a pas d'effet lorsque PHP fonctionne en mode safe mode . Il n'y a pas d'autre solution que de changer de mode, ou de modifier la durée maximale d'exécution dans le php.ini
 *  - Intégration depuis la version 2.0b des fonctions Mimetype de php (http://fr3.php.net/manual/fr/ref.mime-magic.php).
 *
 * Notes sur l'intégration des fonctions MimeType de PHP:
 *      - PHP doit être compilé avec l'option --enable-mime-magic. Sous Windows, il suffit de s'assurer de l'existence de la dll php_mime_magic.dll et de l'activer dans le php.ini
 *      - Déclarer ensuite une nouvelle section dans votre php.ini et renseignez là comme suit :
 *          [MIME_MAGIC]
 *          ;PHP_INI_SYSTEM Disponible depuis PHP 5.0.0.
 *          mime_magic.debug = 0
 *          ;PHP_INI_SYSTEM Disponible depuis PHP 4.3.0.
 *          mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime" où $PHP_INSTALL_DIR fait référence à  votre chemin jusqu'à l'exécutable PHP
 *      - Le fichier magic.mime n'est pas fourni avec PHP. Il est téléchargeable http://gnuwin32.sourceforge.net/packages/file.htm (dans l'arborescence \share\file\)
 *        Il est recommandé de le copier à la racine de l'exécutable PHP. (étape nécessaire sous windows, pas sûr pour les autres OS)
 *
 * Notes sur l'installation de la librairie PECL plateforme windows
 *      - Télécharger la collection de modules PECL depuis la page de téléchargement général de PHP en adéquation avec la version de PHP utilisée ("Collection of PECL modules", http://www.php.net/downloads.php)
 *      - Installez la dll "php_fileinfo.dll" dans le répertoire classique d'installation de php
 *      - Ajoutez la ligne suivante dans votre php.ini
 *          [extension=php_fileinfo.dll]
 *      - Assurez-vous que la dll dispose des permissions suffisantes pour être exécutée par le serveur web.
 *      - Pour éviter des erreurs à la limite du compréhensible sous windows, le fichier "magic" est livré avec la classe upload. Il est issu de l'installation d'Apache 2.0.59.
 */

// Déprécié, gardé pour compatibilité descendante. Utiliser le booléen renvoyé par la méthode Execute() en lieu et place.
global $UploadError;

class Upload {

    // constantes méthode de vérification des entêtes
    const CST_UPL_HEADER_BROWSER  = 0; // Navigateur
    const CST_UPL_HEADER_MIMETYPE = 1; // librairie mime_type
    const CST_UPL_HEADER_FILEINFO = 2; // librairie fileinfo (PECL)

    // constantes méthode d'écriture des fichiers
    const CST_UPL_WRITE_ERASE  = 0;
    const CST_UPL_WRITE_COPY   = 1;
    const CST_UPL_WRITE_IGNORE = 2;

    // constantes types d'erreurs 1 : appairage avec les erreurs retournées par PHP
    const CST_UPL_ERR_NONE                  = UPLOAD_ERR_OK;            // Aucune erreur, le téléchargement est valide
    const CST_UPL_ERR_EXCEED_INI_FILESIZE   = UPLOAD_ERR_INI_SIZE;      // la taille du fichier excède la directive max_file_size (php.ini)
    const CST_UPL_ERR_EXCEED_FORM_FILESIZE  = UPLOAD_ERR_FORM_SIZE;     // la taille du fichier excède la directive max_file_size (formulaire)
    const CST_UPL_ERR_CORRUPT_FILE          = UPLOAD_ERR_PARTIAL;       // le fichier n'a pas été chargé complètement
    const CST_UPL_ERR_EMPTY_FILE            = UPLOAD_ERR_NO_FILE;       // champ du formulaire vide
    const CST_UPL_ERR_NO_TMP_DIR            = UPLOAD_ERR_NO_TMP_DIR;    // Un dossier temporaire est manquant. Introduit en PHP 4.3.10 et PHP 5.0.3.
    const CST_UPL_ERR_CANT_WRITE            = UPLOAD_ERR_CANT_WRITE;    // Échec de l'écriture du fichier sur le disque. Introduit en PHP 5.1.0.
    const CST_UPL_ERR_EXTENSION             = UPLOAD_ERR_EXTENSION;     // L'envoi de fichier est arrêté par l'extension. Introduit en PHP 5.2.0.

    // constantes types d'erreurs 2 : erreurs supplémentaires détectées par la classe
    const CST_UPL_ERR_UNSAFE_FILE           = 20; // fichier potentiellement dangereux
    const CST_UPL_ERR_WRONG_MIMETYPE        = 21; // le fichier n'est pas conforme à la liste des entêtes autorisés
    const CST_UPL_ERR_WRONG_EXTENSION       = 22; // le fichier n'est pas conforme à la liste des extensions autorisées
    const CST_UPL_ERR_IMG_EXCEED_MAX_WIDTH  = 23; // largeur max de l'image excède celle autorisée
    const CST_UPL_ERR_IMG_EXCEED_MAX_HEIGHT = 24; // hauteur max de l'image excède celle autorisée
    const CST_UPL_ERR_IMG_EXCEED_MIN_WIDTH  = 25; // largeur min de l'image excède celle autorisée
    const CST_UPL_ERR_IMG_EXCEED_MIN_HEIGHT = 26; // hauteur min de l'image excède celle autorisée

    const CST_UPL_EXT_FILEINFO  = 'fileinfo';
    const CST_UPL_EXT_MIMEMAGIC = 'mime_magic';
    const CST_UPL_PHP_VERSION   = '5.0.4';

    /**
     * Etant donné qu'entre les différents navigateurs les informations sur les entêtes de fichiers peuvent différer,
     * il est dorénavant possible de laisser PHP s'occuper du type MIME. L'ajout de cette fonctionnalité nécessite
     * l'activation de la librairie mime_magic ou fileinfo.
     *
     * Positionné à self::CST_UPL_HEADER_BROWSER, la vérification des entêtes de fichiers se fera comme auparavant, cad via les informations retournées par le navigateur.
     * Positionné à self::CST_UPL_HEADER_MIMETYPE, la vérification est basé sur les fonctions Mimetype de php (extension mime_magic)
     * Positionné à self::CST_UPL_HEADER_FILEINFO, la vérification est basé sur la classe fileinfo() (librairie PECL)
     *
     * @var integer
     */
    public $phpDetectMimeType = self::CST_UPL_HEADER_BROWSER;

    /**
     * Initialisée dynamiquement dans la fonction loadPECLInfoLib() suivant le paramétrage
     * de la propriété $phpDetectMimeType.
     *
     * @var string $path . $filename
     */
    public $magicfile = '';

    /**
     * Par défaut la classe génère des champs de formulaire à la norme x-html.
     *
     * @var boolean
     */
    public $xhtml = true;

    /**
     * Taille maximale exprimée en kilo-octets pour l'upload d'un fichier.
     * Valeur par défaut : celle configurée dans le php.ini (cf. constructeur).
     *
     * @var integer
     */
    public $MaxFilesize = null;

    /**
     * Largeur maximum d'une image exprimée en pixel.
     *
     * @var int
     */
    public $ImgMaxWidth = null;

    /**
     * Hauteur maximum d'une image exprimée en pixel.
     *
     * @var int
     */
    public $ImgMaxHeight = null;

    /**
     * Largeur minimum d'une image exprimée en pixel.
     *
     * @var int
     */
    public $ImgMinWidth = null;

    /**
     * Hauteur minimum d'une image exprimée en pixel.
     *
     * @var int
     */
    public $ImgMinHeight = null;

    /**
     * Répertoire de destination dans lequel vont être chargés les fichiers.
     * Accepte les chemins relatifs et absolus.
     *
     * @var string
     */
    public $DirUpload = '';

    /**
     * Nombre de champs de type file que la classe devra gérer.
     *
     * @var integer
     */
    public $Fields = 1;

    /**
     * Paramètres à ajouter aux champ de type file (ex: balise style, évenements JS...)
     *
     * @var string
     */
    public $FieldOptions = '';

    /**
     * Définit si les champs sont obligatoires ou non.
     *
     * @var boolean
     */
    public $Required = false;

    /**
     * Politique de sécurité max : ignore tous les fichiers exécutables / interprétable.
     * Déprécié. Gardé pour compatibilité descendante.
     *
     * @var boolean
     */
    public $SecurityMax = false;

    /**
     * Permet de préciser un nom pour le fichier à uploader.
     * Peut être utilisé conjointement avec les propriétés $Suffixe / $Prefixe
     *
     * @var string
     */
    public $Filename = '';

    /**
     * Préfixe pour le nom du fichier sur le serveur.
     *
     * @var string
     */
    public $Prefixe = '';

    /**
     * Suffixe pour le nom du fichier sur le serveur.
     *
     * @var string
     */
    public $Suffixe = '';

    /**
     * Méthode à employer pour l'écriture des fichiers si un fichier de même nom est présent dans le répertoire :
     * self::CST_UPL_WRITE_ERASE  : le fichier du serveur est écrasé par le nouveau fichier.
     * self::CST_UPL_WRITE_COPY   : le nouveau fichier est uploadé mais précédé de la mention 'copie_de_'.
     * self::CST_UPL_WRITE_IGNORE : le nouveau fichier est ignoré.
     *
     * @var integer
     */
    public $WriteMode = self::CST_UPL_WRITE_ERASE;

    /**
     * Chaine de caractères représentant les entêtes de fichiers autorisés (mime-type).
     * Les entêtes doivent être séparées par des points virgules.
     * $Upload->MimeType = 'image/gif;image/pjpeg';
     *
     * @var string
     */
    public $MimeType = '';

    /**
     * Positionné à [true], une erreur de configuration du composant sera envoyé en sortie écran et bloquera le script
     * en cours d'exécution.
     *
     * @var boolean
     */
    public $TrackError = true;

    /**
     * Réaffection des droits utilisateur après écriture du document sur le serveur.
     *
     * @var string
     */
    public $Permission = 0666;

    /**
     * Liste des extensions autorisées séparées par un point virgule.
     * $Upload->Extension = ".dat;.csv;.txt";
     *
     * @var string
     */
    public $Extension = '';

    /**
     * En remplacement de la variable globale $UploadError.
     *
     * @var boolean.
     */
    private $uplSuccess = true;

    /**
     * Tableau des erreurs rencontrés durant l'upload.
     *
     * @var array
     */
    private $ArrOfError = array();

    /**
     * Propriétés temporaires utilisées lors du parcours de la variable globale $_FILES
     */
    private $_field = 0;                // position du champ dans le formulaire à partir de 1 (0 étant réservé au champ max_file_size)
    private $_size  = 0;                // poids du fichier
    private $_type  = '';               // type mime renvoyé par le navigateur
    private $_name  = '';               // nom du fichier
    private $_temp  = '';               // emplacement temporaire
    private $_ext   = '';               // extension du fichier
    private $_error = UPLOAD_ERR_OK;    // Erreur upload retournée par PHP

    /**
     * Tableaux des messages d'erreurs sur l'échec d'une upload.
     *
     * @see setError()
     * @var array
     */
    private $errorMsg = array(
        self::CST_UPL_ERR_EXCEED_INI_FILESIZE   => 'Le document [%FILENAME%] excède la directive [upload_max_filesize] du fichier de configuration [php.ini].',
        self::CST_UPL_ERR_EXCEED_FORM_FILESIZE  => 'Le document [%FILENAME%] excède la directive MAX_FILE_SIZE spécifiée dans le formulaire.',
        self::CST_UPL_ERR_CORRUPT_FILE          => 'Document [%FILENAME%] corrompu.',
        self::CST_UPL_ERR_EMPTY_FILE            => "Le champ [parcourir] du formulaire d'upload n'a pas été renseigné.",
        self::CST_UPL_ERR_NO_TMP_DIR            => 'Un dossier temporaire est manquant.',
        self::CST_UPL_ERR_CANT_WRITE            => "Échec de l'écriture du fichier [%FILENAME%] sur le disque.",
        self::CST_UPL_ERR_EXTENSION             => "L'envoi du fichier [%FILENAME%] est arrêté par l'extension.",
        self::CST_UPL_ERR_UNSAFE_FILE           => 'Document [%FILENAME%] potentiellement dangereux.',
        self::CST_UPL_ERR_WRONG_MIMETYPE        => "Le document [%FILENAME%] n'est pas conforme à la liste des entêtes autorisés.",
        self::CST_UPL_ERR_WRONG_EXTENSION       => "Le document [%FILENAME%] n'est pas conforme à la liste des extensions autorisées.",
        self::CST_UPL_ERR_IMG_EXCEED_MAX_WIDTH  => "La largeur de l'image [%FILENAME%] excède celle autorisée.",
        self::CST_UPL_ERR_IMG_EXCEED_MAX_HEIGHT => "La hauteur de l'image [%FILENAME%] excède celle autorisée.",
        self::CST_UPL_ERR_IMG_EXCEED_MIN_WIDTH  => "La largeur de l'image [%FILENAME%] est inférieure à celle autorisée.",
        self::CST_UPL_ERR_IMG_EXCEED_MIN_HEIGHT => "La hauteur de l'image [%FILENAME%] est inférieure à celle autorisée."
    );

    /**
     * Constructeur.
     */
    public function __construct() {
        $this->MaxFilesize = @preg_replace('M', '', @ini_get('upload_max_filesize')) * 1024;
    }

    /**
     * Lance l'initialisation de la classe pour la génération du formulaire
     *
     * @access public
     */
    public function InitForm() {
        $this->SetMaxFilesize();
        $this->CreateFields();
    }

    /**
     * Retourne le tableau des erreurs survenues durant l'upload
     *
     *
     * if (!$Upload->Execute()) {
     *     print_r($Upload-> GetError);
     * }
     *
     *
     * @access public
     * @param integer $num_field numéro du champ 'file' sur lequel on souhaite récupérer l'erreur
     * @return array
     */
    public function GetError($num_field='') {
        return (Empty($num_field)) ? $this->ArrOfError : $this->ArrOfError[$num_field];
    }

    /**
     * Retourne le tableau contenant les informations sur les fichiers uploadés
     *
     *
     * if (!$Upload->Execute()) {
     *     print_r($Upload->GetSummary());
     * }
     *
     *
     * @access public
     * @param integer $num_field    numéro du champ 'file' sur lequel on souhaite récupérer les informations
     * @return array                tableau des infos fichiers
     */
    public function GetSummary($num_field = null) {

        if (!isSet($num_field)) {
            $result = (isSet($this->Infos)) ? $this->Infos : false;
        }
        else {
            $result = (isSet($this->Infos[$num_field])) ? $this->Infos[$num_field] : false;
        }

        return $result;
    }

    /**
     * Lance les différents traitements nécessaires à l'upload
     *
     * @return boolean
     */
    public function Execute(){
        @set_time_limit(0);

        $this->CheckConfig();
        $this->CheckUpload();

        return $this->uplSuccess;
    }

    /**
     * Permet de modifier le message d'erreur en cas d'échec d'une upload.
     * Le libellé peut contenir le mot clé %FILENAME%.
     *
     * @var int    $code_erreur
     * @var string $libelle
     * @see AddError()
     * @return boolean
     */
    public function setErrorMsg($code_erreur, $libelle) {

        if (!isSet($this->errorMsg[$code_erreur])) {
            $this->Error('le paramètre $code_erreur passé à la méthode [setErrorMsg] est erroné.');
            return false;
        }

        $this->errorMsg[$code_erreur] = $libelle;

        return true;
    }

    /**
     * Méthode de définition des propriétés sur les dimensions des images.
     * La vérification sur le bon format est géré dans la méthode CheckImgPossibility().
     *
     * @param integer $maxWidth
     * @param integer $minWidth
     * @param integer $maxHeight
     * @param integer $minHeight
     */
    public function SetImgDim($maxWidth = null, $minWidth = null, $maxHeight = null, $minHeight = null) {
        $this->ImgMaxHeight = $maxHeight;
        $this->ImgMaxWidth  = $maxWidth;
        $this->ImgMinHeight = $minHeight;
        $this->ImgMinWidth  = $minWidth;
    }

    /**
     * Méthode lançant les vérifications sur les fichiers.
     * Initialisation de la propriété $uplSuccess à false si erreur, lance la
     * méthode d'écriture toutes les vérifications sont ok.
     * @access private
     */
    private function CheckUpload() {

        if (!isSet($_FILES['userfile']['tmp_name'])) {
            $this->Error('Le tableau contenant les informations des fichiers téléchargés est vide.' . PHP_EOL .
                         'Si vous avez renseigné un champ de fichier, il est probable que la taille de ce dernier excède les capacités de chargement du serveur.');
        }

        $nbFiles = count($_FILES['userfile']['tmp_name']);

        // Parcours des fichiers à uploader
        for ($i=0; $i < $nbFiles; $i++)  {

            // Récup des particularité du fichier dans les propriétés temporaires
            $this->_field++;
            $this->_size  = $_FILES['userfile']['size'][$i];
            $this->_type  = $_FILES['userfile']['type'][$i];
            $this->_name  = $_FILES['userfile']['name'][$i];
            $this->_temp  = $_FILES['userfile']['tmp_name'][$i];
            $this->_ext   = strtolower(substr($this->_name, strrpos($this->_name, '.')));
            $this->_error = $_FILES['userfile']['error'][$i];

            // On exécute les vérifications demandées
            if ($this->_error == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'][$i])) {

                // Vérification du type mime via la librairie "mime_magic" : on surcharge la propriété _type avec le type renvoyé par la fonction mime_content_type
                if ($this->phpDetectMimeType === self::CST_UPL_HEADER_MIMETYPE) {
                    $this->_type = mime_content_type($_FILES['userfile']['tmp_name'][$i]);
                }

                // Vérification du type mime via la librairie "file_info" : on surcharge la propriété _type avec le type renvoyé par la fonction fileinfo()
                else if ($this->phpDetectMimeType === self::CST_UPL_HEADER_FILEINFO) {

                    $fInfo = new finfo(FILEINFO_MIME, $this->magicfile);

                    // La classe retourne une chaine de type "mime; charset". Seul la partie mime nous intéresse.
                    $mime = explode(';', $fInfo->file($_FILES['userfile']['tmp_name'][$i]));

                    $this->_type = trim($mime[0]);

                    unset($fInfo, $mime);
                }

                // Vérification des erreurs suplémentaires détectées par la classe
                if (!$this->CheckSecurity() || !$this->CheckMimeType() || !$this->CheckExtension() || !$this->CheckImg()) {
                    continue;
                }
            }
            else {
                // Erreur retournée par PHP
                $this->AddError($this->_error);
                continue;
            }

            // Le fichier a passé toutes les vérifications, on procède à l'écriture
            $this->WriteFile($this->_name, $this->_type, $this->_temp, $this->_ext, $this->_field);
        }
    }

    /**
     * Ecrit le fichier sur le serveur.
     *
     * @access private
     * @param string $name        nom du fichier sans son extension
     * @param string $type        entete du fichier
     * @param string $temp        chemin du fichier temporaire
     * @param string $temp        extension du fichier précédée d'un point
     * @param string $num_fied    position du champ dans le formulaire à compter de 1
     * @return bool               true/false => succes/erreur
     */
    private function WriteFile($name, $type, $temp, $ext, $num_field) {

        $new_filename = null;

        if (is_uploaded_file($temp)) {

            // Nettoyage du nom original du fichier
            $new_filename = (Empty($this->Filename)) ? $this->CleanFileName(substr($name, 0, strrpos($name, '.'))) : $this->Filename;

            // Ajout préfixes / suffixes + extension :
            $new_filename = $this->Prefixe . $new_filename . $this->Suffixe . $ext;

            switch ($this->WriteMode) {

                case self::CST_UPL_WRITE_ERASE :
                    $uploaded = @move_uploaded_file($temp, $this->DirUpload . $new_filename);
                break;

                case self::CST_UPL_WRITE_COPY :

                    if ($this->AlreadyExist($new_filename)) {
                        $new_filename = 'copie_de_' . $new_filename;
                    }

                    $uploaded = @move_uploaded_file($temp, $this->DirUpload . $new_filename);

                 break;

                case self::CST_UPL_WRITE_IGNORE :

                    if ($this->AlreadyExist($new_filename)) $uploaded = true;
                    else                                    $uploaded = @move_uploaded_file($temp, $this->DirUpload . $new_filename);

                break;
            }

            // Informations pouvant être utiles au développeur (si le fichier a pu être copié)
            if ($uploaded) {

                $filesize = filesize($this->DirUpload . $new_filename);

                $this->Infos[$num_field]['nom']          = $new_filename;
                $this->Infos[$num_field]['nom_originel'] = $name;
                $this->Infos[$num_field]['chemin']       = $this->DirUpload . $new_filename;
                $this->Infos[$num_field]['poids']        = number_format($filesize/1024, 3, '.', '');
                $this->Infos[$num_field]['octets']       = $filesize;
                $this->Infos[$num_field]['mime-type']    = $type;
                $this->Infos[$num_field]['extension']    = $ext;
            }
            else {
                $this->Error('move_uploaded_file() a généré une erreur. Vérifiez les droits d\'écriture du répertoire temporaire d\'upload [' . @ini_get('upload_tmp_dir') . '] et celui du répertoire de destination [' . $this->DirUpload . '].');
                return false;
            }

            // Mise en place des droits
            if (function_exists('chmod')) {
                @chmod($this->DirUpload . $new_filename, $this->Permission);
            }

            return true;

        } // End is_uploaded_file

        return false;
    }

    /**
     * Vérifie si le fichier passé en paramètre existe déjà dans le répertoire DirUpload
     *
     * @access private
     * @return bool
     */
    private function AlreadyExist($file) {
        return (file_exists($this->DirUpload . $file));
    }

    /**
     * Vérifie la hauteur/largeur d'une image
     *
     * @access private
     * @return bool
     */
    private function CheckImg() {

        $dim = @getimagesize($this->_temp);
        $res = true;

        // On travaille sur un fichier image
        if ($dim != false) {

            if (!Empty($this->ImgMaxWidth) && $dim[0] > $this->ImgMaxWidth)  {
                $this->AddError(self::CST_UPL_ERR_IMG_EXCEED_MAX_WIDTH);
                $res = false;
            }

            if (!Empty($this->ImgMaxHeight) && $dim[1] > $this->ImgMaxHeight) {
                $this->AddError(self::CST_UPL_ERR_IMG_EXCEED_MAX_HEIGHT);
                $res = false;
            }

            if (!Empty($this->ImgMinWidth)  && $dim[0] < $this->ImgMinWidth) {
                $this->AddError(self::CST_UPL_ERR_IMG_EXCEED_MIN_WIDTH);
                $res = false;
            }

            if (!Empty($this->ImgMinHeight) && $dim[1] < $this->ImgMinHeight) {
                $this->AddError(self::CST_UPL_ERR_IMG_EXCEED_MIN_HEIGHT);
                $res = false;
            }
        }

        return $res;
    }

    /**
     * Vérifie l'extension des fichiers suivant celles précisées dans $Extension
     * @access private
     * @return bool
     */
    private function CheckExtension() {

        $ArrOfExtension = explode(';', strtolower($this->Extension));

        if (!Empty($this->Extension) && !in_array($this->_ext, $ArrOfExtension)) {
            $this->AddError(self::CST_UPL_ERR_WRONG_EXTENSION);
            return false;
        }

        return true;
    }

    /**
     * Vérifie l'entête des fichiers suivant ceux précisés dans $MimeType
     * @access private
     * @return bool
     */
    private function CheckMimeType() {

        $ArrOfMimeType = explode(';', $this->MimeType);

        if (!Empty($this->MimeType) && !in_array($this->_type, $ArrOfMimeType)) {
            $this->AddError(self::CST_UPL_ERR_WRONG_MIMETYPE);
            return false;
        }

        return true;
    }

    /**
     * Ajoute une erreur pour le fichier en cours de lecture dans le tableau des erreur.
     * Voir http://www.php.net/manual/fr/features.file-upload.errors.php
     *
     * @access private
     */
    private function AddError($code_erreur) {

        // Déprécié. Gardé pour compatibilité.
        global $UploadError;

        $positionnerEnErreur = true;

        switch ($code_erreur) {

            case self::CST_UPL_ERR_NONE :
               $positionnerEnErreur = false;
            break;

            case '' :
                $msg = 'Exception levée mais non décelée pour le document %FILENAME%.';
            break;

            case self::CST_UPL_ERR_EMPTY_FILE :
                $msg = $this->errorMsg[$code_erreur];
                $positionnerEnErreur = $this->Required;
            break;

            default :
                $msg = $this->errorMsg[$code_erreur];
                $positionnerEnErreur = true;
            break;

        }

        if ($positionnerEnErreur) {

            $msg              = str_replace('%FILENAME%', utf8_decode($this->_name), $msg);
            $UploadError      = true;
            $this->uplSuccess = false;

            $this->ArrOfError[$this->_field][$code_erreur] = $msg;
        }
    }

    /**
     * Vérifie les critères de la politique de sécurité
     * OV : 26/10/07 => déprécié.
     *
     * @access private
     * @return bool
     */
    private function CheckSecurity() {

        // Bloque tous les fichiers executables, et tous les fichiers php pouvant être interprété mais dont l'entête ne peut les identifier comme étant dangereux
        if ($this->SecurityMax === true && ereg ('application/octet-stream', $this->_type) || preg_match("/.php$|.inc$|.php3$/i", $this->_ext)) {
            $this->AddError(self::CST_UPL_ERR_UNSAFE_FILE);
            return false;
        }

        return true;
    }

    /**
     * Vérifie et formate le chemin de destination :
     *     - définit comme rep par défaut celui de la classe
     *     - teste l'existance du répertoire et son accès en écriture
     * @access private
     */
    private function CheckDirUpload() {

        // Si aucun répertoire n'a été précisé, on prend celui de la classe
        if (Empty($this->DirUpload)) $this->DirUpload = dirname(__FILE__);

        $this->DirUpload = $this->FormatDir($this->DirUpload);

        // Le répertoire existe?
        if (!is_dir($this->DirUpload)) $this->Error('Le répertoire de destination spécifiée par la propriété DirUpload n\'existe pas.');

        // Anciennement, le test sur le droit en écriture était géré via la fonction is_writeable() ici.
        // Malheureusement, pour des raisons inconnus, ce test pouvait généré une erreur alors que le répertoire de destination était correctement configuré (Windows Server 2003).
        // Le test est finalement délocalisé lors de l'écriture du fichier via la fonction move_uploaded_file().
    }

    /**
     * Formate le répertoire passé en paramètre
     * - convertit un chemin relatif en chemin absolu
     * - ajoute si besoin le dernier slash (ou antislash suivant le système)
     *
     * @access private
     */
    private function FormatDir($Dir) {

        // Convertit les chemins relatifs en chemins absolus
        if (function_exists('realpath')) {
            if (realpath($Dir)) $Dir = realpath($Dir);
        }

        // Position du dernier slash/antislash
        if ($Dir[strlen($Dir)-1] != DIRECTORY_SEPARATOR) $Dir .= DIRECTORY_SEPARATOR;

        return $Dir;
    }

    /**
     * Formate la chaine passée en paramètre en nom de fichier standard (pas de caractères spéciaux ni d'espaces)
     * @access private
     * @param  string $str   chaine à formater
     * @return string        chaine formatée
     */
    private function CleanFileName($str) {

        $return = '';

        for ($i=0; $i <= strlen($str)-1; $i++) {
            if (eregi('[a-z]',$str{$i}))              $return .= $str{$i};
            elseif (eregi('[0-9]', $str{$i}))         $return .= $str{$i};
            elseif (ereg('[àâäãáåÀÁÂÃÄÅ]', $str{$i})) $return .= 'a';
            elseif (ereg('[æÆ]', $str{$i}))           $return .= 'a';
            elseif (ereg('[çÇ]', $str{$i}))           $return .= 'c';
            elseif (ereg('[éèêëÉÈÊËE]', $str{$i}))    $return .= 'e';
            elseif (ereg('[îïìíÌÍÎÏ]', $str{$i}))     $return .= 'i';
            elseif (ereg('[ôöðòóÒÓÔÕÖ]', $str{$i}))   $return .= 'o';
            elseif (ereg('[ùúûüÙÚÛÜ]', $str{$i}))     $return .= 'u';
            elseif (ereg('[ýÿݟ]', $str{$i}))         $return .= 'y';
            elseif (ereg('[ ]', $str{$i}))            $return .= '_';
            elseif (ereg('[.]', $str{$i}))            $return .= '_';
            else                                      $return .= $str{$i};
        }

        return utf8_encode(str_replace(array('\\', '/', ':', '*', '?', '"', '<', '>', '|'), '', $return));
    }

    /**
     * Conversion du poids maximum d'un fichier exprimée en Ko en octets
     * @access private
     */
    private function SetMaxFilesize() {
        (is_numeric($this->MaxFilesize)) ? $this->MaxFilesize = $this->MaxFilesize * 1024 : $this->Error('la propriété MaxFilesize doit être une valeur numérique');
    }

    /**
     * Crée les champs de type fichier suivant la propriété Fields dans un tableau $Field. Ajoute le contenu de FieldOptions aux champs.
     * @access private
     */
    private function CreateFields() {

        if (!is_int($this->Fields)) {
            $this->Error('la propriété Fields doit être un entier');
        }

        for ($i=0; $i <= $this->Fields; $i++) {
            if ($i == 0)  $this->Field[] = ($this->xhtml) ? '<input type="hidden" name="MAX_FILE_SIZE" value="'. $this->MaxFilesize .'" />' : '<input type="hidden" name="MAX_FILE_SIZE" value="'. $this->MaxFilesize .'">';
            else          $this->Field[] = ($this->xhtml) ? '<input type="file" name="userfile[]" '. $this->FieldOptions .'/>'              : '<input type="file" name="userfile[]" '. $this->FieldOptions .'>';
        }
    }

    /**
     * Vérifie la configuration de la classe.
     * @access private
     */
    private function CheckConfig() {

        if (!version_compare(phpversion(), self::CST_UPL_PHP_VERSION)) {
            $this->Error('Version PHP minimale requise : ' . self::CST_UPL_PHP_VERSION . '.');
        }

        if (ini_get('file_uploads') != 1) {
            $this->Error('la configuration du serveur ne vous autorise pas à faire du transfert de fichier. Vérifiez la propriété [file_uploads] du fichier [php.ini].');
        }

        if (!is_string($this->Extension)) $this->Error('la propriété Extension est mal configurée.');
        if (!is_string($this->MimeType))  $this->Error('la propriété MimeType est mal configurée.');
        if (!is_string($this->Filename))  $this->Error('la propriété Filename est mal configurée.');
        if (!is_bool($this->Required))    $this->Error('la propriété Required est mal configurée.');
        if (!is_bool($this->SecurityMax)) $this->Error('la propriété SecurityMax est mal configurée.');

        if ($this->WriteMode != self::CST_UPL_WRITE_COPY && $this->WriteMode != self::CST_UPL_WRITE_ERASE && $this->WriteMode != self::CST_UPL_WRITE_IGNORE) {
            $this->Error('la propriété WriteMode est mal configurée.');
        }

        $this->CheckImgPossibility();
        $this->CheckDirUpload();

        // Vérification de la propriété $phpDetectMimeType.
        if (!is_int($this->phpDetectMimeType) || ($this->phpDetectMimeType != self::CST_UPL_HEADER_BROWSER && $this->phpDetectMimeType != self::CST_UPL_HEADER_FILEINFO && $this->phpDetectMimeType != self::CST_UPL_HEADER_MIMETYPE)) {
            $this->Error('la propriété phpDetectMimeType est mal configurée.');
        }
        else if ($this->phpDetectMimeType === self::CST_UPL_HEADER_MIMETYPE) {
            $this->loadMimeTypeLib();
        }
        else if ($this->phpDetectMimeType === self::CST_UPL_HEADER_FILEINFO) {
            $this->loadPECLInfoLib();
        }
    }

    /**
     * Vérifie les propriétés ImgMaxWidth/ImgMaxHeight
     * @access private
     */
    private function CheckImgPossibility() {
        if (!Empty($this->ImgMaxWidth)  && !is_numeric($this->ImgMaxWidth))  $this->Error('la propriété ImgMaxWidth est mal configurée.');
        if (!Empty($this->ImgMaxHeight) && !is_numeric($this->ImgMaxHeight)) $this->Error('la propriété ImgMaxHeight est mal configurée.');
        if (!Empty($this->ImgMinWidth)  && !is_numeric($this->ImgMinWidth))  $this->Error('la propriété ImgMinWidth est mal configurée.');
        if (!Empty($this->ImgMinHeight) && !is_numeric($this->ImgMinHeight)) $this->Error('la propriété ImgMinHeight est mal configurée.');
    }

    /**
     * Essaie de charger la librairie MimeType.
     *
     * @access  private
     * @return  bool
     */
    private function loadMimeTypeLib() {

        if(!extension_loaded(self::CST_UPL_EXT_MIMEMAGIC)) @dl(self::CST_UPL_EXT_MIMEMAGIC . PHP_SHLIB_SUFFIX);

        if(!extension_loaded(self::CST_UPL_EXT_MIMEMAGIC)) {
            trigger_error('Impossible de charger la librairie ' . self::CST_UPL_EXT_MIMEMAGIC . '(http://fr3.php.net/manual/fr/ref.mime-magic.php). La vérification des entêtes de fichiers se fera par le biais des informations retournées par la navigateur.', E_USER_WARNING);
            $this->phpDetectMimeType = self::CST_UPL_HEADER_BROWSER;
            return false;
        }

        return true;
    }

    /**
     * Essaie de charger la librairie PECL.
     * Note : impossible d'activer à la volée cette extension.
     *
     * @access  private
     * @return  bool
     */
    private function loadPECLInfoLib() {

        if(!extension_loaded(self::CST_UPL_EXT_FILEINFO)) {
            trigger_error('Impossible de charger la librairie ' . self::CST_UPL_EXT_FILEINFO . ' (http://fr3.php.net/manual/fr/ref.fileinfo). La vérification des entêtes de fichiers se fera par le biais des informations retournées par la navigateur.', E_USER_WARNING);
            $this->phpDetectMimeType = self::CST_UPL_HEADER_BROWSER;
            return false;
        }

        $this->magicfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mime_magic' . DIRECTORY_SEPARATOR . 'magic';

        if (!is_file($this->magicfile)) {
            trigger_error('Impossible de charger le fichier "magic" nécéssaire à la librairie FileInfo. La vérification des entêtes de fichiers se fera par le biais des informations retournées par la navigateur.', E_USER_WARNING);
            $this->phpDetectMimeType = self::CST_UPL_HEADER_BROWSER;
            return false;
        }

        return true;
    }

    /**
     * Affiche les erreurs de configuration et stoppe tout traitement
     *
     * @var string $error_msg
     */
    private function Error($error_msg) {

        if ($this->TrackError) {
            trigger_error('Erreur [' . get_class($this) . '] : ' . $error_msg, E_USER_ERROR);
            exit;
        }
    }

} // End Class
?>


text:
class AliAnalysisDataContainer;
class AliFlowTrackCuts;
class AliFlowTrackSimpleCuts;
class AliFlowEventCuts;
class AliFlowEventSimpleCuts;

class CutHandlerConvFlow{
  public:
    CutHandlerConvFlow(Int_t nMax=10){
      nCuts=0; nMaxCuts=nMax; validCuts = true;
      eventCutArray = new TString[nMaxCuts]; photonCutArray = new TString[nMaxCuts];
      for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; photonCutArray[i] = "";}
    }

    void AddCut(TString eventCut, TString photonCut){
      if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConvFlow: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
      if( eventCut.Length()!=8 || photonCut.Length()!=26) {cout << "ERROR in CutHandlerConvFlow: Incorrect length of cut string!" << endl; validCuts = false; return;}
      eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut;
      nCuts++;
      return;
    }
    Bool_t AreValid(){return validCuts;}
    Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;}
    TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerConvFlow: GetEventCut wrong index i" << endl;return "";}}
    TString GetPhotonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return photonCutArray[i]; else {cout << "ERROR in CutHandlerConvFlow: GetPhotonCut wrong index i" << endl;return "";}}
  private:
    Bool_t validCuts;
    Int_t nCuts; Int_t nMaxCuts;
    TString* eventCutArray;
    TString* photonCutArray;
};

void AddTask_GammaConvFlow_pPb(
                                TString uniqueID              = "",
                                Int_t trainConfig             = 1,                            //change different set of cuts
                                Int_t enableQAMesonTask       = 0,                            //enable QA in AddTask_GammaConvFlow_PbPb2
                                Int_t enableQAPhotonTask      = 0,                            // enable additional QA task
                                TString cutnumberAODBranch    = "100000006008400000001500000",
                                Bool_t debug                  = kFALSE,
                                Bool_t UseMassSel             = kFALSE,
                                Float_t MinMass               = 0,
                                Float_t MaxMass               = 0.2,
                                Bool_t UseKappaSel            = kFALSE,
                                Float_t MinKappa              = 0,
                                Float_t MaxKappa              = 10,
                                Bool_t isMC                   = kFALSE,
                                TString additionalTrainConfig = "0"                           // additional counter for trainconfig, always has to be last parameter
                              ) {

  Int_t isHeavyIon = 2;

  // make use of train subwagon feature
  if (additionalTrainConfig.Atoi() > 0){
    trainConfig = trainConfig + additionalTrainConfig.Atoi();
  }

  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
      Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
      return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  //=========  Set Cutnumber for V0Reader ================================
  TString cutnumberPhoton = "06000008000100001500000000";
  TString cutnumberEvent = "80000103";
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  //========= Add V0 Reader to  ANALYSIS manager if not yet existent =====
  TString V0ReaderName = Form("V0ReaderV1_%s_%s",cutnumberEvent.Data(),cutnumberPhoton.Data());
  if( !(AliV0ReaderV1*)mgr->GetTask(V0ReaderName.Data()) ){
      AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data());

      fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
      fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
      fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
      fV0ReaderV1->SetUseMassToZero(kFALSE);
      if (!mgr) {
          Error("AddTask_V0ReaderV1", "No analysis manager found.");
          return;
      }

      AliConvEventCuts *fEventCuts=NULL;
      if(cutnumberEvent!=""){
          fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
          fEventCuts->SetPreSelectionCutFlag(kTRUE);
          fEventCuts->SetV0ReaderName(V0ReaderName);
          if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
              fV0ReaderV1->SetEventCuts(fEventCuts);
              fEventCuts->SetFillCutHistograms("",kTRUE);
          }
      }

      // Set AnalysisCut Number
      AliConversionPhotonCuts *fCuts=NULL;
      if(cutnumberPhoton!=""){
          fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
          fCuts->SetPreSelectionCutFlag(kTRUE);
          fCuts->SetIsHeavyIon(isHeavyIon);
          fCuts->SetV0ReaderName(V0ReaderName);
          if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
              fV0ReaderV1->SetConversionCuts(fCuts);
              fCuts->SetFillCutHistograms("",kTRUE);
          }
      }

      if(inputHandler->IsA()==AliAODInputHandler::Class()){
          // AOD mode
          fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
      }
      fV0ReaderV1->Init();

      AliLog::SetGlobalLogLevel(AliLog::kInfo);

      //connect input V0Reader
      mgr->AddTask(fV0ReaderV1);
      mgr->ConnectInput(fV0ReaderV1,0,cinput);
  }

  CutHandlerConvFlow cuts;

  if (trainConfig == 1){
    cuts.AddCut("80000013", "00200009000000008260400000");
  } else if (trainConfig == 2){
    cuts.AddCut("80200013", "00200009000000008260400000");
  } else if (trainConfig == 3){
    cuts.AddCut("82400013", "00200009000000008260400000");
  } else if (trainConfig == 4){
    cuts.AddCut("84600013", "00200009000000008260400000");
  } else if (trainConfig == 5){
    cuts.AddCut("86000013", "00200009000000008260400000");
  } else {
      Error(Form("GammaConvV1_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
      return;
  }

  if(!cuts.AreValid()){
    cout << "\n\n****************************************************" << endl;
    cout << "ERROR: No valid cuts stored in CutHandlerConv! Returning..." << endl;
    cout << "****************************************************\n\n" << endl;
    return;
  }

  const int numberOfCuts = cuts.GetNCuts();

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //================================================
  AliAnalysisTaskGammaConvFlow *task=NULL;
  task= new AliAnalysisTaskGammaConvFlow(Form("GammaConvV1_%i",trainConfig),numberOfCuts);
  task->SetIsHeavyIon(isHeavyIon);
  task->AliAnalysisTaskGammaConvFlow::SetIsMC(isMC);
  task->SetV0ReaderName(V0ReaderName);

  AliFlowTrackCuts* cutsRP = new AliFlowTrackCuts(Form("RFPcuts%s",uniqueID));
  if(!cutsRP) {
      if(debug) cout << " Fatal error: no RP cuts found, could be a library problem! " << endl;
      return 0x0;
  }
  cutsRP = cutsRP->GetStandardVZEROOnlyTrackCuts(); // select vzero tracks
  cutsRP->SetVZEROgainEqualizationPerRing(kFALSE);
  cutsRP->SetApplyRecentering(kTRUE);

  task->SetRPCuts(cutsRP);

  if(UseMassSel==kTRUE)  task->SetMassWindow(MinMass,MaxMass);
  if(UseKappaSel==kTRUE) task->SetKappaWindow(MinKappa,MaxKappa);

  //======================================================================
  TList *EventCutList = new TList();
  TList *ConvCutList = new TList();

  TList *HeaderList = new TList();
  TObjString *Header1 = new TObjString("BOX");
  HeaderList->Add(Header1);
  //    TObjString *Header3 = new TObjString("eta_2");
  //    HeaderList->Add(Header3);

  EventCutList->SetOwner(kTRUE);
  AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts];
  ConvCutList->SetOwner(kTRUE);
  AliConversionPhotonCuts **analysisCuts = new AliConversionPhotonCuts*[numberOfCuts];

  for(Int_t i = 0; i<numberOfCuts; i++){
    analysisEventCuts[i] = new AliConvEventCuts();
    analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data());
    analysisEventCuts[i]->SetV0ReaderName(V0ReaderName);
    EventCutList->Add(analysisEventCuts[i]);
    analysisEventCuts[i]->SetFillCutHistograms("",kFALSE);

    analysisCuts[i] = new AliConversionPhotonCuts();
    analysisCuts[i]->InitializeCutsFromCutString((cuts.GetPhotonCut(i)).Data());
    analysisCuts[i]->SetV0ReaderName(V0ReaderName);
    ConvCutList->Add(analysisCuts[i]);
    analysisCuts[i]->SetFillCutHistograms("",kFALSE);

    analysisEventCuts[i]->SetAcceptedHeader(HeaderList);
  }

  task->SetEventCutList(numberOfCuts,EventCutList);
  task->SetConversionCutList(numberOfCuts,ConvCutList);
  task->SetDoMesonAnalysis(kFALSE);
  task->SetDoMesonQA(enableQAMesonTask); //Attention new switch for Pi0 QA
  task->SetDoPhotonQA(enableQAPhotonTask);  //Attention new switch small for Photon QA

  //connect containers
  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer(Form("GammaConvV1_%i",trainConfig), TList::Class(),
                      AliAnalysisManager::kOutputContainer,Form("GammaConvFlow_%i.root",trainConfig));

  mgr->AddTask(task);
  mgr->ConnectInput(task,0,cinput);
  mgr->ConnectOutput(task,1,coutput);

  return;

}


text:
package info

import (
	"time"

	"github.com/elastic/beats/libbeat/common"
	"github.com/elastic/beats/libbeat/logp"
	"github.com/elastic/beats/metricbeat/mb"
	"github.com/elastic/beats/metricbeat/module/redis"

	rd "github.com/garyburd/redigo/redis"
)

var (
	debugf = logp.MakeDebug("redis-info")
)

func init() {
	if err := mb.Registry.AddMetricSet("redis", "info", New); err != nil {
		panic(err)
	}
}

// MetricSet for fetching Redis server information and statistics.
type MetricSet struct {
	mb.BaseMetricSet
	pool *rd.Pool
}

// New creates new instance of MetricSet
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
	// Unpack additional configuration options.
	config := struct {
		IdleTimeout time.Duration `config:"idle_timeout"`
		Network     string        `config:"network"`
		MaxConn     int           `config:"maxconn" validate:"min=1"`
		Password    string        `config:"password"`
	}{
		Network:  "tcp",
		MaxConn:  10,
		Password: "",
	}
	err := base.Module().UnpackConfig(&config)
	if err != nil {
		return nil, err
	}

	return &MetricSet{
		BaseMetricSet: base,
		pool: redis.CreatePool(base.Host(), config.Password, config.Network,
			config.MaxConn, config.IdleTimeout, base.Module().Config().Timeout),
	}, nil
}

// Fetch fetches metrics from Redis by issuing the INFO command.
func (m *MetricSet) Fetch() (common.MapStr, error) {
	// Fetch default INFO.
	info, err := redis.FetchRedisInfo("default", m.pool.Get())
	if err != nil {
		return nil, err
	}

	debugf("Redis INFO from %s: %+v", m.Host(), info)
	return eventMapping(info), nil
}


text:
<!DOCTYPE html>

    <base href="/">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="assets/ico/favicon.ico">
    <title>Book Monster</title>

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

    <link href="assets/css/internal.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Bitter:400,700,400italic' rel='stylesheet' type='text/css'>

          Book Monster

          <form class="form-inline" action="/search" method="post" id="search">

              Query
              <input type="text" class="form-control" id="gossip" name="text" size="75" maxlength="128" value="{{ gossip.text }}" />

            <button type="submit" class="btn btn-default glyphicon glyphicon-search"></button>
          </form>

{{ book.title }}

{{ book.author }}

                 ISBN
                {{ book.isbn }}

                 Theme
                {{ book.productClass }}

                 Imprint
                {{ book.imprint }}

                 Price (RRP)
                £{{ book.rrp }}

                 Publication Date
                {{ book.datePub }}

              {% if book.prize %}

                 Prize
                {{ book.prize }}

              {% endif %}

              <button type="button" class="btn btn-success">Buy this book</button>
              <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">

                Toggle Dropdown
              </button>

Buy from Amazon.co.uk for £{{ book.rrp }} £{{ (book.rrp * 0.75).toFixed(2) }}

Buy from Waterstones for £{{ book.rrp }}

Buy from Blackwells for £{{ book.rrp }}

          {% if gossip %}

{{ gossip.text }}

← Back to results

          {% endif %}