text:
import argparse
import sys

import pysam

def parse_options():
    parser = argparse.ArgumentParser(description="This program checks "
                                     "whether reads that overlap SNPs map "
                                     "back to the same location as the "
                                     "original reads after their alleles "
                                     "are flipped by the "
                                     "find_intersecting_snps.py script. "
                                     "Reads where one or more allelic versions "
                                     "map to a different location (or fail "
                                     "to map) are discarded. Reads that are "
                                     "kept are written to the specified "
                                     "keep_bam output file. Reads in the "
                                     "input remap_bam file are expected to "
                                     "have read names encoding the original "
                                     "map location and number of allelic "
                                     "variants. Specifically, the read names "
                                     "should be delimited with the '.' "
                                     "character and "
                                     "contain the following fields: "
                                     "<orig_name>.<coordinate>."
                                     "<read_number>.<total_read_number>. "
                                     "These read names are "
                                     "generated by the "
                                     "find_intersecting_snps.py script.")

    parser.add_argument("to_remap_bam", help="input BAM file containing "
                        "original set of reads that needed to "
                        "be remapped after having their alleles flipped."
                        " This file is output by the find_intersecting_snps.py "
                        "script.")
    parser.add_argument("remap_bam", help="input BAM file containing "
                        "remapped reads (with flipped alleles)")
    parser.add_argument("keep_bam", help="output BAM file to write "
                        "filtered set of reads to")

    return parser.parse_args()

class ReadStats:
    """Track information about what the program is doing with reads"""
    def __init__(self):
        # reads from original file that were kept:
        self.keep = 0

        # reads from original file that were labeled as 'bad' e.g.
        # due to remapping issues
        self.bad = 0

        # reads from original file that were discarded
        self.discard = 0

        # reads that were not present in original file
        self.not_present = 0

        # paired read where only one read was observed
        self.pair_missing = 0

        # reads that were discarded because they (or their pair) remapped with
        # a different cigar string
        self.cigar_mismatch = 0
        self.cigar_missing = 0

    def write(self):
        sys.stderr.write("keep reads: %d\n" % self.keep)
        sys.stderr.write("bad reads: %d\n" % self.bad)
        sys.stderr.write("not present reads: %d\n" % self.not_present)
        sys.stderr.write("discard reads: {}\n".format(self.discard))
        sys.stderr.write("  CIGAR mismatch {}\n".format(self.cigar_mismatch))
        sys.stderr.write("  CIGAR missing or multiple: {}\n".format(self.cigar_missing))
        sys.stderr.write("  mate pair missing: {}\n".format(self.pair_missing))

def filter_reads(remap_bam):
    # dictionary to keep track of how many times a given read is observed
    read_counts = {}

    # names of reads that should be kept
    keep_reads = set([])
    bad_reads = set([])

    # a dictionary of lists for each read
    # each list contains two sets of CIGAR strings, one for each pair
    cigar_strings = {}

    for read in remap_bam:
        # parse name of read, which should contain:
        # 1 - the original name of the read
        # 2 - the coordinate that it should map to
        # 3 - the number of the read
        # 4 - the total number of reads being remapped
        words = read.qname.split(".")
        if len(words) < 4:
            raise ValueError("expected read names to be formatted "
                             "like <orig_name>.<coordinate>."
                             "<read_number>.<total_read_number> but got "
                             "%s" % read.qname)

        # token separator '.' can potentially occur in
        # original read name, so if more than 4 tokens,
        # assume first tokens make up original read name
        orig_name = ".".join(words[0:len(words)-3])
        coord_str, num_str, total_str = words[len(words)-3:]
        num = int(num_str)
        total = int(total_str)

        # only keep primary alignments and discard 'secondary'
        # and 'supplementary' alignments
        if read.is_secondary or read.is_supplementary:
            bad_reads.add(orig_name)
            continue

        # add the cigars for this read

        # pysam used to give back read1 and read2 flagged consistently,
        # however something now seems broken with the flags. Not sure if
        # this reflects a change in pysam HTSeqLib or elsewhere. Regardless
        # to make WASP robust to this issue, no longer tracking whether a
        # CIGAR corresponds to read1 or read2. This could
        # potentially result in a mapping bias for a very small number of reads
        # (i.e. if read1 and read2 remap to same location with new CIGARs,
        # but the new read1 CIGAR happens to match the old read2 CIGAR and
        # vice-versa, but number is likely to be miniscule.

        if(orig_name in cigar_strings):
            cigar_strings[orig_name].add(read.cigarstring)
        else:
            cigar_strings[orig_name] = set([read.cigarstring])

        correct_map = False

        if '-' in coord_str:
            # paired end read, coordinate gives expected positions for each end
            c1, c2 = coord_str.split("-")

            if not read.is_paired:
                bad_reads.add(orig_name)
                continue
            if not read.is_proper_pair:
                bad_reads.add(orig_name)
                continue

            pos1 = int(c1)
            pos2 = int(c2)
            if pos1 < pos2:
                left_pos = pos1
                right_pos = pos2
            else:
                left_pos = pos2
                right_pos = pos1

            # only use left end of reads, but check that right end is in
            # correct location
            if read.pos < read.next_reference_start or (read.pos == read.next_reference_start and read.is_read1 and not read.is_read2):
                if pos1 == read.pos+1 and pos2 == read.next_reference_start+1:
                    # both reads mapped to correct location
                    correct_map = True
            else:
                # this is right end of read
                continue
        else:
            # single end read
            pos = int(coord_str)

            if pos == read.pos+1:
                # read maps to correct location
                correct_map = True

        if correct_map:
            if orig_name in read_counts:
                read_counts[orig_name] += 1
            else:
                read_counts[orig_name] = 1

            if read_counts[orig_name] == total:
                # all alternative versions of this read
                # mapped to correct location
                if orig_name in keep_reads:
                    raise ValueError("saw read %s more times than "
                                     "expected in input file" % orig_name)
                keep_reads.add(orig_name)

                # remove read from counts to save mem
                del read_counts[orig_name]
        else:
            # read maps to different location
            bad_reads.add(orig_name)

    #sys.stderr.write("keep_reads: %d, bad_reads: %d\n" % (len(keep_reads), len(bad_reads)))
    #sys.stderr.write("%d reads did not have all versions map\n" % (len(read_counts)))

    return keep_reads, bad_reads, cigar_strings

def write_reads(to_remap_bam, keep_bam, keep_reads, bad_reads, cigar_strings):
    """writes reads but also checks cigar strings"""

    stats = ReadStats()

    read_pair_cache = {}

    for read in to_remap_bam:
        if read.qname in bad_reads:
            stats.bad += 1
        elif read.qname in keep_reads:
            if read.is_paired:
                # cache reads until you see their pair
                # then, write both of them to file together
                if read.qname in read_pair_cache:
                    #
                    # check that the CIGAR strings match up
                    # for both reads.
                    # NOTE: 2/8/2021 Code used to assume that read1 and read2 stayed defined as
                    # read1 and read2 following re-alignment. Observed that read1 and read2 sometimes
                    # switch. Changed code to allow for this possibility.
                    r1 = read_pair_cache[read.qname]
                    r2 = read

                    # remove read from cache
                    del read_pair_cache[read.qname]

                    cigs = cigar_strings[read.qname]

                    if len(cigs) == 1:
                        # both reads had same CIGAR in original mapping
                        if (r1.cigarstring == r2.cigarstring) and \
                           (r1.cigarstring in cigs):
                            # Both R1 and R2 cigar strings are the same
                            # and match CIGAR from original mapping
                            stats.keep += 2
                            keep_bam.write(r1)
                            keep_bam.write(r2)
                        else:
                            stats.cigar_mismatch += 1
                            stats.discard += 1
                    elif len(cigs) == 2:
                        # both reads had different CIGAR in original mapping
                        if (r1.cigarstring != r2.cigarstring) and \
                           (r1.cigarstring in cigs) and \
                           (r2.cigarstring in cigs):
                            # verified CIGARs are different and
                            # were both present in original mapping
                            stats.keep += 2
                            keep_bam.write(r1)
                            keep_bam.write(r2)
                        else:
                            stats.cigar_mismatch += 1
                            stats.discard += 1
                    else:
                        # There were no CIGARs or >2 CIGARs in original mapping
                        # This is unexpected and we don't handle this case.
                        stats.cigar_missing += 1
                        stats.discard += 1

                else:
                    # cache this read
                    read_pair_cache[read.qname] = read
            else:
                # single-end read
                if (len(cigar_strings[read.qname]) != 1):
                    # currently don't handle missing/multiple CIGARs
                    stats.cigar_missing += 1
                    stats.discard += 1
                else:
                    if (read.cigarstring in cigar_strings[read.qname]):
                        keep_bam.write(read)
                        stats.keep += 1
                    else:
                        stats.cigar_mismatch += 1
                        stats.discard += 1
        else:
            # read was not labeled as 'keep' or 'bad' in original file
            stats.not_present += 1

    # any reads remaining in the cache have been discarded
    stats.pair_missing += len(read_pair_cache)
    stats.discard += len(read_pair_cache)

    stats.write()

def main(to_remap_bam_path, remap_bam_path, keep_bam_path):
    to_remap_bam = pysam.Samfile(to_remap_bam_path)
    remap_bam = pysam.Samfile(remap_bam_path)
    keep_bam = pysam.Samfile(keep_bam_path, "wb", template=to_remap_bam)

    keep_reads, bad_reads, cigar_strings = filter_reads(remap_bam)

    write_reads(to_remap_bam, keep_bam, keep_reads, bad_reads, cigar_strings)

if __name__ == "__main__":
    options = parse_options()
    main(options.to_remap_bam, options.remap_bam, options.keep_bam)


text:
<?php

namespace MediaMath\TerminalOneAPI\Management\Targeting;

use MediaMath\TerminalOneAPI\Infrastructure\Endpoint;
use MediaMath\TerminalOneAPI\Infrastructure\ManagementApiObject;
use MediaMath\TerminalOneAPI\Infrastructure\NonCreateable;
use MediaMath\TerminalOneAPI\Infrastructure\NonDeletable;
use MediaMath\TerminalOneAPI\Infrastructure\NonUpdateable;

/**
 * Class AudienceSegment
 * @package MediaMath\TerminalOneAPI\Management\Targeting
 */
class AudienceSegment extends ManagementApiObject implements Endpoint
{

    use NonDeletable;
    use NonCreateable;
    use NonUpdateable;

    /**
     * @return string
     */
    public function endpoint()
    {
        return 'audience_segments';
    }

}

redpajama_set_name: RedPajamaGithub


text:
/******************************************************************************
 *
 * Code and text by Sean Baxter, NVIDIA Research
 * See http://nvlabs.github.io/moderngpu for repository and documentation.
 *
 ******************************************************************************/

#pragma once

#include "ctasegscan.cu.h"
#include "ctasearch.cu.h"

