text:
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) :  [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
//     Template File Name:  methodTemplate.tt
//     Build date: 2017-10-08
//     PHP generator version: 1.0.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the Civic Info v2 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Provides polling places, early vote locations, contest data, election officials, and government representatives for U.S. residential addresses.
// API Documentation Link https://developers.google.com/civic-information
//
// Discovery Doc  https://www.googleapis.com/discovery/v1/apis/civicinfo/v2/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
session_start();

/***************************************************
* Include this line for service account authencation.  Note: Not all APIs support service accounts.
//require_once __DIR__ . '/ServiceAccount.php';
* Include the following four lines Oauth2 authencation.
* require_once __DIR__ . '/Oauth2Authentication.php';
* $_SESSION['mainScript'] = basename($_SERVER['PHP_SELF']);   // Oauth2callback.php will return here.
* $client = getGoogleClient();
* $service = new Google_Service_Civicinfo($client);
****************************************************/

// Option paramaters can be set as needed.
 $optParams = array(

  //'address' => '[YourValue]',  // The address to look up. May only be specified if the field ocdId is not given in the URL.

  //'includeOffices' => '[YourValue]',  // Whether to return information about offices and officials. If false, only the top-level district information will be returned.

  //'levels' => '[YourValue]',  // A list of office levels to filter by. Only offices that serve at least one of these levels will be returned. Divisions that don't contain a matching office will not be returned.

  //'roles' => '[YourValue]',  // A list of office roles to filter by. Only offices fulfilling one of these roles will be returned. Divisions that don't contain a matching office will not be returned.
  'fields' => '*'
);
// Single Request.
$results = representativesRepresentativeInfoByAddressExample($service, $optParams);

/**
* Looks up political geography and representative information for a single address.
* @service Authenticated Civicinfo service.
* @optParams Optional paramaters are not required by a request.
* @return RepresentativeInfoResponse
*/
function representativesRepresentativeInfoByAddressExample($service, $optParams)
{
	try
	{
		// Parameter validation.
		if ($service == null)
			throw new Exception("service is required.");
		if ($optParams == null)
			throw new Exception("optParams is required.");
		// Make the request and return the results.
		return $service->representatives->RepresentativeInfoByAddressRepresentatives($optParams);
	}
	catch (Exception $e)
	{
		print "An error occurred: " . $e->getMessage();
	}
}
?>


text:
package ai.cogmission.mosaic;

import java.util.ArrayList;
import java.util.List;

import javax.swing.text.Position;

/**
 * Contains and creates {@link PathIterator.Path} objects. Accepts
 * {@link PathVisitor}s on behalf of the layout mechanism in order to
 * dispatch the visitor along useful {@code PathIterator.Path}s it has previously
 * assembled during the initial layout phase.
 */
class PathIterator<T> implements PathVisitable<T> {
    private List<HorizontalPath> horizontalPaths;
    private List<VerticalPath> verticalPaths;

    /**
     * Constructs a new {@code PathIterator}
     */
    public PathIterator() {
        horizontalPaths = new ArrayList<HorizontalPath>();
        verticalPaths = new ArrayList<VerticalPath>();
    }

    /**
     * Releases memory by clearing out all {@link Path} references.
     */
    void clearAll() {
    	horizontalPaths.clear();
    	verticalPaths.clear();
    }

    /**
     * Copy constructor. Uses the specified {@link LayoutImpl}'s nodelist
     * to re-construct an identical copy of this {@code PathIterator}
     *
     * @param l			the {@link LayoutImpl} supply the required {@link Node}s
     * @param p			the {@code PathIterator} to copy.
     */
    public PathIterator(LayoutImpl<T> l, PathIterator<T> p) {
    	this();

    	for(HorizontalPath path : p.horizontalPaths) {
    		horizontalPaths.add(path.getCopy(l));
    	}

    	for(VerticalPath path : p.verticalPaths) {
    		verticalPaths.add(path.getCopy(l));
    	}
    }

    /**
     * Returns a List of {@link HorizontalPath} objects.
     *
     * @return	 a List of {@link HorizontalPath} objects.
     */
    public List<HorizontalPath> getHorizontalPaths() {
        return horizontalPaths;
    }

    /**
     * Returns a List of {@link VerticalPath} objects.
     *
     * @return	a List of {@link VerticalPath} objects.
     */
    public List<VerticalPath> getVerticalPaths() {
        return verticalPaths;
    }

    /**
     * Returns a count of vertical paths within this
     * {@code PathIterator}
     *
     * @return	a count of vertical paths within this
     * {@code PathIterator}
     */
    public int getVerticalPathCount() {
    	return verticalPaths.size();
    }

    /**
     * Returns a count of horizontal paths within this
     * {@code PathIterator}
     *
     * @return	a count of horizontal paths within this
     * {@code PathIterator}
     */
    public int getHorizontalPathCount() {
    	return horizontalPaths.size();
    }

    public int getTotalPathCount() {
    	return horizontalPaths.size() + verticalPaths.size();
    }

    /**
     * Called by {@link MosaicEngineImpl#requestLayout()} to do the
     * initial assembly of {@link Path} objects.
     *
     * @param node	the "root" node.
     */
    void assemblePaths(Node<T> node) {
    	if(horizontalPaths == null) {
	        horizontalPaths = new ArrayList<HorizontalPath>();
	        verticalPaths = new ArrayList<VerticalPath>();
    	}else{
    		horizontalPaths.clear();
    		verticalPaths.clear();
    	}

        assembleHorizontalPaths(node, horizontalPaths);
        assembleVerticalPaths(node, verticalPaths);
    }

    /**
     * The guts of horizontal path assembly which recursively calls
     * itself to descend the links between nodes at the very left
     * of a layout, until it comes across a node at the very right.
     *
     * When there is a branch from a Divider to many nodes, the path
     * up to that point is copied, the result of which creates a
     * distinct path to each from the starting object to a given
     * ending object.
     *
     * @param curr		the current {@link Node}
     * @param hPaths	List of {@link HorizontalPath}s
     * @param currPath	the current {@code HorizontalPath}
     */
    private void doHorizontalScan(Node<T> curr, List<HorizontalPath> hPaths, HorizontalPath currPath) {
        currPath.add(curr);
        if(curr.nextVertical != null) {
            currPath.add(curr.nextVertical);

            int i = 0;
            for(Node<T> n : curr.nextVertical.nextNodes()) {
                if(i++ == 0) {
                    doHorizontalScan(n, hPaths, currPath);
                }else{
                    currPath = currPath.copyBranch(n.prevVertical);
                    hPaths.add(currPath);
                    doHorizontalScan(n, hPaths, currPath);
                }
            }
        }
    }

    /**
     * Traverses (recursively) to the very bottommost object before calling {@link #doHorizontalScan(Position, List, HorizontalPath)}
     * to traverse the nodes from left to right, creating the {@link HorizontalPath} objects.
     *
     * @param curr		the current {@link Node}
     * @param hPaths	List of {@link HorizontalPath}s
     */
    private void assembleHorizontalPaths(Node<T> curr, List<HorizontalPath> hPaths) {
    	Divider<T> nextHorizontal = null;
        if((nextHorizontal = curr.nextHorizontal) != null && nextHorizontal.hasNext()) {
        	assembleHorizontalPaths(nextHorizontal.nextNodes().get(0), hPaths);
        }

        HorizontalPath currPath = new HorizontalPath();
        hPaths.add(currPath);
        doHorizontalScan(curr, hPaths, currPath);
    }

    /**
     * The guts of {@link VerticalPath} assembly which recursively calls
     * itself to descend the links between nodes at the very top
     * of a layout, until it comes across a node at the very bottom.
     *
     * When there is a branch from a {@link Divider} to many nodes, the path
     * up to that point is copied, the result of which creates a
     * distinct path to each from the starting object to a given
     * ending object.
     *
     * @param curr		the current {@link Node}
     * @param vPaths	List of {@link VerticalPath}s
     * @param currPath	the current {@code VerticalPath}
     */
    private void doVerticalScan(Node<T> curr, List<VerticalPath> vPaths, VerticalPath currPath) {
        currPath.add(curr);
        if(curr.nextHorizontal != null) {
            currPath.add(curr.nextHorizontal);

            int i = 0;
            for(Node<T> n : curr.nextHorizontal.nextNodes()) {
                if(i++ == 0) {
                    doVerticalScan(n, vPaths, currPath);
                }else{
                    currPath = currPath.copyBranch(n.prevHorizontal);
                    vPaths.add(currPath);
                    doVerticalScan(n, vPaths, currPath);
                }
            }
        }
    }

    /**
     * Traverses (recursively) to the very rightmost object before calling {@link #doVerticalScan(Position, List, VerticalPath)}
     * to traverse the nodes from left to right, creating the {@link VerticalPath} objects.
     *
     * @param curr		the current {@link Position}
     * @param vPaths	List of {@link HorizontalPath}s
     */
    private void assembleVerticalPaths(Node<T> curr, List<VerticalPath> vPaths) {
        Divider<T> nextVertical = null;
        if((nextVertical = curr.nextVertical) != null && nextVertical.hasNext()) {
        	assembleVerticalPaths(nextVertical.nextNodes().get(0), vPaths);
        }

        VerticalPath currPath = new VerticalPath();
        vPaths.add(currPath);
        doVerticalScan(curr, vPaths, currPath);
    }

    /**
     * Implementation of the {@link PathVisitable} interface which
     * accepts a {@link PathVisitor}.
     *
     * @param	lv 	the PathVisitor to accept
     */
    @Override
    public void accept(PathVisitor<T> lv) {
    	for(HorizontalPath p : horizontalPaths) {
    		p.accept(lv);
        }
        for(VerticalPath p : verticalPaths) {
        	p.accept(lv);
        }
    }

    /**
     * Temporary method used by tests to "lookup" a {@link Path}
     * by a containing {@link Node}'s String "id". Returns a list of
     * allPaths containing the Node specified by id.
     *
     * @param id	the String id of the {@link Node}
     * @return		Returns a list of allPaths containing the
     * 				Node specified by id.
     */
    public List<Path> lookup(String id) {
    	List<Path> results = new ArrayList<Path>();
    	for(HorizontalPath p : horizontalPaths) {
    		if(p.contains(id)) results.add(p);
    	}
    	for(VerticalPath p : verticalPaths) {
    		if(p.contains(id)) results.add(p);
    	}

    	return results;
    }

    /**
     * Base class for Paths containing nodes and dividers along either a horizontal
     * path or a vertical path beginning at one end of the layout surface
     * and ending at the other. Each path is unique in it's entirety while
     * it may be redundant along several points (an optimization waiting
     * for an opportune time). Paths are assembled by recursively descending
     * down a Node to divider pathway until a divider containing more than
     * one node is encountered. At this point, a copy of the current path is
     * made and the path splits into as many separate and unique paths as there
     * are branches from the divider. In this way, all possible routes through
     * a variable arrangement are covered.
     */
    abstract class Path {
    	/** List of all elements (i.e. Nodes, Dividers) in this path */
        protected List<Element<T>> elems = new ArrayList<Element<T>>();

        /** The count of dividers (every other node) along this path */
        //protected int dividerCount;

        /**
         * Returns a deep copy of this {@code Path} as it's known subtype
         * and with copies of all this Path's inner elements - which copies
         * are all residents of the specified {@link LayoutImpl} instead
         * of the Layout which contains this specific {@code Path}. Therefore,
         * the Layout passed in must already have built its own {@link Element}s
         * and those Elements must have the same id's as the elements in this
         * Path.
         *
         * @param l
         * @return
         */
        abstract <P extends Path> Path getCopy(LayoutImpl<T> l);

        /**
         * Overridden by subclasses to duplicate the current {@code Path}
         * @param s		the {@link Divider} which is the last point to be
         * 				copied along this Path starting at the beginning of
         * 				this Path.
         * @return		a new Path object which is a copy of this Path from it's
         * 				beginning and ending with the specified Divider.
         */
        abstract <P extends Path> Path copyBranch(Divider<T> s);

        /**
         * Overridden by Paths to add a new Node to this Path.
         *
         * @param node	the node to be added.
         */
        void add(Node<T> node) {
        	elems.add(node);
        }

        /**
         * Returns the count of dividers along this particular
         * path.
         *
         * @return	the current count of dividers.
         */
        int getDividerCount() {
        	int count = 0;
        	for(Element<T> e : elems) {
        		if(e.type == ElementType.DIVIDER) {
        			++ count;
        		}
        	}
            return count;
        }

        /**
         * Called locally only to manipulate Elements in the list
         * of Elements.
         * @return
         */
        List<Element<T>> getElements() {
            return elems;
        }

        /**
         * Public interface used for testing purposes. Returns
         * a copy of the current element list.
         *
         * @return	a copy of the current element list.
         */
        public List<Element<T>> getAllElements() {
        	return new ArrayList<Element<T>>(elems);
        }

        /**
         * Adds a divider to this {@code Path}
         *
         * @param divider		the current divider.
         */
        void add(Divider<T> divider) {
            //++ dividerCount;
            elems.add(divider);
        }

        /**
         * returns the number of elements in this {@code Path}
         * @return	the number of elements in this {@code Path}
         */
        int size() {
        	return elems.size();
        }

        /**
         * Returns a flag indicating whether a Node with the
         * specified id exists in this path.
         *
         * @param id
         * @return
         */

        boolean contains(String id) {
        	for(Element<T> e : elems) {
        		if(e.stringID.equals(id)) return true;
        	}
        	return false;
        }

        /**
         * Used for debugging to get the path start node.
         * @param nodeStringID
         * @return flag indicating whether this {@code Path} starts with
         * a Node with the specified string id.
         */
        boolean startsWith(String nodeStringID) {
        	return elems.get(0).stringID.equals(nodeStringID);
        }
    }

    /**
     * A specific instance of a Path object which only contains a horizontal
     * route from a left most Node to a right most Node.
     */
    class HorizontalPath extends Path implements PathVisitable<T> {
    	@Override
    	public <P extends Path> HorizontalPath getCopy(LayoutImpl<T> l) {
    		HorizontalPath newPath = new HorizontalPath();
    		//newPath.dividerCount = this.dividerCount;
    		for(Element<T> e : elems) {
    			switch(e.type) {
	    			case NODE: { newPath.elems.add(l.getNode(e.stringID)); break; }
	    			case DIVIDER: { newPath.elems.add(l.getDivider(e.stringID, ((Divider<T>)e).isVertical)); break; }
	    		}
    		}
    		return newPath;
    	}
    	@Override
        public <P extends Path> HorizontalPath copyBranch(Divider<T> s) {
            HorizontalPath p = new HorizontalPath();
            p.elems.addAll(this.elems.subList(0, this.elems.indexOf(s) + 1)); //Copy only up to divider
            //p.dividerCount = dividerCount;

            return p;
        }
        /**
         * Implementation of the {@link PathVisitable} interface
         *
         * @param lv	the visitor
         */
    	@Override
        public void accept(PathVisitor<T> lv) {
             lv.visit(this);
        }
    }

    /**
     * A specific instance of a Path object which only contains a vertical
     * route from a top most Node to a bottom most Node.
     */
    class VerticalPath extends Path implements PathVisitable<T> {
    	@Override
    	public <P extends Path> VerticalPath getCopy(LayoutImpl<T> l) {
    		VerticalPath newPath = new VerticalPath();
    		//newPath.dividerCount = this.dividerCount;
    		for(Element<T> e : elems) {
    			switch(e.type) {
	    			case NODE: { newPath.elems.add(l.getNode(e.stringID)); break; }
	    			case DIVIDER: { newPath.elems.add(l.getDivider(e.stringID, ((Divider<T>)e).isVertical)); break; }
	    		}
    		}
    		return newPath;
    	}
    	@Override
        public <P extends Path> VerticalPath copyBranch(Divider<T> s) {
            VerticalPath p = new VerticalPath();
            p.elems.addAll(this.elems.subList(0, this.elems.indexOf(s) + 1)); //Copy only up to divider
            //p.dividerCount = dividerCount;

            return p;
        }
    	/**
         * Implementation of the {@link PathVisitable} interface
         *
         * @param lv	the visitor
         */
        @Override
        public void accept(PathVisitor<T> lv) {
            lv.visit(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Test Convert-a-Card analysis."""

import json
from libcrowds_analyst.analysis import playbills

class TestPlaybillsMarkAnalysis(object):

    def test_overlap_ratio_100_with_equal_rects(self):
        """Test for an overlap ratio of 1."""
        rect = {'x': 100, 'y': 100, 'w': 100, 'h': 100}
        overlap = playbills.get_overlap_ratio(rect, rect)
        assert overlap == 1

    def test_overlap_ratio_0_with_adjacent_rects(self):
        """Test for an overlap ratio of 0."""
        r1 = {'x': 100, 'y': 100, 'w': 100, 'h': 100}
        r2 = {'x': 100, 'y': 201, 'w': 100, 'h': 100}
        overlap = playbills.get_overlap_ratio(r1, r2)
        assert overlap == 0

    def test_overlap_ratio_with_overlapping_rects(self):
        """Test form an overlap ratio of 0.5."""
        r1 = {'x': 100, 'y': 100, 'w': 100, 'h': 100}
        r2 = {'x': 150, 'y': 100, 'w': 100, 'h': 100}
        overlap = playbills.get_overlap_ratio(r1, r2)
        assert '{:.2f}'.format(overlap) == '0.33'

    def test_correct_result_analysed(self, mocker, project, result,
                                     processed_payload):
        """Test that the correct result is analysed."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        playbills.analyse_selections(**processed_payload)
        mock_enki.pbclient.find_results.assert_called_with(project.id, limit=1,
                                                           id=result.id, all=1)

    def test_empty_result_updated(self, create_task_run_df, mocker, result,
                                  processed_payload):
        """Test that an empty result is updated correctly."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        tr_info = [
            [],
            [],
        ]
        df = create_task_run_df(tr_info)
        mock_enki.pbclient.find_results.return_value = [result]
        mock_enki.Enki().task_runs_df.__getitem__.return_value = df
        playbills.analyse_selections(**processed_payload)
        mock_enki.pbclient.update_result.assert_called_with(result)
        assert result.info == {
            'annotations': [],
            'analysis_complete': True,
            'analysis_doi': '123/456',
            'analysis_path': '/example'
        }

    def test_equal_regions_combined(self, create_task_run_df, mocker,
                                    result, processed_payload,
                                    select_annotation):
        """Test that equal regions are combined."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        selection = {'x': 400, 'y': 200, 'w': 100, 'h': 100}
        tr_info = [
            [
                select_annotation(**selection),
                select_annotation(**selection)
            ]
        ]
        df = create_task_run_df(tr_info)
        mock_enki.pbclient.find_results.return_value = [result]
        mock_enki.Enki().task_runs_df.__getitem__.return_value = df
        playbills.analyse_selections(**processed_payload)
        mock_enki.pbclient.update_result.assert_called_with(result)
        expected = '?xywh=400,200,100,100'
        annotations = result.info['annotations']
        assert len(annotations) == 1
        assert annotations[0]['target']['selector']['value'] == expected

    def test_similar_regions_combined(self, create_task_run_df, mocker,
                                      result, processed_payload,
                                      select_annotation):
        """Test that regions with an intersection of >= 80% are combined."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        selection1 = {'x': 100, 'y': 100, 'w': 100, 'h': 100}
        selection2 = {'x': 110, 'y': 110, 'w': 90, 'h': 90}
        tr_info = [
            [
                select_annotation(**selection1),
                select_annotation(**selection2)
            ]
        ]
        df = create_task_run_df(tr_info)
        mock_enki.pbclient.find_results.return_value = [result]
        mock_enki.Enki().task_runs_df.__getitem__.return_value = df
        playbills.analyse_selections(**processed_payload)
        mock_enki.pbclient.update_result.assert_called_with(result)
        expected = '?xywh=100,100,100,100'
        annotations = result.info['annotations']
        assert len(annotations) == 1
        assert annotations[0]['target']['selector']['value'] == expected

    def test_rect_from_selection(self, select_annotation):
        """Test that we get the correct rect."""
        selection = {'x': 400, 'y': 200, 'w': 100, 'h': 100}
        anno = select_annotation(**selection)
        rect = playbills.get_rect_from_selection(anno)
        assert rect == selection

    def test_rect_from_selection_works_with_floats(self, select_annotation):
        """Test that we can use floats when converting rects."""
        selection = {'x': 400.123, 'y': 200.456, 'w': 100.789, 'h': 100.511}
        anno = select_annotation(**selection)
        rect = playbills.get_rect_from_selection(anno)
        assert rect == {'x': 400, 'y': 200, 'w': 101, 'h': 101}

    def test_all_selection_results_analysed(self, mocker, result, project,
                                            processed_payload):
        """Test that analysis of all selection results triggered correctly."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        mock_enki.Enki().project = project
        mock_analyse = mocker.patch(
            'libcrowds_analyst.analysis.playbills.analyse_selections'
        )
        mock_object_loader = mocker.patch(
            'libcrowds_analyst.analysis.playbills.object_loader'
        )
        mock_object_loader.load.return_value = [result]
        playbills.analyse_all_selections(**processed_payload)
        expected = processed_payload.copy()
        expected['result_id'] = processed_payload['result_id']
        expected['project_id'] = processed_payload['project_id']
        mock_analyse.assert_called_with(**expected)

    def test_mail_sent_when_all_selection_results_analysed(self, mocker,
                                                           processed_payload):
        """Test that analysis of all selection results triggered correctly."""
        mocker.patch('libcrowds_analyst.analysis.playbills.enki')
        mock_send_mail = mocker.patch(
            'libcrowds_analyst.analysis.playbills.helpers.send_mail'
        )
        playbills.analyse_all_selections(**processed_payload)
        assert mock_send_mail.called

    def test_select_result_initialised_properly(self, mocker,
                                                processed_payload):
        """Test that the result is initialised using the helper function."""
        mocker.patch('libcrowds_analyst.analysis.playbills.enki')
        mock_init_info = mocker.patch('libcrowds_analyst.analysis.playbills.'
                                      'helpers.init_result_info')
        playbills.analyse_selections(**processed_payload)
        assert mock_init_info.call_args[0][0] == processed_payload['doi']
        assert mock_init_info.call_args[0][1] == processed_payload['path']

    def test_select_analysis_throttled(self, mocker, processed_payload):
        """Test that the result is initialised using the helper function."""
        mocker.patch('libcrowds_analyst.analysis.playbills.enki')
        mock_sleep = mocker.patch(
          'libcrowds_analyst.analysis.playbills.time.sleep'
        )
        playbills.analyse_selections(**processed_payload)
        mock_sleep.assert_called_with(processed_payload['throttle'])

    def test_comments_accepted(self, mocker, processed_payload, result,
                               comment_annotation, create_task_run_df):
        """Test that comment annotations are handled properly."""
        mock_enki = mocker.patch(
            'libcrowds_analyst.analysis.playbills.enki'
        )
        comment = comment_annotation('Some comment')
        tr_info = [
            [
                comment
            ]
        ]
        df = create_task_run_df(tr_info)
        mock_enki.pbclient.find_results.return_value = [result]
        mock_enki.Enki().task_runs_df.__getitem__.return_value = df
        playbills.analyse_selections(**processed_payload)
        mock_enki.pbclient.update_result.assert_called_with(result)
        assert result.info['annotations'] == [comment]


text:
package com.oprisnik.semdroid.feature.instance.clazz;

import com.oprisnik.semdroid.app.DexClass;
import com.oprisnik.semdroid.utils.Log;

import at.tuflowgraphy.semantic.base.domain.data.InstanceDataElement;

/**
 * Class instance generator that creates links to all methods of the class and
 * the superclass if the package name starts with "android".
 */
public class MethodLinkAndSuperCIG extends MethodLinkCIG {

    private static final String TAG = "MethodLinkAndSuperCIG";

    @Override
    protected void getClassInstance(DexClass clazz, InstanceDataElement results) {
        super.getClassInstance(clazz, results);

        // Add first external super class if part of Android
        String superClass = clazz.getFirstExternalSuperClass();
        if (superClass.startsWith("Landroid")) {
            results.addValue(getSymbolicFeatureDataElement("extends",
                    superClass));
            Log.v(TAG, clazz.getClassName() + " extends " + superClass);
        }
    }

}


text:
echo "*** Installing goss ***"
curl -L https://github.com/aelsabbahy/goss/releases/download/v0.3.7/goss-linux-amd64 -o /usr/local/bin/goss
chmod +rx /usr/local/bin/goss

echo "*** Checking goss installation ***"
goss --version


text:
using System.Net.Mime;
using BForms.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

namespace BForms.Models
{
    /// <summary>
    /// Represents a list of items for Dropdown, ListBox, RadioList, CheckboxList binding
    /// </summary>
    public class BsSelectList<T>
    {
        private T selectedValues;

        /// <summary>
        /// Selected values
        /// </summary>
        public T SelectedValues
        {
            get
            {
                return selectedValues;
            }
            set
            {
                selectedValues = value;
            }
        }

        public static implicit operator T(BsSelectList<T> value)
        {
            return value.SelectedValues;
        }

        public static implicit operator BsSelectList<T>(T value)
        {
            return new BsSelectList<T> { SelectedValues = value };
        }

        public List<BsSelectListItem> Items { get; set; }

        public BsSelectList()
        {
            Items = new List<BsSelectListItem>();
        }

        /// <summary>
        /// Returns all select list items as IEnumerable
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SelectListItem> ToSelectList()
        {
            var list = new List<SelectListItem>();

            foreach (var item in Items)
            {
                list.Add(new SelectListItem
                         {
                             Selected = item.Selected,
                             Text = item.Text,
                             Value = item.Value
                         });
            }
            return list;
        }

        /// <summary>
        /// Filla BsSelectList.Items with enum vals
        /// </summary>
        public void ItemsFromEnum(Type myEnum, params Enum[] excludedVals)
        {
            var enumType = myEnum;
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("myEnum is not of type enum", "myEnum");
            }

            var excludedList = excludedVals.Select(val => ReflectionHelpers.EnumDisplayName(myEnum, val)).ToList();

            foreach (var item in Enum.GetValues(enumType))
            {
                //get Display Name from resources
                var textValue = ReflectionHelpers.EnumDisplayName(myEnum, item as Enum);

                if (excludedList.All(x => x != textValue))
                {
                    this.Items.Add(new BsSelectListItem
                    {
                        Selected = false,
                        Text = textValue,
                        Value = Convert.ChangeType(item, Enum.GetUnderlyingType(myEnum)).ToString()
                    });
                }
            }
        }

        /// <summary>
        /// Returns a BsSelectList from
        /// </summary>
        public static BsSelectList<T> FromSelectList(IEnumerable<SelectListItem> list)
        {
            var bsList = new BsSelectList<T>();
            foreach (var item in list)
            {
                bsList.Items.Add(new BsSelectListItem
                                 {
                                     Selected = item.Selected,
                                     Text = item.Text,
                                     Value = item.Value
                                 });
            }
            return bsList;
        }

        /// <summary>
        /// Returns a BsSelectList from enum using the DescriptionAttribute
        /// </summary>
        public static BsSelectList<T> FromEnum(Type myEnum)
        {
            var enumType = myEnum;
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("E is not of type enum", "myEnum");
            }

            var bsList = new BsSelectList<T>();
            foreach (var item in Enum.GetValues(enumType))
            {
                //get Display Name from resources
                var textValue = ReflectionHelpers.EnumDisplayName(myEnum, item as Enum);

                bsList.Items.Add(new BsSelectListItem
                                 {
                                     Selected = false,
                                     Text = textValue,
                                     Value = Convert.ChangeType(item, Enum.GetUnderlyingType(myEnum)).ToString()
                                 });
            }

            return bsList;
        }

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.cassandra.io.sstable.IndexSummary (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.io.sstable.IndexSummary

Packages that use IndexSummary

Package
Description

org.apache.cassandra.io.sstable

org.apache.cassandra.io.sstable.format

Uses of IndexSummary in org.apache.cassandra.io.sstable

Methods in org.apache.cassandra.io.sstable that return IndexSummary

Modifier and Type
Method and Description

IndexSummary
IndexSummaryBuilder.build(IPartitioner partitioner)

IndexSummary
IndexSummaryBuilder.build(IPartitioner partitioner,
     IndexSummaryBuilder.ReadableBoundary boundary)

IndexSummary
IndexSummary.IndexSummarySerializer.deserialize(java.io.DataInputStream in,
           IPartitioner partitioner,
           boolean haveSamplingLevel,
           int expectedMinIndexInterval,
           int maxIndexInterval)

static IndexSummary
IndexSummaryBuilder.downsample(IndexSummary existing,
          int newSamplingLevel,
          int minIndexInterval,
          IPartitioner partitioner)

Downsamples an existing index summary to a new sampling level.

IndexSummary
IndexSummary.sharedCopy()

Methods in org.apache.cassandra.io.sstable with parameters of type IndexSummary

Modifier and Type
Method and Description

static IndexSummary
IndexSummaryBuilder.downsample(IndexSummary existing,
          int newSamplingLevel,
          int minIndexInterval,
          IPartitioner partitioner)

Downsamples an existing index summary to a new sampling level.

void
IndexSummary.IndexSummarySerializer.serialize(IndexSummary t,
         DataOutputPlus out,
         boolean withSamplingLevel)

Uses of IndexSummary in org.apache.cassandra.io.sstable.format

Fields in org.apache.cassandra.io.sstable.format declared as IndexSummary

Modifier and Type
Field and Description

protected IndexSummary
SSTableReader.indexSummary

Methods in org.apache.cassandra.io.sstable.format with parameters of type IndexSummary

Modifier and Type
Method and Description

static long
SSTableReader.getIndexScanPositionFromBinarySearchResult(int binarySearchResult,
                                          IndexSummary referencedIndexSummary)

static SSTableReader
SSTableReader.<a href="../../../../../../org/apache/cassandra/io/sstable/format/SSTableReader.html#internalOpen-org.apache.cassandra.io.sstable.Descriptor-java.util.Set-org.apache.cassandra.config.CFMetaData-org.apache.cassandra.dht.IPartitioner-org.apache.cassandra.io.util.SegmentedFile-org.apache.cassandra.io.util.SegmentedFile-org.apache.cassandra.io.sstable.IndexSummary-org.apache.cassandra.utils.IFilter-long-org.apache.cassandra.io.sstable.metadata.StatsMetadata-org.apache.cassandra.io.sstable.format.SSTableReader.OpenReason-">internalOpen(Descriptor desc,
            java.util.Set<Component> components,
            CFMetaData metadata,
            IPartitioner partitioner,
            SegmentedFile ifile,
            SegmentedFile dfile,
            IndexSummary isummary,
            IFilter bf,
            long maxDataAge,
            StatsMetadata sstableMetadata,
            SSTableReader.OpenReason openReason)

Open a RowIndexedReader which already has its state initialized (by SSTableWriter).

static void
SSTableReader.saveSummary(Descriptor descriptor,
           DecoratedKey first,
           DecoratedKey last,
           SegmentedFile.Builder ibuilder,
           SegmentedFile.Builder dbuilder,
           IndexSummary summary)

Save index summary to Summary.db file.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
<?php

// **********************************************************************
// OA::API PHP API interface for OpenAustralia.org
// Version 1.0
// Author: Mark Kinkade <pagetribemail@gmail.com>
//
// This work has been adapted/extended from the great work done by:
// Ruben Arakelyan <ruben@wackomenace.co.uk>
// Copyright (C) 2008 Ruben Arakelyan. Some rights reserved.
//
// This file is licensed under the
// Creative Commons Attribution-ShareAlike license version 2.5
// available at http://creativecommons.org/licenses/by-sa/2.5/
//
// For more information, see http://tools.wackomenace.co.uk/twfyapi/
//
// Inspiration: WebService::TWFY::API by Spiros Denaxas
// Available at: http://search.cpan.org/~sden/WebService-TWFY-API-0.01/
// **********************************************************************

class OAAPI {

    // API key
    private $key;

    // cURL handle
    private $ch;

    // Default constructor
    public function __construct($key) {
        // Check and set API key
        if (!$key) {
            die('ERROR: No API key provided.');
        }
        if (!preg_match('/^[A-Za-z0-9]+$/', $key)) {
            die('ERROR: Invalid API key provided.');
        }
        $this->key = $key;

        // Create a new instance of cURL
        $this->ch = curl_init();

        // Set the user agent
        // It does not provide TheyWorkForYou.com with any personal information
        // but helps them track usage of this PHP class.
        curl_setopt($this->ch, CURLOPT_USERAGENT, 'OA::API PHP class');

        // Return the result
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    }

    // Default destructor
    public function __destruct() {
        // Delete the instance of cURL
        curl_close($this->ch);
    }

    // Send an API query
    public function query($func, $args = array()) {
        // Exit if any arguments are not defined
        if (!isset($func) || $func == '' || !isset($args) || $args == '' || !is_array($args)) {
            die('ERROR: Function name or arguments not provided.');
        }

        // Construct the query
        $query = new OAAPI_Request($func, $args, $this->key);

        // Execute the query
        if (is_object($query)) {
            return $this->_execute_query($query);
        }
        else {
            die('ERROR: Could not assemble request using OAAPI_Request.');
        }
    }

    // Execute an API query
    private function _execute_query($query) {
        // Make the final URL
        $URL = $query->encode_arguments();

        // Set the URL
        curl_setopt($this->ch, CURLOPT_URL, $URL);

        // Get the result
        $result = curl_exec($this->ch);

        // Find out if all is OK
        if (!$result) {
            die('ERROR: cURL error occurred: ' . curl_error($this->ch));
        }
        else {
            return $result;
        }
    }

}

class OAAPI_Request {

    // API URL
    private $URL = 'https://www.openaustralia.org.au/api/';

    // Chosen function, arguments and API key
    private $func;
    private $args;

    // Default constructor
    public function __construct($func, $args, $key) {
        // Set function, arguments and API key
        $this->func = $func;
        $this->args = $args;
        $this->key = $key;

        // Get and set the URL
        $this->URL = $this->_get_uri_for_function($this->func);

        // Check to see if valid URL has been set
        if (!isset($this->URL) || $this->URL == '') {
            die('ERROR: Invalid function: ' . $this->func . '. Please look at the documentation for supported functions.');
        }
    }

    // Encode function arguments into a URL query string
    public function encode_arguments() {
        // Validate the output argument if it exists
        if (array_key_exists('output', $this->args)) {
            if (!$this->_validate_output_argument($this->args['output'])) {
                return '';
            }
        }

        // Make sure all mandatory arguments for a particular function are present
        if (!$this->_validate_arguments($this->func, $this->args)) {
            return '';
        }

        // Assemble the URL
        $full_url = $this->URL . '?key=' . $this->key . '&';
        foreach ($this->args as $name => $value) {
            $full_url .= $name . '=' . $value . '&';
        }
        $full_url = substr($full_url, 0, -1);

        return $full_url;
    }

    // Get the URL for a particular function
    private function _get_uri_for_function($func) {
        // Exit if any arguments are not defined
        if (!isset($func) || $func == '') {
            return '';
        }

        // Define valid functions
        $valid_functions = array(
            'convertURL'        => 'Converts a parliament.uk URL into a TheyWorkForYou one, if possible',
            'getDivisions'    => 'Returns list of electoral divisions',
            'getRepresentative'  => 'Returns main details for a member of the House of Representatives',
            'getRepresentatives' => 'Returns main details for a member of the House of Representatives',
            'getSenator' => 'Returns details for a Senator',
            'getSenators' => 'Returns list of Senators',
            'getDebates' => 'Returns Debates (either House of Representatives or Senate)',
            'getHansard' => 'Returns any of the above',
            'getComments' => 'Returns comments',
        );

        // If the function exists, return its URL
        if (array_key_exists($func, $valid_functions)) {
            return $this->URL . $func;
        }
        else {
            return '';
        }
    }

    // Validate the "output" argument
    private function _validate_output_argument($output) {
        // Exit if any arguments are not defined
        if (!isset($output) || $output == '') {
            return false;
        }

        // Define valid output types
        $valid_params = array(
          'xml'  => 'XML output',
          'php'  => 'Serialized PHP',
          'js'   => 'a JavaScript object',
          'rabx' => 'RPC over Anything But XML',
        );

        // Check to see if the output type provided is valid
        if (array_key_exists($output, $valid_params)) {
            return true;
        }
        else {
            die('ERROR: Invalid output type: ' . $output . '. Please look at the documentation for supported output types.');
        }
    }

    // Validate arguments
    private function _validate_arguments($func, $args) {
        // Define manadatory arguments. Value in array represents mandatory variables
        $functions_params = array(
            'convertURL' => array( 'url' ),
            'getDivisions' => array(),
            'getRepresentative'  => array(),
            'getRepresentatives' => array(),
            'getSenator' => array(),
            'getSenators' => array(),
            'getDebates' => array('type'),
            'getHansard' => array(),
            'getComments' => array(),
        );

        // Check to see if all mandatory arguments are present
        $required_params = $functions_params[$func];
        foreach ($required_params as $param) {
            if (!isset($args[$param])) {
                die('ERROR: All manadatory arguments for ' . $func . ' not provided.');
            }
        }

        return true;
    }

}

?>


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_pi4j_wiringpi_SoftPwm */

#ifndef _Included_com_pi4j_wiringpi_SoftPwm
#define _Included_com_pi4j_wiringpi_SoftPwm
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_pi4j_wiringpi_SoftPwm
 * Method:    softPwmCreate
 * Signature: (III)I
 */
JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_SoftPwm_softPwmCreate
  (JNIEnv *, jclass, jint, jint, jint);

/*
 * Class:     com_pi4j_wiringpi_SoftPwm
 * Method:    softPwmWrite
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_com_pi4j_wiringpi_SoftPwm_softPwmWrite
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif


text:
using System;

namespace Consolas.Core
{
    public class ArgumentLL2Parser
    {
        private Queue<string> _queue;
        private ArgumentSet _arguments;

        public ArgumentSet Parse(string[] args, ArgumentSet arguments)
        {
            if (args == null || args.Length == 0)
            {
                return arguments;
            }

            _queue = new Lexer().Tokenize(args);
            _arguments = arguments;

            Args();

            return _arguments;
        }

        private void Args()
        {
            if (Arg())
            do WhiteSpace();
            while (Arg());
        }

        private bool Arg()
        {
            if (Prefix) Statement();
            else Value(isDefault: true);
            return End();
        }

        private void WhiteSpace()
        {
            if (Tokens.WhiteSpace.IsMatch(Peek()))
            {
                Dequeue();
            }
        }

        private bool Prefix
        {
            get
            {
                if (Tokens.Prefix.IsMatch(Peek()))
                {
                    Dequeue();
                    return true;
                }
                return false;
            }
        }

        private bool Statement()
        {
            return
                ValueStatement()
             || BooleanStatement()
             || Error("statement");
        }

        private bool ValueStatement()
        {
            return
                AssignmentStatement()
             || PropertyStatement();
        }

        private bool BooleanStatement()
        {
            var booleanStatement = Tokens.BooleanStatement.Match(Peek());

            if (booleanStatement.Success)
            {
                Dequeue();

                var name = booleanStatement.Groups["name"]?.Value;
                var @operator = booleanStatement.Groups["operator"]?.Value;

                if (!string.IsNullOrEmpty(@operator))
                {
                    _queue.DeDequeue(@operator);
                }

                return BooleanArgument(name);
            }

            return false;
        }

        private bool AssignmentStatement()
        {
            var assignmentStatement = Tokens.AssigmentStatement.Match(Peek());

            if (assignmentStatement.Success)
            {
                Dequeue();

                var name = assignmentStatement.Groups["name"]?.Value;
                var op = assignmentStatement.Groups["operator"]?.Value;
                var value = assignmentStatement.Groups["value"]?.Value;

                if (!string.IsNullOrEmpty(value))
                {
                    _queue.DeDequeue(value);
                }
                _queue.DeDequeue(op);

                return ValueArgument(name);
            }
            return false;
        }

        private bool PropertyStatement()
        {
            var name = Peek();
            if (Tokens.Name.IsMatch(name))
            {
                Dequeue();

                if (Tokens.WhiteSpace.IsMatch(Peek()))
                {
                    return ValueArgument(name);
                }

                _queue.DeDequeue(name);
            }
            return false;
        }

        private void Value(string name = null, string val = null,
            bool isDefault = false)
        {
            var value = val ?? GetValue();
            _arguments.Add(name ?? value, new Argument
            {
                IsMatch = true,
                Value = value,
                IsDefault = isDefault
            });
        }

        private string GetValue()
        {
            var value = Peek();
            if (IsValue(value))
            {
                return Dequeue();
            }
            throw Error(value, "value");
        }

        private static bool IsValue(string value)
        {
            return Tokens.Value.IsMatch(value);
        }

        private bool ValueArgument(string name)
        {
            return
                AssingmentWithoutOperator(name)
             || AssinmentWithOperator(name);
        }

        private bool AssingmentWithoutOperator(string name)
        {
            var @operator = Peek();

            if (Tokens.WhiteSpace.IsMatch(@operator))
            {
                Operator();

                if (!IsValue(Peek()))
                {
                    _queue.DeDequeue(@operator);
                    _queue.DeDequeue(name);
                    return false;
                }
                Value(name: name);

                return true;
            }

            return false;
        }

        private bool AssinmentWithOperator(string name)
        {
            var @operator = Peek();

            if (Tokens.AssignmentOperator.IsMatch(@operator))
            {
                Operator();

                if (IsValue(Peek()))
                {
                    Value(name: name);
                }
                else
                {
                    Value(name: name, val: "");
                }
                return true;
            }

            return false;
        }

        private bool BooleanArgument(string name)
        {
            var value = true.ToString();

            var boolOperator = Peek();
            if (Tokens.BoolOperator.IsMatch(boolOperator))
            {
                boolOperator = Dequeue();
                boolOperator = (boolOperator == "+").ToString();
                value = boolOperator;
            }

            _arguments.Add(name, new Argument
            {
                Value = value,
                IsMatch = true
            });

            return true;
        }

        private void Operator()
        {
            Dequeue();
        }

        private bool Error(string name)
        {
            throw Error(Peek(), name);
        }

        private Exception Error(string token, string name)
        {
            return new Exception(string.Format("Couldn't parse '{0}' as {1}", token, name));
        }

        private bool End()
        {
            return _queue.Count > 0;
        }

        private string Dequeue()
        {
            return _queue.Dequeue();
        }

        private string Peek()
        {
            return _queue.Count > 0
                ? _queue.Peek()
                : "";
        }
    }
}


text:
require(['aplazame'], function (aplazame) {

  aplazame.init({
    sandbox: true,
    publicKey: document.body.getAttribute('data-public-key')
  });

  console.log('demo-article-require', arguments);

  aplazame._.ready(function () {

    function amount2string (amount) {
      var cents = amount%100;
      return parseInt(amount/100) + '.' + ( cents < 10 ? '0' : '' ) + cents;
    }

    function toEUR (amount) {
      if( amount < 0 ) {
        return '-' + toEUR(-amount);
      }
      return amount2string(amount) + '€';
    }

    var choices = document.querySelectorAll('.article-type-choices .article-type input');

    // console.log('price', price);

    [].forEach.call(choices, function (choice) {
      choice.addEventListener('change', function (_e) {
        var price = document.querySelector('[itemprop="price"]'),
            factor = Number( price.getAttribute('data-price-' + this.value) ) || 1;

        price.textContent = toEUR( ( price ? Number( price.getAttribute('content') ) : 0 ) * factor );

        // console.log('change', this, e, this.value, factor, toEUR( priceCents * factor ) );

      });
    });

    var qtyCtrl = document.querySelector('.qty-ctrl'),
        qtyInput = qtyCtrl.querySelector('input'),
        qtyMinus = qtyCtrl.querySelector('button.minus'),
        qtyPlus = qtyCtrl.querySelector('button.plus');

    qtyMinus.setAttribute('disabled', 'disabled');

    qtyMinus.addEventListener('click', function () {
      var newValue = Number(qtyInput.value) - 1;

      if( newValue < 1 ) {
        newValue = 1;
      }

      qtyInput.value = '' + newValue;

      if( newValue === 1 ) {
        qtyMinus.setAttribute('disabled', 'disabled');
      }
    });

    qtyPlus.addEventListener('click', function () {
      qtyInput.value = '' + ( Number(qtyInput.value) + 1 );
      qtyMinus.removeAttribute('disabled');
    });

    // checkout launching

    var params = {
      'checkout-json': 'checkout-ES.json'
    };

    if( location.search ) {
      location.search.replace(/^\?/, '').split('&').forEach(function (part) {
        var param = part.match(/(.*?)=(.*)/);
        if( param ) {
          params[param[1].trim()] = param[2].trim();
        }
      });
    }

    function jsonGet (url, onSuccess, onError) {
      var request = new XMLHttpRequest();

      request.onreadystatechange = function() {
        if(request.readyState === 4) {
          if(request.status === 200) {
            if( onSuccess ) onSuccess(JSON.parse(request.responseText));
          } else {
            if( onError ) onError(request);
          }
        }
      };

      request.open('GET', url, true);
      request.send();
    }

    // console.log('params', location.search.replace(/^\?/, '').split('&')[0].match(/(.*?)\=(.*)/) );

    //     checkoutData = http(params['checkout-json']);

    function randOrderId (_timeout) {
      return 'test-' + new Date().getTime();
    }

    var matchOrderId = ( location.hash || '' ).match(/^#\/order\/([^&]*)/),
        orderId = matchOrderId && matchOrderId[1];

    if( orderId === 'random' ) {
      orderId = randOrderId();
    }

    window.loadCheckout = function () {

      jsonGet(params['checkout-json'], function (data) {
        if( typeof data === 'string' ) {
          try {
            data = JSON.parse(data);
          } catch(err) {
            console.error('received json is not valid');
          }
        }

        if( !orderId ) {
          orderId = randOrderId();
          location.hash = '/order/' + orderId;
        }

        data.order.id = orderId;

        // data.merchant.onError = function () {
        //   console.log('whoops!!');
        // };
        //
        // data.merchant.onSuccess = function () {
        //   console.log('gogogo!!');
        // };
        //
        // data.merchant.onDismiss = function () {
        //   console.log('try again!!');
        // };

        aplazame.checkout(data, {
          onStatusChange: function (status) {
            console.log('onStatusChange', status);
          },
          onClose: function (result_status) {
            console.log('onClose', result_status);
          },
        });
      });

    };

  });

});


text:
const BrowserStack = require('browserstack-local');
const http = require('http');
const handler = require('serve-handler');

const PORT = 3000;
const bslArgs = { force: true, logFile: 'test/browser/browserstack.log' };

exports.mochaGlobalSetup = async function () {
  this.server = http.createServer((req, res) => handler(req, res));
  this.server.listen(PORT);

  console.log('\nStarting BrowserStack Local...');
  this.bsl = new BrowserStack.Local();
  await new Promise((resolve, reject) => {
    this.bsl.start(bslArgs, error => {
      if (error) {
        if (error.name === 'LocalError') {
          console.info(`Skipping BrowserStack Local start: ${error.message}`);
          resolve();
        } else reject(error);
      } else resolve();
    });
  });
  console.log('Starting browser tests...');
};

exports.mochaGlobalTeardown = async function () {
  this.server.close();

  await new Promise(resolve => {
    if (this.bsl && this.bsl.isRunning()) {
      console.log('\nStopping BrowserStack Local...');
      this.bsl.stop(resolve);
    } else resolve();
  });
};


text:
FactoryBot.define do
  factory :eve_type_dogma_effect, class: "Eve::TypeDogmaEffect" do
    association :type, factory: :eve_type

    sequence(:effect_id)

    is_default { [true, false].sample }
  end
end


text:
import React, { Component, PropTypes } from 'react';
import * as SurveyJSEditor from 'surveyjs-editor';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { notification } from 'antd';
import client from '../api/client';
import { actions } from '../reducers/surveys/actions';
import 'surveyjs-editor/surveyeditor.css';
import 'bootstrap/dist/css/bootstrap.css';

class SurveyEditorPage extends Component {
  constructor(props) {
    super(props);
    this.editor = null;
  }

  componentDidMount = () => {
    if(location.pathname.indexOf('survey-org-editor') > -1) {
      this.props.actions.loadSurveyOrgModel();
    } else {
      this.props.actions.loadSurveyModel();
    }
    this.editor = new SurveyJSEditor.SurveyEditor('surveyEditorContainer', {});
    this.editor.saveSurveyFunc = this.submitSurveyModel;
  }

  submitSurveyModel = () => {
    let model;
    eval(`model = ${this.editor.text}`);
    console.log(model);
    if (location.pathname.indexOf('survey-org-editor') > -1) {
      client.saveSurveyOrgModel(model).then(() => {
        notification.success({title: 'Survey Org created correctly...'});
      });
    } else {
      client.saveSurveyModel(model).then(() => {
        notification.success({title: 'Survey created correctly...'});
      });
    }
  }

  render = () => {
    const orgModel = location.pathname.indexOf('survey-org-editor') > -1;
    let survey = this.props.survey;
    if (orgModel) {
      survey = this.props.surveyOrgModel;
    }

    if (this.editor) {
      console.log('Render Survey: ', survey);
      this.editor.changeText(JSON.stringify(survey), true);
    }

    return <div id="surveyEditorContainer" />;
  }

}

SurveyEditorPage.propTypes = {
  survey: PropTypes.object,
  surveyOrgModel: PropTypes.object,
  location: PropTypes.shape({
    pathname: PropTypes.string
  })
};

const mapStateToProps = (state) => ({
  survey: state.survey,
  surveyOrgModel: state.surveyOrgModel
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(actions, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(SurveyEditorPage);


text:
#import "DVTAnnotationProvider.h"

#import "DVTMessageBubbleAnnotationDelegate-Protocol.h"

@class IDEAnnotationContext;

@interface IDEIssueAnnotationProvider : DVTAnnotationProvider <DVTMessageBubbleAnnotationDelegate>
{
    IDEAnnotationContext *_context;
    id <DVTObservingToken> _fileIssueObservingToken;
}

+ (id)annotationProviderForContext:(id)arg1 error:(id *)arg2;
- (void)_rebuildAnnotations;
- (void)_revealInIssueNavigator:(id)arg1;
@property IDEAnnotationContext *context; // @synthesize context=_context;
- (id)contextMenuItemsForAnnotation:(id)arg1 inTextSidebarView:(id)arg2;
- (void)didClickAnnotation:(id)arg1 inTextSidebarView:(id)arg2 event:(id)arg3;
- (void)didClickMessageBubbleForAnnotation:(id)arg1 onIcon:(BOOL)arg2 inTextView:(id)arg3 event:(id)arg4;
- (void)didDeleteOrReplaceParagraphForAnnotation:(id)arg1;
- (id)init;
- (id)initWithContext:(id)arg1;
- (BOOL)shouldMoveCursorForAnnotation:(id)arg1;
- (double)sidebarMarkerOpacityForAnnotation:(id)arg1;

@end


text:
<?php

namespace Amadeus\Client\Struct\Fare\MasterPricer;

/**
 * DateTimeDetails
 *
 * @package Amadeus\Client\Struct\Fare\MasterPricer
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class DateTimeDetails
{
    /**
     * @var int|string
     */
    public $date;

    /**
     * @var int|string
     */
    public $otherDate;

    /**
     * DateTimeDetails constructor.
     *
     * @param int|string $date
     */
    public function __construct($date)
    {
        $this->date = $date;
    }
}


text:
function Currency(currency){
    this.currency = currency;

    this.toNumber = function(text){
        if(this.isNumeric(text))
            return parseFloat(text);

        //converting to a string if a number as passed
        text = text + " ";

        //Removing symbol in unicode format (i.e. ᅜ)
        text = text.replace(/&.*?;/, "", text);

        //Removing all non-numeric characters
        var clean_number = "";
        var is_negative = false;
        for(var i=0; i<text.length; i++){
            var digit = text.substr(i,1);
            if( (parseInt(digit) >= 0 && parseInt(digit) <= 9) || digit == "," || digit == "." )
                clean_number += digit;
            else if(digit == '-')
                is_negative = true;
        }

        //Removing thousand separators but keeping decimal point
        var float_number = "";
        var decimal_separator = this.currency && this.currency["decimal_separator"] ? this.currency["decimal_separator"] : ".";

        for(var i=0; i<clean_number.length; i++)
        {
            var char = clean_number.substr(i,1);
            if (char >= '0' && char <= '9')
                float_number += char;
            else if(char == decimal_separator){
                float_number += ".";
            }
        }

        if(is_negative)
            float_number = "-" + float_number;

        return this.isNumeric(float_number) ? parseFloat(float_number) : false;
    };

    this.toMoney = function(number){
        if(!this.isNumeric(number))
            number = this.toNumber(number);

        if(number === false)
            return "";

        number = number + "";
        negative = "";
        if(number[0] == "-"){
            negative = "-";
            number = parseFloat(number.substr(1));
        }
        money = this.numberFormat(number, this.currency["decimals"], this.currency["decimal_separator"], this.currency["thousand_separator"]);

        var symbol_left = this.currency["symbol_left"] ? this.currency["symbol_left"] + this.currency["symbol_padding"] : "";
        var symbol_right = this.currency["symbol_right"] ? this.currency["symbol_padding"] + this.currency["symbol_right"] : "";
        money =  negative + this.htmlDecode(symbol_left) + money + this.htmlDecode(symbol_right);
        return money;
    };

    this.numberFormat = function(number, decimals, dec_point, thousands_sep){
        number = (number+'').replace(',', '').replace(' ', '');
        var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',

        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };

        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }

        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }

        return s.join(dec);
    }

    this.isNumeric = function(number){
        return !isNaN(parseFloat(number)) && isFinite(number);
    };

    this.htmlDecode = function(text) {
        var c,m,d = text;

        // look for numerical entities "
        var arr=d.match(/&#[0-9]{1,5};/g);

        // if no matches found in string then skip
        if(arr!=null){
            for(var x=0;x<arr.length;x++){
                m = arr[x];
                c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
                // if its a valid number we can decode
                if(c >= -32768 && c <= 65535){
                    // decode every single match within string
                    d = d.replace(m, String.fromCharCode(c));
                }else{
                    d = d.replace(m, ""); //invalid so replace with nada
                }
            }
        }
        return d;
    };
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="description" content="">
	<meta name="author" content="">

	<title>SIMPLEX Cumulative Report JHU</title>

	<link href="css/bootstrap.min.css" rel="stylesheet">

	<link rel="stylesheet" href="font-awesome/css/font-awesome.css">

	<link href="css/main.css" rel="stylesheet">

	<link rel="shortcut icon" href="ocp_main3.ico">

	<link rel="stylesheet" href="../../fonts/gentona/gentona.css">
	<link rel="stylesheet" href="../../fonts/titling-gothic/titling-gothic.css">
	<link rel="stylesheet" href="../../fonts/quadon/quadon.css">
	<link rel="stylesheet" href="../../fonts/arnhem/arnhem.css">

# SIMPLEX Phase I Report

| Title | Value |
| :--- | :--- |
| Tile of Effort | From RAGs to Riches |
| Contract Numbers | N66001-15-C-4041 |
| Reporting Period | May 2015 - July 2016 |
| PI Name | Joshua T. Vogelstein |

# Table of Contents

For SIMPLEX, we have four tasks, as listed below (see links for detailed reports)

1. [*Computer science*](./cs.html):
    1. Store
    2. Explore
    3. Parse
    4. Analyze

2. [*Statistical science*](./stats.html):
    1. Time-series
    2. Graphs
    3. Shapes
    4. Matrices

2. [*Datafication*](./datafication.html)
    1. Electron Microscopy
    1. Light Microscopy
    2. X-Ray Microscopy
    2. Magnetic Resonance

4. [*Discovery*](./discovery.html)
    1. Optimal Pipelines
    2. Extensible Neurocartography
    3. Syanpse Spatial Point Processes
    4. Synapse Types
    5. CLARITY Registration and Classification
	  6. MR Batch Effects

A summary slide highlighting several key results is available as [pdf](../../figs/Phase1_slide.pdf), [powerpoint](../../figs/Phase1_slide.pptx), and [keynote](../../figs/Phase1_slide.key).

---

# SIMPLEX Enabled Publications, Conference Presentations, & Code

## Publications

1. Kutten KS, et al. [Deformably Registering and Annotating Whole CLARITY Brains to an Atlas via Masked LDDMM](https://github.com/neurodata/spiePhotonics/raw/master/spiePhotonics.pdf). SPIE Photonics. Volume 9896.

1. Zheng, Da, et al. [An SSD-based eigensolver for spectral analysis on
billion-node graphs](http://arxiv.org/abs/1602.01421), arXiv:1602.01421, 2016.

1. Zheng, Da, et al. [Semi-External Memory Sparse Matrix Multiplication
on Billion-node Graphs in a Multicore Architecture](http://arxiv.org/abs/1602.02864), arXiv:1602.02864, 2016.

## Pre-Prints

1. E. Dyer, et al. [Quantifying mesoscale neuroanatomy using X-ray microtomography](http://arxiv.org/abs/1604.03629). 2016.

1. T. Tomia, et al. [Randomer Forests](http://arxiv.org/abs/1506.03410). arXiv, 2016.

1. D. Zheng, et al. [FlashMatrix: Parallel, Scalable Data Analysis with Generalized Matrix Operations using Commodity SSDs](http://arxiv.org/abs/1604.06414v1). arXiv, 1604.06414, 2016.

1. D. Mhembere, et al. [NUMA-optimized in-memory and semi-external-memory parameterized clustering](../../figs/kmeans.pdf). 2016.

1. K. Lillaney, et al. [NDBlaze: Sequentializing random writes to a spatial database](../../figs/ndblaze2016.pdf). 2016.

1. K. Levin and V. Lyzinski. [Laplacian eigenmaps from sparse, noisy similarity measurements](http://arxiv.org/abs/1603.03972). arXiv, 1603.03972, 2016.

1. V. Lyzinski, et al. [On the consistency of the likelihood maximization vertex nomination scheme: bridging the gap between maximum likelihood estimation and graph matching](http://arxiv.org/abs/1607.01369). arXiv, 1607.01369, 2016.

## Presentations
1. [Vertex Nomination via Local Neighborhood Matching](../../figs/JSM2016-VNLNM.pdf), JSM 2016.

1. [Asymptotic Relative Efficiency for Robust Estimation of the Mean of Contaminated Graphs under a Low Rank Model](../../figs/JSM2016-RobustLLG.pdf), JSM 2016

1. NeuroData: Enabling Terascale Neuroscience for Everyone, Keystone Symposia: State of the Brain, 2016.

1. [FlashR: Enable Parallel, Scalable Data Analysis in R](https://zheng-da.github.io/FlashR-intro/#1), useR!, 2016.

1. [Spectral clustering for billion-node graphs](../../figs/NS16.pdf), SIAM NS, 2016.

1. From RAGs to Riches: Utilizing Richly Attributed Graphs to Reason from Heterogeneous Data: Part 1. DARPA SIMPLEX PI Meeting, 2015.

1. Special Symposium: Neuroscience in the 21st Century, Kavli, 2015.

1.  Open Connectome Project: Lowering the Barrier to Entry of Big Data Neuroscience, Institute for Computational Medicine at Johns Hopkins University, 2015.

1. [Discovery of Brainwide Neural-Behavioral Maps via Multiscale Unsupervised Structure Learning](../../figs/NIH-talk.key). NIH, 2015.

1. Law of Large Graphs, DARPA Graphs, 2015.

1. From RAGs to Riches: Utilizing Richly Attributed Graphs to Reason from Heterogeneous Data, SIMPLEX Kickoff, 2015.

1. Opportunities and Challenges in Big Data Neuroscience, DoE, 2015.

## Conference Posters

1. G. Kiar, et al. GruteDB: An optimized open-source distributed DTI pipeline estimates brain graphs from > 5,000 publicly-available scans enabling mega-analysis. In OHBM, 2016.

1. H. Patsolic, et al. [Vertex nomination via local neighborhood seeded graph matching](../../figs/SIAM-NS16-VNSGM.pdf).  In SIAM Workshop on Network Science, 2016

1. J. T. Vogelstein. NeuroData: Enabling Terascale Neuroscience for Everyone. In Janelia: High-Resolution Circuit Reconstruction, 2016.

1. G. Kiar, et al. C4: Community Connectomics via Cloud Computing. In OHBM, 2015.

1. S. Chen, et al. High Dimensional State Space Model with L-1 and L-2 Penalties. In ENAR 2015.

designed by us.   © neurodata.io  2016


text:
@interface AIMOnAirXMLParser ()<NSXMLParserDelegate>
@property (nonatomic, strong) NSXMLParser *parser;
@property (nonatomic, strong) dispatch_queue_t dispatchQueue;
@property (nonatomic, strong) AIMOnAirDocument *parsedDocument;

@property (nonatomic, strong) NSMutableArray *epgItems;
@property (nonatomic, strong) NSMutableArray *playoutitems;
@property (nonatomic, strong) NSMutableArray *customFields;
@property (nonatomic, strong) NSMutableDictionary *item;
@end

@implementation AIMOnAirXMLParser
@synthesize delegate;

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dispatchQueue = dispatch_queue_create("com.thisisaim.xmlParser", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (instancetype)initWithFile:(NSString *)fileName
{
    if (!fileName || fileName.length == 0) {
        return nil;
    }
    self = [self init];
    if (self) {
        self.parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName]];
        if (!self.parser) {
            return nil;
        }
    }
    return self;
}

- (instancetype)initWithRawString:(NSString *)rawString
{
    if (!rawString || rawString.length == 0) {
        return nil;
    }
    self = [self initWithData:[rawString dataUsingEncoding:NSUTF8StringEncoding]];
    if (self) {

    }
    return self;
}

- (instancetype)initWithData:(NSData *)data
{
    if (!data || data.length == 0) {
        return nil;
    }
    self = [self init];
    if (self) {
        self.parser = [[NSXMLParser alloc] initWithData:data];
        if (!self.parser) {
            return nil;
        }
    }
    return self;
}

- (void) parse{

    self.parsedDocument = nil;
    self.parser.delegate = self;

    dispatch_async(self.dispatchQueue, ^{

        BOOL parsed = [self.parser parse];

        if (parsed) {

            if (self.delegate !=nil) {

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.delegate parser:self didFinishParsingWithObject:self.parsedDocument];
                });
            }
        }else{

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.delegate parser:self didFailWithError:self.parser.parserError];
            });

        }
    });

}

- (void) clearAll{

    [self.epgItems removeAllObjects];
    self.epgItems = nil;

    [self.playoutitems removeAllObjects];
    self.playoutitems = nil;

    [self.item removeAllObjects];
    self.item = nil;

    [self.customFields removeAllObjects];
    self.customFields = nil;
}

#pragma mark -
#pragma mark NSXMLParserDelegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{
    if ([elementName isEqualToString:@"onAir"]) {
        [self clearAll];
    }else if ([elementName isEqualToString:@"epgData"]) {
        self.epgItems = [[NSMutableArray alloc] initWithCapacity:100];
    }else if ([elementName isEqualToString:@"playoutData"]){
        self.playoutitems = [[NSMutableArray alloc] initWithCapacity:100];
    }else if ([elementName isEqualToString:@"customFields"]){
        self.customFields = [[NSMutableArray alloc] initWithCapacity:5];
    }else if ([elementName isEqualToString:@"epgItem"] || [elementName isEqualToString:@"playoutItem"]){
        self.item = [[NSMutableDictionary alloc] initWithDictionary:attributeDict];
    }else if ([elementName isEqualToString:@"customField"]){
        [self.customFields addObject:attributeDict];
    }
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{

}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
    if ([elementName isEqualToString:@"onAir"]) {
        self.parsedDocument = [[AIMOnAirDocument alloc] initWithEPGItems:self.epgItems andPlayoutItems:self.playoutitems];
    }else if ([elementName isEqualToString:@"epgData"]) {

    }else if ([elementName isEqualToString:@"playoutData"]){

    }else if ([elementName isEqualToString:@"customFields"]){
        [self.item setObject:self.customFields forKey:@"customFields"];
        self.customFields = nil;
    }else if ([elementName isEqualToString:@"epgItem"]){
        [self.epgItems addObject:[[AIMEPGItem alloc] initWithDictionary:self.item]];
    }else if([elementName isEqualToString:@"playoutItem"]){
        [self.playoutitems addObject:[[AIMPlayoutItem alloc] initWithDictionary:self.item]];
    }else if ([elementName isEqualToString:@"customField"]){

    }
}

- (void)dealloc
{
    [self clearAll];
}
@end


text:
namespace viz {

GLOutputSurface::GLOutputSurface(
    scoped_refptr<VizProcessContextProvider> context_provider,
    gpu::SurfaceHandle surface_handle)
    : OutputSurface(context_provider),
      viz_context_provider_(context_provider),
      surface_handle_(surface_handle),
      use_gpu_fence_(
          context_provider->ContextCapabilities().chromium_gpu_fence &&
          context_provider->ContextCapabilities()
              .use_gpu_fences_for_overlay_planes) {
  const auto& context_capabilities = context_provider->ContextCapabilities();
  capabilities_.output_surface_origin = context_capabilities.surface_origin;
  capabilities_.supports_stencil = context_capabilities.num_stencil_bits > 0;
  // Since one of the buffers is used by the surface for presentation, there can
  // be at most |num_surface_buffers - 1| pending buffers that the compositor
  // can use.
  capabilities_.max_frames_pending =
      context_capabilities.num_surface_buffers - 1;
  capabilities_.supports_gpu_vsync = context_capabilities.gpu_vsync;
  capabilities_.supports_dc_layers = context_capabilities.dc_layers;
  capabilities_.supports_surfaceless = context_capabilities.surfaceless;
  capabilities_.android_surface_control_feature_enabled =
      context_provider->GetGpuFeatureInfo()
          .status_values[gpu::GPU_FEATURE_TYPE_ANDROID_SURFACE_CONTROL] ==
      gpu::kGpuFeatureStatusEnabled;
}

GLOutputSurface::~GLOutputSurface() {
  viz_context_provider_->SetUpdateVSyncParametersCallback(
      UpdateVSyncParametersCallback());
  viz_context_provider_->SetGpuVSyncCallback(GpuVSyncCallback());
  if (gpu_fence_id_ > 0)
    context_provider()->ContextGL()->DestroyGpuFenceCHROMIUM(gpu_fence_id_);
}

void GLOutputSurface::BindToClient(OutputSurfaceClient* client) {
  DCHECK(client);
  DCHECK(!client_);
  client_ = client;
}

void GLOutputSurface::EnsureBackbuffer() {}

void GLOutputSurface::DiscardBackbuffer() {
  context_provider()->ContextGL()->DiscardBackbufferCHROMIUM();
}

void GLOutputSurface::BindFramebuffer() {
  context_provider()->ContextGL()->BindFramebuffer(GL_FRAMEBUFFER, 0);
}

void GLOutputSurface::SetDrawRectangle(const gfx::Rect& rect) {
  DCHECK(capabilities_.supports_dc_layers);

  if (set_draw_rectangle_for_frame_)
    return;
  DCHECK(gfx::Rect(size_).Contains(rect));
  DCHECK(has_set_draw_rectangle_since_last_resize_ ||
         (gfx::Rect(size_) == rect));
  set_draw_rectangle_for_frame_ = true;
  has_set_draw_rectangle_since_last_resize_ = true;
  context_provider()->ContextGL()->SetDrawRectangleCHROMIUM(
      rect.x(), rect.y(), rect.width(), rect.height());
}

void GLOutputSurface::Reshape(const gfx::Size& size,
                              float device_scale_factor,
                              const gfx::ColorSpace& color_space,
                              gfx::BufferFormat format,
                              bool use_stencil) {
  size_ = size;
  has_set_draw_rectangle_since_last_resize_ = false;
  set_draw_rectangle_for_frame_ = false;
  context_provider()->ContextGL()->ResizeCHROMIUM(
      size.width(), size.height(), device_scale_factor,
      color_space.AsGLColorSpace(), gfx::AlphaBitsForBufferFormat(format));
}

void GLOutputSurface::SwapBuffers(OutputSurfaceFrame frame) {
  DCHECK(context_provider_);

  uint32_t flags = 0;
  if (wants_vsync_parameter_updates_)
    flags |= gpu::SwapBuffersFlags::kVSyncParams;

  // The |swap_size| here should always be in the UI's logical screen space
  // since it is forwarded to the client code which is unaware of the display
  // transform optimization.
  gfx::Size swap_size = ApplyDisplayInverse(gfx::Rect(size_)).size();
  auto swap_callback = base::BindOnce(
      &GLOutputSurface::OnGpuSwapBuffersCompleted,
      weak_ptr_factory_.GetWeakPtr(), std::move(frame.latency_info),
      frame.top_controls_visible_height_changed, swap_size);
  gpu::ContextSupport::PresentationCallback presentation_callback;
  presentation_callback = base::BindOnce(&GLOutputSurface::OnPresentation,
                                         weak_ptr_factory_.GetWeakPtr());

  set_draw_rectangle_for_frame_ = false;
  if (frame.sub_buffer_rect) {
    HandlePartialSwap(*frame.sub_buffer_rect, flags, std::move(swap_callback),
                      std::move(presentation_callback));
  } else if (!frame.content_bounds.empty()) {
    context_provider_->ContextSupport()->SwapWithBounds(
        frame.content_bounds, flags, std::move(swap_callback),
        std::move(presentation_callback));
  } else {
    context_provider_->ContextSupport()->Swap(flags, std::move(swap_callback),
                                              std::move(presentation_callback));
  }
}

uint32_t GLOutputSurface::GetFramebufferCopyTextureFormat() {
  auto* gl = static_cast<VizProcessContextProvider*>(context_provider());
  return gl->GetCopyTextureInternalFormat();
}

bool GLOutputSurface::IsDisplayedAsOverlayPlane() const {
  return false;
}

unsigned GLOutputSurface::GetOverlayTextureId() const {
  return 0;
}

bool GLOutputSurface::HasExternalStencilTest() const {
  return false;
}

void GLOutputSurface::ApplyExternalStencil() {}

void GLOutputSurface::DidReceiveSwapBuffersAck(
    const gfx::SwapResponse& response) {
  client_->DidReceiveSwapBuffersAck(response.timings);
}

void GLOutputSurface::HandlePartialSwap(
    const gfx::Rect& sub_buffer_rect,
    uint32_t flags,
    gpu::ContextSupport::SwapCompletedCallback swap_callback,
    gpu::ContextSupport::PresentationCallback presentation_callback) {
  context_provider_->ContextSupport()->PartialSwapBuffers(
      sub_buffer_rect, flags, std::move(swap_callback),
      std::move(presentation_callback));
}

void GLOutputSurface::OnGpuSwapBuffersCompleted(
    std::vector<ui::LatencyInfo> latency_info,
    bool top_controls_visible_height_changed,
    const gfx::Size& pixel_size,
    const gpu::SwapBuffersCompleteParams& params) {
  if (!params.texture_in_use_responses.empty())
    client_->DidReceiveTextureInUseResponses(params.texture_in_use_responses);
  if (!params.ca_layer_params.is_empty)
    client_->DidReceiveCALayerParams(params.ca_layer_params);
  DidReceiveSwapBuffersAck(params.swap_response);

  UpdateLatencyInfoOnSwap(params.swap_response, &latency_info);
  latency_tracker_.OnGpuSwapBuffersCompleted(
      latency_info, top_controls_visible_height_changed);

  if (needs_swap_size_notifications_)
    client_->DidSwapWithSize(pixel_size);
}

void GLOutputSurface::OnPresentation(
    const gfx::PresentationFeedback& feedback) {
  client_->DidReceivePresentationFeedback(feedback);
}

unsigned GLOutputSurface::UpdateGpuFence() {
  if (!use_gpu_fence_)
    return 0;

  if (gpu_fence_id_ > 0)
    context_provider()->ContextGL()->DestroyGpuFenceCHROMIUM(gpu_fence_id_);

  gpu_fence_id_ = context_provider()->ContextGL()->CreateGpuFenceCHROMIUM();

  return gpu_fence_id_;
}

void GLOutputSurface::SetNeedsSwapSizeNotifications(
    bool needs_swap_size_notifications) {
  needs_swap_size_notifications_ = needs_swap_size_notifications;
}

void GLOutputSurface::SetUpdateVSyncParametersCallback(
    UpdateVSyncParametersCallback callback) {
  wants_vsync_parameter_updates_ = !callback.is_null();
  viz_context_provider_->SetUpdateVSyncParametersCallback(std::move(callback));
}

void GLOutputSurface::SetGpuVSyncCallback(GpuVSyncCallback callback) {
  DCHECK(capabilities_.supports_gpu_vsync);
  viz_context_provider_->SetGpuVSyncCallback(std::move(callback));
}

void GLOutputSurface::SetGpuVSyncEnabled(bool enabled) {
  DCHECK(capabilities_.supports_gpu_vsync);
  viz_context_provider_->SetGpuVSyncEnabled(enabled);
}

gfx::OverlayTransform GLOutputSurface::GetDisplayTransform() {
  return gfx::OVERLAY_TRANSFORM_NONE;
}

gfx::Rect GLOutputSurface::ApplyDisplayInverse(const gfx::Rect& input) {
  gfx::Transform display_inverse = gfx::OverlayTransformToTransform(
      gfx::InvertOverlayTransform(GetDisplayTransform()), gfx::SizeF(size_));
  return cc::MathUtil::MapEnclosedRectWith2dAxisAlignedTransform(
      display_inverse, input);
}

base::ScopedClosureRunner GLOutputSurface::GetCacheBackBufferCb() {
  return viz_context_provider_->GetCacheBackBufferCb();
}

gpu::SurfaceHandle GLOutputSurface::GetSurfaceHandle() const {
  return surface_handle_;
}

scoped_refptr<gpu::GpuTaskSchedulerHelper>
GLOutputSurface::GetGpuTaskSchedulerHelper() {
  return viz_context_provider_->GetGpuTaskSchedulerHelper();
}

gpu::MemoryTracker* GLOutputSurface::GetMemoryTracker() {
  return viz_context_provider_->GetMemoryTracker();
}

void GLOutputSurface::SetFrameRate(float frame_rate) {
  viz_context_provider_->ContextSupport()->SetFrameRate(frame_rate);
}

}  // namespace viz


text:
The TFS Aggregator is undoubtedly one of the most known and most useful tools for TFS. This comes to fill all the needs that can't be covered using the traditional work item rules. Basically allows you to execute your own rules after each save.

Installation and Deployment

The TFS Aggregator is an open source project stored in https://github.com/tfsaggregator/tfsaggregator. You can download the code and deploy it by yourself or simply use the installer provided by the project. The installer will detect your TFS version and install for you the console app and the plugin.

How the Plugin Works?

A TFS Plugin is a dll installed under "C:\Program Files\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins" which is able to catch a variety of events occurring in TFS and execute an action. The TFS Aggregator catch the event "WorkItemChangedEvent" which occurs each time that work item is saved and execute the actions defined in the policies file.

What is the Console App?

The TFS Aggregator console app is an application developed to simulate the behavior of the aggregator plugin (execute the rules defined in the policies file when a work item is updated). It's very useful for test the policies file before deploying it to the plugins folder.

How to Configure the Policies File

The file is composed of 3 sections: configuration section, rules section and policies section.

The configuration section is used to indicate the aggregator how it should be executed:

rateLimiting: aggregator "time out", to avoid infinite loops

logging: logging type

script: language used to write the rules

authentication: save the changes using the same user or as the service user (impersonate)

server: TFS server url (useful in low balancer environments)

In the rules section is where the actions to be executed are indicated. The rules are written directly in programming language (usually in C#). There are slight changes in the syntax but they are quite intuitive.

Regarding to the policies section, this is the place where you specify the scope in which each rule is applied. Each policy defines a single scope but may contain several rules.

How to Write a Rule

The rule header contains the rule name (must be unique because is used as id) and can contains two different attributes:

appliesTo: Indicate which work item types will be affected by the rule

hasField: Indicate that the rules will be applied to work items types that contains the specified field

The rule content specify the action to be executed when the rule is triggered. This action is written in programing language (usually C#) and must be inside of the CDATA element:

Regarding to the code, if you know the C# TFS API will be quite simple for you understand the syntax. Basically is the same thing but the Aggregator provides a set of objects and methods to help you with the hard work.

Aggregator Main Objects:

Self: contain the work item which trigger the aggregator

Fields: contain a list with all the work item fields

Store: contain the object store (WorkItemStore in the C# TFS API)

Logger: contain the method log used to write logs

Library: contain two useful methods: SendEmail and GetEmailAddress

Aggregator Main Methods (Note: I will use the work item "self" to show the methods but any work item object contains this methods):

Fields: can be used to retrieve all the fields or a specific one using: self.Fields["Title"]

Parent: retrieve the work item parent

Children: retrieve a list with the work item childs

HasParent: retrieve true or false

HasChildren: retrieve true or false

AddWorkItemLink: add a link

AddHyperlink: add a hiperlink

LastRevision: retrieve the a work item with the values before the last save

MakeNewWorkItem: create a new work item

GetGlobalList: retrieve the values of the specified Global List

Note: there is a very good examples and explanations in the official documentation https://tfsaggregator.github.io/using/

How to Write a Policy

Write a policy if a simple thing. Just specify the scope and indicate which rules should be applied in this scope. The policy header contains the attribute name (must be unique because is used as id) and its elements are the following:

collectionScope: contains the collection affected by this policy

projectScope: contains the team project (or team projects) affected by this policy

ruleRef: specify a rule to be executed (you can add several rules to the same policy)

How Can I Test My Policies Using The Console App?

The aggregator console app allows you to execute a specified policies file to a specific work item by running the following command:

"C:\Program Files\TFS Aggregator\bin\TFSAggregator2.ConsoleApp.exe" -f <PoliciesFile> -c <CollectionUrl> -p <TeamProject> -n <WorkItemId>

For example:

"C:\Program Files\TFS Aggregator\bin\TFSAggregator2.ConsoleApp.exe" -f "C:\Users\myuser\Desktop\TFSAggregator2.ServerPlugin.policies" -c http://tfsserver:8080/tfs/DefaultCollection -p MyProject -n 859

How to Deploy My Policies?

After test your policies file using the console app, you will be ready to deploy it as a plugin (to run after each save). To implement the new policies file just paste it in the following path: "C:\Program Files\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins"

Notes

When a rule is executed, the changes are not saved immediately. They are saved only at the end of the execution of all the rules (the aggregator uses a bulk save instead of several single saves)

After the Aggregator is executed it will run again (but it's logical, after all this is executed after each save no?)

Uses the necessary conditions to avoid "infinite loops" (write the rules with this in mind)

You can find a sample policies in the following path "C:\Program Files\TFS Aggregator\Samples"

Check the official documentation here: https://tfsaggregator.github.io/intro/

There is an option to use the TFS Aggregator as web service (but this version is still in beta)


text:
package com.blazeloader.api.client.model;

import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.PositionTextureVertex;
import net.minecraft.client.model.TexturedQuad;

public class ModelUVMappedBox extends ModelBox {
	public static final int SIDE_NORTH = 0;
    public static final int SIDE_SOUTH = 1;
    public static final int SIDE_TOP = 2;
    public static final int SIDE_BOTTOM = 3;
    public static final int SIDE_EAST = 4;
    public static final int SIDE_WEST = 5;

	private final float textureWidth;
	private final float textureHeight;

	private final int boxDepth;
	private final int boxWidth;
	private final int boxHeight;

	private final boolean mirrored;

    public ModelUVMappedBox(ModelRenderer renderer, int texOffsetX, int texOffsetY, float originX, float originY, float originZ, int width, int height, int depth, float scale) {
    	this(renderer, texOffsetX, texOffsetY, originX, originY, originZ, width, height, depth, scale, renderer.mirror);
    }

    public ModelUVMappedBox(ModelRenderer renderer, int texOffsetX, int texOffsetY, float originX, float originY, float originZ, int width, int height, int depth, float scale, boolean mirror) {
    	super(renderer, texOffsetX, texOffsetY, originX, originY, originZ, width, height, depth, scale, mirror);
    	textureWidth = renderer.textureWidth;
    	textureHeight = renderer.textureHeight;
    	boxDepth = depth;
    	boxWidth = width;
    	boxHeight = height;
    	mirrored = mirror;
    }

    public ModelUVMappedBox setFaceUV(int side, int x, int y) {
    	switch (side) {
    	case SIDE_NORTH: return setNorthFaceUV(x, y);
    	case SIDE_SOUTH: return setSouthFaceUV(x, y);
    	case SIDE_EAST: return setEastFaceUV(x, y);
    	case SIDE_WEST: return setWestFaceUV(x, y);
    	case SIDE_TOP: return setTopFaceUV(x, y);
    	case SIDE_BOTTOM: return setBottomFaceUV(x, y);
    	}
    	return this;
    }

    public ModelUVMappedBox setNorthFaceUV(int x, int y) {//^^ Front
    	quadList[0] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[5], vertexPositions[1], vertexPositions[2], vertexPositions[6]},
    			x, y, x + boxDepth, y + boxHeight, textureWidth, textureHeight);
    	if (mirrored) quadList[0].flipFace();
    	return this;
    }

    public ModelUVMappedBox setSouthFaceUV(int x, int y) {//^^ back
    	quadList[1] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[0], vertexPositions[4], vertexPositions[7], vertexPositions[3]},
    			x, y, x + boxDepth, y + boxHeight, textureWidth, textureHeight);
    	if (mirrored) quadList[1].flipFace();
    	return this;
    }

    public ModelUVMappedBox setTopFaceUV(int x, int y) { //^^
    	quadList[2] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[5], vertexPositions[4], vertexPositions[0], vertexPositions[1]},
    			x, y, x + boxWidth, y + boxDepth, textureWidth, textureHeight);
    	if (mirrored) quadList[2].flipFace();
    	return this;
    }

    public ModelUVMappedBox setBottomFaceUV(int x, int y) {//^^
    	quadList[3] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[2], vertexPositions[3], vertexPositions[7], vertexPositions[6]},
    			x, y + boxDepth, x + boxWidth, y, textureWidth, textureHeight);
    	if (mirrored) quadList[3].flipFace();
    	return this;
    }

    public ModelUVMappedBox setEastFaceUV(int x, int y) {//^^ left
    	quadList[4] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[1], vertexPositions[0], vertexPositions[3], vertexPositions[2]},
    			x, y, x + boxWidth, y + boxHeight, textureWidth, textureHeight);
    	if (mirrored) quadList[4].flipFace();
    	return this;
    }

    public ModelUVMappedBox setWestFaceUV(int x, int y) {//^^ Right
    	quadList[5] = new TexturedQuad(new PositionTextureVertex[] {vertexPositions[4], vertexPositions[5], vertexPositions[6], vertexPositions[7]},
    			x, y, x + boxWidth, y + boxHeight, textureWidth, textureHeight);
    	if (mirrored) quadList[5].flipFace();
    	return this;
    }
}