text:
package com.fireball1725.skeleton.common.container;

import com.fireball1725.skeleton.common.container.slot.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;

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

public abstract class ContainerBase extends Container {
    final InventoryPlayer inventoryPlayer;
    final TileEntity tileEntity;
    public boolean isContainerValid = true;
    protected HashSet<Integer> locked = new HashSet<Integer>();

    public ContainerBase(InventoryPlayer inventoryPlayer, TileEntity tileEntity) {
        this.inventoryPlayer = inventoryPlayer;
        this.tileEntity = tileEntity;
    }

    protected void bindPlayerInventory(InventoryPlayer inventoryPlayer, int offsetX, int offsetY) {
        // Get player inventory slots...
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 9; j++) {
                if (this.locked.contains(Integer.valueOf(j + i * 9 + 9))) {
                    addSlotToContainer(new SlotDisabled(inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18));
                } else {
                    addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18));
                }
            }
        }

        // Get hotbar slots...
        for (int i = 0; i < 9; i++) {
            if (this.locked.contains(Integer.valueOf(i))) {
                addSlotToContainer(new SlotDisabled(inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY));
            } else {
                addSlotToContainer(new SlotPlayerHotBar(inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY));
            }
        }
    }

    @Override
    public boolean canInteractWith(EntityPlayer player) {
        if (this.isContainerValid) {
            if ((this.tileEntity instanceof IInventory))
                return ((IInventory) this.tileEntity).isUseableByPlayer(player);

            return true;
        }
        return false;
    }

    @Override
    public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int idx) {
        //todo: refactor this mess
        ItemStack itemStack = null;
        SlotBase clickSlot = (SlotBase) this.inventorySlots.get(idx);
        if (clickSlot instanceof SlotDisabled) {
            return null;
        }

        if ((clickSlot != null) && (clickSlot.getHasStack())) {
            itemStack = clickSlot.getStack();
            if (itemStack == null) {
                return null;
            }

            List<Slot> selectedSlots = new ArrayList();
            if (clickSlot.isPlayerSide()) {
                //itemStack = shiftStoreItem(itemStack);
                for (int x = 0; x < this.inventorySlots.size(); x++) {
                    SlotBase advSlot = (SlotBase) this.inventorySlots.get(x);
                    if ((!advSlot.isPlayerSide()) && (!(advSlot instanceof SlotFake))) {
                        if (advSlot.isItemValid(itemStack)) {
                            selectedSlots.add(advSlot);
                        }
                    }
                }
            } else {
                for (int x = 0; x < this.inventorySlots.size(); x++) {
                    SlotBase advSlot = (SlotBase) this.inventorySlots.get(x);
                    if ((advSlot.isPlayerSide()) && (!(advSlot instanceof SlotFake))) {
                        if (advSlot.isItemValid(itemStack)) {
                            selectedSlots.add(advSlot);
                        }
                    }
                }
            }

            if ((selectedSlots.isEmpty()) && (clickSlot.isPlayerSide())) {
                if (itemStack != null) {
                    for (int x = 0; x < this.inventorySlots.size(); x++) {
                        SlotBase advSlot = (SlotBase) this.inventorySlots.get(x);
                        ItemStack dest = advSlot.getStack();
                        if ((!advSlot.isPlayerSide()) && (advSlot instanceof SlotFake)) {
                            if (dest == null) {
                                advSlot.putStack(itemStack != null ? itemStack.copy() : null);
                                advSlot.onSlotChanged();
                                updateSlot(advSlot);
                                return null;
                            }
                        }
                    }
                }
            }

            if (itemStack != null) {
                for (Slot d : selectedSlots) {
                    if ((!(d instanceof SlotDisabled))) {
                        if ((d.isItemValid(itemStack)) && (itemStack != null)) {
                            if (d.getHasStack()) {
                                ItemStack t = d.getStack();
                                if ((itemStack != null) && (itemStack.isItemEqual(t))) {
                                    int maxSize = t.getMaxStackSize();
                                    if (maxSize > d.getSlotStackLimit()) {
                                        maxSize = d.getSlotStackLimit();
                                    }
                                    int placeAble = maxSize - t.stackSize;
                                    if (itemStack.stackSize < placeAble) {
                                        placeAble = itemStack.stackSize;
                                    }
                                    t.stackSize += placeAble;
                                    itemStack.stackSize -= placeAble;
                                    if (itemStack.stackSize <= 0) {
                                        clickSlot.putStack(null);
                                        d.onSlotChanged();

                                        updateSlot(clickSlot);
                                        updateSlot(d);
                                        return null;
                                    }
                                    updateSlot(d);
                                }
                            }
                        }
                    }
                }

                for (Slot d : selectedSlots) {
                    if ((!(d instanceof SlotDisabled))) {
                        if ((d.isItemValid(itemStack)) && (itemStack != null)) {
                            if (d.getHasStack()) {
                                ItemStack t = d.getStack();
                                if ((itemStack != null) && (itemStack.isItemEqual(t))) {
                                    int maxSize = t.getMaxStackSize();
                                    if (maxSize > d.getSlotStackLimit()) {
                                        maxSize = d.getSlotStackLimit();
                                    }
                                    int placeAble = maxSize - t.stackSize;
                                    if (itemStack.stackSize < placeAble) {
                                        placeAble = itemStack.stackSize;
                                    }
                                    t.stackSize += placeAble;
                                    itemStack.stackSize -= placeAble;
                                    if (itemStack.stackSize <= 0) {
                                        clickSlot.putStack(null);
                                        d.onSlotChanged();

                                        updateSlot(clickSlot);
                                        updateSlot(d);
                                        return null;
                                    }
                                    updateSlot(d);
                                }
                            } else {
                                int maxSize = itemStack.getMaxStackSize();
                                if (maxSize > d.getSlotStackLimit()) {
                                    maxSize = d.getSlotStackLimit();
                                }
                                ItemStack tmp = itemStack.copy();
                                if (tmp.stackSize > maxSize) {
                                    tmp.stackSize = maxSize;
                                }
                                itemStack.stackSize -= tmp.stackSize;
                                d.putStack(tmp);
                                if (itemStack.stackSize <= 0) {
                                    clickSlot.putStack(null);
                                    d.onSlotChanged();

                                    updateSlot(clickSlot);
                                    updateSlot(d);
                                    return null;
                                }
                                updateSlot(d);
                            }
                        }
                    }
                }
            }

            clickSlot.putStack(itemStack != null ? itemStack.copy() : null);
        }
        updateSlot(clickSlot);
        return null;
    }

    private void updateSlot(final Slot slot) {
        this.detectAndSendChanges();
    }
}


text:
package com.stratio.connector.mongodb.core.engine.metadata;

import org.junit.Assert;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.stratio.crossdata.common.data.ColumnName;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.exceptions.UnsupportedException;
import com.stratio.crossdata.common.statements.structures.BooleanSelector;
import com.stratio.crossdata.common.statements.structures.ColumnSelector;
import com.stratio.crossdata.common.statements.structures.IntegerSelector;
import com.stratio.crossdata.common.statements.structures.Operator;
import com.stratio.crossdata.common.statements.structures.Relation;
import com.stratio.crossdata.common.statements.structures.RelationSelector;
import com.stratio.crossdata.common.statements.structures.Selector;
import com.stratio.crossdata.common.statements.structures.StringSelector;

public class UpdateDBObjectBuilderTest {

    private static final String COLLECTION_NAME = "coll_name";
    private static final String DB_NAME = "db_name";
    private static final String COLUMN_NAME = "row_name";
    private static final String OTHER_COLUMN_NAME = "other_row_name";
    private static final String STRING_VALUE = "cell_value";
    private static final String STRING_VALUE_OTHER = "other_cell_value";
    private static final Long LONG_VALUE = 25l;

    @Test
    public void addUpdateRelationtest() throws UnsupportedException, ExecutionException {

        UpdateDBObjectBuilder updateDBObjectBuilder = new UpdateDBObjectBuilder();
        Assert.assertEquals("The update query should be empty", new BasicDBObject(), updateDBObjectBuilder.build());

        Relation rel = getBasicRelation(COLUMN_NAME, Operator.ASSIGN, STRING_VALUE);
        updateDBObjectBuilder.addUpdateRelation(rel.getLeftTerm(), rel.getOperator(), rel.getRightTerm());

        BasicDBObject updatedExpected = new BasicDBObject();
        updatedExpected.append("$set", new BasicDBObject(COLUMN_NAME, STRING_VALUE));
        Assert.assertEquals("The update query is not the expected", updatedExpected, updateDBObjectBuilder.build());

        // The following operation should not modify the query
        updateDBObjectBuilder.addUpdateRelation(rel.getLeftTerm(), rel.getOperator(), rel.getRightTerm());
        Assert.assertEquals("The update query is not the expected", updatedExpected, updateDBObjectBuilder.build());

        // The following operation should modify the set
        updateDBObjectBuilder.addUpdateRelation(rel.getLeftTerm(), rel.getOperator(), new StringSelector(
                        STRING_VALUE_OTHER));
        updatedExpected.append("$set", new BasicDBObject(COLUMN_NAME, STRING_VALUE_OTHER));
        Assert.assertEquals("The update query is not the expected", updatedExpected, updateDBObjectBuilder.build());

        Relation rel2 = getBasicRelation(OTHER_COLUMN_NAME, Operator.SUBTRACT, 20l);
        updateDBObjectBuilder.addUpdateRelation(rel2.getLeftTerm(), rel2.getOperator(), rel2.getRightTerm());
        updatedExpected.append("$inc", new BasicDBObject(OTHER_COLUMN_NAME, -20l));
        Assert.assertEquals("The update query is not the expected", updatedExpected, updateDBObjectBuilder.build());

    }

