text:
package org.elasticsearch.search.facet.histogram.unbounded;

import org.apache.lucene.index.IndexReader;
import org.elasticsearch.common.CacheRecycler;
import org.elasticsearch.common.trove.ExtTLongObjectHashMap;
import org.elasticsearch.index.cache.field.data.FieldDataCache;
import org.elasticsearch.index.field.data.FieldDataType;
import org.elasticsearch.index.field.data.NumericFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.search.facet.AbstractFacetCollector;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.FacetPhaseExecutionException;
import org.elasticsearch.search.facet.histogram.HistogramFacet;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;

/**
 * A histogram facet collector that uses the same field as the key as well as the
 * value.
 */
public class FullHistogramFacetCollector extends AbstractFacetCollector {

    private final String indexFieldName;

    private final HistogramFacet.ComparatorType comparatorType;

    private final FieldDataCache fieldDataCache;

    private final FieldDataType fieldDataType;

    private NumericFieldData fieldData;

    private final HistogramProc histoProc;

    public FullHistogramFacetCollector(String facetName, String fieldName, long interval, HistogramFacet.ComparatorType comparatorType, SearchContext context) {
        super(facetName);
        this.comparatorType = comparatorType;
        this.fieldDataCache = context.fieldDataCache();

        MapperService.SmartNameFieldMappers smartMappers = context.smartFieldMappers(fieldName);
        if (smartMappers == null || !smartMappers.hasMapper()) {
            throw new FacetPhaseExecutionException(facetName, "No mapping found for field [" + fieldName + "]");
        }

        // add type filter if there is exact doc mapper associated with it
        if (smartMappers.explicitTypeInNameWithDocMapper()) {
            setFilter(context.filterCache().cache(smartMappers.docMapper().typeFilter()));
        }

        FieldMapper mapper = smartMappers.mapper();

        indexFieldName = mapper.names().indexName();
        fieldDataType = mapper.fieldDataType();

        histoProc = new HistogramProc(interval);
    }

    @Override
    protected void doCollect(int doc) throws IOException {
        fieldData.forEachValueInDoc(doc, histoProc);
    }

    @Override
    protected void doSetNextReader(IndexReader reader, int docBase) throws IOException {
        fieldData = (NumericFieldData) fieldDataCache.cache(fieldDataType, reader, indexFieldName);
    }

    @Override
    public Facet facet() {
        return new InternalFullHistogramFacet(facetName, comparatorType, histoProc.entries, true);
    }

    public static long bucket(double value, long interval) {
        return (((long) (value / interval)) * interval);
    }

    public static class HistogramProc implements NumericFieldData.DoubleValueInDocProc {

        final long interval;

        final ExtTLongObjectHashMap<InternalFullHistogramFacet.FullEntry> entries = CacheRecycler.popLongObjectMap();

        public HistogramProc(long interval) {
            this.interval = interval;
        }

        @Override
        public void onValue(int docId, double value) {
            long bucket = bucket(value, interval);
            InternalFullHistogramFacet.FullEntry entry = entries.get(bucket);
            if (entry == null) {
                entry = new InternalFullHistogramFacet.FullEntry(bucket, 1, value, value, 1, value);
                entries.put(bucket, entry);
            } else {
                entry.count++;
                entry.totalCount++;
                entry.total += value;
                if (value < entry.min) {
                    entry.min = value;
                }
                if (value > entry.max) {
                    entry.max = value;
                }
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.ma.MaskType — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="Masked array operations" href="../routines.ma.html" />
    <link rel="next" title="numpy.ma.masked_array" href="numpy.ma.masked_array.html" />
    <link rel="prev" title="numpy.ma.where" href="numpy.ma.where.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

Masked array operations »

numpy.ma.MaskType¶

<tt class="descclassname">numpy.ma.</tt><tt class="descname">MaskType</tt>[source]¶

alias of <tt class="xref py py-class docutils literal">bool_</tt>

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.

redpajama_set_name: RedPajamaGithub


text:
package algorithms.repeatedstring;

import java.util.Scanner;

public class Solution {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    long repeatLength = scanner.nextLong();
    System.out.println(repeatedString(input, repeatLength));
  }

  static long repeatedString(String input, long length) {
    long aCount = input.chars().filter(ch -> ch == 'a').count();
    long repeatedTimes = length / input.length();
    long remainderCount = length % input.length();
    long remainderACount = input.chars().limit(remainderCount).filter(ch -> ch == 'a').count();
    return (aCount * repeatedTimes) + remainderACount;
  }
}


text:
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "./Graph",
    "blocks/Container",
    "blocks/Exception"
], function (declare, lang, Graph, Container, Exception) {
    /**
     * @class RdfJs.TripleStore
     */
    return declare([], {
        /** @property {blocks.Container} The graphs stored in this sto*/
        _graphData: null,
        /** @property {String|String[]} - Default Graph(s) */
        _default: null,
        /** @constructs RdfJs.Graph */
        GraphCtor: null,
        constructor: function (args) {
            args = args || {};

            this.GraphCtor = args.GraphCtor || Graph;

            var defGraph = args.default || "urn:Default";
            this.setDefault(defGraph);

            this._graphData = new Container();
        },
        /**
         * Creates a new RDF Graph and adds it to the store
         * @param {String} name - Name of this new graph
         * @return {RdfJs.Graph}
         */
        addGraph: function (name) {
            if (name === "DEFAULT" || name === "ALL") {
                throw new Exception("Invalid Graph type");
            }
            var graph = new this.GraphCtor();

            this._graphData.set(name, graph);

            return graph;
        },
        /**
         * Executes a Method on the requested graphs
         * @param {Function} method - The method to execute
         * @param {String|String[]} graphs - The Graphs being executed against
         * @param {Boolean} [create] - Create a graph if it does not exist
         */
        runOnGraphs: function (method, graphs, create) {
            var store = this;
            graphs = graphs || "DEFAULT";
            if (!lang.isArray(graphs)) {
                graphs = [graphs];
            }

            var gNames = store._resolveGraphs(graphs);

            gNames.forEach(function (gName) {
                var graph = store.getGraph(gName, create);
                if (graph) {
                    method.apply(store, [graph]);
                }
            });
        },
        /**
         * Takes a list of Graphs and returns a list of realized names
         * @description Removes duplicates to avoid redundant calls, as well as handling the DEFAULT and ALL keywords
         * @param {String[]} list - The list of desired names
         * @param {blocks.Container} [mix] - Hash of graph names used internally by _resolveGraphs
         * @returns {Array}
         * @private
         */
        _resolveGraphs: function (list, mix) {
            var store = this;
            var selected = mix || new Container();

            for (var idx = 0; idx < list.length; idx++) {
                var item = list[idx];
                if (item === "ALL") {
                    store._resolveGraphs(this._graphData.keys(), selected);
                } else if (item === "DEFAULT") {
                    store._resolveGraphs(store._default, selected);
                } else {
                    selected.set(item, true);
                }
            }

            return selected.keys();
        },
        /**
         * Sets the default graph(s)
         * @param {String|String[]} value - Name(s) of the graphs to use
         */
        setDefault: function (value) {
            if (!lang.isArray(value)) {
                value = [value];
            }
            this._default = value;
        },
        /**
         * Adds a Triple to the specified Graph
         * @param {RdfJs.Triple} triple - The Triple being added
         * @param {String|String[]} graphName - The target Graph name(s)
         */
        add: function (triple, graphName) {
            this.runOnGraphs(function (graph) {
                graph.add(triple);
            }, graphName, true);
        },
        /**
         * Adds all Triples from input Graph to the specified Graph
         * @param {RdfJs.Graph} graph - The graph being added
         * @param {String|String[]} graphName - The target Graph name(s)
         */
        addAll: function (graph, graphName) {
            this.runOnGraphs(function (destGraph) {
                destGraph.addAll(graph);
            }, graphName, true);
        },
        /**
         * Removes a Triple from the specified Graph
         * @param {RdfJs.Triple} triple - The Triple being removed
         * @param {String|String[]} graphName - The target Graph name(s)
         */
        remove: function (triple, graphName) {
            this.runOnGraphs(function (graph) {
                graph.remove(triple);
            }, graphName);
        },
        /**
         * Removes matching Triple(s) from the specified Graph
         * @param {String} [subject] - The NT form subject being searched for
         * @param {String} [predicate] - The NT form predicate being searched for
         * @param {String} [object] - The NT form object being searched for
         * @param {String|String[]} graphName - The target Graph name(s)
         */
        removeMatches: function (subject, predicate, object, graphName) {
            this.runOnGraphs(function (graph) {
                graph.removeMatches(subject, predicate, object);
            }, graphName);
        },
        /**
         * Returns an Array containing the Triples from all Graphs
         * @param {String|String[]} graphName - The target Graph name(s)
         * @return {RdfJs.Triple[]}
         */
        toArray: function (graphName) {
            var out = [];
            this.runOnGraphs(function (graph) {
                out = out.concat(graph.toArray());
            }, graphName);
            return out;
        },
        /**
         * Returns true if tFilter returns true for any Triple in the target Graph(s)
         * @param {Function} tFilter - Filter to run against the Graph
         * @param {String|String[]} graphName - The target Graph name(s)
         * @returns {Boolean}
         */
        some: function (tFilter, graphName) {
            var some = false;
            this.runOnGraphs(function (graph) {
                some = some || graph.some(tFilter);
            }, graphName);
            return some;
        },
        /**
         * Returns true if tFilter returns true for every Triple in the target Graph(s)
         * @param {Function} tFilter - Filter to run against the Graph
         * @param {String|String[]} graphName - The target Graph name(s)
         * @returns {Boolean}
         */
        every: function (tFilter, graphName) {
            var every = true;
            this.runOnGraphs(function (graph) {
                every = every && graph.every(tFilter);
            }, graphName);
            return every;
        },
        /**
         * Returns A Graph containing the filtered Triples from the target Graph(s)
         * @param {Function} tFilter - Filter to run against the Graph
         * @param {String|String[]} graphName - The target Graph name(s)
         * @returns {RdfJs.Graph}
         */
        filter: function (tFilter, graphName) {
            var filtered = new this.GraphCtor();

            this.runOnGraphs(function (graph) {
                filtered.addAll(graph.filter(tFilter));
            }, graphName);
            return filtered;
        },
        /**
         * Runs the input function on the target Graph(s)
         * @param {Function} tCallback - Filter to run against the Graph
         * @param {String|String[]} graphName - The target Graph name(s)
         * @returns {RdfJs.Graph}
         */
        forEach: function (tCallback, graphName) {
            this.runOnGraphs(function (graph) {
                graph.forEach(tCallback);
            }, graphName);
        },
        /**
         * Returns A Graph containing the matched Triples from the target Graph(s)
         * @param {String} [subject] - The NT form subject being searched for
         * @param {String} [predicate] - The NT form predicate being searched for
         * @param {String} [object] - The NT form object being searched for
         * @param {String|String[]} graphName - The target Graph name(s)
         * @returns {RdfJs.Graph}
         */
        match: function (subject, predicate, object, graphName) {
            var matched = new this.GraphCtor();

            this.runOnGraphs(function (graph) {
                matched.addAll(graph.match(subject, predicate, object));
            }, graphName);
            return matched;
        },
        /**
         * Gets a Graph from the Store
         * @param {String} name - Name of the Graph to get
         * @param {Boolean} [create] - Create a graph if it does not exist
         * @returns {RdfJs.Graph}
         */
        getGraph: function (name, create) {
            name = (name === "DEFAULT") ? this._default : name;
            return this._graphData.get(name) || (create ? this.addGraph(name) : null);
        },
        /**
         * Removes a Graph from the Store
         * @param {String|String[]} name - the Graph(s) to remove
         */
        removeGraph: function (name) {
            var list = this._resolveGraphs(name);

            list.forEach(function (name) {
                this._graphData.remove(name);
            }.bind(this));
        }
    });
});


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocMAH.Configuration
{
	public class DocumentationElement : ConfigurationElement, IDocumentationConfiguration
	{
		[ConfigurationProperty("pageTitle", DefaultValue = "Documentation")]
		public virtual string PageTitle
		{
			get { return (string)this["pageTitle"]; }
			set { this["pageTitle"] = value; }
		}

		[ConfigurationProperty("customCss", DefaultValue = null)]
		public virtual string CustomCss
		{
			get { return (string)this["customCss"]; }
			set { this["customCss"] = value; }
		}

		[ConfigurationProperty("disabled", DefaultValue = false)]
		public virtual bool Disabled
		{
			get { return (bool)this["disabled"]; }
			set { this["disabled"] = value; }
		}
	}
}


text:
GoogleBody
==========

An Android Project About Google Body App


text:
class Model
{
  private:
  public:
    virtual void train(DirectoryIterator& boardFiles, const char* lifeDirectory) = 0;
    virtual float predict(const char* boardFile) const = 0;
    virtual float test(DirectoryIterator& boardFiles) const = 0;