namespace mgpu {

////////////////////////////////////////////////////////////////////////////////
// Segmented reduce utility functions.

// Extract the upper-bound indices from the coded ranges. Decrement to include
// the first addressed row/segment.

struct SegReduceRange {
	int begin;
	int end;
	int total;
	bool flushLast;
};

MGPU_DEVICE SegReduceRange DeviceShiftRange(int limit0, int limit1) {
	SegReduceRange range;
	range.begin = 0x7fffffff & limit0;
	range.end = 0x7fffffff & limit1;
	range.total = range.end - range.begin;
	range.flushLast = 0 == (0x80000000 & limit1);
	range.end += !range.flushLast;
	return range;
}

// Reconstitute row/segment indices from a starting row index and packed end
// flags. Used for pre-processed versions of interval reduce and interval Spmv.
template<int VT>
MGPU_DEVICE void DeviceExpandFlagsToRows(int first, int endFlags,
	int rows[VT + 1]) {

	rows[0] = first;
	#pragma unroll
	for(int i = 0; i < VT; ++i) {
		if((1<< i) & endFlags) ++first;
		rows[i + 1] = first;
	}
}

////////////////////////////////////////////////////////////////////////////////
// After loading CSR terms into shared memory, each thread binary searches
// (upper-bound) to find its starting point. Each thread then walks forward,
// emitting the csr0-relative row indices to register.

template<int NT, int VT>
MGPU_DEVICE int DeviceExpandCsrRows(int tidOffset, int* csr_shared,
	int numRows, int end, int rows[VT + 1], int rowStarts[VT]) {

	// Each thread binary searches for its starting row.
	int row = BinarySearch<MgpuBoundsUpper>(csr_shared, numRows, tidOffset,
		mgpu::less<int>()) - 1;

	// Each thread starts at row and scans forward, emitting row IDs into
	// register. Store the CTA-local row index (starts at 0) to rows and the
	// start of the row (globally) to rowStarts.
	int curOffset = csr_shared[row];
	int nextOffset = (row + 1 < numRows) ? csr_shared[row + 1] : end;

	rows[0] = row;
	rowStarts[0] = curOffset;
	int endFlags = 0;

	#pragma unroll
	for(int i = 1; i <= VT; ++i) {
		// Advance the row cursor when the iterator hits the next row offset.
		if(tidOffset + i == nextOffset) {
			// Set an end flag when the cursor advances to the next row.
			endFlags |= 1<< (i - 1);

			// Advance the cursor and load the next row offset.
			++row;
			curOffset = nextOffset;
			nextOffset = (row + 1 < numRows) ? csr_shared[row + 1] : end;
		}
		rows[i] = row;
		if(i < VT) rowStarts[i] = curOffset;
	}
	__syncthreads();

	return endFlags;
}

////////////////////////////////////////////////////////////////////////////////
// DeviceSegReducePrepare
// Expand non-empty interval of CSR elements into row indices. Compute end-flags
// by comparing adjacent row IDs.

// DeviceSegReducePrepare may be called either by a pre-processing kernel or by
// the kernel that actually evaluates the segmented reduction if no preprocesing
// is desired.
struct SegReduceTerms {
	int endFlags;
	int tidDelta;
};

template<int NT, int VT>
MGPU_DEVICE SegReduceTerms DeviceSegReducePrepare(int* csr_shared, int numRows,
	int tid, int gid, bool flushLast, int rows[VT + 1], int rowStarts[VT]) {

	// Pass a sentinel (end) to point to the next segment start. If we flush,
	// this is the end of this tile. Otherwise it is INT_MAX
	int endFlags = DeviceExpandCsrRows<NT, VT>(gid + VT * tid, csr_shared,
		numRows, flushLast ? (gid + NT * VT) : INT_MAX, rows, rowStarts);

	// Find the distance to to scan to compute carry-in for each thread. Use the
	// existance of an end flag anywhere in the thread to determine if carry-out
	// values from the left should propagate through to the right.
	int tidDelta = DeviceFindSegScanDelta<NT>(tid, rows[0] != rows[VT],
		csr_shared);

	SegReduceTerms terms = { endFlags, tidDelta };
	return terms;
}

////////////////////////////////////////////////////////////////////////////////
// CTASegReduce
// Core segmented reduction code. Supports fast-path and slow-path for intra-CTA
// segmented reduction. Stores partials to global memory.
// Callers feed CTASegReduce::ReduceToGlobal values in thread order.
template<int NT, int VT, bool HalfCapacity, typename T, typename Op>
struct CTASegReduce {
	typedef CTASegScan<NT, Op> SegScan;

	enum {
		NV = NT * VT,
		Capacity = HalfCapacity ? (NV / 2) : NV
	};

	union Storage {
		typename SegScan::Storage segScanStorage;
		T values[Capacity];
	};

	template<typename DestIt>
	MGPU_DEVICE static void ReduceToGlobal(const int rows[VT + 1], int total,
		int tidDelta, int startRow, int block, int tid, T data[VT],
		DestIt dest_global, T* carryOut_global, T identity, Op op,
		Storage& storage) {

		// Run a segmented scan within the thread.
		T x, localScan[VT];
		#pragma unroll
		for(int i = 0; i < VT; ++i) {
			x = i ? op(x, data[i]) : data[i];
			localScan[i] = x;
			if(rows[i] != rows[i + 1]) x = identity;
		}

		// Run a parallel segmented scan over the carry-out values to compute
		// carry-in.
		T carryOut;
		T carryIn = SegScan::SegScanDelta(tid, tidDelta, x,
			storage.segScanStorage, &carryOut, identity, op);

		// Store the carry-out for the entire CTA to global memory.
		if(!tid) carryOut_global[block] = carryOut;

		dest_global += startRow;
		if(HalfCapacity && total > Capacity) {
			// Add carry-in to each thread-local scan value. Store directly
			// to global.
			#pragma unroll
			for(int i = 0; i < VT; ++i) {
				// Add the carry-in to the local scan.
				T x2 = op(carryIn, localScan[i]);

				// Store on the end flag and clear the carry-in.
				if(rows[i] != rows[i + 1]) {
					carryIn = identity;
					dest_global[rows[i]] = x2;
				}
			}
		} else {
			// All partials fit in shared memory. Add carry-in to each thread-
			// local scan value.
			#pragma unroll
			for(int i = 0; i < VT; ++i) {
				// Add the carry-in to the local scan.
				T x2 = op(carryIn, localScan[i]);

				// Store reduction when the segment changes and clear the
				// carry-in.
				if(rows[i] != rows[i + 1]) {
					storage.values[rows[i]] = x2;
					carryIn = identity;
				}
			}
			__syncthreads();

			// Cooperatively store reductions to global memory.
			for(int index = tid; index < total; index += NT)
				dest_global[index] = storage.values[index];
			__syncthreads();
		}
	}
};

} // namespace mgpu


text:
// Copyright 2009 Opera Software.
// This code is released under the BSD license found in the license.txt file.

function test(){  /**  Discard JSON input if extra comma before closing curly brace */
	/* Some JS implementations allow this for JS code, but it should not be allowed for JSON per the JSON spec
	*/
	var passed = false;
	try{
		JSON.parse(
			'{"test":[1,2,3],}'
		);
	}catch(e){
		passed=true;
	}
	return passed && typeof JSON=='object' ;
}


text:
<?php

namespace Olousouzian\AtlasBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('OlousouzianAtlasBundle:Default:index.html.twig');
    }
}


text:
Clazz.declarePackage ("J.adapter.readers.simple");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.simple.AmpacReader", ["JU.P3"], function () {
c$ = Clazz.decorateAsClass (function () {
this.atomCount = 0;
this.freqAtom0 = -1;
this.partialCharges = null;
this.atomPositions = null;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.simple, "AmpacReader", J.adapter.smarter.AtomSetCollectionReader);
$_V(c$, "checkLine",
function () {
if (this.line.indexOf ("CARTESIAN COORDINATES") >= 0) {
if (!this.doGetModel (++this.modelNumber, null)) return this.checkLastModel ();
this.readCoordinates ();
return true;
}if (!this.doProcessLines) return true;
if (this.line.indexOf ("NET ATOMIC CHARGES") >= 0) {
this.readPartialCharges ();
return true;
}if (this.line.indexOf ("VIBRATIONAL FREQUENCIES") >= 0) {
this.readFrequencies ();
return true;
}return true;
});
$_M(c$, "readCoordinates",
($fz = function () {
var haveFreq = (this.freqAtom0 >= 0);
if (haveFreq) {
this.atomPositions =  new Array (this.atomCount);
} else {
this.atomSetCollection.newAtomSet ();
}this.readLine ();
this.atomCount = 0;
while (this.readLine () != null) {
var tokens = this.getTokens ();
if (tokens.length < 5) break;
if (haveFreq) {
this.atomPositions[this.atomCount] = JU.P3.new3 (this.parseFloatStr (tokens[2]), this.parseFloatStr (tokens[3]), this.parseFloatStr (tokens[4]));
} else {
var symbol = tokens[1];
var atom = this.atomSetCollection.addNewAtom ();
atom.elementSymbol = symbol;
this.setAtomCoordXYZ (atom, this.parseFloatStr (tokens[2]), this.parseFloatStr (tokens[3]), this.parseFloatStr (tokens[4]));
}this.atomCount++;
}
if (haveFreq) this.setPositions ();
}, $fz.isPrivate = true, $fz));
$_M(c$, "setPositions",
($fz = function () {
var maxAtom = this.atomSetCollection.getAtomCount ();
var atoms = this.atomSetCollection.getAtoms ();
for (var i = this.freqAtom0; i < maxAtom; i++) {
atoms[i].setT (this.atomPositions[i % this.atomCount]);
atoms[i].partialCharge = this.partialCharges[i % this.atomCount];
}
}, $fz.isPrivate = true, $fz));
$_M(c$, "readPartialCharges",
($fz = function () {
this.readLine ();
this.partialCharges =  Clazz.newFloatArray (this.atomCount, 0);
var tokens;
for (var i = 0; i < this.atomCount; i++) {
if (this.readLine () == null || (tokens = this.getTokens ()).length < 4) break;
this.partialCharges[i] = this.parseFloatStr (tokens[2]);
}
}, $fz.isPrivate = true, $fz));
$_M(c$, "readFrequencies",
($fz = function () {
while (this.readLine () != null && this.line.indexOf ("FREQ  :") < 0) {
}
while (this.line != null && this.line.indexOf ("FREQ  :") >= 0) {
var frequencies = this.getTokens ();
while (this.readLine () != null && this.line.indexOf ("IR I") < 0) {
}
var iAtom0 = this.atomSetCollection.getAtomCount ();
if (this.vibrationNumber == 0) this.freqAtom0 = iAtom0;
var frequencyCount = frequencies.length - 2;
var ignore =  Clazz.newBooleanArray (frequencyCount, false);
for (var i = 0; i < frequencyCount; ++i) {
ignore[i] = !this.doGetVibration (++this.vibrationNumber);
if (ignore[i]) continue;
this.atomSetCollection.cloneLastAtomSet ();
this.atomSetCollection.setAtomSetName (frequencies[i + 2] + " cm^-1");
this.atomSetCollection.setAtomSetModelProperty ("Frequency", frequencies[i + 2] + " cm^-1");
this.atomSetCollection.setAtomSetModelProperty (".PATH", "Frequencies");
}
this.fillFrequencyData (iAtom0, this.atomCount, this.atomCount, ignore, false, 8, 9, null, 0);
this.readLine ();
this.readLine ();
}
}, $fz.isPrivate = true, $fz));
});


