text:
package org.apache.ignite.internal.processors.cache.query;

import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.query.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.cluster.*;
import org.apache.ignite.internal.processors.affinity.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.query.*;
import org.apache.ignite.internal.util.future.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.plugin.security.*;

import org.jetbrains.annotations.*;

import java.util.*;

import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.*;

/**
 * Query adapter.
 */
public class GridCacheQueryAdapter<T> implements CacheQuery<T> {
    /** Is local node predicate. */
    private static final IgnitePredicate<ClusterNode> IS_LOC_NODE = new IgnitePredicate<ClusterNode>() {
        @Override public boolean apply(ClusterNode n) {
            return n.isLocal();
        }
    };

    /** */
    private final GridCacheContext<?, ?> cctx;

    /** */
    private final GridCacheQueryType type;

    /** */
    private final IgniteLogger log;

    /** Class name in case of portable query. */
    private final String clsName;

    /** */
    private final String clause;

    /** */
    private final IgniteBiPredicate<Object, Object> filter;

    /** Partition. */
    private Integer part;

    /** */
    private final boolean incMeta;

    /** */
    private volatile GridCacheQueryMetricsAdapter metrics;

    /** */
    private volatile int pageSize = Query.DFLT_PAGE_SIZE;

    /** */
    private volatile long timeout;

    /** */
    private volatile boolean keepAll = true;

    /** */
    private volatile boolean incBackups;

    /** */
    private volatile boolean dedup;

    /** */
    private volatile ClusterGroup prj;

    /** */
    private boolean keepPortable;

    /** */
    private UUID subjId;

    /** */
    private int taskHash;

    /**
     * @param cctx Context.
     * @param type Query type.
     * @param clsName Class name.
     * @param clause Clause.
     * @param filter Scan filter.
     * @param part Partition.
     * @param incMeta Include metadata flag.
     * @param keepPortable Keep portable flag.
     */
    public GridCacheQueryAdapter(GridCacheContext<?, ?> cctx,
        GridCacheQueryType type,
        @Nullable String clsName,
        @Nullable String clause,
        @Nullable IgniteBiPredicate<Object, Object> filter,
        @Nullable Integer part,
        boolean incMeta,
        boolean keepPortable) {
        assert cctx != null;
        assert type != null;
        assert part == null || part >= 0;

        this.cctx = cctx;
        this.type = type;
        this.clsName = clsName;
        this.clause = clause;
        this.filter = filter;
        this.part = part;
        this.incMeta = incMeta;
        this.keepPortable = keepPortable;

        log = cctx.logger(getClass());

        metrics = new GridCacheQueryMetricsAdapter();
    }

    /**
     * @param cctx Context.
     * @param type Query type.
     * @param log Logger.
     * @param pageSize Page size.
     * @param timeout Timeout.
     * @param keepAll Keep all flag.
     * @param incBackups Include backups flag.
     * @param dedup Enable dedup flag.
     * @param prj Grid projection.
     * @param filter Key-value filter.
     * @param part Partition.
     * @param clsName Class name.
     * @param clause Clause.
     * @param incMeta Include metadata flag.
     * @param keepPortable Keep portable flag.
     * @param subjId Security subject ID.
     * @param taskHash Task hash.
     */
    public GridCacheQueryAdapter(GridCacheContext<?, ?> cctx,
        GridCacheQueryType type,
        IgniteLogger log,
        int pageSize,
        long timeout,
        boolean keepAll,
        boolean incBackups,
        boolean dedup,
        ClusterGroup prj,
        IgniteBiPredicate<Object, Object> filter,
        @Nullable Integer part,
        @Nullable String clsName,
        String clause,
        boolean incMeta,
        boolean keepPortable,
        UUID subjId,
        int taskHash) {
        this.cctx = cctx;
        this.type = type;
        this.log = log;
        this.pageSize = pageSize;
        this.timeout = timeout;
        this.keepAll = keepAll;
        this.incBackups = incBackups;
        this.dedup = dedup;
        this.prj = prj;
        this.filter = filter;
        this.part = part;
        this.clsName = clsName;
        this.clause = clause;
        this.incMeta = incMeta;
        this.keepPortable = keepPortable;
        this.subjId = subjId;
        this.taskHash = taskHash;
    }

    /**
     * @return Type.
     */
    public GridCacheQueryType type() {
        return type;
    }

    /**
     * @return Class name.
     */
    @Nullable public String queryClassName() {
        return clsName;
    }

    /**
     * @return Clause.
     */
    @Nullable public String clause() {
        return clause;
    }

    /**
     * @return Include metadata flag.
     */
    public boolean includeMetadata() {
        return incMeta;
    }

    /**
     * @return {@code True} if portable should not be deserialized.
     */
    public boolean keepPortable() {
        return keepPortable;
    }

    /**
     * Forces query to keep portable object representation even if query was created on plain projection.
     *
     * @param keepPortable Keep portable flag.
     */
    public void keepPortable(boolean keepPortable) {
        this.keepPortable = keepPortable;
    }

    /**
     * @return Security subject ID.
     */
    public UUID subjectId() {
        return subjId;
    }

    /**
     * @return Task hash.
     */
    public int taskHash() {
        return taskHash;
    }