    virtual bool writeToFile(const char* filename) const = 0;
    virtual bool readFromFile(const char* filename) = 0;
};

#endif


text:
const cloudinary = require('cloudinary')
const config = require('config')
const User = require('../../models/user.js')
const Street = require('../../models/street.js')
const logger = require('../../../lib/logger.js')()
const { SAVE_THUMBNAIL_EVENTS } = require('../../../lib/util.js')

const ALLOW_ANON_STREET_THUMBNAILS = false

exports.post = async function (req, res) {
  let json

  // The request payload is a stringified JSON due to the data URL for the street thumbnail being too large.
  // Setting the bodyParser.text({ limit }) works for a specific route whereas bodyParser.json({ limit }) does not.
  // As a result of sending the request payload as `text/plain` we have to parse the JSON string to access the object values.
  try {
    json = await JSON.parse(req.body)
  } catch (error) {
    res.status(400).json({ status: 400, msg: 'Could not parse body as JSON.' })
    return
  }

  const { image, event, streetType, editCount, creatorId } = json

  if (!image) {
    res.status(400).json({ status: 400, msg: 'Image data not specified.' })
    return
  }

  if (!req.params.street_id) {
    res.status(400).json({ status: 400, msg: 'Please provide street ID.' })
    return
  }

  // 1) Check if street exists.
  let street

  try {
    street = await Street.findOne({ id: req.params.street_id })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ status: 500, msg: 'Error finding street.' })
  }

  if (!street) {
    res.status(404).json({ status: 404, msg: 'Street not found.' })
    return
  }

  const publicId = `${config.env}/street_thumbnails/` + (streetType || req.params.street_id)

  const details = {
    public_id: publicId,
    street_type: streetType,
    creator_id: creatorId,
    edit_count: editCount
  }

  // 2) Check if street thumbnail exists.
  let resource

  try {
    resource = await cloudinary.v2.api.resource(publicId)
  } catch (err) {
    // If the http_code returned is 404, the street thumbnail does not exist which we shouldn't consider an error.
    if (err.error.http_code !== 404) {
      logger.error(err)
    }
  }

  // 3a) If street is a DEFAULT_STREET or EMPTY_STREET and thumbnail exists, return existing street thumbnail.
  // 3b) If nothing changed since the last street thumbnail upload (based on editCount), return existing street thumbnail.
  const tag = resource && resource.tags && resource.tags[0]
  const thumbnailSaved = (streetType && resource) || (tag && editCount && parseInt(tag, 10) === editCount)

  // Currently only uploading street thumbnails for initial street render. If not initial street render, only log details.
  if (event !== SAVE_THUMBNAIL_EVENTS.INITIAL && event !== SAVE_THUMBNAIL_EVENTS.TEST) {
    // If thumbnailSaved === true, then no upload would have been made.
    if (!thumbnailSaved) {
      logger.info({ event, ...details }, 'Uploading street thumbnail.')
    }

    res.status(501).json({ status: 501, msg: 'Only saving initial street rendered thumbnail.' })
    return
  }

  const handleUploadSuccess = function (resource) {
    const thumbnail = {
      public_id: resource.public_id,
      width: resource.width,
      height: resource.height,
      format: resource.format,
      secure_url: resource.secure_url,
      created_at: resource.created_at
    }

    res.status(201).json(thumbnail)
  }

  const handleUploadStreetThumbnail = async function (publicId) {
    if (!publicId) {
      res.status(400).json({ status: 400, msg: 'Please provide the public ID to be used.' })
      return
    }

    try {
      await cloudinary.v2.uploader.remove_all_tags([publicId])
      resource = await cloudinary.v2.uploader.upload(image, { public_id: publicId, tags: editCount })
    } catch (error) {
      logger.error(error)
    }

    if (!resource) {
      res.status(500).json({ status: 500, msg: 'Error uploading street thumbnail.' })
      return
    }

    logger.info({ event, ...details }, 'Uploading street thumbnail.')
    return resource
  }

  const handleFindStreetWithCreator = async function (street) {
    if (!req.userId) {
      res.status(401).json({ status: 401, msg: 'Please provide a user ID.' })
      return
    }

    let user

    try {
      user = await User.findOne({ id: req.userId })
    } catch (error) {
      logger.error(error)
      res.status(500).json({ status: 500, msg: 'Error finding user.' })
      return
    }

    if (!user) {
      res.status(403).json({ status: 403, msg: 'User not found.' })
      return
    }

    if (street.creator_id.toString() !== user._id.toString()) {
      res.status(403).json({ status: 403, msg: 'User does not have the right permissions to upload street thumbnail.' })
      return
    }

    const publicId = `${config.env}/street_thumbnails/${street.id}`
    return publicId
  }

  const handleError = function (error) {
    logger.error(error)
    res.status(500).end()
  }

  if (thumbnailSaved) {
    handleUploadSuccess(resource)
  } else if (!resource || (!street.creator_id && ALLOW_ANON_STREET_THUMBNAILS)) {
    // 3c) If street thumbnail does not exist, upload to Cloudinary no matter the currently signed in user.
    // 3d) If street was created by anonymous user, upload to Cloudinary.
    handleUploadStreetThumbnail(publicId)
      .then(handleUploadSuccess)
      .catch(handleError)
  } else if (street.creator_id) {
    // 3e) If street thumbnail already exists and street was created by a user, check if signed in user = creator.
    handleFindStreetWithCreator(street)
      .then(handleUploadStreetThumbnail)
      .then(handleUploadSuccess)
      .catch(handleError)
  } else {
    res.status(403).json({ status: 403, msg: 'User does not have the right permissions to upload street thumbnail.' })
  }
}