text:
package org.eclipse.php.core.tests.markoccurrence;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.php.core.tests.AbstractPDTTTest;
import org.eclipse.php.core.tests.PHPCoreTests;
import org.eclipse.php.core.tests.PdttFile;
import org.eclipse.php.internal.core.PHPVersion;
import org.eclipse.php.internal.core.ast.locator.PhpElementConciliator;
import org.eclipse.php.internal.core.ast.nodes.ASTNode;
import org.eclipse.php.internal.core.ast.nodes.ASTParser;
import org.eclipse.php.internal.core.ast.nodes.Identifier;
import org.eclipse.php.internal.core.ast.nodes.Program;
import org.eclipse.php.internal.core.corext.dom.NodeFinder;
import org.eclipse.php.internal.core.project.PHPNature;
import org.eclipse.php.internal.core.project.ProjectOptions;
import org.eclipse.php.internal.core.search.IOccurrencesFinder;
import org.eclipse.php.internal.core.search.IOccurrencesFinder.OccurrenceLocation;
import org.eclipse.php.internal.core.search.OccurrencesFinderFactory;

public class MarkOccurrenceTests extends AbstractPDTTTest {

	protected static final char OFFSET_CHAR = '|';
	protected static final Map<PHPVersion, String[]> TESTS = new LinkedHashMap<PHPVersion, String[]>();
	static {
		TESTS.put(PHPVersion.PHP5,
				new String[] { "/workspace/markoccurrence/php5" });
		TESTS.put(PHPVersion.PHP5_3, new String[] {
				"/workspace/markoccurrence/php5",
				"/workspace/markoccurrence/php53" });
		TESTS.put(PHPVersion.PHP5_4, new String[] {
				"/workspace/markoccurrence/php5",
				"/workspace/markoccurrence/php53",
				"/workspace/markoccurrence/php54" });
	};

	protected static IProject project;
	protected static IFile testFile;

	public static void setUpSuite() throws Exception {
		project = ResourcesPlugin.getWorkspace().getRoot()
				.getProject("MarkOccurrenceTests");
		if (project.exists()) {
			return;
		}

		project.create(null);
		project.open(null);

		// configure nature
		IProjectDescription desc = project.getDescription();
		desc.setNatureIds(new String[] { PHPNature.ID });
		project.setDescription(desc, null);
	}

	public static void tearDownSuite() throws Exception {
		project.close(null);
		project.delete(true, true, null);
		project = null;
	}

	public MarkOccurrenceTests(String description) {
		super(description);
	}

	public static Test suite() {

		TestSuite suite = new TestSuite("Auto Mark Occurrence Tests");

		for (final PHPVersion phpVersion : TESTS.keySet()) {
			TestSuite phpVerSuite = new TestSuite(phpVersion.getAlias());

			for (String testsDirectory : TESTS.get(phpVersion)) {

				for (final String fileName : getPDTTFiles(testsDirectory)) {
					try {
						final PdttFile pdttFile = new PdttFile(fileName);
						phpVerSuite.addTest(new MarkOccurrenceTests(phpVersion
								.getAlias() + " - /" + fileName) {

							protected void setUp() throws Exception {
								PHPCoreTests.setProjectPhpVersion(project,
										phpVersion);
								pdttFile.applyPreferences();
							}

							protected void tearDown() throws Exception {
								if (testFile != null) {
									testFile.delete(true, null);
									testFile = null;
								}
							}

							protected void runTest() throws Throwable {
								// OccurrenceLocation[] proposals =
								// getProposals(pdttFile
								// .getFile());
								compareProposals(pdttFile.getFile());
							}
						});
					} catch (final Exception e) {
						phpVerSuite.addTest(new TestCase(fileName) { // dummy
									// test
									// indicating
									// PDTT
									// file
									// parsing
									// failure
									protected void runTest() throws Throwable {
										throw e;
									}
								});
					}
				}
			}
			suite.addTest(phpVerSuite);
		}

		// Create a setup wrapper
		TestSetup setup = new TestSetup(suite) {
			protected void setUp() throws Exception {
				setUpSuite();
			}

			protected void tearDown() throws Exception {
				tearDownSuite();
			}
		};
		return setup;
	}

	/**
	 * Creates test file with the specified content and calculates the offset at
	 * OFFSET_CHAR. Offset character itself is stripped off.
	 *
	 * @param data
	 *            File data
	 * @return offset where's the offset character set.
	 * @throws Exception
	 */
	protected static void compareProposals(String data) throws Exception {

		int offset = data.lastIndexOf(OFFSET_CHAR);
		if (offset == -1) {
			throw new IllegalArgumentException("Offset character is not set");
		}
		List<Integer> starts = new ArrayList<Integer>();
		int startIndex = -1;
		while ((startIndex = data.indexOf('%', startIndex + 1)) >= 0) {
			starts.add(startIndex);
		}
		if (starts.size() % 2 != 0) {
			throw new IllegalArgumentException("% must be paired");
		}
		List<Integer> newStarts = new ArrayList<Integer>();
		for (int i = 0; i < starts.size(); i++) {
			int oldstart = starts.get(i) - i;
			if (oldstart > offset) {
				oldstart--;
			}
			newStarts.add(oldstart);
		}
		// replace the offset character
		data = data.replaceAll("%", "");

		offset = data.lastIndexOf(OFFSET_CHAR);
		// replace the offset character
		data = data.substring(0, offset) + data.substring(offset + 1);

		testFile = project.getFile("test.php");
		testFile.create(new ByteArrayInputStream(data.getBytes()), true, null);
		project.refreshLocal(IResource.DEPTH_INFINITE, null);
		project.build(IncrementalProjectBuilder.FULL_BUILD, null);

		PHPCoreTests.waitForIndexer();
		// PHPCoreTests.waitForAutoBuild();
		Program astRoot = createProgramFromSource(testFile);
		ASTNode selectedNode = NodeFinder.perform(astRoot, offset, 0);
		OccurrenceLocation[] locations = null;
		if (selectedNode != null
				&& (selectedNode instanceof Identifier || (isScalarButNotInString(selectedNode)))) {
			int type = PhpElementConciliator.concile(selectedNode);
			if (markOccurrencesOfType(type)) {
				IOccurrencesFinder finder = OccurrencesFinderFactory
						.getOccurrencesFinder(type);
				if (finder != null) {
					if (finder.initialize(astRoot, selectedNode) == null) {
						locations = finder.getOccurrences();
					}
				}
			}
		}
		compareProposals(locations, newStarts);
		// return locations;
	}

	/**
	 * Returns is the occurrences of the type should be marked.
	 *
	 * @param type
	 *            One of the {@link PhpElementConciliator} constants integer
	 *            type.
	 * @return True, if the type occurrences should be marked; False, otherwise.
	 */
	public static boolean markOccurrencesOfType(int type) {
		switch (type) {
		case PhpElementConciliator.CONCILIATOR_GLOBAL_VARIABLE:
		case PhpElementConciliator.CONCILIATOR_LOCAL_VARIABLE:
		case PhpElementConciliator.CONCILIATOR_FUNCTION:
		case PhpElementConciliator.CONCILIATOR_CLASSNAME:
		case PhpElementConciliator.CONCILIATOR_CONSTANT:
		case PhpElementConciliator.CONCILIATOR_CLASS_MEMBER:
			return true;
		case PhpElementConciliator.CONCILIATOR_UNKNOWN:
		case PhpElementConciliator.CONCILIATOR_PROGRAM:
		default:
			return false;
		}
	}

	/**
	 * Checks whether or not the node is a scalar and return true only if the
	 * scalar is not part of a string
	 *
	 * @param node
	 * @return
	 */
	public static boolean isScalarButNotInString(ASTNode node) {
		return (node.getType() == ASTNode.SCALAR)
				&& (node.getParent().getType() != ASTNode.QUOTE);
	}

	public static Program createProgramFromSource(IFile file) throws Exception {
		ISourceModule source = DLTKCore.createSourceModuleFrom(file);
		return createProgramFromSource(source);
	}

	public static Program createProgramFromSource(ISourceModule source)
			throws Exception {
		PHPVersion version;
		if (project != null) {
			version = ProjectOptions.getPhpVersion(project);
		} else {
			version = ProjectOptions.getDefaultPhpVersion();
		}
		ASTParser newParser = ASTParser.newParser(version,
				(ISourceModule) source);
		return newParser.createAST(null);
	}

	protected static ISourceModule getSourceModule() {
		return DLTKCore.createSourceModuleFrom(testFile);
	}

	public static void compareProposals(OccurrenceLocation[] proposals,
			List<Integer> starts) throws Exception {
		// String[] lines = pdttFile.getExpected().split("\n");
		proposals = olderLocations(proposals);
		boolean proposalsEqual = true;
		if (proposals.length == starts.size() / 2) {
			for (int i = 0; i < proposals.length; i++) {
				if (!(proposals[i].getOffset() == starts.get(i * 2) && (proposals[i]
						.getOffset() + proposals[i].getLength()) == starts
						.get(i * 2 + 1))) {
					proposalsEqual = false;
					break;
				}
			}
		} else if (proposals == null && starts.size() == 0) {
			// proposalsEqual = true;
		} else {
			proposalsEqual = false;
		}

		if (!proposalsEqual) {
			StringBuilder errorBuf = new StringBuilder();
			errorBuf.append("\nEXPECTED COMPLETIONS LIST:\n-----------------------------\n");
			for (int i = 0; i < starts.size() / 2; i++) {
				errorBuf.append('[').append(starts.get(i * 2)).append(',')
						.append(starts.get(i * 2 + 1) - starts.get(i * 2))
						.append(']').append("\n");
			}
			errorBuf.append("\nACTUAL COMPLETIONS LIST:\n-----------------------------\n");
			for (OccurrenceLocation p : proposals) {
				errorBuf.append('[').append(p.getOffset()).append(',')
						.append(p.getLength()).append(']').append("\n");
			}
			fail(errorBuf.toString());
		}
	}

	private static OccurrenceLocation[] olderLocations(
			OccurrenceLocation[] proposals) {
		if (proposals == null) {
			return new OccurrenceLocation[0];
		}
		List<OccurrenceLocation> result = new ArrayList<OccurrenceLocation>();

		for (int i = 0; i < proposals.length; i++) {
			result.add(proposals[i]);
		}
		Collections.sort(result, new Comparator<OccurrenceLocation>() {

			public int compare(OccurrenceLocation o1, OccurrenceLocation o2) {

				return o1.getOffset() - o2.getOffset();
			}
		});
		return result.toArray(new OccurrenceLocation[result.size()]);
	}
}