    /**
     * Method under test addUpdateRelation().
     *
     * @throws UnsupportedException
     *             the unsupported exception
     * @throws ExecutionException
     *             the execution exception
     */
    @Test
    public void addUpdateInnerRelationTest() throws UnsupportedException, ExecutionException {

        UpdateDBObjectBuilder updateDBObjectBuilder = new UpdateDBObjectBuilder();

        Relation rel = getBasicRelation(OTHER_COLUMN_NAME, Operator.ASSIGN,
                        getBasicRelation(OTHER_COLUMN_NAME, Operator.SUBTRACT, 20l));

        updateDBObjectBuilder.addUpdateRelation(rel.getLeftTerm(), rel.getOperator(), rel.getRightTerm());
        BasicDBObject updatedExpected = new BasicDBObject("$inc", new BasicDBObject(OTHER_COLUMN_NAME, -20l));
        Assert.assertEquals("The inner relation processing is not the expected", updatedExpected,
                        updateDBObjectBuilder.build());

    }

    private Relation getBasicRelation(String column1, Operator assign, Object valueUpdated) {
        Selector leftSelector = new ColumnSelector(new ColumnName(DB_NAME, COLLECTION_NAME, column1));
        leftSelector.setAlias(column1);
        Selector rightSelector = null;
        if (valueUpdated instanceof Integer) {
            rightSelector = new IntegerSelector((int) valueUpdated);
        } else if (valueUpdated instanceof String) {
            rightSelector = new StringSelector((String) valueUpdated);
        } else if (valueUpdated instanceof Boolean) {
            rightSelector = new BooleanSelector((Boolean) valueUpdated);
        } else if (valueUpdated instanceof Relation) {
            rightSelector = new RelationSelector((Relation) valueUpdated);
        } else if (valueUpdated instanceof Long) {
            rightSelector = new IntegerSelector((int) (long) valueUpdated);
        }
        return new Relation(leftSelector, assign, rightSelector);
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Twilio.TwiML.Tests.DocExamples
{
    [TestClass]
	public class GatherTests : TestBase
	{
		[TestMethod]
		public void Example_1()
		{
			var response = new TwilioResponse();
			response.Gather();

			Assert.IsTrue(IsValidTwiML(response.ToXDocument()));
		}

		// http://www.twilio.com/docs/api/twiml/gather#examples-2
		[TestMethod]
		public void Example_2()
		{
			var response = new TwilioResponse();
			response.BeginGather(new { action = "/process_gather.php", method = "GET" });
			response.Say("Please enter your account number, followed by the pound sign");
			response.EndGather();
			response.Say("We didn't receive any input. Goodbye!");

			Assert.IsTrue(IsValidTwiML(response.ToXDocument()));
		}

		// http://www.twilio.com/docs/api/twiml/gather#hints
		[TestMethod]
		public void Advanced()
		{
			var response = new TwilioResponse();
			response.BeginGather(new { action = "/process_gather.php", method = "GET" });
			response.Say("Enter something, or not");
			response.EndGather();
			response.Redirect("/process_gather.php?Digits=TIMEOUT", "GET");

			Assert.IsTrue(IsValidTwiML(response.ToXDocument()));
		}
	}
}


text:
package com.navercorp.pinpoint.bootstrap.config;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * @author Woonduk Kang(emeroad)
 */
public class TransportModuleTest {

    @Test
    public void parse() {
        Assertions.assertEquals(TransportModule.parse("GRPC"), TransportModule.GRPC);
        Assertions.assertEquals(TransportModule.parse("THRIFT"), TransportModule.THRIFT);

        Assertions.assertNull(TransportModule.parse("ERROR"));
    }

    @Test
    public void parse1() {
        Assertions.assertEquals(TransportModule.parse("ERROR", TransportModule.GRPC), TransportModule.GRPC);
    }
}


text:
// Type definitions for react-native-video 2.0
// Project: https://github.com/react-native-community/react-native-video
// Definitions by: HuHuanming <https://github.com/huhuanming>
//                 abrahambotros <https://github.com/abrahambotros>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

import * as React from 'react';
import {
    ViewProperties
} from 'react-native';

export interface VideoProperties extends ViewProperties {
    /* Native only */
    src?: any;
    seek?: number;
    fullscreen?: boolean;
    onVideoLoadStart?(): void;
    onVideoLoad?(): void;
    onVideoBuffer?(): void;
    onVideoError?(): void;
    onVideoProgress?(): void;
    onVideoSeek?(): void;
    onVideoEnd?(): void;
    onTimedMetadata?(): void;
    onVideoFullscreenPlayerWillPresent?(): void;
    onVideoFullscreenPlayerDidPresent?(): void;
    onVideoFullscreenPlayerWillDismiss?(): void;
    onVideoFullscreenPlayerDidDismiss?(): void;

    /* Wrapper component */
    // Opaque type returned by require('./video.mp4')
    source: { uri?: string } | number;
    resizeMode?: string;
    poster?: string;
    repeat?: boolean;
    paused?: boolean;
    muted?: boolean;
    volume?: number;
    rate?: number;
    playInBackground?: boolean;
    playWhenInactive?: boolean;
    ignoreSilentSwitch?: 'ignore' | 'obey';
    disableFocus?: boolean;
    controls?: boolean;
    currentTime?: number;
    progressUpdateInterval?: number;
    onLoadStart?(): void;
    onLoad?(): void;
    onBuffer?(): void;
    onError?(): void;
    onProgress?(data: {
        currentTime: number,
        playableDuration: number,
    }): void;
    onSeek?(): void;
    onEnd?(): void;
    onFullscreenPlayerWillPresent?(): void;
    onFullscreenPlayerDidPresent?(): void;
    onFullscreenPlayerWillDismiss?(): void;
    onFullscreenPlayerDidDismiss?(): void;
    onReadyForDisplay?(): void;
    onPlaybackStalled?(): void;
    onPlaybackResume?(): void;
    onPlaybackRateChange?(): void;
    onAudioFocusChanged?(): void;
    onAudioBecomingNoisy?(): void;

    /* Required by react-native */
    scaleX?: number;
    scaleY?: number;
    translateX?: number;
    translateY?: number;
    rotation?: number;
}

export default class Video extends React.Component<VideoProperties> {
    seek(time: number): void;
    presentFullscreenPlayer(): void;
    dismissFullscreenPlayer(): void;
}


text:
<?php

namespace Magento\GiftMessage\Setup;

use Magento\Catalog\Setup\CategorySetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Quote\Setup\QuoteSetupFactory;
use Magento\Sales\Setup\SalesSetupFactory;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * Category setup factory
     *
     * @var CategorySetupFactory
     */
    protected $categorySetupFactory;

    /**
     * Quote setup factory
     *
     * @var QuoteSetupFactory
     */
    protected $quoteSetupFactory;

    /**
     * Sales setup factory
     *
     * @var SalesSetupFactory
     */
    protected $salesSetupFactory;

    /**
     * Init
     *
     * @param CategorySetupFactory $categorySetupFactory
     * @param QuoteSetupFactory $quoteSetupFactory
     * @param SalesSetupFactory $salesSetupFactory
     */
    public function __construct(
        CategorySetupFactory $categorySetupFactory,
        QuoteSetupFactory $quoteSetupFactory,
        SalesSetupFactory $salesSetupFactory
    ) {
        $this->categorySetupFactory = $categorySetupFactory;
        $this->quoteSetupFactory = $quoteSetupFactory;
        $this->salesSetupFactory = $salesSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /**
         * Add 'gift_message_id' attributes for entities
         */
        $options = ['type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, 'visible' => false, 'required' => false];
        $entities = ['quote', 'quote_address', 'quote_item', 'quote_address_item'];
        foreach ($entities as $entity) {
            /** @var \Magento\Quote\Setup\QuoteSetup $quoteSetup */
            $quoteSetup = $this->quoteSetupFactory->create(['setup' => $setup]);
            $quoteSetup->addAttribute($entity, 'gift_message_id', $options);
        }

        /** @var \Magento\Sales\Setup\SalesSetup $salesSetup */
        $salesSetup = $this->salesSetupFactory->create(['setup' => $setup]);
        $salesSetup->addAttribute('order', 'gift_message_id', $options);
        $salesSetup->addAttribute('order_item', 'gift_message_id', $options);
        /**
         * Add 'gift_message_available' attributes for entities
         */
        $salesSetup->addAttribute('order_item', 'gift_message_available', $options);

        /** @var \Magento\Catalog\Setup\CategorySetup $catalogSetup */
        $catalogSetup = $this->categorySetupFactory->create(['setup' => $setup]);
        $catalogSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'gift_message_available',
            [
                'group' => 'Gift Options',
                'backend' => 'Magento\Catalog\Model\Product\Attribute\Backend\Boolean',
                'frontend' => '',
                'label' => 'Allow Gift Message',
                'input' => 'select',
                'class' => '',
                'source' => 'Magento\Catalog\Model\Product\Attribute\Source\Boolean',
                'global' => true,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'apply_to' => '',
                'input_renderer' => 'Magento\GiftMessage\Block\Adminhtml\Product\Helper\Form\Config',
                'visible_on_front' => false,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false,
            ]
        );

        $groupName = 'Autosettings';
        $entityTypeId = $catalogSetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
        $attributeSetId = $catalogSetup->getAttributeSetId($entityTypeId, 'Default');

        $attribute = $catalogSetup->getAttribute($entityTypeId, 'gift_message_available');
        if ($attribute) {
            $catalogSetup->addAttributeToGroup(
                $entityTypeId,
                $attributeSetId,
                $groupName,
                $attribute['attribute_id'],
                60
            );
        }
    }
}


text:
<?php

namespace Bootstrap\Components\ClientComponents;
use Bootstrap\Views\BootstrapView;

trait Html {

