text:
/**
 * A class to lazily compute values and keep them around.
 */
export class Cache<T> {
    private cached: T | null = null;
    private compute: () => T;

    /**
     * @param {() => T} compute A function to generate the value to cache.
     */
    constructor(compute: () => T) {
        this.compute = compute;
    }

    /**
     * @param {() => T} compute A function to generate the value to cache.
     */
    public static create<T>(compute: () => T): Cache<T> {
        return new Cache<T>(compute);
    }

    /**
     * Deletes the cached value, forcing it to be recomputed.
     */
    public invalidate() {
        this.cached = null;
    }

    /**
     * @returns {T} The cached value, which is created if it doesn't already exist.
     */
    public value(): T {
        if (this.cached === null) {
            this.cached = this.compute();
        }

        return this.cached;
    }
}


text:
FROM mattdm/fedora-small:latest

# Do not install kernel here - it'll fail
RUN yum -y install grub2

redpajama_set_name: RedPajamaGithub


text:
package com.sun.app.common;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.sun.core.Constants;

/**
 * 文件上传总控制器
 *
 * @author Nanlei
 *
 */
public class FileUploadController extends SimpleFormController {
	private static final Log log = LogFactory
			.getLog(FileUploadController.class);
	private HashMap<String, FileUploadProcess> processMap;
	private boolean needTranslateGetMethod = false;

	public boolean isNeedTranslateGetMethod() {
		return needTranslateGetMethod;
	}

	public void setNeedTranslateGetMethod(boolean needTranslateGetMethod) {
		this.needTranslateGetMethod = needTranslateGetMethod;
	}

	public HashMap<String, FileUploadProcess> getProcessMap() {
		return processMap;
	}

	public void setProcessMap(HashMap<String, FileUploadProcess> processMap) {
		this.processMap = processMap;
		System.out.println(this.processMap);
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ModelAndView mv = null;
		putParameterToAttribute(request);
		System.out.println(command);
		System.out.println(errors);
		String commond = (String) request.getAttribute(Constants.COMMAND);
		// 根据提交的command,选择对应的process进行处理
		FileUploadProcess process = null;
		if (commond == null || StringUtils.isEmpty(commond.trim())) {
			if (log.isDebugEnabled()) {
				log
						.debug("commond is null,and will choose the default process");
			}
			process = processMap.get(Constants.DEFAULT);
		} else {
			process = processMap.get(commond);
		}
		// 如果process不存在,跳转到系统错误页面
		if (process == null) {
			if (log.isErrorEnabled()) {
				log.error("process is null,please check your config files");
			}
			mv = new ModelAndView(Constants.SYSTEM_ERROR);
		} else {
			// 进行对应的处理
			Result result = null;
			result = process.validatAndProcess(request, response, command,
					errors);
			if (StringUtils.isNotEmpty(result.getMsgCode())
					&& !result.getMsgCode().startsWith(Constants.ERROR_PREFIX)) {
				Object[] msgArgs = result.getMsgArgs();
				if (null != msgArgs && msgArgs.length != 0) {
					for (int i = 0; i < msgArgs.length; i++) {
						Object msgArg = msgArgs[i];
						if (msgArg instanceof String) {
							if (((String) msgArg).indexOf('.') != -1) {
								String realMsg = this.getApplicationContext()
										.getMessage(
												(String) msgArg,
												null,
												RequestContextUtils
														.getLocale(request));
								msgArgs[i] = realMsg;
							}
						}
					}
				}
				String errorMessage = this.getApplicationContext().getMessage(
						result.getMsgCode(), msgArgs,
						RequestContextUtils.getLocale(request));
				request.setAttribute(Constants.ERROR, errorMessage);
				result.getModel().put("error", errorMessage);
			}

			if (result == null || result.getForward() == null) {
				if (log.isDebugEnabled()) {
					log
							.debug("the forward is null,will be go to the systemerror page");
				}
				mv = new ModelAndView(Constants.SYSTEM_ERROR);
			} else {
				if (result.isRedirect()) {
					mv = new ModelAndView("redirect:" + result.getForward(),
							result.getModel());
				} else if (result.isForward()) {
					mv = new ModelAndView("forward:" + result.getForward(),
							result.getModel());
				} else {
					mv = new ModelAndView(result.getForward(), result
							.getModel());
					if (mv.getViewName().equalsIgnoreCase("jsonView")) {
						if (request.getProtocol().equals("HTTP/1.0")) {
							response.setHeader("Pragma", "no-cache");
						}
						if (request.getProtocol().equals("HTTP/1.1")) {
							response.setHeader("Cache-Control", "no-cache");
							response.addHeader("Cache-Control", "no-store");
							response.addHeader("Cache-Control",
									"must-revalidate");
						}
						response.setDateHeader("Expires", 0);
					}
				}
			}

		}
		return mv;
	}

	private void putParameterToAttribute(HttpServletRequest request) {
		Map<String, String[]> paraMap = request.getParameterMap();
		Iterator<String> iter = paraMap.keySet().iterator();
		boolean isGetMethod = request.getMethod().equalsIgnoreCase("get");
		while (iter.hasNext()) {
			String key = iter.next();
			String[] values = paraMap.get(key);
			if (isGetMethod && needTranslateGetMethod && values != null) {
				for (int i = 0; i < values.length; i++) {
					try {
						values[i] = new String(values[i].getBytes("8859_1"),
								"UTF-8");
					} catch (UnsupportedEncodingException e) {
						if (log.isDebugEnabled()) {
							log.debug(e);
						}
						if (log.isInfoEnabled()) {
							log.info("Unsupport encode!");
						}
					}
				}
			}
			if (request.getAttribute(key) == null) {
				if (values != null) {
					if (values.length == 1) {
						request.setAttribute(key, values[0]);
					} else {
						request.setAttribute(key, Arrays.asList(values));
					}
				}
			}
		}
	}

}


text:
#ifndef _DMCLIENT_H
#define _DMCLIENT_H

#include <sys/param.h>
#include <sys/time.h>

#include <stdio.h>

#include "dm.h"

#define AUTH_USERLEN 256
#define AUTH_PWDLEN 256

struct dmauth {
	int	 port;
	char 	*scheme;
	char	*host;
	char	 user[AUTH_USERLEN+1];
	char	 pwd[AUTH_PWDLEN+1];
};

extern int		 dmLastErrCode;
extern int		 dmRestartCalls;
extern char 		 dmLastErrString[];

typedef int (*dm_auth_t)(struct dmauth *);
extern dm_auth_t		 dmAuthMethod;
typedef void (*stat_display_t) (struct xferstat *, int);
extern stat_display_t	 dmStatDisplayMethod;

int dmget(struct dmreq);
void dmSigHandler(int sig);

#endif /* _DMCLIENT_H */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus erythrojonipus Fayod

### Remarks
null


text:
namespace System.Security.Policy {
    /// <summary>
    ///     Interface for evidence objects that support being "unverified".  For instance, StrongName
    ///     evidence for a strong name signature which was not yet verified.  This interface is used to
    ///     keep track of weather or not the evidence object was needed to compute a grant set.  If it was,
    ///     then we can force verificaiton of the evidence object -- if not we can save time by not doing
    ///     any verification on it.  (Since we didn't use it for policy resolution, it wouldn't have
    ///     mattered if the evidence was not present in the first place).
    /// </summary>
    internal interface IDelayEvaluatedEvidence {
        /// <summary>
        ///     Is this evidence object verified yet?
        /// </summary>
        bool IsVerified
        {
            [System.Security.SecurityCritical]
            get;
        }

        /// <summary>
        ///     Was this evidence object used during the course of policy evaluation?
        /// </summary>
        bool WasUsed { get; }

        /// <summary>
        ///     Mark the object as used
        /// </summary>
        void MarkUsed();
    }
}


text:
sap.ui.define(["exports", "sap/ui/webc/common/thirdparty/base/asset-registries/Icons"], function (_exports, _Icons) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.pathData = _exports.ltr = _exports.default = _exports.accData = void 0;
  const name = "target";
  const pathData = "M256 365L146 218h73V37h74v181h72zM1 510V308h70v107q0 15 10 25t25 10h299q15 0 25.5-10t10.5-25V308h70v202H1z";
  _exports.pathData = pathData;
  const ltr = false;
  _exports.ltr = ltr;
  const accData = null;
  _exports.accData = accData;
  const collection = "business-suite";
  const packageName = "@ui5/webcomponents-icons-business-suite";
  (0, _Icons.registerIcon)(name, {
    pathData,
    ltr,
    collection,
    packageName
  });
  var _default = "target";
  _exports.default = _default;
});


text:
<kd-info-card>
  <kd-info-card-header>{{::$ctrl.i18n.MSG_SERVICE_DETAIL_RESOURCE_DETAILS_TITLE}}</kd-info-card-header>
  <kd-info-card-section name="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_DETAILS_SUBTITLE}}">
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_NAME_LABEL}}">
      <kd-middle-ellipsis display-string="{{::$ctrl.service.objectMeta.name}}"></kd-middle-ellipsis>
    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_NAMESPACE_LABEL}}">
      {{::$ctrl.service.objectMeta.namespace}}
    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_LABEL_SELECTOR_LABEL}}">

        <kd-labels labels="::$ctrl.service.selector"></kd-labels>

        none

    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_LABELS_LABEL}}">

        <kd-labels labels="::$ctrl.service.objectMeta.labels"></kd-labels>

        none

    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_TYPE_LABEL}}">
      {{::$ctrl.service.type}}
    </kd-info-card-entry>
  </kd-info-card-section>

  <kd-info-card-section name="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_CONNECTION_SUBTITLE}}">
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_CLUSTER_IP_LABEL}}">
      {{::$ctrl.service.clusterIP}}
    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_INTERNAL_ENDPOINTS_LABEL}}" ng-if="::$ctrl.service.internalEndpoint">
      <kd-internal-endpoint endpoint="::$ctrl.service.internalEndpoint"></kd-internal-endpoint>
    </kd-info-card-entry>
    <kd-info-card-entry title="{{::$ctrl.i18n.MSG_SERVICE_DETAIL_EXTERNAL_ENDPOINTS_LABEL}}"
                        ng-if="::$ctrl.service.externalEndpoints">
      <kd-external-endpoint endpoints="::$ctrl.service.externalEndpoints"></kd-external-endpoint>
    </kd-info-card-entry>
  </kd-info-card-section>
