text:
// *************************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
//   Support: support@scichart.com
//   Sales:   sales@scichart.com
//
// BoxPlotExampleView.xaml.cs is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
// *************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using SciChart.Charting.Model.DataSeries;
using SciChart.Examples.ExternalDependencies.Data;

namespace SciChart.Examples.Examples.CreateSimpleChart
{
    /// <summary>
    /// Interaction logic for BoxPlotExampleView.xaml
    /// </summary>
    public partial class BoxPlotExampleView : UserControl
    {
        public BoxPlotExampleView()
        {
            InitializeComponent();

            this.Loaded += (sender, args) =>
                {
                    // Box data is a multi-dimensional table containing minimum, lower quartile, median, upper quartile, maximum Y values vs X
                    IEnumerable<BoxPoint> boxData = GetBoxPlotData(10).ToArray();

                    var boxDataSeries = new BoxPlotDataSeries<DateTime, double>();

                    boxDataSeries.Append(boxData.Select(x => x.Date),
                        boxData.Select(x => x.Median),
                        boxData.Select(x => x.Minimum),
                        boxData.Select(x => x.LowerQuartile),
                        boxData.Select(x => x.UpperQuartile),
                        boxData.Select(x => x.Maximum));

                    boxSeries.DataSeries = boxDataSeries;
                };

            sciChart.ZoomExtents();
        }

        private IEnumerable<BoxPoint> GetBoxPlotData(int count)
        {
            var dates = Enumerable.Range(0, count).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var medianValues = new RandomWalkGenerator().GetRandomWalkSeries(count).YData;

            var random = new Random();
            for (int i = 0; i < count; i++)
            {
                double med = medianValues[i];

                double min = med - random.NextDouble();
                double max = med + random.NextDouble();

                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

        private struct BoxPoint
        {
            public readonly DateTime Date;
            public readonly double Minimum;
            public readonly double LowerQuartile;
            public readonly double Median;
            public readonly double UpperQuartile;
            public readonly double Maximum;

            public BoxPoint(DateTime date, double min, double lower, double med, double upper, double max)
                : this()
            {
                Date = date;
                Minimum = min;
                LowerQuartile = lower;
                Median = med;
                UpperQuartile = upper;
                Maximum = max;
            }
        }
    }
}


text:
package com.sun.corba.se.impl.transport;

import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.omg.CORBA.INITIALIZE;
import org.omg.CORBA.INTERNAL;
import org.omg.CORBA.CompletionStatus;

import com.sun.corba.se.pept.transport.Acceptor;
import com.sun.corba.se.pept.transport.ConnectionCache;
import com.sun.corba.se.pept.transport.ByteBufferPool;
import com.sun.corba.se.pept.transport.ContactInfo;
import com.sun.corba.se.pept.transport.InboundConnectionCache;
import com.sun.corba.se.pept.transport.OutboundConnectionCache;
import com.sun.corba.se.pept.transport.Selector;

import com.sun.corba.se.spi.ior.IORTemplate;
import com.sun.corba.se.spi.ior.ObjectAdapterId;
import com.sun.corba.se.spi.orb.ORB;
import com.sun.corba.se.spi.transport.CorbaAcceptor;
import com.sun.corba.se.spi.transport.CorbaTransportManager;
import com.sun.corba.se.pept.transport.Connection;
import com.sun.corba.se.pept.transport.ConnectionCache;

// REVISIT - impl/poa specific:
import com.sun.corba.se.impl.oa.poa.Policies;
import com.sun.corba.se.impl.orbutil.ORBUtility;

/**
 * @author Harold Carr
 */
public class CorbaTransportManagerImpl
    implements
        CorbaTransportManager
{
    protected ORB orb;
    protected List acceptors;
    protected Map outboundConnectionCaches;
    protected Map inboundConnectionCaches;
    protected Selector selector;

    public CorbaTransportManagerImpl(ORB orb)
    {
        this.orb = orb;
        acceptors = new ArrayList();
        outboundConnectionCaches = new HashMap();
        inboundConnectionCaches = new HashMap();
        selector = new SelectorImpl(orb);
    }

    ////////////////////////////////////////////////////
    //
    // pept TransportManager
    //

    public ByteBufferPool getByteBufferPool(int id)
    {
        throw new RuntimeException();
    }

    public OutboundConnectionCache getOutboundConnectionCache(
        ContactInfo contactInfo)
    {
        synchronized (contactInfo) {
            if (contactInfo.getConnectionCache() == null) {
                OutboundConnectionCache connectionCache = null;
                synchronized (outboundConnectionCaches) {
                    connectionCache = (OutboundConnectionCache)
                        outboundConnectionCaches.get(
                            contactInfo.getConnectionCacheType());
                    if (connectionCache == null) {
                        // REVISIT: Would like to be able to configure
                        // the connection cache type used.
                        connectionCache =
                            new CorbaOutboundConnectionCacheImpl(orb,
                                                                 contactInfo);
                        outboundConnectionCaches.put(
                            contactInfo.getConnectionCacheType(),
                            connectionCache);
                    }
                }
                contactInfo.setConnectionCache(connectionCache);
            }
            return contactInfo.getConnectionCache();
        }
    }

    public Collection getOutboundConnectionCaches()
    {
        return outboundConnectionCaches.values();
    }

    public InboundConnectionCache getInboundConnectionCache(
        Acceptor acceptor)
    {
        synchronized (acceptor) {
            if (acceptor.getConnectionCache() == null) {
                InboundConnectionCache connectionCache = null;
                synchronized (inboundConnectionCaches) {
                    connectionCache = (InboundConnectionCache)
                        inboundConnectionCaches.get(
                            acceptor.getConnectionCacheType());
                    if (connectionCache == null) {
                        // REVISIT: Would like to be able to configure
                        // the connection cache type used.
                        connectionCache =
                            new CorbaInboundConnectionCacheImpl(orb,
                                                                acceptor);
                        inboundConnectionCaches.put(
                            acceptor.getConnectionCacheType(),
                            connectionCache);
                    }
                }
                acceptor.setConnectionCache(connectionCache);
            }
            return acceptor.getConnectionCache();
        }
    }

    public Collection getInboundConnectionCaches()
    {
        return inboundConnectionCaches.values();
    }

    public Selector getSelector(int id)
    {
        return selector;
    }

    public synchronized void registerAcceptor(Acceptor acceptor)
    {
        if (orb.transportDebugFlag) {
            dprint(".registerAcceptor->: " + acceptor);
        }
        acceptors.add(acceptor);
        if (orb.transportDebugFlag) {
            dprint(".registerAcceptor<-: " + acceptor);
        }
    }

    public Collection getAcceptors()
    {
        return getAcceptors(null, null);
    }

    public synchronized void unregisterAcceptor(Acceptor acceptor)
    {
        acceptors.remove(acceptor);
    }

    public void close()
    {
        try {
            if (orb.transportDebugFlag) {
                dprint(".close->");
            }
            for (Object cc : outboundConnectionCaches.values()) {
                ((ConnectionCache)cc).close() ;
            }
            for (Object cc : inboundConnectionCaches.values()) {
                ((ConnectionCache)cc).close() ;
            }
            getSelector(0).close();
        } finally {
            if (orb.transportDebugFlag) {
                dprint(".close<-");
            }
        }
    }

    ////////////////////////////////////////////////////
    //
    // CorbaTransportManager
    //

    public Collection getAcceptors(String objectAdapterManagerId,
                                   ObjectAdapterId objectAdapterId)
    {
        // REVISIT - need to filter based on arguments.

        // REVISIT - initialization will be moved to OA.
        // Lazy initialization of acceptors.
        Iterator iterator = acceptors.iterator();
        while (iterator.hasNext()) {
            Acceptor acceptor = (Acceptor) iterator.next();
            if (acceptor.initialize()) {
                if (acceptor.shouldRegisterAcceptEvent()) {
                    orb.getTransportManager().getSelector(0)
                        .registerForEvent(acceptor.getEventHandler());
                }
            }
        }
        return acceptors;
    }

    // REVISIT - POA specific policies
    public void addToIORTemplate(IORTemplate iorTemplate,
                                 Policies policies,
                                 String codebase,
                                 String objectAdapterManagerId,
                                 ObjectAdapterId objectAdapterId)
    {
        Iterator iterator =
            getAcceptors(objectAdapterManagerId, objectAdapterId).iterator();
        while (iterator.hasNext()) {
            CorbaAcceptor acceptor = (CorbaAcceptor) iterator.next();
            acceptor.addToIORTemplate(iorTemplate, policies, codebase);
        }
    }

    ////////////////////////////////////////////////////
    //
    // implemenation
    //

    protected void dprint(String msg)
    {
        ORBUtility.dprint("CorbaTransportManagerImpl", msg);
    }
}

// End of file.

redpajama_set_name: RedPajamaGithub


text:
/* OPENBSD ORIGINAL: lib/libc/stdlib/realpath.c */

/*
 * Copyright (c) 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Jan-Simon Pendry.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "includes.h"

#if !defined(HAVE_REALPATH) || defined(BROKEN_REALPATH)

#if defined(LIBC_SCCS) && !defined(lint)
static char *rcsid = "$OpenBSD: realpath.c,v 1.11 2004/11/30 15:12:59 millert Exp $";
#endif /* LIBC_SCCS and not lint */

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

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/*
 * MAXSYMLINKS
 */
#ifndef MAXSYMLINKS
#define MAXSYMLINKS 5
#endif

/*
 * char *realpath(const char *path, char resolved_path[MAXPATHLEN]);
 *
 * Find the real name of path, by removing all ".", ".." and symlink
 * components.  Returns (resolved) on success, or (NULL) on failure,
 * in which case the path which caused trouble is left in (resolved).
 */
char *
realpath(const char *path, char *resolved)
{
	struct stat sb;
	int fd, n, needslash, serrno;
	char *p, *q, wbuf[MAXPATHLEN];
	int symlinks = 0;

	/* Save the starting point. */
#ifndef HAVE_FCHDIR
	char start[MAXPATHLEN];
	/* this is potentially racy but without fchdir we have no option */
	if (getcwd(start, sizeof(start)) == NULL) {
		resolved[0] = '.';
		resolved[1] = '\0';
		return (NULL);
	}
#endif
	if ((fd = open(".", O_RDONLY)) < 0) {
		resolved[0] = '.';
		resolved[1] = '\0';
		return (NULL);
	}

	/* Convert "." -> "" to optimize away a needless lstat() and chdir() */
	if (path[0] == '.' && path[1] == '\0')
		path = "";

	/*
	 * Find the dirname and basename from the path to be resolved.
	 * Change directory to the dirname component.
	 * lstat the basename part.
	 *     if it is a symlink, read in the value and loop.
	 *     if it is a directory, then change to that directory.
	 * get the current directory name and append the basename.
	 */
	if (strlcpy(resolved, path, MAXPATHLEN) >= MAXPATHLEN) {
		serrno = ENAMETOOLONG;
		goto err2;
	}
loop:
	q = strrchr(resolved, '/');
	if (q != NULL) {
		p = q + 1;
		if (q == resolved)
			q = "/";
		else {
			do {
				--q;
			} while (q > resolved && *q == '/');
			q[1] = '\0';
			q = resolved;
		}
		if (chdir(q) < 0)
			goto err1;
	} else
		p = resolved;

	/* Deal with the last component. */
	if (*p != '\0' && lstat(p, &sb) == 0) {
		if (S_ISLNK(sb.st_mode)) {
			if (++symlinks > MAXSYMLINKS) {
				errno = ELOOP;
				goto err1;
			}
			if ((n = readlink(p, resolved, MAXPATHLEN-1)) < 0)
				goto err1;
			resolved[n] = '\0';
			goto loop;
		}
		if (S_ISDIR(sb.st_mode)) {
			if (chdir(p) < 0)
				goto err1;
			p = "";
		}
	}

	/*
	 * Save the last component name and get the full pathname of
	 * the current directory.
	 */
	if (strlcpy(wbuf, p, sizeof(wbuf)) >= sizeof(wbuf)) {
		errno = ENAMETOOLONG;
		goto err1;
	}
	if (getcwd(resolved, MAXPATHLEN) == NULL)
		goto err1;

	/*
	 * Join the two strings together, ensuring that the right thing
	 * happens if the last component is empty, or the dirname is root.
	 */
	if (resolved[0] == '/' && resolved[1] == '\0')
		needslash = 0;
	else
		needslash = 1;

	if (*wbuf) {
		if (strlen(resolved) + strlen(wbuf) + needslash >= MAXPATHLEN) {
			errno = ENAMETOOLONG;
			goto err1;
		}
		if (needslash) {
			if (strlcat(resolved, "/", MAXPATHLEN) >= MAXPATHLEN) {
				errno = ENAMETOOLONG;
				goto err1;
			}
		}
		if (strlcat(resolved, wbuf, MAXPATHLEN) >= MAXPATHLEN) {
			errno = ENAMETOOLONG;
			goto err1;
		}
	}

	/* Go back to where we came from. */
#ifdef HAVE_FCHDIR
	if (fchdir(fd) < 0) {
#else
	if (chdir(start) < 0) {
#endif
		serrno = errno;
		goto err2;
	}

	/* It's okay if the close fails, what's an fd more or less? */
	(void)close(fd);
	return (resolved);

err1:	serrno = errno;
#ifdef HAVE_FCHDIR
	(void)fchdir(fd);
#else
	chdir(start);
#endif
err2:	(void)close(fd);
	errno = serrno;
	return (NULL);
}
#endif /* !defined(HAVE_REALPATH) || defined(BROKEN_REALPATH) */


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.05.04 at 06:39:06 PM CEST
//

package com.sap.dpre.entities.jaxb.policy;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element ref="{}Type"/>
 *         <element name="Hide" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "name",
    "type",
    "hide"
})
@XmlRootElement(name = "Column")
public class Column {

    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Type", required = true)
    protected String type;
    @XmlElement(name = "Hide")
    protected boolean hide;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     * Gets the value of the hide property.
     *
     */
    public boolean isHide() {
        return hide;
    }