    /**
     * @param subjId Security subject ID.
     */
    public void subjectId(UUID subjId) {
        this.subjId = subjId;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> pageSize(int pageSize) {
        A.ensure(pageSize > 0, "pageSize > 0");

        this.pageSize = pageSize;

        return this;
    }

    /**
     * @return Page size.
     */
    public int pageSize() {
        return pageSize;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> timeout(long timeout) {
        A.ensure(timeout >= 0, "timeout >= 0");

        this.timeout = timeout;

        return this;
    }

    /**
     * @return Timeout.
     */
    public long timeout() {
        return timeout;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> keepAll(boolean keepAll) {
        this.keepAll = keepAll;

        return this;
    }

    /**
     * @return Keep all flag.
     */
    public boolean keepAll() {
        return keepAll;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> includeBackups(boolean incBackups) {
        this.incBackups = incBackups;

        return this;
    }

    /**
     * @return Include backups.
     */
    public boolean includeBackups() {
        return incBackups;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> enableDedup(boolean dedup) {
        this.dedup = dedup;

        return this;
    }

    /**
     * @return Enable dedup flag.
     */
    public boolean enableDedup() {
        return dedup;
    }

    /** {@inheritDoc} */
    @Override public CacheQuery<T> projection(ClusterGroup prj) {
        this.prj = prj;

        return this;
    }

    /**
     * @return Grid projection.
     */
    public ClusterGroup projection() {
        return prj;
    }

    /**
     * @return Key-value filter.
     */
    @Nullable public <K, V> IgniteBiPredicate<K, V> scanFilter() {
        return (IgniteBiPredicate<K, V>)filter;
    }

    /**
     * @return Partition.
     */
    @Nullable public Integer partition() {
        return part;
    }

    /**
     * @throws IgniteCheckedException If query is invalid.
     */
    public void validate() throws IgniteCheckedException {
        if ((type != SCAN && type != SET) && !GridQueryProcessor.isEnabled(cctx.config()))
            throw new IgniteCheckedException("Indexing is disabled for cache: " + cctx.cache().name());
    }

    /**
     * @param res Query result.
     * @param err Error or {@code null} if query executed successfully.
     * @param startTime Start time.
     * @param duration Duration.
     */
    public void onExecuted(Object res, Throwable err, long startTime, long duration) {
        GridQueryProcessor.onExecuted(cctx, metrics, res, err, startTime, duration, log);
    }

    /** {@inheritDoc} */
    @Override public CacheQueryFuture<T> execute(@Nullable Object... args) {
        return execute(null, null, args);
    }

    /** {@inheritDoc} */
    @Override public <R> CacheQueryFuture<R> execute(IgniteReducer<T, R> rmtReducer, @Nullable Object... args) {
        return execute(rmtReducer, null, args);
    }

    /** {@inheritDoc} */
    @Override public <R> CacheQueryFuture<R> execute(IgniteClosure<T, R> rmtTransform, @Nullable Object... args) {
        return execute(null, rmtTransform, args);
    }

    /** {@inheritDoc} */
    @Override public QueryMetrics metrics() {
        return metrics.copy();
    }

    /** {@inheritDoc} */
    @Override public void resetMetrics() {
        metrics = new GridCacheQueryMetricsAdapter();
    }

    /**
     * @param rmtReducer Optional reducer.
     * @param rmtTransform Optional transformer.
     * @param args Arguments.
     * @return Future.
     */
    @SuppressWarnings("IfMayBeConditional")
    private <R> CacheQueryFuture<R> execute(@Nullable IgniteReducer<T, R> rmtReducer,
        @Nullable IgniteClosure<T, R> rmtTransform, @Nullable Object... args) {
        Collection<ClusterNode> nodes;

        try {
            nodes = nodes();
        }
        catch (IgniteCheckedException e) {
            return queryErrorFuture(cctx, e, log);
        }

        cctx.checkSecurity(SecurityPermission.CACHE_READ);

        if (nodes.isEmpty())
            return queryErrorFuture(cctx, new ClusterGroupEmptyCheckedException(), log);

        if (log.isDebugEnabled())
            log.debug("Executing query [query=" + this + ", nodes=" + nodes + ']');

        if (cctx.deploymentEnabled()) {
            try {
                cctx.deploy().registerClasses(filter, rmtReducer, rmtTransform);
                cctx.deploy().registerClasses(args);
            }
            catch (IgniteCheckedException e) {
                return queryErrorFuture(cctx, e, log);
            }
        }

        if (subjId == null)
            subjId = cctx.localNodeId();

        taskHash = cctx.kernalContext().job().currentTaskNameHash();

        final GridCacheQueryBean bean = new GridCacheQueryBean(this, (IgniteReducer<Object, Object>)rmtReducer,
            (IgniteClosure<Object, Object>)rmtTransform, args);

        final GridCacheQueryManager qryMgr = cctx.queries();

        boolean loc = nodes.size() == 1 && F.first(nodes).id().equals(cctx.localNodeId());

        if (type == SQL_FIELDS || type == SPI)
            return (CacheQueryFuture<R>)(loc ? qryMgr.queryFieldsLocal(bean) :
                qryMgr.queryFieldsDistributed(bean, nodes));
        else if (type == SCAN && part != null && nodes.size() > 1)
            return new CacheQueryFallbackFuture<>(nodes, bean, qryMgr);
        else
            return (CacheQueryFuture<R>)(loc ? qryMgr.queryLocal(bean) : qryMgr.queryDistributed(bean, nodes));
    }

    /**
     * @return Nodes to execute on.
     */
    private Collection<ClusterNode> nodes() throws IgniteCheckedException {
        CacheMode cacheMode = cctx.config().getCacheMode();

        switch (cacheMode) {
            case LOCAL:
                if (prj != null)
                    U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " +
                        "(only local node will be queried): " + this);

                if (type == SCAN && cctx.config().getCacheMode() == LOCAL &&
                    partition() != null && partition() >= cctx.affinity().partitions())
                    throw new IgniteCheckedException("Invalid partition number: " + partition());

                return Collections.singletonList(cctx.localNode());

            case REPLICATED:
                if (prj != null || partition() != null)
                    return nodes(cctx, prj, partition());

                return cctx.affinityNode() ?
                    Collections.singletonList(cctx.localNode()) :
                    Collections.singletonList(F.rand(nodes(cctx, null, partition())));

            case PARTITIONED:
                return nodes(cctx, prj, partition());

            default:
                throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode);
        }
    }

    /**
     * @param cctx Cache context.
     * @param prj Projection (optional).
     * @return Collection of data nodes in provided projection (if any).
     */
    private static Collection<ClusterNode> nodes(final GridCacheContext<?, ?> cctx,
        @Nullable final ClusterGroup prj, @Nullable final Integer part) {
        assert cctx != null;

        final AffinityTopologyVersion topVer = cctx.affinity().affinityTopologyVersion();

        Collection<ClusterNode> affNodes = CU.affinityNodes(cctx);

        if (prj == null && part == null)
            return affNodes;

        final Set<ClusterNode> owners =
            part == null ? Collections.<ClusterNode>emptySet() : new HashSet<>(cctx.topology().owners(part, topVer));

        return F.view(affNodes, new P1<ClusterNode>() {
            @Override public boolean apply(ClusterNode n) {

                return cctx.discovery().cacheAffinityNode(n, cctx.name()) &&
                    (prj == null || prj.node(n.id()) != null) &&
                    (part == null || owners.contains(n));
            }
        });
    }

    /**
     * @param cctx Cache context.
     * @param e Exception.
     * @param log Logger.
     */
    private static <T> GridCacheQueryErrorFuture<T> queryErrorFuture(GridCacheContext<?, ?> cctx,
        Exception e, IgniteLogger log) {

        GridCacheQueryMetricsAdapter metrics = (GridCacheQueryMetricsAdapter)cctx.queries().metrics();

        GridQueryProcessor.onExecuted(cctx, metrics, null, e, 0, 0, log);

        return new GridCacheQueryErrorFuture<>(cctx.kernalContext(), e);
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridCacheQueryAdapter.class, this);
    }

    /**
     * Wrapper for queries with fallback.
     */
    private static class CacheQueryFallbackFuture<R> extends GridFutureAdapter<Collection<R>>
        implements CacheQueryFuture<R> {
        /** Query future. */
        private volatile GridCacheQueryFutureAdapter<?, ?, R> fut;

        /** Backups. */
        private final Queue<ClusterNode> nodes;

        /** Bean. */
        private final GridCacheQueryBean bean;

        /** Query manager. */
        private final GridCacheQueryManager qryMgr;

        /**
         * @param nodes Backups.
         * @param bean Bean.
         * @param qryMgr Query manager.
         */
        public CacheQueryFallbackFuture(Collection<ClusterNode> nodes, GridCacheQueryBean bean,
            GridCacheQueryManager qryMgr) {
            this.nodes = fallbacks(nodes);
            this.bean = bean;
            this.qryMgr = qryMgr;

            init();
        }

        /**
         * @param nodes Nodes.
         * @return Nodes for query execution.
         */
        private Queue<ClusterNode> fallbacks(Collection<ClusterNode> nodes) {
            Queue<ClusterNode> fallbacks = new LinkedList<>();

            ClusterNode node = F.first(F.view(nodes, IS_LOC_NODE));

            if (node != null)
                fallbacks.add(node);

            fallbacks.addAll(node != null ? F.view(nodes, F.not(IS_LOC_NODE)) : nodes);

            return fallbacks;
        }

        /**
         *
         */
        @SuppressWarnings("unchecked")
        private void init() {
            ClusterNode node = nodes.poll();

            GridCacheQueryFutureAdapter<?, ?, R> fut0 = (GridCacheQueryFutureAdapter<?, ?, R>)(node.isLocal() ?
                qryMgr.queryLocal(bean) :
                qryMgr.queryDistributed(bean, Collections.singleton(node)));

            fut0.listen(new IgniteInClosure<IgniteInternalFuture<Collection<R>>>() {
                @Override public void apply(IgniteInternalFuture<Collection<R>> fut) {
                    try {
                        onDone(fut.get());
                    }
                    catch (IgniteClientDisconnectedCheckedException e) {
                        onDone(e);
                    }
                    catch (IgniteCheckedException e) {
                        if (F.isEmpty(nodes))
                            onDone(e);
                        else
                            init();
                    }
                }
            });

            fut = fut0;
        }

        /** {@inheritDoc} */
        @Override public int available() {
            return fut.available();
        }

        /** {@inheritDoc} */
        @Override public boolean cancel() throws IgniteCheckedException {
            return fut.cancel();
        }

        /** {@inheritDoc} */
        @Override public R next() {
            return fut.next();
        }
    }
}


text:
<?php

require_once '../../../vendor/autoload.php';
require_once '../../../apikey.php';

$token  = new \Tmdb\ApiToken(TMDB_API_KEY);
$client = new \Tmdb\Client($token);

$repository = new \Tmdb\Repository\NetworkRepository($client);
$network    = $repository->load(49);

var_dump($network);

redpajama_set_name: RedPajamaGithub


text:
var db = require("./db");
var uuid = require("uuid");
var transporter = require("./mail");
var console = require("console");
var logger = require("./logger");
var config = require("../config");
var _ = require("lodash");
var valid = require("validator");

var util = {

  /**
   * generate a new token
   *
   * @returns token
   */
  newToken: function () {
    return uuid().replace(/-/g, '');
  },

  /**
   * send message by mail
   *
   * @param {String} from
   * @param {String} to
   * @param {String} subject
   * @param {String} text
   * @returns send info
   */
  sendMessage: async function (from, to, subject, text) {
    var mailOpts = {
      from: from, to: to, subject: subject, text: text
    };
    return await transporter.sendMailAsync(mailOpts);
  },

  /**
   * send a token to a certain mail
   *
   * @param {String} to receiver
   * @param {String} token token content
   * @returns
   */
  sendToken: async function (to, token) {
    return await util.sendMessage(`NotificationSync <${config.mail.auth.user}>`, to, "Notification Sync Message", `Dear ${to}: your new token is ${token}`);
  },

  saveNewToken: async function (user) {
    if (!valid.isEmail(user.mail)) {
      throw new Error("Need a correct email address");
    }
    var newToken = util.newToken();
    var res = await db.query(`select * from user where mail = '${user.mail}'`);
    if (res.length > 0) {
      await db.query("insert into token set ?", { user_id: res[0].id, content: newToken });
    } else {
      var res = await db.query("insert into user set ?", user);
      await db.query("insert into token set ?", { user_id: res.insertId, content: newToken })
    }
    await util.sendToken(user.mail, newToken);
  },

  findUserByToken: async function (token) {
    return await db.query(`SELECT user.* from user INNER JOIN token on token.user_id = user.id where token.content = '${token}'`)
  },

  findNotificationByUser: async function (user) {
    return await db.query(`select * from notification where user_id = '${user.id}'`);
  },

  saveNewNotification: async function (user, notification) {
    var newNotification = { user_id: user.id, title: notification.title, content: notification.content };
    return await db.query(`insert into notification set ?`, newNotification);
  },

  /**
   * find unreaded notifications of the user
   *
   * @param {Object} user
   * @returns
   */
  findNotificationUnreaded: async function (user) {
    var notifications = await util.findNotificationByUser(user);
    var ret = _.filter(notifications, { readed: 0 });
    return ret;
  },

  /**
   * set all notifications as readed
   *
   * @param {Array<Number>} ids all notifications ids
   * @returns
   */
  updateNotificationAsReaded: async function (ids) {
    ids = ids || [];
    var ret = await Promise.all(ids.map(id => db.query("update notification set readed = 1 where id = ?", [id])));
    return ret;
  }

};

module.exports = util;


text:
      <button class="btn btn-default btn-xs" ng-click="$selectAll()">All</button>
      <button class="btn btn-default btn-xs" ng-click="$selectNone()">None</button>


text:
import React from 'react'
import PropTypes from 'prop-types'
import isEqual from 'lodash.isequal'

class Form extends React.Component {
  static propTypes = {
    /** Form html chilren */
    children: PropTypes.node,
    /** HTML form attributes */
    formProps: PropTypes.shape({}),
    /** onSubmit callback will pass in model as parameter */
    onSubmit: PropTypes.func,
    /** onValidationError callback will pass in invalid FormComponents as parameter */
    onValidationError: PropTypes.func,
    /** errors from server mapped to model names. Will attach serverErrors styling to FormComppnents */
    serverErrors: PropTypes.shape({}),
  }

  static childContextTypes = {
    ICFormable: PropTypes.object,
  }

  constructor() {
    super()
    this.state = { serverErrors: null }
    this.model = {}
    this.formComponents = {}
    this.invalidComponents = []
  }

  getChildContext() {
    return {
      ICFormable: {
        registerComponent: this.registerComponent,
        unregisterComponent: this.unregisterComponent,
      },
    }
  }

  componentDidMount() {
    this.updateModel()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.serverErrors && !isEqual(this.state.serverErrors, nextProps.serverErrors)) {
      this.setState({ serverErrors: nextProps.serverErrors }, () => {
        this.setErrorsOnFormComponents(this.state.serverErrors)
      })
    }
  }

  setErrorsOnFormComponents(serverErrors) {
    Object.keys(serverErrors).forEach(name => {
      const component = this.formComponents[name]
      component.setState({
        isValid: false,
        serverError: serverErrors[name],
      })
    })
  }

  handleSubmit = e => {
    e && e.preventDefault()
    this.updateModel()

    if (this.formIsValid()) {
      this.setState({ serverErrors: null }, () => {
        this.props.onSubmit && this.props.onSubmit(this.model)
      })
    } else {
      this.props.onValidationError && this.props.onValidationError(this.invalidComponents)
    }
  }

  registerComponent = component => {
    this.formComponents[component.props.name] = component
  }

  unregisterComponent = component => {
    delete this.formComponents[component.props.name]
    delete this.model[component.props.name]
  }

  formIsValid() {
    const components = Object.values(this.formComponents)
    this.invalidComponents = components.filter(component => !component.validate())
    return this.invalidComponents.length === 0
  }

  updateModel() {
    Object.keys(this.formComponents).forEach(name => {
      const component = this.formComponents[name]
      if (component.props.disabled) {
        delete this.model[name]
      } else {
        this.model[name] = component.getValue()
      }
    })
  }

  render() {
    const { children, formProps } = this.props

    return (
      <form {...formProps} onSubmit={this.handleSubmit}>
        {children}
      </form>
    )
  }
}

export default Form


text:
msg = "'import ugali.analysis.isochrone' is deprecated. "
msg += "Use 'import ugali.isochrone' instead."
DeprecationWarning(msg)

from ugali.isochrone import *


text:
package i5.las2peer.services.ocd.metrics;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.junit.Ignore;
import org.junit.Test;

import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.algorithms.CostFunctionOptimizationClusteringAlgorithm;
import i5.las2peer.services.ocd.algorithms.OcdAlgorithm;
import i5.las2peer.services.ocd.algorithms.utils.OcdAlgorithmException;
import i5.las2peer.services.ocd.graphs.Cover;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.testsUtils.OcdTestGraphFactory;

public class NewmanModularityCombinedTest {
	@Ignore
	@Test
	public void testOnJmol() throws AdapterException, FileNotFoundException, IllegalArgumentException, ParseException, OcdAlgorithmException, InterruptedException, OcdMetricException{
		CustomGraph graph = OcdTestGraphFactory.getJmolTestGraph();
		OcdAlgorithm algo = new CostFunctionOptimizationClusteringAlgorithm();
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put(CostFunctionOptimizationClusteringAlgorithm.MAXIMUM_K_NAME, Integer.toString(5));
		parameters.put(CostFunctionOptimizationClusteringAlgorithm.OVERLAPPING_THRESHOLD_NAME, Double.toString(0.3));
		algo.setParameters(parameters);
		Cover cover = algo.detectOverlappingCommunities(graph);

		NewmanModularityCombined metric = new NewmanModularityCombined();
		double value = metric.measure(cover);
		System.out.println(value);
	}
}


text:
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Web.Filters;
using Web.Models;

namespace Web.Controllers
{
    [RoutePrefix("api/role")]
    [ValidateAntiForgeryToken]
    public class RoleController : ApiController
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public RoleController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        // POST api/role/AddUserToRole
        [Authorize(Roles = "admin")]
        [Route("AddUserToRole")]
        public async Task<IHttpActionResult> AddUserToRole(UserRoleModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _userManager.AddToRoleAsync(model.UserId, model.Role);
            var errorResult = GetErrorResult(result);

            return errorResult ?? Ok();
        }