exports.delete = async function (req, res) {
  if (!req.params.street_id) {
    res.status(400).json({ status: 400, msg: 'Please provide street ID.' })
    return
  }

  // 1) Verify user is logged in.
  const userId = req.userId

  if (!userId) {
    res.status(401).json({ status: 401, msg: 'Please provide user ID.' })
    return
  }

  let user

  try {
    user = await User.findOne({ id: userId })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ status: 500, msg: 'Error finding user.' })
  }

  if (!user) {
    res.status(404).json({ status: 404, msg: 'User not found.' })
    return
  }

  // Is requesting user logged in?
  if (user.login_tokens.indexOf(req.loginToken) === -1) {
    res.status(401).end()
    return
  }

  // 2) Check that street exists.
  // 3) Verify that street is owned by logged in user.
  let street

  try {
    street = await Street.findOne({ id: req.params.street_id })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ status: 500, msg: 'Error finding street.' })
  }

  if (!street) {
    res.status(404).json({ status: 404, msg: 'Street not found.' })
    return
  } else if (street.creator_id.toString() !== user._id.toString()) {
    res.status(403).json({ status: 403, msg: 'Signed in user cannot delete street thumbnail.' })
    return
  }

  // 4) Delete street thumbnail from cloudinary.
  const publicId = `${config.env}/street_thumbnails/${req.params.street_id}`
  cloudinary.v2.uploader.destroy(publicId, function (error, result) {
    if (error) {
      logger.error(error)
      res.status(500).json({ status: 500, msg: 'Error deleting street thumbnail.' })
      return
    }

    res.status(204).end()
  })
}

exports.get = async function (req, res) {
  if (!req.params.street_id) {
    res.status(400).json({ status: 400, msg: 'Please provide a street id.' })
    return
  }

  let resource

  try {
    const publicId = `${config.env}/street_thumbnails/${req.params.street_id}`
    resource = await cloudinary.v2.api.resource(publicId)
  } catch (error) {
    logger.error(error)
    res.status(500).json({ status: 500, msg: 'Error finding street thumbnail.' })
    return
  }

  if (!resource) {
    res.status(404).json({ status: 404, msg: 'Could not find street thumbnail.' })
    return
  }

  res.status(200).json(resource)
}


text:
var make_lazy = function (a) {
	return a.bind.apply(a, arguments)
};


text:
namespace luabind {

	template<typename T>
	T* get_pointer(T* pointer)
	{
		return pointer;
	}

	template<typename T>
	T* get_pointer(const std::unique_ptr<T>& pointer)
	{
		return pointer.get();
	}

	template<typename T>
	T* get_pointer(const std::shared_ptr<T>& pointer)
	{
		return pointer.get();
	}

	namespace detail {

		template<typename T>
		struct pointer_traits {
			enum { is_pointer = false };
		};

		template<typename T>
		struct pointer_traits<T*>
		{
			enum { is_pointer = true };
			typedef T value_type;
		};

		template<typename T>
		struct pointer_traits<std::unique_ptr<T>>
		{
			enum { is_pointer = true };
			typedef T value_type;
		};

		template<typename T>
		struct pointer_traits<std::shared_ptr<T>>
		{
			enum { is_pointer = true };
			typedef T value_type;
		};

		template<typename T>
		using is_pointer_to_const = std::is_const< typename pointer_traits<T>::value_type >;

		template<typename T>
		void release_ownership(std::unique_ptr<T>& p)
		{
			p.release();
		}

		template <class P>
		void release_ownership(P const&)
		{
			throw std::runtime_error(
				"luabind: smart pointer does not allow ownership transfer");
		}

		namespace has_get_pointer_
		{

			struct any
			{
				template<class T> any(T const&);
			};

			struct no_overload_tag
			{};

			typedef char(&yes)[1];
			typedef char(&no)[2];

			no_overload_tag operator, (no_overload_tag, int);

			template<class T>
			T* get_pointer(T const volatile*);

			template<class T>
			T* get_pointer(std::unique_ptr<T> const&);

			template<class T>
			T* get_pointer(std::shared_ptr<T> const&);

			detail::has_get_pointer_::no_overload_tag
				get_pointer(detail::has_get_pointer_::any);

			template<class T>
			yes check(T const&);
			no check(no_overload_tag);

			template<class T>
			struct impl
			{
				static typename std::add_lvalue_reference<T>::type x;
				static const bool value = (sizeof(has_get_pointer_::check((get_pointer(x), 0)))==1);
				typedef std::integral_constant<bool, value> type;
			};

		} // namespace has_get_pointer_

		template<class T>
		struct has_get_pointer
			: has_get_pointer_::impl<T>::type
		{};

	} // namespace detail

} // namespace luabind

#endif // LUABIND_GET_POINTER_051023_HPP


text:
/* xTests header files */
#include <xtests/implicit_link.h>

/* Pantheios header files */
#include <pantheios/implicit_link/util.h>
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.null.h>
#include <pantheios/implicit_link/be.null.h>
PANTHEIOS_EXTERN PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[];

/* ///////////////////////////// end of file //////////////////////////// */


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _JBIG2_OBJECT_H_
#define _JBIG2_OBJECT_H_
#include "JBig2_Define.h"
class CJBig2_Module;
#define _JBIG2_NO_EXPECTION_
class CJBig2_Object
{
public:

    void *operator new(size_t size, CJBig2_Module *pModule, FX_LPCSTR filename, int line);

    void operator delete(void *p, CJBig2_Module *pModule, FX_LPCSTR filename, int line);

    void *operator new(size_t size, CJBig2_Module *pModule);

    void operator delete(void *p);

    void operator delete(void *p, CJBig2_Module *pModule);

    void *operator new[](size_t size, CJBig2_Module *pModule, size_t unit_size,
                         FX_LPCSTR filename, int line);

    void operator delete[](void *p, CJBig2_Module *pModule, size_t unit_size,
                           FX_LPCSTR filename, int line);

    void *operator new[](size_t size, CJBig2_Module *pModule, size_t unit_size);

    void operator delete[](void* p);

    void operator delete[](void *p, CJBig2_Module *pModule, size_t unit_size);
public:

    CJBig2_Module *m_pModule;
};
#define JBIG2_NEW new(m_pModule)
#define JBIG2_ALLOC(p, a) p = JBIG2_NEW a; p->m_pModule = m_pModule;
#endif


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.

