text:
// ========================================================================
// Copyright (c) 2010 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.server.handler;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.AbstractHttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.IPAddressMap;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/**
 * IP Access Handler
 *

 * Controls access to the wrapped handler by the real remote IP. Control is provided
 * by white/black lists that include both internet addresses and URIs. This handler
 * uses the real internet address of the connection, not one reported in the forwarded
 * for headers, as this cannot be as easily forged.
 *

 * Typically, the black/white lists will be used in one of three modes:
 *

 *
Blocking a few specific IPs/URLs by specifying several black list entries.
 *
Allowing only some specific IPs/URLs by specifying several white lists entries.
 *
Allowing a general range of IPs/URLs by specifying several general white list
 * entries, that are then further refined by several specific black list exceptions
 *

 *

 * An empty white list is treated as match all. If there is at least one entry in
 * the white list, then a request must match a white list entry. Black list entries
 * are always applied, so that even if an entry matches the white list, a black list
 * entry will override it.
 *

 * Internet addresses may be specified as absolute address or as a combination of
 * four octet wildcard specifications (a.b.c.d) that are defined as follows.
 *

 *

 * nnn - an absolute value (0-255)
 * mmm-nnn - an inclusive range of absolute values,
 *           with following shorthand notations:
 *           nnn- => nnn-255
 *           -nnn => 0-nnn
 *           -    => 0-255
 * a,b,... - a list of wildcard specifications
 *

 *

 * Internet address specification is separated from the URI pattern using the "|" (pipe)
 * character. URI patterns follow the servlet specification for simple * prefix and
 * suffix wild cards (e.g. /, /foo, /foo/bar, /foo/bar/*, *.baz).
 *

 * Earlier versions of the handler used internet address prefix wildcard specification
 * to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
 * They also used the first "/" character of the URI pattern to separate it from the
 * internet address. Both of these features have been deprecated in the current version.
 *

 * Examples of the entry specifications are:
 *

 *
10.10.1.2 - all requests from IP 10.10.1.2
 *
10.10.1.2|/foo/bar - all requests from IP 10.10.1.2 to URI /foo/bar
 *
10.10.1.2|/foo/* - all requests from IP 10.10.1.2 to URIs starting with /foo/
 *
10.10.1.2|*.html - all requests from IP 10.10.1.2 to URIs ending with .html
 *
10.10.0-255.0-255 - all requests from IPs within 10.10.0.0/16 subnet
 *
10.10.0-.-255|/foo/bar - all requests from IPs within 10.10.0.0/16 subnet to URI /foo/bar
 *
10.10.0-3,1,3,7,15|/foo/* - all requests from IPs addresses with last octet equal
 *                                  to 1,3,7,15 in subnet 10.10.0.0/22 to URIs starting with /foo/
 *

 *

 * Earlier versions of the handler used internet address prefix wildcard specification
 * to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
 * They also used the first "/" character of the URI pattern to separate it from the
 * internet address. Both of these features have been deprecated in the current version.
 */
public class IPAccessHandler extends HandlerWrapper
{
    private static final Logger LOG = Log.getLogger(IPAccessHandler.class);

    IPAddressMap<PathMap> _white = new IPAddressMap<PathMap>();
    IPAddressMap<PathMap> _black = new IPAddressMap<PathMap>();

    /* ------------------------------------------------------------ */
    /**
     * Creates new handler object
     */
    public IPAccessHandler()
    {
        super();
    }

    /* ------------------------------------------------------------ */
    /**
     * Creates new handler object and initializes white- and black-list
     *
     * @param white array of whitelist entries
     * @param black array of blacklist entries
     */
    public IPAccessHandler(String[] white, String []black)
    {
        super();

        if (white != null && white.length > 0)
            setWhite(white);
        if (black != null && black.length > 0)
            setBlack(black);
    }

    /* ------------------------------------------------------------ */
    /**
     * Add a whitelist entry to an existing handler configuration
     *
     * @param entry new whitelist entry
     */
    public void addWhite(String entry)
    {
        add(entry, _white);
    }

    /* ------------------------------------------------------------ */
    /**
     * Add a blacklist entry to an existing handler configuration
     *
     * @param entry new blacklist entry
     */
    public void addBlack(String entry)
    {
        add(entry, _black);
    }

    /* ------------------------------------------------------------ */
    /**
     * Re-initialize the whitelist of existing handler object
     *
     * @param entries array of whitelist entries
     */
    public void setWhite(String[] entries)
    {
        set(entries, _white);
    }

    /* ------------------------------------------------------------ */
    /**
     * Re-initialize the blacklist of existing handler object
     *
     * @param entries array of blacklist entries
     */
    public void setBlack(String[] entries)
    {
        set(entries, _black);
    }

    /* ------------------------------------------------------------ */
    /**
     * Checks the incoming request against the whitelist and blacklist
     *
     * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        // Get the real remote IP (not the one set by the forwarded headers (which may be forged))
        AbstractHttpConnection connection = baseRequest.getConnection();
        if (connection!=null)
        {
            EndPoint endp=connection.getEndPoint();
            if (endp!=null)
            {
                String addr = endp.getRemoteAddr();
                if (addr!=null && !isAddrUriAllowed(addr,baseRequest.getPathInfo()))
                {
                    response.sendError(HttpStatus.FORBIDDEN_403);
                    baseRequest.setHandled(true);
                    return;
                }
            }
        }

        getHandler().handle(target,baseRequest, request, response);
    }

    /* ------------------------------------------------------------ */
    /**
     * Helper method to parse the new entry and add it to
     * the specified address pattern map.
     *
     * @param entry new entry
     * @param patternMap target address pattern map
     */
    protected void add(String entry, IPAddressMap<PathMap> patternMap)
    {
        if (entry != null && entry.length() > 0)
        {
            boolean deprecated = false;
            int idx;
            if (entry.indexOf('|') > 0 )
            {
                idx = entry.indexOf('|');
            }
            else
            {
                idx = entry.indexOf('/');
                deprecated = (idx >= 0);
            }

            String addr = idx > 0 ? entry.substring(0,idx) : entry;
            String path = idx > 0 ? entry.substring(idx) : "/*";

            if (addr.endsWith("."))
                deprecated = true;
            if (path!=null && (path.startsWith("|") || path.startsWith("/*.")))
                path=path.substring(1);

            PathMap pathMap = patternMap.get(addr);
            if (pathMap == null)
            {
                pathMap = new PathMap(true);
                patternMap.put(addr,pathMap);
            }
            if (path != null)
                pathMap.put(path,path);

            if (deprecated)
                LOG.debug(toString() +" - deprecated specification syntax: "+entry);
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Helper method to process a list of new entries and replace
     * the content of the specified address pattern map
     *
     * @param entries new entries
     * @param patternMap target address pattern map
     */
    protected void set(String[] entries,  IPAddressMap<PathMap> patternMap)
    {
        patternMap.clear();

        if (entries != null && entries.length > 0)
        {
            for (String addrPath:entries)
            {
                add(addrPath, patternMap);
            }
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Check if specified request is allowed by current IPAccess rules.
     *
     * @param addr internet address
     * @param path context path
     * @return true if request is allowed
     *
     */
    protected boolean isAddrUriAllowed(String addr, String path)
    {
        if (_white.size()>0)
        {
            boolean match = false;

            Object whiteObj = _white.getLazyMatches(addr);
            if (whiteObj != null)
            {
                List whiteList = (whiteObj instanceof List) ? (List)whiteObj : Collections.singletonList(whiteObj);

                for (Object entry: whiteList)
                {
                    PathMap pathMap = ((Map.Entry<String,PathMap>)entry).getValue();
                    if (match = (pathMap!=null && (pathMap.size()==0 || pathMap.match(path)!=null)))
                        break;
                }
            }

            if (!match)
                return false;
        }

        if (_black.size() > 0)
        {
            Object blackObj = _black.getLazyMatches(addr);
            if (blackObj != null)
            {
                List blackList = (blackObj instanceof List) ? (List)blackObj : Collections.singletonList(blackObj);

                for (Object entry: blackList)
                {
                    PathMap pathMap = ((Map.Entry<String,PathMap>)entry).getValue();
                    if (pathMap!=null && (pathMap.size()==0 || pathMap.match(path)!=null))
                        return false;
                }
            }
        }

        return true;
    }

    /* ------------------------------------------------------------ */
    /**
     * Dump the white- and black-list configurations when started
     *
     * @see org.eclipse.jetty.server.handler.HandlerWrapper#doStart()
     */
    @Override
    protected void doStart()
        throws Exception
    {
        super.doStart();

        if (LOG.isDebugEnabled())
        {
            System.err.println(dump());
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Dump the handler configuration
     */
    public String dump()
    {
        StringBuilder buf = new StringBuilder();

        buf.append(toString());
        buf.append(" WHITELIST:\n");
        dump(buf, _white);
        buf.append(toString());
        buf.append(" BLACKLIST:\n");
        dump(buf, _black);

        return buf.toString();
    }

    /* ------------------------------------------------------------ */
    /**
     * Dump a pattern map into a StringBuilder buffer
     *
     * @param buf buffer
     * @param patternMap pattern map to dump
     */
    protected void dump(StringBuilder buf, IPAddressMap<PathMap> patternMap)
    {
        for (String addr: patternMap.keySet())
        {
            for (Object path: ((PathMap)patternMap.get(addr)).values())
            {
                buf.append("# ");
                buf.append(addr);
                buf.append("|");
                buf.append(path);
                buf.append("\n");
            }
        }
    }
 }


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Bloom.Book;
using Bloom.Collection;
using CommandLine;
using SIL.IO;
using SIL.Progress;

namespace Bloom.CLI
{
	/// <summary>
	/// This command needs to
	/// * set the xmatter to something appropriate
	/// * set the layout to something appropriate
	/// * set the L1, L2, and L3 languages
	/// * Spread all the above around, as if the book had been loaded in Bloom
	/// * Make sure it has all the needed stylesheets
	/// </summary>
	class HydrateBookCommand
	{
		public static int Handle(HydrateParameters options)
		{
			if (!Directory.Exists(options.Path))
			{
				if (options.Path.Contains(".htm"))
				{
					Debug.WriteLine("Supply only the directory, not the path to the file.");
					Console.Error.WriteLine("Supply only the directory, not the path to the file.");
				}
				else
				{
					Debug.WriteLine("Could not find " + options.Path);
					Console.Error.WriteLine("Could not find " + options.Path);
				}
				return 1;
			}
			Console.WriteLine("Starting Hydrating.");

			var layout = new Layout
			{
				SizeAndOrientation = SizeAndOrientation.FromString(options.SizeAndOrientation)
			};

			var collectionSettings = new CollectionSettings
			{
				XMatterPackName = options.XMatter,
				Language1Iso639Code = options.VernacularIsoCode,
				Language2Iso639Code = options.NationalLanguage1IsoCode,
				Language3Iso639Code = options.NationalLanguage2IsoCode
			};

			XMatterPackFinder xmatterFinder = new XMatterPackFinder(new[] { BloomFileLocator.GetInstalledXMatterDirectory() });
			var locator = new BloomFileLocator(collectionSettings, xmatterFinder, ProjectContext.GetFactoryFileLocations(),
				ProjectContext.GetFoundFileLocations(), ProjectContext.GetAfterXMatterFileLocations());

			var bookInfo = new BookInfo(options.Path, true);
			var book = new Book.Book(bookInfo, new BookStorage(options.Path, locator, new BookRenamedEvent(), collectionSettings),
				null, collectionSettings, null, null, new BookRefreshEvent());

			if (collectionSettings.XMatterPackName == "Video")
			{
				if (null == book.OurHtmlDom.SelectSingleNodeHonoringDefaultNS("//script[contains(text(),'bloomPlayer.js')]"))
				{
					var element = book.OurHtmlDom.Head.AppendChild(book.OurHtmlDom.RawDom.CreateElement("script")) as XmlElement;
					element.IsEmpty = false;
					element.SetAttribute("type", "text/javascript");
					element.SetAttribute("src", "bloomPlayer.js");
				}

				AddRequisiteJsFiles(options.Path);
			}

			//we might change this later, or make it optional, but for now, this will prevent surprises to processes
			//running this CLI... the folder name won't change out from under it.
			book.LockDownTheFileAndFolderName = true;

			book.SetLayout(layout);
			book.BringBookUpToDate(new NullProgress());
			Console.WriteLine("Finished Hydrating.");
			Debug.WriteLine("Finished Hydrating.");
			return 0;
		}

		private static void AddRequisiteJsFiles(string path)
		{
			const string bloomPlayerFileName = "bloomPlayer.js";
			var bloomLibraryJsPath = FileLocator.GetFileDistributedWithApplication(bloomPlayerFileName);
			RobustFile.Copy(bloomLibraryJsPath, Path.Combine(path, bloomPlayerFileName), true);
		}
	}
}

// Used with https://github.com/gsscoder/commandline, which we get via nuget.
// (using the beta of commandline 2.0, as of Bloom 3.8)

[Verb("hydrate", HelpText = "Apply XMatter, Page Size/Orientation, and Languages. Used by automated converters and app makers.")]
public class HydrateParameters
{
	public enum PresetOption
	{
		App,
		Shellbook
	}

	private PresetOption _preset;
	private string _sizeAndOrientation;
	private string _xMatter;
	private string _nationalLanguage1IsoCode;
	private string _nationalLanguage2IsoCode;

	[Option("bookpath", HelpText = "path to the book", Required = true)]
	public string Path { get; set; }

	// When a book is opened in a collection, Bloom gathers the vernacular, national, and regional languages
	// from the collection settings and makes changes to the html so that, for example, the current vernacular
	// shows on each page, rather than in the source bubbles. It does that by adding classes such as "content1".
	// The command being defined here can do that, too. This is needed for cases where, for example, the user
	// selects a book from BloomLibrary and wants to make an app out of it for his language. But his language
	// might not be the one that was "l1" when the book was uploaded. Using these parameters, the program making
	// him an app can specify that this language should be the l1.

	[Option("vernacularisocode", HelpText = "iso code of primary language", Required = true)]
	public string VernacularIsoCode { get; set; }

	[Option("nationallanguage1isocode", HelpText = "iso code of secondary language", Default = "", Required = false)]
	public string NationalLanguage1IsoCode
	{
		//"Default" is not working
		get { return _nationalLanguage1IsoCode ?? string.Empty; }
		set { _nationalLanguage1IsoCode = value; }
	}

	[Option("nationallanguage2isocode", HelpText = "iso code of tertiary language", Default = "", Required = false)]
	public string NationalLanguage2IsoCode
	{
		//"Default" is not working
		get { return _nationalLanguage2IsoCode ?? string.Empty; }
		set { _nationalLanguage2IsoCode = value; }
	}

	[Option("preset", HelpText = "alternative to specifying layout and xmatter. Supported values are 'app' and 'shellbook'", Required = false)]
	public string Preset {
		get { return _preset.ToString().ToLowerInvariant(); }
		set
		{
			switch (value.ToLowerInvariant())
			{
				case "app":
					_preset = PresetOption.App;
					SizeAndOrientation = "Device16x9Landscape";
					XMatter = "Video";
					break;
				case "shellbook":
					_preset = PresetOption.Shellbook;
					SizeAndOrientation = "A5Portrait";
					XMatter = "Traditional";
					break;
				default:
					throw new ArgumentException("{0} is not a valid preset. Valid values are 'app' and 'shellbook'.", value);
			}
		}
	}

	[Option("sizeandorientation", HelpText = "desired size & orientation", Required = false)]
	public string SizeAndOrientation
	{
		get
		{
			if (string.IsNullOrEmpty(_sizeAndOrientation))
			{
				return "Device16x9Landscape";
			}

			return _sizeAndOrientation;
		}
		set { _sizeAndOrientation = value; }
	}

	[Option("xmatter", HelpText = "front/back matter pack to apply. E.g. 'Video', 'Factory'", Required = false)]
	public string XMatter
	{
		get
		{
			if (string.IsNullOrEmpty(_xMatter))
			{
				return "Video";
			}

			return _xMatter;
		}
		set { _xMatter = value; }
	}

	/*
	[Option("multilinguallevel", HelpText = "value of either 1, 2, or 3 (monolingual, bilingual, trilingual)", Required = false)]
	public int MultilingualLevel { get; set; }
	*/
}

//Enhance: someday we could gather more info. For now, we assume the caller
//wants to make an app. We assume Bloom can look inside the app to determine
//if a video-style or book-style xmatter is appropriate.

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "PHP-ABAC, la nouvelle librairie Open-Source de gestion des droits, by Kilix"
description: "Contrôler les accès dans son application à l'aide des attributs de l'utilisateur, des ressources et de l'environnement, une nouvelle façon d'appréhender la gestion des droits !"
date:   2015-11-16 19:12:36
author: Axel Venet
category: backend
tags: [backend, security, access-control]
---

Aujourd'hui, Kilix publie sur Github son premier projet open-source ([lien ici](https://github.com/Kilix/php-abac)).

Celui-ci consiste en l'implémentation en PHP d'un concept de gestion d'accès : ABAC (Attribute-Based Access-Control).

<!--more-->

Au cours de notre vie d'agence et de nos projets, nous avions flirté avec un concept voisin : RBAC (Role-Based Access-Control).
Une des [principales librairies PHP implémentant RBAC](https://github.com/OWASP/rbac), que nous avons donc testé, emploie deux arbres hiérarchiques distincts :
l'un dédié aux rôles tandis que l'autre à des permissions.
Un rôle pouvait ensuite être lié à une ou plusieurs permissions.
L'application intégrant RBAC contrôle ensuite que l'utilisateur dispose bien d'une permission donnée au travers des rôles qui lui sont assignés.

<img src="http://phprbac.net/img/rbac.png" alt="Drawing" style="width: 600px;"/>

Cependant, au sein de nos projets, le thème de la gestion des droits a été fortement challengé par des besoins métiers très spécifiques.
Se baser uniquement sur la possession d'une permission pour déterminer l'accès à une ressource ou à une action n'était pas suffisant pour répondre à ces besoins.
Nous avions dès lors besoin de la notion de contextualisation, pour définir le droit d'accès à une ressource, non seulement selon l'utilisateur, mais aussi selon la ressource accédée.

Par exemple, pour éditer un article de blog, il n'est parfois pas suffisant de contrôler une permission ``edit_article`` ou un rôle ``ROLE_CONTRIBUTOR``.
Des informations supplémentaires doivent être contrôlées, comme par exemple la propriété de l'article (à un groupe ou à son auteur), le statut de l'article (publié, archivé...).

Pour répondre à cette problématique, nous avons utilisé sur nos projets Symfony2 la notion de ``SecurityVoter``, ce qui nous a permis de répondre au besoin.
Mais l'idée d'une librairie générique dédiée à ce type de gestion des droits était lancée. Une librairie où la contextualisation serait nativement gérée.

Par le biais d'un [document de spécification du NIST](http://nvlpubs.nist.gov/nistpubs/specialpublications/NIST.sp.800-162.pdf), nous avons découvert le concept d'ABAC.
Cette fois-ci, plutôt que de se baser sur les rôles d'un utilisateur, cette philosophie de contrôle d'accès se repose sur la notion d'attributs.
Non seulement les attributs de l'utilisateur, mais également les attributs de la ressource accédée et de l'environnement.
Ceci permet de pouvoir contrôler l'accès selon l'utilisateur mais aussi selon la ressource à laquelle on veut accéder !
De plus, la notion de rôles et de permissions peut être conservée. Il suffit de considérer ces derniers comme étant des attributs de l'utilisateur. RBAC peut donc être une composante au sein d'ABAC !

![image alt text](http://ef67fc04ce9b132c2b32-8aedd782b7d22cfe0d1146da69a52436.r14.cf1.rackcdn.com/guidance-aims-to-ease-access-control-eresource-1-a-5706.jpg)

Pour ce faire, nous définissons des "Policy Rules", des règles qui vont déterminer quels attributs l'utilisateur, la ressource et l'environnement doivent avoir pour que la règle soit vérifiée et l'accès autorisé.
Chaque règle va donc contenir un ensemble d'attributs avec des valeurs attendues, et un système de comparaison.
Grâce à cela, nous allons pouvoir effectuer des vérifications "complexes", par exemple vérifier qu'un utilisateur a bien passé son code il y a moins de 5 ans pour pouvoir s'inscrire à l'auto-école en épreuve de conduite.

Tout cela est stocké en base de données, la définition des règles tout comme les attributs visés, la librairie récupérant les attributs directement via des requêtes SQL dynamiques.
Pour le moment, la librairie dans sa version MVP supporte uniquement un fonctionnement sous Mysql, mais une évolution incluant le fonctionnement sous d'autres bases de données peut être envisagée.

D'autres évolutions peuvent être apportées à cette librairie. Sa version MVP peut être améliorée, et nous sommes vigilants vis-à-vis des feedbacks que nous espérons obtenir. Dans une approche Agile, nous comptons être à l'écoute des utilisateurs, et grâce à leur expérience, améliorer cette librairie, faciliter son utilisation, la rendre confortable malgré la complexité qu'elle tente de génériser.

Nous sommes également ouverts à toute contribution directe. N'hésitez pas à forker le dépôt, effectuer vos modifications et ensuite nous soumettre une Pull Request, ce sera avec plaisir que nous la challengerons avec vous pour l'intégrer !

Merci pour votre lecture !


text:
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement

#include "type_.CImageAnnotationStatement.h"

namespace AIMXML
{

class CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement : public ::AIMXML::CImageAnnotationStatement
{
public:
	AIMXML_EXPORT CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement(xercesc::DOMNode* const& init);
	AIMXML_EXPORT CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement(CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement const& init);
	void operator=(CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement const& other) { m_node = other.m_node; }
	static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_altova_CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement); }
	AIMXML_EXPORT void SetXsiType();
};

}	// namespace AIMXML

#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CThreeDimensionGeometricShapeEntityExcludesThreeDimensionGeometricShapeEntityStatement


text:
__g_inst_QrCodeM2Renderer__ = new QrCodeM2Renderer();
__g_inst_QrCodeMCRenderer__ = new QrCodeMCRenderer();
__g_inst_QrCodeM1Renderer__ = new QrCodeM1Renderer();
__g_inst_Dmatx200Renderer__ = new DataMatrixECC200Renderer();

/// JQuery plugin of QR Code model2 renderer.
$.fn.paintQrCodeM2 = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var mat = __g_inst_QrCodeM2Renderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    if (i < mat.length) {
      __g_inst_QrCodeM2Renderer__.drawSymbol(this, px, py, dotsize, mat[i]);
    }
    i++;
  });
}

///
$.fn.paintQrCodeM2_SVG = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var canvsizeX = (__g_qrm2matsize__[version] * dotsize) + (px * 2);
  var canvsizeY = (__g_qrm2matsize__[version] * dotsize) + (py * 2);
  var mat = __g_inst_QrCodeM2Renderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    var svg = "";
    if (i < mat.length) {
      svg = __g_inst_QrCodeM2Renderer__.toSymbolSVG(
        canvsizeX.toString() + "cm", canvsizeY.toString() + "cm",
        "black", px, py, dotsize, "cm", mat[i]);
    }
    this.innerHTML = svg;
    i++;
  });
}

/// JQuery plugin of Micro QR Code renderer.
$.fn.paintQrCodeMC = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var mat = __g_inst_QrCodeMCRenderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    if (i < mat.length) {
      __g_inst_QrCodeMCRenderer__.drawSymbol(this, px, py, dotsize, mat[i]);
    }
    i++;
  });
}