    /**
     * @param $content string, HTML formatted text. Note that this does not support all HTML notation and this is
     * one of the few exceptions where support differs between iOS and Android. On iOS only font size and color are
     * supported whereas Android uses a webview to render the content. This is due to performance, where Android is
     * much more performant on rendering html content. You can also apply normal appzio formatting for the entire text
     * block.
     * @param array $parameters selected_state, variable, onclick, style
     * <code>
     * $array = array(
     * 'selected_state' => 'style-class-name',
     * 'variable'   => 'variablename',
     * 'onclick' => $onclick, // this must be an object or an array of objects
     * 'style' => 'style-class-name',
     * );
     * </code>
     * @param array $styles -- please see the link for more information about parameters [link] Bootstrap\Components\ComponentStyles
     * @return \stdClass
     */

    public function getComponentHtml(string $content, array $parameters=array(),array $styles=array()) {
        /** @var BootstrapView $this */

		$obj = new \StdClass;
        $obj->type = 'msg-html';
        $obj->content = $content;

        $obj = $this->attachStyles($obj,$styles);
        $obj = $this->attachParameters($obj,$parameters);
        $obj = $this->configureDefaults($obj);

        return $obj;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>cloud</artifactId>
	<packaging>pom</packaging>

	<parent>
		<groupId>com.gwtjs.icustom</groupId>
		<artifactId>icustom-boot</artifactId>
		<version>0.7.11.8</version>
		<relativePath>../pom.xml</relativePath><!-- lookup parent from repository -->
	</parent>

	<modules>
		<!--common core -->
		<module>cloud-eureka-server</module>
		<module>cloud-eureka-client</module>
		<module>cloud-service-ribbon</module>
		<module>cloud-service-feign</module>
		<module>cloud-service-zuul</module>
		<module>cloud-config-server</module>
		<module>cloud-config-client</module>
	</modules>

</project>


text:
package ddf.minim;

/**
 * An AudioListener can be used to monitor Recordable
 * objects. Each time a Recordable object receives a new sample buffer
 * from the audio system, or generates a new sample buffer at the request of the
 * audio system, it passes a copy of this buffer to its listeners. You can
 * implement this interface if you want to receive samples in a callback fashion,
 * rather than using an object's AudioBuffers to access them. You
 * add an AudioListener to a Recordable by calling
 * {@link Recordable#addListener(AudioListener)}. When you want to stop
 * receiving samples you call {@link Recordable#removeListener(AudioListener)}.
 *
 * @author Damien Di Fede
 *
 */
public interface AudioListener
{
  /**
   * Called by the Recordable object this is attached to
   * when that object has new samples.
   *
   * @param samp a buffer of samples from a MONO sound stream
   */
  void samples(float[] samp);

  /**
   * Called by the Recordable object this is attached to
   * when that object has new samples.
   *
   * @param sampL the left channel of a STEREO sound stream
   * @param sampR the right channel of a STEREO sound stream
   */
  void samples(float[] sampL, float[] sampR);
}


text:
/* Checks whether a matrix is upper triangular, lower triangular, identity,
diagonal or tridiagonal. Should be updated for more efficient algorithms. */

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int** createMatrix(int, int);          // prototype to allocate space for matrix
void inputMatrix(int **, int, int);    // prototype to populate matrix
void displayMatrix(int **, int, int); // prototype to display elements of the matrix
int isUpperTriangular(int **, int); // prototype to check whether the matrix is upper triangular
int isLowerTriangular(int **, int); // prototype to check whether the matrix is lower triangular
int isIdentity(int**, int);     // prototype to check whether the matrix is identity
int isDiagonal(int**, int);     // prototype to check whether the matrix is diagonal
int isTriDiagonal(int**, int);  // prototype to check whether the matrix is tridiagonal
void delMatrix(int**, int); // deallocates memory

#define TRUE 1
#define FALSE 0

int main()
{
	int **mat, size;
	printf("Please enter the order for a 2D square matrix.\n");
	scanf("%d",&size);
	mat = createMatrix(size, size);
    printf("Please enter the elements for the matrix.\n");
	inputMatrix(mat, size, size);
    printf("The matrix you have entered is:\n\n");
	displayMatrix(mat, size, size);
	printf("\n\n");

	if(isUpperTriangular(mat, size))
		printf("The matrix is an Upper Triangular matrix.\n");
	else
		printf("The matrix is not an Upper Triangular matrix.\n");

	if(isLowerTriangular(mat, size))
		printf("The matrix is a Lower Triangular matrix.\n");
    else
    	printf("The matrix is not a Lower Triangular matrix.\n");

	if(isIdentity(mat, size))
		printf("The matrix is an Identity matrix.\n");
    else
    	printf("The matrix is not an Identity matrix.\n");

	if(isDiagonal(mat, size))
		printf("The matrix is a Diagonal matrix.\n");
    else
    	printf("The matrix is not a Diagonal matrix.\n");

    if(isTriDiagonal(mat, size))
		printf("The matrix is a Tridiagonal matrix.\n");
    else
    	printf("The matrix is not a Tridiagonal matrix.\n");
	printf("\n\n");
	delMatrix(mat, size); // memory is deallocated
	return 0;
} // end of main

int** createMatrix(int row, int col) // dynamically allocates memory for the matrix
{
    int **p, i = 0;
    p = (int**)malloc(row * sizeof(int*));
	if(p == NULL)
	{
		perror("Error allocating memory.\n");
		exit(EXIT_FAILURE);
	}
    for(i = 0; i < row; i++)
    {
		*(p + i) = (int*)malloc(col * sizeof(int)); // allocates memory for each element
		if(*(p + i) == NULL)
		{
			perror("Error allocating memory.\n");
			exit(EXIT_FAILURE);
		}
    }
    return p;
}

void inputMatrix(int **arr, int x, int y) // takes user input for the matrix
{
	int i = 0, j = 0;
    for(i = 0; i < x; i++)
    {
		for(j = 0; j < y; j++)
        {
			scanf("%d", *(arr + i) + j);
        }
    }
}

void displayMatrix(int **arr, int x, int y) // displays the matrix
{
	int i = 0, j = 0;
    for(i = 0; i < x; i++)
    {
		for(j = 0; j < y; j++)
        {
			printf("%d ", *(*(arr + i) + j));
        }
        printf("\n");
    }
}

int isUpperTriangular(int **arr, int order)
{
	int i = 0, j = 0;
    for(i = 0; i < order; i++)
    {
		for(j = 0; j < order; j++)
        {
			if(i > j)
			{
				if(arr[i][j] == 0)
					return TRUE;
				else
					return FALSE;
			}
		}
    }
}

int isLowerTriangular(int **arr, int order)
{
    int i = 0, j = 0;
    for(i = 0; i < order; i++)
    {
		for(j = 0; j < order; j++)
        {
			if(i < j)
			{
				if(arr[i][j] == 0)
					return TRUE;
				else
					return FALSE;
			}
		}
    }
}

int isIdentity(int **arr, int order) // this function is dependent on isDiagonal()
{	int i = 0, j = 0, count = 0;
	for(i = 0; i < order; i++)
	{
		for(j = 0; j < order; j++)
		{
			if(i == j && arr[i][j] == 1)
				count++; // counts the number of ones in the principal diagonal
		}
    }
	if(isDiagonal(arr, order) && count == order) // checks if the matrix is diagonal
		return TRUE;
	else
		return FALSE;
}

int isDiagonal(int **arr, int order)
{
	int i = 0, j = 0;
    for(i = 0; i < order; i++)
	{
		for(j = 0; j < order; j++)
		{
			if(i != j)
			{
				if (arr[i][j] != 0)
					return FALSE;
			}

        }
	}
	return TRUE;
}

int isTriDiagonal(int **arr, int order)
{
    int i = 0, j = 0, count = 0, zeros = 0;
    for(i = 0; i < order; i++)
    {
		for(j = 0; j < order; j++)
        {
			if(abs(i - j) > 1 && arr[i][j] == 0)
				count++; // counts the total number of zeros above and below the tridiagonals
		}
    }
	for(i = 0; i < order; i++)
    {
		for(j = 0; j < order; j++)
        {
			if(arr[i][j] == 0) // counts the total number of zeros
				zeros++;
        }
    }
	if(count == zeros) // checks whether the total number of zeros matches the number for a tridiagonal matrix of said order
		return TRUE;
	else
		return FALSE;
}

void delMatrix(int **arr, int order)
{
	int i = 0;
	for(i = 0; i < order; i++)
		free(arr[i]);
	free(arr);
}


text:
using System;
using System.Runtime;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection.Runtime.General;

using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;

using Internal.Metadata.NativeFormat;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NativeFormat;

namespace Internal.Runtime.TypeLoader
{
    public sealed partial class TypeLoaderEnvironment
    {
        public enum MethodAddressType
        {
            None,
            Exact,
            Canonical,
            UniversalCanonical
        }

        /// <summary>
        /// Resolve a MethodDesc to a callable method address and unboxing stub address.
        /// </summary>
        /// <param name="method">Native metadata method description object</param>
        /// <param name="methodAddress">Resolved method address</param>
        /// <param name="unboxingStubAddress">Resolved unboxing stub address</param>
        /// <returns>true when the resolution succeeded, false when not</returns>
        internal static bool TryGetMethodAddressFromMethodDesc(
            MethodDesc method,
            out IntPtr methodAddress,
            out IntPtr unboxingStubAddress,
            out MethodAddressType foundAddressType)
        {
            methodAddress = IntPtr.Zero;
            unboxingStubAddress = IntPtr.Zero;
            foundAddressType = MethodAddressType.None;

#if SUPPORTS_R2R_LOADING
            TryGetCodeTableEntry(method, out methodAddress, out unboxingStubAddress, out foundAddressType);
#endif
#if SUPPORT_DYNAMIC_CODE
            if (foundAddressType == MethodAddressType.None)
                MethodEntrypointStubs.TryGetMethodEntrypoint(method, out methodAddress, out unboxingStubAddress, out foundAddressType);
#endif
            if (foundAddressType != MethodAddressType.None)
                return true;

            // Otherwise try to find it via an invoke map
            return TryGetMethodAddressFromTypeSystemMethodViaInvokeMap(method, out methodAddress, out unboxingStubAddress, out foundAddressType);
        }

        /// <summary>
        /// Resolve a MethodDesc to a callable method address and unboxing stub address by searching
        /// by searching in the InvokeMaps. This function is a wrapper around TryGetMethodInvokeDataFromInvokeMap
        /// that produces output in the format which matches the code table system.
        /// </summary>
        /// <param name="method">Native metadata method description object</param>
        /// <param name="methodAddress">Resolved method address</param>
        /// <param name="unboxingStubAddress">Resolved unboxing stub address</param>
        /// <returns>true when the resolution succeeded, false when not</returns>
        private static bool TryGetMethodAddressFromTypeSystemMethodViaInvokeMap(
            MethodDesc method,
            out IntPtr methodAddress,
            out IntPtr unboxingStubAddress,
            out MethodAddressType foundAddressType)
        {
            methodAddress = IntPtr.Zero;
            unboxingStubAddress = IntPtr.Zero;
            foundAddressType = MethodAddressType.None;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
            NativeFormatMethod nativeFormatMethod = method.GetTypicalMethodDefinition() as NativeFormatMethod;
            if (nativeFormatMethod == null)
                return false;

            MethodSignatureComparer methodSignatureComparer = new MethodSignatureComparer(
                nativeFormatMethod.MetadataReader, nativeFormatMethod.Handle);

            // Try to find a specific canonical match, or if that fails, a universal match
            if (TryGetMethodInvokeDataFromInvokeMap(
                nativeFormatMethod,
                method,
                ref methodSignatureComparer,
                CanonicalFormKind.Specific,
                out methodAddress,
                out foundAddressType) ||

                TryGetMethodInvokeDataFromInvokeMap(
                nativeFormatMethod,
                method,
                ref methodSignatureComparer,
                CanonicalFormKind.Universal,
                out methodAddress,
                out foundAddressType))
            {
                if (method.OwningType.IsValueType && !method.Signature.IsStatic)
                {
                    // In this case the invoke map found an unboxing stub, and we should pull the method address out as well
                    unboxingStubAddress = methodAddress;
                    methodAddress = RuntimeAugments.GetCodeTarget(unboxingStubAddress);

                    if (!method.HasInstantiation && ((foundAddressType != MethodAddressType.Exact) || method.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any)))
                    {
                        IntPtr underlyingTarget; // unboxing and instantiating stub handling
                        if (!TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(methodAddress, out underlyingTarget))
                        {
                            Environment.FailFast("Expected this to be an unboxing and instantiating stub.");
                        }
                        methodAddress = underlyingTarget;
                    }
                }

                return true;
            }

#endif
            return false;
        }

        /// <summary>
        /// Attempt a virtual dispatch on a given instanceType based on the method found via a metadata token
        /// </summary>
        private static bool TryDispatchMethodOnTarget_Inner(NativeFormatModuleInfo module, int metadataToken, RuntimeTypeHandle targetInstanceType, out IntPtr methodAddress)
        {
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
            TypeSystemContext context = TypeSystemContextFactory.Create();

            NativeFormatMetadataUnit metadataUnit = context.ResolveMetadataUnit(module);
            MethodDesc targetMethod = metadataUnit.GetMethod(metadataToken.AsHandle(), null);
            TypeDesc instanceType = context.ResolveRuntimeTypeHandle(targetInstanceType);

            MethodDesc realTargetMethod = targetMethod;

            // For non-interface methods we support the target method not being the exact target. (This allows
            // a canonical method to be passed in and work for any generic type instantiation.)
            if (!targetMethod.OwningType.IsInterface)
                realTargetMethod = instanceType.FindMethodOnTypeWithMatchingTypicalMethod(targetMethod);

            bool success = LazyVTableResolver.TryDispatchMethodOnTarget(instanceType, realTargetMethod, out methodAddress);

            TypeSystemContextFactory.Recycle(context);
            return success;
#else
            methodAddress = IntPtr.Zero;
            return false;
#endif
        }

#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
#if DEBUG
        private static int s_ConvertDispatchCellInfoCounter;
#endif

        /// <summary>
        /// Attempt to convert the dispatch cell to a metadata token to a more efficient vtable dispatch or interface/slot dispatch.
        /// Failure to convert is not a correctness issue. We also support performing a dispatch based on metadata token alone.
        /// </summary>
        private static DispatchCellInfo ConvertDispatchCellInfo_Inner(NativeFormatModuleInfo module, DispatchCellInfo cellInfo)
        {
            Debug.Assert(cellInfo.CellType == DispatchCellType.MetadataToken);

            TypeSystemContext context = TypeSystemContextFactory.Create();

            MethodDesc targetMethod = context.ResolveMetadataUnit(module).GetMethod(cellInfo.MetadataToken.AsHandle(), null);
            Debug.Assert(!targetMethod.HasInstantiation); // At this time we do not support generic virtuals through the dispatch mechanism
            Debug.Assert(targetMethod.IsVirtual);
            if (targetMethod.OwningType.IsInterface)
            {
                if (!LazyVTableResolver.TryGetInterfaceSlotNumberFromMethod(targetMethod, out cellInfo.InterfaceSlot))
                {
                    // Unable to resolve interface method. Fail, by not mutating cellInfo
                    return cellInfo;
                }

                if (!targetMethod.OwningType.RetrieveRuntimeTypeHandleIfPossible())
                {
                    new TypeBuilder().BuildType(targetMethod.OwningType);
                }

                cellInfo.CellType = DispatchCellType.InterfaceAndSlot;
                cellInfo.InterfaceType = targetMethod.OwningType.RuntimeTypeHandle.ToIntPtr();
                cellInfo.MetadataToken = 0;
            }
            else
            {
                // Virtual function case, attempt to resolve to a VTable slot offset.
                // If the offset is less than 4096 update the cellInfo
#if DEBUG
                // The path of resolving a metadata token at dispatch time is relatively rare in practice.
                // Force it to occur in debug builds with much more regularity
                if ((s_ConvertDispatchCellInfoCounter % 16) == 0)
                {
                    s_ConvertDispatchCellInfoCounter++;
                    TypeSystemContextFactory.Recycle(context);
                    return cellInfo;
                }
                s_ConvertDispatchCellInfoCounter++;
#endif

                int slotIndexOfMethod = LazyVTableResolver.VirtualMethodToSlotIndex(targetMethod);
                int vtableOffset = -1;
                if (slotIndexOfMethod >= 0)
                    vtableOffset = LazyVTableResolver.SlotIndexToEETypeVTableOffset(slotIndexOfMethod);
                if ((vtableOffset < 4096) && (vtableOffset != -1))
                {
                    cellInfo.CellType = DispatchCellType.VTableOffset;
                    cellInfo.VTableOffset = checked((uint)vtableOffset);
                    cellInfo.MetadataToken = 0;
                }
                // Otherwise, do nothing, and resolve with a metadata dispatch later
            }

            TypeSystemContextFactory.Recycle(context);
            return cellInfo;
        }
#endif

        /// <summary>
        /// Resolve a dispatch on an interface EEType/slot index pair to a function pointer
        /// </summary>
        private bool TryResolveTypeSlotDispatch_Inner(IntPtr targetTypeAsIntPtr, IntPtr interfaceTypeAsIntPtr, ushort slot, out IntPtr methodAddress)
        {
            methodAddress = IntPtr.Zero;

#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
            TypeSystemContext context = TypeSystemContextFactory.Create();

            TypeDesc targetType;
            TypeDesc interfaceType;

            unsafe
            {
                targetType = context.ResolveRuntimeTypeHandle(((EEType*)targetTypeAsIntPtr.ToPointer())->ToRuntimeTypeHandle());
                interfaceType = context.ResolveRuntimeTypeHandle(((EEType*)interfaceTypeAsIntPtr.ToPointer())->ToRuntimeTypeHandle());
            }

            if (!(interfaceType.GetTypeDefinition() is MetadataType))
            {
                // If the interface open type is not a metadata type, this must be an interface not known in the metadata world.
                // Use the redhawk resolver for this directly.
                TypeDesc pregeneratedType = LazyVTableResolver.GetMostDerivedPregeneratedOrTemplateLoadedType(targetType);
                pregeneratedType.RetrieveRuntimeTypeHandleIfPossible();
                interfaceType.RetrieveRuntimeTypeHandleIfPossible();
                methodAddress = RuntimeAugments.ResolveDispatchOnType(pregeneratedType.RuntimeTypeHandle, interfaceType.RuntimeTypeHandle, slot);
            }
            else
            {
                MethodDesc interfaceMethod;

                if (!LazyVTableResolver.TryGetMethodFromInterfaceSlot(interfaceType, slot, out interfaceMethod))
                    return false;

                if (!LazyVTableResolver.TryDispatchMethodOnTarget(targetType, interfaceMethod, out methodAddress))
                    return false;
            }

            TypeSystemContextFactory.Recycle(context);

            return true;
#else
            return false;
#endif
        }
    }
}


text:
import codecs
import json
import os
import re
import sys
from datetime import date
from django.conf import settings

DATA_FOLDER = ''

#SUCCESS_FOLDER = "DecidingForceArticles"
ARTICLE_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceArticles")
FILENAME_ERROR_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceErrors/filename")
HEADER_ERROR_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceErrors/header")
TEXT_ERROR_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceErrors/text")
DUPLICATES_ERROR_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceErrors/duplicates")
WARNING_FOLDER = os.path.join(DATA_FOLDER, "DecidingForceErrors/warning")
#ARTICLE_FOLDER = "DecidingForceArticles_Sample/"

# List of known duplicates
DUPLICATES_FILE = os.path.join(DATA_FOLDER,"duplicates.txt")

# Format of the article filenames.
# Example: 1000BethlehemPA-LehighValleyLive-02.txt
FILENAME_RE = (r'^(?P<article_id>\d+)' # article ID
               '-?' # optional hyphen
               '(?P<city>[\w\ \.-]+)' # city name
               ',? ?' # optional space and comma
               '(?P<state>[A-Z][A-Z])?' # optional state name
               '-' # hyphen
               '(?P<periodical>[\w\.]+)' # periodical name
               '-' # hypen
               '\s*' # optional whitespace
               '(?P<periodical_code>\d+)' # periodical code
               '\.txt' # extension
           )

# Format of a TUA tag.
# Example: <2><Camp>using social networking, emails/></>
TUA_RE = (r'(<(?P<tua_id>\d+)>)?' # optional id number (<2>)
          '<(?P<tua_type>[^>]+)>' # the type (<Protester>)
          '(?P<tua_body>.+?)' # the body (...text...)
          '/>(</>)?' # the close tags
)

# Format of some text inside of brackets.
# Example: [<2><Camp>Some text] goes here/></>
BRACKET_RE = (r'\[' # open bracket
              '(<[^>]*>)*' # possible TUA start tags
              '(?P<text>[^\]/<>]*)' # the actual text
              '(/>(</>)?)?' # possible TUA end tags
              '\]' # close bracket
          )

# Format of the date published header line. Example: 11-5-11
DATE_HEADER_RE = r'(?P<month>\d+)-(?P<day>\d+)-(?P<year>\d+)'

# Format of an annotator. Example: <!!>SLG</>
ANNO_RE = r'(<!!>)?\s*(?P<annotator>[A-Z]+)\s*(</>)?'

# Format of the version. Example: v23
VERSION_RE = r'v(?P<version>\d+)'

class ArticleParseError(Exception):
    FILENAME_ERROR = 0
    HEADER_ERROR = 1
    TEXT_ERROR = 2
    DUPLICATE_ERROR = 3
    BRACKET_WARNING = 4