        // POST api/role/RemoveUserFromRole
        [Authorize(Roles = "admin")]
        [Route("RemoveUserFromRole")]
        public async Task<IHttpActionResult> RemoveUserFromRole(UserRoleModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _userManager.RemoveFromRoleAsync(model.UserId, model.Role);
            var errorResult = GetErrorResult(result);

            return errorResult ?? Ok();
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (result.Succeeded) return null;
            if (result.Errors != null)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            if (ModelState.IsValid)
            {
                // No ModelState errors are available to send, so just return an empty BadRequest.
                return BadRequest();
            }

            return BadRequest(ModelState);
        }

    }
}


text:
from tag_tests import *
from model_tests import *


text:
require File.expand_path('../spec_helper', __FILE__)

describe Cequel::Record::Dirty do
  model :Post do
    key :permalink, :text
    column :title, :text
    set :categories, :text
  end

  context 'loaded model' do
    let(:post) do
      Post.create!(
        permalink: 'cequel',
        title: 'Cequel',
        categories: Set['Libraries']
      )
    end

    it 'should not have changed attributes by default' do
      expect(post.changed_attributes).to be_empty
    end

    it 'should have changed attributes if attributes change' do
      post.title = 'Cequel ORM'
      expect(post.changed_attributes).
        to eq({:title => 'Cequel'}.with_indifferent_access)
    end

    it 'should not have changed attributes if attribute set to the same thing' do
      post.title = 'Cequel'
      expect(post.changed_attributes).to be_empty
    end

    it 'should support *_changed? method' do
      post.title = 'Cequel ORM'
      expect(post.title_changed?).to eq(true)
    end

    it 'should not have changed attributes after save' do
      post.title = 'Cequel ORM'
      post.save
      expect(post.changed_attributes).to be_empty
    end

    it 'should have previous changes after save' do
      post.title = 'Cequel ORM'
      post.save
      expect(post.previous_changes).
        to eq({ :title => ['Cequel', 'Cequel ORM'] }.with_indifferent_access)
    end

    it 'should detect changes to collections' do
      post.categories << 'Gems'
      expect(post.changes).to eq(
        {categories: [Set['Libraries'], Set['Libraries', 'Gems']]}.
        with_indifferent_access
      )
    end
  end

  context 'unloaded model' do
    let(:post) { Post['cequel'] }

    it 'should not track changes' do
      post.title = 'Cequel'
      expect(post.changes).to be_empty
    end
  end
end


text:
@interface STTabBarController : UITabBarController

@end


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.server.browserlaunchers;

import org.openqa.selenium.server.RemoteControlConfiguration;

/**
 * {@link org.openqa.selenium.server.browserlaunchers.GoogleChromeLauncher} functional test class.
 *
 * <p>
 * If no local proxy server (such as Selenium Server) is running during this test, there won't be a
 * proxy server for Google Chrome to use. The --proxy-server command-line switch given to Google
 * Chrome does not fall back to a direct connection, so the URLs loaded by this test won't work
 * unless Selenium Server is already running. The tests will still pass, though.
 */
public class GoogleChromeLauncherFunctionalTest {
  public void testCanLaunchASingleBrowser() {
    final GoogleChromeLauncher launcher;

    launcher =
        new GoogleChromeLauncher(BrowserOptions.newBrowserOptions(),
            new RemoteControlConfiguration(), "aSessionId", (String) null);
    launcher.launch("http://www.google.com/");
    Sleeper.sleepTightInSeconds(5);
    launcher.close();
  }

  public void testCanLaunchTwoBrowsersInSequence() {
    final GoogleChromeLauncher firstLauncher;
    final GoogleChromeLauncher secondLauncher;

    firstLauncher =
        new GoogleChromeLauncher(BrowserOptions.newBrowserOptions(),
            new RemoteControlConfiguration(), "firstSessionId", (String) null);
    secondLauncher =
        new GoogleChromeLauncher(BrowserOptions.newBrowserOptions(),
            new RemoteControlConfiguration(), "secondSessionId", (String) null);

    firstLauncher.launch("http://www.google.com/");
    Sleeper.sleepTightInSeconds(5);
    firstLauncher.close();

    secondLauncher.launch("http://www.google.com/");
    Sleeper.sleepTightInSeconds(5);
    secondLauncher.close();
  }

  public void testCanLaunchTwoBrowsersInterleaved() {
    final GoogleChromeLauncher firstLauncher;
    final GoogleChromeLauncher secondLauncher;

    firstLauncher =
        new GoogleChromeLauncher(BrowserOptions.newBrowserOptions(),
            new RemoteControlConfiguration(), "firstSessionId", (String) null);
    secondLauncher =
        new GoogleChromeLauncher(BrowserOptions.newBrowserOptions(),
            new RemoteControlConfiguration(), "secondSessionId", (String) null);

    firstLauncher.launch("http://www.google.com/");
    secondLauncher.launch("http://www.google.com/");
    Sleeper.sleepTightInSeconds(5);
    firstLauncher.close();
    secondLauncher.close();
  }
}


text:
#ifndef test_insert_H_
#define test_insert_H_

# include "Prefix.h"
# if defined (EH_NEW_HEADERS)
#  include <utility>
#  include <vector>
#  include <cassert>
#  include <climits>
# else
#  include <vector.h>
#  include <assert.h>
#  include <limits.h>
# endif
#include "random_number.h"
#include "nc_alloc.h"
#include "ThrowCompare.h"

// A classification system for containers, for verification
struct container_tag {};
struct sequence_container_tag  {};
struct associative_container_tag  {};

struct set_tag  {};
struct multiset_tag  {};
struct map_tag {};
struct multimap_tag {};

template <class C, class Iter>
size_t CountNewItems( const C&, const Iter& firstNew,
                      const Iter& lastNew, sequence_container_tag )
{
    size_t dist = 0;
#if 0 //def __SUNPRO_CC
    EH_DISTANCE( firstNew, lastNew, dist );
#else
    EH_DISTANCE( Iter(firstNew), Iter(lastNew), dist );
#endif
    return dist;
}

template <class C, class Iter>
size_t CountNewItems( const C& c, const Iter& firstNew,
                      const Iter& lastNew, multimap_tag )
{
    return CountNewItems( c, firstNew, lastNew, sequence_container_tag() );
}

template <class C, class Iter>
size_t CountNewItems( const C& c, const Iter& firstNew,
                      const Iter& lastNew, multiset_tag )
{
    return CountNewItems( c, firstNew, lastNew, sequence_container_tag() );
}

template <class C, class Iter, class KeyOfValue>
#ifdef __BORLANDC__
size_t CountUniqueItems_Aux( const C& original, const Iter& firstNew,
#else
size_t CountUniqueItems_Aux( const C& original, Iter firstNew,
#endif
                             Iter lastNew, const KeyOfValue& keyOfValue )
{
  typedef typename C::key_type key;
  typedef typename C::const_iterator const_iter;
  typedef EH_STD::vector<key> key_list;
  typedef typename key_list::iterator key_iterator;
  key_list keys;
  size_t dist = 0;
#ifdef __SUNPRO_CC
  EH_DISTANCE( firstNew, lastNew, dist );
#else
  EH_DISTANCE( Iter(firstNew), Iter(lastNew), dist );
#endif
  keys.reserve( dist );
  for ( Iter x = firstNew; x != lastNew; ++x )
    keys.push_back( keyOfValue(*x) );

  EH_STD::sort( keys.begin(), keys.end() );
  key_iterator last = EH_STD::unique( keys.begin(), keys.end() );

    size_t cnt = 0;
    for ( key_iterator tmp = keys.begin(); tmp != last; ++tmp )
    {
        if ( const_iter(original.find( *tmp )) == const_iter(original.end()) )
            ++cnt;
    }
    return cnt;
}

#if ! defined (__SGI_STL)
EH_BEGIN_NAMESPACE
template <class T>
struct identity
{
  const T& operator()( const T& x ) const { return x; }
};
# if ! defined (__KCC)
template <class _Pair>
struct select1st : public unary_function<_Pair, typename _Pair::first_type> {
  const typename _Pair::first_type& operator()(const _Pair& __x) const {
    return __x.first;
  }
};
# endif
EH_END_NAMESPACE
#endif

template <class C, class Iter>
size_t CountUniqueItems( const C& original, const Iter& firstNew,
                         const Iter& lastNew, set_tag )
{
    typedef typename C::value_type value_type;
    return CountUniqueItems_Aux( original, firstNew, lastNew,
                                 EH_STD::identity<value_type>() );
}

template <class C, class Iter>
size_t CountUniqueItems( const C& original, const Iter& firstNew,
                         const Iter& lastNew, map_tag )
{
#ifdef EH_MULTI_CONST_TEMPLATE_ARG_BUG
    return CountUniqueItems_Aux( original, firstNew, lastNew,
                                 EH_SELECT1ST_HINT<C::value_type, C::key_type>() );
#else
    typedef typename C::value_type value_type;
    return CountUniqueItems_Aux( original, firstNew, lastNew,
                                 EH_STD::select1st<value_type>() );
#endif
}

template <class C, class Iter>
size_t CountNewItems( const C& original, const Iter& firstNew,
                      const Iter& lastNew, map_tag )
{
    return CountUniqueItems( original, firstNew, lastNew,
                             container_category( original ) );
}

template <class C, class Iter>
size_t CountNewItems( const C& original, const Iter& firstNew,
                      const Iter& lastNew, set_tag )
{
    return CountUniqueItems( original, firstNew, lastNew,
                             container_category( original ) );
}

template <class C, class SrcIter>
inline void VerifyInsertion( const C& original, const C& result,
                             const SrcIter& firstNew, const SrcIter& lastNew,
                             size_t, associative_container_tag )
{
    typedef typename C::const_iterator DstIter;
    DstIter first1 = original.begin();
    DstIter first2 = result.begin();

    DstIter* from_orig = new DstIter[original.size()];
    DstIter* last_from_orig = from_orig;

    // fbp : for hashed containers, the following is needed :
    while ( first2 != result.end() )
    {
        EH_STD::pair<DstIter, DstIter> p = EH_STD::mismatch( first1, original.end(), first2 );
        if ( p.second != result.end() )
        {
            SrcIter srcItem = EH_STD::find( SrcIter(firstNew), SrcIter(lastNew), *p.second );

            if (srcItem == lastNew)
            {
                // not found in input range, probably re-ordered from the orig
                DstIter* tmp;
                tmp = EH_STD::find( from_orig, last_from_orig, p.first );

                // if already here, exclude
                if (tmp != last_from_orig)
                {
                    EH_STD::copy(tmp+1, last_from_orig, tmp);
                    last_from_orig--;
                }
                else
                {
                    // register re-ordered element
                    DstIter dstItem;
                    dstItem = EH_STD::find( first1, original.end(), *p.first );
                    EH_ASSERT( dstItem != original.end() );
                    *last_from_orig = dstItem;
                    last_from_orig++;
                    ++p.first;
                }
            }
            ++p.second;
        }
        first1 = p.first;
        first2 = p.second;
    }

    delete [] from_orig;
}

// VC++
template <class C, class SrcIter>
inline void VerifyInsertion(
    const C& original, const C& result, const SrcIter& firstNew,
    const SrcIter& lastNew, size_t, set_tag )
{
    VerifyInsertion( original, result, firstNew, lastNew,
                     size_t(0), associative_container_tag() );
}

template <class C, class SrcIter>
inline void VerifyInsertion(const C& original, const C& result,
                            const SrcIter& firstNew, const SrcIter& lastNew,
                            size_t, multiset_tag )
{
    VerifyInsertion( original, result, firstNew, lastNew,
                     size_t(0), associative_container_tag() );
}

template <class C, class SrcIter>
inline void VerifyInsertion(
    const C& original, const C& result, const SrcIter& firstNew,
    const SrcIter& lastNew, size_t, map_tag )
{
    VerifyInsertion( original, result, firstNew, lastNew,
                     size_t(0), associative_container_tag() );
}

template <class C, class SrcIter>
inline void VerifyInsertion(
    const C& original, const C& result, const SrcIter& firstNew,
    const SrcIter& lastNew, size_t, multimap_tag )
{
    VerifyInsertion( original, result, firstNew, lastNew,
                     size_t(0), associative_container_tag() );
}

template <class C, class SrcIter>
void VerifyInsertion(
# ifdef _MSC_VER
    const C& original, const C& result, SrcIter firstNew,
    SrcIter lastNew, size_t insPos, sequence_container_tag )
# else
    const C& original, const C& result, const SrcIter& firstNew,
    const SrcIter& lastNew, size_t insPos, sequence_container_tag )