///
$.fn.paintQrCodeMC_SVG = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var canvsizeX = (__g_qrm2matsize__[version] * dotsize) + (px * 2);
  var canvsizeY = (__g_qrm2matsize__[version] * dotsize) + (py * 2);
  var mat = __g_inst_QrCodeMCRenderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    var svg = "";
    if (i < mat.length) {
      svg = __g_inst_QrCodeMCRenderer__.toSymbolSVG(
        canvsizeX.toString() + "cm", canvsizeY.toString() + "cm",
        "black", px, py, dotsize, "cm", mat[i]);
    }
    this.innerHTML = svg;
    i++;
  });
}

/// JQuery plugin of QR Code model1 renderer.
$.fn.paintQrCodeM1 = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var mat = __g_inst_QrCodeM1Renderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    if (i < mat.length) {
      __g_inst_QrCodeM1Renderer__.drawSymbol(this, px, py, dotsize, mat[i]);
    }
    i++;
  });
}

///
$.fn.paintQrCodeM1_SVG = function(version, level, mode, charset, data, px, py, dotsize, mask) {
  var canvsizeX = (__g_qrm1matsize__[version] * dotsize) + (px * 2);
  var canvsizeY = (__g_qrm1matsize__[version] * dotsize) + (py * 2);
  var mat = __g_inst_QrCodeM1Renderer__.createSymbol(data, version, level, mode, charset, mask);
  var i = 0;
  return this.each(function() {
    var svg = "";
    if (i < mat.length) {
      svg = __g_inst_QrCodeM1Renderer__.toSymbolSVG(
        canvsizeX.toString() + "cm", canvsizeY.toString() + "cm",
        "black", px, py, dotsize, "cm", mat[i]);
    }
    this.innerHTML = svg;
    i++;
  });
}