</kd-info-card>


text:
/*
 * This file is generated by jOOQ.
 */
package org.curioswitch.database.cafemapdb.tables.pojos;

import java.time.LocalDateTime;

import javax.annotation.processing.Generated;

import org.curioswitch.database.cafemapdb.tables.interfaces.IFlywaySchemaHistory;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.12.1"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class FlywaySchemaHistory implements IFlywaySchemaHistory {

    private static final long serialVersionUID = -1108298762;

    private final Integer       installedRank;
    private final String        version;
    private final String        description;
    private final String        type;
    private final String        script;
    private final Integer       checksum;
    private final String        installedBy;
    private final LocalDateTime installedOn;
    private final Integer       executionTime;
    private final Byte          success;

    public FlywaySchemaHistory(IFlywaySchemaHistory value) {
        this.installedRank = value.getInstalledRank();
        this.version = value.getVersion();
        this.description = value.getDescription();
        this.type = value.getType();
        this.script = value.getScript();
        this.checksum = value.getChecksum();
        this.installedBy = value.getInstalledBy();
        this.installedOn = value.getInstalledOn();
        this.executionTime = value.getExecutionTime();
        this.success = value.getSuccess();
    }

    public FlywaySchemaHistory(
        Integer       installedRank,
        String        version,
        String        description,
        String        type,
        String        script,
        Integer       checksum,
        String        installedBy,
        LocalDateTime installedOn,
        Integer       executionTime,
        Byte          success
    ) {
        this.installedRank = installedRank;
        this.version = version;
        this.description = description;
        this.type = type;
        this.script = script;
        this.checksum = checksum;
        this.installedBy = installedBy;
        this.installedOn = installedOn;
        this.executionTime = executionTime;
        this.success = success;
    }

    @Override
    public Integer getInstalledRank() {
        return this.installedRank;
    }

    @Override
    public String getVersion() {
        return this.version;
    }

    @Override
    public String getDescription() {
        return this.description;
    }

    @Override
    public String getType() {
        return this.type;
    }

    @Override
    public String getScript() {
        return this.script;
    }

    @Override
    public Integer getChecksum() {
        return this.checksum;
    }

    @Override
    public String getInstalledBy() {
        return this.installedBy;
    }

    @Override
    public LocalDateTime getInstalledOn() {
        return this.installedOn;
    }

    @Override
    public Integer getExecutionTime() {
        return this.executionTime;
    }

    @Override
    public Byte getSuccess() {
        return this.success;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final FlywaySchemaHistory other = (FlywaySchemaHistory) obj;
        if (installedRank == null) {
            if (other.installedRank != null)
                return false;
        }
        else if (!installedRank.equals(other.installedRank))
            return false;
        if (version == null) {
            if (other.version != null)
                return false;
        }
        else if (!version.equals(other.version))
            return false;
        if (description == null) {
            if (other.description != null)
                return false;
        }
        else if (!description.equals(other.description))
            return false;
        if (type == null) {
            if (other.type != null)
                return false;
        }
        else if (!type.equals(other.type))
            return false;
        if (script == null) {
            if (other.script != null)
                return false;
        }
        else if (!script.equals(other.script))
            return false;
        if (checksum == null) {
            if (other.checksum != null)
                return false;
        }
        else if (!checksum.equals(other.checksum))
            return false;
        if (installedBy == null) {
            if (other.installedBy != null)
                return false;
        }
        else if (!installedBy.equals(other.installedBy))
            return false;
        if (installedOn == null) {
            if (other.installedOn != null)
                return false;
        }
        else if (!installedOn.equals(other.installedOn))
            return false;
        if (executionTime == null) {
            if (other.executionTime != null)
                return false;
        }
        else if (!executionTime.equals(other.executionTime))
            return false;
        if (success == null) {
            if (other.success != null)
                return false;
        }
        else if (!success.equals(other.success))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((this.installedRank == null) ? 0 : this.installedRank.hashCode());
        result = prime * result + ((this.version == null) ? 0 : this.version.hashCode());
        result = prime * result + ((this.description == null) ? 0 : this.description.hashCode());
        result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
        result = prime * result + ((this.script == null) ? 0 : this.script.hashCode());
        result = prime * result + ((this.checksum == null) ? 0 : this.checksum.hashCode());
        result = prime * result + ((this.installedBy == null) ? 0 : this.installedBy.hashCode());
        result = prime * result + ((this.installedOn == null) ? 0 : this.installedOn.hashCode());
        result = prime * result + ((this.executionTime == null) ? 0 : this.executionTime.hashCode());
        result = prime * result + ((this.success == null) ? 0 : this.success.hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("FlywaySchemaHistory (");

        sb.append(installedRank);
        sb.append(", ").append(version);
        sb.append(", ").append(description);
        sb.append(", ").append(type);
        sb.append(", ").append(script);
        sb.append(", ").append(checksum);
        sb.append(", ").append(installedBy);
        sb.append(", ").append(installedOn);
        sb.append(", ").append(executionTime);
        sb.append(", ").append(success);

        sb.append(")");
        return sb.toString();
    }
}


text:
from Foundation import *
import pwd

FIELDS = "name password uid gid class change expire gecos home_dir shell".split()
def getPasswords():
    a = NSMutableArray.array()

    for pw in pwd.getpwall():
        a.append({
            'name': pw.pw_name,
            'password': pw.pw_passwd,
            'uid': pw.pw_uid,
            'gid': pw.pw_gid,
            'gecos': pw.pw_gecos,
            'home_dir': pw.pw_dir,
            'shell': pw.pw_shell,
        })

    return a

class TableModelAppDelegate (NSObject):
    def passwords(self):
        if not hasattr(self, '_cachedpasswords'):
            self._cachedpasswords = getPasswords()
        return self._cachedpasswords

    @objc.IBAction
    def insertRecord_(self, sender):
        passwords = self.passwords()

        self.willChangeValueForKey_('passwords')
        passwords.append(dict(zip(FIELDS, FIELDS)))
        self.didChangeValueForKey_('passwords')


text:
import unittest

import numpy as np
from numpy import testing as np_testing

from pymanopt.manifolds.manifold import Manifold

def manifold_factory(*, point_layout):
    class CustomManifold(Manifold):
        def __init__(self):
            super().__init__(
                name="Test manifold", dimension=3, point_layout=point_layout
            )

        def _generic(self, *args, **kwargs):
            pass

        inner_product = _generic
        norm = _generic
        projection = _generic
        random_point = _generic
        random_tangent_vector = _generic
        zero_vector = _generic

    return CustomManifold()

class TestUnaryFunction(unittest.TestCase):
    """Test cost function, gradient and Hessian for a unary cost function.

    This test uses a cost function of the form::

        f = lambda x: np.sum(x ** 2)
    """

    def setUp(self):
        self.manifold = manifold_factory(point_layout=1)
        self.n = 10
        self.cost = None

    def test_unary_function(self):
        cost = self.cost
        assert cost is not None
        n = self.n

        x = np.random.normal(size=n)

        # Test whether cost function accepts single argument.
        self.assertAlmostEqual(np.sum(x**2), cost(x))

        # Test whether gradient accepts single argument.
        euclidean_gradient = cost.get_gradient_operator()
        np_testing.assert_allclose(2 * x, euclidean_gradient(x))

        # Test the Hessian.
        u = np.random.normal(size=n)

        # Test whether Hessian accepts two regular arguments.
        ehess = cost.get_hessian_operator()
        # Test whether Hessian-vector product is correct.
        np_testing.assert_allclose(2 * u, ehess(x, u))

class TestUnaryComplexFunction(unittest.TestCase):
    """Test cost function, gradient and Hessian of complex unary cost function.

    This test uses a cost function of the form::

        f = lambda x: np.sum(x ** 2).real
    """

    def setUp(self):
        self.manifold = manifold_factory(point_layout=1)
        self.n = 10
        self.cost = None

    def test_unary_function(self):
        cost = self.cost
        assert cost is not None
        n = self.n

        x = np.random.normal(size=n) + 1j * np.random.normal(size=n)

        # Test whether cost function accepts single argument.
        self.assertAlmostEqual(np.sum(x**2).real, cost(x))

        # Test whether gradient accepts single argument.
        euclidean_gradient = cost.get_gradient_operator()
        np_testing.assert_allclose(2 * x.conj(), euclidean_gradient(x))

        # Test the Hessian.
        u = np.random.normal(size=n) + 1j * np.random.normal(size=n)

        # Test whether Hessian accepts two regular arguments.
        ehess = cost.get_hessian_operator()
        # Test whether Hessian-vector product is correct.
        np_testing.assert_allclose(2 * u.conj(), ehess(x, u))

class TestNaryFunction(unittest.TestCase):
    """Test cost function, gradient and Hessian for an nary cost function.

    This test uses a cost function of the form::

        f = lambda x, y: x @ y

    This situation arises e.g. when optimizing over the
    :class:`pymanopt.manifolds.FixedRankEmbedded` manifold where points on the
    manifold are represented as a 3-tuple of a truncated SVD.
    """

    def setUp(self):
        self.manifold = manifold_factory(point_layout=2)
        self.n = 10
        self.cost = None

    def test_nary_function(self):
        cost = self.cost
        assert cost is not None
        n = self.n

        x = np.random.normal(size=n)
        y = np.random.normal(size=n)

        self.assertAlmostEqual(x @ y, cost(x, y))

        euclidean_gradient = cost.get_gradient_operator()
        g = euclidean_gradient(x, y)
        self.assertIsInstance(g, (list, tuple))
        self.assertEqual(len(g), 2)
        for gi in g:
            self.assertIsInstance(gi, np.ndarray)
        g_x, g_y = g
        np_testing.assert_allclose(g_x, y)
        np_testing.assert_allclose(g_y, x)

        # Test the Hessian-vector product.
        u = np.random.normal(size=n)
        v = np.random.normal(size=n)

        ehess = cost.get_hessian_operator()
        h = ehess(x, y, u, v)
        self.assertIsInstance(h, (list, tuple))
        self.assertEqual(len(h), 2)
        for hi in h:
            self.assertIsInstance(hi, np.ndarray)

        # Test whether the Hessian-vector product is correct.
        h_x, h_y = h
        np_testing.assert_allclose(h_x, v)
        np_testing.assert_allclose(h_y, u)