# endif
{
    typename C::const_iterator p1 = original.begin();
    typename C::const_iterator p2 = result.begin();
    SrcIter tmp(firstNew);

    for ( size_t n = 0; n < insPos; n++, ++p1, ++p2)
        EH_ASSERT( *p1 == *p2 );

    for (; tmp != lastNew; ++p2, ++tmp ) {
        EH_ASSERT(p2 != result.end());
        EH_ASSERT(*p2 == *tmp);
    }

    for (;  p2 != result.end(); ++p1, ++p2 )
        EH_ASSERT( *p1 == *p2 );
    EH_ASSERT( p1 == original.end() );
}

template <class C, class SrcIter>
inline void VerifyInsertion( const C& original, const C& result,
                             const SrcIter& firstNew,
                             const SrcIter& lastNew, size_t insPos )
{
    EH_ASSERT( result.size() == original.size() +
            CountNewItems( original, firstNew, lastNew,
                           container_category(original) ) );
    VerifyInsertion( original, result, firstNew, lastNew, insPos,
                     container_category(original) );
}

template <class C, class Value>
void VerifyInsertN( const C& original, const C& result, size_t insCnt,
                    const Value& val, size_t insPos )
{
    typename C::const_iterator p1 = original.begin();
    typename C::const_iterator p2 = result.begin();
  (void)val;    //*TY 02/06/2000 - to suppress unused variable warning under nondebug build

    for ( size_t n = 0; n < insPos; n++ )
        EH_ASSERT( *p1++ == *p2++ );

    while ( insCnt-- > 0 )
    {
        EH_ASSERT(p2 != result.end());
        EH_ASSERT(*p2 == val );
        ++p2;
    }

    while ( p2 != result.end() ) {
        EH_ASSERT( *p1 == *p2 );
        ++p1; ++p2;
    }
    EH_ASSERT( p1 == original.end() );
}

template <class C>
void prepare_insert_n( C&, size_t ) {}

// Metrowerks 1.8 compiler requires that specializations appear first (!!)
// or it won't call them. Fixed in 1.9, though.
inline void MakeRandomValue(bool& b) { b = bool(random_number(2) != 0); }

template<class T>
inline void MakeRandomValue(T&) {}

template <class C>
struct test_insert_one
{
    test_insert_one( const C& orig, int pos =-1 )
        : original( orig ), fPos( random_number( orig.size() ))
    {
        MakeRandomValue( fInsVal );
        if ( pos != -1 )
        {
            fPos = size_t(pos);
            if ( pos == 0 )
                gTestController.SetCurrentTestName("single insertion at begin()");
            else
                gTestController.SetCurrentTestName("single insertion at end()");
        }
        else
            gTestController.SetCurrentTestName("single insertion at random position");
    }

    void operator()( C& c ) const
    {
        prepare_insert_n( c, (size_t)1 );
        typename C::iterator pos = c.begin();
        EH_STD::advance( pos, size_t(fPos) );
        c.insert( pos, fInsVal );

        // Prevent simulated failures during verification
        gTestController.CancelFailureCountdown();
        // Success. Check results.
        VerifyInsertion( original, c, &fInsVal, 1+&fInsVal, fPos );
    }
private:
    typename C::value_type fInsVal;
    const C& original;
    size_t fPos;
};

template <class C>
struct test_insert_n
{
    test_insert_n( const C& orig, size_t insCnt, int pos =-1 )
        : original( orig ), fPos( random_number( orig.size() )), fInsCnt(insCnt)
    {
        MakeRandomValue( fInsVal );
        if (pos!=-1)
        {
            fPos=size_t(pos);
            if (pos==0)
                gTestController.SetCurrentTestName("n-ary insertion at begin()");
            else
                gTestController.SetCurrentTestName("n-ary insertion at end()");
        }
        else
            gTestController.SetCurrentTestName("n-ary insertion at random position");
    }

    void operator()( C& c ) const
    {
        prepare_insert_n( c, fInsCnt );
        typename C::iterator pos = c.begin();
        EH_STD::advance( pos, fPos );
        c.insert( pos, fInsCnt, fInsVal );

        // Prevent simulated failures during verification
        gTestController.CancelFailureCountdown();
        // Success. Check results.
        VerifyInsertN( original, c, fInsCnt, fInsVal, fPos );
    }
private:
    typename C::value_type fInsVal;
    const C& original;
    size_t fPos;
    size_t fInsCnt;
};

template <class C>
struct test_insert_value
{
    test_insert_value( const C& orig )
        : original( orig )
    {
        MakeRandomValue( fInsVal );
        gTestController.SetCurrentTestName("insertion of random value");
    }

    void operator()( C& c ) const
    {
        c.insert( fInsVal );

        // Prevent simulated failures during verification
        gTestController.CancelFailureCountdown();
        // Success. Check results.
        VerifyInsertion( original, c, &fInsVal, 1+&fInsVal, size_t(0) );
    }
private:
    typename C::value_type fInsVal;
    const C& original;
};

template <class C>
struct test_insert_noresize
{
    test_insert_noresize( const C& orig )
        : original( orig )
    {
        MakeRandomValue( fInsVal );
        gTestController.SetCurrentTestName("insertion of random value without resize");
    }

    void operator()( C& c ) const
    {
        c.insert_noresize( fInsVal );

        // Prevent simulated failures during verification
        gTestController.CancelFailureCountdown();
        // Success. Check results.
        VerifyInsertion( original, c, &fInsVal, 1+&fInsVal, size_t(0) );
    }
private:
    typename C::value_type fInsVal;
    const C& original;
};

template <class C, class Position, class Iter>
void do_insert_range( C& c_inst, Position offset,
                      Iter first, Iter last, sequence_container_tag )
{
    typedef typename C::iterator CIter;
    CIter pos = c_inst.begin();
    EH_STD::advance( pos, offset );
    c_inst.insert( pos, first, last );
}

template <class C, class Position, class Iter>
void do_insert_range( C& c, Position,
                      Iter first, Iter last, associative_container_tag )
{
    c.insert( first, last );
}

template <class C, class Position, class Iter>
void do_insert_range( C& c, Position, Iter first, Iter last, multiset_tag )
{
    c.insert( first, last );
}

template <class C, class Position, class Iter>
void do_insert_range( C& c, Position, Iter first, Iter last, multimap_tag )
{
    c.insert( first, last );
}

template <class C, class Position, class Iter>
void do_insert_range( C& c, Position, Iter first, Iter last, set_tag )
{
    c.insert( first, last );
}

template <class C, class Position, class Iter>
void do_insert_range( C& c, Position, Iter first, Iter last, map_tag )
{
    c.insert( first, last );
}

/*
template <class C, class Iter>
void prepare_insert_range( C&, size_t, Iter, Iter) {}
*/

template <class C, class Iter>
struct test_insert_range
{
    test_insert_range( const C& orig, Iter first, Iter last, int pos=-1 )
        : fFirst( first ),
          fLast( last ),
          original( orig ),
          fPos( random_number( orig.size() ))
    {
        gTestController.SetCurrentTestName("range insertion");
        if ( pos != -1 )
        {
            fPos = size_t(pos);
            if ( pos == 0 )
                gTestController.SetCurrentTestName("range insertion at begin()");
            else
                gTestController.SetCurrentTestName("range insertion at end()");
        }
        else
            gTestController.SetCurrentTestName("range insertion at random position");
    }

    void operator()( C& c ) const
    {
//        prepare_insert_range( c, fPos, fFirst, fLast );
        do_insert_range( c, fPos, fFirst, fLast, container_category(c) );

        // Prevent simulated failures during verification
        gTestController.CancelFailureCountdown();
        // Success. Check results.
        VerifyInsertion( original, c, fFirst, fLast, fPos );
    }
private:
    Iter fFirst, fLast;
    const C& original;
    size_t fPos;
};

template <class C, class Iter>
test_insert_range<C, Iter> insert_range_tester( const C& orig, const Iter& first, const Iter& last )
{
    return test_insert_range<C, Iter>( orig, first, last );
}

template <class C, class Iter>
test_insert_range<C, Iter> insert_range_at_begin_tester( const C& orig, const Iter& first, const Iter& last )
{
  return test_insert_range<C, Iter>( orig, first, last , 0);
}

template <class C, class Iter>
test_insert_range<C, Iter> insert_range_at_end_tester( const C& orig, const Iter& first, const Iter& last )
{
  return test_insert_range<C, Iter>( orig, first, last , (int)orig.size());
}