/// JQuery plugin of DataMatric (ECC200) renderer.
$.fn.paintDmatx200 = function(nrow, ncol, mode, charset, data, px, py, dotsize) {
  var mat = __g_inst_Dmatx200Renderer__.createSymbol(data, nrow, ncol, mode, charset);
  var i = 0;
  return this.each(function() {
    if (i < mat.length) {
      __g_inst_Dmatx200Renderer__.drawSymbol(this, px, py, dotsize, mat[i][1], mat[i][0][1], mat[i][0][0]);
    }
    i++;
  });
}

/// JQuery plugin
$.fn.clearCanvas = function() {
  return this.each(function() {
    this.getContext("2d").clearRect(0, 0, this.width, this.height);
  });
}


text:
using System;

using Easylink;
using Easylink.Tests;
using Easylink.Tests.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EasylinkApp.Tests
{
    [TestClass]
    public class InheritedMappingTest
    {
        protected IDatabase database;

        [TestInitialize]
        public void Test_Initialization()
        {

            var dbConfig = new DbConfig()
            {
                ConnectionString = @"Server=meng\sqlexpress;Database=easylink;User Id=easylink; Password=password;",
                DatabaseType = DatabaseType.SqlServer,
                SchemaName = "dbo",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);

            database = DatabaseFactory.Create();

            Mapping.SetNextId<BusinessTax>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<PropertyTax>(NextIdOption.AutoIncrement);

        }

        [TestMethod]
        public void tax_should_insert_property_tax()
        {

            Action procedure = () =>
            {
                var propertyTax = FakeTax.GetFakePropertyTax();

                database.Insert(propertyTax);

                var propertyTaxRetrieved = database.RetrieveObject<PropertyTax>(p => p.Id == propertyTax.Id);

                Assert.IsNotNull(propertyTaxRetrieved);

                Assert.IsTrue(propertyTaxRetrieved.TaxName == propertyTax.TaxName);
                Assert.IsTrue(propertyTaxRetrieved.City  == propertyTax.City);
                Assert.IsTrue(propertyTaxRetrieved.PropertyCode == propertyTax.PropertyCode);
                Assert.IsTrue(propertyTaxRetrieved.IsResidential  == propertyTax.IsResidential );
                Assert.IsTrue(propertyTaxRetrieved.TaxPayable  == propertyTax.TaxPayable);
                Assert.IsTrue(propertyTaxRetrieved.TaxRate == propertyTax.TaxRate);
                Assert.IsTrue(propertyTaxRetrieved.EffectiveDate == propertyTax.EffectiveDate);

            };

            database.ExecuteInTest(procedure);

        }

        [TestMethod]
        public void tax_should_insert_business_tax()
        {

            Action procedure = () =>
            {
                var businessTax = FakeTax.GetFakeBusinessTax();

                database.Insert(businessTax);

                var businessTaxRetrieved = database.RetrieveObject<BusinessTax>(b => b.Id == businessTax.Id);

                Assert.IsNotNull(businessTaxRetrieved);

                Assert.IsTrue(businessTaxRetrieved.TaxName == businessTax.TaxName);
                Assert.IsTrue(businessTaxRetrieved.CompanyName  == businessTax.CompanyName);
                Assert.IsTrue(businessTaxRetrieved.Contact== businessTax.Contact);
                Assert.IsTrue(businessTaxRetrieved.TaxDueDate == businessTax.TaxDueDate);
                Assert.IsTrue(businessTaxRetrieved.TaxableIncome == businessTax.TaxableIncome);
                Assert.IsTrue(businessTaxRetrieved.TaxRate == businessTax.TaxRate);
                Assert.IsTrue(businessTaxRetrieved.Waived  == businessTax.Waived);

            };

            database.ExecuteInTest(procedure);

        }

    }
}


text:
<idea-plugin>
  <extensionPoints>
    <extensionPoint name="remoteServer.type" interface="com.intellij.remoteServer.ServerType"/>
    <extensionPoint name="remoteServer.deploymentSource.type" interface="com.intellij.remoteServer.configuration.deployment.DeploymentSourceType"/>
    <extensionPoint name="remoteServer.viewContributor" interface="com.intellij.remoteServer.impl.runtime.ui.RemoteServersViewContributor"/>
  </extensionPoints>

  <extensions defaultExtensionNs="com.intellij">
    <applicationService serviceInterface="com.intellij.remoteServer.configuration.RemoteServersManager"
                        serviceImplementation="com.intellij.remoteServer.impl.configuration.RemoteServersManagerImpl"/>
    <applicationService serviceInterface="com.intellij.remoteServer.runtime.ServerConnectionManager"
                        serviceImplementation="com.intellij.remoteServer.impl.runtime.ServerConnectionManagerImpl"/>
    <applicationService serviceInterface="com.intellij.remoteServer.agent.RemoteAgentManager"
                        serviceImplementation="com.intellij.remoteServer.agent.impl.RemoteAgentManagerImpl"/>
    <applicationService serviceInterface="com.intellij.remoteServer.runtime.clientLibrary.ClientLibraryManager"
                        serviceImplementation="com.intellij.remoteServer.impl.runtime.clientLibrary.ClientLibraryManagerImpl"/>
    <applicationConfigurable instance="com.intellij.remoteServer.impl.configuration.RemoteServerListConfigurable"/>
    <programRunner implementation="com.intellij.remoteServer.impl.runtime.DeployToServerRunner"/>
    <projectService serviceInterface="com.intellij.remoteServer.runtime.ui.RemoteServersView"
                    serviceImplementation="com.intellij.remoteServer.impl.runtime.ui.RemoteServersViewImpl"/>
    <remoteServer.deploymentSource.type implementation="com.intellij.remoteServer.impl.configuration.deployment.ModuleDeploymentSourceType"/>
  </extensions>
  <application-components>
    <component>
      <implementation-class>com.intellij.remoteServer.impl.configuration.deployment.DeployToServerConfigurationTypesRegistrar</implementation-class>
    </component>
  </application-components>
  <project-components>
    <component>
      <implementation-class>com.intellij.remoteServer.impl.runtime.ui.ServersToolWindowOpener</implementation-class>
    </component>
  </project-components>

  <actions>
    <group id="RemoteServersViewToolbar">
      <action id="RemoteServers.RunServer" class="com.intellij.remoteServer.impl.runtime.ui.tree.actions.RunServerAction"/>
      <action id="RemoteServers.DebugServer" class="com.intellij.remoteServer.impl.runtime.ui.tree.actions.DebugServerAction"/>
      <action id="RemoteServers.StopServer" class="com.intellij.remoteServer.impl.runtime.ui.tree.actions.StopServerAction"/>
      <action id="RemoteServers.EditServer" class="com.intellij.remoteServer.impl.runtime.ui.tree.actions.EditConfigurationAction"/>
      <separator/>
      <action id="RemoteServers.DeployAll" class="com.intellij.remoteServer.impl.runtime.ui.tree.actions.DeployAllAction"/>
    </group>
  </actions>
</idea-plugin>


text:
package radium.executable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.ParserProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import radium.inject.Injectors;
import radium.inject.arg4j.Arg4jModule;

import com.google.inject.Injector;

public abstract class Executable {

	public static enum Status {

		SUCCESS(0), FAILURE(1);

		private int code;

		Status(int code) {
			this.code = code;
		}

		public int getCode() {
			return code;
		}
	}

	final private static Logger LOGGER = LoggerFactory.getLogger(Executable.class);

	public static Injector INJECTOR;

	private CmdLineParser parser;

	protected Executable() {
		super();
	}

