text:
package home.ned.lul;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.BrowseFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.OnItemViewSelectedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

public class MainFragment extends BrowseFragment {
    private static final String TAG = "MainFragment";

    private static final int BACKGROUND_UPDATE_DELAY = 300;
    private static final int GRID_ITEM_WIDTH = 200;
    private static final int GRID_ITEM_HEIGHT = 200;
//    private static final int NUM_ROWS = 5;
    private static int NUM_COLS = 5;

    private final Handler mHandler = new Handler();
    private ArrayObjectAdapter mRowsAdapter;
    private Drawable mDefaultBackground;
    private DisplayMetrics mMetrics;
    private Timer mBackgroundTimer;
    private URI mBackgroundURI;
    private BackgroundManager mBackgroundManager;
    private int mBackgroundColor;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.i(TAG, "onActivityCreated: "+getActivity().getTitle());
        super.onActivityCreated(savedInstanceState);

        prepareBackgroundManager();

        setupUIElements();

        setupEventListeners();

        Intent networkIntent = new Intent(getActivity(), NetworkStreamService.class);
        getActivity().getApplicationContext().startService(networkIntent);

        Intent epgIntent = new Intent(getActivity(), EPGService.class);
        epgIntent.putExtra("force-update", true);
        getActivity().getApplicationContext().startService(epgIntent);

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
                new IntentFilter("epg-loaded"));
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int count = intent.getIntExtra("count", 0);
            Log.d("receiver", "EPG Data Loaded");
            if(count > 0 ){
                loadRows((count/NUM_COLS), count);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mBackgroundTimer) {
            Log.d(TAG, "onDestroy: " + mBackgroundTimer.toString());
            mBackgroundTimer.cancel();
        }
    }

    private void loadRows(int numRows, int count) {
        Context activity = getActivity();
        if(activity == null){
            return;
        }
        Map<String,  ArrayList<Movie>> list = MovieList.setupMovies(activity.getApplicationContext());
        mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        CardPresenter cardPresenter = new CardPresenter();
        Iterator it = list.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry pair = (Map.Entry)it.next();
            String cat = (String)pair.getKey();
            ArrayList<Movie> channels = (ArrayList<Movie>)pair.getValue();
            ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter);
            Iterator channelIt = channels.iterator();
            String pgRating = null;
            while(channelIt.hasNext()){
                Movie channel = (Movie)channelIt.next();
                listRowAdapter.add(channel);
                pgRating = channel.getPgRating();
            }
            //Exclude no-no channels
            if(pgRating.equals("free")){
                HeaderItem header = new HeaderItem(0,cat);
                mRowsAdapter.add(new ListRow(header, listRowAdapter));
            }
        }

        HeaderItem gridHeader = new HeaderItem(2, "PREFERENCES");
        GridItemPresenter mGridPresenter = new GridItemPresenter();
        ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
        gridRowAdapter.add(getResources().getString(R.string.grid_view));
        gridRowAdapter.add(getString(R.string.error_fragment));
        gridRowAdapter.add(getResources().getString(R.string.personal_settings));
        mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));

        setAdapter(mRowsAdapter);

    }

    private void prepareBackgroundManager() {

        mBackgroundManager = BackgroundManager.getInstance(getActivity());
        mBackgroundManager.attach(getActivity().getWindow());
        mDefaultBackground = getResources().getDrawable(R.drawable.default_background);

        mMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);

    }

    private void setupUIElements() {
        // setBadgeDrawable(getActivity().getResources().getDrawable(
        // R.drawable.videos_by_google_banner));
//        setTitle(getString(R.string.browse_title)); // Badge, when set, takes precedent
        // over title
        setHeadersState(HEADERS_ENABLED);
        setHeadersTransitionOnBackEnabled(true);

        // set fastLane (or headers) background color
        setBrandColor(getResources().getColor(R.color.fastlane_background));
        // set search icon color
        setSearchAffordanceColor(getResources().getColor(R.color.search_opaque));

    }

    private void setupEventListeners() {
        setOnSearchClickedListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
        setOnItemViewClickedListener(new ItemViewClickedListener());
        setOnItemViewSelectedListener(new ItemViewSelectedListener());
    }

    private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Movie) {
                Movie movie = (Movie) item;
                Log.i(TAG, "onItemClicked: "+((Movie) item).getTitle());
//                Intent intent = new Intent(getActivity(), DetailsActivity.class);
//                intent.putExtra(DetailsActivity.MOVIE, movie);
                Intent intent = new Intent(getActivity(), NativePlaybackActivity.class);
                intent.putExtra(DetailsActivity.MOVIE, movie);

                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        DetailsActivity.SHARED_ELEMENT_NAME).toBundle();

                getActivity().startActivity(intent, bundle);
            } else if (item instanceof String) {
                if (((String) item).indexOf(getString(R.string.error_fragment)) >= 0) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    startActivity(intent);
                }else if(((String) item).indexOf(getString(R.string.personal_settings)) >= 0){
                    Intent intent = new Intent(getActivity(),EPGService.class);
                    intent.putExtra("force-update", true);
                    getActivity().getApplicationContext().startService(intent);

                }else {
                    Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }
    }

    private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
        @Override
        public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item,
                                   RowPresenter.ViewHolder rowViewHolder, Row row) {
            if (item instanceof Movie) {
                Log.i(TAG, "onItemSelected: "+((Movie) item).getInfo());
            }

        }
    }

    protected void updateBackground(String uri) {
        int width = mMetrics.widthPixels;
        int height = mMetrics.heightPixels;
//        Glide.with(getActivity())
//                .load(uri)
//                .centerCrop()
//                .error(mDefaultBackground)
//                .into(new SimpleTarget<GlideDrawable>(width, height) {
//                    @Override
//                    public void onResourceReady(GlideDrawable resource,
//                                                GlideAnimation<? super GlideDrawable>
//                                                        glideAnimation) {
//                        mBackgroundManager.setDrawable(resource);
//                    }
//                });
        mBackgroundManager.setColor(mBackgroundColor);
        mBackgroundTimer.cancel();
    }

    private void startBackgroundTimer() {
        if (null != mBackgroundTimer) {
            mBackgroundTimer.cancel();
        }
        mBackgroundTimer = new Timer();
        mBackgroundTimer.schedule(new UpdateBackgroundTask(), BACKGROUND_UPDATE_DELAY);
    }

    private class UpdateBackgroundTask extends TimerTask {

        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mBackgroundURI != null) {
                        updateBackground(mBackgroundURI.toString());
                    }
                }
            });

        }
    }

    private class GridItemPresenter extends Presenter {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent) {
            TextView view = new TextView(parent.getContext());
            view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.setBackgroundColor(getResources().getColor(R.color.default_background));
            view.setTextColor(Color.WHITE);
            view.setGravity(Gravity.CENTER);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, Object item) {
            ((TextView) viewHolder.view).setText((String) item);
        }

        @Override
        public void onUnbindViewHolder(ViewHolder viewHolder) {
        }
    }

}


text:
<?php
	PerchUI::set_subnav(array(
		array('page'=>array(
						'core/apps/assets',
						'core/apps/assets/edit',
						'core/apps/assets/delete',
						),
				'label'=>'Add/Edit'),
		array('page'=>array(
						'core/apps/assets/tags',
						'core/apps/assets/tags/edit',
						'core/apps/assets/tags/delete'),
				'label'=>'Tags'),
	));

redpajama_set_name: RedPajamaGithub


text:
package net.floodlightcontroller.dedu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;