    def __init__(self, message, error_type):
        super(ArticleParseError, self).__init__(message)
        self.error_type = error_type

def parse_document(path):
    with open(path, 'r') as f:
        raw_text = f.read()

    # extract info from the file name
    article_id, city, state, periodical, periodical_code = parse_filename(path)

    # don't parse known duplicates
    if article_id in parse_duplicates():
        raise ArticleParseError("Article %s is known duplicate!" % article_id,
                                ArticleParseError.DUPLICATE_ERROR)

    # extract info from the header and remove it from the text
    (clean_text, date_published, annotators, version) = parse_header(raw_text)

    # store type and offset information for each TUA, and strip TUA tags from
    # the text
    tuas = {}
    raw_tuas, clean_text = parse_and_clean_tuas(clean_text)
    for tua_id, tua_type, tua_body, tua_span in raw_tuas:
        if tua_type not in tuas:
            tuas[tua_type] = {}
        if tua_id not in tuas[tua_type]:
            tuas[tua_type][tua_id] = []

        if (clean_text[tua_span[0]:tua_span[1]].strip().lower()
            != tua_body.strip().lower()):
            raise ArticleParseError(
                "Reconstructed clean text didn't match TUA body!",
                ArticleParseError.TEXT_ERROR)

        tuas[tua_type][tua_id].append(tua_span)