	public static void execute(Class<? extends Executable> executableClass, String... arguments) {
		String executableClassSimpleName = executableClass.getSimpleName();
		// Let create the Guice injector.
		Injector injector = null;
		try {
			injector = Injectors.discoverInjector(new Arg4jModule(executableClass, arguments));
		} catch (CmdLineException e) {
			e.printStackTrace();
		}
		try {
			try {
				Method createInjectorMethod = executableClass.getMethod("createInjector");
				LOGGER.debug("Using createInjector() of {}", executableClassSimpleName);
				injector = (Injector) createInjectorMethod.invoke(null, injector);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
				e.printStackTrace();
				LOGGER.error("Unable to invoke createInjector", e);
				exit(Status.FAILURE);
			}
		} catch (NoSuchMethodException e) {
			LOGGER.debug("Using only the discovered injector");
		}
		INJECTOR = injector;

		// Now let's find the ParserProperties we are going to use with Args4j
		ParserProperties parserProperties = parserProperties();
		try {
			try {
				Method parserPropertiesMethod = executableClass.getMethod("parserProperties");
				LOGGER.debug("Using parserProperties() of {}", executableClassSimpleName);
				parserProperties = (ParserProperties) parserPropertiesMethod.invoke(null);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
				LOGGER.error("Unable to invoke createInjector()", e);
			}
		} catch (NoSuchMethodException e) {
			LOGGER.debug("Using the default parserProperties()");
			parserProperties = parserProperties();
		}

		// We can now instanciate the subclass of Executable.
		Executable executable = injector.getInstance(executableClass);

		/*CmdLineParser parser = new CmdLineParser(executable, parserProperties);
		executable.parser = parser;
		try {
			parser.parseArgument(arguments);
		} catch (CmdLineException e) {
			e.printStackTrace();
			usage(executableClass, parser);
			exit(Status.FAILURE);
		}*/

		Status status = executable.execute();
		exit(status);
	}

	public static Injector getInjector() {
		return INJECTOR;
	}

	protected static ParserProperties parserProperties() {
		return ParserProperties.defaults();
	}

	public static void usage(Class<? extends Executable> executableClass, CmdLineParser parser) {
		System.err.print(executableClass.getName());
		parser.printSingleLineUsage(System.err);
		System.err.println();
		parser.printUsage(System.err);
	}

	public void usage() {
		usage(getClass(), parser);
	}

	public static void exit(Status status) {
		System.exit(status.getCode());
	}

	public abstract Status execute();

}


text:
"""
sinecosine.py
Author: Mary Feyrer
Credit: colorpicker.com, Tess Snyder

Assignment:

In this assignment you must use *list comprehensions* to generate sprites that show the behavior
of certain mathematical functions: sine and cosine.

The sine and cosine functions are provided in the Python math library. These functions are used
to relate *angles* to *rectangular* (x,y) coordinate systems and can be very useful in computer
game design.

Unlike the last assignment using ggame`, this one will not provide any "skeleton" code to fill
in. You should use your submission for the Picture assignment
(https://github.com/HHS-IntroProgramming/Picture) as a reference for starting this assignment.

See:
https://github.com/HHS-IntroProgramming/Sine-Cosine/blob/master/README.md
for a detailed list of requirements for this assignment.

https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics
for general information on how to use ggame.

https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Programmed-Graphics
for general information on using list comprehensions to generate graphics.

http://brythonserver.github.io/ggame/
for detailed information on ggame.
"""
from ggame import App, Color, LineStyle, Sprite
from ggame import CircleAsset
from math import sin, cos, radians

red = Color(0xff0000, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
purple = Color(0x8E2EC9, 1.0)
thinline = LineStyle(1, black)

bluecircle = CircleAsset(5, thinline, blue)
redcircle = CircleAsset(5, thinline, red)
purplecircle = CircleAsset(5, thinline, purple)
xcoordinates = range(0, 360, 10)

sprites = [Sprite(bluecircle, (x+10, 100+100*sin(radians(x))+10)) for x in xcoordinates]
sprites = [Sprite(redcircle, (x+10, 100+100*cos(radians(x))+10)) for x in xcoordinates]
sprites = [Sprite(purplecircle, (100+100*cos(radians(x))+20, 400+100*sin(radians(x))-30)) for x in xcoordinates]

myapp = App()
myapp.run()


text:
//  ------------------------------------------------------------------------------------
//  Copyright (c) Microsoft Corporation
//  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
//
//  THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
//  CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
//  NON-INFRINGEMENT.
//
//  See the Apache Version 2.0 License for specific language governing permissions and
//  limitations under the License.
//  ------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MFWindowApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MFWindowApplication1")]
[assembly: AssemblyCopyright("Copyright ©  2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
"""
exec_command

Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining environment variables.

Provides functions:
  exec_command  --- execute command in a specified directory and
                    in the modified environment.
  find_executable --- locate a command using info from environment
                    variable PATH. Equivalent to posix `which`
                    command.

Author: Pearu Peterson <pearu@cens.ioc.ee>
Created: 11 January 2003

Requires: Python 2.x

Succesfully tested on:
  os.name | sys.platform | comments
  --------+--------------+----------
  posix   | linux2       | Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3
                           PyCrust 0.9.3, Idle 1.0.2
  posix   | linux2       | Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2
  posix   | sunos5       | SunOS 5.9, Python 2.2, 2.3.2
  posix   | darwin       | Darwin 7.2.0, Python 2.3
  nt      | win32        | Windows Me
                           Python 2.3(EE), Idle 1.0, PyCrust 0.7.2
                           Python 2.1.1 Idle 0.8
  nt      | win32        | Windows 98, Python 2.1.1. Idle 0.8
  nt      | win32        | Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests
                           fail i.e. redefining environment variables may
                           not work. FIXED: don't use cygwin echo!
                           Comment: also `cmd /c echo` will not work
                           but redefining environment variables do work.
  posix   | cygwin       | Cygwin 98-4.10, Python 2.3.3(cygming special)
  nt      | win32        | Windows XP, Python 2.3.3

Known bugs:
- Tests, that send messages to stderr, fail when executed from MSYS prompt
  because the messages are lost at some point.
"""

__all__ = ['exec_command','find_executable']

import os
import sys
import shlex

from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
from numpy.distutils.compat import get_exception

from numpy.compat import open_latin1

def temp_file_name():
    fo, name = make_temp_file()
    fo.close()
    return name

def get_pythonexe():
    pythonexe = sys.executable
    if os.name in ['nt','dos']:
        fdir,fn = os.path.split(pythonexe)
        fn = fn.upper().replace('PYTHONW','PYTHON')
        pythonexe = os.path.join(fdir,fn)
        assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
    return pythonexe

def splitcmdline(line):
    import warnings
    warnings.warn('splitcmdline is deprecated; use shlex.split',
                  DeprecationWarning)
    return shlex.split(line)

def find_executable(exe, path=None, _cache={}):
    """Return full path of a executable or None.

    Symbolic links are not followed.
    """
    key = exe, path
    try:
        return _cache[key]
    except KeyError:
        pass
    log.debug('find_executable(%r)' % exe)
    orig_exe = exe

    if path is None:
        path = os.environ.get('PATH',os.defpath)
    if os.name=='posix':
        realpath = os.path.realpath
    else:
        realpath = lambda a:a

    if exe.startswith('"'):
        exe = exe[1:-1]

    suffixes = ['']
    if os.name in ['nt','dos','os2']:
        fn,ext = os.path.splitext(exe)
        extra_suffixes = ['.exe','.com','.bat']
        if ext.lower() not in extra_suffixes:
            suffixes = extra_suffixes

    if os.path.isabs(exe):
        paths = ['']
    else:
        paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]

    for path in paths:
        fn = os.path.join(path, exe)
        for s in suffixes:
            f_ext = fn+s
            if not os.path.islink(f_ext):
                f_ext = realpath(f_ext)
            if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
                log.good('Found executable %s' % f_ext)
                _cache[key] = f_ext
                return f_ext

    log.warn('Could not locate executable %s' % orig_exe)
    return None

############################################################

def _preserve_environment( names ):
    log.debug('_preserve_environment(%r)' % (names))
    env = {}
    for name in names:
        env[name] = os.environ.get(name)
    return env

def _update_environment( **env ):
    log.debug('_update_environment(...)')
    for name,value in env.items():
        os.environ[name] = value or ''

def exec_command( command,
                  execute_in='', use_shell=None, use_tee = None,
                  _with_python = 1,
                  **env ):
    """ Return (status,output) of executed command.

    command is a concatenated string of executable and arguments.
    The output contains both stdout and stderr messages.
    The following special keyword arguments can be used:
      use_shell - execute `sh -c command`
      use_tee   - pipe the output of command through tee
      execute_in - before run command `cd execute_in` and after `cd -`.

    On NT, DOS systems the returned status is correct for external commands.
    Wild cards will not work for non-posix systems or when use_shell=0.
    """
    log.debug('exec_command(%r,%s)' % (command,\
         ','.join(['%s=%r'%kv for kv in env.items()])))

    if use_tee is None:
        use_tee = os.name=='posix'
    if use_shell is None:
        use_shell = os.name=='posix'
    execute_in = os.path.abspath(execute_in)
    oldcwd = os.path.abspath(os.getcwd())

    if __name__[-12:] == 'exec_command':
        exec_dir = os.path.dirname(os.path.abspath(__file__))
    elif os.path.isfile('exec_command.py'):
        exec_dir = os.path.abspath('.')
    else:
        exec_dir = os.path.abspath(sys.argv[0])
        if os.path.isfile(exec_dir):
            exec_dir = os.path.dirname(exec_dir)

    if oldcwd!=execute_in:
        os.chdir(execute_in)
        log.debug('New cwd: %s' % execute_in)
    else:
        log.debug('Retaining cwd: %s' % oldcwd)

    oldenv = _preserve_environment( env.keys() )
    _update_environment( **env )

    try:
        # _exec_command is robust but slow, it relies on
        # usable sys.std*.fileno() descriptors. If they
        # are bad (like in win32 Idle, PyCrust environments)
        # then _exec_command_python (even slower)
        # will be used as a last resort.
        #
        # _exec_command_posix uses os.system and is faster
        # but not on all platforms os.system will return
        # a correct status.
        if _with_python and sys.stdout.fileno() == -1:
            st = _exec_command_python(command,
                                      exec_command_dir = exec_dir,
                                      **env)
        elif os.name=='posix':
            st = _exec_command_posix(command,
                                     use_shell=use_shell,
                                     use_tee=use_tee,
                                     **env)
        else:
            st = _exec_command(command, use_shell=use_shell,
                               use_tee=use_tee,**env)
    finally:
        if oldcwd!=execute_in:
            os.chdir(oldcwd)
            log.debug('Restored cwd to %s' % oldcwd)
        _update_environment(**oldenv)

    return st

def _exec_command_posix( command,
                         use_shell = None,
                         use_tee = None,
                         **env ):
    log.debug('_exec_command_posix(...)')

    if is_sequence(command):
        command_str = ' '.join(list(command))
    else:
        command_str = command

    tmpfile = temp_file_name()
    stsfile = None
    if use_tee:
        stsfile = temp_file_name()
        filter = ''
        if use_tee == 2:
            filter = r'| tr -cd "\n" | tr "\n" "."; echo'
        command_posix = '( %s ; echo $? > %s ) 2>&1 | tee %s %s'\
                      % (command_str,stsfile,tmpfile,filter)
    else:
        stsfile = temp_file_name()
        command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\
                        % (command_str,stsfile,tmpfile)
        #command_posix = '( %s ) > %s 2>&1' % (command_str,tmpfile)

    log.debug('Running os.system(%r)' % (command_posix))
    status = os.system(command_posix)

    if use_tee:
        if status:
            # if command_tee fails then fall back to robust exec_command
            log.warn('_exec_command_posix failed (status=%s)' % status)
            return _exec_command(command, use_shell=use_shell, **env)

    if stsfile is not None:
        f = open_latin1(stsfile,'r')
        status_text = f.read()
        status = int(status_text)
        f.close()
        os.remove(stsfile)

    f = open_latin1(tmpfile,'r')
    text = f.read()
    f.close()
    os.remove(tmpfile)

    if text[-1:]=='\n':
        text = text[:-1]

    return status, text

def _exec_command_python(command,
                         exec_command_dir='', **env):
    log.debug('_exec_command_python(...)')

    python_exe = get_pythonexe()
    cmdfile = temp_file_name()
    stsfile = temp_file_name()
    outfile = temp_file_name()

    f = open(cmdfile,'w')
    f.write('import os\n')
    f.write('import sys\n')
    f.write('sys.path.insert(0,%r)\n' % (exec_command_dir))
    f.write('from exec_command import exec_command\n')
    f.write('del sys.path[0]\n')
    f.write('cmd = %r\n' % command)
    f.write('os.environ = %r\n' % (os.environ))
    f.write('s,o = exec_command(cmd, _with_python=0, **%r)\n' % (env))
    f.write('f=open(%r,"w")\nf.write(str(s))\nf.close()\n' % (stsfile))
    f.write('f=open(%r,"w")\nf.write(o)\nf.close()\n' % (outfile))
    f.close()

    cmd = '%s %s' % (python_exe, cmdfile)
    status = os.system(cmd)
    if status:
        raise RuntimeError("%r failed" % (cmd,))
    os.remove(cmdfile)

    f = open_latin1(stsfile,'r')
    status = int(f.read())
    f.close()
    os.remove(stsfile)

    f = open_latin1(outfile,'r')
    text = f.read()
    f.close()
    os.remove(outfile)

    return status, text

def quote_arg(arg):
    if arg[0]!='"' and ' ' in arg:
        return '"%s"' % arg
    return arg

def _exec_command( command, use_shell=None, use_tee = None, **env ):
    log.debug('_exec_command(...)')

    if use_shell is None:
        use_shell = os.name=='posix'
    if use_tee is None:
        use_tee = os.name=='posix'
    using_command = 0
    if use_shell:
        # We use shell (unless use_shell==0) so that wildcards can be
        # used.
        sh = os.environ.get('SHELL','/bin/sh')
        if is_sequence(command):
            argv = [sh,'-c',' '.join(list(command))]
        else:
            argv = [sh,'-c',command]
    else:
        # On NT, DOS we avoid using command.com as it's exit status is
        # not related to the exit status of a command.
        if is_sequence(command):
            argv = command[:]
        else:
            argv = shlex.split(command)

    if hasattr(os,'spawnvpe'):
        spawn_command = os.spawnvpe
    else:
        spawn_command = os.spawnve
        argv[0] = find_executable(argv[0]) or argv[0]
        if not os.path.isfile(argv[0]):
            log.warn('Executable %s does not exist' % (argv[0]))
            if os.name in ['nt','dos']:
                # argv[0] might be internal command
                argv = [os.environ['COMSPEC'],'/C'] + argv
                using_command = 1

    so_fileno = sys.stdout.fileno()
    se_fileno = sys.stderr.fileno()
    so_flush = sys.stdout.flush
    se_flush = sys.stderr.flush
    so_dup = os.dup(so_fileno)
    se_dup = os.dup(se_fileno)

    outfile = temp_file_name()
    fout = open(outfile,'w')
    if using_command:
        errfile = temp_file_name()
        ferr = open(errfile,'w')

    log.debug('Running %s(%s,%r,%r,os.environ)' \
              % (spawn_command.__name__,os.P_WAIT,argv[0],argv))

    argv0 = argv[0]
    if not using_command:
        argv[0] = quote_arg(argv0)

    so_flush()
    se_flush()
    os.dup2(fout.fileno(),so_fileno)
    if using_command:
        #XXX: disabled for now as it does not work from cmd under win32.
        #     Tests fail on msys
        os.dup2(ferr.fileno(),se_fileno)
    else:
        os.dup2(fout.fileno(),se_fileno)
    try:
        status = spawn_command(os.P_WAIT,argv0,argv,os.environ)
    except OSError:
        errmess = str(get_exception())
        status = 999
        sys.stderr.write('%s: %s'%(errmess,argv[0]))

    so_flush()
    se_flush()
    os.dup2(so_dup,so_fileno)
    os.dup2(se_dup,se_fileno)

    fout.close()
    fout = open_latin1(outfile,'r')
    text = fout.read()
    fout.close()
    os.remove(outfile)

    if using_command:
        ferr.close()
        ferr = open_latin1(errfile,'r')
        errmess = ferr.read()
        ferr.close()
        os.remove(errfile)
        if errmess and not status:
            # Not sure how to handle the case where errmess
            # contains only warning messages and that should
            # not be treated as errors.
            #status = 998
            if text:
                text = text + '\n'
            #text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess)
            text = text + errmess
            print (errmess)
    if text[-1:]=='\n':
        text = text[:-1]
    if status is None:
        status = 0

    if use_tee:
        print (text)

    return status, text

def test_nt(**kws):
    pythonexe = get_pythonexe()
    echo = find_executable('echo')
    using_cygwin_echo = echo != 'echo'
    if using_cygwin_echo:
        log.warn('Using cygwin echo in win32 environment is not supported')

        s,o=exec_command(pythonexe\
                         +' -c "import os;print os.environ.get(\'AAA\',\'\')"')
        assert s==0 and o=='',(s,o)

        s,o=exec_command(pythonexe\
                         +' -c "import os;print os.environ.get(\'AAA\')"',
                         AAA='Tere')
        assert s==0 and o=='Tere',(s,o)

        os.environ['BBB'] = 'Hi'
        s,o=exec_command(pythonexe\
                         +' -c "import os;print os.environ.get(\'BBB\',\'\')"')
        assert s==0 and o=='Hi',(s,o)

        s,o=exec_command(pythonexe\
                         +' -c "import os;print os.environ.get(\'BBB\',\'\')"',
                         BBB='Hey')
        assert s==0 and o=='Hey',(s,o)

        s,o=exec_command(pythonexe\
                         +' -c "import os;print os.environ.get(\'BBB\',\'\')"')
        assert s==0 and o=='Hi',(s,o)
    elif 0:
        s,o=exec_command('echo Hello')
        assert s==0 and o=='Hello',(s,o)

        s,o=exec_command('echo a%AAA%')
        assert s==0 and o=='a',(s,o)

        s,o=exec_command('echo a%AAA%',AAA='Tere')
        assert s==0 and o=='aTere',(s,o)

        os.environ['BBB'] = 'Hi'
        s,o=exec_command('echo a%BBB%')
        assert s==0 and o=='aHi',(s,o)

        s,o=exec_command('echo a%BBB%',BBB='Hey')
        assert s==0 and o=='aHey', (s,o)
        s,o=exec_command('echo a%BBB%')
        assert s==0 and o=='aHi',(s,o)

        s,o=exec_command('this_is_not_a_command')
        assert s and o!='',(s,o)

        s,o=exec_command('type not_existing_file')
        assert s and o!='',(s,o)

    s,o=exec_command('echo path=%path%')
    assert s==0 and o!='',(s,o)

    s,o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \
                     % pythonexe)
    assert s==0 and o=='win32',(s,o)

    s,o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe)
    assert s==1 and o,(s,o)

    s,o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\
                     % pythonexe)
    assert s==0 and o=='012',(s,o)

    s,o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe)
    assert s==15 and o=='',(s,o)

    s,o=exec_command('%s -c "print \'Heipa\'"' % pythonexe)
    assert s==0 and o=='Heipa',(s,o)

    print ('ok')