import LabelsController from 'common/components/labels/labels_controller';
import componentsModule from 'common/components/components_module';

describe('Labels controller', () => {
  /**
   * @type {!LabelsController}
   */
  let ctrl;

  beforeEach(() => {
    angular.mock.module(componentsModule.name);
    angular.mock.inject(($controller) => { ctrl = $controller(LabelsController); });
  });

  it('should display correct number of labels', () => {
    // given
    ctrl.labels = {
      'label-1': 'value-1',
      'label-2': 'value-2',
      'label-3': 'value-3',
      'label-4': 'value-4',
      'label-5': 'value-5',
      'label-6': 'value-6',
      'label-7': 'value-7',
      'label-8': 'value-8',
      'label-9': 'value-9',
      'label-10': 'value-10',
    };

    expect(ctrl.isMoreAvailable()).toBe(true);
    expect(ctrl.isShowingAll()).toBe(false);
    expect(ctrl.isVisible(0)).toBe(true);
    expect(ctrl.isVisible(4)).toBe(true);
    expect(ctrl.isVisible(5)).toBe(false);

    // when
    ctrl.switchLabelsView();

    // then
    expect(ctrl.isShowingAll()).toBe(true);
    expect(ctrl.isVisible(0)).toBe(true);
    expect(ctrl.isVisible(7)).toBe(true);
    expect(ctrl.isVisible(8)).toBe(true);
  });

  it('should not display switch if there are less than 5 labels', () => {
    // given
    ctrl.labels = {
      'label-1': 'value-1',
      'label-2': 'value-2',
      'label-3': 'value-3',
      'label-4': 'value-4',
      'label-5': 'value-5',
    };

    // then
    expect(ctrl.isMoreAvailable()).toBe(false);
  });
});


text:
module Concealable
  extend ActiveSupport::Concern

  include SetOperations

  included do
    scope :concealed, -> { column_names.include?('concealed') ? where(concealed: true) : none }
    scope :visible, -> { column_names.include?('concealed') ? where(concealed: false) : all }
  end

  def concealed?
    attributes.has_key?('concealed') ? attributes['concealed'] : false
  end

  def visible?
    attributes.has_key?('concealed') ? !attributes['concealed'] : true
  end

  # May be overridden in models
  def should_be_concealed?
    false
  end
end


text:
body, html { padding: 0; margin: 0; font-size: 16px; font-family: Verdana, Arial; }
.container { margin: auto; height: auto; overflow: hidden; padding: 20px 2%; }
.button { margin: 0 2px; padding: 6px 16px 8px; }


text:
glaze
=====

A mini web framework in Go. Glaze currently only provides a simple
controller/view abstraction to make it easier to get a simple web
app up and running.

This example assumes that you have a view directory laid out like so:

```
/path/to/views/
	layouts/
		default.html
	public/
		index.html
```

Glaze will always try to load any layout files from "layouts/*.html"
under the given view root. The layout should be inside a {{define "layout"}}...{{end}} block.

controllers/public.go:

```go
package controllers

import (
	"net/http"

	"github.com/octoberxp/glaze"
)

type Public struct {
	*glaze.Controller
}

func NewPublicController() *Public {
	controller, err := glaze.NewController("/path/to/views/", "public")
	if err != nil {
		panic(err)
	}

	return &Public{Controller: controller}
}

func (controller *Public) Index(w http.ResponseWriter, r *http.Request) {
	controller.RenderTemplate(w, "index", nil)
}
```

main.go:

```go
package main

import (
	"net/http"

	"exampleapp/controllers"
)

func main() {
	// Instantiate controllers
	public := controllers.NewPublicController()

	// Configure routes
	http.HandleFunc("/", public.Index)

	// And start the server
	http.ListenAndServe(":9000", nil)
}
```


text: ALTER TABLE `channel` ADD `image` VARCHAR(255) NOT NULL AFTER `is_admin`;


text:
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.log4j.Logger;

public class PlayByPlayMapper extends Mapper<LongWritable, Text, Text, Text> {
	Logger logger = Logger.getLogger(PlayByPlayMapper.class);

	private static final char OUTPUT_SEPARATOR = '\t';

	/** (14:56) E.Manning pass incomplete deep left to H.Nicks. */
	Pattern incompletePass = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*pass.*incomplete.*(to ([A-Za-z]*\\.?\\s?[A-Za-z]*))?");

	/**
	 * (11:28) (Shotgun) J.Cutler pass short right intended for M.Forte
	 * INTERCEPTED by J.Freeman at CHI 4. J.Freeman for 4 yards TOUCHDOWN.
	 */
	Pattern interception = Pattern
			.compile("([A-Za-z]*\\.\\s?[A-Za-z]*).*intended for.*INTERCEPTED by ([A-Za-z]*\\.?\\s?[A-Za-z]*)");

	/**
	 * (14:49) E.Manning pass short middle to V.Cruz to NYG 21 for 5 yards
	 * (S.Lee) [J.Hatcher].
	 */
	Pattern completePass = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*pass.*to ([A-Z]*\\.\\s?[A-Za-z]*).*\\(?([A-Z]*\\.\\s?[A-Za-z]*)?\\)?\\s?\\[?([A-Z]*\\.\\s?[A-Za-z]*)?\\]?");

	/**
	 * (13:58) S.Weatherford punts 56 yards to DAL 23 Center-Z.DeOssie. D.Bryant
	 * to DAL 24 for 1 yard (Z.DeOssie).
	 */
	Pattern punt = Pattern
			.compile("([A-Z]*\\.\\s?[A-Za-z]*)\\s*punts.*to.*\\.\\s?([A-Z]*\\.\\s?[A-Za-z]*)?");

	/** (13:44) D.Murray left guard to DAL 27 for 3 yards (C.Blackburn). */
	Pattern run = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*.*[to|for].*\\(?([A-Z]*\\.\\s?[A-Za-z]*)?\\)?\\s?\\[?([A-Z]*\\.\\s?[A-Za-z]*)?\\]?");

	/**
	 * D.Bailey kicks 69 yards from DAL 35 to NYG -4. D.Wilson to NYG 16 for 20
	 * yards (A.Holmes).
	 */
	Pattern kickoff = Pattern
			.compile("([A-Z]*\\.\\s?[A-Za-z]*)\\s*kicks.*from.*\\.?\\s?([A-Z]*\\.\\s?[A-Za-z]*)?");

	/** (:17) (No Huddle) M.Stafford spiked the ball to stop the clock. */
	Pattern spike = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*spiked the ball");