    /**
     * Sets the value of the hide property.
     *
     */
    public void setHide(boolean value) {
        this.hide = value;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Module: ActionController::Streaming</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

  Module
ActionController::Streaming

        In:

actionpack/lib/action_controller/streaming.rb

Methods for sending arbitrary data and for streaming files to the browser,
instead of rendering.

Methods

send_data

send_file

Constants

    DEFAULT_SEND_FILE_OPTIONS
    =
    {       :type         => 'application/octet-stream'.freeze,       :disposition  => 'attachment'.freeze,       :stream       => true,       :buffer_size  => 4096,       :x_sendfile   => false

    X_SENDFILE_HEADER
    =
    'X-Sendfile'.freeze

Protected Instance methods

    send_data(data, options = {})

Sends the given binary data to the browser. This method is similar to
<tt>render :text => data</tt>, but also allows you to specify whether
the browser should display the response as a file attachment (i.e. in a
download dialog) or as inline data. You may also set the content type, the
apparent file name, and other things.

Options:

<tt>:filename</tt> - suggests a filename for the browser to use.

<tt>:type</tt> - specifies an HTTP content type. Defaults to
‘application/octet-stream’. You can specify either a string or
a symbol for a registered type register with <tt>Mime::Type.register</tt>,
for example :json

<tt>:disposition</tt> - specifies whether the file will be shown inline or
downloaded. Valid values are ‘inline’ and
‘attachment’ (default).

<tt>:status</tt> - specifies the status code to send with the response.
Defaults to ‘200 OK’.

Generic data download:

  send_data buffer

Download a dynamically-generated tarball:

  send_data generate_tgz('dir'), :filename => 'dir.tgz'

Display an image Active Record in the browser:

  send_data image.data, :type => image.content_type, :disposition => 'inline'

See <tt>send_file</tt> for more
information on HTTP Content-* headers and caching.

Tip: if you want to stream large amounts of on-the-fly generated
data to the browser, then use <tt>render :text => proc { … }</tt>
instead. See ActionController::Base#render
for more information.

[ show source ]

     # File actionpack/lib/action_controller/streaming.rb, line 140
140:       def send_data(data, options = {}) #:doc:
141:         logger.info "Sending data #{options[:filename]}" if logger
142:         send_file_headers! options.merge(:length => data.bytesize)
143:         @performed_render = false
144:         render :status => options[:status], :text => data
145:       end

    send_file(path, options = {})

Sends the file, by default streaming it 4096 bytes at a time. This way the
whole file doesn‘t need to be read into memory at once. This makes it
feasible to send even large files. You can optionally turn off streaming
and send the whole file at once.

Be careful to sanitize the path parameter if it is coming from a web page.
<tt>send_file(params[:path])</tt>
allows a malicious user to download any file on your server.

Options:

<tt>:filename</tt> - suggests a filename for the browser to use. Defaults
to <tt>File.basename(path)</tt>.

<tt>:type</tt> - specifies an HTTP content type. Defaults to
‘application/octet-stream’. You can specify either a string or
a symbol for a registered type register with <tt>Mime::Type.register</tt>,
for example :json

<tt>:length</tt> - used to manually override the length (in bytes) of the
content that is going to be sent to the client. Defaults to
<tt>File.size(path)</tt>.

<tt>:disposition</tt> - specifies whether the file will be shown inline or
downloaded. Valid values are ‘inline’ and
‘attachment’ (default).

<tt>:stream</tt> - whether to send the file to the user agent as it is read
(<tt>true</tt>) or to read the entire file before sending (<tt>false</tt>).
Defaults to <tt>true</tt>.

<tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to
stream the file. Defaults to 4096.

<tt>:status</tt> - specifies the status code to send with the response.
Defaults to ‘200 OK’.

<tt>:url_based_filename</tt> - set to <tt>true</tt> if you want the browser
guess the filename from the URL, which is necessary for i18n filenames on
certain browsers (setting <tt>:filename</tt> overrides this option).

<tt>:x_sendfile</tt> - uses X-Sendfile to send the file when set to
<tt>true</tt>. This is currently only available with Lighttpd/Apache2 and
specific modules installed and activated. Since this uses the web server to
send the file, this may lower memory consumption on your server and it will
not block your application for further requests. See blog.lighttpd.net/articles/2006/07/02/x-sendfile
and tn123.ath.cx/mod_xsendfile/
for details. Defaults to <tt>false</tt>.

The default Content-Type and Content-Disposition headers are set to
download arbitrary binary files in as many browsers as possible. IE
versions 4, 5, 5.5, and 6 are all known to have a variety of quirks
(especially when downloading over SSL).

Simple download:

  send_file '/path/to.zip'

Show a JPEG in the browser:

  send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'

Show a 404 page in the browser:

  send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404

Read about the other Content-* HTTP headers if you‘d like to provide
the user with more information (such as Content-Description) in www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.

Also be aware that the document may be cached by proxies and browsers. The
Pragma and Cache-Control headers declare how the file may be cached by
intermediaries. They default to require clients to validate with the server
before releasing cached responses. See www.mnot.net/cache_docs/ for an
overview of web caching and www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
for the Cache-Control header spec.

[ show source ]

     # File actionpack/lib/action_controller/streaming.rb, line 79
 79:       def send_file(path, options = {}) #:doc:
 80:         raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
 81:
 82:         options[:length]   ||= File.size(path)
 83:         options[:filename] ||= File.basename(path) unless options[:url_based_filename]
 84:         send_file_headers! options
 85:
 86:         @performed_render = false
 87:
 88:         if options[:x_sendfile]
 89:           logger.info "Sending #{X_SENDFILE_HEADER} header #{path}" if logger
 90:           head options[:status], X_SENDFILE_HEADER => path
 91:         else
 92:           if options[:stream]
 93:             render :status => options[:status], :text => Proc.new { |response, output|
 94:               logger.info "Streaming file #{path}" unless logger.nil?
 95:               len = options[:buffer_size] || 4096
 96:               File.open(path, 'rb') do |file|
 97:                 while buf = file.read(len)
 98:                   output.write(buf)
 99:                 end
100:               end
101:             }
102:           else
103:             logger.info "Sending file #{path}" unless logger.nil?
104:             File.open(path, 'rb') { |file| render :status => options[:status], :text => file.read }
105:           end
106:         end
107:       end


text:
<?php
namespace PhpDescribe\Spec;
describe('Greater than specs', function() {

    it('should pass', function() {
        expect(5)->should('be greater than',2);
    });

    it('should fail', function() {
        expect(3)->should('be greater than',8);
    });

    it('should be greater than', function() {
        expect(3)->should('be greater than',3);
    });

});


text:
package com.breezee.prj.sodexo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import java.io.IOException;

/**
 * Created by Silence on 2016/2/10.
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.breezee")
@ImportResource(value = {"classpath:/sodexo-provider.xml"})
public class SodexoService {

    /**
     * 启动本服务
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        SpringApplication.run(SodexoService.class, args);
    }
}


text:
using System;
using ServiceStack.DataAnnotations;

namespace CrawlLeague.ServiceModel.Types
{
    public class ParticipantStatus
    {
        [Description("Name of the crawler")]
        public string UserName { get; set; }

        [Description("Name of the division that the participant belongs to")]
        public string DivisionName { get; set; }

        [Description("Name of the server that the participant plays on")]
        public string ServerName { get; set; }

        [Description("Abbreviation of the server that the participant plays on")]
        public string ServerAbbreviation { get; set; }

        [Description("Curent total score for the season")]
        public int Score { get; set; }

        [Description("Number of games played during the season")]
        public int GamesPlayed { get; set; }

        [Description("Number of games won during the season")]
        public int WinCount { get; set; }

        [Description("Number of character levels gained")]
        public int TotalCharacaterLevels { get; set; }

        [Description("Number of branches visited during the season")]
        public int BranchesVisited { get; set; }

        [Description("Number of dungeon levels visited during the season")]
        public int LevelsVisited { get; set; }

        [Description("Number of runes collected during the season")]
        public int RuneCount { get; set; }

        [Description("Number of kills made during the season")]
        public int TotalKills { get; set; }

        [Description("When was the last game recorded for this participant")]
        public DateTime LastGame { get; set; }

        [Description("References to peripheral resources")]
        public ParticipantRefs References { get; set; }
    }
}


text:
typedef NS_ENUM(NSUInteger,LCCheckMobileModel) {
    LCCheckMobileSMSModel = 100,
    LCCheckMobilePhoneModel = 101,
};

@interface LCHTTPSessionManager (AotumanUserAPI)

- (NSURLSessionDataTask *)signin:(NSString *)username
                        password:(NSString *)password
                         success:(void (^)(NSDictionary *))success
                         failure:(LCHTTPSessionFailureBlock)failure;
@end


text:
<!--{ ids:[132], language:'JavaScript', type:'workshop', order: 0, name:'Variables I', description:'Create variable and store data' }-->

### Exercise

Declare a variable named `numberOfStatesInUSA`. Assign that variable the number of states that make up the USA. If you do not know this number, do a search or phone a friend.


text:
package demo.java.v2c06.ProgressBarTest;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

import javax.swing.*;

/**
 * This program demonstrates the use of a progress bar to monitor the progress of a thread.
 * @version 1.04 2007-08-01
 * @author Cay Horstmann
 */
public class ProgressBarTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               JFrame frame = new ProgressBarFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * A frame that contains a button to launch a simulated activity, a progress bar, and a text area
 * for the activity output.
 */
class ProgressBarFrame extends JFrame
{
   public ProgressBarFrame()
   {
      setTitle("ProgressBarTest");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // this text area holds the activity output
      textArea = new JTextArea();

      // set up panel with button and progress bar

      final int MAX = 1000;
      JPanel panel = new JPanel();
      startButton = new JButton("Start");
      progressBar = new JProgressBar(0, MAX);
      progressBar.setStringPainted(true);
      panel.add(startButton);
      panel.add(progressBar);

      checkBox = new JCheckBox("indeterminate");
      checkBox.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               progressBar.setIndeterminate(checkBox.isSelected());
               progressBar.setStringPainted(!progressBar.isIndeterminate());
            }
         });
      panel.add(checkBox);
      add(new JScrollPane(textArea), BorderLayout.CENTER);
      add(panel, BorderLayout.SOUTH);

      // set up the button action

      startButton.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               startButton.setEnabled(false);
               activity = new SimulatedActivity(MAX);
               activity.execute();
            }
         });
   }

   private JButton startButton;
   private JProgressBar progressBar;
   private JCheckBox checkBox;
   private JTextArea textArea;
   private SimulatedActivity activity;

   public static final int DEFAULT_WIDTH = 400;
   public static final int DEFAULT_HEIGHT = 200;

   class SimulatedActivity extends SwingWorker<Void, Integer>
   {
      /**
       * Constructs the simulated activity that increments a counter from 0 to a
       * given target.
       * @param t the target value of the counter.
       */
      public SimulatedActivity(int t)
      {
         current = 0;
         target = t;
      }

      protected Void doInBackground() throws Exception
      {
         try
         {
            while (current < target)
            {
               Thread.sleep(100);
               current++;
               publish(current);
            }
         }
         catch (InterruptedException e)
         {
         }
         return null;
      }

      protected void process(List<Integer> chunks)
      {
         for (Integer chunk : chunks)
         {
            textArea.append(chunk + "\n");
            progressBar.setValue(chunk);
         }
      }

      protected void done()
      {
         startButton.setEnabled(true);
      }

      private int current;
      private int target;
   }
}