def test_posix(**kws):
    s,o=exec_command("echo Hello",**kws)
    assert s==0 and o=='Hello',(s,o)

    s,o=exec_command('echo $AAA',**kws)
    assert s==0 and o=='',(s,o)

    s,o=exec_command('echo "$AAA"',AAA='Tere',**kws)
    assert s==0 and o=='Tere',(s,o)

    s,o=exec_command('echo "$AAA"',**kws)
    assert s==0 and o=='',(s,o)

    os.environ['BBB'] = 'Hi'
    s,o=exec_command('echo "$BBB"',**kws)
    assert s==0 and o=='Hi',(s,o)

    s,o=exec_command('echo "$BBB"',BBB='Hey',**kws)
    assert s==0 and o=='Hey',(s,o)

    s,o=exec_command('echo "$BBB"',**kws)
    assert s==0 and o=='Hi',(s,o)

    s,o=exec_command('this_is_not_a_command',**kws)
    assert s!=0 and o!='',(s,o)

    s,o=exec_command('echo path=$PATH',**kws)
    assert s==0 and o!='',(s,o)

    s,o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws)
    assert s==0 and o=='posix',(s,o)

    s,o=exec_command('python -c "raise \'Ignore me.\'"',**kws)
    assert s==1 and o,(s,o)

    s,o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws)
    assert s==0 and o=='012',(s,o)

    s,o=exec_command('python -c "import sys;sys.exit(15)"',**kws)
    assert s==15 and o=='',(s,o)

    s,o=exec_command('python -c "print \'Heipa\'"',**kws)
    assert s==0 and o=='Heipa',(s,o)

    print ('ok')

def test_execute_in(**kws):
    pythonexe = get_pythonexe()
    tmpfile = temp_file_name()
    fn = os.path.basename(tmpfile)
    tmpdir = os.path.dirname(tmpfile)
    f = open(tmpfile,'w')
    f.write('Hello')
    f.close()

    s,o = exec_command('%s -c "print \'Ignore the following IOError:\','\
                       'open(%r,\'r\')"' % (pythonexe,fn),**kws)
    assert s and o!='',(s,o)
    s,o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe,fn),
                       execute_in = tmpdir,**kws)
    assert s==0 and o=='Hello',(s,o)
    os.remove(tmpfile)
    print ('ok')

def test_svn(**kws):
    s,o = exec_command(['svn','status'],**kws)
    assert s,(s,o)
    print ('svn ok')

def test_cl(**kws):
    if os.name=='nt':
        s,o = exec_command(['cl','/V'],**kws)
        assert s,(s,o)
        print ('cl ok')

if os.name=='posix':
    test = test_posix
elif os.name in ['nt','dos']:
    test = test_nt
else:
    raise NotImplementedError('exec_command tests for ', os.name)

############################################################

if __name__ == "__main__":

    test(use_tee=0)
    test(use_tee=1)
    test_execute_in(use_tee=0)
    test_execute_in(use_tee=1)
    test_svn(use_tee=1)
    test_cl(use_tee=1)


text:
  Einvaux est
       un village
       géographiquement positionné dans le département de Meurthe-et-Moselle en Lorraine. On dénombrait 314 habitants en 2008.

La ville propose quelques  équipements, elle propose entre autres un terrain de sport.

Le parc d'habitations, à Einvaux, se décomposait en 2011 en neuf appartements et 149 maisons soit
 un marché plutôt équilibré.

Si vous pensez venir habiter à Einvaux, vous pourrez aisément trouver une maison à acheter.

À coté de Einvaux sont situées les villes de
Moriviller à 3 km, 94 habitants,
Domptail-en-l'Air à 5 km, 60 habitants,
Franconville localisée à 4 km, 48 habitants,
Lamath à 5 km, 195 habitants,
Rozelieures à 5 km, 160 habitants,
Romain localisée à 3 km, 49 habitants,
 entre autres. De plus, Einvaux est située à seulement 27 km de Nancy.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.ComponentModel.Composition;