class TestNaryParameterGrouping(unittest.TestCase):
    """Test parameter grouping for cost function, gradient and Hessian.

    This test assumes a cost function of the form::

        f = lambda x, y, z: np.sum(x ** 2 * y + 3 * z)

    This situation could arise e.g. on product manifolds where one of the
    underlying manifolds represents points as a tuple of arrays.
    """

    def setUp(self):
        self.manifold = manifold_factory(point_layout=3)
        self.n = 10
        self.cost = None

    def test_nary_parameter_grouping(self):
        cost = self.cost
        assert cost is not None
        n = self.n

        x, y, z = [np.random.normal(size=n) for _ in range(3)]

        self.assertAlmostEqual(np.sum(x**2 + y + z**3), cost(x, y, z))

        euclidean_gradient = cost.get_gradient_operator()
        g = euclidean_gradient(x, y, z)

        self.assertIsInstance(g, (list, tuple))
        self.assertEqual(len(g), 3)
        for grad in g:
            self.assertIsInstance(grad, np.ndarray)
        g_x, g_y, g_z = g

        # Verify correctness of the gradient.
        np_testing.assert_allclose(g_x, 2 * x)
        np_testing.assert_allclose(g_y, 1)
        np_testing.assert_allclose(g_z, 3 * z**2)

        # Test the Hessian.
        u, v, w = [np.random.normal(size=n) for _ in range(3)]

        ehess = cost.get_hessian_operator()
        h = ehess(x, y, z, u, v, w)

        # Test the type composition of the return value.
        self.assertIsInstance(h, (list, tuple))
        self.assertEqual(len(h), 3)
        for hess in h:
            self.assertIsInstance(hess, np.ndarray)
        h_x, h_y, h_z = h

        # Test whether the Hessian-vector product is correct.
        np_testing.assert_allclose(h_x, 2 * u)
        np_testing.assert_allclose(h_y, 0)
        np_testing.assert_allclose(h_z, 6 * z * w)

class TestVector(unittest.TestCase):
    def setUp(self):
        np.seterr(all="raise")

        self.manifold = manifold_factory(point_layout=1)

        n = self.n = 15

        Y = self.Y = np.random.normal(size=n)
        A = self.A = np.random.normal(size=n)

        # Calculate correct cost and grad...
        self.correct_cost = np.exp(np.sum(Y**2))
        self.correct_grad = 2 * Y * np.exp(np.sum(Y**2))

        # ... and hess
        # First form hessian matrix H
        # Convert Y and A into matrices (row vectors)
        Ymat = Y[np.newaxis, :]
        Amat = A[np.newaxis, :]

        diag = np.eye(n)

        H = np.exp(np.sum(Y**2)) * (4 * Ymat.T @ Ymat + 2 * diag)

        # Then 'left multiply' H by A
        self.correct_hess = np.squeeze(np.array(Amat @ H))

    def test_compile(self):
        np_testing.assert_allclose(self.correct_cost, self.cost(self.Y))

    def test_grad(self):
        grad = self.cost.get_gradient_operator()
        np_testing.assert_allclose(self.correct_grad, grad(self.Y))

    def test_hessian(self):
        hess = self.cost.get_hessian_operator()

        # Now test hess
        np_testing.assert_allclose(self.correct_hess, hess(self.Y, self.A))

class TestMatrix(unittest.TestCase):
    def setUp(self):
        np.seterr(all="raise")

        self.manifold = manifold_factory(point_layout=1)

        m = self.m = 10
        n = self.n = 15

        Y = self.Y = np.random.normal(size=(m, n))
        A = self.A = np.random.normal(size=(m, n))

        # Calculate correct cost and grad...
        self.correct_cost = np.exp(np.sum(Y**2))
        self.correct_grad = 2 * Y * np.exp(np.sum(Y**2))

        # ... and hess
        # First form hessian tensor H (4th order)
        Y1 = Y.reshape(m, n, 1, 1)
        Y2 = Y.reshape(1, 1, m, n)

        # Create an m x n x m x n array with diag[i,j,k,l] == 1 iff
        # (i == k and j == l), this is a 'diagonal' tensor.
        diag = np.eye(m * n).reshape(m, n, m, n)

        H = np.exp(np.sum(Y**2)) * (4 * Y1 * Y2 + 2 * diag)

        # Then 'right multiply' H by A
        Atensor = A.reshape(1, 1, m, n)

        self.correct_hess = np.sum(H * Atensor, axis=(2, 3))

    def test_compile(self):
        np_testing.assert_allclose(self.correct_cost, self.cost(self.Y))

    def test_grad(self):
        grad = self.cost.get_gradient_operator()
        np_testing.assert_allclose(self.correct_grad, grad(self.Y))

    def test_hessian(self):
        hess = self.cost.get_hessian_operator()

        # Now test hess
        np_testing.assert_allclose(self.correct_hess, hess(self.Y, self.A))

class TestTensor3(unittest.TestCase):
    def setUp(self):
        np.seterr(all="raise")

        self.manifold = manifold_factory(point_layout=1)

        n1 = self.n1 = 3
        n2 = self.n2 = 4
        n3 = self.n3 = 5

        Y = self.Y = np.random.normal(size=(n1, n2, n3))
        A = self.A = np.random.normal(size=(n1, n2, n3))

        # Calculate correct cost and grad...
        self.correct_cost = np.exp(np.sum(Y**2))
        self.correct_grad = 2 * Y * np.exp(np.sum(Y**2))

        # ... and hess
        # First form hessian tensor H (6th order)
        Y1 = Y.reshape(n1, n2, n3, 1, 1, 1)
        Y2 = Y.reshape(1, 1, 1, n1, n2, n3)

        # Create an n1 x n2 x n3 x n1 x n2 x n3 diagonal tensor
        diag = np.eye(n1 * n2 * n3).reshape(n1, n2, n3, n1, n2, n3)

        H = np.exp(np.sum(Y**2)) * (4 * Y1 * Y2 + 2 * diag)

        # Then 'right multiply' H by A
        Atensor = A.reshape(1, 1, 1, n1, n2, n3)

        self.correct_hess = np.sum(H * Atensor, axis=(3, 4, 5))

    def test_compile(self):
        np_testing.assert_allclose(self.correct_cost, self.cost(self.Y))

    def test_grad(self):
        grad = self.cost.get_gradient_operator()
        np_testing.assert_allclose(self.correct_grad, grad(self.Y))

    def test_hessian(self):
        hess = self.cost.get_hessian_operator()

        # Now test hess
        np_testing.assert_allclose(self.correct_hess, hess(self.Y, self.A))

class TestMixed(unittest.TestCase):
    def setUp(self):
        np.seterr(all="raise")

        self.manifold = manifold_factory(point_layout=3)

        n1 = self.n1 = 3
        n2 = self.n2 = 4
        n3 = self.n3 = 5
        n4 = self.n4 = 6
        n5 = self.n5 = 7
        n6 = self.n6 = 8

        self.y = y = (
            np.random.normal(size=n1),
            np.random.normal(size=(n2, n3)),
            np.random.normal(size=(n4, n5, n6)),
        )
        self.a = a = (
            np.random.normal(size=n1),
            np.random.normal(size=(n2, n3)),
            np.random.normal(size=(n4, n5, n6)),
        )

        self.correct_cost = (
            np.exp(np.sum(y[0] ** 2))
            + np.exp(np.sum(y[1] ** 2))
            + np.exp(np.sum(y[2] ** 2))
        )

        # Calculate correct grad
        g1 = 2 * y[0] * np.exp(np.sum(y[0] ** 2))
        g2 = 2 * y[1] * np.exp(np.sum(y[1] ** 2))
        g3 = 2 * y[2] * np.exp(np.sum(y[2] ** 2))

        self.correct_grad = (g1, g2, g3)

        # Calculate correct hess
        # 1. Vector
        Ymat = y[0][np.newaxis, :]
        Amat = a[0][np.newaxis, :]

        diag = np.eye(n1)

        H = np.exp(np.sum(y[0] ** 2)) * (4 * Ymat.T @ Ymat + 2 * diag)

        # Then 'left multiply' H by A
        h1 = np.array(Amat @ H).flatten()

        # 2. MATRIX
        # First form hessian tensor H (4th order)
        Y1 = y[1].reshape(n2, n3, 1, 1)
        Y2 = y[1].reshape(1, 1, n2, n3)

        # Create an m x n x m x n array with diag[i,j,k,l] == 1 iff
        # (i == k and j == l), this is a 'diagonal' tensor.
        diag = np.eye(n2 * n3).reshape(n2, n3, n2, n3)

        H = np.exp(np.sum(y[1] ** 2)) * (4 * Y1 * Y2 + 2 * diag)

        # Then 'right multiply' H by A
        Atensor = a[1].reshape(1, 1, n2, n3)

        h2 = np.sum(H * Atensor, axis=(2, 3))

        # 3. Tensor3
        # First form hessian tensor H (6th order)
        Y1 = y[2].reshape(n4, n5, n6, 1, 1, 1)
        Y2 = y[2].reshape(1, 1, 1, n4, n5, n6)

        # Create an n1 x n2 x n3 x n1 x n2 x n3 diagonal tensor
        diag = np.eye(n4 * n5 * n6).reshape(n4, n5, n6, n4, n5, n6)

        H = np.exp(np.sum(y[2] ** 2)) * (4 * Y1 * Y2 + 2 * diag)

        # Then 'right multiply' H by A
        Atensor = a[2].reshape(1, 1, 1, n4, n5, n6)

        h3 = np.sum(H * Atensor, axis=(3, 4, 5))

        self.correct_hess = (h1, h2, h3)

    def test_compile(self):
        np_testing.assert_allclose(self.correct_cost, self.cost(*self.y))

    def test_grad(self):
        grad = self.cost.get_gradient_operator()
        g = grad(*self.y)
        for k in range(len(g)):
            np_testing.assert_allclose(self.correct_grad[k], g[k])

    def test_hessian(self):
        hess = self.cost.get_hessian_operator()

        # Now test hess
        h = hess(*self.y, *self.a)
        for k in range(len(h)):
            np_testing.assert_allclose(self.correct_hess[k], h[k])


text:
/*
 * ymd2yd - compute the date in the year from y/m/d
 *
 * A thin wrapper around a more general calendar function.
 */

#include <config.h>
#include "ntp_stdlib.h"
#include "ntp_calendar.h"