text:
package com.google.common.graph;

import static com.google.common.graph.TestUtil.ERROR_ELEMENT_NOT_IN_GRAPH;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.common.testing.AbstractPackageSanityTests;
import junit.framework.AssertionFailedError;

/**
 * Covers basic sanity checks for the entire package.
 *
 * @author Kurt Alfred Kluever
 */

public class PackageSanityTests extends AbstractPackageSanityTests {

  private static final AbstractGraphBuilder<?> GRAPH_BUILDER_A =
      GraphBuilder.directed().expectedNodeCount(10);
  private static final AbstractGraphBuilder<?> GRAPH_BUILDER_B =
      ValueGraphBuilder.directed().allowsSelfLoops(true).expectedNodeCount(16);

  private static final ImmutableGraph<String> IMMUTABLE_GRAPH_A =
      GraphBuilder.directed().<String>immutable().addNode("A").build();
  private static final ImmutableGraph<String> IMMUTABLE_GRAPH_B =
      GraphBuilder.directed().<String>immutable().addNode("B").build();

  private static final NetworkBuilder<?, ?> NETWORK_BUILDER_A =
      NetworkBuilder.directed().allowsParallelEdges(true).expectedNodeCount(10);
  private static final NetworkBuilder<?, ?> NETWORK_BUILDER_B =
      NetworkBuilder.directed().allowsSelfLoops(true).expectedNodeCount(16);

  private static final ImmutableNetwork<String, String> IMMUTABLE_NETWORK_A =
      NetworkBuilder.directed().<String, String>immutable().addNode("A").build();
  private static final ImmutableNetwork<String, String> IMMUTABLE_NETWORK_B =
      NetworkBuilder.directed().<String, String>immutable().addNode("B").build();

  public PackageSanityTests() {
    setDistinctValues(AbstractGraphBuilder.class, GRAPH_BUILDER_A, GRAPH_BUILDER_B);
    setDistinctValues(Graph.class, IMMUTABLE_GRAPH_A, IMMUTABLE_GRAPH_B);
    setDistinctValues(NetworkBuilder.class, NETWORK_BUILDER_A, NETWORK_BUILDER_B);
    setDistinctValues(Network.class, IMMUTABLE_NETWORK_A, IMMUTABLE_NETWORK_B);
    setDefault(EndpointPair.class, EndpointPair.ordered("A", "B"));
  }

  @Override
  public void testNulls() throws Exception {
    try {
      super.testNulls();
    } catch (AssertionFailedError e) {
      assertWithMessage("Method did not throw null pointer OR element not in graph exception.")
          .that(e)
          .hasCauseThat()
          .hasMessageThat()
          .contains(ERROR_ELEMENT_NOT_IN_GRAPH);
    }
  }
}


text:
package deewiant.ammunition.guns.common;

import java.awt.geom.Point2D;

import robocode.util.Utils;

import deewiant.common.Enemy;
import deewiant.common.Global;
import deewiant.common.Tools;

// http://www-128.ibm.com/developerworks/library/j-circular/
public final class Circulinear {
	private Circulinear() {}

	public static double calculate(
		final Enemy dude,
		final double bulletSpeed,
		final boolean circular
	) {
		Point2D guess = new Point2D.Double(dude.x, dude.y);

		if (!Tools.zero(dude.velocity)) {
			for (int i = 10; i-- > 0;) {
				final long time =
					Global.bot.getTime() +
					Math.round(Global.me.distance(guess) / bulletSpeed);

				if (circular)
					guess = dude.guessCircularPosition(time);
				else
					guess = dude.guessLinearPosition  (time);
			}
		}

		return Utils.normalAbsoluteAngle(Tools.atan2(guess, Global.me));
	}
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="fill"
    android:padding="@dimen/layoutMargin1">

    <TextView
        android:id="@+id/itemServerId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:maxLines="1"
        android:textSize="@dimen/textSize2"
        android:visibility="gone" />

    <TextView
        android:id="@+id/itemServerUrl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/itemServerId"
        android:text="@string/defaultHttpServer"
        android:textSize="@dimen/textSize2" />

    <!-- TODO: This could be used to indicate the default server -->

    <TextView
        android:id="@+id/itemServerStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:text="@string/middot"
        android:textColor="@color/green1"
        android:textSize="@dimen/textSize3"
        android:visibility="gone" />

</RelativeLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0">
    <channel>
        <title>McKinley Health Center</title>
        <link>http://illinois.edu/calendar/list/44</link>
        <description>McKinley Health Center Calendar</description>
    </channel>
</rss>


text:
#ifndef __NGEN_STATICDELEGATE_HPP
#define __NGEN_STATICDELEGATE_HPP

#include "Ngen.Delegate.hpp"
#include "Ngen.Cast.hpp"

namespace Ngen {
	/** @brief A non-member static function without a return argument.
	 */
   template<typename... TParams>
   class StaticDelegate : public VoidDelegate<TParams...> {
   public:
      /** @brief Native function signature. */
      typedef void(TFunction)(TParams...);

		/** @brief A type redefinition of the expanded delegate typename. */
      typedef StaticDelegate<TParams...> TSelf;

		/** @brief Constructor. Default. */
		StaticDelegate() : mFunction(0) {}

		/** @brief Constructor. (TFunction). */
      StaticDelegate(TFunction func) {
         mFunction = func;
      }

		/** @brief Constructor. Copy. */
      StaticDelegate(const StaticDelegate<TParams...>& copy) : mFunction(copy.mFunction) {}

		/** @brief De-constructor. */
      ~StaticDelegate() {

      }

		/** @brief Determines if the Delegate is equal-to another delegate. */
      virtual bool EqualTo(Delegate* rhs) const {
         if(rhs->IsMember() || rhs->IsNonVoid()) {
            return false;
         }

         return ((TSelf*)rhs)->mFunction == mFunction;
      }

		/** @brief operator!=(const Delegate* const). */
      bool operator!=(const Delegate* const rhs) {
         if(rhs->IsMember() || rhs->IsNonVoid()) {
            return true;
         }

         return ((TSelf*)rhs)->mFunction != mFunction;
      }

		/** @brief operator=(const Delegate* const). */
      TSelf& operator=(const TSelf& rhs) {
         if(this == &rhs) {
				return *this;
         }

         mFunction = rhs.mFunction;
         return *this;
      }

		/** @brief operator()(unknown, unknown*). */
      unknown operator()(unknown _this, unknown* params) {
			_Call(params, typename make_index_pack_t<sizeof...(TParams)>::type());
			return null;
      }

		/** @brief Determines if the delegate references a constant-member function. */
      bool IsConst() const { return false; }

		/** @brief Determines if the delegate references a member function. */
      bool IsMember() const { return false; }

		/** @brief Gets the number of parameters needed to perform a valid invocation. */
		uword Length() const { return sizeof...(TParams); }

		/** @brief Invokes the function being referenced by the delegate. */
      void Call(TParams... params) {
			mFunction(params...);
      }

   protected:
   	template<uword... I> void _Call(unknown* params, index_pack_t<I...>) {
			Call((Cast<TParams>::From(params[I]))...);
   	}

      TFunction* mFunction;
   };

   template<typename TReturn, typename... TParams>
   class NonVoidStaticDelegate : public NonVoidDelegate<TReturn, TParams...> {
   public:
      /** @brief Native function signature. */
      typedef TReturn(TFunction)(TParams...);

      typedef NonVoidStaticDelegate<TParams...> TSelf;

		NonVoidStaticDelegate() : mFunction(0) {}

      NonVoidStaticDelegate(TFunction func) {
         mFunction = func;
      }

      ~NonVoidStaticDelegate() {

      }

		/** @brief Determines if the Delegate is equal-to another delegate. */
      virtual bool EqualTo(Delegate* rhs) const {
         if(rhs->IsMember() || !rhs->IsNonVoid()) {
            return false;
         }

         return ((TSelf*)rhs)->mFunction == mFunction;
      }

      /** @brief operator=(const Delegate* const). */
      TSelf& operator=(const TSelf& rhs) {
         if(this == &rhs) {
				return *this;
         }

         mFunction = rhs->mFunction;
         return *this;
      }

		unknown operator()(unknown _this, unknown* params) {
			TReturn ret = _Call(params, typename make_index_pack_t<sizeof...(TParams)>::type());
			return Cast<TReturn>::To(ret);
      }

      bool IsConst() const { return false; }

      bool IsMember() const { return false; }

      TReturn Call(TParams... params) {
         return mFunction(params...);
      }

   protected:
   	template<uword... I>
   	TReturn _Call(unknown* params, index_pack_t<I...>) {
			return Call((Cast<TParams>::From(params[I]))...);
   	}

      TFunction* mFunction;
   };
}
#endif // __NGEN_STATICDELEGATE_HPP


text:
<?xml version="1.0" encoding="utf-8"?>
<beans class="org.wikiup.modules.jsp.JspServletContainer">
	<bean name="el" class="org.wikiup.core.impl.el.TemplateExpressionLanguage" variable-pattern="#{}"/>
	<bean name="servletConfig" class="org.wikiup.modules.jsp.JspServletConfig">
		<property name="javaEncoding" value="utf-8"/>
		<property name="compilerTargetVM" value="1.5"/>
		<property name="compilerSourceVM" value="1.5"/>
	</bean>
	<bean name="jspServlet" class="org.wikiup.modules.jsp.JspServlet"/>
</beans>


text:
<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repository\LogRepository;
use Carbon\Carbon;

class LogSuccessfulLogin
{
    public $request;

    public $logger;

    /**
     * LogSuccessfulLogin constructor.
     * @param Request $request
     * @param LogRepository $logger
     */
    public function __construct(Request $request, LogRepository $logger)
    {
        $this->request = $request;
        $this->logger = $logger;
    }

    /**
     * @param Login $event
     */
    public function handle(Login $event)
    {
        $event->user->last_login_at = Carbon::now();
        $event->user->ip = $this->request->ip();
        $event->user->save();
        $attributes = [
            'userid'       =>  $event->user->id,
            'username'      =>  $event->user->name,
            'httpuseragent' => $_SERVER['HTTP_USER_AGENT'],
            'sessionid'     => session()->getId(),
            'ip'            => getClientIps()
        ];
        $this->logger->log($attributes);
    }
}


text:
<?php

namespace Addvilz\CorrelationCalculatorBundle\CorrelationCalculator;

class SampleValidationException extends \InvalidArgumentException
{
    /**
     * @var \Exception
     */
    private $previous;