	/**
	 * (9:14) L.Tynes 22 yard field goal is GOOD Center-Z.DeOssie
	 * Holder-S.Weatherford.
	 */
	Pattern fieldGoal = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*).*field goal");

	/** D.Bailey extra point is GOOD Center-L.Ladouceur Holder-C.Jones. */
	Pattern extraPoint = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*).*extra point");

	/**
	 * (9:36) PENALTY on NYG-V.Cruz False Start 5 yards enforced at DAL 47 - No
	 * Play.
	 */
	Pattern penalty = Pattern.compile(".*PENALTY.*");

	/**
	 * (12:19) (Shotgun) R.Tannehill FUMBLES (Aborted) at MIA 49 recovered by
	 * MIA-D.Thomas at HST 49. D.Thomas to HST 49 for no gain (B.Cushing).
	 */
	Pattern fumble = Pattern.compile(".*FUMBLES.*");

	/** (3:42) J.Flacco sacked at BLT 15 for -5 yards (T.Hali). */
	Pattern sack = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*.*sacked.*\\(?([A-Z]*\\.\\s?[A-Za-z]*)\\)?\\s?\\[?([A-Z]*\\.\\s?[A-Za-z]*)?\\]?");

	/** (1:18) J.Flacco kneels to BLT 40 for -1 yards. */
	Pattern kneel = Pattern.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*kneels");

	/** *** play under review *** */
	Pattern review = Pattern.compile("play under review");

	/** (5:42) Alex Smith scrambles right end to CLV 20 for 3 yards (J.Haden). */
	Pattern scramble = Pattern
			.compile("([A-Za-z]*\\.?\\s?[A-Za-z]*)\\s*scrambles");

	/** END QUARTER 3 */
	Pattern endQuarter = Pattern.compile("END [QUARTER|GAME]");

	/** 20120909_STL@DET */
	Pattern gameString = Pattern.compile("(\\d*)_([A-Z]*)@([A-Z]*)");

	Pattern[] allPatterns = { incompletePass, interception, completePass, punt,
			kickoff, spike, fieldGoal, extraPoint, sack, kneel, review,
			scramble, endQuarter, run };

	String idPrefix = null;
	int id = 0;

	@Override
	public void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		String line = value.toString();

		String[] pieces = line.split(",", -1);

		if (pieces.length == 0) {
			// Skip lines that are only commas
			// ,,,,,,,,,,,,
			return;
		}

		String qb = "", offensivePlayer = "", defensivePlayer1 = "", defensivePlayer2 = "";
		boolean hasPenalty = false, hasFumble = false, hasIncomplete = false, isGoalGood = false;
		String playType = "";

		boolean found = false;

		int piecesIndex = -1;

		String playDesc = null;

		// Sometimes the play description is in a different field
		if (pieces[9].length() > 7) {
			playDesc = pieces[9];
			piecesIndex = 9;
		} else if (pieces[11].length() > 7) {
			playDesc = pieces[11];
			piecesIndex = 11;
		} else {
			logger.warn("Line is null \"" + line + "\"");
			return;
		}

		if (pieces.length < piecesIndex + 2) {
			logger.warn("Line is not big enough \"" + line + "\"");
			return;
		}

		for (Pattern pattern : allPatterns) {
			Matcher matcher = pattern.matcher(playDesc);

			if (matcher.find()) {
				found = true;

				if (pattern == incompletePass) {
					qb = matcher.group(1);
					offensivePlayer = matcher.group(3);
					hasIncomplete = true;
					playType = "PASS";
				} else if (pattern == interception) {
					qb = matcher.group(1);
					defensivePlayer1 = matcher.group(2);
					playType = "INTERCEPTION";
				} else if (pattern == completePass) {
					qb = matcher.group(1);
					offensivePlayer = matcher.group(2);
					defensivePlayer1 = matcher.group(3);
					defensivePlayer2 = matcher.group(4);
					playType = "PASS";
				} else if (pattern == punt) {
					qb = matcher.group(1);
					defensivePlayer1 = matcher.group(2);
					playType = "PUNT";
				} else if (pattern == kickoff) {
					offensivePlayer = matcher.group(1);
					defensivePlayer1 = matcher.group(2);
					playType = "KICKOFF";
				} else if (pattern == spike) {
					qb = matcher.group(1);
					playType = "SPIKE";
				} else if (pattern == fieldGoal) {
					qb = matcher.group(1);
					isGoalGood = playDesc.toLowerCase().indexOf("no good") == -1
							&& playDesc.toLowerCase().indexOf("missed") == -1;
					playType = "FIELDGOAL";
				} else if (pattern == extraPoint) {
					qb = matcher.group(1);
					isGoalGood = playDesc.toLowerCase().indexOf("no good") == -1
							&& playDesc.toLowerCase().indexOf("missed") == -1;
					playType = "EXTRAPOINT";
				} else if (pattern == sack) {
					offensivePlayer = matcher.group(1);
					defensivePlayer1 = matcher.group(2);
					defensivePlayer2 = matcher.group(3);

					// Workaround regex bug
					if (defensivePlayer2 != null
							&& defensivePlayer2.equals(".")) {
						defensivePlayer2 = "";
					}

					playType = "SACK";
				} else if (pattern == kneel) {
					qb = matcher.group(1);
					playType = "KNEEL";
				} else if (pattern == review) {
					playType = "REVIEW";
				} else if (pattern == scramble) {
					qb = matcher.group(1);
					playType = "SCRAMBLE";
				} else if (pattern == endQuarter) {
					playType = "END";
				} else if (pattern == run) {
					offensivePlayer = matcher.group(1);
					defensivePlayer1 = matcher.group(2);
					defensivePlayer2 = matcher.group(3);

					// Workaround regex bug
					if (defensivePlayer2 != null
							&& defensivePlayer2.equals(".")) {
						defensivePlayer2 = "";
					}

					playType = "RUN";
				}

				break;
			}
		}

		// Always check for penalties and fumbles
		Matcher matcher = penalty.matcher(playDesc);

		if (matcher.find()) {
			hasPenalty = true;
		}

		matcher = fumble.matcher(playDesc);

		if (matcher.find()) {
			hasFumble = true;
		}

		if (found == false) {
			context.getCounter("inc", "notfound").increment(1);
			logger.warn("Did not match \"" + line + "\"");

			return;
		}

		StringBuilder output = new StringBuilder();

		// Process the game output
		Matcher gameMatcher = gameString.matcher(pieces[0]);

		// Process the game output
		if (gameMatcher.find()) {
			// Check that offense and defense is filled in
			if (pieces[4].trim().length() == 0) {
				pieces[4] = gameMatcher.group(3).equals(pieces[5]) ? gameMatcher
						.group(2) : gameMatcher.group(3);
				logger.warn("Replacing offense to be " + pieces[4] + " Off:"
						+ pieces[5]);
			}

			if (pieces[5].trim().length() == 0) {
				pieces[4] = gameMatcher.group(3).equals(pieces[4]) ? gameMatcher
						.group(3) : gameMatcher.group(2);
				logger.warn("Replacing offense to be " + pieces[5] + " Def:"
						+ pieces[4]);
			}
		} else {
			context.getCounter("inc", "gamenotfound").increment(1);
			logger.warn("Game did not match \"" + line + "\"");
			return;
		}

		// Add all of the pieces
		for (int i = 0; i < pieces.length; i++) {
			// Normalize output across all seasons by removing extra info
			if (piecesIndex == 11) {
				if (i == 9 || i == 10 || i == 12 || i == 13 || i == 14) {
					continue;
				}

				output.append(pieces[i]).append(OUTPUT_SEPARATOR);
			} else {
				output.append(pieces[i]).append(OUTPUT_SEPARATOR);
			}
		}

		// Check that extracted data isn't from missing groups
		if (qb == null) {
			qb = "";
		}

		if (offensivePlayer == null) {
			offensivePlayer = "";
		}

		if (defensivePlayer1 == null) {
			defensivePlayer1 = "";
		}

		if (defensivePlayer2 == null) {
			defensivePlayer2 = "";
		}

		// Process the play by play data
		output.append(qb).append(OUTPUT_SEPARATOR);
		output.append(offensivePlayer).append(OUTPUT_SEPARATOR);
		output.append(defensivePlayer1).append(OUTPUT_SEPARATOR);
		output.append(defensivePlayer2).append(OUTPUT_SEPARATOR);
		output.append(hasPenalty).append(OUTPUT_SEPARATOR);
		output.append(hasFumble).append(OUTPUT_SEPARATOR);
		output.append(hasIncomplete).append(OUTPUT_SEPARATOR);
		output.append(isGoalGood).append(OUTPUT_SEPARATOR);
		output.append(playType).append(OUTPUT_SEPARATOR);

		// Process the game output
		output.append(gameMatcher.group(3)).append(OUTPUT_SEPARATOR);
		output.append(gameMatcher.group(2)).append(OUTPUT_SEPARATOR);
		output.append(gameMatcher.group(1)).append(OUTPUT_SEPARATOR);

		// Output the unique id of the play
		output.append(idPrefix).append("_").append(StringUtils.leftPad(String.valueOf(id), 8, "0"));
		id++;

		context.write(new Text(pieces[0]), new Text(output.toString()));
	}

	@Override
	public void setup(Context context) {
		id = 0;

		FileSplit fileSplit = (FileSplit) context.getInputSplit();
		idPrefix = fileSplit.getPath().getName();

		// Crop until the first underscore
		idPrefix = idPrefix.substring(0, idPrefix.indexOf("_"));
	}
}


text:
using Gama.Atenciones.Wpf.FakeServices;
using Gama.Atenciones.Wpf.Services;
using Gama.Atenciones.Wpf.ViewModels;
using Moq;
using NHibernate;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Gama.Atenciones.Business;
using Gama.Atenciones.Wpf.Eventos;
using Gama.Atenciones.Wpf.UIEvents;
using Core.Util;