    # If the only tua_type is 'Useless', this document is likely a duplicate.
    if len(tuas.keys()) == 1 and 'Useless' in tuas.keys():
        print "Possibly useless:", article_id
        raise ArticleParseError("Only found Useless tuas!",
                                ArticleParseError.DUPLICATE_ERROR)

    # Warning: brackets left over are usually bad news.
    if '[' in clean_text or ']' in clean_text:
        print "Possible Error:", article_id
#        raise ArticleParseError("Brackets remain in clean text!",
#                                ArticleParseError.BRACKET_WARNING)

    # print out our data.
    # TODO: store this somewhere.
    metadata = {
        'annotators': annotators,
        'version': version,
        'date_published': date_published,
        'article_id': article_id,
        'city': city,
        'state': state,
        'periodical': periodical,
        'periodical_code': periodical_code,
    }
    return {
        'metadata': metadata,
        'text': clean_text,
        'tuas': tuas
    }

#    print "final clean text:", clean_text
#    import pprint; pprint.pprint(tuas)
#    print "annotators:", annotators
#    print "version:", version
#    print "date published:", date_published
#    print "article ID:", article_id
#    print "city:", city
#    print "state:", state
#    print "periodical:", periodical
#    print "periodical code:", periodical_code
#    print "\n\n\n"

def parse_header(raw_text):
    # expected header format:
    #
    # A 3-line paragraph containing:
    #   +*+*      <-- special separator text
    #   11-5-11   <-- Date published (month-day-year)
    #   <!!>SLG</>, v23  <-- annotators and version number
    lines = raw_text.splitlines()
    header_rownum = 1
    for i, line in enumerate(lines):
        # Remove windows UTF-8 junk
        if line.startswith(codecs.BOM_UTF8):
            line = line[3:]

        # Skip blank lines
        if not line.strip():
            continue

        # Start of Header
        if line.strip() == '+*+*':
            header_rownum = 2

        # Unknown line
        elif header_rownum == 2:
            date_published = parse_date_line(line)
            header_rownum = 3

        # Annotator / Version line
        elif header_rownum == 3:
            annotators, version = parse_annotator_line(line)
            if not annotators and not version:
                raise ArticleParseError("Unexpected header line 3: " + line,
                                        ArticleParseError.HEADER_ERROR)
            break

    if header_rownum != 3:
        raise ArticleParseError("Not all header lines found!",
                                ArticleParseError.HEADER_ERROR)
    headerless_text = '\n'.join(lines[i+1:]).strip()
    return (headerless_text, date_published, annotators, version)

def parse_date_line(raw_text):
    # Format: month-day-year
    # Example: 11-8-11
    match = re.search(DATE_HEADER_RE, raw_text)
    date_published = None
    if match:
        month, day, year = match.group('month', 'day', 'year')
        try:
            date_published = date(2000 + int(year), int(month), int(day))
        except ValueError:
            raise ArticleParseError("Parsed an Invalid Date: " + raw_text,
                                    ArticleParseError.HEADER_ERROR)
    elif ('Undated' not in raw_text and 'undated' not in raw_text
          and '???' not in raw_text):
        raise ArticleParseError('Unexpected header line 2: ' + raw_text,
                                ArticleParseError.HEADER_ERROR)

    return date_published

def parse_annotator_line(raw_text):
    # Format: <!!>ABC</>, v##[, <!!>BCD</>]
    # Examples:
    #   <!!>SLG</>, v23
    #   <!!>CRV</>, v26, <!!> EDC</>
    annotators = []
    version = None
    for anno_match in re.finditer(ANNO_RE, raw_text):
        annotators.append(anno_match.group('annotator'))
    version_match = re.search(VERSION_RE, raw_text)
    if version_match:
        version = version_match.group('version')
    return (annotators, version)

def parse_and_clean_tuas(raw_text):
    # Extract metadata about TUAs and clean their tags out of the text.
    # See TUA_RE above for TUA formatting.

    tuas = []
    tuas_to_finalize = []
    match = re.search(TUA_RE, raw_text)
    while match:
        t_id, t_type, t_body = match.group('tua_id', 'tua_type', 'tua_body')
        t_id = 1 if t_id is None else t_id

        # Brackets represent back-references to previous text. We need to
        # create TUAs to capture the references to the previous text, then
        # remove the bracketed text from the article.
        has_brackets, clean_text, new_tuas = extract_bracket_text(match, raw_text)
        if has_brackets:
            raw_text = clean_text
            for new_tua_body, new_tua_index, num_matches in new_tuas:
                if new_tua_index == 0: # forward reference--we need to wait.
                    tuas_to_finalize.append((t_id, t_type, new_tua_body,
                                             new_tua_index))
                else:
                    t_span = get_match_span_by_index(
                        re.escape(new_tua_body.strip()),
                        new_tua_index, raw_text)
                    tuas.append((t_id, t_type, new_tua_body, t_span))
        else: # No brackets to remove, just parse and clean the TUA.
            t_start = match.start('tua_body')
            t_index, _ = find_match_index(re.escape(t_body), t_start, raw_text)
            raw_text = merge_with_spacing((raw_text[:match.start()],
                                          t_body,
                                           raw_text[match.end():]))
            t_span = get_match_span_by_index(re.escape(t_body.strip()), t_index,
                                             raw_text)
            tuas.append((t_id, t_type, t_body, t_span))
        match = re.search(TUA_RE, raw_text)

    for t_id, t_type, t_body, t_index in tuas_to_finalize:
        try:
            t_span = get_match_span_by_index(re.escape(t_body.strip()), t_index,
                                             raw_text)
            tuas.append((t_id, t_type, t_body, t_span))

        # This wasn't a forward reference--just normally occuring brackets.
        # So don't create the TUA.
        # WARNING!! This eliminates the bracket contents from the article!!
        # Option: put the contents back? (they're in t_body)
        except ArticleParseError:
            pass