int
ymd2yd(
	int y,
	int m,
	int d)
{
	/*
	 * convert y/m/d to elapsed calendar units, convert that to
	 * elapsed days since the start of the given year and convert
	 * back to unity-based day in year.
	 *
	 * This does no further error checking, since the underlying
	 * function is assumed to work out how to handle the data.
	 */
	return ntpcal_edate_to_yeardays(y-1, m-1, d-1) + 1;
}


text:
package org.apache.taverna.activities.spreadsheet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.Map.Entry;

import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for {@link net.sf.taverna.t2.activities.spreadsheet.ODFSpreadsheetReader}.
 *
 * @author David Withers
 */
public class ODFSpreadsheetReaderTest {

	private SpreadsheetReader spreadsheetReader;

	@Before
	public void setUp() throws Exception {
		spreadsheetReader = new ODFSpreadsheetReader();
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.OdfSpreadsheetReader#read(java.io.InputStream, net.sf.taverna.t2.activities.spreadsheet.Range, net.sf.taverna.t2.activities.spreadsheet.Range, net.sf.taverna.t2.activities.spreadsheet.SpreadsheetRowProcessor)}.
	 */
	@Test
	public void testRead() throws Exception {
		String[] testFiles2 = new String[] { "/test-spreadsheet.ods" };
		for (int i = 0; i < testFiles2.length; i++) {
			final List<Integer> rows = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5));
			spreadsheetReader.read(getClass().getResourceAsStream(testFiles2[i]), new Range(0, 5), new Range(0, 4), false,
					new SpreadsheetRowProcessor() {

						public void processRow(int rowIndex, SortedMap<Integer, String> row) {
							assertTrue(rows.remove((Integer) rowIndex));
							List<Integer> columns = new ArrayList<Integer>(Arrays.asList(0, 1, 2,
									3, 4));
							for (Entry<Integer, String> cell : row.entrySet()) {
								assertTrue(columns.remove(cell.getKey()));
								if (rowIndex == 0) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 1) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 2) {
									if (cell.getKey().equals(0)) {
										assertEquals("true", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("2009-06-15", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertNull(cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("2.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 3 || rowIndex == 4) {
									if (cell.getKey().equals(4)) {
										assertNull(cell.getValue());
									} else {
										assertEquals("X", cell.getValue());
									}
								} else {
									assertNull(cell.getValue());
								}
							}
							assertTrue(columns.isEmpty());
						}
					});
			assertTrue(rows.isEmpty());

		}

	}

	@Test(expected=SpreadsheetReadException.class)
	public void testReadException() throws Exception {
		spreadsheetReader.read(getClass().getResourceAsStream("/test-spreadsheet.csv"), new Range(0,1), new Range(0,1), false, new SpreadsheetRowProcessor() {
			public void processRow(int rowIndex, SortedMap<Integer, String> rowData) {
			}

		});
	}

	@Test(expected=RuntimeException.class)
	public void testReadRuntimeException() throws Exception {
		spreadsheetReader.read(new InputStream() {
			public int read() throws IOException {
				throw new RuntimeException();
			}
		}, new Range(0,1), new Range(0,1), false, new SpreadsheetRowProcessor() {
			public void processRow(int rowIndex, SortedMap<Integer, String> rowData) {
			}
		});
	}

	@Test
	public void testReadAllRows() throws Exception {
		String[] testFiles2 = new String[] { "/test-spreadsheet.ods" };
		for (int i = 0; i < testFiles2.length; i++) {
			final List<Integer> rows = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7,
					8, 9, 10, 11, 12, 13, 14));
			spreadsheetReader.read(getClass().getResourceAsStream(testFiles2[i]), new Range(0, -1), new Range(0, 4), false,
					new SpreadsheetRowProcessor() {

						public void processRow(int rowIndex, SortedMap<Integer, String> row) {
							assertTrue(rows.remove((Integer) rowIndex));
							List<Integer> columns = new ArrayList<Integer>(Arrays.asList(0, 1, 2,
									3, 4));
							for (Entry<Integer, String> cell : row.entrySet()) {
								assertTrue(columns.remove(cell.getKey()));
								if (rowIndex == 0) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 1) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 2) {
									if (cell.getKey().equals(0)) {
										assertEquals("true", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("2009-06-15", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertNull(cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("2.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 3 || rowIndex == 4) {
									if (cell.getKey().equals(4)) {
										assertNull(cell.getValue());
									} else {
										assertEquals("X", cell.getValue());
									}
								} else if (rowIndex == 5 || rowIndex == 6 || rowIndex == 7
										|| rowIndex == 8) {
									assertNull(cell.getValue());
								} else if (rowIndex == 9 || rowIndex == 10 || rowIndex == 11
										|| rowIndex == 12 || rowIndex == 13 || rowIndex == 14) {
									if (cell.getKey().equals(4)) {
										assertNull(cell.getValue());
									} else {
										assertEquals("y", cell.getValue());
									}
								}
							}
							assertTrue(columns.isEmpty());
						}
					});
			assertTrue(rows.isEmpty());
		}
	}

	@Test
	public void testIgnoreBlankRows() throws Exception {
		String[] testFiles2 = new String[] { "/test-spreadsheet.ods" };
		for (int i = 0; i < testFiles2.length; i++) {
			final List<Integer> rows = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14));
			spreadsheetReader.read(getClass().getResourceAsStream(testFiles2[i]), new Range(0, -1), new Range(0, 4), true,
					new SpreadsheetRowProcessor() {

						public void processRow(int rowIndex, SortedMap<Integer, String> row) {
							assertTrue(rows.remove((Integer) rowIndex));
							List<Integer> columns = new ArrayList<Integer>(Arrays.asList(0, 1, 2,
									3, 4));
							for (Entry<Integer, String> cell : row.entrySet()) {
								assertTrue(columns.remove(cell.getKey()));
								if (rowIndex == 0) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 1) {
									if (cell.getKey().equals(0)) {
										assertEquals("A", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("5.0", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertEquals("C", cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("1.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 2) {
									if (cell.getKey().equals(0)) {
										assertEquals("true", cell.getValue());
									} else if (cell.getKey().equals(1)) {
										assertEquals("2009-06-15", cell.getValue());
									} else if (cell.getKey().equals(2)) {
										assertNull(cell.getValue());
									} else if (cell.getKey().equals(3)) {
										assertEquals("2.0", cell.getValue());
									} else {
										assertNull(cell.getValue());
									}
								} else if (rowIndex == 3 || rowIndex == 4) {
									if (cell.getKey().equals(4)) {
										assertNull(cell.getValue());
									} else {
										assertEquals("X", cell.getValue());
									}
								} else if (rowIndex == 9 || rowIndex == 10 || rowIndex == 11
										|| rowIndex == 12 || rowIndex == 13 || rowIndex == 14) {
									if (cell.getKey().equals(4)) {
										assertNull(cell.getValue());
									} else {
										assertEquals("y", cell.getValue());
									}
								}
							}
							assertTrue(columns.isEmpty());
						}
					});
			assertTrue(rows.isEmpty());
		}
	}

}


text:
Приложение содержит функционал по внедрению интеграции с ЕСИА
в механизм аутентификации и авторизации Django, а именно:

* Абстрактную модель **ESIACompatibleUser**;
* Совместиные с абстрактной моделью менеджер **EsiaCompatibleUserManager** и queryset **ESIACompatibleUserQuerySet**;
* Класс для аутентицикации **EsiaAuthBackend**;
* Базовый функционал для прохождения аутентицикации через ЕСИА **(url+view)**

## Зависимости приложения
* Приложения зависит от пакета **esia-connector** (https://github.com/sysols/esia-connector)\
  На данном этапе **esia-connector** требуется установить в разрабатываемый проект как git-подмодуль.\
  Далее, необходимо установить все зависимости **esia-connector**.\
  В будущем **esia-connector** будет оформлен как полноценный пакет с автоматически устанавливаемыми зависимостями.

## Пример использования
Пример использования представлен в проекте **sample-project** репозитория.

#### Основные моменты

##### Требуемые настройки проекта
```python
INSTALLED_APPS = [                                  # Добавить 'esia_auth' в INSTALLED_APPS
    # ...
    'esia_auth',
    # ...
]

AUTH_USER_MODEL = 'app.CustomUser'                  # CustomUser отнаследован от ESIACompatibleUser
AUTHENTICATION_BACKENDS = [
    'esia_auth.gears.EsiaAuthBackend',              # Можете отнаслодовать от EsiaAuthBackend свой бэкенд
    'django.contrib.auth.backends.ModelBackend',
]

ESIA_SETTINGS = {
    'CLIENT_ID': '',
    'REDIRECT_URL': 'http://localhost:8000/esia-auth/login',
    'CERTIFICATE': '/path/to/crt',                              # Относительно ESIA_CERTS_DIR
    'PRIVATE_KEY': '/path/to/key',                              # Относительно ESIA_CERTS_DIR
    'TOKEN_CHECK_KEY': '/path/to/pub_key',                      # Относительно ESIA_CERTS_DIR
    'SERVICE_URL': 'https://esia.gosuslugi.ru',
    'SCOPE': 'openid http://esia.gosuslugi.ru/usr_inf',
}

```

##### URLs
В url-схему проекта добавлена ветка
```python
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # ...
    url(r'^esia-auth/', include('esia_auth.urls', namespace='esia_auth')),  # Необходимо для работы django-esia-auth
    # ...
]
```

Теперь вы можете добавлять ссылки на авторизацию через ЕСИА. Например:
```html
{% extends "admin/login.html" %}
{% load i18n %}

{% block usertools %}
    <a href="{% url 'esia_auth:link' %}">{% trans 'Login with ESIA' %}</a>
{% endblock %}

```

##### Необязательные настройки проекта
* **ESIA_CERTS_DIR** - название директории, где храняться сертификаты и ключи.\
    По умолчанию **certs** в **корне** проекта;
* **ESIA_REDIRECT_AFTER_LOGIN** - адрес редиректа после успешной аутентификации через ЕСИА.\
    По умолчанию **"/"**.
* **ESIA_LOGIN_VIEW** - обработчик для **ESIA_SETTINGS->REDIRECT_URL** (адрес редиректа из ЕСИА).\
    Можете переопределить, например **'apps.user_info.views.login_view'**.\
    По умолчанию берется обработчик из **esia_auth (esia_auth->views->esia_login_view)**;


text:
const actions = {
  scavenge: {
    description: {
      effect() {
        let frac = Random.fraction()
        , peopleCount = this.state.buckets('resources', 'people').getValue()
        , diplomacy = this.getModifier('diplomacy')
        , deathMax = diplomacy ? .05 : .1
        , foodMax = diplomacy ? .3 : .4
        , scrapMax = diplomacy ? .80 : .93
        , evaluation = this.getModifier('evaluation')
        , scrapMulti = this.getModifier('surveying', 1)
        , scrap = 0;
        if (frac < deathMax) {
          let count = Math.round(peopleCount * .1)
          if (count) {
            this.state.buckets('resources', 'people').updateValue(-count)
            log.message(`${count} people were killed!`, 'danger')
          } else log.message('You did not find anything.', 'warning')
        }
        if (frac > deathMax && frac < foodMax) {
          let food = 1 + Random.choice(Array.from(new Array(5), (x,i) => i)) * peopleCount;
          if (food) log.message(`You found ${food} food.`)
          else log.message('You did not find anything.', 'warning')
          this.state.buckets('resources', 'food').updateValue(food)
        }
        if (frac > foodMax && frac < scrapMax) {
          scrap = 1 + Random.choice(Array.from(new Array(10), (x,i) => i)) * peopleCount;
        }
        if (frac > scrapMax) {
          let people = Random.choice(Array.from(new Array(2), (x,i) => i)) * peopleCount;
          if (people) log.message(`You found ${people} people!`, 'success')
          else log.message('You did not find anything.', 'warning')
          extra = this.state.buckets('resources', 'people').updateValue(people)
          if (extra) log.message(`You could not house ${extra} people.`, 'warning')
        }
        if (evaluation || scrap) {
          if (evaluation) {
            scrap += Math.round(peopleCount * 1)
          }
          if (scrap) {
            scrap = scrap * scrapMulti
            log.message(`You found ${scrap} scrap.`)
            this.state.buckets('resources', 'scrap').updateValue(scrap)
          } else log.message('You did not find anything.', 'warning')
        }
      },
      waitTime() {
        let teamwork = this.state.buckets('technology', 'teamwork')
        if (teamwork.owned()) {
          return 2;
        } else {
          return this.state.buckets('resources', 'people').getValue() * .6;
        }
      },
      cost() {
        return {
          food: Math.round( 1 *
            this.state.buckets('resources', 'people').getValue() *
            this.getModifier('conservation', 1)) || 1
        }
      },
      description() {
        return 'Risk the world outside in hopes to find something of value'
      }
    }
  },
  investigate: {
    description: {
      effect() {
        this.state.buckets('resources', 'understanding').updateValue(1 * this.getModifier('language', 1))
      },
      cost() {
        return {
          scrap: 10
        }
      },
      description() {
        return 'Increases your understanding by ' + this.getModifier('language', 1) * 1
      }
    },
    prerequisites() {
      return this.state.buckets('resources', 'scrap').getValue() > 49
    }
  },
  "hunt": {
    description: {
      effect() {
        let peopleCount = this.state.buckets('resources', 'people').getValue()
        , frac = Random.fraction()
        , teamwork = this.getModifier('teamwork')
        , deathMax = teamwork ? .95 : .90
        , foodMulti = teamwork ? 15 : 10
        , animalMax = teamwork ? .10 : .05;

        if (frac > deathMax) {
          let dead = Math.round((peopleCount * .1) % 10);
          if (dead === 0)  dead = 1; //always kill >:(
          this.state.buckets('resources', 'people').updateValue(-dead)
          log.message(`${dead} people died on this hunt!`, 'danger')
        }
        let food = (frac * foodMulti).toFixed(0) * peopleCount + 1;
        this.state.buckets('resources', 'food').updateValue(food)
        log.message(`You collected ${food} food.`)
        if (frac < animalMax) {
          this.state.buckets('resources', 'animals').updateValue(this.getModifier("animal handling", 1))
          log.message(`You found an animal!`, 'success')
        }
      },
      waitTime() {
        let teamwork = this.state.buckets('technology', 'teamwork')
        if (teamwork.owned()) {
          return 2;
        } else {
          return this.state.buckets('resources', 'people').getValue() * .6;
        }
      },
      cost() {
        return {
          food: Math.round( 1 *
            this.state.buckets('resources', 'people').getValue() *
            this.getModifier('conservation', 1)) || 1
        }
      },
      description() { return 'Send out a group to gather food, be warned this is dangerous!'; }
    },
    prerequisites() {
      let tech = this.state.buckets('technology', 'hunting')
      if (tech) return tech.owned()
    }
  },
  butcher: {
    description: {
      effect() {
        this.state.buckets('resources', 'food').updateValue(100)
      },
      cost() {
        return { animals: 10 };
      },
      description() { return 'Collect 100 food'; }
    },
    prerequisites() {
      let tech = this.state.buckets('technology', 'animal farm')
      if (tech) return tech.owned()
    }
  },
  'build shelter': {
    description: {
      effect() {
        this.state.buckets('resources', 'shelter').updateValue(1)
      },
      cost() {
        return { scrap: 200 };
      },
      disable() {
        return this.state.buckets('resources', 'shelter').getValue() >= 15
      },
      description() { return 'Build a place for more people to say.'; }
    },
    prerequisites() {
      let tech = this.state.buckets('technology', 'crafting')
      if (tech) return tech.owned()
    }
  },
  'advance age!': {
    description: {
      effect() {
        this.state.advanceAge('tribal')
      },
      description() { return 'Leave this wasteland and found a tribe.'; }
    },
    prerequisites() {
      let shelter = this.state.buckets('resources', 'shelter')
      , food = this.state.buckets('resources', 'food')
      , animalFarm = this.state.buckets('technology', 'animal farm');
      if (shelter && food && animalFarm) {
        return shelter.getValue() > 9 && food.getValue() > 499 && animalFarm.owned()
      }
    }
  }
}
import {Action} from 'meteor/private:game-engine';
Ages.scavenger.buckets.push({
  class: Action,
  key: 'actions',
  items: actions
})


text:
Configuration for Magento-MVP Ansible Executions
================================================

The configuration files in host_vars are used to define environment specific configuration, such as URLs and credentials.

We ship two sample files OOTB:

* dev-vagrant; contains the sample configuration for the development VM.  If this project has been branched from Magento MVP, then this file should be adjusted to match the projects' configuration.
* singlestack-cloud; contains the sample configuration for a runtime cloud image.  If this project has been branched from Magento MVP, then this file should be adjusted to match the projects' configuration.

It is expected that a configuration file will be created in this folder for each runtime server for a given project, the contents of these files will define the shape and configuration of the runtime servers.

Please see the README.md files for the individual rolebooks to know what configuration variables exist and what can be overridden in these host_var files.


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

/**
 *
 * These are the various summary periods for which feedback is calculated.
 *
 */
public enum FeedbackSummaryPeriodCodeType {

    /**
     *
   * Period including the last 30 days from today.
   *
     */
    THIRTY_DAYS("ThirtyDays"),

    /**
     *
   * Period including the last 52 weeks from today.
   *
     */
    FIFTY_TWO_WEEKS("FiftyTwoWeeks"),

    /**
     *
   * Reserved for internal or future use.
   *
     */
    CUSTOM_CODE("CustomCode");

    private final String value;

    FeedbackSummaryPeriodCodeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static FeedbackSummaryPeriodCodeType fromValue(String v) {
        if (v != null) {
            for (FeedbackSummaryPeriodCodeType c: FeedbackSummaryPeriodCodeType.values()) {
                if (c.value.equals(v)) {
                    return c;
                }
            }
        }
        throw new IllegalArgumentException(v);
    }
}


text:
<?php

namespace PhpCodeQuality\AuthorValidation;

use Symfony\Component\Yaml\Yaml;

/**
 * Configuration class that reads the .check-authors.yml file.
 *
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
 */
class Config
{
    /**
     * Author mapping.
     *
     * Format:
     *   Alias => Real author
     *
     * @var array
     */
    protected $mapping = [];

    /**
     * List of authors to be ignored.
     *
     * @var array
     */
    protected $ignoredAuthors = [];

    /**
     * List of copy-left authors.
     *
     * Format
     *   Author: [Files obtained from that author]
     *
     * @var array
     */
    protected $copyLeft = [];

    /**
     * List of copy-left authors.
     *
     * Format
     *   Author in array key notation: Author
     *
     * @var array
     */
    protected $copyLeftReal = [];

    /**
     * List of paths to include.
     *
     * @var array
     */
    protected $include = [];

    /**
     * List of paths to exclude.
     *
     * @var array
     */
    protected $exclude = [];

    /**
     * Author metadata.
     *
     * Format
     *   Author: [ 'name' => 'value', .. ]
     *
     * @var array
     */
    protected $metadata = [];

    /**
     * Create a new instance.
     *
     * @param string|bool $configFileName The config file to use.
     */
    public function __construct($configFileName = false)
    {
        if ($configFileName !== false) {
            $this->addFromYml($configFileName);
        }
    }

    /**
     * Translate an author to a key value to be used in the lookup arrays.
     *
     * @param string $author The author to make a key.
     *
     * @return string
     */
    private function arrayKey($author)
    {
        return \strtolower(\trim($author));
    }

    /**
     * Match the passed path name against the pattern.
     *
     * @param string $pathName The path name to match.
     * @param string $pattern  The pattern.
     *
     * @return bool True if the pattern matches, false otherwise.
     */
    private function matchPattern($pathName, $pattern)
    {
        if ($pattern[0] !== '/') {
            $pattern = '**/' . $pattern;
        }

        if (\fnmatch($pattern, $pathName)) {
            return true;
        }

        return false;
    }

    /**
     * Match the passed path name against the pattern list.
     *
     * @param string $pathName    The path name to match.
     * @param array  $patternList The pattern list.
     *
     * @return bool|string The first matching pattern if any of the pattern matches, false otherwise.
     */
    private function matchPatterns($pathName, $patternList)
    {
        foreach ($patternList as $pattern) {
            if ($this->matchPattern($pathName, $pattern)) {
                return $pattern;
            }
        }

        return false;
    }

    /**
     * Retrieve the configuration file and merge it into the instance.
     *
     * @param string $fileName The filename to read.
     *
     * @return Config
     *
     * @throws \InvalidArgumentException When the config is not readable.
     */
    public function addFromYml($fileName)
    {
        if (!\is_readable($fileName)) {
            throw new \InvalidArgumentException('Could not read config file: ' . $fileName);
        }

        $config = Yaml::parse(\file_get_contents($fileName));

        if (isset($config['mapping'])) {
            $this->addAuthorMap($config['mapping']);
        }

        if (isset($config['ignore'])) {
            $this->ignoreAuthors($config['ignore']);
        }

        if (isset($config['copy-left'])) {
            $this->addCopyLeftAuthors($config['copy-left']);
        }

        if (isset($config['include'])) {
            $this->includePaths($config['include']);
        }

        if (isset($config['exclude'])) {
            $this->excludePaths($config['exclude']);
        }

        if (isset($config['metadata'])) {
            $this->addAuthorsMetadata($config['metadata']);
        }

        return $this;
    }

    /**
     * Add an author alias.
     *
     * @param string $alias      The alias for the author.
     * @param string $realAuthor The real author to be used.
     *
     * @return Config
     */
    public function aliasAuthor($alias, $realAuthor)
    {
        $this->mapping[$this->arrayKey($alias)] = trim($realAuthor);

        return $this;
    }

    /**
     * Absorb the author mapping.
     *
     * The input argument must be in the format:
     *   Real author: [multiple aliases]
     * or
     *   Real author: alias
     *
     * @param array $mapping The author mapping to absorb.
     *
     * @return Config
     */
    public function addAuthorMap($mapping)
    {
        foreach ($mapping as $author => $aliases) {
            if (\is_array($aliases)) {
                foreach ($aliases as $alias) {
                    $this->aliasAuthor($alias, $author);
                }
            } else {
                $this->aliasAuthor($aliases, $author);
            }
        }

        return $this;
    }

    /**
     * Check if an author is aliased.
     *
     * @param string $potentialAlias The author to check.
     *
     * @return bool
     */
    public function isAlias($potentialAlias)
    {
        return isset($this->mapping[$this->arrayKey($potentialAlias)]);
    }

    /**
     * Translate an author alias to the real name but return null if the author shall be ignored.
     *
     * @param string $author The author to translate.
     *
     * @return string|null
     */
    public function getRealAuthor($author)
    {
        if ($this->isAuthorIgnored($author)) {
            return null;
        }

        if ($this->isAlias($author)) {
            $author = $this->mapping[$this->arrayKey($author)];
        }

        if ($this->isAuthorIgnored($author)) {
            return null;
        }

        return $author;
    }

    /**
     * Ignore the given author.
     *
     * @param string $author The author to ignore.
     *
     * @return Config
     */
    public function ignoreAuthor($author)
    {
        $this->ignoredAuthors[$this->arrayKey($author)] = \trim($author);

        return $this;
    }

    /**
     * Ignore the given authors.
     *
     * @param array $authors The authors to ignore.
     *
     * @return Config
     */
    public function ignoreAuthors($authors)
    {
        foreach ((array) $authors as $author) {
            $this->ignoreAuthor($author);
        }

        return $this;
    }

    /**
     * Check if an author is aliased.
     *
     * @param string $potentialIgnoredAuthor The author to check.
     *
     * @return bool
     */
    public function isAuthorIgnored($potentialIgnoredAuthor)
    {
        return isset($this->ignoredAuthors[$this->arrayKey($potentialIgnoredAuthor)]);
    }

    /**
     * Add the the given authors to the copy-left list using the given pattern.
     *
     * @param string       $author  The author to add.
     * @param string|array $pattern The pattern to add to the author.
     *
     * @return Config
     */
    public function addCopyLeft($author, $pattern)
    {
        if (\is_array($pattern)) {
            foreach ($pattern as $singlePattern) {
                $this->addCopyLeft($author, $singlePattern);
            }

            return $this;
        }

        $this->copyLeft[$this->arrayKey($author)][$this->arrayKey($pattern)] = $pattern;
        $this->copyLeftReal[$this->arrayKey($author)]                        = $author;

        return $this;
    }

    /**
     * Add the the given authors to the copy-left list.
     *
     * @param array $authors The authors to add.
     *
     * @return Config
     */
    public function addCopyLeftAuthors($authors)
    {
        foreach ($authors as $author => $pattern) {
            $this->addCopyLeft($author, $pattern);
        }

        return $this;
    }

    /**
     * Check if an author is listed as copy-left contributor.
     *
     * @param string $author   The author to check.
     * @param string $pathName The path to check.
     *
     * @return bool
     */
    public function isCopyLeftAuthor($author, $pathName)
    {
        $key = $this->arrayKey($author);
        if (!isset($this->copyLeft[$key])) {
            return false;
        }

        return (bool) $this->matchPatterns($pathName, $this->copyLeft[$key]);
    }

    /**
     * Obtain authors to be listed as copy-left contributor.
     *
     * @param string $pathName The path to check.
     *
     * @return string[]
     */
    public function getCopyLeftAuthors($pathName)
    {
        $result = [];
        foreach ($this->copyLeft as $author => $paths) {
            if ($this->matchPatterns($pathName, $paths)) {
                $realAuthor                           = $this->getRealAuthor($this->copyLeftReal[$author]);
                $result[$this->arrayKey($realAuthor)] = $realAuthor;
            }
        }

        return $result;
    }

    /**
     * Add path to the include list.
     *
     * @param string $path The path to include.
     *
     * @return Config
     */
    public function includePath($path)
    {
        $this->include[$this->arrayKey($path)] = $path;

        return $this;
    }

    /**
     * Add paths to the include list.
     *
     * @param array $paths The paths to include.
     *
     * @return Config
     */
    public function includePaths($paths)
    {
        foreach ((array) $paths as $path) {
            $this->includePath($path);
        }

        return $this;
    }

    /**
     * Check if a path matches the include list.
     *
     * @param string $path The path.
     *
     * @return bool
     */
    public function isPathIncluded($path)
    {
        return $this->matchPatterns($path, $this->include);
    }

    /**
     * Retrieve the list of paths to be included.
     *
     * @return string[]
     */
    public function getIncludedPaths()
    {
        return \array_values($this->include);
    }

    /**
     * Add path to the exclude list.
     *
     * @param string $path The path to exclude.
     *
     * @return Config
     */
    public function excludePath($path)
    {
        $this->exclude[$this->arrayKey($path)] = $path;

        return $this;
    }

    /**
     * Add paths to the exclude list.
     *
     * @param array $paths The paths to exclude.
     *
     * @return Config
     */
    public function excludePaths($paths)
    {
        foreach ((array) $paths as $path) {
            $this->excludePath($path);
        }

        return $this;
    }

    /**
     * Check if a path matches the exclude list.
     *
     * @param string $path The path.
     *
     * @return bool
     */
    public function isPathExcluded($path)
    {
        return $this->matchPatterns($path, $this->exclude);
    }

    /**
     * Retrieve the list of paths to be included.
     *
     * @return string[]
     */
    public function getExcludedPaths()
    {
        return \array_values($this->exclude);
    }

    /**
     * Add authors metadata.
     *
     * Format:
     *   Author: [ name => value, ..]
     *
     * @param array $metadata Authors metadata.
     *
     * @return Config
     */
    public function addAuthorsMetadata($metadata)
    {
        foreach ($metadata as $author => $data) {
            foreach ($data as $name => $value) {
                $this->setMetadata($author, $name, $value);
            }
        }

        return $this;
    }

    /**
     * Check if a specific author metadata is defined.
     *
     * @param string $author The author.
     * @param string $name   Metadata name.
     *
     * @return bool
     */
    public function hasMetadata($author, $name)
    {
        return isset($this->metadata[$this->arrayKey($author)][$name]);
    }

    /**
     * Get a specific meta data for an author.
     *
     * It returns null if it is not set.
     *
     * @param string $author The author.
     * @param string $name   Metadata name.
     *
     * @return mixed
     */
    public function getMetadata($author, $name)
    {
        $author = $this->arrayKey($author);

        if (isset($this->metadata[$author][$name])) {
            return $this->metadata[$author][$name];
        }

        return null;
    }

    /**
     * Set a specific meta data for an author.
     *
     * @param string $author The author.
     * @param string $name   Metadata name.
     * @param mixed  $value  Metadata value.
     *
     * @return Config
     */
    public function setMetadata($author, $name, $value)
    {
        $this->metadata[$this->arrayKey($author)][$name] = $value;

        return $this;
    }
}


text:
package io.github.zwieback.relef.exporters;

import io.github.zwieback.relef.entities.Product;
import io.github.zwieback.relef.exporters.xlsx.ProductXlsxConverter;
import io.github.zwieback.relef.repositories.ProductRepository;
import io.github.zwieback.relef.services.DateTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductExporter extends Exporter {

    private final ProductXlsxConverter productXlsxConverter;
    private final ProductRepository productRepository;

    @Autowired
    public ProductExporter(DateTimeService dateTimeService,
                           ProductXlsxConverter productXlsxConverter,
                           ProductRepository productRepository) {
        super(dateTimeService);
        this.productXlsxConverter = productXlsxConverter;
        this.productRepository = productRepository;
    }

    private List<Product> findAllProducts() {
        return productRepository.findAll();
    }

    @Override
    public byte[] toXlsx() {
        return productXlsxConverter.toXlsx(findAllProducts());
    }

    @Override
    public String getXlsxFileName() {
        return super.getFileName("products_", EXTENSION_XLSX);
    }
}


text:
package com.jedrzejewski.slisp.interpreter.primitives;

import com.jedrzejewski.slisp.lispobjects.LispObject;
import com.jedrzejewski.slisp.lispobjects.Num;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;

public class DividePrimitiveTest {

    private DividePrimitive pm = new DividePrimitive();

    @Test
    public void testOneArg() throws Exception {
        Assert.assertEquals(
                new Num(5),
                pm.callWithEvaluatedArgs(Arrays.asList(new Num(5)), null)
        );
    }

    @Test
    public void testMultipleArgs() throws Exception {
        List<LispObject> numbers = Stream
                .of(10, 2, -1)
                .map(Num::new)
                .collect(Collectors.toList());
        Assert.assertEquals(new Num(-5), pm.callWithEvaluatedArgs(numbers, null));
    }
}


text:
namespace arb {
namespace memory {
// tag for final element in a range
struct end_type {};

} // namespace memory
} // namespace arb


text:
import type { TSimpleUser } from './account'
// see https://stackoverflow.com/a/67301712/4050784
// TODO: move tu utils
type TTitleCase<T extends string, D extends string = ' '> = string extends T
  ? never
  : T extends `${infer F}${D}${infer R}`
  ? `${Capitalize<F>}${D}${TTitleCase<R, D>}`
  : Capitalize<T>

export type TEmotionType =
  | 'downvote'
  | 'beer'
  | 'heart'
  | 'confused'
  | 'popcorn'
  | 'pill'

export type TEmotionCountKey = `${TEmotionType}Count`
export type TEmotionViewerHasKey = `viewerHas${TTitleCase<TEmotionType>}ed`

export type TEmotion = {
  [key: string]: number | boolean | string | TSimpleUser[]
  // [key in TEmotionCountKey]: number
  // [key in TEmotionViewerHasKey]: boolean
  // [key in TEmotionType]: number
  // [key in TEmotionViewerHasKey]: boolean
}


text:
since: 2.4.2
category: Connection Management
signatures:
    - - dataType: int
        name: connectionID
        description: ~
        default: ~
      - dataType: bool
        name: bSet
        description: ~
        default: ~
returns:
    dataType: bool
    description: ~
---

This function needs a description. Please feel free to contribute a description to this function.


text:
"""
@file
@brief Measures speed.
"""
import sys
from timeit import Timer

def measure_time(stmt, context=None, repeat=10, number=50, div_by_number=False,
                 max_time=None):
    """
    Measures a statement and returns the results as a dictionary.

    :param stmt: string
    :param context: variable to know in a dictionary
    :param repeat: average over *repeat* experiment
    :param number: number of executions in one row
    :param div_by_number: divide by the number of executions
    :param max_time: execute the statement until the total goes
        beyond this time (approximatively), *repeat* is ignored,
        *div_by_number* must be set to True
    :return: dictionary

    .. runpython::
        :showcode:

        from cpyquickhelper.numbers import measure_time
        from math import cos

        res = measure_time(lambda: cos(0.5))
        print(res)

    See `Timer.repeat <https://docs.python.org/3/library/
    timeit.html?timeit.Timer.repeat>`_
    for a better understanding of parameter *repeat* and *number*.
    The function returns a duration corresponding to
    *number* times the execution of the main statement.

    .. versionchanged:: 0.4
        Parameter *max_time* was added.
    """
    if not callable(stmt) and not isinstance(stmt, str):
        raise TypeError(
            f"stmt is not callable or a string but is of type {type(stmt)!r}.")
    if context is None:
        context = {}

    import numpy  # pylint: disable=C0415
    if isinstance(stmt, str):
        tim = Timer(stmt, globals=context)
    else:
        tim = Timer(stmt)

    if max_time is not None:
        if not div_by_number:
            raise ValueError(
                "div_by_number must be set to True of max_time is defined.")
        i = 1
        total_time = 0
        results = []
        while True:
            for j in (1, 2):
                number = i * j
                time_taken = tim.timeit(number)
                results.append((number, time_taken))
                total_time += time_taken
                if total_time >= max_time:
                    break
            if total_time >= max_time:
                break
            ratio = (max_time - total_time) / total_time
            ratio = max(ratio, 1)
            i = int(i * ratio)

        res = numpy.array(results)
        tw = res[:, 0].sum()
        ttime = res[:, 1].sum()
        mean = ttime / tw
        ave = res[:, 1] / res[:, 0]
        dev = (((ave - mean) ** 2 * res[:, 0]).sum() / tw) ** 0.5
        mes = dict(average=mean, deviation=dev, min_exec=numpy.min(ave),
                   max_exec=numpy.max(ave), repeat=1, number=tw,
                   ttime=ttime)
    else:
        res = numpy.array(tim.repeat(repeat=repeat, number=number))
        if div_by_number:
            res /= number

        mean = numpy.mean(res)
        dev = numpy.mean(res ** 2)
        dev = (dev - mean**2) ** 0.5
        mes = dict(average=mean, deviation=dev, min_exec=numpy.min(res),
                   max_exec=numpy.max(res), repeat=repeat, number=number,
                   ttime=res.sum())

    if 'values' in context:
        if hasattr(context['values'], 'shape'):
            mes['size'] = context['values'].shape[0]
        else:
            mes['size'] = len(context['values'])  # pragma: no cover
    else:
        mes['context_size'] = sys.getsizeof(context)
    return mes

def _fcts():
    """
    Returns functions to measure.
    """
    import numpy  # pylint: disable=C0415
    from .cbenchmark_dot import vector_dot_product  # pylint: disable=E0611,C0415
    from .cbenchmark_dot import vector_dot_product16  # pylint: disable=E0611,C0415
    from .cbenchmark_dot import vector_dot_product16_nofcall  # pylint: disable=E0611,C0415
    from .cbenchmark_dot import vector_dot_product16_sse  # pylint: disable=E0611,C0415

    def simple_dot(values):
        return numpy.dot(values, values)

    def c11_dot(vect):
        return vector_dot_product(vect, vect)

    def c11_dot16(vect):
        return vector_dot_product16(vect, vect)

    def c11_dot16_nofcall(vect):
        return vector_dot_product16_nofcall(vect, vect)

    def c11_dot16_sse(vect):
        return vector_dot_product16_sse(vect, vect)

    return [simple_dot, c11_dot, c11_dot16, c11_dot16_nofcall, c11_dot16_sse]

def check_speed(dims=[100000], repeat=10, number=50, fLOG=print):  # pylint: disable=W0102
    """
    Prints out some information about speed computation
    of this laptop. See :ref:`cbenchmarkbranchingrst` to compare.

    @param      dims        sets of dimensions to try
    @param      repeat      average over *repeat* experiment
    @param      number      number of execution in one row
    @param      fLOG        logging function
    @return                 iterator on results

    :epkg:`numpy` is multithreaded. For an accurate comparison,
    this needs to be disabled. This can be done by setting environment variable
    ``MKL_NUM_THREADS=1`` or by running:

    ::

        import mkl
        mkl.set_num_threads(1)

    .. index:: MKL_NUM_THREADS

    One example of use:

    .. runpython::
        :showcode:

        from cpyquickhelper.numbers import check_speed
        res = list(check_speed(dims=[100, 1000]))
        import pprint
        pprint.pprint(res)
    """
    import numpy  # pylint: disable=C0415
    fcts = _fcts()
    mx = max(dims)
    vect = numpy.ones((mx,))
    for i in range(0, vect.shape[0]):
        vect[i] = i
    for i in dims:
        values = vect[:i].copy()
        for fct in fcts:
            ct = {"fct": fct, 'values': values}
            t = measure_time(lambda f=fct, v=values: f(v),
                             repeat=repeat, number=number, context=ct)
            t['name'] = fct.__name__
            if fLOG:
                fLOG(t)
            yield t


text: dice rolling like trpg


text:
module API
  class Todos < Grape::API
    include PaginationParams

    before { authenticate! }

    ISSUABLE_TYPES = {
      'merge_requests' => ->(iid) { find_merge_request_with_access(iid) },
      'issues' => ->(iid) { find_project_issue(iid) }
    }.freeze

    params do
      requires :id, type: String, desc: 'The ID of a project'
    end
    resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
      ISSUABLE_TYPES.each do |type, finder|
        type_id_str = "#{type.singularize}_iid".to_sym

        desc 'Create a todo on an issuable' do
          success Entities::Todo
        end
        params do
          requires type_id_str, type: Integer, desc: 'The IID of an issuable'
        end
        post ":id/#{type}/:#{type_id_str}/todo" do
          issuable = instance_exec(params[type_id_str], &finder)
          todo = TodoService.new.mark_todo(issuable, current_user).first

          if todo
            present todo, with: Entities::Todo, current_user: current_user
          else
            not_modified!
          end
        end
      end
    end

    resource :todos do
      helpers do
        def find_todos
          TodosFinder.new(current_user, params).execute
        end
      end

      desc 'Get a todo list' do
        success Entities::Todo
      end
      params do
        use :pagination
      end
      get do
        present paginate(find_todos), with: Entities::Todo, current_user: current_user
      end

      desc 'Mark a todo as done' do
        success Entities::Todo
      end
      params do
        requires :id, type: Integer, desc: 'The ID of the todo being marked as done'
      end
      post ':id/mark_as_done' do
        TodoService.new.mark_todos_as_done_by_ids(params[:id], current_user)
        todo = current_user.todos.find(params[:id])

        present todo, with: Entities::Todo, current_user: current_user
      end

      desc 'Mark all todos as done'
      post '/mark_as_done' do
        todos = find_todos
        TodoService.new.mark_todos_as_done(todos, current_user)

        no_content!
      end
    end
  end
end


text:
using UnityEngine;
using System.Collections;

public class SlowBullet : MonoBehaviour
{
	public float slowPercentage = 0.5f;
	public float slowTime;
	public GameObject restoreSpeedObject;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

	void OnCollisionEnter(Collision collision)
	{
		if(collision.collider.tag == "Enemy")
		{
			if(!collision.collider.GetComponentInChildren<RestoreSpeed>())
			{

				ShipSmoothMove scriptInstance = collision.collider.GetComponent<ShipSmoothMove>();

				GameObject restoreSpeedInstance = Instantiate(restoreSpeedObject, collision.collider.transform.position, Quaternion.identity) as GameObject;
				restoreSpeedInstance.transform.parent = collision.collider.transform;
				RestoreSpeed scriptInstance2 = restoreSpeedInstance.GetComponent<RestoreSpeed>();
				scriptInstance2.time = slowTime;
				scriptInstance2.originalSpeed = scriptInstance.maxSpeed;

				scriptInstance.maxSpeed *= slowPercentage;
			}
		}
	}
}


text:
#ifndef INC_CharStreamException_hpp__
#define INC_CharStreamException_hpp__

/* ANTLR Translator Generator
 * Project led by Terence Parr at http://www.jGuru.com
 * Software rights: http://www.antlr.org/license.html
 *
 * $Id: //depot/code/org.antlr/release/antlr-2.7.7/lib/cpp/antlr/CharStreamException.hpp#2 $
 */

#include <antlr/config.hpp>
#include <antlr/ANTLRException.hpp>

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif

class ANTLR_API CharStreamException : public ANTLRException {
public:
	CharStreamException(const ANTLR_USE_NAMESPACE(std)string& s)
		: ANTLRException(s) {}
	~CharStreamException() throw() {}
};

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif

#endif //INC_CharStreamException_hpp__


text:
import divisors from './divisors';
export default (number) => {
  let sqrt = Math.sqrt(number);
  return sqrt % 1.0 === 0 && divisors(number).indexOf(sqrt) > -1;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1424</FormatID>
      <FormatName>Apple Disk Copy Image</FormatName>
      <FormatVersion>4.2</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Aggregate</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Disk Copy 4.2 (DC42) is the common name used to refer to disk images of floppy disks created by the 4.2 version of Disk Copy provided by the Mac Operating System.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>204</ProvenanceSourceID>
      <ProvenanceName>Yale University Library / Yale University Library</ProvenanceName>
      <ProvenanceSourceDate>14 Feb 2014</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>14 Feb 2014</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/625</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <ExternalSignature>
        <ExternalSignatureID>1467</ExternalSignatureID>
        <Signature>dmg</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <ExternalSignature>
        <ExternalSignatureID>1468</ExternalSignatureID>
        <Signature>smi</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <ExternalSignature>
        <ExternalSignatureID>1469</ExternalSignatureID>
        <Signature>img</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <ExternalSignature>
        <ExternalSignatureID>1487</ExternalSignatureID>
        <Signature>image</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>958</SignatureID>
        <SignatureName>Apple Disk Copy Image</SignatureName>
        <SignatureNote>The byte at position 0x40-43 represent four potential values for data block sizes and 0x44-47 represent 3 potential tag sizes in bytes (there is a possiblity there are additional values for these sequences which may require future adjustment to the signature) 0x50 defines the disk encoding. Byte 0x51 defines the 'format byte'. Bytes 0x52-53 are the private word/magic number used for identification. Further information is found here: http://68kmla.org/wiki/index.php/DiskCopy_4.2_format_specification</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1181</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>64</Offset>
          <MaxOffset>
          </MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>(00064000|000C8000|000B4000|00168000)(00002580|00004B00|00000000){8}(00|01|02|03)(02|12|22|24|96)0100</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
import React from 'react';
import RcTree, { TreeNode } from 'rc-tree';
import animation from '../_util/openAnimation';

export interface AntTreeNodeProps {
  disabled?: boolean;
  disableCheckbox?: boolean;
  title?: string | React.ReactNode;
  key?: string;
  isLeaf?: boolean;
}

export class AntTreeNode extends React.Component<AntTreeNodeProps, {}> {
  render() {
    return <AntTreeNode {...this.props} />;
  }
}

export interface AntTreeNodeEvent {
  event: 'check' | 'select';
  node: AntTreeNode;
  checked?: boolean;
  checkedNodes?: Array<AntTreeNode>;
  selected?: boolean;
  selectedNodes?: Array<AntTreeNode>;
}

export interface AntTreeNodeMouseEvent {
  node: AntTreeNode;
  event: React.MouseEventHandler<any>;
}

export interface TreeProps {
  showLine?: boolean;
  className?: string;
  /** 是否支持多选 */
  multiple?: boolean;
  /** 是否自动展开父节点 */
  autoExpandParent?: boolean;
  /** checkable状态下节点选择完全受控(父子节点选中状态不再关联)*/
  checkStrictly?: boolean;
  /** 是否支持选中 */
  checkable?: boolean;
  /** 默认展开所有树节点 */
  defaultExpandAll?: boolean;
  /** 默认展开指定的树节点 */
  defaultExpandedKeys?: Array<string>;
  /** (受控)展开指定的树节点 */
  expandedKeys?: Array<string>;
  /** (受控)选中复选框的树节点 */
  checkedKeys?: Array<string> | { checked: Array<string>, halfChecked: Array<string> };
  /** 默认选中复选框的树节点 */
  defaultCheckedKeys?: Array<string>;
  /** (受控)设置选中的树节点 */
  selectedKeys?: Array<string>;
  /** 默认选中的树节点 */
  defaultSelectedKeys?: Array<string>;
  /** 展开/收起节点时触发 */
  onExpand?: (expandedKeys: Array<string>, info: { node: AntTreeNode, expanded: boolean }) => void | PromiseLike<any>;
  /** 点击复选框触发 */
  onCheck?: (checkedKeys: Array<string>, e: AntTreeNodeEvent) => void;
  /** 点击树节点触发 */
  onSelect?: (selectedKeys: Array<string>, e: AntTreeNodeEvent) => void;
  /** filter some AntTreeNodes as you need. it should return true */
  filterAntTreeNode?: (node: AntTreeNode) => boolean;
  /** 异步加载数据 */
  loadData?: (node: AntTreeNode) => PromiseLike<any>;
  /** 响应右键点击 */
  onRightClick?: (options: AntTreeNodeMouseEvent) => void;
  /** 设置节点可拖拽(IE>8)*/
  draggable?: boolean;
  /** 开始拖拽时调用 */
  onDragStart?: (options: AntTreeNodeMouseEvent) => void;
  /** dragenter 触发时调用 */
  onDragEnter?: (options: AntTreeNodeMouseEvent) => void;
  /** dragover 触发时调用 */
  onDragOver?: (options: AntTreeNodeMouseEvent) => void;
  /** dragleave 触发时调用 */
  onDragLeave?: (options: AntTreeNodeMouseEvent) => void;
  /** drop 触发时调用 */
  onDrop?: (options: AntTreeNodeMouseEvent) => void;
  style?: React.CSSProperties;
  prefixCls?: string;
  filterTreeNode?: (node: AntTreeNode) => boolean;
}

export default class Tree extends React.Component<TreeProps, any> {
  static TreeNode = TreeNode;

  static defaultProps = {
    prefixCls: 'ant-tree',
    checkable: false,
    showIcon: false,
    openAnimation: animation,
  };

  render() {
    const props = this.props;
    let checkable = props.checkable;
    return (
      <RcTree {...props}
        checkable={checkable ? (<span className={`${props.prefixCls}-checkbox-inner`}>) : checkable }>
        {this.props.children}
      </RcTree>
    );
  }
}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'app-click-me2',
  template: `
    <button (click)="onClickMe2($event)">No! .. Click me!</button>
    {{clickMessage}}`
})
export class ClickMe2Component {
  clickMessage = '';
  clicks = 1;

  onClickMe2(event: any) {
    let evtMsg = event ? ' Event target is ' + event.target.tagName  : '';
    this.clickMessage = (`Click #${this.clicks++}. ${evtMsg}`);
  }
}


text:
package org.apache.webbeans.test.managed.multipleinterfaces;

// @Entity ...
public class MyEntity {

    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}


text:
require 'date'
require 'open-uri'
require 'nokogiri'

class YahooMarketCalendar::Client

  API_URL = 'http://info.finance.yahoo.co.jp/fx/marketcalendar/'

  def get_market_events(date: Date.today, **options)
    country_code = options[:country_code] || YahooMarketCalendar::CountryCode::ALL
    priority     = options[:priority]     || YahooMarketCalendar::Priority::ALL

    charset = nil
    html = open(create_api_url(date, country_code, priority)) do |f|
      charset = f.charset
      f.read # read html text
    end

    doc = Nokogiri::HTML.parse(html, nil, charset)

    day_events = nil

    doc.xpath("//*[@id='main']/div[3]/table").each do |node|
      node.css('tr').each do |row|
        unless row.css('th.date').empty? then
          parsed_date = get_event_date(date.year, row.css('th.date').inner_text)
          if parsed_date === date
            day_events = YahooMarketCalendar::DayEvents.new
            day_events.date = parsed_date
          elsif not day_events.nil?
            # got all specified day event
            return day_events
          end
        else
          unless day_events.nil?
            event = YahooMarketCalendar::Event.new
            event.time = row.css('td.time').inner_text
            event.name = row.css('td.event').inner_text
            event.priority = get_priority(row.css('td.priority').css('span').attribute('class').value)
            event.country_code = get_country_code(row.css('td.event').css('span').attribute('class').value)
            event.last_data = row.css('td.last').inner_text
            event.expectation_data = row.css('td.expectation').inner_text
            event.result_data = row.css('td.result').inner_text
            day_events << event
          end
        end
      end
    end
    return day_events
  end

  private

  def create_api_url(date, country_code, priority)
    API_URL + "?d=" + date.strftime("%Y%m%d") + "&c=" + country_code + "&i=" + priority
  end

  def get_event_date(year, date_text)
    /(\d+)\/(\d+)/ =~ date_text
    month = $1.to_i
    day = $2.to_i
    Date.new(year, month, day)
  end

  def get_priority(priority_class_text)
    /icoRating(\d+)/ =~ priority_class_text
    case $1.to_i
    when 1 then
      YahooMarketCalendar::Priority::LOW
    when 2 then
      YahooMarketCalendar::Priority::MIDDLE
    when 3 then
      YahooMarketCalendar::Priority::HIGH
    else
      YahooMarketCalendar::Priority::UNKNOWN
    end
  end

  def get_country_code(country_class_text)
    /icon\d+ ico([a-zA-Z]+)\d+/ =~ country_class_text
    case $1
    when "Jpn" then
      YahooMarketCalendar::CountryCode::JP
    when "Usa" then
      YahooMarketCalendar::CountryCode::US
    when "Eu" then
      YahooMarketCalendar::CountryCode::EUR
    when "Ger" then
      YahooMarketCalendar::CountryCode::DE
    when "Fra" then
      YahooMarketCalendar::CountryCode::FR
    when "Gbr" then
      YahooMarketCalendar::CountryCode::GB
    when "Aus" then
      YahooMarketCalendar::CountryCode::AU
    when "Nzl" then
      YahooMarketCalendar::CountryCode::NZ
    when "Sui" then
      YahooMarketCalendar::CountryCode::CH
    when "Can" then
      YahooMarketCalendar::CountryCode::CA
    when "Rsa" then
      YahooMarketCalendar::CountryCode::ZA
    when "Sin" then
      YahooMarketCalendar::CountryCode::SG
    when "Hkg" then
      YahooMarketCalendar::CountryCode::HK
    when "Cnh" then
      YahooMarketCalendar::CountryCode::CN
    else
      YahooMarketCalendar::CountryCode::UNKNOWN
    end
  end
end