using System.Windows;
using Microsoft.Common.Core.Shell;
using Microsoft.R.Components.Search;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.R.Package.Search {
    [Export(typeof(ISearchControlProvider))]
    internal class VsSearchControlProvider : ISearchControlProvider {
        private readonly ICoreShell _coreShell;
        private readonly Lazy<IVsWindowSearchHostFactory> _factoryLazy;

        [ImportingConstructor]
        public VsSearchControlProvider(ICoreShell coreShell) {
            _coreShell = coreShell;
            _factoryLazy = new Lazy<IVsWindowSearchHostFactory>(()
                => _coreShell.GetService<IVsWindowSearchHostFactory>(typeof(SVsWindowSearchHostFactory)));
        }

        public ISearchControl Create(FrameworkElement host, ISearchHandler handler, SearchControlSettings settings) {
            _coreShell.AssertIsOnMainThread();

            var vsWindowSearchHost = _factoryLazy.Value.CreateWindowSearchHost(host);
            return new VsSearchControl(vsWindowSearchHost, handler, settings);
        }
    }
}


text: th -e "require('mobdebug').listen()"


text:
FIND_PATH(LUABIND_INCLUDE_DIR luabind/luabind.hpp
  HINTS
  $ENV{LUABIND_DIR}
  PATH_SUFFIXES include
  PATHS
  ~/Library/Frameworks
  /Library/Frameworks
  /usr/local
  /usr
  /sw # Fink
  /opt/local # DarwinPorts
  /opt/csw # Blastwave
  /opt
)

FIND_LIBRARY(LUABIND_RELEASE_LIBRARY
  NAMES luabind libluabind
  HINTS
  $ENV{LUABIND_DIR}
  PATH_SUFFIXES lib64 lib
  PATHS
  ~/Library/Frameworks
  /Library/Frameworks
  /usr/local
  /usr
  /sw
  /opt/local
  /opt/csw
  /opt
)

FIND_LIBRARY(LUABIND_DEBUG_LIBRARY
  NAMES luabindd libluabindd
  HINTS
  $ENV{LUABIND_DIR}
  PATH_SUFFIXES lib64 lib
  PATHS
  ~/Library/Frameworks
  /Library/Frameworks
  /usr/local
  /usr
  /sw
  /opt/local
  /opt/csw
  /opt
)

MESSAGE("LUABIND_INCLUDE_DIR = " ${LUABIND_INCLUDE_DIR})
MESSAGE("LUABIND_DEBUG_LIBRARY = " ${LUABIND_DEBUG_LIBRARY})
MESSAGE("LUABIND_RELEASE_LIBRARY = " ${LUABIND_RELEASE_LIBRARY})

IF(LUABIND_DEBUG_LIBRARY AND LUABIND_RELEASE_LIBRARY)
  SET(LUABIND_LIBRARIES debug ${LUABIND_DEBUG_LIBRARY} optimized ${LUABIND_RELEASE_LIBRARY} CACHE STRING "LuaBind Libraries")
ELSE()
  SET(LUABIND_LIBRARIES ${LUABIND_RELEASE_LIBRARY} CACHE STRING "LuaBind Libraries")
ENDIF()

INCLUDE(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set LUABIND_FOUND to TRUE if
# all listed variables are TRUE
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LUABIND DEFAULT_MSG LUABIND_LIBRARIES LUABIND_INCLUDE_DIR)

MARK_AS_ADVANCED(LUABIND_INCLUDE_DIR LUABIND_LIBRARIES LUABIND_DEBUG_LIBRARY LUABIND_RELEASE_LIBRARY)


text:
IF(WIN32)

  FIND_PROGRAM(HTML_HELP_COMPILER
    hhc
    "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]"
    "$ENV{ProgramFiles}/HTML Help Workshop"
    "C:/Program Files/HTML Help Workshop"
    )

  GET_FILENAME_COMPONENT(HTML_HELP_COMPILER_PATH "${HTML_HELP_COMPILER}" PATH)

  FIND_PATH(HTML_HELP_INCLUDE_PATH
    htmlhelp.h
    "${HTML_HELP_COMPILER_PATH}/include"
    "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/include"
    "$ENV{ProgramFiles}/HTML Help Workshop/include"
    "C:/Program Files/HTML Help Workshop/include"
    )

  FIND_LIBRARY(HTML_HELP_LIBRARY
    htmlhelp
    "${HTML_HELP_COMPILER_PATH}/lib"
    "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/lib"
    "$ENV{ProgramFiles}/HTML Help Workshop/lib"
    "C:/Program Files/HTML Help Workshop/lib"
    )

  MARK_AS_ADVANCED(
    HTML_HELP_COMPILER
    HTML_HELP_INCLUDE_PATH
    HTML_HELP_LIBRARY
    )

ENDIF(WIN32)


text:
const hInteval = 5
const vInteval = 5
const kPageSize = 30
const kEdgeInteval = 14
var app = getApp()
let config = require("../../config.js")
let imageHelper = require("../../utils/imagehelper.js")
let topicDataManager = require("../../datamanager/topicdatamanager.js")
let commentDataManager = require("../../datamanager/commentDataManager.js")

Page({
  data: {
    topic: null,
    windowHeight: 600,
    hasMoreComments: false,
    edgeInteval: kEdgeInteval,
    hotTopicComments: [],
    norTopicComments: [],
    loadingDataError: false
  },
  customerData: {
    topicId: "0",
    lastCommentId: "0",
    isloadingMore: false,
    windowWidth: 375
  },
  onShow: function() {
    var info = app.globalData.topicInfo
    if (!info && !this.data.topic) {
      let that = this
      setTimeout(function(){
        that.showLoadingAdInfoView()
      }, 500)
    }
    app.globalData.topicInfo = null
  },
  onLoad:function(options){
    // 生命周期函数--监听页面加载
    this.updateDeviceInfo()
    this.customerData.topicId = options["id"]
    let topicInfo = app.globalData.topicInfo
    if (topicInfo) {
      this.updateTopicInfo(topicInfo)
    } else {
      this.loadTopicDetailInfo()
    }
  },
  onHide: function() {
    wx.hideToast()
  },
  reloadDatas: function() {
    if (this.customerData.isloadingMore) {
      return
    }
    this.showLoadingAdInfoView()
    this.loadTopicDetailInfo()
  },
  updateTopicInfo: function(topicInfo) {
    if (topicInfo) {
      this.setData({
        topic: topicInfo,
        hasMoreComments: topicInfo.commentCount > 0
      })
    }

    if (topicInfo.commentNum > 0) {
      this.customerData.isloadingMore = true
      this.loadMoreTopicComments()
    }
  },
  loadTopicDetailInfo: function() {
    let that = this
    let params = this.loadTopicDetailInfoParams()
    let success = function(topicInfo) {
      imageHelper.calculateDefaultTopicImagesSize(topicInfo.images, kEdgeInteval, hInteval, vInteval, that.customerData.windowWidth)
      that.updateTopicInfo(topicInfo)
    }
    let fail = function() {
      that.setData({
        loadingDataError: true
      })
      wx.showToast({
        title: "加载数据失败",
        duration: 2000
      })
      that.customerData.isloadingMore = false
    }
    topicDataManager.getTopicDetailWithParams(params, success, fail, null)
  },
  showLoadingAdInfoView: function() {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 1000
    })
  },
  loadTopicDetailInfoParams: function() {
    return { "topicId" : this.customerData.topicId ? this.customerData.topicId : ""}
  },
  scrolltolower: function() {
    //正在加载或者无数据,不在加载.
    if (this.customerData.isloadingMore || !this.data.hasMoreComments) {
      return
    }
    this.customerData.isloadingMore = true
    this.loadMoreTopicComments()
  },
  updateDeviceInfo: function() {
    try{
        var res = wx.getSystemInfoSync()
        this.setData({
            windowHeight: res.windowHeight
        })
        this.customerData.windowWidth = res.windowWidth
    } catch(e) {
        console.log('error');
    }
  },
  loadMoreTopicComments: function() {
    let params = this.loadMoreTopicCommentParams()
    let success = this.loadMoreTopicCommentsSuccess
    let that = this
    let complete = function() {
      setTimeout(function() {
        that.customerData.isloadingMore = false
      }, 500)
    }
    commentDataManager.getCommentListWithParams(params, success, null, complete)
  },
  loadMoreTopicCommentParams: function() {
    let opts = {
      size: kPageSize
    }
    return {
      topicId: this.customerData.topicId,
      id: this.customerData.lastCommentId,
      opts: JSON.stringify(opts)
    }
  },
  loadMoreTopicCommentsSuccess: function(retInfo) {
    let apiInfo = retInfo.apiInfo
    this.customerData.lastTopicId = apiInfo.lastId

    let lcalHotComments = this.data.hotTopicComments
    let lcalNorComments = this.data.norTopicComments
    lcalHotComments = lcalHotComments.concat(retInfo.hotComments)
    lcalNorComments = lcalNorComments.concat(retInfo.norComments)
    lcalHotComments = this.updateIsCommentInBottom(lcalHotComments)
    lcalNorComments = this.updateIsCommentInBottom(lcalNorComments)
    this.setData({
      hotTopicComments: lcalHotComments,
      norTopicComments: lcalNorComments,
      hasMoreComments: !apiInfo.endFlag
    })
  },
  updateIsCommentInBottom: function(comments) {
    for (let i = 0; i < comments.length; i++) {
      let comment = comments[i]
      comment.isBottom = (i + 1 == comments.length)
    }
    return comments
  },
  onShareAppMessage: function() {
    // 用户点击右上角分享
    return {
      title: config.shareTitle, // 分享标题
      desc: config.shareDesc, // 分享描述
      path: '/pages/topicdetail/topicdetail?id=' + this.customerData.topicId // 分享路径
    }
  },
  clickToLikeTopic: function() {
    this.showDownloadAlert()
  },
  clickToCommentTopic: function() {
    this.showDownloadAlert()
  },
  showDownloadAlert: function() {
    wx.showModal({
      title: config.downloadTitle,
      content: config.downloadContent,
    })
  }
})


text:
#ifndef ANDROID_HWUI_PATH_TESSELLATOR_H
#define ANDROID_HWUI_PATH_TESSELLATOR_H

#include <utils/Vector.h>

#include "Matrix.h"
#include "Rect.h"
#include "Vertex.h"

namespace android {
namespace uirenderer {

class VertexBuffer {
public:
    VertexBuffer():
        mBuffer(0),
        mVertexCount(0),
        mCleanupMethod(NULL)
    {}

    ~VertexBuffer() {
        if (mCleanupMethod) mCleanupMethod(mBuffer);
    }

    /**
       This should be the only method used by the PathTessellator. Subsequent calls to alloc will
       allocate space within the first allocation (useful if you want to eventually allocate
       multiple regions within a single VertexBuffer, such as with PathTessellator::tesselateLines()
     */
    template <class TYPE>
    TYPE* alloc(int vertexCount) {
        if (mVertexCount) {
            TYPE* reallocBuffer = (TYPE*)mReallocBuffer;
            // already have allocated the buffer, re-allocate space within
            if (mReallocBuffer != mBuffer) {
                // not first re-allocation, leave space for degenerate triangles to separate strips
                reallocBuffer += 2;
            }
            mReallocBuffer = reallocBuffer + vertexCount;
            return reallocBuffer;
        }
        mVertexCount = vertexCount;
        mReallocBuffer = mBuffer = (void*)new TYPE[vertexCount];
        mCleanupMethod = &(cleanup<TYPE>);

        return (TYPE*)mBuffer;
    }