    return (tuas, raw_text)

def find_match_index(regex, match_start, source_text):
    # if regex matches multiple times in source_text, return the index of the
    # match that begins at offset match_start.
    # Returns None if there is no such match
    match_index = None
    num_matches = 0
    for match_num, match in enumerate(re.finditer(regex, source_text, re.I)):
        num_matches += 1
        if match.start() == match_start:
            match_index = match_num
    return (match_index, num_matches)

def get_match_span_by_index(regex, match_index, source_text):
    # Return the index into source_text where regex matches the text for the
    # match_index'th time.
    for match_num, match in enumerate(re.finditer(regex, source_text, re.I)):
        if match_num == match_index:
            return match.span()
    raise ArticleParseError("Match doesn't occur correct number of times",
                            ArticleParseError.TEXT_ERROR)

def extract_bracket_text(match, source_text):
    # brackets might be anywhere starting from the character before the match to
    # the character after it.
    m_start, m_end = match.span()
    bracket_area = source_text[m_start-1:m_end+1]
    if '[' not in bracket_area[:-1] and ']' not in bracket_area[1:]:
        return (False, '', [])

    body_start, body_end = match.span('tua_body')
    try:
        cut_start = m_start if source_text[m_start-1] != '[' else m_start - 1
    except IndexError:
        cut_start = 0

    try:
        cut_end = m_end if source_text[m_end] != ']' else m_end + 1
    except IndexError:
        cut_end = m_end

    bits_to_keep = []
    keep_start_index = body_start
    tuas_to_create = []
    for bracket in re.finditer(BRACKET_RE, source_text[m_start-1:m_end+1]):
        # Find the backreference in the article text and set up a new TUA.
        bracket_text = bracket.group('text')
        if bracket_text == 'DT': # special case--this is never a true bracket.
            continue
        bracket_text_index, num_matches = find_match_index(
            re.escape(bracket_text),
            m_start - 1 + bracket.start('text'),
            source_text)
        # at least one occurrence before the bracket--back reference.
        if bracket_text_index != 0:
            bracket_text_index -= 1
        tuas_to_create.append((bracket_text, bracket_text_index, num_matches))

        # Track the text we need to remove
        # The bracket match is relative to the TUA match, so ajdust the offset.
        bracket_start = bracket.start() + m_start - 1
        bracket_end = bracket.end() + m_start - 1
        bits_to_keep.append((keep_start_index,
                             max(bracket_start, body_start)))
        keep_start_index = min(bracket_end, body_end)

    # reassemble the bracket-less text that needs to stay in the article
    bits_to_keep.append((keep_start_index, body_end))
    remaining_body = merge_with_spacing([source_text[span[0]:span[1]]
                                         for span in bits_to_keep])
    clean_text = merge_with_spacing((source_text[:cut_start],
                                     remaining_body,
                                     source_text[cut_end:]))
    return (True, clean_text, tuas_to_create)

def merge_with_spacing(string_bits):
    # Merge the strings in string_bits with exactly n_spaces spaces between them
    separator = ' '
    no_emptys = [bit for bit in string_bits if bit.strip(' ')]
    if not no_emptys:
        return ''
    return join_safe(separator, no_emptys)

def join_safe(separator, bits_to_join):
    def merge_safe(a, b):
        if not a:
            return b
        if not b:
            return a

        if requires_separator(a, b):
            return a.rstrip(separator) + separator + b.lstrip(separator)
        else:
            return a.rstrip(separator) + b.lstrip(separator)

    return reduce(merge_safe, bits_to_join, '')

def requires_separator(a, b):
    no_separator_chars_left = ['\n', '\x9c']
    no_separator_chars_right = ['\n', ',', '.',]
    no_separator_pair_right = ['"\n', '" ']
    return (a[-1] not in no_separator_chars_left
            and b[0] not in no_separator_chars_right
            and b[0:2] not in no_separator_pair_right)

def parse_filename(filename):
    # Extract metadata from the filename. See FILENAME_RE for formatting info.
    raw_name = os.path.basename(filename)
    match = re.search(FILENAME_RE, raw_name)
    if match:
        return match.group('article_id', 'city', 'state', 'periodical',
                           'periodical_code')
    else:
        raise ArticleParseError('Bad File Name: ' + raw_name,
                                ArticleParseError.FILENAME_ERROR)

def parse_duplicates():
    with open(DUPLICATES_FILE, 'r') as dup_f:
        return dup_f.readlines()

def parse_documents(directory_path, error_directory_paths):
    data = []
    for file_path in os.listdir(directory_path):
        full_path = os.path.join(directory_path, file_path)
        if '.gitignore' in file_path or os.path.isdir(full_path):
            continue
        print "PROCCESING FILE:", file_path, "..."

        try:
            data.append(parse_document(full_path))
        except ArticleParseError as e:
            new_path = os.path.join(error_directory_paths[e.error_type],
                                    file_path)
            os.rename(full_path, new_path)
            print "ERROR!"
    return data

if __name__ == '__main__':
    error_dirs = {
        ArticleParseError.FILENAME_ERROR : FILENAME_ERROR_FOLDER,
        ArticleParseError.HEADER_ERROR : HEADER_ERROR_FOLDER,
        ArticleParseError.TEXT_ERROR : TEXT_ERROR_FOLDER,
        ArticleParseError.DUPLICATE_ERROR: DUPLICATES_ERROR_FOLDER,
        ArticleParseError.BRACKET_WARNING: WARNING_FOLDER
    }

    if len(sys.argv) > 1:
        data = []
        file_path = sys.argv[1]
        try:
            data.append(parse_document(file_path))
        except ArticleParseError as e:
            print e
    else:
        data = parse_documents(ARTICLE_FOLDER, error_dirs)

    # dump the data to a JSON file
    def dthandler(obj):
        if isinstance(obj, date):
            return obj.isoformat()
    json.dump(data, open('data.txt', 'w'), default=dthandler)


text:
package resa.topology;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.Map;

/**
 * Created by ding on 14-1-16.
 */
public class RedisQueueSpout extends BaseRichSpout {

    public static final String OUTPUT_FIELD_NAME = "text";
    protected SpoutOutputCollector collector;

    private String queue;
    private String host;
    private byte[] byteQueueName;
    private int port;
    private transient Jedis jedis = null;

    public RedisQueueSpout(String host, int port, String queue) {
        this.host = host;
        this.port = port;
        this.queue = queue;
    }

    public RedisQueueSpout(String host, int port, String queue, boolean useBinary) {
        this.host = host;
        this.port = port;
        this.queue = queue;
        useBinary(useBinary);
    }

    public void useBinary(boolean use) {
        if (use) {
            byteQueueName = queue.getBytes();
        } else {
            byteQueueName = null;
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields(OUTPUT_FIELD_NAME));
    }

    @Override
    public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
        this.collector = spoutOutputCollector;
    }

    @Override
    public void close() {
        disconnect();
    }

    @Override
    public void nextTuple() {
        Jedis jedis = getConnectedJedis();
        if (jedis == null) {
            return;
        }
        Object text;
        try {
            text = byteQueueName == null ? jedis.lpop(queue) : jedis.lpop(byteQueueName);
        } catch (Exception e) {
            disconnect();
            return;
        }
        if (text != null) {
            emitData(text);
        }
    }

    protected void emitData(Object data) {
        collector.emit(Arrays.asList(data), data);
    }

    private Jedis getConnectedJedis() {
        if (jedis != null) {
            return jedis;
        }
        //try connect to redis server
        try {
            jedis = new Jedis(host, port);
        } catch (Exception e) {
        }
        return jedis;
    }

    private void disconnect() {
        try {
            jedis.disconnect();
        } catch (Exception e) {
        }
        jedis = null;
    }

}


text:
using System.Collections;
using System.Collections.Generic;
using System.Configuration;

namespace Umbraco.Core.Configuration.Dashboard
{
    internal class AreaCollection : ConfigurationElementCollection, IEnumerable<IArea>
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new AreaElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((AreaElement) element).Value;
        }