namespace Gama.Atenciones.WpfTests
{
    public class DashboardViewModelTests : BaseTestClass
    {
        private List<Persona> _Personas;
        private List<Cita> _Citas;
        private List<Atencion> _Atenciones;
        private Mock<IAtencionRepository> _AtencionRepositoryMock;
        private Mock<ICitaRepository> _CitaRepositoryMock;
        private Mock<IEventAggregator> _EventAggregatorMock;
        private Mock<IPersonaRepository> _PersonaRepositoryMock;
        private Mock<ISession> _SessionMock;
        private Preferencias _Settings;
        DashboardViewModel _Vm;

        private Mock<PersonaCreadaEvent> _PersonaCreadaEventMock;
        private Mock<PersonaActualizadaEvent> _PersonaActualizadaEventMock;
        private Mock<PersonaEliminadaEvent> _PersonaEliminadaEventMock;
        private Mock<PersonaEnBusquedaEvent> _PersonaEnBusquedaEventMock;
        private Mock<PersonaSeleccionadaEvent> _PersonaSeleccionadaEventMock;

        private Mock<CitaCreadaEvent> _CitaCreadaEventMock;
        private Mock<CitaActualizadaEvent> _CitaActualizadaEventMock;
        private Mock<CitaEliminadaEvent> _CitaEliminadaEventMock;
        private Mock<CitaSeleccionadaEvent> _CitaSeleccionadaEventMock;

        private Mock<AtencionCreadaEvent> _AtencionCreadaEventMock;
        private Mock<AtencionActualizadaEvent> _AtencionActualizadaEventMock;
        private Mock<AtencionEliminadaEvent> _AtencionEliminadaEventMock;
        private Mock<AtencionSeleccionadaEvent> _AtencionSeleccionadaEventMock;

        public DashboardViewModelTests()
        {
            _PersonaRepositoryMock = new Mock<IPersonaRepository>();
            _CitaRepositoryMock = new Mock<ICitaRepository>();
            _AtencionRepositoryMock = new Mock<IAtencionRepository>();
            _EventAggregatorMock = new Mock<IEventAggregator>();
            _Settings = new Preferencias();
            _SessionMock = new Mock<ISession>();

            var fakeRepository = new FakeRepository();

            _Personas = fakeRepository.Personas;
            _Citas = fakeRepository.Citas;
            _Atenciones = fakeRepository.Atenciones;

            _PersonaRepositoryMock.Setup(p => p.GetAll()).Returns(_Personas);
            _CitaRepositoryMock.Setup(c => c.GetAll()).Returns(_Citas);
            _AtencionRepositoryMock.Setup(a => a.GetAll()).Returns(_Atenciones);

            _PersonaCreadaEventMock = new Mock<PersonaCreadaEvent>();
            _PersonaActualizadaEventMock = new Mock<PersonaActualizadaEvent>();
            _PersonaEliminadaEventMock = new Mock<PersonaEliminadaEvent>();
            _PersonaEnBusquedaEventMock = new Mock<PersonaEnBusquedaEvent>();
            _PersonaSeleccionadaEventMock = new Mock<PersonaSeleccionadaEvent>();

            _CitaCreadaEventMock = new Mock<CitaCreadaEvent>();
            _CitaActualizadaEventMock = new Mock<CitaActualizadaEvent>();
            _CitaEliminadaEventMock = new Mock<CitaEliminadaEvent>();
            _CitaSeleccionadaEventMock = new Mock<CitaSeleccionadaEvent>();

            _AtencionCreadaEventMock = new Mock<AtencionCreadaEvent>();
            _AtencionActualizadaEventMock = new Mock<AtencionActualizadaEvent>();
            _AtencionEliminadaEventMock = new Mock<AtencionEliminadaEvent>();
            _AtencionSeleccionadaEventMock = new Mock<AtencionSeleccionadaEvent>();

            _EventAggregatorMock.Setup(e => e.GetEvent<PersonaCreadaEvent>()).Returns(_PersonaCreadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<PersonaActualizadaEvent>()).Returns(_PersonaActualizadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<PersonaEliminadaEvent>()).Returns(_PersonaEliminadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<PersonaSeleccionadaEvent>()).Returns(_PersonaSeleccionadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<PersonaEnBusquedaEvent>()).Returns(_PersonaEnBusquedaEventMock.Object);

            _EventAggregatorMock.Setup(e => e.GetEvent<CitaCreadaEvent>()).Returns(_CitaCreadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<CitaActualizadaEvent>()).Returns(_CitaActualizadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<CitaEliminadaEvent>()).Returns(_CitaEliminadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<CitaSeleccionadaEvent>()).Returns(_CitaSeleccionadaEventMock.Object);

            _EventAggregatorMock.Setup(e => e.GetEvent<AtencionCreadaEvent>()).Returns(_AtencionCreadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<AtencionActualizadaEvent>()).Returns(_AtencionActualizadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<AtencionEliminadaEvent>()).Returns(_AtencionEliminadaEventMock.Object);
            _EventAggregatorMock.Setup(e => e.GetEvent<AtencionSeleccionadaEvent>()).Returns(_AtencionSeleccionadaEventMock.Object);

            _Vm = new DashboardViewModel(
                personaRepository: _PersonaRepositoryMock.Object,
                citaRepository: _CitaRepositoryMock.Object,
                atencionRepository: _AtencionRepositoryMock.Object,
                eventAggregator: _EventAggregatorMock.Object,
                settings: _Settings,
                session: _SessionMock.Object);
        }

        [Fact]
        private void ShouldInitializeItsProperties()
        {
            ///
            /// Assert
            ///

            Assert.Null(_Vm.FechaDeInicio);
            Assert.Null(_Vm.FechaDeFin);
            Assert.NotNull(_Vm.SelectPersonaCommand);
            Assert.NotNull(_Vm.SelectCitaCommand);
            Assert.NotNull(_Vm.SelectAtencionCommand);

            _PersonaRepositoryMock.Verify(p => p.GetAll(), Times.Once);
            _CitaRepositoryMock.Verify(c => c.GetAll(), Times.Once);
            _AtencionRepositoryMock.Verify(a => a.GetAll(), Times.Once);
        }

        [Fact]
        private void ShouldFiltrarPersonasAtencionesYCitasPorFecha()
        {
            ///
            /// Arrange && Act
            ///
            // Modificar las fechas ya debe efectuar el cambio, no hay comando
            // a través del cual se haga
            _Vm.FechaDeInicio = DateTime.Now.AddDays(-5);
            _Vm.FechaDeFin = DateTime.Now.AddDays(2);

            ///
            /// Assert
            ///
            Assert.True(_Vm.Personas.All(
               p => p.CreatedAt.IsBetween(_Vm.FechaDeInicio, _Vm.FechaDeFin)
                    || p.UpdatedAt.IsBetween(_Vm.FechaDeInicio, _Vm.FechaDeFin)));
            Assert.True(_Vm.Atenciones.All(x => x.Fecha.IsBetween(_Vm.FechaDeInicio, _Vm.FechaDeFin)));
            Assert.True(_Vm.ProximasCitas.All(x => x.Fecha.IsBetween(_Vm.FechaDeInicio, _Vm.FechaDeFin)));
        }

        ///
        ///  TESTS DE LOS COMANDOS
        ///

        [Fact]
        private void ShouldFiltrarPorPersonaSeleccionadaYSoloMostrarAtencionesYCitasSuyas()
        {
            ///
            /// Arrange
            ///
            int expectedId = 1;
            int expectedCount = 1;

            ///
            /// Act
            ///
            _Vm.FiltrarPorPersonaCommand.Execute(_Personas.Find(x => x.Id == expectedId));

            ///
            /// Assert
            ///
            Assert.Equal(_Vm.Personas.Count, expectedCount);
            Assert.Equal(_Vm.Personas.First().Id, expectedId);
            Assert.True(_Vm.ProximasCitas.All(x => x.Persona.Id == expectedId));
            Assert.True(_Vm.Atenciones.All(x => x.Cita.Persona.Id == expectedId));

            // Si se vuelve a ejecutar ese comando, desactivará el filtro, por lo que
            // se debe volver al estado inicial. Pasamos null como parámetro para que de
            // error en caso de meterse por donde no debe. En este caso, al volverse
            // al estado inicial, no debe accederse a ese parámetro.

            ///
            /// Arrange
            ///
            expectedCount = _Personas.Count;

            ///
            /// Act
            ///
            _Vm.FiltrarPorPersonaCommand.Execute(null);

            ///
            /// Assert
            ///
            Assert.Equal(_Vm.Personas.Count, expectedCount);
        }