    template <class TYPE>
    void copyInto(const VertexBuffer& srcBuffer, float xOffset, float yOffset) {
        int verticesToCopy = srcBuffer.getVertexCount();

        TYPE* dst = alloc<TYPE>(verticesToCopy);
        TYPE* src = (TYPE*)srcBuffer.getBuffer();

        for (int i = 0; i < verticesToCopy; i++) {
            TYPE::copyWithOffset(&dst[i], src[i], xOffset, yOffset);
        }
    }

    void* getBuffer() const { return mBuffer; } // shouldn't be const, since not a const ptr?
    unsigned int getVertexCount() const { return mVertexCount; }

    template <class TYPE>
    void createDegenerateSeparators(int allocSize) {
        TYPE* end = (TYPE*)mBuffer + mVertexCount;
        for (TYPE* degen = (TYPE*)mBuffer + allocSize; degen < end; degen += 2 + allocSize) {
            memcpy(degen, degen - 1, sizeof(TYPE));
            memcpy(degen + 1, degen + 2, sizeof(TYPE));
        }
    }

private:
    template <class TYPE>
    static void cleanup(void* buffer) {
        delete[] (TYPE*)buffer;
    }

    void* mBuffer;
    unsigned int mVertexCount;

    void* mReallocBuffer; // used for multi-allocation

    void (*mCleanupMethod)(void*);
};

class PathTessellator {
public:
    static void expandBoundsForStroke(SkRect& bounds, const SkPaint* paint, bool forceExpand);

    static void tessellatePath(const SkPath& path, const SkPaint* paint,
            const mat4 *transform, VertexBuffer& vertexBuffer);

    static void tessellatePoints(const float* points, int count, SkPaint* paint,
            const mat4* transform, SkRect& bounds, VertexBuffer& vertexBuffer);

    static void tessellateLines(const float* points, int count, SkPaint* paint,
            const mat4* transform, SkRect& bounds, VertexBuffer& vertexBuffer);

private:
    static bool approximatePathOutlineVertices(const SkPath &path, bool forceClose,
        float sqrInvScaleX, float sqrInvScaleY, Vector<Vertex> &outputVertices);

/*
  endpoints a & b,
  control c
 */
    static void recursiveQuadraticBezierVertices(
            float ax, float ay,
            float bx, float by,
            float cx, float cy,
            float sqrInvScaleX, float sqrInvScaleY,
            Vector<Vertex> &outputVertices);

/*
  endpoints p1, p2
  control c1, c2
 */
    static void recursiveCubicBezierVertices(
            float p1x, float p1y,
            float c1x, float c1y,
            float p2x, float p2y,
            float c2x, float c2y,
            float sqrInvScaleX, float sqrInvScaleY,
            Vector<Vertex> &outputVertices);
};

}; // namespace uirenderer
}; // namespace android

#endif // ANDROID_HWUI_PATH_TESSELLATOR_H


text:
$(function() {
  var pageToFetch = 2,
      prevQueryLength = 0,
      userId;

  $(".more").click(function() {
    $(this).addClass("loading");
    $.get("/home/mock_set", {page: pageToFetch}, function(data) {
      $(".more").removeClass("loading");
      if (data.trim().length > 0) {
        $("#mock_set").append(data);
      }
      if (pageToFetch === TOTAL_PAGES) {
        $(".more").hide();
      }
      filter_users();
      pageToFetch++;
    });
  });

  $('#show_all_projects').click(function(evt) {
    evt.preventDefault();
    $('#all_projects').show();
    $('#show_all_projects').hide();
  });

  $('.project_filter').keyup(function() {
    var $projects = $('.project_list li');
    var filter = $.trim($(this).val());

    if (filter) {
      filterRegexp = new RegExp(filter ,'i');
      $projects
        .filter(':visible')
        .filter(function() { return !filterRegexp.test(this.textContent); })
        .hide();

      if (filter.length <= prevQueryLength) {
        $projects
          .filter(':hidden')
          .filter(function() { return filterRegexp.test(this.textContent); })
          .show();
      }
    } else {
      $projects.show();
    }

    prevQueryLength = filter.length;
  });

  $('.author_link').click(function(e) {
    e.preventDefault();
    var $this = $(this);

    userId = $this.data('author');
    filterUsers();

    $('.author_link').removeClass('selected');
    $this.addClass('selected');
  });

  var filterUsers = function() {
    if (userId) {
      $('.mock_grid li')
        .hide()
        .filter('[data-author=' + userId + ']')
        .show();
    } else {
      $('.mock_grid li').show();
    }
  }

});


text:
package com.hp.autonomy.aci.content.fieldtext;

import org.junit.Test;

import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;

import static org.junit.Assert.assertEquals;