#endif // test_insert_H_


text:
module Station
  class NorskCountry < Format::HTML
    config do
      id "norskcountry"
      url "http://www.norskcountry.net/includes/playlist.php?show=current"
    end

    def process
      track = data.
        at_css("body").
        text.
        gsub(/Spilles nå:/, "").
        gsub(/\[\d+:\d+\].+$/, "")
      artist, song = split(track)
      { artist: artist, song: song }
    end
  end
end


text:
package cassandradb

import (
	"github.com/google/tsviewdb/src/db/dbcommon"
)

func (c *CassandraDB) DeleteRow(rowKey string) (err error) {
	writer := c.pool.Writer()
	return writer.
		Delete(dbcommon.CFAggregates, []byte(rowKey)).
		Delete(dbcommon.CFPoints, []byte(rowKey)).
		Delete(dbcommon.CFSource, []byte(rowKey)).
		Delete(dbcommon.CFConfigs, []byte(rowKey)).Run()
}


text:
local class = require("libs/middleclass/middleclass")

UI = class("UI")

function UI:initialize()
    self.font = love.graphics.newFont(72)
    self:update_presents_ui()

    self.r = 0

    self.ui_canvas = love.graphics.newCanvas(screen_width, screen_height)
end

function UI:draw()
    -- Rotate around the center of the screen
    love.graphics.setColor(255, 255, 255, 10)
    love.graphics.translate(screen_width/2, screen_height/2)
    love.graphics.rotate(self.r)
    love.graphics.translate(-screen_width/2, -screen_height/2)

    love.graphics.setFont(self.font)
    love.graphics.printf(self.present_text.text, 0, 10, screen_width, "center")

    love.graphics.rotate(0)
    love.graphics.translate(0, 0)
end

function UI:update(dt)
end

function UI:update_presents_ui(delivered)
    if not delivered then delivered = 0 end

    self.present_text = {
        text = delivered
    }

    self.sx = math.random(2, 2)
    self.sy = math.random(2, 2)

    self.r = math.random(-.7, .7)
end


text:
<?php

namespace Frontend\DocenteBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DocenteBundle extends Bundle
{
}


text:
This is watchdog which automatically restarts logmein-hamachi service
when for some reason connection to given VPN was lost.