        [Fact]
        private void ShouldPublishPersonaSeleccionadaEventWhenUnaPersonaIsSelected()
        {
            /// Arrange
            Persona persona = _Personas.First();

            /// Act
            _Vm.SelectPersonaCommand.Execute(persona);

            /// Assert
            _PersonaSeleccionadaEventMock.Verify(e => e.Publish(persona.Id), Times.Once);
        }

        [Fact]
        private void ShouldPublishCitaSeleccionadaEventWhenUnaCitaIsSelected()
        {
            /// Arrange
            Cita cita = _Citas.First();

            /// Act
            _Vm.SelectCitaCommand.Execute(cita);

            /// Assert
            _CitaSeleccionadaEventMock.Verify(e => e.Publish(cita.Persona.Id), Times.Once);
        }

        [Fact]
        private void ShouldPublishAtencionSeleccionadaEventWhenUnaAtencionIsSelected()
        {
            /// Arrange
            Atencion atencion = _Atenciones.First();

            /// Act
            _Vm.SelectAtencionCommand.Execute(atencion);

            /// Assert
            _AtencionSeleccionadaEventMock.Verify(e => e.Publish(It.IsAny<IdentificadorDeModelosPayload>()),
                Times.Once);
        }

        ///
        ///  TESTS DE LOS EVENTOS
        ///

        [Fact]
        private void PersonaEnBusquedaEventShouldFiltrarLasPersonasDisponiblesPorNombre()
        {
            ///
            /// Arrange
            ///
            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            ///
            /// Act
            ///
            eventAggregator.GetEvent<PersonaEnBusquedaEvent>().Publish("ard");

            ///
            /// Assert
            ///
            if (vm.Personas.Count != 0)
                Assert.True(vm.Personas.All(x => x.Nombre.Contains("ard")));
        }

        [Fact]
        private void NuevaPersonaShouldAddLaPersona()
        {
            ///
            /// Arrange
            ///
            var persona = new Persona { Id = int.MaxValue };
            _PersonaRepositoryMock.Setup(p => p.GetById(persona.Id)).Returns(persona);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = _Personas.Count + 1;

            ///
            /// Act
            ///
            eventAggregator.GetEvent<PersonaCreadaEvent>().Publish(persona.Id);

            ///
            /// Assert
            ///
            Assert.Equal(vm.Personas.Count, expectedCount);
            Assert.True(vm.Personas.Where(x => x.Id == persona.Id).ToList().Count == 1);
        }

        [Fact]
        private void PersonaActualizadaEventShouldUpdateLaPersona()
        {
            ///
            /// Arrange
            ///
            var personaAntesDeActualizar = _Personas.First();
            var personaActualizada = new Persona { Id = personaAntesDeActualizar.Id };
            personaActualizada.CopyValuesFrom(personaAntesDeActualizar);
            _PersonaRepositoryMock.Setup(p => p.GetById(personaAntesDeActualizar.Id)).Returns(personaActualizada);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            string expectedName = "Otro nombre";
            string expectedNif = "Otro Nif";
            byte[] expectedImage = Gama.Atenciones.Wpf.Converters.BinaryImageConverter.GetBitmapImageFromUriSource(
                                 new Uri("pack://application:,,,/Gama.Atenciones.Wpf;component/Resources/Images/atencion_icon.png"));

            ///
            /// Act
            ///
            personaActualizada.Nombre = expectedName;
            personaActualizada.Nif = expectedNif;
            personaActualizada.Imagen = expectedImage;
            eventAggregator.GetEvent<PersonaActualizadaEvent>().Publish(personaActualizada.Id);

            ///
            /// Assert
            ///
            var personaSupuestamenteActualizada = vm.Personas.Where(x => x.Id == personaActualizada.Id).First();
            Assert.Equal(personaSupuestamenteActualizada.Nombre, personaActualizada.Nombre);
            Assert.Equal(expectedName, personaSupuestamenteActualizada.Nombre);
            Assert.Equal(personaSupuestamenteActualizada.Nif, personaActualizada.Nif);
            Assert.Equal(expectedNif, personaSupuestamenteActualizada.Nif);
            Assert.Equal(personaSupuestamenteActualizada.Imagen, personaActualizada.Imagen);
            Assert.Equal(expectedImage, personaSupuestamenteActualizada.Imagen);
        }

        [Fact]
        private void PersonaEliminadaEventShouldEliminarLaPersonaYTodasSusCitasYAtenciones()
        {
            ///
            /// Arrange
            ///
            var persona = _Personas.First();

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = _Personas.Count - 1;

            ///
            /// Act
            ///
            eventAggregator.GetEvent<PersonaEliminadaEvent>().Publish(persona.Id);

            ///
            /// Assert
            ///
            Assert.Equal(vm.Personas.Count, expectedCount);
            Assert.True(vm.Personas.Where(x => x.Id == persona.Id).ToList().Count == 0);
            Assert.True(vm.ProximasCitas.All(x => x.Persona.Id != persona.Id));
            Assert.True(vm.Atenciones.All(x => x.Cita.Persona.Id != persona.Id));
        }

        [Fact]
        private void NuevaAtencionShouldAddLaAtencion()
        {
            ///
            /// Arrange
            ///
            var atencion = new Atencion { Id = int.MaxValue };
            _AtencionRepositoryMock.Setup(p => p.GetById(atencion.Id)).Returns(atencion);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = _Atenciones.Count + 1;

            ///
            /// Act
            ///
            eventAggregator.GetEvent<AtencionCreadaEvent>().Publish(atencion.Id);

            ///
            /// Assert
            ///
            Assert.Equal(vm.Atenciones.Count, expectedCount);
            Assert.True(vm.Atenciones.Where(x => x.Id == atencion.Id).ToList().Count == 1);
        }

        [Fact]
        private void AtencionActualizadaEventShouldUpdateLaAtencion()
        {
            ///
            /// Arrange
            ///
            var atencionAntesDeActualizar = _Atenciones.First();
            var atencionActualizada = new Atencion { Id = atencionAntesDeActualizar.Id };
            atencionActualizada.CopyValuesFrom(atencionAntesDeActualizar);
            _AtencionRepositoryMock.Setup(p => p.GetById(atencionAntesDeActualizar.Id)).Returns(atencionActualizada);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            string expectedSeguimiento = "Otro seguimiento";
            bool expectedEsSocial = true;

            ///
            /// Act
            ///
            atencionActualizada.Seguimiento = expectedSeguimiento;
            atencionActualizada.EsSocial = expectedEsSocial;
            eventAggregator.GetEvent<AtencionActualizadaEvent>().Publish(atencionActualizada.Id);

            ///
            /// Assert
            ///
            var atencionSupuestamenteActualizada = vm.Atenciones.Where(x => x.Id == atencionActualizada.Id).First();
            Assert.Equal(atencionSupuestamenteActualizada.Seguimiento, atencionActualizada.Seguimiento);
            Assert.Equal(expectedSeguimiento, atencionSupuestamenteActualizada.Seguimiento);
            Assert.Equal(atencionSupuestamenteActualizada.EsSocial, atencionActualizada.EsSocial);
            Assert.Equal(expectedEsSocial, atencionSupuestamenteActualizada.EsSocial);
        }

        [Fact]
        private void AtencionEliminadaEventShouldEliminarLaAtencion()
        {
            ///
            /// Arrange
            ///
            var atencion = _Atenciones.First();

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = _Citas.Count - 1;

            ///
            /// Act
            ///
            eventAggregator.GetEvent<AtencionEliminadaEvent>().Publish(atencion.Id);

            ///
            /// Assert
            ///
            Assert.Equal(vm.Atenciones.Count, expectedCount);
            Assert.True(vm.Atenciones.Where(x => x.Id == atencion.Id).ToList().Count == 0);
        }

        [Fact]
        private void NuevaCitaShouldAddLaCita()
        {
            //
            // Arrange
            //
            var cita = new Cita { Id = int.MaxValue };

            _CitaRepositoryMock.Setup(p => p.GetById(It.IsAny<int>())).Returns(cita);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = vm.ProximasCitas.Count + 1;

            //
            // Act
            //
            eventAggregator.GetEvent<CitaCreadaEvent>().Publish(cita.Id);

            //
            // Assert
            //
            Assert.Equal(expectedCount, vm.ProximasCitas.Count);
            Assert.True(vm.ProximasCitas.Where(x => x.Id == cita.Id).ToList().Count == 1);
        }