public class RANGETest {
    @Test
    public void singleFieldEpoch() {
        final RANGE range = new RANGE("ns:field", 123456789000L, 123456791000L, RANGE.Type.EPOCH);
        assertEquals("RANGE{123456789e,123456791e}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("123456789e", "123456791e"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void singleFieldDays() {
        final RANGE range = new RANGE("ns:field", 123456789L, 123456791L, RANGE.Type.DAYS);
        assertEquals("RANGE{123456789,123456791}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("123456789", "123456791"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void singleFieldSeconds() {
        final RANGE range = new RANGE("ns:field", 123456789L, 123456791L, RANGE.Type.SECONDS);
        assertEquals("RANGE{123456789s,123456791s}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("123456789s", "123456791s"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void singleFieldDate() {
        final RANGE range = new RANGE("ns:field", ZonedDateTime.parse("2017-02-15T15:39:00Z"), ZonedDateTime.parse("2017-02-15T15:40:00Z"));
        assertEquals("RANGE{2017-02-15T15:39:00Z,2017-02-15T15:40:00Z}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("2017-02-15T15:39:00Z", "2017-02-15T15:40:00Z"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void singleFieldDateWideRange() {
        final RANGE range = new RANGE("ns:field", ZonedDateTime.parse("0000-01-01T01:01:00Z"), ZonedDateTime.parse("3000-03-03T03:03:00Z"));
        assertEquals("RANGE{0000-01-01T01:01:00Z,3000-03-03T03:03:00Z}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("0000-01-01T01:01:00Z", "3000-03-03T03:03:00Z"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void singleFieldDateMillis() {
        final RANGE range = new RANGE("ns:field", ZonedDateTime.parse("0000-01-01T01:01:00.123Z"), ZonedDateTime.parse("3000-03-03T03:03:00.456Z"));
        assertEquals("RANGE{0000-01-01T01:01:00Z,3000-03-03T03:03:00Z}:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("0000-01-01T01:01:00Z", "3000-03-03T03:03:00Z"), range.getValues());
        assertEquals(Collections.singletonList("ns:field"), range.getFields());
    }

    @Test
    public void fieldArrayEpoch() {
        final RANGE range = new RANGE(new String[]{"FIELD1", "FIELD2", "ns:field"}, 123456789000L, 123456791000L, RANGE.Type.EPOCH);
        assertEquals("RANGE{123456789e,123456791e}:FIELD1:FIELD2:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("123456789e", "123456791e"), range.getValues());
        assertEquals(Arrays.asList("FIELD1", "FIELD2", "ns:field"), range.getFields());
    }

    @Test
    public void fieldArrayDate() {
        final RANGE range = new RANGE(new String[]{"FIELD1", "FIELD2", "ns:field"}, ZonedDateTime.parse("2017-02-15T15:39:00Z"), ZonedDateTime.parse("2017-02-15T15:40:00Z"));
        assertEquals("RANGE{2017-02-15T15:39:00Z,2017-02-15T15:40:00Z}:FIELD1:FIELD2:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("2017-02-15T15:39:00Z", "2017-02-15T15:40:00Z"), range.getValues());
        assertEquals(Arrays.asList("FIELD1", "FIELD2", "ns:field"), range.getFields());
    }

    @Test
    public void fieldCollectionEpoch() {
        final RANGE range = new RANGE(Arrays.asList("FIELD1", "FIELD2", "ns:field"), 123456789000L, 123456791000L, RANGE.Type.EPOCH);
        assertEquals("RANGE{123456789e,123456791e}:FIELD1:FIELD2:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("123456789e", "123456791e"), range.getValues());
        assertEquals(Arrays.asList("FIELD1", "FIELD2", "ns:field"), range.getFields());
    }

    @Test
    public void fieldCollectionDate() {
        final RANGE range = new RANGE(Arrays.asList("FIELD1", "FIELD2", "ns:field"), ZonedDateTime.parse("2017-02-15T15:39:00Z"), ZonedDateTime.parse("2017-02-15T15:40:00Z"));
        assertEquals("RANGE{2017-02-15T15:39:00Z,2017-02-15T15:40:00Z}:FIELD1:FIELD2:ns%3Afield", range.toString());
        assertEquals(Arrays.asList("2017-02-15T15:39:00Z", "2017-02-15T15:40:00Z"), range.getValues());
        assertEquals(Arrays.asList("FIELD1", "FIELD2", "ns:field"), range.getFields());
    }
}


text:
// ----------------------------------------------------------------------------
// $Id: IBlockCipher.java,v 1.7 2002/11/07 17:17:45 raif Exp $
//
// Copyright (C) 2001, 2002, Free Software Foundation, Inc.
//
// This file is part of GNU Crypto.
//
// GNU Crypto is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// GNU Crypto is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; see the file COPYING.  If not, write to the
//
//    Free Software Foundation Inc.,
//    59 Temple Place - Suite 330,
//    Boston, MA 02111-1307
//    USA
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library.  Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give
// you permission to link this library with independent modules to
// produce an executable, regardless of the license terms of these
// independent modules, and to copy and distribute the resulting
// executable under terms of your choice, provided that you also meet,
// for each linked independent module, the terms and conditions of the
// license of that module.  An independent module is a module which is
// not derived from or based on this library.  If you modify this
// library, you may extend this exception to your version of the
// library, but you are not obligated to do so.  If you do not wish to
// do so, delete this exception statement from your version.
// ----------------------------------------------------------------------------

import java.security.InvalidKeyException;
import java.util.Iterator;
import java.util.Map;

/**
 *
The basic visible methods of any symmetric key block cipher.

 *
 *
A symmetric key block cipher is a function that maps n-bit plaintext
 * blocks to n-bit ciphertext blocks; n being the cipher's block size.
 * This encryption function is parameterised by a k-bit key, and is invertible.
 * Its inverse is the decryption function.

 *
 *
Possible initialisation values for an instance of this type are:

 *
 *

 *
The block size in which to operate this block cipher instance. This
 *    value is optional, if unspecified, the block cipher's default
 *    block size shall be used.

 *
 *
The byte array containing the user supplied key material to use for
 *    generating the cipher's session key(s). This value is mandatory
 *    and should be included in the initialisation parameters. If it isn't,
 *    an {@link IllegalStateException} will be thrown if any method, other than
 *    reset() is invoked on the instance. Furthermore, the size of
 *    this key material shall be taken as an indication on the key size in which
 *    to operate this instance.

 *

 *
 *
IMPLEMENTATION NOTE: Although all the concrete classes in this
 * package implement the {@link Cloneable} interface, it is important to note
 * here that such an operation DOES NOT clone any session key material
 * that may have been used in initialising the source cipher (the instance to be
 * cloned). Instead a clone of an already initialised cipher is another instance
 * that operates with the same block size but without any knowledge of
 * neither key material nor key size.

 *
 * @version $Revision: 1.7 $
 */
public interface IBlockCipher extends Cloneable {

   // Constants
   // -------------------------------------------------------------------------

   /**
    *
Property name of the block size in which to operate a block cipher.
    * The value associated with this property name is taken to be an
    * {@link Integer}.

    */
   String CIPHER_BLOCK_SIZE = "gnu.crypto.cipher.block.size";

   /**
    *
Property name of the user-supplied key material. The value associated
    * to this property name is taken to be a byte array.

    */
   String KEY_MATERIAL = "gnu.crypto.cipher.key.material";

   // Methods
   // -------------------------------------------------------------------------

   /**
    *
Returns the canonical name of this instance.

    *
    * @return the canonical name of this instance.
    */
   String name();

   /**
    *
Returns the default value, in bytes, of the algorithm's block size.

    *
    * @return the default value, in bytes, of the algorithm's block size.
    */
   int defaultBlockSize();

   /**
    *
Returns the default value, in bytes, of the algorithm's key size.

    *
    * @return the default value, in bytes, of the algorithm's key size.
    */
   int defaultKeySize();

   /**
    *
Returns an {@link Iterator} over the supported block sizes. Each
    * element returned by this object is an {@link Integer}.

    *
    * @return an {@link Iterator} over the supported block sizes.
    */
   Iterator blockSizes();

   /**
    *
Returns an {@link Iterator} over the supported key sizes. Each element
    * returned by this object is an {@link Integer}.

    *
    * @return an {@link Iterator} over the supported key sizes.
    */
   Iterator keySizes();

   /**
    *
Returns a clone of this instance.

    *
    * @return a clone copy of this instance.
    */
   Object clone();

   /**
    *
Initialises the algorithm with designated attributes. Permissible names
    * and values are described in the class documentation above.

    *
    * @param attributes a set of name-value pairs that describes the desired
    * future behaviour of this instance.
    * @exception InvalidKeyException if the key data is invalid.
    * @exception IllegalStateException if the instance is already initialised.
    * @see #KEY_MATERIAL
    * @see #CIPHER_BLOCK_SIZE
    */
   void init(Map attributes)
   throws InvalidKeyException, IllegalStateException;

   /**
    *
Returns the currently set block size for this instance.

    *
    * @return the current block size for this instance.
    * @exception IllegalStateException if the instance is not initialised.
    */
   int currentBlockSize() throws IllegalStateException;

   /**
    *
Resets the algorithm instance for re-initialisation and use with other
    * characteristics. This method always succeeds.

    */
   void reset();

   /**
    *
Encrypts exactly one block of plaintext.

    *
    * @param in the plaintext.
    * @param inOffset index of in from which to start considering
    * data.
    * @param out the ciphertext.
    * @param outOffset index of out from which to store result.
    * @exception IllegalStateException if the instance is not initialised.
    */
   void encryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
   throws IllegalStateException;

   /**
    *
Decrypts exactly one block of ciphertext.

    *
    * @param in the plaintext.
    * @param inOffset index of in from which to start considering
    * data.
    * @param out the ciphertext.
    * @param outOffset index of out from which to store result.
    * @exception IllegalStateException if the instance is not initialised.
    */
   void decryptBlock(byte[] in, int inOffset, byte[] out, int outOffset)
   throws IllegalStateException;

   /**
    *
A correctness test that consists of basic symmetric encryption /
    * decryption test(s) for all supported block and key sizes, as well as one
    * (1) variable key Known Answer Test (KAT).

    *
    * @return true if the implementation passes simple
    * correctness tests. Returns false otherwise.
    */
   boolean selfTest();
}


text:
#ifndef SYSTEM_WRAPPERS_SOURCE_EVENT_WIN_H_
#define SYSTEM_WRAPPERS_SOURCE_EVENT_WIN_H_

#include <stdint.h>

#include <windows.h>

#include BOSS_WEBRTC_U_system_wrappers__include__event_wrapper_h //original-code:"system_wrappers/include/event_wrapper.h"

namespace webrtc {

class EventTimerWin : public EventTimerWrapper {
 public:
  EventTimerWin();
  ~EventTimerWin() override;

  EventTypeWrapper Wait(unsigned long max_time) override;
  bool Set() override;

  bool StartTimer(bool periodic, unsigned long time) override;
  bool StopTimer() override;

 private:
  HANDLE event_;
  uint32_t timerID_;
};

}  // namespace webrtc

#endif  // SYSTEM_WRAPPERS_SOURCE_EVENT_WIN_H_


text:
using System;
using System.ComponentModel;
using DemoCommon;

namespace _06bTypeConverters.Models
{
    [TypeConverter(typeof(DemoVector))]
    public class DemoVectorConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return false;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof (string) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            var source = value as string;
            DemoVector vector;

            return DemoVector.TryParse(source, out vector) ? vector :
                base.ConvertFrom(context, culture, value);
        }
    }
}


text:
作为最大的中文问答社区之一的百度知道上有大量日常问答,bdzd提供了命令行快速查看问答功能.

## Download ##
    git clone git@github.com:wyj1026/bdzd.git

## Usage ##
    cd bdzd
    python bdzd.py [option] question
    ex: python -n 2 如何取得好成绩?
or you can install it:

    cd bdzd
    python setup.py install
then you can use the command everywhere you like.

## Requirements ##
    The script requres requests, pyquery and click.

## Author ##
* Yijie Wang


text:
//=============================================================================
// Copyright 2006-2010 Daniel W. Dyer
//
// 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 org.uncommons.watchmaker.examples;

import java.awt.Container;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * Base class for examples that run as applets.
 * @author Daniel Dyer
 */
public abstract class AbstractExampleApplet extends JApplet
{
    /**
     * {@inheritDoc}
     */
    @Override
    public void init()
    {
        configure(this);
    }

    /**
     * Configure the program to display its GUI in the specified container.
     * @param container The container to place the GUI components in.
     */
    private void configure(final Container container)
    {
        try
        {
            // Use invokeAndWait so that we can be sure that initialisation is complete
            // before continuing.
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    }
                    catch (Exception ex)
                    {
                        // This should never happen as we are installing a known look-and-feel.
                        System.err.println("Failed to load System look-and-feel.");
                    }
                    prepareGUI(container);
                }
            });
        }
        catch (InterruptedException ex)
        {
            // Restore interrupt flag.
            Thread.currentThread().interrupt();
        }
        catch (InvocationTargetException ex)
        {
            ex.getCause().printStackTrace();
            JOptionPane.showMessageDialog(container, ex.getCause(), "Error Occurred", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Implemented in sub-classes to initialise and layout the GUI.
     * @param container The container that this method should add components to.
     */
    protected abstract void prepareGUI(Container container);

    /**
     * Display this example program using a JFrame as the top-level GUI container (rather
     * than running the example as an applet).
     * @param title The text to use for the frame's title bar.
     */
    protected void displayInFrame(String title)
    {
        JFrame frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        configure(frame);
        frame.pack();
        frame.setVisible(true);
    }
}


text:
declare function whatsThatGerber<T extends string>(
  filenames: ReadonlyArray<T>
): Record<T, whatsThatGerber.GerberProps>

declare namespace whatsThatGerber {
  // TODO(mc, 2018-11-21): dedupe this definition and source
  const TYPE_COPPER = 'copper'
  const TYPE_SOLDERMASK = 'soldermask'
  const TYPE_SILKSCREEN = 'silkscreen'
  const TYPE_SOLDERPASTE = 'solderpaste'
  const TYPE_DRILL = 'drill'
  const TYPE_OUTLINE = 'outline'
  const TYPE_DRAWING = 'drawing'

  // board sides
  const SIDE_TOP = 'top'
  const SIDE_BOTTOM = 'bottom'
  const SIDE_INNER = 'inner'
  const SIDE_ALL = 'all'

  function validate(target: object): GerberProps & {valid: boolean}

  function getAllLayers(): Array<GerberProps>

  type GerberType =
    | typeof TYPE_COPPER
    | typeof TYPE_SOLDERMASK
    | typeof TYPE_SILKSCREEN
    | typeof TYPE_SOLDERPASTE
    | typeof TYPE_DRILL
    | typeof TYPE_OUTLINE
    | typeof TYPE_DRAWING
    | null

  type GerberSide =
    | typeof SIDE_TOP
    | typeof SIDE_BOTTOM
    | typeof SIDE_INNER
    | typeof SIDE_ALL
    | null

  interface GerberProps {
    type: GerberType
    side: GerberSide
  }
}

export = whatsThatGerber


text:
<?php

namespace Drupal\Core\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides dependency injection friendly methods for serialization.
 */
trait DependencySerializationTrait {

  /**
   * An array of service IDs keyed by property name used for serialization.
   *
   * @var array
   */
  protected $_serviceIds = array();

  /**
   * {@inheritdoc}
   */
  public function __sleep() {
    $this->_serviceIds = array();
    $vars = get_object_vars($this);
    foreach ($vars as $key => $value) {
      if (is_object($value) && isset($value->_serviceId)) {
        // If a class member was instantiated by the dependency injection
        // container, only store its ID so it can be used to get a fresh object
        // on unserialization.
        $this->_serviceIds[$key] = $value->_serviceId;
        unset($vars[$key]);
      }
      // Special case the container, which might not have a service ID.
      elseif ($value instanceof ContainerInterface) {
        $this->_serviceIds[$key] = 'service_container';
        unset($vars[$key]);
      }
    }

    return array_keys($vars);
  }

  /**
   * {@inheritdoc}
   */
  public function __wakeup() {
    // Tests in isolation potentially unserialize in the parent process.
    if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP']) && !\Drupal::hasContainer()) {
      return;
    }
    $container = \Drupal::getContainer();
    foreach ($this->_serviceIds as $key => $service_id) {
      $this->$key = $container->get($service_id);
    }
    $this->_serviceIds = array();
  }

}


text:
module Mongoid
  module Persistable

    # Defines behaviour for $inc operations.
    #
    # @since 4.0.0
    module Incrementable
      extend ActiveSupport::Concern

      # Increment the provided fields by the corresponding values. Values can
      # be positive or negative, and if no value exists for the field it will
      # be set with the provided value.
      #
      # @example Increment the fields.
      #   document.inc(score: 10, place: 1, lives: -10)
      #
      # @param [ Hash ] increments The field/inc increment pairs.
      #
      # @return [ Document ] The document.
      #
      # @since 4.0.0
      def inc(increments)
        prepare_atomic_operation do |ops|
          process_atomic_operations(increments) do |field, value|
            increment = value.__to_inc__
            current = attributes[field]
            attributes[field] = (current || 0) + increment
            ops[atomic_attribute_name(field)] = increment
          end
          { "$inc" => ops }
        end
      end
    end
  end
end