Execute install.py under root to install it.
Specify your network id (numeric one, name doesn't count) in config file after installation.
Launch watchdog using:

``systemctl start hamachi-watchdog.timer``

Requires:
---------

* python3.4+
* systemd


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.prestosql.type;

import io.prestosql.Session;
import io.prestosql.operator.scalar.FunctionAssertions;
import io.prestosql.spi.type.SqlTimeWithTimeZone;
import io.prestosql.spi.type.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.testng.annotations.Test;

import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.google.common.base.Verify.verify;
import static io.prestosql.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static io.prestosql.spi.type.TimeZoneKey.getTimeZoneKey;
import static io.prestosql.spi.type.TimestampType.createTimestampType;
import static io.prestosql.testing.DateTimeTestingUtils.sqlTimestampOf;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static java.util.concurrent.TimeUnit.HOURS;

public class TestDateTimeOperatorsLegacy
        extends TestDateTimeOperatorsBase
{
    public TestDateTimeOperatorsLegacy()
    {
        super(true);
    }

    @Test
    public void testTimeZoneGap()
    {
        // Time zone gap should be applied

        assertFunction(
                "TIMESTAMP '2013-03-31 00:05' + INTERVAL '1' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 1, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-03-31 00:05' + INTERVAL '2' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 3, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-03-31 00:05' + INTERVAL '3' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 4, 5, 0, 0, session));

        assertFunction(
                "TIMESTAMP '2013-03-31 04:05' - INTERVAL '3' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 0, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-03-31 03:05' - INTERVAL '2' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 0, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-03-31 01:05' - INTERVAL '1' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 3, 31, 0, 5, 0, 0, session));
    }

    @Test
    public void testDaylightTimeSaving()
    {
        // See testDaylightTimeSavingSwitchCrossingIsNotApplied for new semantics
        assertFunction(
                "TIMESTAMP '2013-10-27 00:05' + INTERVAL '1' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 1, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-10-27 00:05' + INTERVAL '2' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 2, 5, 0, 0, session));
        // we need to manipulate millis directly here because 2 am has two representations in out time zone, and we need the second one
        assertFunction(
                "TIMESTAMP '2013-10-27 00:05' + INTERVAL '3' hour",
                createTimestampType(3),
                sqlTimestampOf(3, new DateTime(2013, 10, 27, 0, 5, 0, 0, DATE_TIME_ZONE).plus(HOURS.toMillis(3)), session));
        assertFunction(
                "TIMESTAMP '2013-10-27 00:05' + INTERVAL '4' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 3, 5, 0, 0, session));

        assertFunction(
                "TIMESTAMP '2013-10-27 03:05' - INTERVAL '4' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 0, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-10-27 02:05' - INTERVAL '2' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 0, 5, 0, 0, session));
        assertFunction(
                "TIMESTAMP '2013-10-27 01:05' - INTERVAL '1' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 0, 5, 0, 0, session));

        assertFunction(
                "TIMESTAMP '2013-10-27 03:05' - INTERVAL '1' hour",
                createTimestampType(3),
                sqlTimestampOf(3, new DateTime(2013, 10, 27, 0, 5, 0, 0, DATE_TIME_ZONE).plus(HOURS.toMillis(3)), session));
        assertFunction(
                "TIMESTAMP '2013-10-27 03:05' - INTERVAL '2' hour",
                createTimestampType(3),
                sqlTimestampOf(3, 2013, 10, 27, 2, 5, 0, 0, session));
    }

    @Test
    public void testTimeWithTimeZoneRepresentation()
    {
        // PST -> PDT date
        testTimeRepresentationOnDate(
                new DateTime(2017, 3, 12, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '02:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(37800000, getTimeZoneKey("America/Los_Angeles")));
        testTimeRepresentationOnDate(
                new DateTime(2017, 3, 12, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '03:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(41400000, getTimeZoneKey("America/Los_Angeles")));

        // PDT -> PST date
        testTimeRepresentationOnDate(
                new DateTime(2017, 10, 4, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '02:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(37800000, getTimeZoneKey("America/Los_Angeles")));
        testTimeRepresentationOnDate(
                new DateTime(2017, 10, 4, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '03:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(41400000, getTimeZoneKey("America/Los_Angeles")));

        // PDT date
        testTimeRepresentationOnDate(
                new DateTime(2017, 6, 6, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '02:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(37800000, getTimeZoneKey("America/Los_Angeles")));
        testTimeRepresentationOnDate(
                new DateTime(2017, 6, 6, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '03:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(41400000, getTimeZoneKey("America/Los_Angeles")));

        // PST date
        testTimeRepresentationOnDate(
                new DateTime(2017, 11, 1, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '02:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(37800000, getTimeZoneKey("America/Los_Angeles")));
        testTimeRepresentationOnDate(
                new DateTime(2017, 11, 1, 10, 0, 0, 0, DateTimeZone.UTC),
                "TIME '03:30:00.000 America/Los_Angeles'",
                TIME_WITH_TIME_ZONE,
                new SqlTimeWithTimeZone(41400000, getTimeZoneKey("America/Los_Angeles")));
    }

    private void testTimeRepresentationOnDate(DateTime date, String timeLiteral, Type expectedType, Object expected)
    {
        Session localSession = testSessionBuilder()
                .setTimeZoneKey(getTimeZoneKey("America/Los_Angeles"))
                .setStart(Instant.ofEpochMilli(date.getMillis()))
                .build();

        try (FunctionAssertions localAssertions = new FunctionAssertions(localSession)) {
            localAssertions.assertFunction(timeLiteral, expectedType, expected);
            localAssertions.assertFunctionString(timeLiteral, expectedType, valueFromLiteral(timeLiteral));
        }
    }

    private String valueFromLiteral(String literal)
    {
        Pattern p = Pattern.compile("'(.*)'");
        Matcher m = p.matcher(literal);
        verify(m.find());
        return m.group(1);
    }
}


text:
```
git svn clone https://oneleo-code.au-sdc.com/svn/platform-assets/poc/wag-ue-poc/ ue-showcase --trunk=trunk/ue-showcase --branches=branches --tags=tags --prefix=svn/
```

## Checkout last revision

get list of revisions
```
svn log --stop-on-copy https://oneleo-code.au-sdc.com/svn/platform-assets/poc/wag-ue-poc/trunk/ue-showcase

------------------------------------------------------------------------
r9855 | bsorrentino | 2016-03-22 12:13:10 +0100 (Tue, 22 Mar 2016) | 1 line

update from origin
```
Pick up the revision on first row, in the example r9855, and run commnand

```
git svn clone -r<revision number> https://oneleo-code.au-sdc.com/svn/platform-assets/poc/wag-ue-poc/ ue-showcase --trunk=trunk/ue-showcase --branches=branches --tags=tags --prefix=svn/
```

## Pull from SVN

```
git svn rebase
```

## Push to SVN

```
git svn dcommit
```

## Download new revisions from SVN

```
git svn fetch [--fetch-all]
```

## Create a svn branches

```
git svn branch <branch name>
```

## Create a svn tag

```
git svn branch --tag <tag name>
```

## Checkout a svn branch

```
git checkout -b <local branch name> svn/<svn branch name>
```


text:
DEFINE_int32(file_cache_expiry_period_ms, 60 * 1000,
             "Period of time (in ms) between removing expired file cache descriptors");
TAG_FLAG(file_cache_expiry_period_ms, advanced);

using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;

namespace kudu {

namespace {

template <class FileType>
FileType* CacheValueToFileType(Slice s) {
  return reinterpret_cast<FileType*>(*reinterpret_cast<void**>(
      s.mutable_data()));
}

template <class FileType>
class EvictionCallback : public Cache::EvictionCallback {
 public:
  EvictionCallback() {}

  void EvictedEntry(Slice key, Slice value) override {
    VLOG(2) << "Evicted fd belonging to " << key.ToString();
    delete CacheValueToFileType<FileType>(value);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(EvictionCallback);
};

} // anonymous namespace

namespace internal {

template <class FileType>
class ScopedOpenedDescriptor;

// Encapsulates common descriptor fields and methods.
template <class FileType>
class BaseDescriptor {
 public:
  BaseDescriptor(FileCache<FileType>* file_cache,
                 string filename)
      : file_cache_(file_cache),
        file_name_(std::move(filename)) {}

  ~BaseDescriptor() {
    VLOG(2) << "Out of scope descriptor with file name: " << filename();

    // The (now expired) weak_ptr remains in 'descriptors_', to be removed by
    // the next call to RunDescriptorExpiry(). Removing it here would risk a
    // deadlock on recursive acquisition of 'lock_'.

    if (deleted()) {
      cache()->Erase(filename());

      VLOG(1) << "Deleting file: " << filename();
      WARN_NOT_OK(env()->DeleteFile(filename()), "");
    }
  }

  // Insert a pointer to an open file object into the file cache with the
  // filename as the cache key.
  //
  // Returns a handle to the inserted entry. The handle always contains an open
  // file.
  ScopedOpenedDescriptor<FileType> InsertIntoCache(void* file_ptr) const {
    // The allocated charge is always one byte. This is incorrect with respect
    // to memory tracking, but it's necessary if the cache capacity is to be
    // equivalent to the max number of fds.
    Cache::PendingHandle* pending = CHECK_NOTNULL(cache()->Allocate(
        filename(), sizeof(file_ptr), 1));
    memcpy(cache()->MutableValue(pending),
           &file_ptr,
           sizeof(file_ptr));
    return ScopedOpenedDescriptor<FileType>(this, Cache::UniqueHandle(
        cache()->Insert(pending, file_cache_->eviction_cb_.get()),
        Cache::HandleDeleter(cache())));
  }

  // Retrieves a pointer to an open file object from the file cache with the
  // filename as the cache key.
  //
  // Returns a handle to the looked up entry. The handle may or may not contain
  // an open file, depending on whether the cache hit or missed.
  ScopedOpenedDescriptor<FileType> LookupFromCache() const {
    return ScopedOpenedDescriptor<FileType>(this, Cache::UniqueHandle(
        cache()->Lookup(filename(), Cache::EXPECT_IN_CACHE),
        Cache::HandleDeleter(cache())));
  }

  // Mark this descriptor as to-be-deleted later.
  void MarkDeleted() {
    DCHECK(!deleted());
    while (true) {
      auto v = flags_.load();
      if (flags_.compare_exchange_weak(v, v | FILE_DELETED)) return;
    }
  }

  // Mark this descriptor as invalidated. No further access is allowed
  // to this file.
  void MarkInvalidated() {
    DCHECK(!invalidated());
    while (true) {
      auto v = flags_.load();
      if (flags_.compare_exchange_weak(v, v | INVALIDATED)) return;
    }
  }

  Cache* cache() const { return file_cache_->cache_.get(); }

  Env* env() const { return file_cache_->env_; }

  const string& filename() const { return file_name_; }

  bool deleted() const { return flags_.load() & FILE_DELETED; }
  bool invalidated() const { return flags_.load() & INVALIDATED; }

 private:
  FileCache<FileType>* file_cache_;
  const string file_name_;
  enum Flags {
    FILE_DELETED = 1 << 0,
    INVALIDATED = 1 << 1
  };
  std::atomic<uint8_t> flags_ {0};

  DISALLOW_COPY_AND_ASSIGN(BaseDescriptor);
};

// A "smart" retrieved LRU cache handle.
//
// The cache handle is released when this object goes out of scope, possibly
// closing the opened file if it is no longer in the cache.
template <class FileType>
class ScopedOpenedDescriptor {
 public:
  // A not-yet-but-soon-to-be opened descriptor.
  explicit ScopedOpenedDescriptor(const BaseDescriptor<FileType>* desc)
      : desc_(desc),
        handle_(nullptr, Cache::HandleDeleter(desc_->cache())) {
  }

  // An opened descriptor. Its handle may or may not contain an open file.
  ScopedOpenedDescriptor(const BaseDescriptor<FileType>* desc,
                         Cache::UniqueHandle handle)
      : desc_(desc),
        handle_(std::move(handle)) {
  }

  bool opened() const { return handle_.get(); }

  FileType* file() const {
    DCHECK(opened());
    return CacheValueToFileType<FileType>(desc_->cache()->Value(handle_.get()));
  }

 private:
  const BaseDescriptor<FileType>* desc_;
  Cache::UniqueHandle handle_;
};

// Reference to an on-disk file that may or may not be opened (and thus
// cached) in the file cache.
//
// This empty template is just a specification; actual descriptor classes must
// be fully specialized.
template <class FileType>
class Descriptor : public FileType {
};

// A descriptor adhering to the RWFile interface (i.e. when opened, provides
// a read-write interface to the underlying file).
template <>
class Descriptor<RWFile> : public RWFile {
 public:
  Descriptor(FileCache<RWFile>* file_cache, const string& filename)
      : base_(file_cache, filename) {}

  ~Descriptor() = default;

  Status Read(uint64_t offset, Slice result) const override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Read(offset, result);
  }

  Status ReadV(uint64_t offset, ArrayView<Slice> results) const override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->ReadV(offset, results);
  }

  Status Write(uint64_t offset, const Slice& data) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Write(offset, data);
  }

  Status WriteV(uint64_t offset, ArrayView<const Slice> data) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->WriteV(offset, data);
  }

  Status PreAllocate(uint64_t offset, size_t length, PreAllocateMode mode) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->PreAllocate(offset, length, mode);
  }

  Status Truncate(uint64_t length) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Truncate(length);
  }

  Status PunchHole(uint64_t offset, size_t length) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->PunchHole(offset, length);
  }

  Status Flush(FlushMode mode, uint64_t offset, size_t length) override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Flush(mode, offset, length);
  }

  Status Sync() override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Sync();
  }

  Status Close() override {
    // Intentional no-op; actual closing is deferred to LRU cache eviction.
    return Status::OK();
  }

  Status Size(uint64_t* size) const override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Size(size);
  }

  Status GetExtentMap(ExtentMap* out) const override {
    ScopedOpenedDescriptor<RWFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->GetExtentMap(out);
  }

  const string& filename() const override {
    return base_.filename();
  }

 private:
  friend class FileCache<RWFile>;

  Status Init() {
    return once_.Init(&Descriptor<RWFile>::InitOnce, this);
  }

  Status InitOnce() {
    return ReopenFileIfNecessary(nullptr);
  }

  Status ReopenFileIfNecessary(ScopedOpenedDescriptor<RWFile>* out) const {
    ScopedOpenedDescriptor<RWFile> found(base_.LookupFromCache());
    CHECK(!base_.invalidated());
    if (found.opened()) {
      // The file is already open in the cache, return it.
      if (out) {
        *out = std::move(found);
      }
      return Status::OK();
    }

    // The file was evicted, reopen it.
    //
    // Because the file may be evicted at any time we must use 'sync_on_close'
    // (note: sync is a no-op if the file isn't dirty).
    RWFileOptions opts;
    opts.sync_on_close = true;
    opts.mode = Env::OPEN_EXISTING;
    unique_ptr<RWFile> f;
    RETURN_NOT_OK(base_.env()->NewRWFile(opts, base_.filename(), &f));

    // The cache will take ownership of the newly opened file.
    ScopedOpenedDescriptor<RWFile> opened(base_.InsertIntoCache(f.release()));
    if (out) {
      *out = std::move(opened);
    }
    return Status::OK();
  }

  BaseDescriptor<RWFile> base_;
  KuduOnceDynamic once_;

  DISALLOW_COPY_AND_ASSIGN(Descriptor);
};

// A descriptor adhering to the RandomAccessFile interface (i.e. when opened,
// provides a read-only interface to the underlying file).
template <>
class Descriptor<RandomAccessFile> : public RandomAccessFile {
 public:
  Descriptor(FileCache<RandomAccessFile>* file_cache, const string& filename)
      : base_(file_cache, filename) {}

  ~Descriptor() = default;

  Status Read(uint64_t offset, Slice result) const override {
    ScopedOpenedDescriptor<RandomAccessFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Read(offset, result);
  }

  Status ReadV(uint64_t offset, ArrayView<Slice> results) const override {
    ScopedOpenedDescriptor<RandomAccessFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->ReadV(offset, results);
  }

  Status Size(uint64_t *size) const override {
    ScopedOpenedDescriptor<RandomAccessFile> opened(&base_);
    RETURN_NOT_OK(ReopenFileIfNecessary(&opened));
    return opened.file()->Size(size);
  }

  const string& filename() const override {
    return base_.filename();
  }

  size_t memory_footprint() const override {
    // Normally we would use kudu_malloc_usable_size(this). However, that's
    // not safe because 'this' was allocated via std::make_shared(), which
    // means it isn't necessarily the base of the memory allocation; it may be
    // preceded by the shared_ptr control block.
    //
    // It doesn't appear possible to get the base of the allocation via any
    // shared_ptr APIs, so we'll use sizeof(*this) + 16 instead. The 16 bytes
    // represent the shared_ptr control block. Overall the object size is still
    // undercounted as it doesn't account for any internal heap fragmentation,
    // but at least it's safe.
    //
    // Some anecdotal memory measurements taken inside gdb:
    // - glibc 2.23 malloc_usable_size() on make_shared<FileType>: 88 bytes.
    // - tcmalloc malloc_usable_size() on make_shared<FileType>: 96 bytes.
    // - sizeof(std::_Sp_counted_base<>) with libstdc++ 5.4: 16 bytes.
    // - sizeof(std::__1::__shared_ptr_emplace<>) with libc++ 3.9: 16 bytes.
    // - sizeof(*this): 72 bytes.
    return sizeof(*this) +
        16 + // shared_ptr control block
        once_.memory_footprint_excluding_this() +
        base_.filename().capacity();
  }

 private:
  friend class FileCache<RandomAccessFile>;

  Status Init() {
    return once_.Init(&Descriptor<RandomAccessFile>::InitOnce, this);
  }

  Status InitOnce() {
    return ReopenFileIfNecessary(nullptr);
  }

  Status ReopenFileIfNecessary(
      ScopedOpenedDescriptor<RandomAccessFile>* out) const {
    ScopedOpenedDescriptor<RandomAccessFile> found(base_.LookupFromCache());
    CHECK(!base_.invalidated());
    if (found.opened()) {
      // The file is already open in the cache, return it.
      if (out) {
        *out = std::move(found);
      }
      return Status::OK();
    }

    // The file was evicted, reopen it.
    unique_ptr<RandomAccessFile> f;
    RETURN_NOT_OK(base_.env()->NewRandomAccessFile(base_.filename(), &f));

    // The cache will take ownership of the newly opened file.
    ScopedOpenedDescriptor<RandomAccessFile> opened(
        base_.InsertIntoCache(f.release()));
    if (out) {
      *out = std::move(opened);
    }
    return Status::OK();
  }

  BaseDescriptor<RandomAccessFile> base_;
  KuduOnceDynamic once_;

  DISALLOW_COPY_AND_ASSIGN(Descriptor);
};

} // namespace internal

template <class FileType>
FileCache<FileType>::FileCache(const string& cache_name,
                               Env* env,
                               int max_open_files,
                               const scoped_refptr<MetricEntity>& entity)
    : env_(env),
      cache_name_(cache_name),
      eviction_cb_(new EvictionCallback<FileType>()),
      cache_(NewLRUCache(DRAM_CACHE, max_open_files, cache_name)),
      running_(1) {
  if (entity) {
    cache_->SetMetrics(entity);
  }
  LOG(INFO) << Substitute("Constructed file cache $0 with capacity $1",
                          cache_name, max_open_files);
}

template <class FileType>
FileCache<FileType>::~FileCache() {
  running_.CountDown();
  if (descriptor_expiry_thread_) {
    descriptor_expiry_thread_->Join();
  }
}

template <class FileType>
Status FileCache<FileType>::Init() {
  return Thread::Create("cache", Substitute("$0-evict", cache_name_),
                        &FileCache::RunDescriptorExpiry, this,
                        &descriptor_expiry_thread_);
}

template <class FileType>
Status FileCache<FileType>::OpenExistingFile(const string& file_name,
                                             shared_ptr<FileType>* file) {
  shared_ptr<internal::Descriptor<FileType>> desc;
  {
    // Find an existing descriptor, or create one if none exists.
    std::lock_guard<simple_spinlock> l(lock_);
    RETURN_NOT_OK(FindDescriptorUnlocked(file_name, &desc));
    if (desc) {
      VLOG(2) << "Found existing descriptor: " << desc->filename();
    } else {
      desc = std::make_shared<internal::Descriptor<FileType>>(this, file_name);
      InsertOrDie(&descriptors_, file_name, desc);
      VLOG(2) << "Created new descriptor: " << desc->filename();
    }
  }

  // Check that the underlying file can be opened (no-op for found
  // descriptors). Done outside the lock.
  RETURN_NOT_OK(desc->Init());
  *file = std::move(desc);
  return Status::OK();
}

template <class FileType>
Status FileCache<FileType>::DeleteFile(const string& file_name) {
  {
    std::lock_guard<simple_spinlock> l(lock_);
    shared_ptr<internal::Descriptor<FileType>> desc;
    RETURN_NOT_OK(FindDescriptorUnlocked(file_name, &desc));

    if (desc) {
      VLOG(2) << "Marking file for deletion: " << file_name;
      desc->base_.MarkDeleted();
      return Status::OK();
    }
  }

  // There is no outstanding descriptor. Delete the file now.
  //
  // Make sure it's been fully evicted from the cache (perhaps it was opened
  // previously?) so that the filesystem can reclaim the file data instantly.
  cache_->Erase(file_name);
  return env_->DeleteFile(file_name);
}

template <class FileType>
void FileCache<FileType>::Invalidate(const string& file_name) {
  // Ensure that there is an invalidated descriptor in the map for this filename.
  //
  // This ensures that any concurrent OpenExistingFile() during this method wil
  // see the invalidation and issue a CHECK failure.
  shared_ptr<internal::Descriptor<FileType>> desc;
  {
    // Find an existing descriptor, or create one if none exists.
    std::lock_guard<simple_spinlock> l(lock_);
    auto it = descriptors_.find(file_name);
    if (it != descriptors_.end()) {
      desc = it->second.lock();
    }
    if (!desc) {
      desc = std::make_shared<internal::Descriptor<FileType>>(this, file_name);
      descriptors_.emplace(file_name, desc);
    }

    desc->base_.MarkInvalidated();
  }
  // Remove it from the cache so that if the same path is opened again, we
  // will re-open a new FD rather than retrieving one that might have been
  // cached prior to invalidation.
  cache_->Erase(file_name);

  // Remove the invalidated descriptor from the map. We are guaranteed it
  // is still there because we've held a strong reference to it for
  // the duration of this method, and no other methods erase strong
  // references from the map.
  {
    std::lock_guard<simple_spinlock> l(lock_);
    CHECK_EQ(1, descriptors_.erase(file_name));
  }
}

template <class FileType>
int FileCache<FileType>::NumDescriptorsForTests() const {
  std::lock_guard<simple_spinlock> l(lock_);
  return descriptors_.size();
}

template <class FileType>
string FileCache<FileType>::ToDebugString() const {
  std::lock_guard<simple_spinlock> l(lock_);
  string ret;
  for (const auto& e : descriptors_) {
    bool strong = false;
    bool deleted = false;
    bool opened = false;
    shared_ptr<internal::Descriptor<FileType>> desc = e.second.lock();
    if (desc) {
      strong = true;
      if (desc->base_.deleted()) {
        deleted = true;
      }
      internal::ScopedOpenedDescriptor<FileType> o(
          desc->base_.LookupFromCache());
      if (o.opened()) {
        opened = true;
      }
    }
    if (strong) {
      ret += Substitute("$0 (S$1$2)\n", e.first,
                        deleted ? "D" : "", opened ? "O" : "");
    } else {
      ret += Substitute("$0\n", e.first);
    }
  }
  return ret;
}

template <class FileType>
Status FileCache<FileType>::FindDescriptorUnlocked(
    const string& file_name,
    shared_ptr<internal::Descriptor<FileType>>* file) {
  DCHECK(lock_.is_locked());

  auto it = descriptors_.find(file_name);
  if (it != descriptors_.end()) {
    // Found the descriptor. Has it expired?
    shared_ptr<internal::Descriptor<FileType>> desc = it->second.lock();
    if (desc) {
      CHECK(!desc->base_.invalidated());
      if (desc->base_.deleted()) {
        return Status::NotFound("File already marked for deletion", file_name);
      }

      // Descriptor is still valid, return it.
      if (file) {
        *file = desc;
      }
      return Status::OK();
    }
    // Descriptor has expired; erase it and pretend we found nothing.
    descriptors_.erase(it);
  }
  return Status::OK();
}

template <class FileType>
void FileCache<FileType>::RunDescriptorExpiry() {
  while (!running_.WaitFor(MonoDelta::FromMilliseconds(
      FLAGS_file_cache_expiry_period_ms))) {
    std::lock_guard<simple_spinlock> l(lock_);
    for (auto it = descriptors_.begin(); it != descriptors_.end();) {
      if (it->second.expired()) {
        it = descriptors_.erase(it);
      } else {
        it++;
      }
    }
  }
}

// Explicit specialization for callers outside this compilation unit.
template class FileCache<RWFile>;
template class FileCache<RandomAccessFile>;

} // namespace kudu


text:
package com.narvis.dataaccess.interfaces.dataproviders;

import com.narvis.dataaccess.exception.IllegalKeywordException;
import com.narvis.dataaccess.exception.NoDataException;

/*
 * @author Yoann LE MOUËL & Alban BONNET & Charles COQUE & Raphaël BLIN
 */
public interface IDataProvider {

    public String getData(String... keywords) throws NoDataException, IllegalKeywordException;

}


text:
app.views.Base = Backbone.View.extend({

});


text:
using System;
using NUnit.Framework;

[TestFixture]
public class ExcelToNumberTests {

    [Test]
    public void Test1() {
        Console.WriteLine("****** Basic Tests");
        Assert.AreEqual(1, ExcelToNumber.TitleToNumber("A"));
        Assert.AreEqual(27, ExcelToNumber.TitleToNumber("AA"));
        Assert.AreEqual(52, ExcelToNumber.TitleToNumber("AZ"));
        Assert.AreEqual(53, ExcelToNumber.TitleToNumber("BA"));
        Assert.AreEqual(28779382963L, ExcelToNumber.TitleToNumber("CODEWARS"));
    }
}


text:
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;

/// Window class responsible for human IO and graphics display

/**
 * A window class that displays the game and is responsible for performing human
 * IO if necessary.  You should not need to worry about the contents of this
 * class, as none of the methods contained here will be necessary for developing
 * an AI player.
 *
 * @author Leonid Shamis
 */
public final class Display extends javax.swing.JPanel implements IOModule, MouseListener, MouseMotionListener
{
    /// Subclass to synchronize human player actions.
    /**
     * This class is used to implement the human moves.  It relies on a bit of
     * threading hacking and should not be modified as minor changes can break
     * the human input functions.
     */
    private static final class HumanBlocker
    {
        /// Semaphore used for thread blocking.
        private final Semaphore readySignal = new Semaphore(0);

        /// Move chosen by human player.
        private volatile int result;

        /// Flag indicating whether or not the human player has chosen a move.
        private volatile boolean moveRetrieved = false;

        /// Sets what the player's move was, then unblocks the thread so it it will complete.
        /**
         * Sets what the player's move was, then unblocks the thread so it it will complete.
         * @param move The move to record.
         */
        public void setMove(int move)
        {
            result = move;
            readySignal.release();
        }

        /// Request a move selection from active human player.
        /**
         * Blocks until the human has chosen a move, then returns that move.  Calling this
         * function more than once per HumanBlocker will cause an IllegalStateException.
         *
         * @return The move chosen by the human.
         */
        public int getMove()
        {
            // Set that we've retrieved the move.
            synchronized(this)
            {
                if(moveRetrieved)
                {
                    throw new IllegalStateException("Already retrieved stored move!");
                }
                moveRetrieved = true;
            }

            // Wait for the move to be ready
            try
            {
                readySignal.acquire();
            }
            catch(InterruptedException iex)
            {
                throw new RuntimeException("Interrupted a thread... this shouldn't be possible");
            }

            return result;
        }
    }

    /// Colors used in the display.
    private static final Color [] coinColors = new Color[]{Color.WHITE, Color.RED, Color.YELLOW};
    /// Human interaction blocker, to be set on human action request.
    private volatile HumanBlocker currentBlocker = null;
    /// Active game being displayed.
    private GameStateModule game;
    /// Column over which the mouse is located.
    private int MouseX;

    /// Default constructor.
    public Display()
    {
        setBackground(Color.GRAY);
        addMouseListener(this);
        addMouseMotionListener(this);
        setPreferredSize(new Dimension(500, 450));
    }

    /// Set up request for human player chosen move.
    public int getHumanMove()
    {
        final HumanBlocker ourBlocker = new HumanBlocker();
        currentBlocker = ourBlocker;
        this.repaint();
        return ourBlocker.getMove();
    }

    /// Set up pretty anti-aliased graphics.
    private Graphics2D setup2DGraphics(final Graphics g)
    {
        final Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        return g2d;
    }

    /// Draw the active game board.
    private void drawBoard(final Graphics2D g2d)
    {
        // Get panel dimentions
        final int width = this.getWidth();
        final int height = this.getHeight();

        // Dimentions of the circles for a game.getWidth()xgame.getWidth() grid
        final double circleWidth = ((double) width) / game.getWidth();
        final double circleHeight = ((double) height) / (1 + game.getHeight());

        // Reduce the dimentions to prevent overlaps
        final int cW = (int) (circleWidth) - 2;
        final int cH = (int) (circleHeight) - 2;

        // for each column
        for(int x = 0; x < game.getWidth(); x++)
        {
            //for each row
            for(int y = 1; y <= game.getHeight(); y++)
            {
                // Location of the current circle
                final int cX = (int) (x * circleWidth) + 1;
                final int cY = (int) (y * circleHeight) + 1;

                // Choose the appropriate color
                g2d.setColor(coinColors[game.getAt(x, game.getHeight() - y)]);

                // Draw circle
                g2d.fillOval(cX, cY, cW, cH);
            }
        }
    }

    /// Outlines all pieces to make it look nicer.
    private void drawOutlines(final Graphics2D g2d)
    {
        // Setup the brush
        g2d.setStroke(new BasicStroke(2));
        g2d.setColor(Color.BLACK);

        // Get panel dimentions
        final int width = this.getWidth();
        final int height = this.getHeight();

        // Dimentions of the circles for a game.getWidth()xgame.getWidth() grid
        final double circleWidth = ((double) width) / game.getWidth();
        final double circleHeight = ((double) height) / (1 + game.getHeight());

        // Reduce the dimentions to prevent overlaps
        final int cW = (int) (circleWidth) - 2;
        final int cH = (int) (circleHeight) - 2;

        // for each column
        for(int x = 0; x < game.getWidth(); x++)
        {
            // for each row
            for(int y = 1; y <= game.getHeight(); y++)
            {
                // Location of the current circle
                final int cX = (int) (x * circleWidth) + 1;
                final int cY = (int) (y * circleHeight) + 1;

                // Outline circle
                g2d.drawOval(cX, cY, cW, cH);
            }
        }

        // Draw a line between the move selector and the board
        g2d.setStroke(new BasicStroke(3));
        g2d.drawLine(-1, cH - 2, width + 1, cH - 2);
    }

    /// Draw the human player move selector.
    private void drawMove(final Graphics2D g2d)
    {
        // Get dimentions
        final int width = this.getWidth();
        final int height = this.getHeight();

        final double circleWidth = ((double) width) / game.getWidth();
        final double circleHeight = ((double) height) / (1 + game.getHeight());

        final int cX = (int) (MouseX * circleWidth) + game.getHeight();
        final int cY = 1;
        final int cW = (int) (circleWidth) - 12;
        final int cH = (int) (circleHeight) - 12;

        // Get color
        g2d.setColor(coinColors[game.getActivePlayer()]);

        // Draw and outline move
        g2d.fillOval(cX, cY, cW, cH);

        g2d.setStroke(new BasicStroke(2));
        g2d.setColor(Color.BLACK);
        g2d.drawOval(cX, cY, cW, cH);
    }

    /// If a player has won draw a line connecting the four checkers.
    private void drawVictory(final Graphics2D g2d, final Point start, final Point end)
    {
        // Get panel dimentions
        final int width = this.getWidth();
        final int height = this.getHeight();

        // Dimentions of the circles for a game.getWidth()xgame.getWidth() grid
        final double circleWidth = ((double) width) / game.getWidth();
        final double circleHeight = ((double) height) / (1 + game.getHeight());

        // Get the first victory tile
        final int startX = (int) (start.x * circleWidth) + 1 + (int) (circleWidth / 2);
        final int startY = (int) ((game.getHeight() - start.y) * circleHeight) + 1 + (int) (circleHeight / 2);

        // Get the last victory tile
        final int endX = (int) (end.x * circleWidth) + 1 + (int) (circleWidth / 2);
        final int endY = (int) ((game.getHeight() - end.y) * circleHeight) + 1 + (int) (circleHeight / 2);

        // Draw a line through the victory tiles
        g2d.setColor(Color.BLACK);
        g2d.setStroke(new BasicStroke(10, BasicStroke.CAP_ROUND, 0));
        g2d.drawLine(startX, startY, endX, endY);

        g2d.setColor(Color.WHITE);
        g2d.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
        g2d.drawLine(startX, startY, endX, endY);
    }

    /// Instructions for repainting the panel.
    @Override
    public void paintComponent(final Graphics g)
    {
        super.paintComponent(g);

        if(game == null)
            return;

        final Graphics2D g2d = setup2DGraphics(g);
        drawBoard(g2d);
        drawOutlines(g2d);
        // Draw move selector if there is a request for it
        if(currentBlocker != null)
        {
            drawMove(g2d);
        }
        if(game.isGameOver() && game.getWinner() != 0)
        {
            drawVictory(g2d, game.getStartPt(), game.getEndPt());
        }
    }

    /// Calls for repaint
    public void drawBoard(final GameStateModule game)
    {
        this.game = game;
        repaint();
    }

    /// Empty.
    public void mousePressed(MouseEvent e)
    {
    }

    /// Gets selected move from the active human player if it was requested.
    public void mouseReleased(MouseEvent e)
    {
        // Update mouse position
        MouseX = game.getWidth() * e.getX() / this.getWidth();

        // If this isn't a legal move, abort.
        if(!game.canMakeMove(MouseX)) return;

        // Ignore if there is no request
        if(currentBlocker == null)
        {
            return;
        }

        // Releases the blocker.  DO NOT REORDER THESE LINES!
        final HumanBlocker current = currentBlocker;
        currentBlocker = null;

        // Report Selection
        current.setMove(MouseX);
        // Update graphics
        this.repaint();
    }

    /// Empty.
    public void mouseEntered(MouseEvent e)
    {
    }

    /// Empty.
    public void mouseExited(MouseEvent e)
    {
    }

    /// Empty.
    public void mouseClicked(MouseEvent e)
    {
    }

    /// Updates mouse position if the mouse has moved.
    public void mouseMoved(MouseEvent e)
    {
        MouseX = game.getWidth() * e.getX() / this.getWidth();
        this.repaint();
    }

    /// Updates mouse position if the mouse has moved.
    public void mouseDragged(MouseEvent e)
    {
        MouseX = game.getWidth() * e.getX() / this.getWidth();
        this.repaint();
    }
}


text:
package de.schub.marathon_scaler.Monitoring.Strategy;

import de.schub.marathon_scaler.AppStatistics;
import mesosphere.marathon.client.model.v2.App;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Dynamically scale a app verticalle (adds 50% more resources)
 * Configuration via marathon labels in the app configuration:
 *
 * ```json
 * "labels": {
 *    "scaling": "vertical"
 * }
 * ```
 *
 *  Will scale up if CPU usage is > 90% or memory usage is > 90%.
 */
public class Vertical implements ScalingStrategy
{
    public final static String NAME = "vertical";

    Logger logger = LoggerFactory.getLogger(Vertical.class);

    @Override
    public void scale(App app, AppStatistics statistics)
    {
        // current cpu greater 90 percent
        if (statistics.getCpu().orElse(0F) > 0.9) {
            app.setCpus(app.getCpus() * 1.5);
            logger.info(
                "scaling app {} to {} cpus due to cpu usage ({})",
                app.getId(),
                app.getCpus(),
                statistics.getCpu().get() * 100
            );
        }

        // current memory consumption is greater than 90 percent of max
        if (statistics.getMemoryInMegabytes() > app.getMem() * 0.9) {
            Double oldMem = app.getMem();
            app.setMem(oldMem * 1.5);
            logger.info(
                "scaling app {} to {} Memory due to memory usage ({} MB/{} MB)",
                app.getId(),
                app.getMem(),
                statistics.getMemoryInMegabytes(),
                oldMem
            );
        }
    }

    @Override
    public long getStatisticsInterval()
    {
        // last 10 minutes
        return 60 * 10;
    }
}


text:
.cssClass .kwfFieldError label { color: var(typo); }
.cssClass .kwfFieldError input,
.cssClass .kwfFieldError textarea {
    color: var(typo);
    border-color: var(errorBorder) ;
}

.cssClass button {
    cursor: pointer;
}

.cssClass form .kwfField label,
.cssClass form .kwfField span.fieldContent {
    line-height: 20px;
}
.cssClass .submitWrapper {
    text-align: center;
    clear: both;
}
.cssClass .submitWrapper .beforeButton,
.cssClass .submitWrapper .button,
.cssClass .submitWrapper .saving,
.cssClass .submitWrapper .afterButton {
    float: left;
}
.cssClass .submitWrapper .button {
    position: relative;
}
.cssClass .submitWrapper .saving {
    width: 24px;
    height: 24px;
    background-image: url(/assets/kwf/Kwc/Form/loading.gif);
    visibility: hidden;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -12px;
    margin-left: -12px;
}

.cssClass input,
.cssClass textarea,
.cssClass select {
    padding: 2px;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
    color: var(typo);
    line-height: 18px;
    outline: none;
    float: left;
}

.cssClass input.radio {
    margin-left: 10px;
    border: none;
    background: none;
}
.cssClass form .kwfFormFieldCheckbox input {
    width: auto;
    border: none;
    background: none;
    margin-top: 3px;
}
.cssClass label {
    line-height: 18px;
}
.cssClass .kwcLabelPositionAbove .kwfFormFieldWrapper.hasLabel {
    margin-left: 0;
    padding-left: 0;
}
.cssClass .kwfFieldRequired label { font-weight: normal; }
.cssClass .kwfFieldRequired span label { font-weight: normal; }
.cssClass .kwfFieldLabelAlignTop label {
    width: auto;
    margin: 0px;
    text-align: left;
}
.cssClass .kwfFieldLabelAlignLeft label {
    text-align: left;
}
.cssClass .showField {
    font-weight: bold;
    margin-bottom: 9px;
}
.cssClass fieldset {
    margin-bottom: 20px;
    padding: 10px;
}
.cssClass fieldset legend {
    font-weight: bold;
    margin-left: 20px;
    padding: 5px;
}
.cssClass form .kwfFormFieldRadio .kwfFormFieldWrapper label {
    margin-right: 20px;
    clear: none;
}
.cssClass form .kwfFormFieldRadio input { margin: 0px; padding: 0px; }
.cssClass form .kwfFormFieldRadioHorizontal span { display: inline-block; }
.cssClass form .kwfFormFieldRadioVertical span { display: block; }
.cssClass form .kwfFormFieldRadioVertical span label { margin-left: 0px; }
.cssClass form .kwfFormFieldRadioVertical label { float: none; }

.cssClass form .kwfFormFieldMultiCheckboxHorizontal label { float: none; width: auto; margin-left: 0px; }
.cssClass form .kwfFormFieldMultiCheckboxHorizontal .checkboxItem { float: left; white-space: nowrap; padding-right: 10px; }
.cssClass form .kwfFormFieldMultiCheckboxHorizontal .checkboxItem label { font-weight: normal; }

.cssClass form .kwfFormContainerColumns .kwfFormContainerColumn { float: left; clear: none; }
.cssClass form .kwfFormContainerColumns .kwfFormContainerColumn .kwfField { clear: none; }

.cssClass span.comment { margin-left: 10px; color: #999; }
.cssClass .kwfField { clear: both; position: relative; margin-bottom: 4px; }

.cssClass .kwcLabelPositionAbove label {
    display: block;
    float: none;
    margin-left: 0px;
    text-align: left;
    width: 100%;
}


text:
@interface DownloadUrlToDiskOperation : NSOperation {
  NSError*  error_;

  // In concurrent operations, we have to manage the operation's state
  BOOL executing_;
  BOOL finished_;

  // The actual NSURLConnection management
  NSURL*    connectionURL_;
  NSURLConnection*  connection_;

  // To save to disk
  NSString *filePath;
  NSOutputStream *stream;
   long long contentlength;
    long downloaded_data;
}
@property (nonatomic,readonly) NSError* error;

@property(nonatomic, readonly) NSURL *connectionURL;
@property(nonatomic, retain) NSString *filePath;

-(id)initWithUrl:(NSURL *)aUrl saveToFilePath:(NSString *)aFilePath;

@end


text:
import Types
import Delaunay

import qualified Data.Array.Parallel.Unlifted as U
import qualified Data.Array.Parallel.Prelude  as P
import qualified Data.Array.Parallel.PArray as PA

import SVG

import System.Environment
import System.IO

main = do
         [arg] <- getArgs
         h <- openBinaryFile arg ReadMode
         pts <- U.hGet h
         let points = P.fromUArrPA_2' pts
             edges  = PA.toList (delaunayPoints points)
         putStrLn $ svg (PA.toList points) edges


text:
set HS_SCRIPTS=%code%\hotspotter\hs_scripts

:: Build using win32 script
cd %code%\flann
call build_flann_mingw.bat

cd %code%\opencv
call build_opencv_mingw.bat

cd %code%\hesaff
call build_hessaff_mingw.bat

:: Install opencv and flann
cd %code%\flann
make install
cd %code%\opencv
make install

color
cd %HS_SCRIPTS%