        IEnumerator<IArea> IEnumerable<IArea>.GetEnumerator()
        {
            for (var i = 0; i < Count; i++)
            {
                yield return BaseGet(i) as IArea;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
/**
 * PowerGrid styling extension
 *
 * Allows changing the class for cells.
 *
 * Usage:
 *
 *  {
 *      styling: {
 *          applyClasses: (record, column, callback) => {
 *              // Set up binding here, so that callback is invoked with the correct class. Callback can be invoked
 *              // later, and multiple times.
 *              var class = 'someclass';
 *              callback(class);
 *
 *              // (Optionally) return a function that will be called when the cell is destroyed. Use this to destroy
 *              // bindings, for example.
 *              return function() { <<dispose here>> }
 *          }
 *      }
 * }
 */
import override from "../override.js";

var whitespace = /\s+/;

export default function (grid, pluginOptions) {
    override(grid, function ($super) {
        return {
            renderCell: function (record, column, rowIdx, columnIdx) {
                var cell = $super.renderCell.apply(this, arguments),
                    oldClasses, oldClassUnparsed;
                var cleanup = pluginOptions.applyClasses(record, column, function (className) {
                    if (className == oldClassUnparsed) {
                        return;
                    }
                    var currentClasses = cell.className;
                    if (oldClasses) {
                        currentClasses = currentClasses.split(whitespace).filter(function (e) {
                            return oldClasses.indexOf(e) == -1;
                        }).join(" ");
                    }
                    if (className) {
                        cell.className = currentClasses + " " + className;
                        oldClasses = className.split(whitespace);
                    } else {
                        cell.className = currentClasses;
                        oldClasses = null;
                    }
                    oldClassUnparsed = className;
                });

                // TODO handle clean up (remove observers when cell is destroyed)

                return cell;
            }
        }
    });
}


text:
require 'test_helper'

class ActsAsNormalizedTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, ActsAsNormalized
  end
end


text:
package org.apache.maven.plugins.surefire.report;

import java.io.File;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.apache.maven.doxia.markup.HtmlMarkup;
import org.apache.maven.doxia.sink.Sink;
import org.apache.maven.doxia.sink.SinkEventAttributeSet;
import org.apache.maven.doxia.sink.SinkEventAttributes;
import org.apache.maven.reporting.MavenReportException;

/**
 *
 */
public class SurefireReportGenerator
{
    private final SurefireReportParser report;

    private List<ReportTestSuite> testSuites;

    private final boolean showSuccess;

    private final String xrefLocation;

    private static final int LEFT = Sink.JUSTIFY_LEFT;

    public SurefireReportGenerator( List<File> reportsDirectories, Locale locale, boolean showSuccess,
                                    String xrefLocation )
    {
        report = new SurefireReportParser( reportsDirectories, locale );

        this.xrefLocation = xrefLocation;

        this.showSuccess = showSuccess;
    }

    public void doGenerateReport( ResourceBundle bundle, Sink sink )
        throws MavenReportException
    {
        testSuites = report.parseXMLReportFiles();

        sink.head();

        sink.title();
        sink.text( bundle.getString( "report.surefire.header" ) );
        sink.title_();

        sink.head_();

        sink.body();

        SinkEventAttributeSet atts = new SinkEventAttributeSet();
        atts.addAttribute( SinkEventAttributes.TYPE, "text/javascript" );
        sink.unknown( "script", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );
        sink.unknown( "cdata", new Object[]{ HtmlMarkup.CDATA_TYPE, javascriptToggleDisplayCode() }, null );
        sink.unknown( "script", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );

        sink.section1();
        sink.sectionTitle1();
        sink.text( bundle.getString( "report.surefire.header" ) );
        sink.sectionTitle1_();
        sink.section1_();

        constructSummarySection( bundle, sink );

        Map<String, List<ReportTestSuite>> suitePackages = report.getSuitesGroupByPackage( testSuites );
        if ( !suitePackages.isEmpty() )
        {
            constructPackagesSection( bundle, sink, suitePackages );
        }

        if ( !testSuites.isEmpty() )
        {
            constructTestCasesSection( bundle, sink );
        }

        List<ReportTestCase> failureList = report.getFailureDetails( testSuites );
        if ( !failureList.isEmpty() )
        {
            constructFailureDetails( sink, bundle, failureList );
        }

        sink.body_();

        sink.flush();

        sink.close();
    }

    private void constructSummarySection( ResourceBundle bundle, Sink sink )
    {
        Map<String, String> summary = report.getSummary( testSuites );

        sink.section1();
        sink.sectionTitle1();
        sink.text( bundle.getString( "report.surefire.label.summary" ) );
        sink.sectionTitle1_();

        sinkAnchor( sink, "Summary" );

        constructHotLinks( sink, bundle );

        sinkLineBreak( sink );

        sink.table();

        sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, true );

        sink.tableRow();

        sinkHeader( sink, bundle.getString( "report.surefire.label.tests" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.errors" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.failures" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.skipped" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.successrate" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.time" ) );

        sink.tableRow_();

        sink.tableRow();

        sinkCell( sink, summary.get( "totalTests" ) );

        sinkCell( sink, summary.get( "totalErrors" ) );

        sinkCell( sink, summary.get( "totalFailures" ) );

        sinkCell( sink, summary.get( "totalSkipped" ) );

        sinkCell( sink, summary.get( "totalPercentage" ) + "%" );

        sinkCell( sink, summary.get( "totalElapsedTime" ) );

        sink.tableRow_();

        sink.tableRows_();

        sink.table_();

        sink.lineBreak();

        sink.paragraph();
        sink.text( bundle.getString( "report.surefire.text.note1" ) );
        sink.paragraph_();

        sinkLineBreak( sink );

        sink.section1_();
    }

    private void constructPackagesSection( ResourceBundle bundle, Sink sink,
                                           Map<String, List<ReportTestSuite>> suitePackages )
    {
        NumberFormat numberFormat = report.getNumberFormat();

        sink.section1();
        sink.sectionTitle1();
        sink.text( bundle.getString( "report.surefire.label.packagelist" ) );
        sink.sectionTitle1_();

        sinkAnchor( sink, "Package_List" );

        constructHotLinks( sink, bundle );

        sinkLineBreak( sink );

        sink.table();

        sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, true );

        sink.tableRow();

        sinkHeader( sink, bundle.getString( "report.surefire.label.package" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.tests" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.errors" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.failures" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.skipped" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.successrate" ) );

        sinkHeader( sink, bundle.getString( "report.surefire.label.time" ) );

        sink.tableRow_();

        for ( Map.Entry<String, List<ReportTestSuite>> entry : suitePackages.entrySet() )
        {
            sink.tableRow();

            String packageName = entry.getKey();

            List<ReportTestSuite> testSuiteList = entry.getValue();

            Map<String, String> packageSummary = report.getSummary( testSuiteList );

            sinkCellLink( sink, packageName, "#" + packageName );

            sinkCell( sink, packageSummary.get( "totalTests" ) );

            sinkCell( sink, packageSummary.get( "totalErrors" ) );

            sinkCell( sink, packageSummary.get( "totalFailures" ) );

            sinkCell( sink, packageSummary.get( "totalSkipped" ) );

            sinkCell( sink, packageSummary.get( "totalPercentage" ) + "%" );

            sinkCell( sink, packageSummary.get( "totalElapsedTime" ) );

            sink.tableRow_();
        }

        sink.tableRows_();

        sink.table_();

        sink.lineBreak();

        sink.paragraph();
        sink.text( bundle.getString( "report.surefire.text.note2" ) );
        sink.paragraph_();

        for ( Map.Entry<String, List<ReportTestSuite>> entry : suitePackages.entrySet() )
        {
            String packageName = entry.getKey();

            List<ReportTestSuite> testSuiteList = entry.getValue();

            sink.section2();
            sink.sectionTitle2();
            sink.text( packageName );
            sink.sectionTitle2_();

            sinkAnchor( sink, packageName );

            boolean showTable = false;

            for ( ReportTestSuite suite : testSuiteList )
            {
                if ( showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0 )
                {
                    showTable = true;

                    break;
                }
            }

            if ( showTable )
            {
                sink.table();

                sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, true );

                sink.tableRow();

                sinkHeader( sink, "" );

                sinkHeader( sink, bundle.getString( "report.surefire.label.class" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.tests" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.errors" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.failures" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.skipped" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.successrate" ) );

                sinkHeader( sink, bundle.getString( "report.surefire.label.time" ) );

                sink.tableRow_();

                for ( ReportTestSuite suite : testSuiteList )
                {
                    if ( showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0 )
                    {

                        sink.tableRow();

                        sink.tableCell();

                        sink.link( "#" + suite.getPackageName() + suite.getName() );

                        if ( suite.getNumberOfErrors() > 0 )
                        {
                            sinkIcon( "error", sink );
                        }
                        else if ( suite.getNumberOfFailures() > 0 )
                        {
                            sinkIcon( "junit.framework", sink );
                        }
                        else if ( suite.getNumberOfSkipped() > 0 )
                        {
                            sinkIcon( "skipped", sink );
                        }
                        else
                        {
                            sinkIcon( "success", sink );
                        }

                        sink.link_();

                        sink.tableCell_();

                        sinkCellLink( sink, suite.getName(), "#" + suite.getPackageName() + suite.getName() );

                        sinkCell( sink, Integer.toString( suite.getNumberOfTests() ) );

                        sinkCell( sink, Integer.toString( suite.getNumberOfErrors() ) );

                        sinkCell( sink, Integer.toString( suite.getNumberOfFailures() ) );

                        sinkCell( sink, Integer.toString( suite.getNumberOfSkipped() ) );

                        String percentage =
                            report.computePercentage( suite.getNumberOfTests(), suite.getNumberOfErrors(),
                                                      suite.getNumberOfFailures(), suite.getNumberOfSkipped() );
                        sinkCell( sink, percentage + "%" );

                        sinkCell( sink, numberFormat.format( suite.getTimeElapsed() ) );

                        sink.tableRow_();
                    }
                }

                sink.tableRows_();

                sink.table_();
            }

            sink.section2_();
        }

        sinkLineBreak( sink );

        sink.section1_();
    }

    private void constructTestCasesSection( ResourceBundle bundle, Sink sink )
    {
        NumberFormat numberFormat = report.getNumberFormat();

        sink.section1();
        sink.sectionTitle1();
        sink.text( bundle.getString( "report.surefire.label.testcases" ) );
        sink.sectionTitle1_();

        sinkAnchor( sink, "Test_Cases" );

        constructHotLinks( sink, bundle );

        for ( ReportTestSuite suite : testSuites )
        {
            List<ReportTestCase> testCases = suite.getTestCases();

            if ( testCases != null && !testCases.isEmpty() )
            {
                sink.section2();
                sink.sectionTitle2();
                sink.text( suite.getName() );
                sink.sectionTitle2_();

                sinkAnchor( sink, suite.getPackageName() + suite.getName() );

                boolean showTable = false;

                for ( ReportTestCase testCase : testCases )
                {
                    if ( testCase.getFailure() != null || showSuccess )
                    {
                        showTable = true;

                        break;
                    }
                }

                if ( showTable )
                {
                    sink.table();

                    sink.tableRows( new int[]{ LEFT, LEFT, LEFT }, true );

                    for ( ReportTestCase testCase : testCases )
                    {
                        if ( testCase.getFailure() != null || showSuccess )
                        {
                            sink.tableRow();

                            sink.tableCell();

                            Map<String, Object> failure = testCase.getFailure();

                            if ( failure != null )
                            {
                                sink.link( "#" + testCase.getFullName() );

                                sinkIcon( (String) failure.get( "type" ), sink );

                                sink.link_();
                            }
                            else
                            {
                                sinkIcon( "success", sink );
                            }

                            sink.tableCell_();

                            if ( failure != null )
                            {
                                sink.tableCell();

                                sinkLink( sink, testCase.getName(), "#" + testCase.getFullName() );

                                SinkEventAttributeSet atts = new SinkEventAttributeSet();
                                atts.addAttribute( SinkEventAttributes.CLASS, "detailToggle" );
                                atts.addAttribute( SinkEventAttributes.STYLE, "display:inline" );
                                sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );

                                sink.link( "javascript:toggleDisplay('" + toHtmlId( testCase.getFullName() ) + "');" );

                                atts = new SinkEventAttributeSet();
                                atts.addAttribute( SinkEventAttributes.STYLE, "display:inline;" );
                                atts.addAttribute( SinkEventAttributes.ID, toHtmlId( testCase.getFullName() ) + "off" );
                                sink.unknown( "span", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );
                                sink.text( " + " );
                                sink.unknown( "span", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );

                                atts = new SinkEventAttributeSet();
                                atts.addAttribute( SinkEventAttributes.STYLE, "display:none;" );
                                atts.addAttribute( SinkEventAttributes.ID, toHtmlId( testCase.getFullName() ) + "on" );
                                sink.unknown( "span", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );
                                sink.text( " - " );
                                sink.unknown( "span", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );

                                sink.text( "[ Detail ]" );
                                sink.link_();

                                sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );

                                sink.tableCell_();
                            }
                            else
                            {
                                sinkCell( sink, testCase.getName() );
                            }

                            sinkCell( sink, numberFormat.format( testCase.getTime() ) );

                            sink.tableRow_();

                            if ( failure != null )
                            {
                                sink.tableRow();

                                sinkCell( sink, "" );
                                sinkCell( sink, (String) failure.get( "message" ) );
                                sinkCell( sink, "" );
                                sink.tableRow_();

                                List<String> detail = (List<String>) failure.get( "detail" );
                                if ( detail != null )
                                {

                                    sink.tableRow();
                                    sinkCell( sink, "" );

                                    sink.tableCell();
                                    SinkEventAttributeSet atts = new SinkEventAttributeSet();
                                    atts.addAttribute( SinkEventAttributes.ID,
                                                       toHtmlId( testCase.getFullName() ) + "error" );
                                    atts.addAttribute( SinkEventAttributes.STYLE, "display:none;" );
                                    sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );

                                    sink.verbatim( null );
                                    for ( String line : detail )
                                    {
                                        sink.text( line );
                                        sink.lineBreak();
                                    }
                                    sink.verbatim_();

                                    sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );
                                    sink.tableCell_();

                                    sinkCell( sink, "" );

                                    sink.tableRow_();
                                }
                            }
                        }
                    }

                    sink.tableRows_();

                    sink.table_();
                }

                sink.section2_();
            }
        }

        sinkLineBreak( sink );

        sink.section1_();
    }

    private String toHtmlId( String id )
    {
        return id.replace( ".", "_" );
    }

    private void constructFailureDetails( Sink sink, ResourceBundle bundle, List<ReportTestCase> failureList )
    {
        Iterator<ReportTestCase> failIter = failureList.iterator();

        if ( failIter != null )
        {
            sink.section1();
            sink.sectionTitle1();
            sink.text( bundle.getString( "report.surefire.label.failuredetails" ) );
            sink.sectionTitle1_();

            sinkAnchor( sink, "Failure_Details" );

            constructHotLinks( sink, bundle );

            sinkLineBreak( sink );

            sink.table();

            sink.tableRows( new int[]{ LEFT, LEFT }, true );

            while ( failIter.hasNext() )
            {
                ReportTestCase tCase = failIter.next();

                Map<String, Object> failure = tCase.getFailure();

                sink.tableRow();

                sink.tableCell();

                String type = (String) failure.get( "type" );
                sinkIcon( type, sink );

                sink.tableCell_();

                sinkCellAnchor( sink, tCase.getName(), tCase.getFullName() );

                sink.tableRow_();

                String message = (String) failure.get( "message" );

                sink.tableRow();

                sinkCell( sink, "" );

                StringBuilder sb = new StringBuilder();
                sb.append( type );

                if ( message != null )
                {
                    sb.append( ": " );
                    sb.append( message );
                }

                sinkCell( sink, sb.toString() );

                sink.tableRow_();

                List<String> detail = (List<String>) failure.get( "detail" );
                if ( detail != null )
                {
                    boolean firstLine = true;

                    String techMessage = "";
                    for ( String line : detail )
                    {
                        techMessage = line;
                        if ( firstLine )
                        {
                            firstLine = false;
                        }
                        else
                        {
                            sink.text( "    " );
                        }
                    }

                    sink.tableRow();

                    sinkCell( sink, "" );

                    sink.tableCell();
                    SinkEventAttributeSet atts = new SinkEventAttributeSet();
                    atts.addAttribute( SinkEventAttributes.ID, tCase.getName() + "error" );
                    sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts );

                    if ( xrefLocation != null )
                    {
                        String path = tCase.getFullClassName().replace( '.', '/' );

                        sink.link( xrefLocation + "/" + path + ".html#" +
                                       getErrorLineNumber( tCase.getFullName(), techMessage ) );
                    }
                    sink.text(
                        tCase.getFullClassName() + ":" + getErrorLineNumber( tCase.getFullName(), techMessage ) );

                    if ( xrefLocation != null )
                    {
                        sink.link_();
                    }
                    sink.unknown( "div", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null );

                    sink.tableCell_();

                    sink.tableRow_();
                }
            }

            sink.tableRows_();

            sink.table_();
        }

        sinkLineBreak( sink );

        sink.section1_();
    }

    private String getErrorLineNumber( String className, String source )
    {
        StringTokenizer tokenizer = new StringTokenizer( source );

        while ( tokenizer.hasMoreTokens() )
        {
            String token = tokenizer.nextToken();
            if ( token.startsWith( className ) )
            {
                int idx = token.indexOf( ":" );
                if ( idx >= 0 )
                {
                    int closeIdx = token.lastIndexOf( ")" );

                    if ( closeIdx > idx + 1 )
                    {
                        return token.substring( idx + 1, closeIdx );
                    }
                }
            }
        }
        return "";
    }

    private void constructHotLinks( Sink sink, ResourceBundle bundle )
    {
        if ( !testSuites.isEmpty() )
        {
            sink.paragraph();

            sink.text( "[" );
            sinkLink( sink, bundle.getString( "report.surefire.label.summary" ), "#Summary" );
            sink.text( "]" );

            sink.text( " [" );
            sinkLink( sink, bundle.getString( "report.surefire.label.packagelist" ), "#Package_List" );
            sink.text( "]" );

            sink.text( " [" );
            sinkLink( sink, bundle.getString( "report.surefire.label.testcases" ), "#Test_Cases" );
            sink.text( "]" );

            sink.paragraph_();
        }
    }

    private void sinkLineBreak( Sink sink )
    {
        sink.lineBreak();
    }

    private void sinkIcon( String type, Sink sink )
    {
        sink.figure();

        if ( type.startsWith( "junit.framework" ) || "skipped".equals( type ) )
        {
            sink.figureGraphics( "images/icon_warning_sml.gif" );
        }
        else if ( type.startsWith( "success" ) )
        {
            sink.figureGraphics( "images/icon_success_sml.gif" );
        }
        else
        {
            sink.figureGraphics( "images/icon_error_sml.gif" );
        }

        sink.figure_();
    }

    private void sinkHeader( Sink sink, String header )
    {
        sink.tableHeaderCell();
        sink.text( header );
        sink.tableHeaderCell_();
    }

    private void sinkCell( Sink sink, String text )
    {
        sink.tableCell();
        sink.text( text );
        sink.tableCell_();
    }

    private void sinkLink( Sink sink, String text, String link )
    {
        sink.link( link );
        sink.text( text );
        sink.link_();
    }

    private void sinkCellLink( Sink sink, String text, String link )
    {
        sink.tableCell();
        sinkLink( sink, text, link );
        sink.tableCell_();
    }

    private void sinkCellAnchor( Sink sink, String text, String anchor )
    {
        sink.tableCell();
        sinkAnchor( sink, anchor );
        sink.text( text );
        sink.tableCell_();
    }

    private void sinkAnchor( Sink sink, String anchor )
    {
        sink.anchor( anchor );
        sink.anchor_();
    }

    private static String javascriptToggleDisplayCode()
    {
        final StringBuilder str = new StringBuilder( 64 );

        // the javascript code is emitted within a commented CDATA section
        // so we have to start with a newline and comment the CDATA closing in the end
        str.append( "\n" );
        str.append( "function toggleDisplay(elementId) {\n" );
        str.append( " var elm = document.getElementById(elementId + 'error');\n" );
        str.append( " if (elm && typeof elm.style != \"undefined\") {\n" );
        str.append( " if (elm.style.display == \"none\") {\n" );
        str.append( " elm.style.display = \"\";\n" );
        str.append( " document.getElementById(elementId + 'off').style.display = \"none\";\n" );
        str.append( " document.getElementById(elementId + 'on').style.display = \"inline\";\n" );
        str.append( " }" );
        str.append( " else if (elm.style.display == \"\") {" );
        str.append( " elm.style.display = \"none\";\n" );
        str.append( " document.getElementById(elementId + 'off').style.display = \"inline\";\n" );
        str.append( " document.getElementById(elementId + 'on').style.display = \"none\";\n" );
        str.append( " } \n" );
        str.append( " } \n" );
        str.append( " }\n" );
        str.append( "//" );

        return str.toString();
    }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { LocationService } from './location.service';

describe('LocationService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LocationService]
    });
  });

  it('should ...', inject([LocationService], (service: LocationService) => {
    expect(service).toBeTruthy();
  }));
});