text:
package nl.nn.adapterframework.management.bus;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.List;
import java.util.Map;

import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * In the Log4J4Ibis.xml is a nl.nn.adapterframework.management.bus definition which we use here to test the BUS responses.
 */
@SuppressWarnings("unchecked") //can be removed once we implement a DAO
public class TestUpdateLogDefinitions extends BusTestBase {
	private static final String LOG_DEFINITION_PACKAGE = "nl.nn.adapterframework.management.bus";
	private static final String EXCEPTION_MESSAGE = "neither [reconfigure], [logPackage] or [level] provided";

	@Test
	public void getLogDefinitions() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.GET);
		Message<?> response = callSyncGateway(request);
		String json = (String) response.getPayload();

		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> responseMap = mapper.readValue(json, Map.class);

		Object loggersObj = responseMap.get("loggers");
		if(loggersObj instanceof Map) {
			Map<String, Object> loggers = (Map<String, Object>) loggersObj;
			assertEquals("DEBUG", loggers.get(LOG_DEFINITION_PACKAGE));
		}

		boolean foundTestDefinition = false;
		Object definitionsObj = responseMap.get("definitions");
		if(definitionsObj instanceof List) {
			List<Map<String, ?>> definitions = (List<Map<String, ?>>) definitionsObj;
			for(Map<String, ?> definition : definitions) {
				if(LOG_DEFINITION_PACKAGE.equals(definition.get("name"))) {
					foundTestDefinition = true;
					assertEquals("DEBUG", definition.get("level"));
				}
			}
		}

		assertTrue("not testing the log definition retrieval!", foundTestDefinition);
	}

	@Test
	public void getLogDefinitionsWithFilter() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.GET);
		request.setHeader("filter", LOG_DEFINITION_PACKAGE);
		Message<?> response = callSyncGateway(request);
		String json = (String) response.getPayload();

		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> responseMap = mapper.readValue(json, Map.class);

		Object loggersObj = responseMap.get("loggers");
		if(loggersObj instanceof Map) {
			Map<String, String> loggers = (Map<String, String>) loggersObj;
			assertEquals("DEBUG", loggers.get("nl.nn.adapterframework.management.bus.endpoints"));
		}

		assertThat(json, Matchers.containsString("\"nl.nn.adapterframework.management.bus\":"));
		assertThat(json, Matchers.containsString("\"nl.nn.adapterframework.management.bus.endpoints\":"));
	}

	@Test
	public void reconfigureLogDefinitionsNoHeaders() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);

		try {
			callSyncGateway(request);
		} catch (Exception e) {
			assertTrue(e.getCause() instanceof BusException);
			BusException be = (BusException) e.getCause();
			assertEquals(EXCEPTION_MESSAGE, be.getMessage());
		}
	}

	@Test
	public void reconfigureLogDefinitionsEmptyHeader() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);
		request.setHeader("reconfigure", "");
		Message<?> response = callSyncGateway(request);

		assertEquals(204, response.getHeaders().get(ResponseMessage.STATUS_KEY));
	}

	@Test
	public void reconfigureLogDefinitions() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);
		request.setHeader("reconfigure", "true");
		Message<?> response = callSyncGateway(request);

		assertEquals(202, response.getHeaders().get(ResponseMessage.STATUS_KEY));
	}

	@Test
	public void updateLogDefinitionsEmptyHeader() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);
		request.setHeader("logPackage", LOG_DEFINITION_PACKAGE);
		request.setHeader("level", "");

		try {
			callSyncGateway(request);
		} catch (Exception e) {
			assertTrue(e.getCause() instanceof BusException);
			BusException be = (BusException) e.getCause();
			assertEquals(EXCEPTION_MESSAGE, be.getMessage());
		}
	}

	@Test
	public void updateLogDefinitionsNoHeader() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);
		request.setHeader("logPackage", LOG_DEFINITION_PACKAGE);

		try {
			callSyncGateway(request);
		} catch (Exception e) {
			assertTrue(e.getCause() instanceof BusException);
			BusException be = (BusException) e.getCause();
			assertEquals(EXCEPTION_MESSAGE, be.getMessage());
		}
	}

	@Test
	public void updateLogDefinitions() throws Exception {
		MessageBuilder<String> request = createRequestMessage("NONE", BusTopic.LOG_DEFINITIONS, BusAction.MANAGE);
		request.setHeader("logPackage", LOG_DEFINITION_PACKAGE);
		request.setHeader("level", "debug");
		Message<?> response = callSyncGateway(request);

		assertEquals(202, response.getHeaders().get(ResponseMessage.STATUS_KEY));
	}
}