import org.openflow.protocol.OFFPUpdate;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionFPUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Distributing implements IOFMessageListener, IFloodlightModule {
	protected IFloodlightProviderService floodlightProvider;
	protected Set macAddresses;
	protected static Logger logger;
	// modules about compute the finger print vector
	//===================TODO======================

	@Override
	//Need provide ID for OFMessageListener
	public String getName() {
		return Distributing.class.getSimpleName();
	}

	@Override
	public boolean isCallbackOrderingPrereq(OFType type, String name) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isCallbackOrderingPostreq(OFType type, String name) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Collection<Class<? extends IFloodlightService>> getModuleServices() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
		Collection<Class<? extends IFloodlightService>> l=
				new ArrayList<Class<? extends IFloodlightService>>();
		l.add(IFloodlightProviderService.class);
		return l;
	}

	@Override
	public void init(FloodlightModuleContext context)
			throws FloodlightModuleException {
		floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
		macAddresses = new ConcurrentSkipListSet<Long>();
		logger = LoggerFactory.getLogger(Distributing.class);
	}

	@Override
	public void startUp(FloodlightModuleContext context) {
		//want to got useful info from packet in msg
		floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
	}

	@Override
	public net.floodlightcontroller.core.IListener.Command receive(
			IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
		//i want to see the packet in data,to see if get such as the file name

		OFPacketIn pi = (OFPacketIn)msg;
		logger.info("PacketIn buffer id :" + pi.getBufferId());

		OFMatch match = new OFMatch();
	    match.loadFromPacket(pi.getPacketData(), pi.getInPort());
	    logger.info("destination port num: " + (short)match.getTransportDestination());
	    if(match.getNetworkProtocol() == 0x11 && match.getTransportDestination() == 2500){
	    	// UDP
	    	logger.info("packet_in len: " + pi.getLengthU());
	    	StringBuffer buff = new StringBuffer();
	        for (int i = 0; i < pi.getPacketData().length; i++)	            {
	        	 buff.append((char)pi.getPacketData()[i]);
	        }
	    	String filename = buff.substring(54, buff.length());
	    	logger.info("filename : " + filename);

	    }

	    /*After got the file name from the packet_in,
	     * we push the appropriate fp vector to the SW
	     * (TODO:the switches along the path)
	     */
	    OFFPUpdate fu =
                (OFFPUpdate) floodlightProvider.getOFMessageFactory()
                                              .getMessage(OFType.FP_UPDATE);
        OFActionFPUpdate action = new OFActionFPUpdate();
        action.setVector(0xffffffff); // just for testing
        List<OFAction> actions = new ArrayList<OFAction>();
        actions.add(action);

        fu.setBufferId(OFFPUpdate.BUFFER_ID_NONE)
            .setActions(actions)
            .setLengthU(OFFPUpdate.MINIMUM_LENGTH+OFActionFPUpdate.MINIMUM_LENGTH);
        try {
			sw.write(fu, cntx);
		} catch (IOException e) {
            logger.error("Failure writing fp update", e);
        }

		return Command.CONTINUE;// other handlers in this pipeline to process this packetin ;
	}

}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace QuantConnect.Api
{
    /// <summary>
    /// File for a project
    /// </summary>
    public class ProjectFile
    {
        /// <summary>
        /// Name of a project file
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name;

        /// <summary>
        /// Contents of the project file
        /// </summary>
        [JsonProperty(PropertyName = "content")]
        public string Code;

        /// <summary>
        /// DateTime project file was modified
        /// </summary>
        [JsonProperty(PropertyName = "modified")]
        public DateTime DateModified{ get; set; }
    }

    /// <summary>
    /// Response received when reading all files of a project
    /// </summary>
    public class ProjectFilesResponse : RestResponse
    {
        /// <summary>
        /// List of project file information
        /// </summary>
        [JsonProperty(PropertyName = "files")]
        public List<ProjectFile> Files;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version3" level="2" version="3"
      xmlns:math="http://www.w3.org/1998/Math/MathML">
    <model>
        <listOfCompartments>
			<compartment id="c"/>
        </listOfCompartments>
        <listOfParameters>
          <parameter id="p"/>
        </listOfParameters>
        <listOfInitialAssignments>
			<initialAssignment symbol="c" sboTerm="SBO:0000268">
				<math xmlns="http://www.w3.org/1998/Math/MathML">
					<apply>
					<power/> <ci> p </ci> <cn> 3 </cn>
					</apply>
				</math>
			</initialAssignment>
        </listOfInitialAssignments>
    </model>
</sbml>


text:
<?php

namespace WebthinkSniffer\Webthink\Sniffs\Commenting;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

/**
 * Makes sure that deprecated annotation has a description.
 * This way we ensure that the author of the annotation wrote why it was deprecated
 * and the alternative that can be used.
 *
 * @author George Mponos <gmponos@gmail.com>
 */
final class DeprecatedMissingDescriptionSniff implements Sniff
{
    /**
     * @inheritDoc
     */
    public function process(File $phpCsFile, $stackPointer)
    {
        $tokens = $phpCsFile->getTokens();
        if ($tokens[$stackPointer]['content'] !== '@deprecated') {
            return;
        }

        $next = $stackPointer + 2;
        if ($tokens[$next]['type'] !== 'T_DOC_COMMENT_STRING') {
            $phpCsFile->addError(
                'Deprecated annotation must have a description for alternative usage.',
                $stackPointer,
                'MissingDescription'
            );
        }
    }

    /**
     * @inheritDoc
     */
    public function register()
    {
        return [
            T_DOC_COMMENT_TAG,
        ];
    }
}


text:
package org.red5.net.websocket.server;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsSession;
import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.apache.tomcat.websocket.pojo.PojoMethodMapping;
import org.apache.tomcat.websocket.server.Constants;
import org.apache.tomcat.websocket.server.UriTemplate;
import org.apache.tomcat.websocket.server.WsServerContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provides a per class loader (i.e. per web application) instance of a ServerContainer. Web application wide defaults may be configured by setting the
 * following servlet context initialization parameters to the desired values.
 *

 *
{@link Constants#BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}

 *
{@link Constants#TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}

 *

 */
public class DefaultWsServerContainer extends WsWebSocketContainer implements ServerContainer {

    private final Logger log = LoggerFactory.getLogger(DefaultWsServerContainer.class);

    private static final StringManager sm = StringManager.getManager(WsServerContainer.class);

    private static final CloseReason AUTHENTICATED_HTTP_SESSION_CLOSED = new CloseReason(CloseCodes.VIOLATED_POLICY, "Authenticated HTTP session that has ended");

    private final ServletContext servletContext;

    private final ConcurrentMap<String, ServerEndpointConfig> configExactMatchMap = new ConcurrentHashMap<>();

    private final ConcurrentMap<Integer, SortedSet<TemplatePathMatch>> configTemplateMatchMap = new ConcurrentHashMap<>();

    private volatile boolean enforceNoAddAfterHandshake = org.apache.tomcat.websocket.Constants.STRICT_SPEC_COMPLIANCE;

    private volatile boolean addAllowed = true;

    private final ConcurrentMap<String, Set<WsSession>> authenticatedSessions = new ConcurrentHashMap<>();

    private volatile boolean endpointsRegistered;

    private volatile CopyOnWriteArraySet<String> registeredEndpointPaths = new CopyOnWriteArraySet<>();

    public DefaultWsServerContainer(ServletContext servletContext) {
        log.debug("ctor - context: {}", servletContext);
        this.servletContext = servletContext;
        setInstanceManager((InstanceManager) servletContext.getAttribute(InstanceManager.class.getName()));
        // Configure servlet context wide defaults
        String value = servletContext.getInitParameter(Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
        if (value != null) {
            setDefaultMaxBinaryMessageBufferSize(Integer.parseInt(value));
        }
        value = servletContext.getInitParameter(Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
        if (value != null) {
            setDefaultMaxTextMessageBufferSize(Integer.parseInt(value));
        }
        value = servletContext.getInitParameter(Constants.ENFORCE_NO_ADD_AFTER_HANDSHAKE_CONTEXT_INIT_PARAM);
        if (value != null) {
            setEnforceNoAddAfterHandshake(Boolean.parseBoolean(value));
        }
        /* get the websocket filter and coordinate the async setting
        <filter-name>WebSocketFilter</filter-name>
        <filter-class>org.red5.net.websocket.server.WsFilter</filter-class>
        <async-supported>false</async-supported>
         */
    }

    /**
     * Published the provided endpoint implementation at the specified path with the specified configuration. {@link #org.apache.tomcat.websocket.server.WsServerContainer(ServletContext)}
     * must be called before calling this method.
     *
     * @param sec
     *            The configuration to use when creating endpoint instances
     * @throws DeploymentException
     *             if the endpoint cannot be published as requested
     */
    @Override
    public void addEndpoint(ServerEndpointConfig sec) throws DeploymentException {
        log.debug("addEndpoint: {}", sec);
        if (enforceNoAddAfterHandshake && !addAllowed) {
            throw new DeploymentException(sm.getString("serverContainer.addNotAllowed"));
        }
        if (servletContext == null) {
            throw new DeploymentException(sm.getString("serverContainer.servletContextMissing"));
        }
        String path = sec.getPath();
        // Add method mapping to user properties
        PojoMethodMapping methodMapping = new PojoMethodMapping(sec.getEndpointClass(), sec.getDecoders(), path, null); // null for instance manager
        if (methodMapping.getOnClose() != null || methodMapping.getOnOpen() != null || methodMapping.getOnError() != null || methodMapping.hasMessageHandlers()) {
            sec.getUserProperties().put(org.apache.tomcat.websocket.pojo.Constants.POJO_METHOD_MAPPING_KEY, methodMapping);
        }
        UriTemplate uriTemplate = new UriTemplate(path);
        if (uriTemplate.hasParameters()) {
            Integer key = Integer.valueOf(uriTemplate.getSegmentCount());
            SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key);
            if (templateMatches == null) {
                // Ensure that if concurrent threads execute this block they both end up using the same TreeSet instance
                templateMatches = new TreeSet<>(TemplatePathMatchComparator.getInstance());
                configTemplateMatchMap.putIfAbsent(key, templateMatches);
                templateMatches = configTemplateMatchMap.get(key);
            }
            if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) {
                // Duplicate uriTemplate;
                throw new DeploymentException(sm.getString("serverContainer.duplicatePaths", path, sec.getEndpointClass(), sec.getEndpointClass()));
            }
        } else {
            // Exact match
            ServerEndpointConfig old = configExactMatchMap.put(path, sec);
            if (old != null) {
                // Duplicate path mappings
                throw new DeploymentException(sm.getString("serverContainer.duplicatePaths", path, old.getEndpointClass(), sec.getEndpointClass()));
            }
        }
        // save a reference so we can kill any zombies
        registeredEndpointPaths.add(path);
        endpointsRegistered = true;
    }

    /**
     * Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)} for publishing plain old java objects (POJOs) that have been annotated as WebSocket endpoints.
     *
     * @param pojo
     *            The annotated POJO
     */
    @Override
    public void addEndpoint(Class<?> pojo) throws DeploymentException {
        log.debug("addEndpoint: {}", pojo);
        ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
        if (annotation == null) {
            throw new DeploymentException(sm.getString("serverContainer.missingAnnotation", pojo.getName()));
        }
        String path = annotation.value();
        // Validate encoders
        validateEncoders(annotation.encoders());
        // ServerEndpointConfig
        ServerEndpointConfig sec;
        Class<? extends Configurator> configuratorClazz = annotation.configurator();
        Configurator configurator = null;
        if (!configuratorClazz.equals(Configurator.class)) {
            try {
                configurator = annotation.configurator().getConstructor().newInstance();
            } catch (ReflectiveOperationException e) {
                throw new DeploymentException(sm.getString("serverContainer.configuratorFail", annotation.configurator().getName(), pojo.getClass().getName()), e);
            }
        }
        sec = ServerEndpointConfig.Builder.create(pojo, path).decoders(Arrays.asList(annotation.decoders())).encoders(Arrays.asList(annotation.encoders())).subprotocols(Arrays.asList(annotation.subprotocols())).configurator(configurator).build();
        addEndpoint(sec);
    }

    boolean areEndpointsRegistered() {
        return endpointsRegistered;
    }

    /**
     * Until the WebSocket specification provides such a mechanism, this Tomcat proprietary method is provided to enable applications to programmatically
     * determine whether or not to upgrade an individual request to WebSocket.
     *

     * Note: This method is not used by Tomcat but is used directly by third-party code and must not be removed.
     *
     * @param request
     *            The request object to be upgraded
     * @param response
     *            The response object to be populated with the result of the upgrade
     * @param sec
     *            The server endpoint to use to process the upgrade request
     * @param pathParams
     *            The path parameters associated with the upgrade request
     *
     * @throws ServletException
     *             If a configuration error prevents the upgrade from taking place
     * @throws IOException
     *             If an I/O error occurs during the upgrade process
     */
    public void doUpgrade(HttpServletRequest request, HttpServletResponse response, ServerEndpointConfig sec, Map<String, String> pathParams) throws ServletException, IOException {
        log.debug("doUpgrade");
        UpgradeUtil.doUpgrade(this, request, response, sec, pathParams);
    }

    public WsMappingResult findMapping(String path) {
        log.debug("findMapping: {}", path);
        // Prevent registering additional endpoints once the first attempt has been made to use one
        if (addAllowed) {
            addAllowed = false;
        }
        // Check an exact match. Simple case as there are no templates.
        ServerEndpointConfig sec = configExactMatchMap.get(path);
        log.debug("configExactMatchMap: {}", configExactMatchMap);
        if (sec != null) {
            return new WsMappingResult(sec, Collections.<String, String> emptyMap());
        }
        // No exact match. Need to look for template matches.
        UriTemplate pathUriTemplate = null;
        try {
            pathUriTemplate = new UriTemplate(path);
        } catch (DeploymentException e) {
            // Path is not valid so can't be matched to a WebSocketEndpoint
            return null;
        }
        // Number of segments has to match
        Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount());
        SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key);
        log.debug("configTemplateMatchMap - key: {} {}", key, configTemplateMatchMap);
        if (templateMatches == null) {
            // No templates with an equal number of segments so there will be no matches
            return null;
        }
        // List is in alphabetical order of normalized templates.
        // Correct match is the first one that matches.
        Map<String, String> pathParams = null;
        for (TemplatePathMatch templateMatch : templateMatches) {
            pathParams = templateMatch.getUriTemplate().match(pathUriTemplate);
            if (pathParams != null) {
                sec = templateMatch.getConfig();
                break;
            }
        }
        if (sec == null) {
            // No match
            return null;
        }
        return new WsMappingResult(sec, pathParams);
    }

    public boolean isEnforceNoAddAfterHandshake() {
        return enforceNoAddAfterHandshake;
    }

    public void setEnforceNoAddAfterHandshake(boolean enforceNoAddAfterHandshake) {
        this.enforceNoAddAfterHandshake = enforceNoAddAfterHandshake;
    }

    public Set<String> getRegisteredEndpointPaths() {
        return Collections.unmodifiableSet(registeredEndpointPaths);
    }

    /**
     * {@inheritDoc}
     *
     * Overridden to make it visible to other classes in this package.
     */
    @Override
    protected void registerSession(Object endpoint, WsSession wsSession) {
        // Server side uses the endpoint path as the key
        // Client side uses the client endpoint instance
        super.registerSession(endpoint, wsSession);
        if (wsSession.isOpen() && wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) {
            registerAuthenticatedSession(wsSession, wsSession.getHttpSessionId());
            log.debug("registerSession - registerAuthenticatedSession: {}", wsSession.getId());
        }
        log.debug("registerSession: {} endpoint: {}", wsSession.getId(), endpoint);
    }

    /**
     * {@inheritDoc}
     *
     * Overridden to make it visible to other classes in this package.
     */
    @Override
    protected void unregisterSession(Object endpoint, WsSession wsSession) {
        if (wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) {
            unregisterAuthenticatedSession(wsSession, wsSession.getHttpSessionId());
            log.debug("unregisterSession - unregisterAuthenticatedSession: {}", wsSession.getId());
        }
        super.unregisterSession(endpoint, wsSession);
        log.debug("unregisterSession: {} endpoint: {}", wsSession.getId(), endpoint);
    }

    private void registerAuthenticatedSession(WsSession wsSession, String httpSessionId) {
        Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
        if (wsSessions == null) {
            wsSessions = Collections.newSetFromMap(new ConcurrentHashMap<WsSession, Boolean>());
            authenticatedSessions.putIfAbsent(httpSessionId, wsSessions);
            wsSessions = authenticatedSessions.get(httpSessionId);
        }
        wsSessions.add(wsSession);
    }

    private void unregisterAuthenticatedSession(WsSession wsSession, String httpSessionId) {
        Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
        // wsSessions will be null if the HTTP session has ended
        if (wsSessions != null) {
            wsSessions.remove(wsSession);
        }
    }

    public void closeAuthenticatedSession(String httpSessionId) {
        Set<WsSession> wsSessions = authenticatedSessions.remove(httpSessionId);
        if (wsSessions != null && !wsSessions.isEmpty()) {
            for (WsSession wsSession : wsSessions) {
                try {
                    wsSession.close(AUTHENTICATED_HTTP_SESSION_CLOSED);
                } catch (IOException e) {
                    // Any IOExceptions during close will have been caught and the onError method called.
                }
            }
        }
    }

    private static void validateEncoders(Class<? extends Encoder>[] encoders) throws DeploymentException {
        for (Class<? extends Encoder> encoder : encoders) {
            // Need to instantiate decoder to ensure it is valid and that deployment can be failed if it is not
            @SuppressWarnings("unused")
            Encoder instance;
            try {
                encoder.getConstructor().newInstance();
            } catch (ReflectiveOperationException e) {
                throw new DeploymentException(sm.getString("serverContainer.encoderFail", encoder.getName()), e);
            }
        }
    }

    private static class TemplatePathMatch {

        private final ServerEndpointConfig config;

        private final UriTemplate uriTemplate;

        public TemplatePathMatch(ServerEndpointConfig config, UriTemplate uriTemplate) {
            this.config = config;
            this.uriTemplate = uriTemplate;
        }

        public ServerEndpointConfig getConfig() {
            return config;
        }

        public UriTemplate getUriTemplate() {
            return uriTemplate;
        }
    }

    /**
     * This Comparator implementation is thread-safe so only create a single instance.
     */
    private static class TemplatePathMatchComparator implements Comparator<TemplatePathMatch> {

        private static final TemplatePathMatchComparator INSTANCE = new TemplatePathMatchComparator();

        public static TemplatePathMatchComparator getInstance() {
            return INSTANCE;
        }

        private TemplatePathMatchComparator() {
            // Hide default constructor
        }

        @Override
        public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) {
            return tpm1.getUriTemplate().getNormalizedPath().compareTo(tpm2.getUriTemplate().getNormalizedPath());
        }
    }

}


text:
extern "Java"
{
  namespace javax
  {
    namespace print
    {
      namespace attribute
      {
          class UnmodifiableSetException;
      }
    }
  }
}

class javax::print::attribute::UnmodifiableSetException : public ::java::lang::RuntimeException
{

public:
  UnmodifiableSetException();
  UnmodifiableSetException(::java::lang::String *);
  static ::java::lang::Class class$;
};

#endif // __javax_print_attribute_UnmodifiableSetException__


text:
import Ember from 'ember';
import '../lib/darkroom.save';
import FoundationBase from '../mixins/foundation-base';

export default Ember.Controller.extend(FoundationBase, {
  authors: ['MattKetmo', 'blazeeboy'],
  initDarkroom: function(){
    if(this.image !== ""){
      // remove darkroom plugin output
      Ember.$('.darkroom-toolbar, .darkroom-image-container').remove();

      // then convert the image to darkroom after rendering
      // as it doesn't work directly after changing Image property
      // it should update view to put image as SRC then convert it.
      Ember.run.scheduleOnce('afterRender', this, ()=>{
        this.set('darkroom', new Darkroom('.darkroom-image img'));
      });
    }
  }.observes('image')
});


text:
include(CMakeParseArguments)

cmake_minimum_required(VERSION 3.1.3)

# ----------------------- Public Functions.
# These are all documented in README_cmake.md.
#
# Note that certain CMake variables may need to be set correctly to use these rules:
#
# - If you are using a Halide distribution, simply set HALIDE_DISTRIB_DIR
# to the path to the distrib directory.
#
# - More complex usages (mainly, internal-to-Halide users) may, instead, set some combination
# of HALIDE_TOOLS_DIR, HALIDE_INCLUDE_DIR, and HALIDE_COMPILER_LIB.
#

# Add the include paths and link dependencies for halide_image_io.
function(halide_use_image_io TARGET)
  foreach(PKG PNG JPEG)
    find_package(${PKG} QUIET)
    if(${PKG}_FOUND)
      target_compile_definitions(${TARGET} PRIVATE ${${PKG}_DEFINITIONS})
      target_include_directories(${TARGET} PRIVATE ${${PKG}_INCLUDE_DIRS})
      target_link_libraries(${TARGET} PRIVATE ${${PKG}_LIBRARIES})
    else()
      message(STATUS "${PKG} not found for ${TARGET}; compiling with -DHALIDE_NO_${PKG}")
      target_compile_definitions(${TARGET} PRIVATE -DHALIDE_NO_${PKG})
    endif()
  endforeach()
endfunction()

# Make a build target for a Generator.
function(halide_generator NAME)
  set(oneValueArgs GENERATOR_NAME)
  set(multiValueArgs SRCS DEPS INCLUDES)
  cmake_parse_arguments(args "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

  if(NOT ${NAME} MATCHES "^.*\\.generator$")
    message(FATAL_ERROR "halide_generator rules must have names that end in .generator (${NAME})")
  endif()

  string(REGEX REPLACE "\\.generator*$" "" BASENAME ${NAME})

  if ("${args_GENERATOR_NAME}" STREQUAL "")
    set(args_GENERATOR_NAME "${BASENAME}")
  endif()

  # We could precompile GenGen.cpp, but add_executable() requires
  # at least one source file, and this is the cheapest one we're going to have.
  add_executable("${NAME}_binary" "${HALIDE_TOOLS_DIR}/GenGen.cpp")
  _halide_set_cxx_options("${NAME}_binary")
  target_include_directories("${NAME}_binary" PRIVATE "${HALIDE_TOOLS_DIR}")
  target_link_libraries("${NAME}_binary" PRIVATE ${HALIDE_COMPILER_LIB} ${HALIDE_SYSTEM_LIBS} ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
  if (MSVC)
    target_link_libraries("${NAME}_binary" PRIVATE Kernel32)
  endif()

  list(LENGTH args_SRCS SRCSLEN)
  # Don't create an empty object-library: that can cause quiet failures in MSVC builds.
  if("${SRCSLEN}" GREATER 0)
    set(GENLIB "${NAME}_library")
    # Use Shared Libraries for all Generators to ensure that the RegisterGenerator
    # code is not dead-stripped.
    add_library("${GENLIB}" STATIC ${args_SRCS})
    _halide_set_cxx_options("${GENLIB}")
    target_link_libraries("${GENLIB}" ${args_DEPS})
    target_include_directories("${GENLIB}" PRIVATE ${args_INCLUDES} "${HALIDE_INCLUDE_DIR}" "${HALIDE_TOOLS_DIR}")
    foreach(DEP ${args_DEPS})
      target_include_directories("${GENLIB}" PRIVATE
                                 $<TARGET_PROPERTY:${DEP},INTERFACE_INCLUDE_DIRECTORIES>)
    endforeach()
    # Ensure that Halide.h is built prior to any Generator
    add_dependencies("${GENLIB}" ${HALIDE_COMPILER_LIB})

    _halide_get_static_library_actual_path(${GENLIB} GENLIB_ACTUAL_PATH)

    # We need to ensure that the libraries are linked in with --whole-archive
    # (or the equivalent), to ensure that the Generator-registration code
    # isn't omitted. Sadly, there's no portable way to do this, so we do some
    # special-casing here:
    if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
      target_link_libraries("${NAME}_binary" PRIVATE "${GENLIB}")
      set_target_properties("${NAME}_binary" PROPERTIES LINK_FLAGS -Wl,-force_load,${GENLIB_ACTUAL_PATH})
    elseif(MSVC)
      # Note that this requires VS2015 R2+
      target_link_libraries("${NAME}_binary" PRIVATE "${GENLIB}")
      set_target_properties("${NAME}_binary" PROPERTIES LINK_FLAGS "/WHOLEARCHIVE:${GENLIB}.lib")
    else()
      # Assume Linux or similar
      target_link_libraries("${NAME}_binary" PRIVATE -Wl,--whole-archive "${GENLIB}" -Wl,-no-whole-archive)
    endif()
  endif()

  _halide_genfiles_dir(${BASENAME} GENFILES_DIR)
  set(STUB_HDR "${GENFILES_DIR}/${BASENAME}.stub.h")
  set(GENERATOR_EXEC_ARGS "-g" "${args_GENERATOR_NAME}" "-o" "${GENFILES_DIR}" "-e" "cpp_stub" "-n" "${BASENAME}")

  _halide_add_exec_generator_target(
    "${NAME}_stub_gen"
    GENERATOR_BINARY "${NAME}_binary"
    GENERATOR_ARGS   "${GENERATOR_EXEC_ARGS}"
    OUTPUTS          "${STUB_HDR}"
  )
  set_property(TARGET "${NAME}_stub_gen" PROPERTY _HALIDE_GENERATOR_NAME "${args_GENERATOR_NAME}")

  if("${SRCSLEN}" GREATER 0)
    add_library("${NAME}" STATIC IMPORTED)
    set_target_properties("${NAME}" PROPERTIES
      IMPORTED_LOCATION "${GENLIB_ACTUAL_PATH}")
  else()
    add_library("${NAME}" INTERFACE)
  endif()
  add_dependencies("${NAME}" "${NAME}_stub_gen")
  set_target_properties("${NAME}" PROPERTIES
    INTERFACE_INCLUDE_DIRECTORIES "${GENFILES_DIR}")
endfunction()

# Use a Generator target to emit a code library.
function(halide_library_from_generator BASENAME)
  set(options )
  set(oneValueArgs FUNCTION_NAME GENERATOR HALIDE_TARGET)
  set(multiValueArgs EXTRA_OUTPUTS FILTER_DEPS GENERATOR_ARGS HALIDE_TARGET_FEATURES INCLUDES)
  cmake_parse_arguments(args "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

  if ("${args_GENERATOR}" STREQUAL "")
    set(args_GENERATOR "${BASENAME}.generator")
  endif()
  if ("${args_FUNCTION_NAME}" STREQUAL "")
    set(args_FUNCTION_NAME "${BASENAME}")
  endif()
  if ("${args_HALIDE_TARGET}" STREQUAL "")
    set(args_HALIDE_TARGET "host")
  endif()
  # It's fine for EXTRA_OUTPUTS, GENERATOR_ARGS, FILTER_DEPS, HALIDE_TARGET_FEATURES to be empty

  # Some sanity checking
  if("${args_HALIDE_TARGET}" MATCHES "^target=")
    message(FATAL_ERROR "HALIDE_TARGET should not begin with 'target='.")
  endif()
  foreach(FEATURE ${args_HALIDE_TARGET_FEATURES})
    if("${FEATURE}" STREQUAL "no_runtime")
      message(FATAL_ERROR "HALIDE_TARGET_FEATURES may not contain 'no_runtime'.")
    endif()
    # Note that this list isn't exhaustive, but will check enough of the likely
    # common cases to enforce proper usage.
    if("${FEATURE}" STREQUAL "host" OR
       "${FEATURE}" STREQUAL "x86" OR
       "${FEATURE}" STREQUAL "arm" OR
       "${FEATURE}" STREQUAL "32" OR
       "${FEATURE}" STREQUAL "64" OR
       "${FEATURE}" STREQUAL "linux" OR
       "${FEATURE}" STREQUAL "osx" OR
       "${FEATURE}" STREQUAL "windows" OR
       "${FEATURE}" STREQUAL "ios" OR
       "${FEATURE}" STREQUAL "android")
      message(FATAL_ERROR "HALIDE_TARGET_FEATURES may not the Arch/OS/Bits string '${FEATURE}'; use HALIDE_TARGET instead.")
    endif()
  endforeach()
  foreach(ARG ${args_GENERATOR_ARGS})
    if("${ARG}" MATCHES "^target=")
      message(FATAL_ERROR "GENERATOR_ARGS may not include 'target=whatever'; use HALIDE_TARGET instead.")
    endif()
  endforeach()

  set(OUTPUTS static_library h)
  foreach(E ${args_EXTRA_OUTPUTS})
    if("${E}" STREQUAL "cpp")
      message(FATAL_ERROR "halide_library('${BASENAME}') doesn't support 'cpp' in EXTRA_OUTPUTS; please depend on '${BASENAME}_cc' instead.")
    endif()
    if("${E}" STREQUAL "cpp_stub")
      message(FATAL_ERROR "halide_library('${BASENAME}') doesn't support 'cpp_stub' in EXTRA_OUTPUTS; please depend on '${BASENAME}.generator' instead.")
    endif()
    list(FIND OUTPUTS ${E} index)
    if (${index} GREATER -1)
      message(FATAL_ERROR "Duplicate entry ${E} in extra_outputs.")
    endif()
    list(APPEND OUTPUTS ${E})
  endforeach()

  get_property(GENERATOR_NAME TARGET "${args_GENERATOR}_stub_gen" PROPERTY _HALIDE_GENERATOR_NAME)

  # Create a directory to contain generator specific intermediate files
  _halide_genfiles_dir(${BASENAME} GENFILES_DIR)

  # Append HALIDE_TARGET_FEATURES to the target(s)
  set(TARGET_WITH_FEATURES "${args_HALIDE_TARGET}")
  foreach(FEATURE ${args_HALIDE_TARGET_FEATURES})
    _halide_add_target_features("${TARGET_WITH_FEATURES}" ${FEATURE} TARGET_WITH_FEATURES)
  endforeach()
  # Select the runtime to use *before* adding no_runtime
  _halide_library_runtime("${TARGET_WITH_FEATURES}" RUNTIME_NAME)
  _halide_add_target_features("${TARGET_WITH_FEATURES}" "no_runtime" TARGET_WITH_FEATURES)

  set(GENERATOR_EXEC_ARGS "-o" "${GENFILES_DIR}")
  list(APPEND GENERATOR_EXEC_ARGS "-g" "${GENERATOR_NAME}")
  list(APPEND GENERATOR_EXEC_ARGS "-f" "${args_FUNCTION_NAME}" )
  list(APPEND GENERATOR_EXEC_ARGS "-x" ".s=.s.txt,.cpp=.generated.cpp")
  list(APPEND GENERATOR_EXEC_ARGS "target=${TARGET_WITH_FEATURES}")
  # GENERATOR_ARGS always come last
  list(APPEND GENERATOR_EXEC_ARGS ${args_GENERATOR_ARGS})

  # CMake has no map type, and no switch statement. Whee!
  set(OUTPUT_FILES )
  foreach(OUTPUT ${OUTPUTS})
    if ("${OUTPUT}" STREQUAL "static_library")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}${CMAKE_STATIC_LIBRARY_SUFFIX}")
    elseif ("${OUTPUT}" STREQUAL "o")
      # Apparently CMake has no predefined variable for this suffix.
      if(MSVC)
        list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.obj")
      else()
        list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.o")
      endif()
    elseif ("${OUTPUT}" STREQUAL "h")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.h")
    elseif ("${OUTPUT}" STREQUAL "assembly")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.s.txt")
    elseif ("${OUTPUT}" STREQUAL "bitcode")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.bc")
    elseif ("${OUTPUT}" STREQUAL "stmt")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.stmt")
    elseif ("${OUTPUT}" STREQUAL "schedule")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.schedule")
    elseif ("${OUTPUT}" STREQUAL "html")
      list(APPEND OUTPUT_FILES "${GENFILES_DIR}/${BASENAME}.html")
    endif()
  endforeach()

  # Output everything (except for the generated .cpp file)
  string(REPLACE ";" "," OUTPUTS_COMMA "${OUTPUTS}")
  set(ARGS_WITH_OUTPUTS "-e" ${OUTPUTS_COMMA} ${GENERATOR_EXEC_ARGS})
  _halide_add_exec_generator_target(
    "${BASENAME}_lib_gen"
    GENERATOR_BINARY "${args_GENERATOR}_binary"
    GENERATOR_ARGS   "${ARGS_WITH_OUTPUTS}"
    OUTPUTS          ${OUTPUT_FILES}
  )

  add_library("${BASENAME}" STATIC IMPORTED)
  add_dependencies("${BASENAME}" "${BASENAME}_lib_gen" "${RUNTIME_NAME}")
  set_target_properties("${BASENAME}" PROPERTIES
    IMPORTED_LOCATION "${GENFILES_DIR}/${BASENAME}${CMAKE_STATIC_LIBRARY_SUFFIX}"
    INTERFACE_INCLUDE_DIRECTORIES "${GENFILES_DIR}" ${args_INCLUDES}
    INTERFACE_LINK_LIBRARIES "${RUNTIME_NAME};${args_FILTER_DEPS};${CMAKE_DL_LIBS};${CMAKE_THREAD_LIBS_INIT}")

  # A separate invocation for the generated .cpp file,
  # since it's rarely used, and some code will fail at Generation
  # time at present (e.g. code with predicated loads or stores).
  set(ARGS_WITH_OUTPUTS "-e" "cpp" ${GENERATOR_EXEC_ARGS})
  _halide_add_exec_generator_target(
    "${BASENAME}_cc_gen"
    GENERATOR_BINARY "${args_GENERATOR}_binary"
    GENERATOR_ARGS   "${ARGS_WITH_OUTPUTS}"
    OUTPUTS          "${GENFILES_DIR}/${BASENAME}.generated.cpp"
  )

  add_library("${BASENAME}_cc" STATIC "${GENFILES_DIR}/${BASENAME}.generated.cpp")
  # Needs _lib_gen as well, to get the .h file
  add_dependencies("${BASENAME}_cc" "${BASENAME}_lib_gen" "${BASENAME}_cc_gen")
  target_link_libraries("${BASENAME}_cc" PRIVATE ${args_FILTER_DEPS})
  target_include_directories("${BASENAME}_cc" PRIVATE "${HALIDE_INCLUDE_DIR}")
  target_include_directories("${BASENAME}_cc" PUBLIC "${GENFILES_DIR}" ${args_INCLUDES})
  # Very few of the cc_libs are needed, so exclude from "all".
  set_target_properties("${BASENAME}_cc" PROPERTIES EXCLUDE_FROM_ALL TRUE)

  # Code to build the BASENAME.rungen target
  set(RUNGEN "${BASENAME}.rungen")
  add_executable("${RUNGEN}" "${HALIDE_TOOLS_DIR}/RunGenStubs.cpp")
  target_compile_definitions("${RUNGEN}" PRIVATE "-DHL_RUNGEN_FILTER_HEADER=\"${BASENAME}.h\"")
  target_link_libraries("${RUNGEN}" PRIVATE _halide_library_from_generator_rungen "${BASENAME}")
  # Not all Generators will build properly with RunGen (e.g., missing
  # external dependencies), so exclude them from the "ALL" targets
  set_target_properties("${RUNGEN}" PROPERTIES EXCLUDE_FROM_ALL TRUE)

  # BASENAME.run simply runs the BASENAME.rungen target
  add_custom_target("${BASENAME}.run"
                    COMMAND "${RUNGEN}" "${RUNARGS}"
                    DEPENDS "${RUNGEN}")
  set_target_properties("${BASENAME}.run" PROPERTIES EXCLUDE_FROM_ALL TRUE)
endfunction()

# Rule to build and use a Generator; it's convenient sugar around
# halide_generator() + halide_library_from_generator().
function(halide_library NAME)
  set(oneValueArgs FUNCTION_NAME HALIDE_TARGET GENERATOR GENERATOR_NAME)
  set(multiValueArgs EXTRA_OUTPUTS FILTER_DEPS GENERATOR_DEPS HALIDE_TARGET_FEATURES INCLUDES GENERATOR_ARGS SRCS)
  cmake_parse_arguments(args "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

  if (NOT "${args_GENERATOR}" STREQUAL "")
    message(FATAL_ERROR "halide_library('${BASENAME}') doesn't take a GENERATOR argument. Did you mean to use GENERATOR_NAME, or the halide_library_from_generator() rule?")
  endif()

  halide_generator("${NAME}.generator"
                   SRCS ${args_SRCS}
                   DEPS ${args_GENERATOR_DEPS}
                   INCLUDES ${args_INCLUDES}
                   GENERATOR_NAME ${args_GENERATOR_NAME})

  halide_library_from_generator("${NAME}"
                   DEPS ${args_FILTER_DEPS}
                   INCLUDES ${args_INCLUDES}
                   GENERATOR "${NAME}.generator"
                   FUNCTION_NAME ${args_FUNCTION_NAME}
                   HALIDE_TARGET ${args_HALIDE_TARGET}
                   HALIDE_TARGET_FEATURES ${args_HALIDE_TARGET_FEATURES}
                   GENERATOR_ARGS ${args_GENERATOR_ARGS}
                   EXTRA_OUTPUTS ${args_EXTRA_OUTPUTS})
endfunction()

# ----------------------- Private Functions.
# All functions, properties, variables, etc. that being with an underscore
# should be assumed to be private implementation details; don't rely on them externally.

# Set the C++ options necessary for using libHalide.
function(_halide_set_cxx_options TARGET)
  set_target_properties("${TARGET}" PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO)
  if (MSVC)
    target_compile_definitions("${TARGET}" PUBLIC "-D_CRT_SECURE_NO_WARNINGS" "-D_SCL_SECURE_NO_WARNINGS")
    target_compile_options("${TARGET}" PRIVATE "/GR-")
  else()
    target_compile_options("${TARGET}" PRIVATE "-fno-rtti")
  endif()
endfunction()

# Get (and lazily create) the generated-files directory for Generators.
function(_halide_genfiles_dir NAME OUTVAR)
  set(GENFILES_DIR "${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/genfiles/${NAME}")
  file(MAKE_DIRECTORY "${GENFILES_DIR}")
  set(${OUTVAR} "${GENFILES_DIR}" PARENT_SCOPE)
endfunction()

# Given the target of a static library, return the path to the actual .a file
function(_halide_get_static_library_actual_path TARGET OUTVAR)
  get_target_property(DIR ${TARGET} LIBRARY_OUTPUT_DIRECTORY)
  if (DIR)
    set(DIR "${DIR}/")
  else()
    # Set to empty string since it could be "DIR-NOTFOUND"
    set(DIR "")
  endif()
  set(${OUTVAR} "${DIR}${CMAKE_CFG_INTDIR}/${CMAKE_STATIC_LIBRARY_PREFIX}${TARGET}${CMAKE_STATIC_LIBRARY_SUFFIX}" PARENT_SCOPE)
endfunction()

# Adds features to a target string, canonicalizing the result.
# If multitarget, features are added to all.
function(_halide_add_target_features HALIDE_TARGET HALIDE_FEATURES OUTVAR)
  string(REPLACE "," ";" MULTITARGETS "${HALIDE_TARGET}")
  foreach(T ${MULTITARGETS})
    string(REPLACE "-" ";" NEW_T "${T}")
    foreach(F ${HALIDE_FEATURES})
      list(APPEND NEW_T ${F})
    endforeach()
    string(REPLACE ";" "-" NEW_T "${NEW_T}")
    _halide_canonicalize_target("${NEW_T}" NEW_T)
    list(APPEND NEW_MULTITARGETS ${NEW_T})
  endforeach()
  string(REPLACE ";" "," NEW_MULTITARGETS "${NEW_MULTITARGETS}")
  set(${OUTVAR} "${NEW_MULTITARGETS}" PARENT_SCOPE)
endfunction()

# If any of the (multi) targets have the feature specified, set outvar to true.
# Otherwise set outvar to false.
function(_halide_has_target_feature HALIDE_TARGET HALIDE_FEATURE OUTVAR)
  set(${OUTVAR} FALSE PARENT_SCOPE)
  string(REPLACE "," ";" FEATURES "${HALIDE_TARGET}")
  string(REPLACE "-" ";" FEATURES "${HALIDE_TARGET}")
  foreach(F ${FEATURES})
    if("${F}" STREQUAL "${HALIDE_FEATURE}")
      set(${OUTVAR} TRUE PARENT_SCOPE)
    endif()
  endforeach()
endfunction()

# Split the target into base and feature lists.
function(_halide_split_target HALIDE_TARGET OUTVAR_BASE OUTVAR_FEATURES)
  if("${HALIDE_TARGET}" MATCHES ".*,.*")
    message(FATAL_ERROR "Multitarget may not be specified in _halide_split_target(${HALIDE_TARGET})")
  endif()

  string(REPLACE "-" ";" FEATURES "${HALIDE_TARGET}")
  list(LENGTH FEATURES LEN)
  if("${LEN}" EQUAL 0)
    message(FATAL_ERROR "Empty target")
  endif()

  list(GET FEATURES 0 BASE)
  if ("${BASE}" STREQUAL "host")
    list(REMOVE_AT FEATURES 0)
  else()
    if("${LEN}" LESS 3)
      message(FATAL_ERROR "Illegal target (${HALIDE_TARGET})")
    endif()
    list(GET FEATURES 0 1 2 BASE)
    list(REMOVE_AT FEATURES 0 1 2)
  endif()
  set(${OUTVAR_BASE} "${BASE}" PARENT_SCOPE)
  set(${OUTVAR_FEATURES} "${FEATURES}" PARENT_SCOPE)
endfunction()

# Join base and feature lists back into a target. Do not canonicalize.
function(_halide_join_target BASE FEATURES OUTVAR)
  foreach(F ${FEATURES})
    list(APPEND BASE ${F})
  endforeach()
  string(REPLACE ";" "-" BASE "${BASE}")
  set(${OUTVAR} "${BASE}" PARENT_SCOPE)
endfunction()

# Alphabetizes the features part of the target to make sure they always match no
# matter the concatenation order of the target string pieces. Remove duplicates.
function(_halide_canonicalize_target HALIDE_TARGET OUTVAR)
  if("${HALIDE_TARGET}" MATCHES ".*,.*")
    message(FATAL_ERROR "Multitarget may not be specified in _halide_canonicalize_target(${HALIDE_TARGET})")
  endif()
  _halide_split_target("${HALIDE_TARGET}" BASE FEATURES)
  list(REMOVE_DUPLICATES FEATURES)
  list(SORT FEATURES)
  _halide_join_target("${BASE}" "${FEATURES}" HALIDE_TARGET)
  set(${OUTVAR} "${HALIDE_TARGET}" PARENT_SCOPE)
endfunction()

# Given a HALIDE_TARGET, return the CMake target name for the runtime.
function(_halide_runtime_target_name HALIDE_TARGET OUTVAR)
  # MULTITARGETS = HALIDE_TARGET.split(",")
  string(REPLACE "," ";" MULTITARGETS "${HALIDE_TARGET}")
  # HALIDE_TARGET = MULTITARGETS.final_element()
  list(GET MULTITARGETS -1 HALIDE_TARGET)
  _halide_canonicalize_target("${HALIDE_TARGET}" HALIDE_TARGET)
  _halide_split_target("${HALIDE_TARGET}" BASE FEATURES)
  # Discard target features which do not affect the contents of the runtime.
  list(REMOVE_DUPLICATES FEATURES)
  list(REMOVE_ITEM FEATURES "user_context" "no_asserts" "no_bounds_query" "no_runtime" "profile")
  list(SORT FEATURES)
  # Now build up the name
  set(RESULT "halide_rt")
  foreach(B ${BASE})
    list(APPEND RESULT ${B})
  endforeach()
  if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    set(HALIDE_ABBREVIATE_TARGETS TRUE)
  endif()
  if(HALIDE_ABBREVIATE_TARGETS)
    # Windows systems still have limits of 260-character pathnames in
    # lots of situations, and CMake can replicate project names multiple times
    # in the same path, so long target strings can cause us to overflow
    # this limit, even if CMAKE_OBJECT_PATH_MAX is set. So here we make
    # algorithmically-generated abbreviations for all the feature strings
    # and use those for external cmaketarget/filenames.

    # Halide Target Features we know about. (This need not be exact, but should
    # be close for best compression.)
    list(APPEND KNOWN_FEATURES armv7s avx avx2 avx512 avx512_cannonlake avx512_knl
         avx512_skylake c_plus_plus_name_mangling cl_doubles cuda cuda_capability_30
         cuda_capability_32 cuda_capability_35 cuda_capability_50 cuda_capability_61
         debug f16c fma fma4 fuzz_float_stores hvx_128 hvx_64 hvx_shared_object
         hvx_v62 hvx_v65 hvx_v66 jit large_buffers matlab metal mingw msan no_asserts
         no_bounds_query no_neon no_runtime opencl opengl openglcompute
         power_arch_2_07 profile soft_float_abi sse41 trace_loads trace_realizations
         trace_stores user_context vsx)
    # Synthesize a one-or-two-char abbreviation based on the feature's position
    # in the KNOWN_FEATURES list.
    set(I 0)
    foreach(F ${KNOWN_FEATURES})
      math(EXPR II "97 + (${I} / 26)")
      if("${II}" GREATER 97)
        string(ASCII ${II} C1)
      else()
        set(C1 "")
      endif()
      math(EXPR II "97 + (${I} % 26)")
      string(ASCII ${II} C2)
      # CMake has no map-like structure; we'll fake it using synthesized variable names.
      set(HALIDE_TARGET_FEATURE_ABBREVIATION_${F} ${C1}${C2})
      math(EXPR I "${I} + 1")
    endforeach()
  endif()

  foreach(F ${FEATURES})
    if(DEFINED HALIDE_TARGET_FEATURE_ABBREVIATION_${F})
      list(APPEND RESULT ${HALIDE_TARGET_FEATURE_ABBREVIATION_${F}})
    else()
      # Unknown features get appended to the end
      list(APPEND RESULT ${F})
    endif()
  endforeach()

  # Finally, convert from a list into a _ separated name
  string(REPLACE ";" "_" RESULT "${RESULT}")
  set(${OUTVAR} "${RESULT}" PARENT_SCOPE)
endfunction()

# Generate the runtime library for the given halide_target; return
# its cmake target name in outvar.
function(_halide_library_runtime HALIDE_TARGET OUTVAR)
  if(NOT TARGET halide_library_runtime.generator)
    halide_generator(halide_library_runtime.generator SRCS "")
  endif()

  string(REPLACE "," ";" MULTITARGETS "${HALIDE_TARGET}")
  list(GET MULTITARGETS -1 HALIDE_TARGET)
  _halide_runtime_target_name("${HALIDE_TARGET}" RUNTIME_NAME)
  if(NOT TARGET "${RUNTIME_NAME}_runtime_gen")
    set(RUNTIME_LIB "${RUNTIME_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX}")

    _halide_genfiles_dir(${RUNTIME_NAME} GENFILES_DIR)
    set(GENERATOR_EXEC_ARGS "-o" "${GENFILES_DIR}")
    list(APPEND GENERATOR_EXEC_ARGS "-r" "${RUNTIME_NAME}")
    list(APPEND GENERATOR_EXEC_ARGS "target=${HALIDE_TARGET}")

    _halide_add_exec_generator_target(
      "${RUNTIME_NAME}_runtime_gen"
      GENERATOR_BINARY "halide_library_runtime.generator_binary"
      GENERATOR_ARGS   "${GENERATOR_EXEC_ARGS}"
      OUTPUTS          "${GENFILES_DIR}/${RUNTIME_LIB}"
    )

    # By default, IMPORTED libraries are only visible to the declaration
    # directories (and subdirectories); since runtime libraries are declared
    # lazily, we need to ensure they are globally visible to avoid ordering issues.
    add_library("${RUNTIME_NAME}" STATIC IMPORTED GLOBAL)
    add_dependencies("${RUNTIME_NAME}" "${RUNTIME_NAME}_runtime_gen")
    set_target_properties("${RUNTIME_NAME}" PROPERTIES
      IMPORTED_LOCATION "${GENFILES_DIR}/${RUNTIME_LIB}")

    # It's hard to force specific system libraries to the end of link order
    # in CMake, because of course it is; to mitigate this, we do snooping
    # here for common targets with extra dependencies and add them to
    # the dependencies for runtime, to ensure that they get sorted into
    # an appropriate spot in link order.
    set(RT_LIBS )

    # opengl
    _halide_has_target_feature("${HALIDE_TARGET}" opengl HAS_OPENGL)
    if("${HAS_OPENGL}")
      find_package(OpenGL QUIET)
      if (OpenGL_FOUND)
        list(APPEND RT_LIBS ${OPENGL_LIBRARIES})
      endif()
      if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
        # Linux systems need X11 for OpenGL as well
        find_package(X11 QUIET)
        if (X11_FOUND)
          list(APPEND RT_LIBS ${X11_LIBRARIES})
        endif()
      endif()
    endif()

    set_target_properties("${RUNTIME_NAME}" PROPERTIES
      INTERFACE_LINK_LIBRARIES "${RT_LIBS}")

  endif()
  set(${OUTVAR} "${RUNTIME_NAME}" PARENT_SCOPE)
endfunction()

function(_halide_add_exec_generator_target EXEC_TARGET)
  set(options )
  set(oneValueArgs GENERATOR_BINARY)
  set(multiValueArgs OUTPUTS GENERATOR_ARGS)
  cmake_parse_arguments(args "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

  set(EXTRA_OUTPUTS_COMMENT )
  foreach(OUTPUT ${args_OUTPUTS})
    if((${OUTPUT} MATCHES "^.*\\.h$") OR (${OUTPUT} MATCHES "^.*${CMAKE_STATIC_LIBRARY_SUFFIX}$"))
      # Ignore
    else()
      set(EXTRA_OUTPUTS_COMMENT "${EXTRA_OUTPUTS_COMMENT}\nEmitting extra Halide output: ${OUTPUT}")
    endif()
  endforeach()

  add_custom_target(${EXEC_TARGET} DEPENDS ${args_OUTPUTS})

  # As of CMake 3.x, add_custom_command() recognizes executable target names in its COMMAND.
  add_custom_command(
    OUTPUT ${args_OUTPUTS}
    DEPENDS ${args_GENERATOR_BINARY}
    COMMAND ${args_GENERATOR_BINARY} ${args_GENERATOR_ARGS}
    COMMENT "${EXTRA_OUTPUTS_COMMENT}"
  )
  foreach(OUT ${args_OUTPUTS})
    set_source_files_properties(${OUT} PROPERTIES GENERATED TRUE)
  endforeach()
endfunction()

# ----------------------- Configuration code

# If paths to tools, include, and libHalide aren't specified, infer them
# based on the path to the distrib folder. If the path to the distrib
# folder isn't specified, fail.
if("${HALIDE_TOOLS_DIR}" STREQUAL "" OR
    "${HALIDE_INCLUDE_DIR}" STREQUAL "" OR
    "${HALIDE_COMPILER_LIB}" STREQUAL "")
  if("${HALIDE_DISTRIB_DIR}" STREQUAL "")
    message(FATAL_ERROR "HALIDE_DISTRIB_DIR must point to the Halide distribution directory.")
  endif()
  set(HALIDE_INCLUDE_DIR "${HALIDE_DISTRIB_DIR}/include")
  set(HALIDE_TOOLS_DIR "${HALIDE_DISTRIB_DIR}/tools")
  if(${HALIDE_DISTRIB_USE_STATIC_LIBRARY})
    message(STATUS "Using ${HALIDE_DISTRIB_DIR}/lib/libHalide${CMAKE_STATIC_LIBRARY_SUFFIX}")
    add_library(_halide_compiler_lib STATIC IMPORTED)
    set_target_properties(_halide_compiler_lib PROPERTIES
      IMPORTED_LOCATION "${HALIDE_DISTRIB_DIR}/lib/libHalide${CMAKE_STATIC_LIBRARY_SUFFIX}"
      INTERFACE_INCLUDE_DIRECTORIES ${HALIDE_INCLUDE_DIR})
    set(HALIDE_COMPILER_LIB _halide_compiler_lib)
  else()
    message(STATUS "Using ${HALIDE_DISTRIB_DIR}/bin/libHalide${CMAKE_SHARED_LIBRARY_SUFFIX}")
    add_library(_halide_compiler_lib SHARED IMPORTED)
    set_target_properties(_halide_compiler_lib PROPERTIES
      IMPORTED_LOCATION "${HALIDE_DISTRIB_DIR}/bin/libHalide${CMAKE_SHARED_LIBRARY_SUFFIX}"
      INTERFACE_INCLUDE_DIRECTORIES ${HALIDE_INCLUDE_DIR})
    set(HALIDE_COMPILER_LIB _halide_compiler_lib)
  endif()
endif()

if("${HALIDE_SYSTEM_LIBS}" STREQUAL "")
  # If HALIDE_SYSTEM_LIBS isn't defined, we are compiling against a Halide distribution
  # folder; this is normally captured in the halide_config.cmake file. If that file
  # exists in the same directory as this one, just include it here.
  if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/halide_config.cmake")
    include("${CMAKE_CURRENT_LIST_DIR}/halide_config.cmake")
  else()
    message(WARNING "HALIDE_SYSTEM_LIBS is not set and we could not find halide_config.cmake")
  endif()
endif()

define_property(TARGET PROPERTY _HALIDE_GENERATOR_NAME
                BRIEF_DOCS "Internal use by Halide build rules: do not use externally"
                FULL_DOCS "Internal use by Halide build rules: do not use externally")

add_library(_halide_library_from_generator_rungen "${HALIDE_TOOLS_DIR}/RunGen.cpp")
target_include_directories(_halide_library_from_generator_rungen PRIVATE "${HALIDE_INCLUDE_DIR}")
halide_use_image_io(_halide_library_from_generator_rungen)
_halide_set_cxx_options(_halide_library_from_generator_rungen)
set_target_properties(_halide_library_from_generator_rungen PROPERTIES EXCLUDE_FROM_ALL TRUE)


text:
Liquid-Glob
===

A custom tag for the Liquid templating engine (and therefore Jekyll) that allows you to iterate over files in a directory, using a glob pattern (see `Dir.glob`). This snippet barely qualifies for it's own repository but I'm including it for completeness.

Usage
---

If you're using Jekyll you can simply clone this repository into your `_plugins` folder to begin using it, otherwise place it somewhere where it will be read by your application.

A usage example:

```html+jinja
<ul>
  {% glob images/*_slider.jpg %}
    {% for file in files %}
      <li><img src="{{ file }}" /></li>
    {% endfor %}
  {% endglob %}
</ul>
```


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorPrimary"
    android:padding="16dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Keine Internetverbindung."
        android:textColor="#FFFFFF"
        android:textSize="16sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Du hast zur Zeit keine Verbindung zum Internet. Überprüfe deine Einstellungen und versuche es erneut."
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>
</LinearLayout>


text:
GroveHeartrate::GroveHeartrate(int pinsda, int pinscl)
{
    this->i2c = (I2C_T *)malloc(sizeof(I2C_T));
    grove_heartrate_init(this->i2c, pinsda, pinscl);
}

bool GroveHeartrate::write_setup(void)
{
    return grove_heartrate_write_setup(this->i2c);
}

bool GroveHeartrate::read_heartrate(uint8_t *lux)
{
    return grove_heartrate_getheartrate(this->i2c, lux);
}


text:
package nl.equens.tester;
import java.util.HashSet;
import java.util.Set;

public class SudokuValidator {
	private static final int VALUE_MAX = 9;
	private static final int VALUE_MIN = 1;
	private static final int VALUES_COUNT = VALUE_MAX - VALUE_MIN + 1;
	private static final int FIELD_WIDTH = VALUES_COUNT;
	private static final int FIELD_HEIGHT = FIELD_WIDTH;
	private static final int BOX_HEIGHT = (int) Math.round(Math
			.sqrt(VALUES_COUNT));
	private static final int BOX_WIDTH = BOX_HEIGHT;
	private Integer[][] field;

	public SudokuValidator(Integer[][] field) {
		this.field = field;

	}

	public boolean isValid() {
		boolean isValid = true;

		isValid = validateGrid();
		if (isValid) {
			isValid = validateRows();
		}

		if (isValid) {
			isValid = validateColumns();
		}

		if (isValid) {
			isValid = validateBoxes();
		}

		return isValid;

	}

	/**
	 * Validate whether the provided Grid is valid.
	 *
	 * Checks the height, width and cell values
	 *
	 * @return true if valid, false otherwise
	 */
	private boolean validateGrid() {
		if (field.length != FIELD_HEIGHT) {
			return false;
		}

		if (field[0].length != FIELD_WIDTH) {
			return false;
		}

		if (validateCells()) {
			return false;
		}

		return true;
	}

	/**
	 * Validate whether the provided cells are valid.
	 *
	 * @return true if valid, false otherwise
	 */
	private boolean validateCells() {
		for (Integer[] row : field) {
			for (Integer value : row) {
				if (value == null || value < VALUE_MIN || value > VALUE_MAX) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Validate the grid rows
	 *
	 * @return true if all rows are valid, false otherwise
	 */
	private boolean validateRows() {
		for (Integer[] row : field) {
			boolean isValidRow = validateRow(row);
			if (!isValidRow) {
				return false;
			}
		}

		return true;
	}

	private boolean validateRow(Integer[] row) {
		Set<Integer> hits = new HashSet<>();
		for (int value : row) {
			hits.add(value);
		}
		return hits.size() == VALUES_COUNT;
	}

	/**
	 * Validate the grid columns
	 *
	 * @return true if all columns are valid, false otherwise
	 */
	private boolean validateColumns() {
		for (int colIndex = 0; colIndex < FIELD_WIDTH; colIndex++) {
			boolean isValidColumn = validateColumn(colIndex);
			if (!isValidColumn) {
				return false;
			}
		}

		return true;
	}

	private boolean validateColumn(final int colIndex) {
		Set<Integer> hits = new HashSet<>();
		for (int rowIndex = 0; rowIndex < FIELD_HEIGHT; rowIndex++) {
			hits.add(field[rowIndex][colIndex]);
		}
		return hits.size() == VALUES_COUNT;
	}

	/**
	 * Validate the grid boxes
	 *
	 * @return true if all boxes are valid, false otherwise
	 */
	private boolean validateBoxes() {
		for (int cellStartRow = 0; cellStartRow < FIELD_HEIGHT; cellStartRow += BOX_HEIGHT) {
			for (int cellStartCol = 0; cellStartCol < FIELD_WIDTH; cellStartCol += BOX_WIDTH) {
				boolean isValidCell = validateBox(cellStartRow, cellStartCol);
				if (!isValidCell) {
					return false;
				}
			}
		}

		return true;
	}

	private boolean validateBox(final int cellStartRow, final int cellStartCol) {
		Set<Integer> hits = new HashSet<>();
		final int cellEndRow = cellStartRow + BOX_HEIGHT;
		final int cellEndCol = cellStartCol + BOX_WIDTH;

		for (int rowIndex = cellStartRow; rowIndex < cellEndRow; rowIndex++) {
			for (int colIndex = cellStartCol; colIndex < cellEndCol; colIndex++) {
				hits.add(field[rowIndex][colIndex]);
			}
		}
		return hits.size() == VALUES_COUNT;
	}

	public boolean matchesSeed(Integer[][] seed) {
		int height = seed.length;
		if (height != field.length) {
			return false;
		}

		int width = seed[0].length;
		if (width != field[0].length) {
			return false;
		}

		for (int rowIndex = 0; rowIndex < height; rowIndex++) {
			for (int colIndex = 0; colIndex < width; colIndex++) {
				final Integer seedValue = seed[rowIndex][colIndex];
				if (seedValue != null) {
					final int fieldValue = field[rowIndex][colIndex];
					if (seedValue != fieldValue) {
						return false;
					}
				}
			}
		}

		return true;
	}

}


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

namespace SimplePointPlugin.Helpers
{
  internal class RBushCoord3D : ISpatialData, IComparable<RBushCoord3D>
  {

    public static readonly double Tolerance = 0.000001;
    private Envelope _envelope;
    private long _oid;
    private ArcGIS.Core.Geometry.Coordinate3D _coord;

    public RBushCoord3D(ArcGIS.Core.Geometry.Coordinate3D coord, long oid)
    {
      _oid = oid;

      //save the original
      _coord = coord;

      //RBush requires a reference
      //to the envelope so we can't construct it "on-the-fly"
      _envelope = new Envelope(
        minX: coord.X - Tolerance,
        minY: coord.Y - Tolerance,
        maxX: coord.X + Tolerance,
        maxY: coord.Y + Tolerance);

    }

    //ISpatialData from RBush
    public ref readonly Envelope Envelope => ref _envelope;

    public long ObjectID => _oid;

    public ArcGIS.Core.Geometry.Coordinate3D Coordinate3D => _coord;

    public int CompareTo(RBushCoord3D other)
    {
      return this.ObjectID.CompareTo(other.ObjectID);
    }
  }

  internal static class RBushExtensions
  {

    internal static bool Contains2D(this Envelope envelope, ArcGIS.Core.Geometry.Coordinate3D coord)
    {
      //we are only comparing the x and y!
      return (coord.X < envelope.MaxX &&
              coord.X > envelope.MinX &&
              coord.Y < envelope.MaxY &&
              coord.Y > envelope.MinY);
    }

    internal static Envelope Union2D(this Envelope envelope, Envelope other)
    {
      return new Envelope(
        minX: Math.Min(envelope.MinX, other.MinX),
        minY: Math.Min(envelope.MinY, other.MinY),
        maxX: Math.Max(envelope.MaxX, other.MaxX),
        maxY: Math.Max(envelope.MaxY, other.MaxY));
    }

    internal static ArcGIS.Core.Geometry.Envelope ToEsriEnvelope(this Envelope envelope,
                                                       ArcGIS.Core.Geometry.SpatialReference sr = null,
                                                       bool hasZ = false,
                                                       bool hasM = false)
    {
      var builder = new ArcGIS.Core.Geometry.EnvelopeBuilderEx(ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(
                  envelope.MinX,
                  envelope.MinY,
                  envelope.MaxX,
                  envelope.MaxY,
                  sr));

      //Assume 0 for Z
      if (hasZ)
      {
        builder.ZMin = 0;
        builder.ZMax = 0;
      }
      builder.HasZ = hasZ;
      builder.HasM = hasM;
      return builder.ToGeometry();
    }

    internal static Envelope ToRBushEnvelope(this ArcGIS.Core.Geometry.Envelope esriEnvelope)
    {
      //Spatial index does not handle Z
      return new Envelope(
        minX: esriEnvelope.XMin,
        minY: esriEnvelope.YMin,
        maxX: esriEnvelope.XMax,
        maxY: esriEnvelope.YMax);
    }

    internal static ArcGIS.Core.Geometry.MapPoint ToMapPoint(this RBushCoord3D rbushCoord,
                                                 ArcGIS.Core.Geometry.SpatialReference sr)
    {
      return ArcGIS.Core.Geometry.MapPointBuilderEx.CreateMapPoint(rbushCoord.Coordinate3D, sr);
    }

    internal static bool HasRelationship(this ArcGIS.Core.Geometry.IGeometryEngine engine,
                                          ArcGIS.Core.Geometry.Geometry geom1,
                                          ArcGIS.Core.Geometry.Geometry geom2,
                                          ArcGIS.Core.Data.SpatialRelationship relationship)
    {

      switch (relationship)
      {
        case ArcGIS.Core.Data.SpatialRelationship.Intersects:
          return engine.Intersects(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.IndexIntersects:
          return engine.Intersects(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.EnvelopeIntersects:
          return engine.Intersects(geom1.Extent, geom2.Extent);
        case ArcGIS.Core.Data.SpatialRelationship.Contains:
          return engine.Contains(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.Crosses:
          return engine.Crosses(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.Overlaps:
          return engine.Overlaps(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.Touches:
          return engine.Touches(geom1, geom2);
        case ArcGIS.Core.Data.SpatialRelationship.Within:
          return engine.Within(geom1, geom2);
      }
      return false;//unknown relationship
    }
  }
}


text:
define(['require/app', 'require/service1'], function(module) {
  module.controller('url11Ctrl', function ($scope, Service1Srv) {
    $scope.whoami = 'url11Ctrl';
    $scope.whoismyservice = Service1Srv();
  });
});


text:
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine.UI;

public class TurnBasedCombatStateMachine : MonoBehaviour {

    private int turnNumber = 0;
	private Button back;
	private Transform endscene;
	private Text content;
    private Text wl;
    private Transform lg;
    private Transform sv;
    public bool isFresh = true;
    private static LevelUp lu = new LevelUp();
    public static int experienceGain = 40;
    public static int goldPenalty = 500; // minus this if lost
    private bool isLevelUp = false;
    public enum BattleStates {START,PLAYERCHOICE, PLAYERANIMATE,ENEMYCHOICE, LOSE, WIN }
    private BattleStates currentState;
    private WorldInformation winfo;

    public void setCurrentState(int battleState)
    {
        currentState = (BattleStates)battleState;
    }
    public BattleStates getCurrentState()
    {
        return currentState;
    }

	// Use this for initialization
	void Start () {

        currentState = BattleStates.PLAYERCHOICE;
		back = transform.Find ("Canvas/Back").GetComponent<Button> ();
		endscene = transform.Find ("Canvas/EndScene");
		content = endscene.Find ("Scroll View/Viewport/Content").GetComponent<Text> ();
        sv = endscene.Find("Scroll View");
        wl = endscene.Find("State").GetComponent<Text>();
        lg = endscene.Find("Loss");
        winfo = GameObject.Find("GameInformation").GetComponent<WorldInformation>();
	}

	private string displayString(BaseCharacter c){

		int oldD = c.Defense;
		int oldA = c.Agility;
		int oldI = c.Intellect;
		int oldS = c.Strength;
		int oldH = c.Health;

		return
			"\nDefense: " + oldD + "-->" + c.Defense +
			"\nAgility: " + oldA + "-->" + c.Agility +
			"\nIntellect: " + oldI + "-->" + c.Intellect +
			"\nStrength: " + oldS + "-->" + c.Strength +
			"\nHealth: " + oldH + "-->" + c.CurrentHealth +"\n";
	}

	public void nextScene()
	{
        endscene.gameObject.SetActive(false);
        lg.gameObject.SetActive(false);
        sv.gameObject.SetActive(false);

        isLevelUp = false;
        //next.onClick.RemoveAllListeners();
        Debug.Log("ON TO THE NEXT SCENE");
		Application.LoadLevel ("test");
	}

    public void Lose()
    {
        back.gameObject.SetActive(true);
        back.onClick.AddListener(() => nextScene());
        isFresh = false;
        Debug.Log("YOU LOSE -------------------------");
        sv.gameObject.SetActive(false);
        endscene.gameObject.SetActive(true);
        lg.gameObject.SetActive(true);
        wl.text = "You Lose!";

        //TODO GUI:
        //You Lose!
        //Lose 500 gold.

        // if lose, minus gold
        GameInformation.Gold -= goldPenalty;
        if (GameInformation.Gold < 0)
        {
            GameInformation.Gold = 0;
        }

    }

    public void Win()
    {
        back.gameObject.SetActive(true);
        back.onClick.AddListener(() => nextScene());
        isFresh = false;
        Debug.Log("YOU WIN -------------------------");
        endscene.gameObject.SetActive(true);
        sv.gameObject.SetActive(true);
        wl.text = "You Win!";
        //string quest = WorldInformation.CurrentQuest.QuestName;
        Debug.Log(WorldInformation.CurrentQuest.QuestName);
        content.text = "You have finished the quest: \n* *\n";
        content.text += WorldInformation.CurrentQuest.QuestName ;
        content.text += "\n* *\nAll characters have gained 40 experience.";

        //TODO GUI:
        //You Win!
        //You have finished the current quest.name and gained all the rewards.
        //Every character gains 40 XP.

        // if win, get the rewards
        GameInformation.Gold += WorldInformation.CurrentQuest.GoldReward;

        if (WorldInformation.CurrentQuest.WeaponReward != null)
        {
            GameInformation.PlayerInventory.Weapons.Add(WorldInformation.CurrentQuest.WeaponReward);
        }
        if (WorldInformation.CurrentQuest.EquipmentReward != null)
        {
            GameInformation.PlayerInventory.Equipment.Add(WorldInformation.CurrentQuest.EquipmentReward);
        }
        if (WorldInformation.CurrentQuest.PotionReward != null)
        {
            GameInformation.PlayerInventory.Potions.Add(WorldInformation.CurrentQuest.PotionReward);
        }

        // move the quest to FinishedQuests
        GameInformation.PlayerQuestLog.FinishedQuests.Add(WorldInformation.CurrentQuest);
        GameInformation.PlayerQuestLog.CurrentQuests.Remove(WorldInformation.CurrentQuest);
        WorldInformation.CurrentQuest = null;

        //Gain XP, check for levelup
        promote(GameInformation.PlayerCharacter);
        promote(GameInformation.Char1);
        promote(GameInformation.Char2);
        promote(GameInformation.Char3);
        promote(GameInformation.Char4);
        promote(GameInformation.Char5);

    }

    //Helper func: Gain XP, check for levelup
    private void promote(BaseCharacter character)
    {
        if (character != null)
        {

            character.CurrentXP += experienceGain;
            isLevelUp = lu.LevelUpCharacter(character);
            if (isLevelUp)
            {

                // save old stats for GUI display
                int oldD = character.Defense;
                int oldA = character.Agility;
                int oldI = character.Intellect;
                int oldS = character.Strength;

                // increase stats when level up
                int tier = (int)character.PlayerClass / 4 + 1;

                //basic increase
                character.Defense += tier;
                character.Agility += tier;
                character.Intellect += tier;
                character.Strength += tier;
                character.Health += tier * 20;
                if (character.Health > 100)
                {
                    character.Health = 100;
                }

                //extra increase based on class
                if ((int)character.PlayerClass % 4 == 0)
                {
                    //squire
                    character.Defense += tier;
                    character.Strength += tier;
                }
                else if ((int)character.PlayerClass % 4 == 1)
                {
                    //Apprentice
                    character.Agility += tier;
                    character.Intellect += tier;
                }
                else if ((int)character.PlayerClass % 4 == 2)
                {
                    //Thief
                    character.Agility += tier;
                    character.Strength += tier;

                }
                else
                {
                    //Archer
                    character.Defense += tier;
                    character.Intellect += tier;
                }

                try
                {
                    SaveInformation.SaveAllCharacterInformation();
                }
                catch (Exception e)
                {
                    Debug.Log("Couldnt save character information");
                }

                content.text += "\n* *\nLevel up!\n* *\n" + character.PlayerName +
                "\nDefense: " + oldD + "-->" + character.Defense +
                "\nAgility: " + oldA + "-->" + character.Agility +
                "\nIntellect: " + oldI + "-->" + character.Intellect +
                "\nStrength: " + oldS + "-->" + character.Strength;

            }
        }
    }

	void Update () {

        Debug.Log(currentState);

        switch (currentState)
        {
            //setup functions that run when each state is active.
            case (BattleStates.START):

                //setup battle function
                break;

            //Set players turn to true------------------------------------------------------------------------------------------------------
            case (BattleStates.PLAYERCHOICE):

                Transform players = transform.GetChild(0);
                for (int i = 0; i < players.childCount; i++)
                {
                    CharController currentPlayer = players.GetChild(i).GetComponent<CharController>();

                    if (currentPlayer.myTurn)
                    {
                        //Debug.Log("Waiting for player " + i);
                        break; //Dont Continue untill this players turn is over.
                    }

                    if (!currentPlayer.myTurn && turnNumber == i)
                    {
                        currentPlayer.myTurn = true;
                        turnNumber += 1;
                        break;
                    }
                }

                if (turnNumber == players.childCount && !players.GetChild(turnNumber - 1).GetComponent<CharController>().myTurn)
                {
                    turnNumber = 0;
                    currentState = BattleStates.ENEMYCHOICE;
                }

                break;

            //Set enemies turn to true--------------------------------------------------------------------------------------------------------
            case (BattleStates.ENEMYCHOICE):
                //Need Artificial intelligence here
                Transform enemies = transform.GetChild(1);
                for (int i = 0; i < enemies.childCount; i++)
                {
                    CharController currentPlayer = enemies.GetChild(i).GetComponent<CharController>();
                    if (currentPlayer.myTurn)
                        break; //Dont Continue untill this players turn is over.
                    if (!currentPlayer.myTurn && turnNumber == i)
                    {
                        currentPlayer.myTurn = true;
                        turnNumber += 1;
                        break;
                    }
                }

                if (turnNumber == enemies.childCount && !enemies.GetChild(turnNumber - 1).GetComponent<CharController>().myTurn)
                {
                    turnNumber = 0;
                    currentState = BattleStates.PLAYERCHOICE;
                }

                break;
            //LOSS---------------------------------------------------------------------------------------------------------------------------------------
            case (BattleStates.LOSE):
                if (isFresh)
                {
                    Lose();
                }

                currentState = BattleStates.START;
                break;

            case (BattleStates.WIN):
                if (isFresh)
                {
                    Win();
                }
                currentState = BattleStates.START;
                break;

        }
    }
}


text:
define([
  'client/views/graph/stack',
  'extensions/collections/collection'
],
function (Stack, Collection) {
  describe('Stack component', function () {
    var el, wrapper, collection, graph;
    var d3 = Stack.prototype.d3;
    beforeEach(function () {
      el = $('

').appendTo($('body'));
      wrapper = d3.select(el[0]).append('svg').append('g');
      collection = new Collection([
        { 'a:count': 1, 'b:count': 2, 'total:count': 3 },
        { 'a:count': 4, 'b:count': 5, 'total:count': 9 },
        { 'a:count': 7, 'b:count': 8, 'total:count': 15 },
        { 'a:count': 9, 'b:count': 10, 'total:count': 19 },
        { 'a:count': 11, 'b:count': 12, 'total:count': 23 }
      ]);

      graph = {
        getXPos: function (index) {
          return index;
        },
        getYPos: function (index, attr) {
          return collection.at(index) ? collection.at(index).get(attr) : null;
        },
        getY0Pos: function () {
          return 0;
        },
        innerHeight: 100,
        innerWidth: 200
      };

    });

    afterEach(function () {
      el.remove();
    });

    describe('render', function () {

      var view;
      beforeEach(function () {
        view = new Stack({
          interactive: false,
          wrapper: wrapper,
          collection: collection,
          scales: {
            x: function (x) {
              return x;
            },
            y: function (y) {
              return y;
            }
          },
          graph: graph,
          valueAttr: 'a:count'
        });
      });

      it('renders a stack consisting of a stroked path and a filled path for each item in the collection', function () {
        view.render();
        var coords = _.map(collection.pluck('a:count'), function (y, i) {
          return (i + 0.5) + ',' + (y);
        });
        var line = 'M' + coords.join('L');
        expect(wrapper.selectAll('path.line').attr('d')).toEqual(line);
        var basecoords = _.map([5, 4, 3, 2, 1], function (x) {
          return (x - 0.5) + ',0';
        });
        var stackLine = 'M' + [].concat(coords, basecoords).join('L') + 'Z';
        expect(wrapper.selectAll('path.stack').attr('d')).toEqual(stackLine);
      });

      it('renders multiple paths when there are gaps in the data', function () {
        collection.at(2).set('a:count', null);
        view.render();
        expect(wrapper.selectAll('path.line').attr('d')).toEqual('M0.5,1L1.5,4M3.5,9L4.5,11');
        expect(wrapper.selectAll('path.stack').attr('d')).toEqual('M0.5,1L1.5,4L1.5,0L0.5,0ZM3.5,9L4.5,11L4.5,0L3.5,0Z');
      });

      it('puts the bottom of the stack along the baseline provided by the graph', function () {
        graph.getY0Pos = function (index) {
          return index;
        };
        view.render();
        var coords = _.map(collection.pluck('a:count'), function (y, i) {
          return (i + 0.5) + ',' + y;
        });
        var basecoords = _.map([4, 3, 2, 1, 0], function (x) {
          return (x + 0.5) + ',' + x;
        });
        var stackLine = 'M' + [].concat(coords, basecoords).join('L') + 'Z';
        expect(wrapper.selectAll('path.stack').attr('d')).toEqual(stackLine);
      });

      it('scales x&y values appropriately using scale functions provided', function () {
        view.scales = {
          x: function (x) {
            return 2 * x;
          },
          y: function (y) {
            return 3 * y;
          }
        };
        view.render();
        var coords = _.map(collection.pluck('a:count'), function (y, i) {
          return ((2 * i) + 0.5) + ',' + (3 * y);
        });
        var line = 'M' + coords.join('L');
        expect(wrapper.selectAll('path.line').attr('d')).toEqual(line);
        var basecoords = _.map([4, 3, 2, 1, 0], function (x) {
          return ((2 * x) + 0.5) + ',0';
        });
        var stackLine = 'M' + [].concat(coords, basecoords).join('L') + 'Z';
        expect(wrapper.selectAll('path.stack').attr('d')).toEqual(stackLine);
      });

    });

    describe('onChangeSelected', function () {

      describe('when not grouped', function () {

        var view;
        beforeEach(function () {
          view = new Stack({
            interactive: false,
            wrapper: wrapper,
            collection: collection,
            scales: {
              x: function (x) {
                return x;
              },
              y: function (y) {
                return y;
              }
            },
            graph: graph,
            valueAttr: 'a:count'
          });
        });

        it('adds a selected class to line', function () {
          view.render();
          view.onChangeSelected(collection.at(0), 0);
          expect(wrapper.select('path.line').attr('class').split(' ')).toContain('selected');
          expect(wrapper.select('path.stack').attr('class').split(' ')).toContain('selected');
        });

        it('does not render a highlighted cursor line', function () {
          view.render();
          view.onChangeSelected(collection.at(0), 0);
          expect(wrapper.selectAll('.cursorLine.selected')[0].length).toEqual(0);
        });

        it('does not render an extra selection point', function () {
          view.render();
          view.onChangeSelected(collection.at(3), 3);
          expect(wrapper.selectAll('.selectedIndicator')[0].length).toEqual(1);
          var c1 = d3.select(wrapper.selectAll('.selectedIndicator')[0][0]);
          expect(c1.attr('cy')).toEqual('9');
        });

      });

      describe('when grouped', function () {

        var view;
        beforeEach(function () {
          view = new Stack({
            interactive: false,
            wrapper: wrapper,
            collection: collection,
            scales: {
              x: function (x) {
                return x;
              },
              y: function (y) {
                return y;
              }
            },
            graph: graph,
            valueAttr: 'a:count',
            grouped: true
          });
          graph.getY0Pos = function (index, attr) {
            return collection.at(index).get(attr) / 2;
          };
        });

        it('selects stack if valueAttr option matches line valueAttr', function () {
          view.render();
          view.onChangeSelected(collection.at(3), 3, { valueAttr: 'a:count' });
          expect(wrapper.select('path.line').attr('class')).toContain('selected');
          expect(wrapper.select('path.stack').attr('class')).toContain('selected');
        });

        it('deselects stack if valueAttr option does not match line valueAttr', function () {
          view.render();
          view.onChangeSelected(collection.at(3), 3, { valueAttr: 'b:count' });
          expect(wrapper.select('path.line').attr('class').split(' ')).not.toContain('selected');
          expect(wrapper.select('path.line').attr('class').split(' ')).toContain('not-selected');
          expect(wrapper.select('path.stack').attr('class').split(' ')).not.toContain('selected');
          expect(wrapper.select('path.stack').attr('class').split(' ')).toContain('not-selected');
        });

        it('renders a highlighted cursor line across the the stack', function () {
          view.render();

          view.onChangeSelected(collection.at(0), 0, { valueAttr: 'a:count' });

          expect(wrapper.selectAll('.cursorLine.selected').attr('x1')).toEqual('0.5');
          expect(wrapper.selectAll('.cursorLine.selected').attr('x2')).toEqual('0.5');
          expect(wrapper.selectAll('.cursorLine.selected').attr('y1')).toEqual('0.5');
          expect(wrapper.selectAll('.cursorLine.selected').attr('y2')).toEqual('1');

          view.onChangeSelected(collection.at(1), 1, { valueAttr: 'a:count' });

          expect(wrapper.selectAll('.cursorLine.selected').attr('x1')).toEqual('1.5');
          expect(wrapper.selectAll('.cursorLine.selected').attr('x2')).toEqual('1.5');
          expect(wrapper.selectAll('.cursorLine.selected').attr('y1')).toEqual('2');
          expect(wrapper.selectAll('.cursorLine.selected').attr('y2')).toEqual('4');
        });

        it('renders an extra selection point at bottom of stack', function () {
          view.render();

          view.onChangeSelected(collection.at(3), 3, { valueAttr: 'a:count' });

          expect(wrapper.selectAll('.selectedIndicator')[0].length).toEqual(2);
          var c1 = d3.select(wrapper.selectAll('.selectedIndicator')[0][0]);
          var c2 = d3.select(wrapper.selectAll('.selectedIndicator')[0][1]);
          expect(c1.attr('cy')).toEqual('9');
          expect(c2.attr('cy')).toEqual('4.5');
        });

      });

    });
  });
});


text:
from __future__ import unicode_literals

import collections

from . import util

__all__ = ['parse_public_key_jwk']

class PublicKey(object):
    def key_type(self):
        raise NotImplementedError()

    def key_id(self):
        raise NotImplementedError()

    def crypto_public_key(self):
        raise NotImplementedError()

    def pem_block(self):
        raise NotImplementedError()

    def to_map(self):
        raise NotImplementedError()

    def verify(self, buffer, alg, signature):
        raise NotImplementedError()

    def marshal_json(self):
        return util.dump_json(self.to_map())

    def json(self):
        return collections.OrderedDict(sorted(self.to_map().items(), key=lambda item: item[0]))

class PrivateKey(PublicKey):
    def public_key(self):
        raise NotImplementedError()

    def crypto_private_key(self):
        raise NotImplementedError()

    def sign(self, buffer, hash_id):
        raise NotImplementedError()

def parse_public_key_jwk(jwk):
    from libtrust import ec_key
    from libtrust import rsa_key

    kty = jwk['kty']
    return {
        'EC': ec_key.ec_public_key_from_map,
        'RSA': rsa_key.rsa_public_key_from_map
    }[kty](jwk)


text:
Find a Shoe

        Loading...

 0" >

{{product.name}}

                {{ product.company }}

 0" class="text-center">

No Products Found that Match Your Search


text:
#ifndef _RAYBOUNDINGBOX_H_
#define _RAYBOUNDINGBOX_H_

#include <tbb/tbb.h>

#include <core/Common.h>
#include <core/RayUncompressed.h>

MSC_NAMESPACE_BEGIN

/**
 * @brief      Functor class to find bounding box from an array of rays
 *
 * This class was created to find the bounding box of a group of rays using tbb in parrallel manner.
 */
class RayBoundingbox
{
public:
  /**
   * @brief      Initialiser list for class
   */
  RayBoundingbox(RayUncompressed* _data)
   : m_data(_data)
  {;}

  /**
   * @brief      Initialiser list used when splitting class
   */
  RayBoundingbox(RayBoundingbox& s, tbb::split )
   : m_data(s.m_data)
  {;}

  /**
   * @brief      Operator overloader to allow the class to act as a functor with tbb
   *
   * @param[in]  r           a one dimensional range over an array of rays
   */
  void operator()(const tbb::blocked_range< size_t >& r);

  /**
   * @brief      Join method to allow for a parallel reduction algorithm and avoid thread contention
   *
   * @param      rhs   { parameter_description }
   */
  void join( RayBoundingbox& rhs );

  /**
   * @brief      Getter method for bounding box
   *
   * @return     bounding box
   */
  inline BoundingBox3f value() const {return m_value;}

private:
  RayUncompressed* m_data;
  BoundingBox3f m_value;
};

MSC_NAMESPACE_END

#endif