    /**
     * @param \Exception $previous
     */
    public function __construct($message, \Exception $previous)
    {
        parent::__construct($message);
        $this->previous = $previous;
    }
}


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

SYNOPSIS

DESCRIPTION

Accessors

Methods

Archive::Tar::File->new( file => $path )

Archive::Tar::File->new( data => $path, $data, $opt )

Archive::Tar::File->new( chunk => $chunk )

$bool = $file->extract( [ $alternative_name ] )

$path = $file->full_path

$bool = $file->validate

$bool = $file->has_content

$content = $file->get_content

$cref = $file->get_content_by_ref

$bool = $file->replace_content( $content )

$bool = $file->rename( $new_name )

$bool = $file->chmod $mode)

$bool = $file->chown( $user [, $group])

Convenience methods

NAME

Archive::Tar::File - a subclass for in-memory extracted file from Archive::Tar

SYNOPSIS

    my @items = $tar->get_files;

    print $_->name, ' ', $_->size, "\n" for @items;

    print $object->get_content;
    $object->replace_content('new content');

    $object->rename( 'new/full/path/to/file.c' );

DESCRIPTION

Archive::Tar::Files provides a neat little object layer for in-memory extracted files. It's mostly used internally in Archive::Tar to tidy up the code, but there's no reason users shouldn't use this API as well.

Accessors

A lot of the methods in this package are accessors to the various fields in the tar header:

name

The file's name

mode

The file's mode

uid

The user id owning the file

gid

The group id owning the file

size

File size in bytes

mtime

Modification time. Adjusted to mac-time on MacOS if required

chksum

Checksum field for the tar header

type

File type -- numeric, but comparable to exported constants -- see Archive::Tar's documentation

linkname

If the file is a symlink, the file it's pointing to

magic

Tar magic string -- not useful for most users

version

Tar version string -- not useful for most users

uname

The user name that owns the file

gname

The group name that owns the file

devmajor

Device major number in case of a special file

devminor

Device minor number in case of a special file

prefix

Any directory to prefix to the extraction path, if any

raw

Raw tar header -- not useful for most users

Methods

Archive::Tar::File->new( file => $path )

Returns a new Archive::Tar::File object from an existing file.

Returns undef on failure.

Archive::Tar::File->new( data => $path, $data, $opt )

Returns a new Archive::Tar::File object from data.

$path defines the file name (which need not exist), $data the file contents, and $opt is a reference to a hash of attributes which may be used to override the default attributes (fields in the tar header), which are described above in the Accessors section.

Returns undef on failure.

Archive::Tar::File->new( chunk => $chunk )

Returns a new Archive::Tar::File object from a raw 512-byte tar archive chunk.

Returns undef on failure.

$bool = $file->extract( [ $alternative_name ] )

Extract this object, optionally to an alternative name.

See Archive::Tar->extract_file for details.

Returns true on success and false on failure.

$path = $file->full_path

Returns the full path from the tar header; this is basically a concatenation of the prefix and name fields.

$bool = $file->validate

Done by Archive::Tar internally when reading the tar file: validate the header against the checksum to ensure integer tar file.

Returns true on success, false on failure

$bool = $file->has_content

Returns a boolean to indicate whether the current object has content. Some special files like directories and so on never will have any content. This method is mainly to make sure you don't get warnings for using uninitialized values when looking at an object's content.

$content = $file->get_content

Returns the current content for the in-memory file

$cref = $file->get_content_by_ref

Returns the current content for the in-memory file as a scalar reference. Normal users won't need this, but it will save memory if you are dealing with very large data files in your tar archive, since it will pass the contents by reference, rather than make a copy of it first.

$bool = $file->replace_content( $content )

Replace the current content of the file with the new content. This only affects the in-memory archive, not the on-disk version until you write it.

Returns true on success, false on failure.

$bool = $file->rename( $new_name )

Rename the current file to $new_name.

Note that you must specify a Unix path for $new_name, since per tar standard, all files in the archive must be Unix paths.

Returns true on success and false on failure.

$bool = $file->chmod $mode)

Change mode of $file to $mode. The mode can be a string or a number which is interpreted as octal whether or not a leading 0 is given.

Returns true on success and false on failure.

$bool = $file->chown( $user [, $group])

Change owner of $file to $user. If a $group is given that is changed as well. You can also pass a single parameter with a colon separating the use and group as in 'root:wheel'.

Returns true on success and false on failure.

Convenience methods

To quickly check the type of a Archive::Tar::File object, you can use the following methods:

$file->is_file

Returns true if the file is of type file

$file->is_dir

Returns true if the file is of type dir

$file->is_hardlink

Returns true if the file is of type hardlink

$file->is_symlink

Returns true if the file is of type symlink

$file->is_chardev

Returns true if the file is of type chardev

$file->is_blockdev

Returns true if the file is of type blockdev

$file->is_fifo

Returns true if the file is of type fifo

$file->is_socket

Returns true if the file is of type socket

$file->is_longlink

Returns true if the file is of type LongLink. Should not happen after a successful read.

$file->is_label

Returns true if the file is of type Label. Should not happen after a successful read.

$file->is_unknown

Returns true if the file type is unknown


text:
package gov.hhs.fha.nhinc.subscription.repository.service;

import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerException;
import gov.hhs.fha.nhinc.hiem.dte.EndpointReferenceHelper;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.properties.PropertyAccessException;
import gov.hhs.fha.nhinc.properties.PropertyAccessor;
import org.w3._2005._08.addressing.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author rayj
 */
public class ConnectSubscriptionReferenceHelper {

    public static final String REFERENCE_PARAMETER_SUBSCRIPTION_ID_NAMESPACE = "http://www.hhs.gov/healthit/nhin";
    public static final String REFERENCE_PARAMETER_SUBSCRIPTION_ID_ELEMENT_NAME = "SubscriptionId";
    private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
            .getLog(HiemSubscriptionRepositoryService.class);

    public EndpointReferenceType createSubscriptionReference(String subscriptionId) {
        String url = getSubscriptionManagerEndpointAddress();
        EndpointReferenceHelper helper = new EndpointReferenceHelper();
        EndpointReferenceType subscriptionReference = helper.createEndpointReferenceAddressOnly(url);
        helper.attachSimpleReferenceParameter(subscriptionReference, REFERENCE_PARAMETER_SUBSCRIPTION_ID_NAMESPACE,
                REFERENCE_PARAMETER_SUBSCRIPTION_ID_ELEMENT_NAME, subscriptionId);
        return subscriptionReference;
    }

    // todo: move to common location
    private String getSubscriptionManagerEndpointAddress() {
        String subMgrUrl = null;
        String homeCommunityId = null;
        try {
            log.info("Attempting to retrieve property: " + NhincConstants.HOME_COMMUNITY_ID_PROPERTY
                    + " from property file: " + NhincConstants.GATEWAY_PROPERTY_FILE);
            homeCommunityId = PropertyAccessor.getInstance().getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                    NhincConstants.HOME_COMMUNITY_ID_PROPERTY);
            log.info("Retrieve local home community id: " + homeCommunityId);
        } catch (PropertyAccessException ex) {
            log.error("Error: Failed to retrieve " + NhincConstants.HOME_COMMUNITY_ID_PROPERTY
                    + " from property file: " + NhincConstants.GATEWAY_PROPERTY_FILE);
            log.error(ex.getMessage());
        }

        if (NullChecker.isNotNullish(homeCommunityId)) {
            try {
                subMgrUrl = ConnectionManagerCache.getInstance().getInternalEndpointURLByServiceName(
                		NhincConstants.HIEM_SUBSCRIPTION_MANAGER_SERVICE_NAME);
            } catch (ConnectionManagerException ex) {
                log.error("Error: Failed to retrieve url for service: "
                        + NhincConstants.HIEM_SUBSCRIPTION_MANAGER_SERVICE_NAME + " for community id: "
                        + homeCommunityId);
                log.error(ex.getMessage());
            }
        }
        return subMgrUrl;
    }
}


text:
import React, { useEffect } from "react";
import Slider from "../../components/slider/";
import { connect } from "react-redux";
import * as actions from "./store/actions";
import RecommendList from "../../components/list/";
import Scroll from "../../baseUI/scroll/index";
import { Content } from "./style";
import { forceCheck } from "react-lazyload";
import { renderRoutes } from "react-router-config";
import { EnterLoading } from "./../Singers/style";
import Loading from "../../baseUI/loading-v2/index";

function Recommend(props) {
  const { bannerList, recommendList, songsCount, enterLoading } = props;

  const { getBannerDataDispatch, getRecommendListDataDispatch } = props;

  useEffect(() => {
    if (!bannerList.size) {
      getBannerDataDispatch();
    }
    if (!recommendList.size) {
      getRecommendListDataDispatch();
    }
    // eslint-disable-next-line
  }, []);

  const bannerListJS = bannerList ? bannerList.toJS() : [];
  const recommendListJS = recommendList ? recommendList.toJS() : [];

  return (
    <Content play={songsCount}>
      <Scroll className="list" onScroll={forceCheck}>
        <div>
          <Slider bannerList={bannerListJS}></Slider>
          <RecommendList recommendList={recommendListJS}></RecommendList>
        </div>
      </Scroll>
      {enterLoading ? (
        <EnterLoading>
          <Loading></Loading>
        </EnterLoading>
      ) : null}
      {renderRoutes(props.route.routes)}
    </Content>
  );
}

// 映射Redux全局的state到组件的props上
const mapStateToProps = (state) => ({
  bannerList: state.getIn(["recommend", "bannerList"]),
  recommendList: state.getIn(["recommend", "recommendList"]),
  songsCount: state.getIn(["player", "playList"]).size,
  enterLoading: state.getIn(["recommend", "enterLoading"]),
});
// 映射dispatch到props上
const mapDispatchToProps = (dispatch) => {
  return {
    getBannerDataDispatch() {
      dispatch(actions.getBannerList());
    },
    getRecommendListDataDispatch() {
      dispatch(actions.getRecommendList());
    },
  };
};

// 将ui组件包装成容器组件
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(React.memo(Recommend));


text:
* `stack setup`
* `stack build`

## Generate the purescript code for the servant API

* `stack exec PSGenerator`

## Build the frontend

* `cd frontend`
* Install npm
* Install bower and pulp via npm
* Run `npm install`
* Run `npm run build`

## Run the server

* `stack exec central-counter`
* Visit http://localhost:8081/index.html in multiple browser windows and click `+` and `-`.
* Have fun!