text:
title:  "Secret History of Silicon Valley"
date:   2011-06-28 00:00:00
categories:
tags:
comments: true
---

This isn't new but anyone interested in the evolution of the technology and entrepreneurial ecosystem of silicon valley should check out Steve Blanks secret history talk. It starts with the evolution of radar during world war 2 but it gets us to silicon valley today.

<iframe width="420" height="315" src="//www.youtube.com/embed/ZTC_RxWN_xo" frameborder="0" allowfullscreen></iframe>


text:
package org.terasology.logic.permission;

import com.google.common.base.Predicate;
import org.terasology.entitySystem.entity.EntityRef;

public interface PermissionManager {
    /**
     * Allows the player to use chat commands.
     */
    static final String CHAT_PERMISSION = "chat";

    /**
     * Allows the player to use cheats that
     *

     *
1. have no global impact.

     *
2. don't endanger the stability of the game

     *

     * The intention is that the permission can be given to all players on a server where players focus on building and
     * not mining.
     */
    static final String CHEAT_PERMISSION = "cheat";

    /**
     * Used to indicate that something requires no permission.
     */
    static final String NO_PERMISSION = "";

    /**
     * Allows the player to edit settings of other users.
     *
     * e.g. adding permissions, renaming them etc.
     */
    static final String USER_MANAGEMENT_PERMISSION = "userManagement";

    /**
     * Allows the player to perform server maintenance tasks like stopping the server.
     */
    static final String SERVER_MANAGEMENT_PERMISSION = "serverManagement";

    /**
     * Allows the player to use debug commands which are not intended to be used on a real server.
     */
    static final String DEBUG_PERMISSION = "debug";

    /**
     * Adds specified permission to the player (client info entity).
     *
     * @param player     Player (client info entity) to add permission to.
     * @param permission Permission to add.
     */
    void addPermission(EntityRef player, String permission);

    /**
     * Checks if the specified player (client info entity) has said permission.
     * Note: Local player is considered to have all the permissions in all situations.
     *
     * @param player     Player (client info entity) to check.
     * @param permission Permission to check.
     * @return If player (client info entity) has permission.
     */
    boolean hasPermission(EntityRef player, String permission);

    /**
     * Checks if the specified player (client info entity) has permission that is accepted by the specified predicate.
     * Note: Local player is considered to have all the permissions in all situations.
     *
     * @param player              Player (client info entity) to check.
     * @param permissionPredicate Permission predicate to check against.
     * @return If player (client info entity) has permission matching the predicate.
     */
    boolean hasPermission(EntityRef player, Predicate<String> permissionPredicate);

    /**
     * Removes specified permission from the player (client info entity).
     *
     * @param player     Player (client info entity) to remove permission from.
     * @param permission Permission to remove.
     */
    void removePermission(EntityRef player, String permission);
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Getting started</title>
<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../mpi.html" title="Chapter 19. Boost.MPI">
<link rel="prev" href="../mpi.html" title="Chapter 19. Boost.MPI">
<link rel="next" href="tutorial.html" title="Tutorial">

Home
Libraries
People
FAQ
More

Getting started

MPI Implementation

Configure and Build

Installing and Using Boost.MPI

Testing Boost.MPI

      Getting started with Boost.MPI requires a working MPI implementation, a recent
      version of Boost, and some configuration information.

MPI Implementation

        To get started with Boost.MPI, you will first need a working MPI implementation.
        There are many conforming MPI
        implementations available. Boost.MPI should work with any of the
        implementations, although it has only been tested extensively with:

            Open MPI 1.0.x

            LAM/MPI 7.x

            MPICH 1.2.x