        [Fact]
        private void CitaActualizadaEventShouldUpdateLaCita()
        {
            ///
            /// Arrange
            ///
            var citaAntesDeActualizar = _Citas.First();
            var citaActualizada = new Cita { Id = citaAntesDeActualizar.Id };
            citaActualizada.CopyValuesFrom(citaAntesDeActualizar);
            _CitaRepositoryMock.Setup(p => p.GetById(citaAntesDeActualizar.Id)).Returns(citaActualizada);

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            string expectedSala = "Otro sala";
            DateTime expectedFecha = DateTime.Now.AddDays(4);

            ///
            /// Act
            ///
            citaActualizada.Sala = expectedSala;
            citaActualizada.Fecha = expectedFecha;
            eventAggregator.GetEvent<CitaActualizadaEvent>().Publish(citaActualizada.Id);

            ///
            /// Assert
            ///
            var citaSupuestamenteActualizada = vm.ProximasCitas.Where(x => x.Id == citaActualizada.Id).First();
            Assert.Equal(citaSupuestamenteActualizada.Sala, citaActualizada.Sala);
            Assert.Equal(expectedSala, citaSupuestamenteActualizada.Sala);
            Assert.Equal(citaSupuestamenteActualizada.Fecha, citaActualizada.Fecha);
            Assert.Equal(expectedFecha, citaSupuestamenteActualizada.Fecha);
        }

        [Fact]
        private void CitaEliminadaEventShouldEliminarLaCitaYLaAtencionAsociada()
        {
            ///
            /// Arrange
            ///
            var cita = _Citas.First();

            var eventAggregator = new EventAggregator();

            var vm = new DashboardViewModel(
                _PersonaRepositoryMock.Object,
                _CitaRepositoryMock.Object,
                _AtencionRepositoryMock.Object,
                eventAggregator,
                _Settings,
                _SessionMock.Object);

            int expectedCount = _Citas.Count - 1;

            ///
            /// Act
            ///
            eventAggregator.GetEvent<CitaEliminadaEvent>().Publish(cita.Id);

            ///
            /// Assert
            ///
            Assert.Equal(vm.ProximasCitas.Count, expectedCount);
            Assert.True(vm.ProximasCitas.Where(x => x.Id == cita.Id).ToList().Count == 0);
            Assert.True(vm.Atenciones.All(x => x.Cita.Id != cita.Id));
        }
    }
}


text:
/**
 *
 */
package org.openforis.calc.transformation;

import javax.annotation.PostConstruct;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author M. Togna
 *
 */
@Deprecated
@Component
public class TransformationDatabase {

	private static final String DB_META_NAME = "calcDb";

	@Value("${calc.jdbc.host}")
	private String host;
	@Value("${calc.jdbc.port}")
	private String port;
	@Value("${calc.jdbc.db}")
	private String db;
	@Value("${calc.jdbc.username}")
	private String user;
	@Value("${calc.jdbc.password}")
	private String pass;
//	@Value("${calc.jdbc.schema}")
//	private String schema;
	private DatabaseMeta databaseMeta;

	public TransformationDatabase() {
	}

	public DatabaseMeta getDatabaseMeta() {
		return databaseMeta;
	}

	@PostConstruct
	protected void init() throws KettleException{
		KettleEnvironment.init();
		databaseMeta = new DatabaseMeta(DB_META_NAME, "postgreSQL", null, host, db, port, user, pass);
	}
}


text:
This Algorithmic art generator is to create and show an understanding that everyone is unique and not everyone has the same perseptions.
Through the generated art I wanted to express the differences people have and create art to show that beauty is not perfection.

(it draws feet)

The project is built using Nodejs and Paperjs.
## Installing
sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
1. Install node
    * [https://nodejs.org/en/](https://nodejs.org/en/)
1. Install [npm](https://www.npmjs.org) dependencies
    * `npm install`

## Running the site
1. `DEBUG=walls.cool:* npm start`
1. on web browser
   * [http://localhost:3000](http://localhost:3000)


text:
https://docs.docker.com/engine/installation/

## Install docker-compose

```
pip3 install docker-compose
```

Create an alias for docker-compose command
```
alias dc=docker-compose
```

## Build the image
```
dc build
dc create
docker network create impaladocker_default
```

## Create the .env file
```
AWS_SECRET_ACCESS_KEY=your_secret
AWS_ACCESS_KEY_ID=your_key
S3_DEFAULT_BUCKET=your_bucket
```

## Start Impala
```
dc start
```

## Test impala on s3
```
dc exec worker impala-shell
```
If you see that your are not connected, do CTRL-D and retry a bit later.
To make sure all the processes are up, you shoud do :
```
dc ps
```
(It's normal that impala-base is not up)

###SQL
```
CREATE DATABASE  s3test LOCATION 's3a://your_bucket/impala-db-in-docker';
CREATE EXTERNAL TABLE s3test.smallParquet ( a INT, b STRING) STORED AS PARQUET LOCATION  's3a://your_bucket/impala-db-in-docker/smallParquet';
INSERT INTO s3test.smallParquet VALUES (1,'2');
SELECT * from s3test.smallParquet;
```

Validate that the data is there :
```
dc exec worker aws s3 ls s3://your_bucket/impala-db-in-docker/smallParquet/
```


text:
As the name suggests, the Generic Skeleton Website is a skeleton website/webapp that can
be the base of any new starting web based project.

It makes heavy use of javascript **Asynchronous Module Definition (AMD)** for the front end
development, following a **Model-View-Controller (MVC)** pattern.

Stay tuned for more updates!!


text:
<?php

declare(strict_types=1);

namespace Kreait\Firebase\JWT\Action\FetchGooglePublicKeys;

use Kreait\Firebase\JWT\Action\FetchGooglePublicKeys;
use Kreait\Firebase\JWT\Contract\Expirable;
use Kreait\Firebase\JWT\Contract\Keys;
use Kreait\Firebase\JWT\Error\FetchingGooglePublicKeysFailed;
use Psr\Cache\CacheItemPoolInterface;
use StellaMaris\Clock\ClockInterface;

/**
 * @internal
 */
final class WithPsr6Cache implements Handler
{
    private Handler $handler;

    private CacheItemPoolInterface $cache;

    private ClockInterface $clock;

    public function __construct(Handler $handler, CacheItemPoolInterface $cache, ClockInterface $clock)
    {
        $this->handler = $handler;
        $this->cache = $cache;
        $this->clock = $clock;
    }

    public function handle(FetchGooglePublicKeys $action): Keys
    {
        $now = $this->clock->now();
        $cacheKey = \md5(\get_class($action));

        /** @noinspection PhpUnhandledExceptionInspection */
        $cacheItem = $this->cache->getItem($cacheKey);

        /** @var Keys|Expirable|null $keys */
        $keys = $cacheItem->get();

        // We deliberately don't care if the cache item is expired here, as long as the keys
        // themselves are not expired
        if ($keys instanceof Keys && $keys instanceof Expirable && !$keys->isExpiredAt($now)) {
            return $keys;
        }

        // Non-expiring keys coming from a cache hit can be returned as well
        if ($keys instanceof Keys && !($keys instanceof Expirable) && $cacheItem->isHit()) {
            return $keys;
        }

        // At this point, we have to re-fetch the keys, because either the cache item is a miss
        // or the value in the cache item is not a Keys object

        // We need fresh keys
        try {
            $keys = $this->handler->handle($action);
        } catch (FetchingGooglePublicKeysFailed $e) {
            $reason = \sprintf(
                'The inner handler of %s (%s) failed in fetching keys: %s',
                __CLASS__,
                \get_class($this->handler),
                $e->getMessage()
            );

            throw FetchingGooglePublicKeysFailed::because($reason, $e->getCode(), $e);
        }

        $cacheItem->set($keys);

        if ($keys instanceof Expirable) {
            $cacheItem->expiresAt($keys->expiresAt());
        } else {
            $cacheItem->expiresAfter($action->getFallbackCacheDuration()->value());
        }

        $this->cache->save($cacheItem);

        return $keys;
    }
}