text:
GnuplotRB is a plot generator for Ruby based on
[Gnuplot](http://www.gnuplot.info).

This software has been developed as a product in Google Summer of Code 2015 (GSoC2015). Its progress may be saw in [SciRuby mailing list](https://groups.google.com/forum/?fromgroups#!topic/sciruby-dev/lhWvb5hWc3k) or in [project's blog](http://www.evgrafov.work/gnuplotrb/).

[![Gem Version](https://badge.fury.io/rb/gnuplotrb.svg)](https://badge.fury.io/rb/gnuplotrb)
[![Dependency Status](https://gemnasium.com/badges/github.com/SciRuby/gnuplotrb.svg)](https://gemnasium.com/github.com/SciRuby/gnuplotrb)
[![Build Status](https://travis-ci.org/SciRuby/gnuplotrb.svg?branch=master)](https://travis-ci.org/SciRuby/gnuplotrb)
[![Code Climate](https://codeclimate.com/github/SciRuby/gnuplotrb/badges/gpa.svg)](https://codeclimate.com/github/SciRuby/gnuplotrb)
[![Test Coverage](https://codeclimate.com/github/SciRuby/gnuplotrb/badges/coverage.svg)](https://codeclimate.com/github/SciRuby/gnuplotrb/coverage)

## Table of contents
* [Installation](https://github.com/sciruby/gnuplotrb#installation)
* [Getting started](https://github.com/sciruby/gnuplotrb#getting-started)
  - [Plottable classes](https://github.com/sciruby/gnuplotrb#plottable-classes)
  - [Notebooks](https://github.com/sciruby/gnuplotrb#notebooks)
  - [Plain examples](https://github.com/sciruby/gnuplotrb#plain-examples)
* [Contributing](https://github.com/sciruby/gnuplotrb#contributing)

## Installation
### Dependencies
*   Ruby 2.0+
*   It is required to install [gnuplot 5.0](http://www.gnuplot.info/download.html) to use that gem.

### Gem installation
#### Install latest stable version from Rubygems

```sh
gem install gnuplotrb
```

#### Install latest stable version using bundler
* add `gem gnuplotrb` to your `Gemfile`
* run `bundle install`

#### Install latest version from source (may be unstable)

```sh
git clone https://github.com/sciruby/gnuplotrb.git
cd gnuplotrb
bundle install
rake install
```

## Getting started
GnuplotRB gem is based on [Gnuplot](http://www.gnuplot.info/) so I would recommend to use [Gnuplot doc](http://www.gnuplot.info/docs_5.0/gnuplot.pdf) and [GnuplotRB doc at Rubydoc](https://rubygems.org/gems/gnuplotrb) in cases when docs and examples (as notebooks and plain examples) present here are not enough to explain how to plot something.

### Plottable classes
Each of plottable classes may be outputted to image file using ```#to_png```, ```#to_svg```, ```#to_gif``` and so on methods. You can read more about it in [GnuplotRB doc](https://rubygems.org/gems/gnuplotrb) related to Plottable module or see examples in [beginners
notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/basic_usage.ipynb).

#### Dataset
Single dataset may be created with math formula ('sin(x)') or some data. If your data is stored in a file you can just pass a filename (e.g. 'gnuplotrb.data'). Dataset may also be constructed out of data contained in Ruby classes (Array, Daru containers), see [example notebooks](https://github.com/sciruby/gnuplotrb#possible-datasources).

Dataset have several possible options which are explained in [gnuplot
doc](http://www.gnuplot.info/docs_5.0/gnuplot.pdf) (pp. 80-102). Options are passed to Dataset.new as hash and are tranlated into gnuplot format before plotting:

```ruby
Dataset.new(data, with: 'lines', using: '1:2')
```

Examples of option translation (nested containers allowed):

* Hash:

```ruby
{ key1: "value1", key2: { nested_key1: "nested_value1" } } # => "key1 value1 key2 nested key1 nested_value1"
```

* Hashes with underscored keys (see [#7](https://github.com/dilcom/gnuplotrb/issues/7)):

```ruby
{ style_data: 'histograms' } #=> "style data histograms"
```

* Range:

```ruby
{ xrange: 0..100 } # => "xrange [0:100]"
```

* Array (often used with nested hashes) and Array of Numeric

```ruby
['png', { size: [400, 500] }] # => "png size 400,500"
```

* Others

```ruby
some_object # => some_object.to_s
```

Once Dataset created, it may be updated with new data or options. Methods related to updating are explained in [a notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/updating_data.ipynb).

Just as other Plottable object Dataset has several plotting methods which are desribed in [beginners notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/basic_usage.ipynb).

#### Plot
Plot is a container for several datasets and layout options:
```ruby
Plot.new(ds1, ds2, ds2, xrange: 1..10)
```

Datasets contained bu Plot are outputted on single xy plain.

Plot's options are explained in [gnuplot doc](http://www.gnuplot.info/docs_5.0/gnuplot.pdf) (pp. 105-181). Plot options are translated into gnuplot format the same way as Dataset's (except adding 'set' before each option). Plot's datasets and Plot itself may be updated with almost the same methods as desribed in Dataset section above.

#### Splot
Almost the same as Plot but for 3-D plots. See Plot section.

#### Multiplot

Container for several Plot or Splot objects, each of them is plotted in its own xy(z) space. So Multiplot offers single layout (image filewindow) for several plots. It's grid is tuned by :layout option, and you can also set layout's title:
```ruby
Multiplot.new(plot1, plot2, splot1, layout: [3, 1], title: 'Three plots on a layout')
```

Updating methods for Multiplot are almost the same as Plot's and Dataset's and are covered in Multiplot's docs and [multiplot notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/multiplot_layout.ipynb). See examples there.

#### Animation

Animation is a container for several Plot, Splot or Multiplot objects. Each of contained items is considered as frame in gif animation which is creating by ```#plot``` call. Animation's frames and options may be modifyed or updated just as other classes above. Animation does not support methods like ```#to_png``` and may be plotted only with ```#plot``` method. Please see [related notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/animated_plots.ipynb) and docs at RubyDoc for examples.

### Notebooks

This notebooks are powered by [Ruby kernel](https://github.com/SciRuby/iruby/) for [IPython/Jupyter](https://jupyter.org/). I placed them here to show some GnuplotRB's capabilities and ways of using it together with iRuby.

To use GnuplotRB gem with iRuby you need to install them both.

* iRuby installation is covered in its [README](https://github.com/SciRuby/iruby/blob/master/README.md). It also covers installation of iPython and other dependecies.
* GnuplotRB gem installation covered in [README](https://github.com/sciruby/gnuplotrb#installation) too.

#### Embedding plots into iRuby
Using GnuplotRB inside iRuby notebooks is covered in:

* [Basic usage notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/basic_usage.ipynb).

#### 2D and 3D plots
GnuplotRB is capable to plot vast range of plots from histograms to 3D
heatmaps. Gem's repository contains examples of several plot types:

* [Heatmaps](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/heatmaps.ipynb)
* [Vectorfield](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/vector_field.ipynb) (Thanks, [Alexej](https://github.com/agisga))
* [Math equations](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/math_plots.ipynb)
* [3D visualizations](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/3d_plot.ipynb)
* [Histogram](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/histogram.ipynb)

#### Possible datasources
GnuplotRB may take data in Ruby container or in a file. Supported containers
for now are `Array`, `Daru::Vector` and `Daru::DataFrame`. When data given in file,
GnuplotRB pass filename to Gnuplot **without** reading the file into memory.

Examples of using different datasources:

* [Data given in file or Ruby Array](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/points_from_different_sources.ipynb)
* [Data given in Daru containers](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/plotting_from_daru.ipynb)
* [Data given in Daru containers (with timeseries)](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/time_series_from_daru.ipynb)
* [Updating plots with new data](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/updating_data.ipynb)

#### Multiplot
You can not only plot several datasets in single coordinate system but place
several coordinate systems on a canvas.

* [Multiplot example notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/multiplot_layout.ipynb).

#### Animation
It's possible to use several plots (Plot, Splot or Multiplot objects) to create gif animation.

* [Animation example notebook](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/animated_plots.ipynb).

#### Fitting data with formula
GnuplotRB also may be used to fit some data with given math formula.

* [Fitting data](http://nbviewer.ipython.org/github/sciruby/gnuplotrb/blob/master/notebooks/fitting_data.ipynb)

### Plain examples
You may find several examples in [examples directory](https://github.com/sciruby/gnuplotrb/tree/master/examples).

## Contributing

1.  [Fork repository](https://github.com/sciruby/gnuplotrb/fork)
2.  Create your feature branch (`git checkout -b my-new-feature`)
3.  Commit your changes (`git commit -am 'Add some feature'`)
4.  Push to the branch (`git push origin my-new-feature`)
5.  Create a new Pull Request


text:
/**
 *          Date: Dec 13, 2005
 *          Time: 12:33:48
 */

package org.apache.harmony.test.func.api.java.lang.Thread.getAllStackTraces.getAllStackTraces20.getAllStackTraces2020;

import org.apache.harmony.share.Test;

import java.security.Permission;

public class getAllStackTraces2020 extends Test {
    public static final String TESTED_THREAD_NAME = "SecurityManagerTestThread";

    volatile static boolean tStop = false;

    class locSecurityManager extends SecurityManager{
/* This Security Manager blocks any access to the thtread wint given name */
        private String prohibitedThreadGroupName;
        public locSecurityManager( String prohibitedThreadGroupName){
            super();
            this.prohibitedThreadGroupName = prohibitedThreadGroupName;
        }

        public void checkAccess(ThreadGroup tg){
            if( tg.getName().equals( prohibitedThreadGroupName ))
                throw new SecurityException( "Acces denied to ThreadGroup "+ tg.getName() +
                        " by SecurityManager " + getClass().getName());
            else
                super.checkAccess( tg );
        }

        public void checkPermission( Permission perm ){
            info(" started checkPermission( " + perm +" )from Security Manager " + getClass().getName());
            if( perm.equals( new RuntimePermission("setSecurityManager") ) ) {
                log.info("checking RuntimePermission( " + perm.getName()+ " ): PERMITTED");
            } else if( perm.equals( new RuntimePermission("getStackTrace") ) ) {
                log.info("checking RuntimePermission( " + perm.getName()+ " ): PERMITTED");
            } else if( perm.equals( new RuntimePermission("modifyThreadGroup") ) ) {
                log.info("checking RuntimePermission( " + perm.getName()+ " ): PROHIBITED");
                throw new SecurityException();
            } else {
                //super.checkPermission( perm );
              return;
            }
        }
    }

    public static void main(String args[]) {
        System.exit(new getAllStackTraces2020().test());
    }

    public int test() {
        info( getClass().getName() );
        if( ! checkJavaVersionGreateOrEqual(1.5)  ){
            return fail("Test has not been started.");
        }
        SecurityManager ts = new locSecurityManager( Thread.currentThread().getThreadGroup().getName() );
        SecurityManager sSM = System.getSecurityManager();
        info( "System Security Manager is: " + sSM );

        Thread[] tarray  =  {null};
        System.setSecurityManager( ts );
        info( "System Security Manager was changed to: " + System.getSecurityManager());
        try{
            Thread.getAllStackTraces();
            tStop = true;
            System.setSecurityManager( sSM );
            info( "System Security Manager has been changed to: " + System.getSecurityManager());
            return fail( "Expected SecurityException has NOT been thrown" );
        }catch( SecurityException se ){
            tStop = true;
            System.setSecurityManager( sSM );
            info( "System Security Manager has been changed to: " + System.getSecurityManager());
            return pass( "Expected SecurityException has been thrown" );
        }
    }

    void info(String text){
        log.info( text );
//        System.out.println(text); System.out.flush();
    }
    public boolean checkJavaVersionGreateOrEqual( double checkedVer ){
        double ver = Float.parseFloat( System.getProperties().getProperty("java.version").substring(0,3) );
        if( ver >= checkedVer )
            return true;
        else {
            info("Java version:\t"+ System.getProperties().getProperty("java.version"));
            info("Test supports java version " +checkedVer+ " and higher");
            return false;
        }
    }
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;

namespace Delta.Input.States
{
    public sealed class KeyboardInputState
    {
        static readonly Keys[] _keyIndices = new Keys[256];
#if WINDOWS
        static readonly uint[] _scanCodes = new uint[256];
        static readonly byte[] _keyStateBytes = new byte[256];

        static IntPtr _layout;

        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, out char pwszBuff, int cchBuff, uint wFlags, IntPtr layout);
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern uint MapVirtualKeyEx(uint uCode, uint uMapType, IntPtr layout);
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern IntPtr GetKeyboardLayout(uint thread);
#else
		private static char[] _chatpadGreenMapping = new char[256];
		private static char[] _chatpadOrangeMapping = new char[256];
#endif

        Button[] _buttons = new Button[256];
        float _initialTick = -1;
        KeyState _state;
        KeyMap _currentFrame;
        KeyMap _previousFrame;

        static KeyboardInputState()
        {
            System.Reflection.FieldInfo[] enums = typeof(Keys).GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            List<Keys> keys = new List<Keys>();
            List<Keys> controlKeys = new List<Keys>();

            foreach (System.Reflection.FieldInfo field in enums)
            {
                Keys key = (Keys)field.GetValue(null);
                keys.Add(key);
                if (char.IsControl((char)key))
                    controlKeys.Add(key);
            }

#if WINDOWS
            _layout = GetKeyboardLayout(0);

            for (int scan = 0; scan < 255; scan++)
            {
                uint key = MapVirtualKeyEx((uint)scan, 1, _layout);
                if (key != 0)
                    _scanCodes[key] = (uint)scan;
            }
#else
			char[] map = _chatpadGreenMapping;

			map['q'] = '!';
			map['w'] = '@';
			map['e'] = (char)8364;//'euro';
			map['r'] = '#';
			map['t'] = '%';
			map['y'] = '^';
			map['U'] = '&';
			map['I'] = '*';
			map['o'] = '(';
			map['p'] = ')';
			map['a'] = '~';
			map['s'] = (char)353;
			map['d'] = '{';
			map['f'] = '}';
			map['g'] = (char)168;
			map['h'] = '/';
			map['j'] = (char)903;
			map['k'] = '[';
			map['l'] = ']';
			map[','] = ':';
			map['z'] = (char)729;
			map['x'] = (char)0x00AB;
			map['c'] = (char)0x00BB;
			map['v'] = '-';
			map['b'] = '|';
			map['n'] = '<';
			map['m'] = '>';
			map['.'] = '?';

			map = _chatpadOrangeMapping;
			map['q'] = (char)0x00EC;
			map['w'] = (char)0x00E3;
			map['e'] = (char)0x00E9;
			map['r'] = '$';
			map['t'] = (char)0x00DE;
			map['y'] = (char)0x00FD;
			map['U'] = (char)0x00FA;
			map['I'] = (char)0x00ED;
			map['o'] = (char)0x00F3;
			map['p'] = '=';
			map['a'] = (char)0x00E1;
			map['s'] = (char)0x00DF;
			map['d'] = (char)0x00F4;
			map['f'] = (char)0x00A3;
			map['g'] = (char)0x00A5;
			map['h'] = '\\';
			map['j'] = '\"';
			map['k'] = '$';
			map['l'] = (char)0x00F8;
			map[','] = ';';
			map['z'] = (char)0x00E6;
			map['x'] = (char)0x0153;
			map['c'] = (char)0x00E7;
			map['v'] = '_';
			map['b'] = '+';
			map['n'] = (char)0x00F1;
			map['m'] = (char)0x00B5;
			map['.'] = (char)0x00BF;
#endif
            _keyIndices = keys.ToArray();
        }

        internal KeyboardInputState()
        {
            _state = new KeyState(_buttons);
            for (int x = 0; x < 256; x++)
                _buttons[x] = new Button();
        }

        public static Keys[] GetKeyArray()
        {
            return (Keys[])_keyIndices.Clone();
        }

        public bool TryGetKeyChar(Keys key, out char keyChar)
        {
#if XBOX360
			keyChar = (char)key;
			if (this.KeyState.ChatPadGreen && _chatpadGreenMapping[(int)key] != '\0')
				keyChar = char.ToUpper(_chatpadGreenMapping[(int)key]);
			if (this.KeyState.ChatPadOrange && _chatpadOrangeMapping[(int)key] != '\0')
				keyChar = char.ToUpper(_chatpadOrangeMapping[(int)key]);
			if (!(this.KeyState.LeftShift | this.KeyState.RightShift))
				keyChar = char.ToLower(keyChar);
			return char.IsLetterOrDigit(keyChar) || char.IsPunctuation(keyChar) || char.IsWhiteSpace(keyChar);
#else
            keyChar = '\0';
            _keyStateBytes[0x10] = (byte)((KeyState.LeftShift.IsDown | KeyState.RightShift.IsDown) ? 0x80 : 0);
            _keyStateBytes[0x11] = (byte)((KeyState.LeftControl.IsDown | KeyState.RightControl.IsDown) ? 0x80 : 0);
            return ToUnicodeEx((uint)key, _scanCodes[(uint)key], _keyStateBytes, out keyChar, 1, 0, _layout) == 1;
#endif
        }

        public KeyState KeyState { get { return _state; } }

        public static implicit operator KeyboardState(KeyboardInputState input)
        {
            return input._currentFrame.state;
        }

        public Button this[Keys key] { get { return _buttons[(int)key]; } }

        public bool IsDown(Keys key)
        {
            return _buttons[(int)key].IsDown;
        }

        //public bool IsDown(Keys key, float duration)
        //{
        //    return _buttons[(int)key].IsDown && _buttons[(int)key].DownDuration >= duration;
        //}

        public bool IsUp(Keys key)
        {
            return !_buttons[(int)key].IsDown;
        }

        //public bool IsUp(Keys key, float duration)
        //{
        //    return !_buttons[(int)key] && _buttons[(int)key].UpDuration >= duration;
        //}

        public bool IsPressed(Keys key)
        {
            return _buttons[(int)key].IsPressed;
        }

        public bool IsReleased(Keys key)
        {
            return _buttons[(int)key].IsReleased;
        }

        internal void Update(DeltaGameTime time, ref KeyboardState keyboardState)
        {
            if (_initialTick <= -1)
            {
                _initialTick = time.TotalSeconds;
                _currentFrame.state = keyboardState;
            }

            time.TotalSeconds -= _initialTick;

            _previousFrame.state = _currentFrame.state;
            _currentFrame.state = keyboardState;

            for (int i = 0; i < 32; i++)
            {
                _buttons[32 * 0 + i].SetState((_currentFrame.currentState0 & ((uint)1) << i) != 0, time);
                _buttons[32 * 1 + i].SetState((_currentFrame.currentState1 & ((uint)1) << i) != 0, time);
                _buttons[32 * 2 + i].SetState((_currentFrame.currentState2 & ((uint)1) << i) != 0, time);
                _buttons[32 * 3 + i].SetState((_currentFrame.currentState3 & ((uint)1) << i) != 0, time);
                _buttons[32 * 4 + i].SetState((_currentFrame.currentState4 & ((uint)1) << i) != 0, time);
                _buttons[32 * 5 + i].SetState((_currentFrame.currentState5 & ((uint)1) << i) != 0, time);
                _buttons[32 * 6 + i].SetState((_currentFrame.currentState6 & ((uint)1) << i) != 0, time);
                _buttons[32 * 7 + i].SetState((_currentFrame.currentState7 & ((uint)1) << i) != 0, time);
            }
        }

        public void KeyDown(Action<Keys> callback)
        {
            if (_currentFrame.currentState0 != 0) HeldCallback(callback, 0);
            if (_currentFrame.currentState1 != 0) HeldCallback(callback, 1);
            if (_currentFrame.currentState2 != 0) HeldCallback(callback, 2);
            if (_currentFrame.currentState3 != 0) HeldCallback(callback, 3);
            if (_currentFrame.currentState4 != 0) HeldCallback(callback, 4);
            if (_currentFrame.currentState5 != 0) HeldCallback(callback, 5);
            if (_currentFrame.currentState6 != 0) HeldCallback(callback, 6);
            if (_currentFrame.currentState7 != 0) HeldCallback(callback, 7);
        }

        public void KeyPressed(Action<Keys> callback)
        {
            if (_currentFrame.currentState0 != _previousFrame.currentState0) PressCallback(callback, 0);
            if (_currentFrame.currentState1 != _previousFrame.currentState1) PressCallback(callback, 1);
            if (_currentFrame.currentState2 != _previousFrame.currentState2) PressCallback(callback, 2);
            if (_currentFrame.currentState3 != _previousFrame.currentState3) PressCallback(callback, 3);
            if (_currentFrame.currentState4 != _previousFrame.currentState4) PressCallback(callback, 4);
            if (_currentFrame.currentState5 != _previousFrame.currentState5) PressCallback(callback, 5);
            if (_currentFrame.currentState6 != _previousFrame.currentState6) PressCallback(callback, 6);
            if (_currentFrame.currentState7 != _previousFrame.currentState7) PressCallback(callback, 7);
        }

        public void KeyUp(Action<Keys> callback)
        {
            if (_currentFrame.currentState0 != _previousFrame.currentState0) ReleaseCallback(callback, 0);
            if (_currentFrame.currentState1 != _previousFrame.currentState1) ReleaseCallback(callback, 1);
            if (_currentFrame.currentState2 != _previousFrame.currentState2) ReleaseCallback(callback, 2);
            if (_currentFrame.currentState3 != _previousFrame.currentState3) ReleaseCallback(callback, 3);
            if (_currentFrame.currentState4 != _previousFrame.currentState4) ReleaseCallback(callback, 4);
            if (_currentFrame.currentState5 != _previousFrame.currentState5) ReleaseCallback(callback, 5);
            if (_currentFrame.currentState6 != _previousFrame.currentState6) ReleaseCallback(callback, 6);
            if (_currentFrame.currentState7 != _previousFrame.currentState7) ReleaseCallback(callback, 7);
        }

        //public void GetPressedKeys(List<Keys> pressedList)
        //{
        //    pressedList.Clear();
        //    if (_currentFrame.currentState0 != _previousFrame.currentState0) PressList(pressedList, 0);
        //    if (_currentFrame.currentState1 != _previousFrame.currentState1) PressList(pressedList, 1);
        //    if (_currentFrame.currentState2 != _previousFrame.currentState2) PressList(pressedList, 2);
        //    if (_currentFrame.currentState3 != _previousFrame.currentState3) PressList(pressedList, 3);
        //    if (_currentFrame.currentState4 != _previousFrame.currentState4) PressList(pressedList, 4);
        //    if (_currentFrame.currentState5 != _previousFrame.currentState5) PressList(pressedList, 5);
        //    if (_currentFrame.currentState6 != _previousFrame.currentState6) PressList(pressedList, 6);
        //    if (_currentFrame.currentState7 != _previousFrame.currentState7) PressList(pressedList, 7);
        //}

        //public void GetHeldKeys(List<Keys> heldKeyList)
        //{
        //    heldKeyList.Clear();
        //    if (_currentFrame.currentState0 != 0) HeldList(heldKeyList, 0);
        //    if (_currentFrame.currentState1 != 0) HeldList(heldKeyList, 1);
        //    if (_currentFrame.currentState2 != 0) HeldList(heldKeyList, 2);
        //    if (_currentFrame.currentState3 != 0) HeldList(heldKeyList, 3);
        //    if (_currentFrame.currentState4 != 0) HeldList(heldKeyList, 4);
        //    if (_currentFrame.currentState5 != 0) HeldList(heldKeyList, 5);
        //    if (_currentFrame.currentState6 != 0) HeldList(heldKeyList, 6);
        //    if (_currentFrame.currentState7 != 0) HeldList(heldKeyList, 7);
        //}

        void PressCallback(Action<Keys> callback, int group)
        {
            for (int i = 0; i < 32; i++)
                if (_buttons[32 * group + i].IsPressed)
                    callback((Keys)(32 * group + i));
        }

        void ReleaseCallback(Action<Keys> callback, int group)
        {
            for (int i = 0; i < 32; i++)
                if (_buttons[32 * group + i].IsReleased)
                    callback((Keys)(32 * group + i));
        }

        void HeldCallback(Action<Keys> callback, int group)
        {
            for (int i = 0; i < 32; i++)
                if (_buttons[32 * group + i].IsDown)
                    callback((Keys)(32 * group + i));
        }

        //void PressList(List<Keys> list, int group)
        //{
        //    for (int i = 0; i < 32; i++)
        //        if (_buttons[32 * group + i].IsPressed)
        //            list.Add((Keys)(32 * group + i));
        //}
        //void HeldList(List<Keys> list, int group)
        //{
        //    for (int i = 0; i < 32; i++)
        //        if (_buttons[32 * group + i].IsDown)
        //            list.Add((Keys)(32 * group + i));
        //}
    }
}


text:
namespace hollow {

struct SNES : public Object {
  GEODE_DECLARE_TYPE(HOLLOW_EXPORT)
  typedef Object Base;
  typedef PetscReal T;

  const ::SNES snes;

protected:
  SNES(const MPI_Comm comm);
  SNES(const ::SNES snes); // Steals ownership
public:
  ~SNES();

  MPI_Comm comm() const;

  void set_from_options();

  void set_dm(const DM& dm);

  // Set Jacobian matrices:
  //   A: Approximate Jacobian matrix
  //   B: Matrix used to construct the preconditioner (usually the same)
  void set_jacobian(const Mat& A, const Mat& P);

  // Solve the nonlinear system F(x) = b
  //   b: RHS, or null for b = 0
  //   x: Initial guess and solution
  void solve(Ptr<const Vec> b, Vec& x);

  int iterations() const;

  // Compute objective (which must exist)
  T objective(const Vec& x) const;

  // Compute function
  void residual(const Vec& x, Vec& f) const;

  // Do we have various functions?
  bool has_objective() const;
  bool has_jacobian() const;

  // Compare residuals and jacobians to finite differences
  void consistency_test(const Vec& x, const T small, const T rtol, const T atol, const int steps) const;

  // Add an additional monitoring routine
  void add_monitor(const function<void(int,T)>& monitor);
};

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  c
  r123::Engine

Searching...

No Matches


text:
package org.insightech.er.editor.model.diagram_contents.element.node.table.index;

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

import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.Column;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.CopyColumn;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn;

public class CopyIndex extends Index {

	private static final long serialVersionUID = -7896024413398953097L;

	private Index originalIndex;

	public CopyIndex(ERTable copyTable, Index originalIndex,
			List<Column> copyColumns) {
		super(copyTable, originalIndex.getName(), originalIndex.isNonUnique(),
				originalIndex.getType(), originalIndex.getDescription());

		this.originalIndex = originalIndex;

		List<Boolean> descs = originalIndex.getDescs();

		int i = 0;

		for (NormalColumn originalIndexColumn : originalIndex.getColumns()) {
			Boolean desc = Boolean.FALSE;

			if (descs.size() > i) {
				desc = descs.get(i);
			}

			if (copyColumns != null) {

				boolean isGroupColumn = true;

				for (Column column : copyColumns) {
					if (column instanceof CopyColumn) {
						CopyColumn copyColumn = (CopyColumn) column;

						if (copyColumn.getOriginalColumn().equals(
								originalIndexColumn)) {
							this.addColumn(copyColumn, desc);
							isGroupColumn = false;
							break;
						}
					}
				}

				if (isGroupColumn) {
					this.addColumn(originalIndexColumn, desc);
				}

			} else {
				this.addColumn(originalIndexColumn, desc);
			}

			i++;
		}
	}

	public Index getRestructuredIndex(ERTable originalTable) {
		if (this.originalIndex == null) {
			this.originalIndex = new Index(originalTable, this.getName(), this
					.isNonUnique(), this.getType(), this.getDescription());
		}

		copyData(this, this.originalIndex);

		List<NormalColumn> indexColumns = new ArrayList<NormalColumn>();

		for (NormalColumn column : this.originalIndex.getColumns()) {
			if (column instanceof CopyColumn) {
				CopyColumn copyColumn = (CopyColumn) column;
				column = copyColumn.getOriginalColumn();
			}
			indexColumns.add(column);
		}

		this.originalIndex.setColumns(indexColumns);
		this.originalIndex.setTable(originalTable);

		return this.originalIndex;
	}

	public static void copyData(Index from, Index to) {
		to.setName(from.getName());
		to.setNonUnique(from.isNonUnique());
		to.setFullText(from.isFullText());
		to.setType(from.getType());
		to.setDescription(from.getDescription());

		to.clearColumns();

		List<Boolean> descs = from.getDescs();
		int i = 0;

		for (NormalColumn column : from.getColumns()) {
			Boolean desc = Boolean.FALSE;

			if (descs.size() > i) {
				desc = descs.get(i);
			}
			to.addColumn(column, desc);
			i++;
		}

	}

}


text:
/*
 * File:   main.cpp
 * Author: Ale Strooisma
 *
 * Created on July 10, 2015, 5:35 PM
 */

#include <cstdlib>
#include <iostream>
#include <unistd.h>

#include "Controller.hpp"
#include "Raid.hpp"
#include "Ship.hpp"
#include "Player.hpp"

using namespace std;

/*
 * Test program for Craftworld: Raiders
 */
int main(int argc, char** argv) {
	cout << "Hello CraftWorld!" << endl;

	Controller controller;
	Ship ship;
	Raid raid(&ship);
	Player player("Oebele");
	bool exit = false;

	controller.startRaid(&raid, &player);
//	raid.setCurrentRoom(raid.getShip()->openDoor());

	cout << "> ";
	for (string line; !exit && getline(cin, line);) {
		if (~isatty(STDIN_FILENO)) {
			cout << line << endl;
		}
		if (line == "exit") {
			exit = true;
		} else {
			controller.processCommand(&player, line);
			cout << "> ";
		}
    }

	return 0;
}


text:
local Vector = require('./vector')
local Wave = require('./wave')

local waves = {}

function love.load()
  width = love.graphics.getWidth()
  height = love.graphics.getHeight()

  -- Creates a magic bridge
  --for i=0, 0.1, 0.02 do
    --table.insert(waves, Wave.new(i))
  --end

  for i=1, 5 do
    local r = love.math.random(0, 100)

    table.insert(waves, Wave.new(r))
  end
end

function love.draw()
  for i,v in ipairs(waves) do
    v:display()
  end
end

function love.update(dt)
  if dt > 0.029 then dt = 0.029 end

  for i,v in ipairs(waves) do
    v:update()
  end
end


text:
package org.jdna.sage.api.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import org.apache.log4j.Logger;

import sagex.SageAPI;

public class SageCommandEnumGenerator {
	private static final Logger log = Logger.getLogger(SageCommandEnumGenerator.class);

	private String packageName;
	private String className;
	private File outFile;
	private File outDir;
	private PrintWriter pw = null;

	public SageCommandEnumGenerator(File srcDir, String packageName, String className) {
		this.packageName = packageName + ".enums";
		this.className = className+"Enum";
		outDir = new File(srcDir, this.packageName.replaceAll("\\.", "/") + "/");
	}

	public void generate() throws Exception {
		outDir.mkdirs();
		outFile = new File(outDir, className + ".java");

		System.out.println("Creating Java: " + outFile.getAbsolutePath());

		pw = new PrintWriter(new FileWriter(outFile));
		pw.printf("package %s;\n\n", packageName);

		pw.println("/**");
		pw.println(" * Unofficial SageTV Generated File - Never Edit");
		pw.println(" * Generated Date/Time: " + new SimpleDateFormat().format(new Date()));
		pw.printf(" * See Official Sage Documentation at %s\n", className, className);
		pw.println(" * This Generated API is not Affiliated with SageTV.  It is user contributed.");
		pw.println(" */");

		pw.printf("public enum %s {\n", className);

		Vector v = getCommandNames();
		for (int i=0;i<v.size();i++) {
		    if (i>0) {
		        pw.println(",");
		    }
		    String name = ((String)v.get(i));
		    name = name.replaceAll("/", "Or");
		    name = name.replaceAll("[^a-zA-Z0-9]", "");
		    if ("-".equals(v.get(i))) {
		        name="Dash";
		    }
		    pw.printf("%s(\"%s\")", name, v.get(i));
		}
		pw.println(";");

		pw.println("\n\nprivate String command;");
		pw.printf("private %s(String cmd) {\n", className);
		pw.println("this.command =cmd;");
		pw.println("}");

		pw.println("public String command() { return command; }");
		pw.println("\n}");

		pw.close();
		pw.flush();
	}

	public Vector getCommandNames() {
		// no longer need to call into sagetv for this, we can use the contstant
		// Vector v = (Vector) SageAPI.call("GetSageCommandNames", null);
		java.util.Vector rv = new java.util.Vector(java.util.Arrays.asList(sage.UserEvent.PRETTY_UENAMES));
		rv.remove(0); // ?
		rv.remove(0); // ?
		rv.remove(rv.size() - 1); // Anything
		return rv;
	}
}