        You can test your implementation using the following simple program, which
        passes a message from one processor to another. Each processor prints a message
        to standard output.

#include <mpi.h>
#include <iostream>

int main(int argc, char* argv[])
{
  MPI_Init(&argc, &argv);

  int rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  if (rank == 0) {
    int value = 17;
    int result = MPI_Send(&value, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
    if (result == MPI_SUCCESS)
      std::cout << "Rank 0 OK!" << std::endl;
  } else if (rank == 1) {
    int value;
    int result = MPI_Recv(&value, 1, MPI_INT, 0, 0, MPI_COMM_WORLD,
			  MPI_STATUS_IGNORE);
    if (result == MPI_SUCCESS && value == 17)
      std::cout << "Rank 1 OK!" << std::endl;
  }
  MPI_Finalize();
  return 0;
}

        You should compile and run this program on two processors. To do this, consult
        the documentation for your MPI implementation. With LAM/MPI,
        for instance, you compile with the mpiCC
        or mpic++
        compiler, boot the LAM/MPI daemon, and run your program via mpirun. For instance, if your program is
        called mpi-test.cpp,
        use the following commands:

mpiCC -o mpi-test mpi-test.cpp
lamboot
mpirun -np 2 ./mpi-test
lamhalt

        When you run this program, you will see both Rank
        0 OK! and Rank
        1 OK! printed to the screen. However, they may
        be printed in any order and may even overlap each other. The following output
        is perfectly legitimate for this MPI program:

Rank Rank 1 OK!
0 OK!

        If your output looks something like the above, your MPI implementation appears
        to be working with a C++ compiler and we're ready to move on.

Configure and Build

        Boost.MPI uses version 2 of the Boost.Build
        system for configuring and building the library binary. You will need a very
        new version of Boost.Jam
        (3.1.12 or later). If you already have Boost.Jam, run bjam
        -v
        to determine what version you are using.

        Information about building Boost.Jam is available
        here. However, most users need only run build.sh in
        the tools/build/jam_src subdirectory of Boost. Then, copy
        the resulting bjam executable
        some place convenient.

        For many users using LAM/MPI,
        MPICH, or OpenMPI, configuration is almost automatic.
        If you don't already have a file user-config.jam in
        your home directory, copy tools/build/v2/user-config.jam there.
        For many users, MPI support can be enabled simply by adding the following
        line to your user-config.jam file, which is used to configure Boost.Build
        version 2.

using mpi ;

        This should auto-detect MPI settings based on the MPI wrapper compiler in
        your path, e.g., mpic++.
        If the wrapper compiler is not in your path, see below.

        To actually build the MPI library, go into the top-level Boost directory
        and execute the command:

bjam --with-mpi

        If your MPI wrapper compiler has a different name from the default, you can
        pass the name of the wrapper compiler as the first argument to the mpi module:

using mpi : /opt/mpich2-1.0.4/bin/mpiCC ;

        If your MPI implementation does not have a wrapper compiler, or the MPI auto-detection
        code does not work with your MPI's wrapper compiler, you can pass MPI-related
        options explicitly via the second parameter to the mpi
        module:

using mpi : : <find-shared-library>lammpio <find-shared-library>lammpi++
              <find-shared-library>mpi <find-shared-library>lam
              <find-shared-library>dl ;

        To see the results of MPI auto-detection, pass --debug-configuration on the bjam command line.

        The (optional) fourth argument configures Boost.MPI for running regression
        tests. These parameters specify the executable used to launch jobs (default:
        "mpirun") followed by any necessary arguments to this to run tests
        and tell the program to expect the number of processors to follow (default:
        "-np"). With the default parameters, for instance, the test harness
        will execute, e.g.,

mpirun -np 4 all_gather_test

Installing and Using Boost.MPI

        Installation of Boost.MPI can be performed in the build step by specifying
        install on the command line
        and (optionally) providing an installation location, e.g.,

bjam --with-mpi install

        This command will install libraries into a default system location. To change
        the path where libraries will be installed, add the option --prefix=PATH.

        To build applications based on Boost.MPI, compile and link them as you normally
        would for MPI programs, but remember to link against the boost_mpi
        and boost_serialization libraries,
        e.g.,

mpic++ -I/path/to/boost/mpi my_application.cpp -Llibdir \
  -lboost_mpi-gcc-mt-1_35 -lboost_serialization-gcc-d-1_35.a

      If you plan to use the Python bindings for
      Boost.MPI in conjunction with the C++ Boost.MPI, you will also need to link
      against the boost_mpi_python library, e.g., by adding -lboost_mpi_python-gcc-mt-1_35
      to your link command. This step will only be necessary if you intend to register C++ types or use the skeleton/content
      mechanism from within Python.

Testing Boost.MPI

        If you would like to verify that Boost.MPI is working properly with your
        compiler, platform, and MPI implementation, a self-contained test suite is
        available. To use this test suite, you will need to first configure Boost.Build
        for your MPI environment and then run bjam
        in libs/mpi/test
        (possibly with some extra options). For LAM/MPI,
        you will need to run lamboot
        before running bjam. For
        MPICH, you may
        need to create a machine file and pass -sMPIRUN_FLAGS="-machinefile <filename>" to
        Boost.Jam; see the section on configuration
        for more information. If testing succeeds, bjam
        will exit without errors.

Copyright © 2005-2007 Douglas Gregor,
      Matthias Troyer, Trustees of Indiana University

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at
        http://www.boost.org/LICENSE_1_0.txt )


text:
define(function() {

  return function(scopeId) {
    var tmpl = '
'+
               '
'+
               '        '+
               '            '+
               '        '+
               '
'+
               '
Show All Columns
'+
               '
'+
               '                Show Column'+
               // '
'+
               // '                    '+
               // '                    <input placeholder="search...">'+
               // '
'+
               '
'+
               '
'+
               '
'+
               '
Hide All Columns
'+
               '
'+
               '                Use pagination'+
               '                '+
               '
'+
               '
'+
               '                Rows to Show'+
               '

'+
               '
'+
               '
Select All Rows
'+
               '
Deselect All Rows
'+
               '
Reverse Selection
'+
               '
Copy to Clipboard
'+ // ????
               // '
Save All as CSV
'+
               // '
Save Selected as CSV
'+
               '
Download All as CSV
'+
               '
Download Selected as CSV
'+
               '
'+
               '                Search...'+
               '                '+
               '
'+
               '
'+
               '                Filter...'+
               '                '+
               '
'+
               '
Hide Filter
'+
               '
Reset All Interactions
'+
               '
'+
               '
'+
               ''+
               '
'+
               '
'+
               '

'+
               '

'+
               '
'+
               '
'+
               '
';

    return tmpl;

  }

});


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

using Internal.NativeFormat;

namespace Internal.TypeSystem
{
    public abstract partial class TypeSystemContext
    {
        public TypeSystemContext() : this(new TargetDetails(TargetArchitecture.Unknown, TargetOS.Unknown, TargetAbi.Unknown))
        {
        }

        public TypeSystemContext(TargetDetails target)
        {
            Target = target;

            _instantiatedTypes = new InstantiatedTypeKey.InstantiatedTypeKeyHashtable();

            _arrayTypes = new ArrayTypeKey.ArrayTypeKeyHashtable();

            _byRefTypes = new ByRefHashtable();

            _pointerTypes = new PointerHashtable();

            _functionPointerTypes = new FunctionPointerHashtable();

            _instantiatedMethods = new InstantiatedMethodKey.InstantiatedMethodKeyHashtable();

            _methodForInstantiatedTypes = new MethodForInstantiatedTypeKey.MethodForInstantiatedTypeKeyHashtable();

            _fieldForInstantiatedTypes = new FieldForInstantiatedTypeKey.FieldForInstantiatedTypeKeyHashtable();

            _signatureVariables = new SignatureVariableHashtable(this);
        }

        public TargetDetails Target
        {
            get;
        }

        public ModuleDesc SystemModule
        {
            get;
            private set;
        }

        protected void InitializeSystemModule(ModuleDesc systemModule)
        {
            Debug.Assert(SystemModule == null);
            SystemModule = systemModule;
        }

        public abstract DefType GetWellKnownType(WellKnownType wellKnownType);

        public virtual ModuleDesc ResolveAssembly(AssemblyName name, bool throwIfNotFound = true)
        {
            if (throwIfNotFound)
                throw new NotSupportedException();
            return null;
        }

        //
        // Array types
        //

        public ArrayType GetArrayType(TypeDesc elementType)
        {
            return GetArrayType(elementType, -1);
        }

        //
        // MDArray types
        //

        private struct ArrayTypeKey
        {
            private TypeDesc _elementType;
            private int _rank;

            public ArrayTypeKey(TypeDesc elementType, int rank)
            {
                _elementType = elementType;
                _rank = rank;
            }

            public TypeDesc ElementType
            {
                get
                {
                    return _elementType;
                }
            }

            public int Rank
            {
                get
                {
                    return _rank;
                }
            }

            public class ArrayTypeKeyHashtable : LockFreeReaderHashtable<ArrayTypeKey, ArrayType>
            {
                protected override int GetKeyHashCode(ArrayTypeKey key)
                {
                    return TypeHashingAlgorithms.ComputeArrayTypeHashCode(key._elementType, key._rank);
                }

                protected override int GetValueHashCode(ArrayType value)
                {
                    return TypeHashingAlgorithms.ComputeArrayTypeHashCode(value.ElementType, value.IsSzArray ? -1 : value.Rank);
                }

                protected override bool CompareKeyToValue(ArrayTypeKey key, ArrayType value)
                {
                    if (key._elementType != value.ElementType)
                        return false;

                    if (value.IsSzArray)
                        return key._rank == -1;

                    return key._rank == value.Rank;
                }

                protected override bool CompareValueToValue(ArrayType value1, ArrayType value2)
                {
                    return (value1.ElementType == value2.ElementType) && (value1.Rank == value2.Rank) && value1.IsSzArray == value2.IsSzArray;
                }

                protected override ArrayType CreateValueFromKey(ArrayTypeKey key)
                {
                    return new ArrayType(key.ElementType, key.Rank);
                }
            }
        }

        private ArrayTypeKey.ArrayTypeKeyHashtable _arrayTypes;

        public ArrayType GetArrayType(TypeDesc elementType, int rank)
        {
            return _arrayTypes.GetOrCreateValue(new ArrayTypeKey(elementType, rank));
        }

        //
        // ByRef types
        //
        public class ByRefHashtable : LockFreeReaderHashtable<TypeDesc, ByRefType>
        {
            protected override int GetKeyHashCode(TypeDesc key)
            {
                return key.GetHashCode();
            }

            protected override int GetValueHashCode(ByRefType value)
            {
                return value.ParameterType.GetHashCode();
            }

            protected override bool CompareKeyToValue(TypeDesc key, ByRefType value)
            {
                return key == value.ParameterType;
            }

            protected override bool CompareValueToValue(ByRefType value1, ByRefType value2)
            {
                return value1.ParameterType == value2.ParameterType;
            }

            protected override ByRefType CreateValueFromKey(TypeDesc key)
            {
                return new ByRefType(key);
            }
        }

        private ByRefHashtable _byRefTypes;

        public ByRefType GetByRefType(TypeDesc parameterType)
        {
            return _byRefTypes.GetOrCreateValue(parameterType);
        }

        //
        // Pointer types
        //
        public class PointerHashtable : LockFreeReaderHashtable<TypeDesc, PointerType>
        {
            protected override int GetKeyHashCode(TypeDesc key)
            {
                return key.GetHashCode();
            }

            protected override int GetValueHashCode(PointerType value)
            {
                return value.ParameterType.GetHashCode();
            }

            protected override bool CompareKeyToValue(TypeDesc key, PointerType value)
            {
                return key == value.ParameterType;
            }

            protected override bool CompareValueToValue(PointerType value1, PointerType value2)
            {
                return value1.ParameterType == value2.ParameterType;
            }

            protected override PointerType CreateValueFromKey(TypeDesc key)
            {
                return new PointerType(key);
            }
        }

        private PointerHashtable _pointerTypes;

        public PointerType GetPointerType(TypeDesc parameterType)
        {
            return _pointerTypes.GetOrCreateValue(parameterType);
        }

        //
        // Function pointer types
        //
        public class FunctionPointerHashtable : LockFreeReaderHashtable<MethodSignature, FunctionPointerType>
        {
            protected override int GetKeyHashCode(MethodSignature key)
            {
                return key.GetHashCode();
            }

            protected override int GetValueHashCode(FunctionPointerType value)
            {
                return value.Signature.GetHashCode();
            }

            protected override bool CompareKeyToValue(MethodSignature key, FunctionPointerType value)
            {
                return key.Equals(value.Signature);
            }

            protected override bool CompareValueToValue(FunctionPointerType value1, FunctionPointerType value2)
            {
                return value1.Signature.Equals(value2.Signature);
            }

            protected override FunctionPointerType CreateValueFromKey(MethodSignature key)
            {
                return new FunctionPointerType(key);
            }
        }

        private FunctionPointerHashtable _functionPointerTypes;

        public FunctionPointerType GetFunctionPointerType(MethodSignature signature)
        {
            return _functionPointerTypes.GetOrCreateValue(signature);
        }

        //
        // Instantiated types
        //

        private struct InstantiatedTypeKey
        {
            private TypeDesc _typeDef;
            private Instantiation _instantiation;

            public InstantiatedTypeKey(TypeDesc typeDef, Instantiation instantiation)
            {
                _typeDef = typeDef;
                _instantiation = instantiation;
            }

            public TypeDesc TypeDef
            {
                get
                {
                    return _typeDef;
                }
            }

            public Instantiation Instantiation
            {
                get
                {
                    return _instantiation;
                }
            }

            public class InstantiatedTypeKeyHashtable : LockFreeReaderHashtable<InstantiatedTypeKey, InstantiatedType>
            {
                protected override int GetKeyHashCode(InstantiatedTypeKey key)
                {
                    return key._instantiation.ComputeGenericInstanceHashCode(key._typeDef.GetHashCode());
                }

                protected override int GetValueHashCode(InstantiatedType value)
                {
                    return value.Instantiation.ComputeGenericInstanceHashCode(value.GetTypeDefinition().GetHashCode());
                }

                protected override bool CompareKeyToValue(InstantiatedTypeKey key, InstantiatedType value)
                {
                    if (key._typeDef != value.GetTypeDefinition())
                        return false;

                    Instantiation valueInstantiation = value.Instantiation;

                    if (key._instantiation.Length != valueInstantiation.Length)
                        return false;

                    for (int i = 0; i < key._instantiation.Length; i++)
                    {
                        if (key._instantiation[i] != valueInstantiation[i])
                            return false;
                    }

                    return true;
                }

                protected override bool CompareValueToValue(InstantiatedType value1, InstantiatedType value2)
                {
                    if (value1.GetTypeDefinition() != value2.GetTypeDefinition())
                        return false;

                    Instantiation value1Instantiation = value1.Instantiation;
                    Instantiation value2Instantiation = value2.Instantiation;

                    if (value1Instantiation.Length != value2Instantiation.Length)
                        return false;

                    for (int i = 0; i < value1Instantiation.Length; i++)
                    {
                        if (value1Instantiation[i] != value2Instantiation[i])
                            return false;
                    }

                    return true;
                }

                protected override InstantiatedType CreateValueFromKey(InstantiatedTypeKey key)
                {
                    return new InstantiatedType((MetadataType)key.TypeDef, key.Instantiation);
                }
            }
        }

        private InstantiatedTypeKey.InstantiatedTypeKeyHashtable _instantiatedTypes;

        public InstantiatedType GetInstantiatedType(MetadataType typeDef, Instantiation instantiation)
        {
            return _instantiatedTypes.GetOrCreateValue(new InstantiatedTypeKey(typeDef, instantiation));
        }

        //
        // Instantiated methods
        //

        private struct InstantiatedMethodKey
        {
            private MethodDesc _methodDef;
            private Instantiation _instantiation;
            private int _hashcode;

            public InstantiatedMethodKey(MethodDesc methodDef, Instantiation instantiation)
            {
                _methodDef = methodDef;
                _instantiation = instantiation;
                _hashcode = TypeHashingAlgorithms.ComputeMethodHashCode(methodDef.OwningType.GetHashCode(),
                    instantiation.ComputeGenericInstanceHashCode(TypeHashingAlgorithms.ComputeNameHashCode(methodDef.Name)));
            }

            public MethodDesc MethodDef
            {
                get
                {
                    return _methodDef;
                }
            }

            public Instantiation Instantiation
            {
                get
                {
                    return _instantiation;
                }
            }

            public class InstantiatedMethodKeyHashtable : LockFreeReaderHashtable<InstantiatedMethodKey, InstantiatedMethod>
            {
                protected override int GetKeyHashCode(InstantiatedMethodKey key)
                {
                    return key._hashcode;
                }

                protected override int GetValueHashCode(InstantiatedMethod value)
                {
                    return value.GetHashCode();
                }

                protected override bool CompareKeyToValue(InstantiatedMethodKey key, InstantiatedMethod value)
                {
                    if (key._methodDef != value.GetMethodDefinition())
                        return false;

                    Instantiation valueInstantiation = value.Instantiation;

                    if (key._instantiation.Length != valueInstantiation.Length)
                        return false;

                    for (int i = 0; i < key._instantiation.Length; i++)
                    {
                        if (key._instantiation[i] != valueInstantiation[i])
                            return false;
                    }

                    return true;
                }

                protected override bool CompareValueToValue(InstantiatedMethod value1, InstantiatedMethod value2)
                {
                    if (value1.GetMethodDefinition() != value2.GetMethodDefinition())
                        return false;

                    Instantiation value1Instantiation = value1.Instantiation;
                    Instantiation value2Instantiation = value2.Instantiation;

                    if (value1Instantiation.Length != value2Instantiation.Length)
                        return false;

                    for (int i = 0; i < value1Instantiation.Length; i++)
                    {
                        if (value1Instantiation[i] != value2Instantiation[i])
                            return false;
                    }

                    return true;
                }

                protected override InstantiatedMethod CreateValueFromKey(InstantiatedMethodKey key)
                {
                    return new InstantiatedMethod(key.MethodDef, key.Instantiation, key._hashcode);
                }
            }
        }

        private InstantiatedMethodKey.InstantiatedMethodKeyHashtable _instantiatedMethods;

        public InstantiatedMethod GetInstantiatedMethod(MethodDesc methodDef, Instantiation instantiation)
        {
            Debug.Assert(!(methodDef is InstantiatedMethod));
            return _instantiatedMethods.GetOrCreateValue(new InstantiatedMethodKey(methodDef, instantiation));
        }

        //
        // Methods for instantiated type
        //

        private struct MethodForInstantiatedTypeKey
        {
            private MethodDesc _typicalMethodDef;
            private InstantiatedType _instantiatedType;
            private int _hashcode;

            public MethodForInstantiatedTypeKey(MethodDesc typicalMethodDef, InstantiatedType instantiatedType)
            {
                _typicalMethodDef = typicalMethodDef;
                _instantiatedType = instantiatedType;
                _hashcode = TypeHashingAlgorithms.ComputeMethodHashCode(instantiatedType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(typicalMethodDef.Name));
            }

            public MethodDesc TypicalMethodDef
            {
                get
                {
                    return _typicalMethodDef;
                }
            }

            public InstantiatedType InstantiatedType
            {
                get
                {
                    return _instantiatedType;
                }
            }

            public class MethodForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable<MethodForInstantiatedTypeKey, MethodForInstantiatedType>
            {
                protected override int GetKeyHashCode(MethodForInstantiatedTypeKey key)
                {
                    return key._hashcode;
                }

                protected override int GetValueHashCode(MethodForInstantiatedType value)
                {
                    return value.GetHashCode();
                }

                protected override bool CompareKeyToValue(MethodForInstantiatedTypeKey key, MethodForInstantiatedType value)
                {
                    if (key._typicalMethodDef != value.GetTypicalMethodDefinition())
                        return false;

                    return key._instantiatedType == value.OwningType;
                }

                protected override bool CompareValueToValue(MethodForInstantiatedType value1, MethodForInstantiatedType value2)
                {
                    return (value1.GetTypicalMethodDefinition() == value2.GetTypicalMethodDefinition()) && (value1.OwningType == value2.OwningType);
                }

                protected override MethodForInstantiatedType CreateValueFromKey(MethodForInstantiatedTypeKey key)
                {
                    return new MethodForInstantiatedType(key.TypicalMethodDef, key.InstantiatedType, key._hashcode);
                }
            }
        }

        private MethodForInstantiatedTypeKey.MethodForInstantiatedTypeKeyHashtable _methodForInstantiatedTypes;

        public MethodDesc GetMethodForInstantiatedType(MethodDesc typicalMethodDef, InstantiatedType instantiatedType)
        {
            Debug.Assert(!(typicalMethodDef is MethodForInstantiatedType));
            Debug.Assert(!(typicalMethodDef is InstantiatedMethod));

            return _methodForInstantiatedTypes.GetOrCreateValue(new MethodForInstantiatedTypeKey(typicalMethodDef, instantiatedType));
        }

        //
        // Fields for instantiated type
        //

        private struct FieldForInstantiatedTypeKey
        {
            private FieldDesc _fieldDef;
            private InstantiatedType _instantiatedType;

            public FieldForInstantiatedTypeKey(FieldDesc fieldDef, InstantiatedType instantiatedType)
            {
                _fieldDef = fieldDef;
                _instantiatedType = instantiatedType;
            }

            public FieldDesc TypicalFieldDef
            {
                get
                {
                    return _fieldDef;
                }
            }

            public InstantiatedType InstantiatedType
            {
                get
                {
                    return _instantiatedType;
                }
            }

            public class FieldForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable<FieldForInstantiatedTypeKey, FieldForInstantiatedType>
            {
                protected override int GetKeyHashCode(FieldForInstantiatedTypeKey key)
                {
                    return key._fieldDef.GetHashCode() ^ key._instantiatedType.GetHashCode();
                }

                protected override int GetValueHashCode(FieldForInstantiatedType value)
                {
                    return value.GetTypicalFieldDefinition().GetHashCode() ^ value.OwningType.GetHashCode();
                }

                protected override bool CompareKeyToValue(FieldForInstantiatedTypeKey key, FieldForInstantiatedType value)
                {
                    if (key._fieldDef != value.GetTypicalFieldDefinition())
                        return false;

                    return key._instantiatedType == value.OwningType;
                }

                protected override bool CompareValueToValue(FieldForInstantiatedType value1, FieldForInstantiatedType value2)
                {
                    return (value1.GetTypicalFieldDefinition() == value2.GetTypicalFieldDefinition()) && (value1.OwningType == value2.OwningType);
                }

                protected override FieldForInstantiatedType CreateValueFromKey(FieldForInstantiatedTypeKey key)
                {
                    return new FieldForInstantiatedType(key.TypicalFieldDef, key.InstantiatedType);
                }
            }
        }

        private FieldForInstantiatedTypeKey.FieldForInstantiatedTypeKeyHashtable _fieldForInstantiatedTypes;

        public FieldDesc GetFieldForInstantiatedType(FieldDesc fieldDef, InstantiatedType instantiatedType)
        {
            return _fieldForInstantiatedTypes.GetOrCreateValue(new FieldForInstantiatedTypeKey(fieldDef, instantiatedType));
        }

        //
        // Signature variables
        //
        private class SignatureVariableHashtable : LockFreeReaderHashtable<uint, SignatureVariable>
        {
            private TypeSystemContext _context;
            public SignatureVariableHashtable(TypeSystemContext context)
            {
                _context = context;
            }

            protected override int GetKeyHashCode(uint key)
            {
                return (int)key;
            }

            protected override int GetValueHashCode(SignatureVariable value)
            {
                uint combinedIndex = value.IsMethodSignatureVariable ? ((uint)value.Index | 0x80000000) : (uint)value.Index;
                return (int)combinedIndex;
            }

            protected override bool CompareKeyToValue(uint key, SignatureVariable value)
            {
                uint combinedIndex = value.IsMethodSignatureVariable ? ((uint)value.Index | 0x80000000) : (uint)value.Index;
                return key == combinedIndex;
            }

            protected override bool CompareValueToValue(SignatureVariable value1, SignatureVariable value2)
            {
                uint combinedIndex1 = value1.IsMethodSignatureVariable ? ((uint)value1.Index | 0x80000000) : (uint)value1.Index;
                uint combinedIndex2 = value2.IsMethodSignatureVariable ? ((uint)value2.Index | 0x80000000) : (uint)value2.Index;

                return combinedIndex1 == combinedIndex2;
            }

            protected override SignatureVariable CreateValueFromKey(uint key)
            {
                bool method = ((key & 0x80000000) != 0);
                int index = (int)(key & 0x7FFFFFFF);
                if (method)
                    return new SignatureMethodVariable(_context, index);
                else
                    return new SignatureTypeVariable(_context, index);
            }
        }

        private SignatureVariableHashtable _signatureVariables;

        public TypeDesc GetSignatureVariable(int index, bool method)
        {
            if (index < 0)
                throw new BadImageFormatException();

            uint combinedIndex = method ? ((uint)index | 0x80000000) : (uint)index;
            return _signatureVariables.GetOrCreateValue(combinedIndex);
        }

        protected internal virtual IEnumerable<MethodDesc> GetAllMethods(TypeDesc type)
        {
            return type.GetMethods();
        }

        /// <summary>
        /// Abstraction to allow the type system context to affect the field layout
        /// algorithm used by types to lay themselves out.
        /// </summary>
        public virtual FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type)
        {
            // Type system contexts that support computing field layout need to override this.
            throw new NotSupportedException();
        }

        /// <summary>
        /// Abstraction to allow the type system context to control the interfaces
        /// algorithm used by types.
        /// </summary>
        public RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForType(TypeDesc type)
        {
            if (type.IsDefType)
            {
                return GetRuntimeInterfacesAlgorithmForDefType((DefType)type);
            }
            else if (type.IsArray)
            {
                ArrayType arrType = (ArrayType)type;
                TypeDesc elementType = arrType.ElementType;
                if (arrType.IsSzArray && !elementType.IsPointer && !elementType.IsFunctionPointer)
                {
                    return GetRuntimeInterfacesAlgorithmForNonPointerArrayType((ArrayType)type);
                }
                else
                {
                    return BaseTypeRuntimeInterfacesAlgorithm.Instance;
                }
            }

            return null;
        }

        /// <summary>
        /// Abstraction to allow the type system context to control the interfaces
        /// algorithm used by types.
        /// </summary>
        protected virtual RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type)
        {
            // Type system contexts that support computing runtime interfaces need to override this.
            throw new NotSupportedException();
        }

        /// <summary>
        /// Abstraction to allow the type system context to control the interfaces
        /// algorithm used by single dimensional array types.
        /// </summary>
        protected virtual RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type)
        {
            // Type system contexts that support computing runtime interfaces need to override this.
            throw new NotSupportedException();
        }

        public virtual VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type)
        {
            // Type system contexts that support virtual method resolution need to override this.
            throw new NotSupportedException();
        }

        // Abstraction to allow different runtimes to have different policy about which fields are
        // in the GC static region, and which are not
        protected internal virtual bool ComputeHasGCStaticBase(FieldDesc field)
        {
            // Type system contexts that support this need to override this.
            throw new NotSupportedException();
        }

        /// <summary>
        /// TypeSystemContext controlled type flags computation. This allows computation of flags which depend
        /// on the particular TypeSystemContext in use
        /// </summary>
        internal TypeFlags ComputeTypeFlags(TypeDesc type, TypeFlags flags, TypeFlags mask)
        {
            // If we are looking to compute HasStaticConstructor, and we haven't yet assigned a value
            if ((mask & TypeFlags.HasStaticConstructorComputed) == TypeFlags.HasStaticConstructorComputed)
            {
                TypeDesc typeDefinition = type.GetTypeDefinition();

                if (typeDefinition != type)
                {
                    // If the type definition is different, the code was working with an instantiated generic or some such.
                    // In that case, just query the HasStaticConstructor property, as it can cache the answer
                    if (typeDefinition.HasStaticConstructor)
                        flags |= TypeFlags.HasStaticConstructor;
                }
                else
                {
                    if (ComputeHasStaticConstructor(typeDefinition))
                    {
                        flags |= TypeFlags.HasStaticConstructor;
                    }
                }

                flags |= TypeFlags.HasStaticConstructorComputed;
            }

            return flags;
        }

        /// <summary>
        /// Algorithm to control which types are considered to have static constructors
        /// </summary>
        protected internal abstract bool ComputeHasStaticConstructor(TypeDesc type);
    }
}


text:
#include "tag.h"

using namespace std;
using namespace utils;

const int TAG::NumCells = 29;

TAG::TAG(int opponents) : NumOpponents(opponents) {
  NumActions = 5;
  Discount = 0.95;
  RewardRange = 10 * NumOpponents;
  mName << "tag_" << opponents;
}

STATE *TAG::Copy(const STATE &state) const {
  const TAG_STATE &tagstate = safe_cast<const TAG_STATE &>(state);
  TAG_STATE *newstate = MemoryPool.Allocate();
  *newstate = tagstate;
  return newstate;
}

void TAG::Validate(const STATE &state) const {
  const TAG_STATE &tagstate = safe_cast<const TAG_STATE &>(state);
  assert(Inside(tagstate.AgentPos));
}

STATE *TAG::CreateStartState() const {
  TAG_STATE *tagstate = MemoryPool.Allocate();
  tagstate->NumAlive = NumOpponents;
  tagstate->AgentPos = GetCoord(SimpleRNG::ins().Random(NumCells));
  tagstate->OpponentPos.clear();
  for (int i = 0; i < NumOpponents; ++i)
    tagstate->OpponentPos.push_back(
        GetCoord(SimpleRNG::ins().Random(NumCells)));
  return tagstate;
}

void TAG::FreeState(STATE *state) const {
  TAG_STATE *tagstate = safe_cast<TAG_STATE *>(state);
  MemoryPool.Free(tagstate);
}

bool TAG::Step(STATE &state, int action, int &observation,
               double &reward) const {
  TAG_STATE &tagstate = safe_cast<TAG_STATE &>(state);

  // Tag action
  if (action == 4)  // tag
  {
    observation = GetIndex(tagstate.AgentPos);
    bool tagged = false;
    for (int opp = 0; opp < NumOpponents; ++opp) {
      if (tagstate.OpponentPos[opp] == tagstate.AgentPos) {
        reward = 10;
        tagged = true;
        tagstate.NumAlive--;
        tagstate.OpponentPos[opp] = coord::Null;
      }
    }
    if (!tagged) {
      reward = -10;
    }
  }

  // Move opponents
  for (int opp = 0; opp < NumOpponents; ++opp)
    if (IsAlive(tagstate, opp)) MoveOpponent(tagstate, opp);

  // Move action
  if (action < 4) {
    reward = -1;
    COORD nextpos = tagstate.AgentPos + coord::Compass[action];
    if (Inside(nextpos)) tagstate.AgentPos = nextpos;
  }

  // Observation occurs in final positions, not start positions
  observation = GetObservation(tagstate, action);
  return tagstate.NumAlive == 0;
}

int TAG::GetObservation(const TAG_STATE &tagstate, int action) const {
  int obs = GetIndex(tagstate.AgentPos);
  if (action < 4)
    for (int opp = 0; opp < NumOpponents; ++opp)
      if (tagstate.OpponentPos[opp] == tagstate.AgentPos) obs = NumCells;
  return obs;
}

bool TAG::Inside(const COORD &coord) const {
  if (coord.Y >= 2) {
    return coord.X >= 5 && coord.X < 8 && coord.Y < 5;
  } else {
    return coord.X >= 0 && coord.X < 10 && coord.Y >= 0;
  }
}

COORD TAG::GetCoord(int index) const {
  assert(NumCells == 29);
  assert(index >= 0 && index < 29);
  if (index < 20) return COORD(index % 10, index / 10);
  index -= 20;
  return COORD(index % 3 + 5, index / 3 + 2);
}

int TAG::GetIndex(const COORD &coord) const {
  assert(coord.X >= 0 && coord.X < 10);
  assert(coord.Y >= 0 && coord.Y < 5);
  if (coord.Y < 2) return coord.Y * 10 + coord.X;
  assert(coord.X >= 5 && coord.X < 8);
  return 20 + (coord.Y - 2) * 3 + coord.X - 5;
}

bool TAG::IsAlive(const TAG_STATE &tagstate, int opp) const {
  return tagstate.OpponentPos[opp].Valid();
}

bool TAG::IsCorner(const COORD &coord) const {
  if (!Inside(coord)) return false;
  if (coord.Y < 2)
    return coord.X == 0 || coord.X == 9;
  else
    return coord.Y == 4 && (coord.X == 5 || coord.X == 7);
}

COORD TAG::GetRandomCorner() const {
  int c = SimpleRNG::ins().Random(6);
  switch (c) {
    case 0:
      return COORD(0, 0);
    case 1:
      return COORD(0, 1);
    case 2:
      return COORD(9, 0);
    case 3:
      return COORD(9, 1);
    case 4:
      return COORD(5, 4);
    case 5:
      return COORD(7, 4);
  }
  return COORD(0, 0);
}

void TAG::MoveOpponent(TAG_STATE &tagstate, int opp) const {
  const COORD &agent = tagstate.AgentPos;
  COORD &opponent = tagstate.OpponentPos[opp];

  static vector<int> actions;
  actions.clear();

  if (opponent.X >= agent.X) actions.push_back(coord::E_EAST);
  if (opponent.Y >= agent.Y) actions.push_back(coord::E_NORTH);
  if (opponent.X <= agent.X) actions.push_back(coord::E_WEST);
  if (opponent.Y <= agent.Y) actions.push_back(coord::E_SOUTH);
  if (opponent.X == agent.X && opponent.Y > agent.Y)
    actions.push_back(coord::E_NORTH);
  if (opponent.Y == agent.Y && opponent.X > agent.X)
    actions.push_back(coord::E_EAST);
  if (opponent.X == agent.X && opponent.Y < agent.Y)
    actions.push_back(coord::E_SOUTH);
  if (opponent.Y == agent.Y && opponent.X < agent.X)
    actions.push_back(coord::E_WEST);

  assert(!actions.empty());
  if (SimpleRNG::ins().Bernoulli(0.8)) {
    int d = actions[SimpleRNG::ins().Random(actions.size())];
    if (Inside(opponent + coord::Compass[d]))
      opponent = opponent + coord::Compass[d];
  }
}

bool TAG::LocalMove(STATE &state, const HISTORY &history, int /*stepObs*/) const {
  TAG_STATE &tagstate = safe_cast<TAG_STATE &>(state);

  int opp = SimpleRNG::ins().Random(NumOpponents);
  if (!IsAlive(tagstate, opp)) return false;
  tagstate.OpponentPos[opp] = GetCoord(SimpleRNG::ins().Random(NumCells));

  int realObs = history.Back().Observation;
  if (realObs < NumCells && realObs != GetIndex(tagstate.AgentPos))
    tagstate.AgentPos = GetCoord(realObs);
  int simObs = GetObservation(tagstate, history.Back().Action);
  return simObs == realObs;
}

void TAG::GeneratePreferred(const STATE &state, const HISTORY &history, vector<int> &actions) const {
  const TAG_STATE &tagstate = safe_cast<const TAG_STATE &>(state);

  // If history is empty then we don't know where we are yet
  if (history.Size() == 0) return;

  // If we just saw an opponent and we are in a corner then TAG
  if (history.Back().Observation == NumCells && IsCorner(tagstate.AgentPos)) {
    actions.push_back(4);
    return;
  }

  // Don't double back and don't go into walls
  for (int d = 0; d < 4; ++d)
    if (history.Back().Action != coord::Opposite(d) &&
        Inside(tagstate.AgentPos + coord::Compass[d]))
      actions.push_back(d);
}

void TAG::DisplayBeliefs(const BELIEF_STATE &, std::ostream &) const {}

void TAG::DisplayState(const STATE &state, std::ostream &ostr) const {
  const TAG_STATE &tagstate = safe_cast<const TAG_STATE &>(state);
  GRID<char> cgrid(10, 5);
  cgrid.SetAllValues('.');
  for (int opp = 0; opp < NumOpponents; ++opp)
    if (IsAlive(tagstate, opp)) cgrid(tagstate.OpponentPos[opp]) = '@';
  cgrid(tagstate.AgentPos) = '*';

  for (int y = 4; y >= 0; y--) {
    for (int x = 0; x < 10; x++) {
      COORD pos(x, y);
      if (Inside(pos)) {
        ostr << cgrid(pos) << ' ';
      } else {
        ostr << "  ";
      }
    }
    ostr << endl;
  }
}

void TAG::DisplayObservation(const STATE &, int observation,
                             std::ostream &ostr) const {
  if (observation == NumCells)
    ostr << "On opponent" << endl;
  else
    ostr << "Agent is at (" << GetCoord(observation).X << ", "
         << GetCoord(observation).Y << ")" << endl;
}

void TAG::DisplayAction(int action, std::ostream &ostr) const {
  if (action < 4)
    ostr << coord::CompassString[action] << endl;
  else
    ostr << "TAG" << endl;
}


text:
package com.example.cmput301f17t27.nume.follows;

import com.example.cmput301f17t27.nume.habitEvent.HabitEvent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;

/**
 * A special class that is very similar to habit but holds
 * the username that the habit belongs to as well as its most
 * recent event. This is so that we have a single object to
 * put for each entry in the following list
 * @author CMPUT301F17T27
 * @version 1.0
 * @see FollowingHabit
 */
public class FollowingHabit implements Serializable {
    public String userName; //The username of the user who this belongs to
    public String title; //The title of the habit
    public String reason; //Reason for the habit
    public Date dateToStart; //Date to start the habit
    public ArrayList<String> frequency; //Days of the week the habit should occur
    public HabitEvent habitEvent; //The most recent habit event (if any) of the habit

    public FollowingHabit(String userName, String title, String reason, Date dateToStart,
                          ArrayList<String> frequency, HabitEvent habitEvent) {
        this.userName = userName;
        this.title = title;
        this.reason = reason;
        this.dateToStart = dateToStart;
        this.frequency = frequency;
        this.habitEvent = habitEvent;
    }
}


text:
<?php
namespace Helper;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class Monolog
{
    public static function init()
    {
        $logger = new Logger('App');
        $logger->pushHandler(new StreamHandler(APP_LOG_FILE, Logger::INFO));
        return $logger;
    }
}


text:
Pattern: Mismatched `printf` arguments

Issue: -

## Description

You're using a `printf` format string with more `%s` variables than arguments to fill them.

Example of **incorrect** code:

```sh
printf "Hello %s, welcome to %s.\n" "$USER"
```

The last `%s` will just become an empty string every time.

Either remove the unused variables from the format string, or add enough arguments to fill them.

Example of **correct** code:

```sh
printf "Hello %s, welcome to %s.\n" "$USER" "$HOSTNAME"
```

## Further Reading

* [ShellCheck - SC2183](https://github.com/koalaman/shellcheck/wiki/SC2183)


text:
function getProductCriterionForm()
{
	if (document.forms)
		return (document.forms['product_criterion_form']);
	else
		return (document.product_criterion_form);
}

function getProductCriterion(path, id_product, id_lang)
{
	$.get(path + 'productcommentscriterion.php', { id_product: id_product, id_lang: id_lang },
	function(data){
		document.getElementById('product_criterions').innerHTML = data;
	});
}


text:
<?php
use yii\helpers\Url;
$session = Yii::$app->session;
$session->isActive?'':$session->open();
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="cleartype" content="on">
    <title>微信安全支付</title>

    <link rel="stylesheet" type="text/css" href="http://static.idaiyan.cn/special/h5_activity365/css/aio.min.css">

    <link rel="stylesheet" type="text/css" href="http://static.idaiyan.cn/special/h5_activity365/css/h5-activity365.css">

                                    订单详情

                                        价格:<input readonly class="c-white disabled font-size-30" type="text" name="user_phone" value="<?php echo $relprice; ?>" autocomplete="off">

                                        手机号:<input readonly class="c-white disabled font-size-30" type="text" name="user_phone" value="<?php echo $mobile; ?>" autocomplete="off">

                                        姓 名:<input readonly class="c-white disabled font-size-30" type="text" name="user_name" value="<?php echo $truename; ?>" autocomplete="off">

                                        订单号:<input readonly class="c-white disabled font-size-30" type="text" name="order" value="<?php echo $out_trade_no; ?>" autocomplete="off">

                                        地 址:

                                            <textarea readonly class="ui-textarea c-white disabled font-size-30" name="user_address"><?php echo $address; ?></textarea>

                                    <button class="uibtn" id="width-360" onclick="callpay()">支付此项目</button>


text:
<!DOCTYPE HTML>

<title>FileSystem.CopyStatusImplementation (xenon 3.1.0 API for Xenon developers)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package nl.esciencecenter.xenon.filesystems

Class FileSystem.CopyStatusImplementation

java.lang.Object

nl.esciencecenter.xenon.filesystems.FileSystem.CopyStatusImplementation

All Implemented Interfaces:

CopyStatus

Enclosing class:

FileSystem

static class FileSystem.CopyStatusImplementation
extends java.lang.Object
implements CopyStatus

CopyStatus contains status information for a specific copy operation.

Field Summary

Fields

Modifier and Type
Field
Description

private long
bytesCopied

private long
bytesToCopy

private java.lang.String
copyIdentifier

private XenonException
exception

private java.lang.String
state

Constructor Summary

Constructors

Constructor
Description

CopyStatusImplementation(java.lang.String copyIdentifier,
                        java.lang.String state,
                        long bytesToCopy,
                        long bytesCopied,
                        XenonException exception)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

long
bytesCopied()

Get the number of bytes that have been copied.

long
bytesToCopy()

Get the number of bytes that need to be copied for the entire copy operation.

boolean
equals(java.lang.Object o)

java.lang.String
getCopyIdentifier()

Get the copy identifier for which this CopyStatus was created.

XenonException
getException()

Get the exception produced by the Copy or while retrieving the status.

java.lang.String
getState()

Get the state of the Copy operation.

boolean
hasException()

Has the Copy or status retrieval produced a exception ?

int
hashCode()

boolean
isDone()

Is the Copy done?

boolean
isRunning()

Is the Copy still running?

void
maybeThrowException()

Throws the exception that occured during copying, if it exists.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

copyIdentifier

private final java.lang.String copyIdentifier

state

private final java.lang.String state

exception

private final XenonException exception

bytesToCopy

private final long bytesToCopy

bytesCopied

private final long bytesCopied

Constructor Detail

CopyStatusImplementation

public CopyStatusImplementation(java.lang.String copyIdentifier,
                                java.lang.String state,
                                long bytesToCopy,
                                long bytesCopied,
                                XenonException exception)

Method Detail

getCopyIdentifier

public java.lang.String getCopyIdentifier()

Description copied from interface: CopyStatus

Get the copy identifier for which this CopyStatus was created.

Specified by:

getCopyIdentifier in interface CopyStatus

Returns:

the Copy.

getState

public java.lang.String getState()

Description copied from interface: CopyStatus

Get the state of the Copy operation.

Specified by:

getState in interface CopyStatus

Returns:

the state of the Copy operation.

getException

public XenonException getException()

Description copied from interface: CopyStatus

Get the exception produced by the Copy or while retrieving the status. If there was no exception,  null will be returned.

 See CopyStatus.maybeThrowException() for the possible exceptions.

Specified by:

getException in interface CopyStatus

Returns:

the exception.

maybeThrowException

public void maybeThrowException()
                         throws XenonException

Description copied from interface: CopyStatus

Throws the exception that occured during copying, if it exists. Otherwise continue.

Specified by:

maybeThrowException in interface CopyStatus

Throws:

PathAlreadyExistsException - If the target already exists and the mode is CopyMode.CREATE.

CopyCancelledException - If the copy was cancelled via FileSystem.cancel(String)

NoSuchPathException - If the source does not exist or the target's parent does not exist

NotConnectedException - If file system is closed.

XenonException - if an I/O error occurred.

isRunning

public boolean isRunning()

Description copied from interface: CopyStatus

Is the Copy still running?

Specified by:

isRunning in interface CopyStatus

Returns:

if the Copy is running.

isDone

public boolean isDone()

Description copied from interface: CopyStatus

Is the Copy done?

Specified by:

isDone in interface CopyStatus

Returns:

if the Copy is done.

hasException

public boolean hasException()

Description copied from interface: CopyStatus

Has the Copy or status retrieval produced a exception ?

Specified by:

hasException in interface CopyStatus

Returns:

if the Copy or status retrieval produced a exception.

bytesToCopy

public long bytesToCopy()

Description copied from interface: CopyStatus

Get the number of bytes that need to be copied for the entire copy operation.

Specified by:

bytesToCopy in interface CopyStatus

Returns:

the number of bytes that need to be copied.

bytesCopied

public long bytesCopied()

Description copied from interface: CopyStatus

Get the number of bytes that have been copied.

Specified by:

bytesCopied in interface CopyStatus

Returns:

the number of bytes that have been copied.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

equals

public boolean equals(java.lang.Object o)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
layout: post
status: publish
published: true
title: Ponto de Situação!
wordpress_id: 1177
wordpress_url: http://www.pedrolamas.com/?p=1177
date: 2010-01-28 00:23:51.000000000 +00:00
categories:
- Geral
tags:
- Ponto
---
Sei que ultimamente tenho andado algo afastado do blog e escrito muito pouco, mas tudo isto tem a ver com algumas mudanças pessoais e profissionais que estão a decorrer na minha vida, e que me tomam a totalidade do tempo!

No entanto, conto em breve ter grandes novidades relativamente ao foco normal do blog, que é o Windows Mobile, em especial agora que se está a aproximar-se a passos largos o Techdays deste ano, onde como já é costume, estarei presente para vos falar das novidades no desenvolvimento para esta plataforma... mas até lá, ainda voltaremos a falar deste assunto! ;)