text:
package org.apache.commons.vfs2.provider.zip;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.junit.Assert;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

public class ZipFileObjectTest {

    private static final String NESTED_FILE_1 = "/read-xml-tests/file1.xml";
    private static final String NESTED_FILE_2 = "/read-xml-tests/file2.xml";

    private void assertDelete(final File fileObject) {
        Assert.assertTrue("Could not delete file", fileObject.delete());
    }

    private File createTempFile() throws IOException {
        final File zipFile = new File("src/test/resources/test-data/read-xml-tests.zip");
        final File newZipFile = File.createTempFile(getClass().getSimpleName(), ".zip");
        newZipFile.deleteOnExit();
        FileUtils.copyFile(zipFile, newZipFile);
        return newZipFile;
    }

    private void getInputStreamAndAssert(final FileObject fileObject, final String expectedId)
            throws FileSystemException, IOException {
        readAndAssert(fileObject, fileObject.getContent().getInputStream(), expectedId);
    }

    private void readAndAssert(final FileObject fileObject, final InputStream inputStream, final String expectedId)
            throws IOException {
        final String streamData = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        final String fileObjectString = fileObject.toString();
        Assert.assertNotNull(fileObjectString, streamData);
        Assert.assertEquals(
                fileObjectString, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<Root"
                        + expectedId + ">foo" + expectedId + "</Root" + expectedId + ">\r\n",
                streamData);
    }

    private void resolveReadAssert(final FileObject zipFileObject, final String path)
            throws IOException, FileSystemException {
        try (FileObject zipFileObject2 = zipFileObject.resolveFile(path)) {
            try (InputStream inputStream = zipFileObject2.getContent().getInputStream()) {
                readAndAssert(zipFileObject2, inputStream, "2");
            }
        }
    }

    /**
     * Tests that when we read a file inside a file Zip and leave it open, we can still delete the Zip after we clean up
     * the Zip file.
     *
     * @throws IOException
     */
    @Test
    @Disabled("Shows that leaving a stream open and not closing any resource leaves the container file locked")
    public void testLeaveNestedFileOpen() throws IOException {
        final File newZipFile = createTempFile();
        final FileSystemManager manager = VFS.getManager();
        try (FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
            @SuppressWarnings({ "resource" })
            final FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
            getInputStreamAndAssert(zipFileObject1, "1");
        }
        assertDelete(newZipFile);
    }

    /**
     * Tests that we can read more than one file within a Zip file, especially after closing each FileObject.
     *
     * @throws IOException
     */
    @Test
    public void testReadingFilesInZipFile() throws IOException {
        final File newZipFile = createTempFile();
        final FileSystemManager manager = VFS.getManager();
        try (FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
            try (FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1)) {
                try (InputStream inputStream = zipFileObject1.getContent().getInputStream()) {
                    readAndAssert(zipFileObject1, inputStream, "1");
                }
            }
            resolveReadAssert(zipFileObject, NESTED_FILE_2);
        }
        assertDelete(newZipFile);
    }

    /**
     * Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
     * process the initial input stream.
     *
     * @throws IOException
     */
    @Test
    public void testReadingOneAfterClosingAnotherFile() throws IOException {
        final File newZipFile = createTempFile();
        final FileSystemManager manager = VFS.getManager();
        final FileObject zipFileObject1;
        final InputStream inputStream1;
        try (FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
            // leave resources open
            zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
            inputStream1 = zipFileObject1.getContent().getInputStream();
        }
        // The zip file is "closed", but we read from the stream now.
        readAndAssert(zipFileObject1, inputStream1, "1");
        // clean up
        zipFileObject1.close();
        assertDelete(newZipFile);
    }

    /**
     * Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
     * process the initial input stream. If our internal reference counting is correct, the test passes.
     *
     * @throws IOException
     */
    @Test
    public void testReadingOneAfterClosingAnotherStream() throws IOException {
        final File newZipFile = createTempFile();
        final FileSystemManager manager = VFS.getManager();
        final FileObject zipFileObject1;
        final InputStream inputStream1;
        try (FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
            // leave resources open (note that internal counters are updated)
            zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
            inputStream1 = zipFileObject1.getContent().getInputStream();
            resolveReadAssert(zipFileObject, NESTED_FILE_2);
        }
        // The Zip file is "closed", but we read from the stream now, which currently fails.
        // Why aren't internal counters preventing the stream from closing?
        readAndAssert(zipFileObject1, inputStream1, "1");
        // clean up
        zipFileObject1.close();
        assertDelete(newZipFile);
    }

    /**
     * Test read file with special name in a zip file
     */
    @Test
    public void testReadSpecialNameFileInZipFile() throws FileSystemException {

        final File testFile = new File("src/test/resources/test-data/special_fileName.zip");
        final String[] fileNames = {"file.txt", "file^.txt", "file~.txt", "file?.txt", "file@.txt", "file$.txt",
                                    "file*.txt", "file&.txt", "file#.txt", "file%.txt", "file!.txt"};
        final FileSystemManager manager = VFS.getManager();
        final String baseUrl = "zip:file:"+testFile.getAbsolutePath();

        // test
        try (FileObject fileObject = manager.resolveFile(baseUrl)) {
            // test getChildren() number equal
            Assert.assertEquals(fileObject.getChildren().length, fileNames.length);

            // test getChild(String)
            for (final String fileName : fileNames) {
                Assert.assertNotNull("can't read file " + fileName, fileObject.getChild(fileName));
            }
        }
    }

    /**
     * Tests that we can resolve a file in a Zip file, then close the container zip, which should still let us delete
     * the Zip file.
     *
     * @throws IOException
     */
    @Test
    public void testResolveNestedFileWithoutCleanup() throws IOException {
        final File newZipFile = createTempFile();
        final FileSystemManager manager = VFS.getManager();
        try (FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
            @SuppressWarnings({ "unused", "resource" })
            // We resolve a nested file and do nothing else.
            final FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
        }
        assertDelete(newZipFile);
    }

}


text:
/**
 * @author gurnoor
 * S & H algorithm
 */

package nl.esciencecenter.qtm.abbreviation;

import java.io.BufferedReader;
import java.io.StringReader;

import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import nl.esciencecenter.qtm.Main;

public class Abbreviator {

	private HashMap mTestDefinitions = new HashMap();
	private HashMap mStats = new HashMap();
	private int truePositives = 0, falsePositives = 0, falseNegatives = 0,
			trueNegatives = 0;
	private char delimiter = '\t';
	private boolean testMode = false;

	private boolean isValidShortForm(String str) {
		return (hasLetter(str) && (Character.isLetterOrDigit(str.charAt(0))
				|| (str.charAt(0) == '(')));
	}

	private boolean hasLetter(String str) {
		for (int i = 0; i < str.length(); i++)
			if (Character.isLetter(str.charAt(i)))
				return true;
		return false;
	}

	private boolean hasCapital(String str) {
		for (int i = 0; i < str.length(); i++)
			if (Character.isUpperCase(str.charAt(i)))
				return true;
		return false;
	}

	private boolean isTrueDefinition(String shortForm, String longForm) {
		Vector entry;
		Iterator itr;

		entry = (Vector) mTestDefinitions.get(shortForm);
		if (entry == null)
			return false;
		itr = entry.iterator();
		while (itr.hasNext()) {
			if (itr.next().toString().equalsIgnoreCase(longForm))
				return true;
		}
		return false;
	}

	public HashMap<String, String> extractAbbrPairs(String text) {

		HashMap<String, String> abbrev = new HashMap<String, String>();

		String str, tmpStr, longForm = "", shortForm = "";
		String currSentence = "";
		int openParenIndex, closeParenIndex = -1, sentenceEnd,
				newCloseParenIndex, tmpIndex = -1;
		boolean newParagraph = true;
		StringTokenizer shortTokenizer;
		try {
			BufferedReader fin = new BufferedReader(new StringReader(text));
			while ((str = fin.readLine()) != null) {
				if (str.length() == 0 || newParagraph
						&& !Character.isUpperCase(str.charAt(0))) {
					currSentence = "";
					newParagraph = true;
					continue;
				}
				newParagraph = false;
				str += " ";
				currSentence += str;
				openParenIndex = currSentence.indexOf(" (");
				do {
					if (openParenIndex > -1)
						openParenIndex++;
					sentenceEnd = Math.max(currSentence.lastIndexOf(". "),
							currSentence.lastIndexOf(", "));
					if ((openParenIndex == -1) && (sentenceEnd == -1)) {
						// Do nothing
					} else if (openParenIndex == -1) {
						currSentence = currSentence.substring(sentenceEnd + 2);
					} else if ((closeParenIndex = currSentence.indexOf(')',
							openParenIndex)) > -1) {
						sentenceEnd = Math.max(
								currSentence.lastIndexOf(". ", openParenIndex),
								currSentence.lastIndexOf(", ", openParenIndex));
						if (sentenceEnd == -1)
							sentenceEnd = -2;
						longForm = currSentence.substring(sentenceEnd + 2,
								openParenIndex);
						shortForm = currSentence.substring(openParenIndex + 1,
								closeParenIndex);
					}
					if (shortForm.length() > 0 || longForm.length() > 0) {
						if (shortForm.length() > 1 && longForm.length() > 1) {
							if ((shortForm.indexOf('(') > -1)
									&& ((newCloseParenIndex = currSentence
											.indexOf(')', closeParenIndex
													+ 1)) > -1)) {
								shortForm = currSentence.substring(
										openParenIndex + 1, newCloseParenIndex);
								closeParenIndex = newCloseParenIndex;
							}
							if ((tmpIndex = shortForm.indexOf(", ")) > -1)
								shortForm = shortForm.substring(0, tmpIndex);
							if ((tmpIndex = shortForm.indexOf("; ")) > -1)
								shortForm = shortForm.substring(0, tmpIndex);
							shortTokenizer = new StringTokenizer(shortForm);
							if (shortTokenizer.countTokens() > 2
									|| shortForm.length() > longForm.length()) {
								// Long form in ( )
								tmpIndex = currSentence.lastIndexOf(" ",
										openParenIndex - 2);
								tmpStr = currSentence.substring(tmpIndex + 1,
										openParenIndex - 1);
								longForm = shortForm;
								shortForm = tmpStr;
								if (!hasCapital(shortForm))
									shortForm = "";
							}
							if (isValidShortForm(shortForm)) {
								HashMap<String, String> singlePair = extractAbbrPair(
										getOnlyStrings(shortForm.trim()),
										longForm.trim());
								abbrev.putAll(singlePair);

							}
						}
						currSentence = currSentence
								.substring(closeParenIndex + 1);
					} else if (openParenIndex > -1) {
						if ((currSentence.length() - openParenIndex) > 200)
							// Matching close paren was not found
							currSentence = currSentence
									.substring(openParenIndex + 1);
						break; // Read next line
					}
					shortForm = "";
					longForm = "";
				} while ((openParenIndex = currSentence.indexOf(" (")) > -1);
			}
			fin.close();
		} catch (Exception ioe) {
			ioe.printStackTrace();
			Main.logger.error(currSentence);
			Main.logger.error(tmpIndex);
		}

		return abbrev;
	}

	public static String getOnlyStrings(String s) {
		Pattern pattern = Pattern.compile("[^a-z A-Z]");
		Matcher matcher = pattern.matcher(s);
		String number = matcher.replaceAll("");
		return number;
	}

	private String findBestLongForm(String shortForm, String longForm) {
		int sIndex;
		int lIndex;
		char currChar;

		sIndex = shortForm.length() - 1;
		lIndex = longForm.length() - 1;
		for (; sIndex >= 0; sIndex--) {
			currChar = Character.toLowerCase(shortForm.charAt(sIndex));
			if (!Character.isLetterOrDigit(currChar))
				continue;
			while (((lIndex >= 0) && (Character
					.toLowerCase(longForm.charAt(lIndex)) != currChar))
					|| ((sIndex == 0) && (lIndex > 0) && (Character
							.isLetterOrDigit(longForm.charAt(lIndex - 1)))))
				lIndex--;
			if (lIndex < 0)
				return null;
			lIndex--;
		}
		lIndex = longForm.lastIndexOf(" ", lIndex) + 1;
		return longForm.substring(lIndex);
	}

	private HashMap<String, String> extractAbbrPair(String shortForm,
			String longForm) {

		HashMap<String, String> Singlepairs;
		Singlepairs = new HashMap<String, String>();

		String bestLongForm;
		StringTokenizer tokenizer;
		int longFormSize, shortFormSize;

		if (shortForm.length() == 1)
			return Singlepairs;
		bestLongForm = findBestLongForm(shortForm, longForm);
		if (bestLongForm == null)
			return Singlepairs;
		tokenizer = new StringTokenizer(bestLongForm, " \t\n\r\f-");
		longFormSize = tokenizer.countTokens();
		shortFormSize = shortForm.length();
		for (int i = shortFormSize - 1; i >= 0; i--)
			if (!Character.isLetterOrDigit(shortForm.charAt(i)))
				shortFormSize--;
		if (bestLongForm.length() < shortForm.length()
				|| bestLongForm.indexOf(shortForm + " ") > -1
				|| bestLongForm.endsWith(shortForm)
				|| longFormSize > shortFormSize * 2
				|| longFormSize > shortFormSize + 5 || shortFormSize > 10)
			return Singlepairs;

		if (testMode) {
			if (isTrueDefinition(shortForm, bestLongForm)) {
				Main.logger.debug(shortForm + delimiter + bestLongForm
						+ delimiter + "TP");
				truePositives++;
			} else {
				falsePositives++;
				Main.logger.debug(shortForm + delimiter + bestLongForm
						+ delimiter + "FP");
			}
		} else {
			// Singlepairs.put(bestLongForm,shortForm);
			Singlepairs.put(shortForm, bestLongForm);
			// Main.logger.debug(shortForm + delimiter + bestLongForm);

		}
		return Singlepairs;
	}

	private static void usage() {
		System.err.println("Usage: ExtractAbbrev [-options] <filename>");
		System.err.println(
				"       <filename> contains text from which abbreviations are extracted");
		System.err.println(
				"       -testlist <file> = list of true abbreviation definition pairs");
		System.err.println("       -usage or -help = this message");
		System.exit(1);
	}

}

redpajama_set_name: RedPajamaGithub


text:
module StatefulLink
  VERSION = '0.0.9'
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

pipeline

tbb::pipeline Member List

This is the complete list of members for tbb::pipeline, including all inherited members.

add_filter(filter &filter_)	tbb::pipeline

clear()	tbb::pipeline

filter (defined in tbb::pipeline)	tbb::pipeline	friend

internal::pipeline_cleaner (defined in tbb::pipeline)	tbb::pipeline	friend

internal::pipeline_root_task (defined in tbb::pipeline)	tbb::pipeline	friend

internal::stage_task (defined in tbb::pipeline)	tbb::pipeline	friend

pipeline()	tbb::pipeline

run(size_t max_number_of_live_tokens)	tbb::pipeline

run(size_t max_number_of_live_tokens, tbb::task_group_context &context)	tbb::pipeline

tbb::interface6::internal::pipeline_proxy (defined in tbb::pipeline)	tbb::pipeline	friend

thread_bound_filter (defined in tbb::pipeline)	tbb::pipeline	friend

~pipeline()	tbb::pipeline	virtual

Copyright © 2005-2015 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
.class public abstract Lcom/samsung/android/dapmanager/IMlDapService$Stub;
.super Landroid/os/Binder;
.source "IMlDapService.java"

# interfaces
.implements Lcom/samsung/android/dapmanager/IMlDapService;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/dapmanager/IMlDapService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Stub"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/samsung/android/dapmanager/IMlDapService$Stub$Proxy;
    }
.end annotation

# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "com.samsung.android.dapmanager.IMlDapService"

.field static final TRANSACTION_checkDeviceCertificate:I = 0x3

.field static final TRANSACTION_deleteDeviceKey:I = 0x4

.field static final TRANSACTION_finalizeOta:I = 0xb

.field static final TRANSACTION_generateSignature:I = 0x9

.field static final TRANSACTION_getCaCertificate:I = 0x1

.field static final TRANSACTION_getDeviceCertificate:I = 0x5

.field static final TRANSACTION_getExtendPcr:I = 0x8

.field static final TRANSACTION_getManufacturerCertificate:I = 0x6

.field static final TRANSACTION_getPcr:I = 0x7

.field static final TRANSACTION_initializeOta:I = 0xa

.field static final TRANSACTION_storeDeviceCertificate:I = 0x2

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    const-string/jumbo v0, "com.samsung.android.dapmanager.IMlDapService"

    invoke-virtual {p0, p0, v0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Lcom/samsung/android/dapmanager/IMlDapService;
    .locals 2

    const/4 v1, 0x0

    if-nez p0, :cond_0

    return-object v1

    :cond_0
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    if-eqz v0, :cond_1

    instance-of v1, v0, Lcom/samsung/android/dapmanager/IMlDapService;

    if-eqz v1, :cond_1

    check-cast v0, Lcom/samsung/android/dapmanager/IMlDapService;

    return-object v0

    :cond_1
    new-instance v1, Lcom/samsung/android/dapmanager/IMlDapService$Stub$Proxy;

    invoke-direct {v1, p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub$Proxy;-><init>(Landroid/os/IBinder;)V

    return-object v1
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 0

    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .locals 14
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    sparse-switch p1, :sswitch_data_0

    invoke-super/range {p0 .. p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v1

    return v1

    :sswitch_0
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    const/4 v1, 0x1

    return v1

    :sswitch_1
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v8

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v3

    invoke-virtual {p0, v8, v3}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->getCaCertificate(I[B)[B

    move-result-object v13

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v13}, Landroid/os/Parcel;->writeByteArray([B)V

    const/4 v1, 0x1

    return v1

    :sswitch_2
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v2

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v3

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v4

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v5

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v6

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v7

    move-object v1, p0

    invoke-virtual/range {v1 .. v7}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->storeDeviceCertificate([B[B[BIII)I

    move-result v10

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v10}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    return v1

    :sswitch_3
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->checkDeviceCertificate()I

    move-result v10

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v10}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    return v1

    :sswitch_4
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->deleteDeviceKey()I

    move-result v10

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v10}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    return v1

    :sswitch_5
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->getDeviceCertificate()Lcom/samsung/android/dapmanager/BufferData;

    move-result-object v11

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v11, :cond_0

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v11, v0, v1}, Lcom/samsung/android/dapmanager/BufferData;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_0
    const/4 v1, 0x1

    return v1

    :cond_0
    const/4 v1, 0x0

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_0

    :sswitch_6
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->getManufacturerCertificate()Lcom/samsung/android/dapmanager/IoBufferData;

    move-result-object v12

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v12, :cond_1

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v12, v0, v1}, Lcom/samsung/android/dapmanager/IoBufferData;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_1
    const/4 v1, 0x1

    return v1

    :cond_1
    const/4 v1, 0x0

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_1

    :sswitch_7
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->getPcr()Lcom/samsung/android/dapmanager/BufferData;

    move-result-object v11

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v11, :cond_2

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v11, v0, v1}, Lcom/samsung/android/dapmanager/BufferData;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_2
    const/4 v1, 0x1

    return v1

    :cond_2
    const/4 v1, 0x0

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_2

    :sswitch_8
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v2

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v9

    invoke-virtual {p0, v2, v9}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->getExtendPcr([BI)Lcom/samsung/android/dapmanager/BufferData;

    move-result-object v11

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v11, :cond_3

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v11, v0, v1}, Lcom/samsung/android/dapmanager/BufferData;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_3
    const/4 v1, 0x1

    return v1

    :cond_3
    const/4 v1, 0x0

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_3

    :sswitch_9
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v2

    invoke-virtual/range {p2 .. p2}, Landroid/os/Parcel;->readInt()I

    move-result v9

    invoke-virtual {p0, v2, v9}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->generateSignature([BI)Lcom/samsung/android/dapmanager/BufferData;

    move-result-object v11

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v11, :cond_4

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    move-object/from16 v0, p3

    invoke-virtual {v11, v0, v1}, Lcom/samsung/android/dapmanager/BufferData;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_4
    const/4 v1, 0x1

    return v1

    :cond_4
    const/4 v1, 0x0

    move-object/from16 v0, p3

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_4

    :sswitch_a
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->initializeOta()I

    move-result v10

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v10}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    return v1

    :sswitch_b
    const-string/jumbo v1, "com.samsung.android.dapmanager.IMlDapService"

    move-object/from16 v0, p2

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/samsung/android/dapmanager/IMlDapService$Stub;->finalizeOta()I

    move-result v10

    invoke-virtual/range {p3 .. p3}, Landroid/os/Parcel;->writeNoException()V

    move-object/from16 v0, p3

    invoke-virtual {v0, v10}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v1, 0x1

    return v1

    nop

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_1
        0x2 -> :sswitch_2
        0x3 -> :sswitch_3
        0x4 -> :sswitch_4
        0x5 -> :sswitch_5
        0x6 -> :sswitch_6
        0x7 -> :sswitch_7
        0x8 -> :sswitch_8
        0x9 -> :sswitch_9
        0xa -> :sswitch_a
        0xb -> :sswitch_b
        0x5f4e5446 -> :sswitch_0
    .end sparse-switch
.end method


text:
require_dependency 'carto/uuidhelper'
require_dependency 'carto/api/vizjson3_presenter'

module VisualizationsControllerHelper
  # This class represents a "visualization locator", as string in one of the following formats:
  # <viz_uuid>, <viz_name>, <schema>.<viz_uuid>, <schema.viz_name>
  # It parses it provides methods to access the different fields, and allows to validate if a
  # visualization matches the "visualization locator" string.
  # This allows flexible specification of visualization names in URL's, accepting canonical
  # visualizations (usually by name) and derived visualizations (by uuid).
  class VisualizationLocator
    include Carto::UUIDHelper

    def initialize(visualization_locator_string)
      table_id_or_name, @schema = visualization_locator_string.split('.').reverse

      if is_uuid?(table_id_or_name)
        @id = table_id_or_name
      else
        @name = table_id_or_name
      end
    end

    def id
      @id
    end

    def name
      @name
    end

    def schema
      @schema
    end

    def matches_visualization?(visualization)
      return false unless visualization
      return false if id && id != visualization.id
      return false if name && name != visualization.name
      return false if schema && schema != visualization.user.database_schema
      true
    end
  end

  def extract_user_from_request_and_viz_locator(viz_locator)
    # 1. Handles any url with "/u/username", or "username.cartodb.com"
    user_or_org_name = CartoDB.extract_subdomain(request)
    user = Carto::User.where(username: user_or_org_name).first

    if user.nil?
      # 2a. User not found: handles org.cartodb.com with "schema.table" visualizations
      organization = Carto::Organization.where(name: user_or_org_name).first
      return nil unless organization
      organization.users.where(username: viz_locator.schema).first
    elsif user.organization.present?
      # 2b. User found in org: handles visualizations shared in the org
      org_user = user.organization.users.where(username: viz_locator.schema).first
      org_user.nil? ? user : org_user
    else
      # Found user not in organization
      user
    end
  end

  # Implicit order due to legacy code: 1st return canonical/table/Dataset if present, else derived/visualization/Map
  def get_priority_visualization(visualization_id, user_id: nil, organization_id: nil)
    Carto::VisualizationQueryBuilder.new
                                    .with_id_or_name(visualization_id)
                                    .with_user_id(user_id)
                                    .with_organization_id(organization_id)
                                    .build
                                    .all
                                    .sort { |vis_a, _vis_b|
                                      vis_a.type == Carto::Visualization::TYPE_CANONICAL ? -1 : 1
                                    }
                                    .first
  end

  def load_visualization_from_id_or_name(id_or_name)
    viz_locator = VisualizationLocator.new(id_or_name)
    if viz_locator.id
      visualization = get_priority_visualization(viz_locator.id)
    else
      user = extract_user_from_request_and_viz_locator(viz_locator)
      visualization = user.nil? ? nil : get_priority_visualization(viz_locator.name, user_id: user.id)
    end

    return nil unless viz_locator.matches_visualization?(visualization)
    visualization
  end

  def generate_vizjson3(visualization, params)
    Carto::Api::VizJSON3Presenter.new(visualization)
                                 .to_vizjson(https_request: is_https?, vector: params[:vector] == 'true')
  end
end


text:
package main

import (
	"flag"
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/prometheus/common/log"

	"github.com/mischief/gopf"
)

var (
	Namespace = "pf"
)

type PfExporter struct {
	fw          pf.Pf

	metrics map[string]*prometheus.Desc
}

// Describe implements the prometheus.Collector interface.
func (e *PfExporter) Describe(ch chan<- *prometheus.Desc) {
	for _, m := range e.metrics {
		ch <- m
	}
}

// Collect implements the prometheus.Collector interface.
func (e *PfExporter) Collect(ch chan<- prometheus.Metric) {
	stats, err := e.fw.Stats()
	if err != nil {
		log.Errorf("failed to get pf stats: %v", err)
		return
	}

	ch <- prometheus.MustNewConstMetric(e.metrics["state_total"], prometheus.GaugeValue, float64(stats.StateCount()))
	ch <- prometheus.MustNewConstMetric(e.metrics["state_searches"], prometheus.CounterValue, float64(stats.StateSearches()))
	ch <- prometheus.MustNewConstMetric(e.metrics["state_inserts"], prometheus.CounterValue, float64(stats.StateInserts()))
	ch <- prometheus.MustNewConstMetric(e.metrics["state_removals"], prometheus.CounterValue, float64(stats.StateRemovals()))

	ifstats := stats.IfStats()
	if ifstats != nil {
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_bytes_in"], prometheus.CounterValue, float64(ifstats.IPv4.BytesIn))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_bytes_out"], prometheus.CounterValue, float64(ifstats.IPv4.BytesOut))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_packets_in_passed"], prometheus.CounterValue, float64(ifstats.IPv4.PacketsInPassed))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_packets_in_blocked"], prometheus.CounterValue, float64(ifstats.IPv4.PacketsInBlocked))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_packets_out_passed"], prometheus.CounterValue, float64(ifstats.IPv4.PacketsOutPassed))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv4_packets_out_blocked"], prometheus.CounterValue, float64(ifstats.IPv4.PacketsOutBlocked))

		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_bytes_in"], prometheus.CounterValue, float64(ifstats.IPv6.BytesIn))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_bytes_out"], prometheus.CounterValue, float64(ifstats.IPv6.BytesOut))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_packets_in_passed"], prometheus.CounterValue, float64(ifstats.IPv6.PacketsInPassed))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_packets_in_blocked"], prometheus.CounterValue, float64(ifstats.IPv6.PacketsInBlocked))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_packets_out_passed"], prometheus.CounterValue, float64(ifstats.IPv6.PacketsOutPassed))
		ch <- prometheus.MustNewConstMetric(e.metrics["ipv6_packets_out_blocked"], prometheus.CounterValue, float64(ifstats.IPv6.PacketsOutBlocked))
	}

	queues, err := e.fw.Queues()
	if err != nil {
		log.Errorf("failed to get queue stats: %v", err)
		return
	}

	for _, queue := range queues {
		ch <- prometheus.MustNewConstMetric(e.metrics["queue_xmit_packets"], prometheus.CounterValue, float64(queue.Stats.TransmitPackets), queue.Name, queue.IfName)
		ch <- prometheus.MustNewConstMetric(e.metrics["queue_xmit_bytes"], prometheus.CounterValue, float64(queue.Stats.TransmitBytes), queue.Name, queue.IfName)
		ch <- prometheus.MustNewConstMetric(e.metrics["queue_dropped_packets"], prometheus.CounterValue, float64(queue.Stats.DroppedPackets), queue.Name, queue.IfName)
		ch <- prometheus.MustNewConstMetric(e.metrics["queue_dropped_bytes"], prometheus.CounterValue, float64(queue.Stats.DroppedBytes), queue.Name, queue.IfName)
	}
}

func NewPfExporter() (*PfExporter, error) {
	var fw pf.Pf
	var err error

	if *fdno != -1 {
		fw = pf.OpenFD(uintptr(*fdno))
	} else {
		fw, err = pf.Open()
		if err != nil {
			return nil, err
		}
	}

	exp := &PfExporter{
		fw: fw,
		metrics: map[string]*prometheus.Desc{
			"state_total": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "state", "total"),
				"Number of pf states.",
				nil,
				nil),
			"state_searches": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "state", "searches_total"),
				"Number of pf state searches.",
				nil, nil),
			"state_inserts": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "state", "inserts_total"),
				"Number of pf state inserts.",
				nil,
				nil),
			"state_removals": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "state", "removals_total"),
				"Number of pf state removals.",
				nil,
				nil),

			"ipv4_bytes_in": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "bytes_in_total"),
				"Number of bytes in on the pf loginterface over IPv4.",
				nil,
				nil),
			"ipv4_bytes_out": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "bytes_out_total"),
				"Number of bytes out on the pf loginterface over IPv4.",
				nil,
				nil),
			"ipv4_packets_in_passed": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "packets_in_passed_total"),
				"Number of packets passed in on the pf loginterface over IPv4.",
				nil,
				nil),
			"ipv4_packets_in_blocked": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "packets_in_blocked_total"),
				"Number of packets blocked in on the pf loginterface over IPv4.",
				nil,
				nil),
			"ipv4_packets_out_passed": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "packets_out_passed_total"),
				"Number of packets passed out on the pf loginterface over IPv4.",
				nil,
				nil),
			"ipv4_packets_out_blocked": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv4", "packets_out_blocked_total"),
				"Number of packets blocked out on the pf loginterface over IPv4.",
				nil,
				nil),

			"ipv6_bytes_in": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "bytes_in_total"),
				"Number of bytes in on the pf loginterface over IPv6.",
				nil,
				nil),
			"ipv6_bytes_out": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "bytes_out_total"),
				"Number of bytes out on the pf loginterface over IPv6.",
				nil,
				nil),
			"ipv6_packets_in_passed": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "packets_in_passed_total"),
				"Number of packets passed in on the pf loginterface over IPv6.",
				nil,
				nil),
			"ipv6_packets_in_blocked": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "packets_in_blocked_total"),
				"Number of packets blocked in on the pf loginterface over IPv6.",
				nil,
				nil),
			"ipv6_packets_out_passed": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "packets_out_passed_total"),
				"Number of packets passed out on the pf loginterface over IPv6.",
				nil,
				nil),
			"ipv6_packets_out_blocked": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "ipv6", "packets_out_blocked_total"),
				"Number of packets blocked out on the pf loginterface over IPv6.",
				nil,
				nil),

			"queue_xmit_packets": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "stats", "queue_transmitted_packets_total"),
				"Number of transmitted packets in a queue partitioned by queue name and interface.",
				[]string{"queue", "interface"},
				nil),
			"queue_xmit_bytes": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "stats", "queue_transmitted_bytes_total"),
				"Number of transmitted bytes in a queue partitioned by queue name and interface.",
				[]string{"queue", "interface"},
				nil),
			"queue_dropped_packets": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "stats", "queue_dropped_packets_total"),
				"Number of dropped packets in a queue partitioned by queue name and interface.",
				[]string{"queue", "interface"},
				nil),
			"queue_dropped_bytes": prometheus.NewDesc(
				prometheus.BuildFQName(Namespace, "stats", "queue_dropped_bytes_total"),
				"Number of dropped bytes in a queue partitioned by queue name and interface.",
				[]string{"queue", "interface"},
				nil),
		},
	}

	return exp, nil
}

var (
	listenAddress = flag.String("web.listen-address", ":9107", "Address to listen on for web interface and telemetry.")
	metricsPath   = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
	fdno          = flag.Int("pf.fd", -1, "if set, use this fd for pf ioctls")
)

func main() {
	flag.Parse()

	exporter, err := NewPfExporter()
	if err != nil {
		log.Fatalf("Failed to create pf exporter: %v", err)
	}

	prometheus.MustRegister(exporter)

	log.Infof("Starting Server: %s", *listenAddress)
	http.Handle(*metricsPath, promhttp.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
             <title>pf Exporter</title>

pf Exporter

<a href='` + *metricsPath + `'>Metrics

             `))
	})
	log.Fatal(http.ListenAndServe(*listenAddress, nil))
}


text:
layout: post
date:	2014-02-24 22:12:00
title:  Three wishes...and no more
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I wish we were like birds, with the ability to fly.

I wish we were like plants , to make food directly from the sun.

I wish we were like other beings, never questioning why.

But we are just human beings, so my wishing is over, and done!


text:
/// <reference path="../../lib/jQuery.d.ts" />
/// <reference path="../../lib/three.d.ts" />
/// <reference path="../core/utils.ts" />
/// <reference path="wall.ts" />
/// <reference path="corner.ts" />
/// <reference path="room.ts" />
/// <reference path="half_edge.ts" />

module BP3D.Model {
  /** */
  const defaultFloorPlanTolerance = 10.0;

  /**
   * A Floorplan represents a number of Walls, Corners and Rooms.
   */
  export class Floorplan {

    /** */
    private walls: Wall[] = [];

    /** */
    private corners: Corner[] = [];

    /** */
    private rooms: Room[] = [];

    /** */
    private new_wall_callbacks = $.Callbacks();

    /** */
    private new_corner_callbacks = $.Callbacks();

    /** */
    private redraw_callbacks = $.Callbacks();

    /** */
    private updated_rooms = $.Callbacks();

    /** */
    public roomLoadedCallbacks = $.Callbacks();

    /**
    * Floor textures are owned by the floorplan, because room objects are
    * destroyed and created each time we change the floorplan.
    * floorTextures is a map of room UUIDs (string) to a object with
    * url and scale attributes.
    */
    private floorTextures = {};

    /** Constructs a floorplan. */
    constructor() {
    }

    // hack
    public wallEdges(): HalfEdge[] {
      var edges = []

      this.walls.forEach((wall) => {
        if (wall.frontEdge) {
          edges.push(wall.frontEdge);
        }
        if (wall.backEdge) {
          edges.push(wall.backEdge);
        }
      });
      return edges;
    }

    // hack
    public wallEdgePlanes(): THREE.Mesh[] {
      var planes = []
      this.walls.forEach((wall) => {
        if (wall.frontEdge) {
          planes.push(wall.frontEdge.plane);
        }
        if (wall.backEdge) {
          planes.push(wall.backEdge.plane);
        }
      });
      return planes;
    }

    private floorPlanes(): THREE.Mesh[] {
      return Core.Utils.map(this.rooms, (room: Room) => {
        return room.floorPlane;
      });
    }

    public fireOnNewWall(callback) {
      this.new_wall_callbacks.add(callback);
    }

    public fireOnNewCorner(callback) {
      this.new_corner_callbacks.add(callback);
    }

    public fireOnRedraw(callback) {
      this.redraw_callbacks.add(callback);
    }

    public fireOnUpdatedRooms(callback) {
      this.updated_rooms.add(callback);
    }

    /**
     * Creates a new wall.
     * @param start The start corner.
     * @param end he end corner.
     * @returns The new wall.
     */
    public newWall(start: Corner, end: Corner): Wall {
      var wall = new Wall(start, end);
      this.walls.push(wall)
      var scope = this;
      wall.fireOnDelete(() => {
        scope.removeWall(wall);
      });
      this.new_wall_callbacks.fire(wall);
      this.update();
      return wall;
    }

    /** Removes a wall.
     * @param wall The wall to be removed.
     */
    private removeWall(wall: Wall) {
      Core.Utils.removeValue(this.walls, wall);
      this.update();
    }

    /**
     * Creates a new corner.
     * @param x The x coordinate.
     * @param y The y coordinate.
     * @param id An optional id. If unspecified, the id will be created internally.
     * @returns The new corner.
     */
    public newCorner(x: number, y: number, id?: string): Corner {
      var corner = new Corner(this, x, y, id);
      this.corners.push(corner);
      corner.fireOnDelete(() => {
        this.removeCorner;
      });
      this.new_corner_callbacks.fire(corner);
      return corner;
    }

    /** Removes a corner.
     * @param corner The corner to be removed.
     */
    private removeCorner(corner: Corner) {
      Core.Utils.removeValue(this.corners, corner);
    }

    /** Gets the walls. */
    public getWalls(): Wall[] {
      return this.walls;
    }

    /** Gets the corners. */
    public getCorners(): Corner[] {
      return this.corners;
    }

    /** Gets the rooms. */
    public getRooms(): Room[] {
      return this.rooms;
    }

    public overlappedCorner(x: number, y: number, tolerance?: number): Corner {
      tolerance = tolerance || defaultFloorPlanTolerance;
      for (var i = 0; i < this.corners.length; i++) {
        if (this.corners[i].distanceFrom(x, y) < tolerance) {
          return this.corners[i];
        }
      }
      return null;
    }

    public overlappedWall(x: number, y: number, tolerance?: number): Wall {
      tolerance = tolerance || defaultFloorPlanTolerance;
      for (var i = 0; i < this.walls.length; i++) {
        if (this.walls[i].distanceFrom(x, y) < tolerance) {
          return this.walls[i];
        }
      }
      return null;
    }

    // import and export -- cleanup

    public saveFloorplan() {
      var floorplan = {
        corners: {},
        walls: [],
        wallTextures: [],
        floorTextures: {},
        newFloorTextures: {}
      }

      this.corners.forEach((corner) => {
        floorplan.corners[corner.id] = {
          'x': corner.x,
          'y': corner.y
        };
      });

      this.walls.forEach((wall) => {
        floorplan.walls.push({
          'corner1': wall.getStart().id,
          'corner2': wall.getEnd().id,
          'frontTexture': wall.frontTexture,
          'backTexture': wall.backTexture
        });
      });
      floorplan.newFloorTextures = this.floorTextures;
      return floorplan;
    }

    public loadFloorplan(floorplan) {
      this.reset();

      var corners = {};
      if (floorplan == null || !('corners' in floorplan) || !('walls' in floorplan)) {
        return
      }
      for (var id in floorplan.corners) {
        var corner = floorplan.corners[id];
        corners[id] = this.newCorner(corner.x, corner.y, id);
      }
      var scope = this;
      floorplan.walls.forEach((wall) => {
        var newWall = scope.newWall(
          corners[wall.corner1], corners[wall.corner2]);
        if (wall.frontTexture) {
          newWall.frontTexture = wall.frontTexture;
        }
        if (wall.backTexture) {
          newWall.backTexture = wall.backTexture;
        }
      });

      if ('newFloorTextures' in floorplan) {
        this.floorTextures = floorplan.newFloorTextures;
      }

      this.update();
      this.roomLoadedCallbacks.fire();
    }

    public getFloorTexture(uuid: string) {
      if (uuid in this.floorTextures) {
        return this.floorTextures[uuid];
      } else {
        return null;
      }
    }

    public setFloorTexture(uuid: string, url: string, scale: number) {
      this.floorTextures[uuid] = {
        url: url,
        scale: scale
      }
    }

    /** clear out obsolete floor textures */
    private updateFloorTextures() {
      var uuids = Core.Utils.map(this.rooms, function (room) {
        return room.getUuid();
      });
      for (var uuid in this.floorTextures) {
        if (!Core.Utils.hasValue(uuids, uuid)) {
          delete this.floorTextures[uuid]
        }
      }
    }

    /** */
    private reset() {
      var tmpCorners = this.corners.slice(0);
      var tmpWalls = this.walls.slice(0);
      tmpCorners.forEach((corner) => {
        corner.remove();
      })
      tmpWalls.forEach((wall) => {
        wall.remove();
      })
      this.corners = [];
      this.walls = [];
    }

    /**
     * Update rooms
     */
    public update() {
      this.walls.forEach((wall) => {
        wall.resetFrontBack();
      });

      var roomCorners = this.findRooms(this.corners);
      this.rooms = [];
      var scope = this;
      roomCorners.forEach((corners) => {
        scope.rooms.push(new Room(scope, corners));
      });
      this.assignOrphanEdges();

      this.updateFloorTextures();
      this.updated_rooms.fire();
    }

    /**
     * Returns the center of the floorplan in the y plane
     */
    public getCenter() {
      return this.getDimensions(true);
    }

    public getSize() {
      return this.getDimensions(false);
    }

    public getDimensions(center) {
      center = center || false; // otherwise, get size

      var xMin = Infinity;
      var xMax = -Infinity;
      var zMin = Infinity;
      var zMax = -Infinity;
      this.corners.forEach((corner) => {
        if (corner.x < xMin) xMin = corner.x;
        if (corner.x > xMax) xMax = corner.x;
        if (corner.y < zMin) zMin = corner.y;
        if (corner.y > zMax) zMax = corner.y;
      });
      var ret;
      if (xMin == Infinity || xMax == -Infinity || zMin == Infinity || zMax == -Infinity) {
        ret = new THREE.Vector3();
      } else {
        if (center) {
          // center
          ret = new THREE.Vector3((xMin + xMax) * 0.5, 0, (zMin + zMax) * 0.5);
        } else {
          // size
          ret = new THREE.Vector3((xMax - xMin), 0, (zMax - zMin));
        }
      }
      return ret;
    }

    private assignOrphanEdges() {
      // kinda hacky
      // find orphaned wall segments (i.e. not part of rooms) and
      // give them edges
      var orphanWalls = []
      this.walls.forEach((wall) => {
        if (!wall.backEdge && !wall.frontEdge) {
          wall.orphan = true;
          var back = new HalfEdge(null, wall, false);
          back.generatePlane();
          var front = new HalfEdge(null, wall, true);
          front.generatePlane();
          orphanWalls.push(wall);
        }
      });

    }

    /*
     * Find the "rooms" in our planar straight-line graph.
     * Rooms are set of the smallest (by area) possible cycles in this graph.
     * @param corners The corners of the floorplan.
     * @returns The rooms, each room as an array of corners.
     */
    public findRooms(corners: Corner[]): Corner[][] {

      function _calculateTheta(previousCorner: Corner, currentCorner: Corner, nextCorner: Corner) {
        var theta = Core.Utils.angle2pi(
          previousCorner.x - currentCorner.x,
          previousCorner.y - currentCorner.y,
          nextCorner.x - currentCorner.x,
          nextCorner.y - currentCorner.y);
        return theta;
      }

      function _removeDuplicateRooms(roomArray: Corner[][]): Corner[][] {
        var results: Corner[][] = [];
        var lookup = {};
        var hashFunc = function (corner) {
          return corner.id
        };
        var sep = '-';
        for (var i = 0; i < roomArray.length; i++) {
          // rooms are cycles, shift it around to check uniqueness
          var add = true;
          var room = roomArray[i];
          for (var j = 0; j < room.length; j++) {
            var roomShift = Core.Utils.cycle(room, j);
            var str = Core.Utils.map(roomShift, hashFunc).join(sep);
            if (lookup.hasOwnProperty(str)) {
              add = false;
            }
          }
          if (add) {
            results.push(roomArray[i]);
            lookup[str] = true;
          }
        }
        return results;
      }

      function _findTightestCycle(firstCorner: Corner, secondCorner: Corner): Corner[] {
        var stack: {
          corner: Corner,
          previousCorners: Corner[]
        }[] = [];

        var next = {
          corner: secondCorner,
          previousCorners: [firstCorner]
        };
        var visited = {};
        visited[firstCorner.id] = true;

        while (next) {
          // update previous corners, current corner, and visited corners
          var currentCorner = next.corner;
          visited[currentCorner.id] = true;

          // did we make it back to the startCorner?
          if (next.corner === firstCorner && currentCorner !== secondCorner) {
            return next.previousCorners;
          }

          var addToStack: Corner[] = [];
          var adjacentCorners = next.corner.adjacentCorners();
          for (var i = 0; i < adjacentCorners.length; i++) {
            var nextCorner = adjacentCorners[i];

            // is this where we came from?
            // give an exception if its the first corner and we aren't at the second corner
            if (nextCorner.id in visited &&
              !(nextCorner === firstCorner && currentCorner !== secondCorner)) {
              continue;
            }

            // nope, throw it on the queue
            addToStack.push(nextCorner);
          }

          var previousCorners = next.previousCorners.slice(0);
          previousCorners.push(currentCorner);
          if (addToStack.length > 1) {
            // visit the ones with smallest theta first
            var previousCorner = next.previousCorners[next.previousCorners.length - 1];
            addToStack.sort(function (a, b) {
              return (_calculateTheta(previousCorner, currentCorner, b) -
                _calculateTheta(previousCorner, currentCorner, a));
            });
          }

          if (addToStack.length > 0) {
            // add to the stack
            addToStack.forEach((corner) => {
              stack.push({
                corner: corner,
                previousCorners: previousCorners
              });
            });
          }

          // pop off the next one
          next = stack.pop();
        }
        return [];
      }

      // find tightest loops, for each corner, for each adjacent
      // TODO: optimize this, only check corners with > 2 adjacents, or isolated cycles
      var loops: Corner[][] = [];

      corners.forEach((firstCorner) => {
        firstCorner.adjacentCorners().forEach((secondCorner) => {
          loops.push(_findTightestCycle(firstCorner, secondCorner));
        });
      });

      // remove duplicates
      var uniqueLoops = _removeDuplicateRooms(loops);
      //remove CW loops
      var uniqueCCWLoops = Core.Utils.removeIf(uniqueLoops, Core.Utils.isClockwise);

      return uniqueCCWLoops;
    }
  }
}


text: export { Api_124 as default } from "../../";


text:
export * from './baSidebar';
export * from './baMenu/components/baMenuItem';
export * from './baMenu';
export * from './baCard';
export * from './baBackTop';


text:
namespace aura {
class Window;
}  // namespace aura

namespace gfx {
class Rect;
}  // namespace gfx

namespace ash {

// Delegate for taking screenshots.
class ScreenshotDelegate {
 public:
  virtual ~ScreenshotDelegate() {}

  // The actual task of taking a screenshot for the given window.
  // This method is called when the user wants to take a screenshot
  // manually.
  virtual void HandleTakeScreenshot(aura::Window* window) = 0;

  // The actual task of taking a partial screenshot for the given
  // window.
  virtual void HandleTakePartialScreenshot(
      aura::Window* window, const gfx::Rect& rect) = 0;
};
}  // namespace ash

#endif  // ASH_SCREENSHOT_DELEGATE_H_


text:
using Duende.IdentityServer.Configuration;
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using DuendeDynamicProviders.Pages.Consent;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;

namespace DuendeDynamicProviders.Pages.Device;

[SecurityHeaders]
[Authorize]
public class Index : PageModel
{
    private readonly IDeviceFlowInteractionService _interaction;
    private readonly IEventService _events;
    private readonly IOptions<IdentityServerOptions> _options;
    private readonly ILogger<Index> _logger;

    public Index(
        IDeviceFlowInteractionService interaction,
        IEventService eventService,
        IOptions<IdentityServerOptions> options,
        ILogger<Index> logger)
    {
        _interaction = interaction;
        _events = eventService;
        _options = options;
        _logger = logger;
    }

    public ViewModel View { get; set; }

    [BindProperty]
    public InputModel Input { get; set; }

    public async Task<IActionResult> OnGet(string userCode)
    {
        if (String.IsNullOrWhiteSpace(userCode))
        {
            View = new ViewModel();
            Input = new InputModel();
            return Page();
        }

        View = await BuildViewModelAsync(userCode);
        if (View == null)
        {
            ModelState.AddModelError("", DeviceOptions.InvalidUserCode);
            View = new ViewModel();
            Input = new InputModel();
            return Page();
        }

        Input = new InputModel {
            UserCode = userCode,
        };

        return Page();
    }

    public async Task<IActionResult> OnPost()
    {
        var request = await _interaction.GetAuthorizationContextAsync(Input.UserCode);
        if (request == null) return RedirectToPage("/Error/Index");

        ConsentResponse grantedConsent = null;

        // user clicked 'no' - send back the standard 'access_denied' response
        if (Input.Button == "no")
        {
            grantedConsent = new ConsentResponse
            {
                Error = AuthorizationError.AccessDenied
            };

            // emit event
            await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
        }
        // user clicked 'yes' - validate the data
        else if (Input.Button == "yes")
        {
            // if the user consented to some scope, build the response model
            if (Input.ScopesConsented != null && Input.ScopesConsented.Any())
            {
                var scopes = Input.ScopesConsented;
                if (ConsentOptions.EnableOfflineAccess == false)
                {
                    scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess);
                }

                grantedConsent = new ConsentResponse
                {
                    RememberConsent = Input.RememberConsent,
                    ScopesValuesConsented = scopes.ToArray(),
                    Description = Input.Description
                };

                // emit event
                await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent));
            }
            else
            {
                ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage);
            }
        }
        else
        {
            ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage);
        }

        if (grantedConsent != null)
        {
            // communicate outcome of consent back to identityserver
            await _interaction.HandleRequestAsync(Input.UserCode, grantedConsent);

            // indicate that's it ok to redirect back to authorization endpoint
            return RedirectToPage("/Device/Success");
        }

        // we need to redisplay the consent UI
        View = await BuildViewModelAsync(Input.UserCode, Input);
        return Page();
    }

    private async Task<ViewModel> BuildViewModelAsync(string userCode, InputModel model = null)
    {
        var request = await _interaction.GetAuthorizationContextAsync(userCode);
        if (request != null)
        {
            return CreateConsentViewModel(model, request);
        }

        return null;
    }

    private ViewModel CreateConsentViewModel(InputModel model, DeviceFlowAuthorizationRequest request)
    {
        var vm = new ViewModel
        {
            ClientName = request.Client.ClientName ?? request.Client.ClientId,
            ClientUrl = request.Client.ClientUri,
            ClientLogoUrl = request.Client.LogoUri,
            AllowRememberConsent = request.Client.AllowRememberConsent
        };

        vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, model == null || model.ScopesConsented?.Contains(x.Name) == true)).ToArray();

        var apiScopes = new List<ScopeViewModel>();
        foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
        {
            var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
            if (apiScope != null)
            {
                var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true);
                apiScopes.Add(scopeVm);
            }
        }
        if (DeviceOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
        {
            apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true));
        }
        vm.ApiScopes = apiScopes;

        return vm;
    }

    private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
    {
        return new ScopeViewModel
        {
            Value = identity.Name,
            DisplayName = identity.DisplayName ?? identity.Name,
            Description = identity.Description,
            Emphasize = identity.Emphasize,
            Required = identity.Required,
            Checked = check || identity.Required
        };
    }

    public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
    {
        return new ScopeViewModel
        {
            Value = parsedScopeValue.RawValue,
            // todo: use the parsed scope value in the display?
            DisplayName = apiScope.DisplayName ?? apiScope.Name,
            Description = apiScope.Description,
            Emphasize = apiScope.Emphasize,
            Required = apiScope.Required,
            Checked = check || apiScope.Required
        };
    }

    private ScopeViewModel GetOfflineAccessScope(bool check)
    {
        return new ScopeViewModel
        {
            Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess,
            DisplayName = DeviceOptions.OfflineAccessDisplayName,
            Description = DeviceOptions.OfflineAccessDescription,
            Emphasize = true,
            Checked = check
        };
    }
}


text:
namespace Simulator
{
namespace drisc
{

Pipeline::PipeAction Pipeline::DummyStage::OnCycle()
{
    COMMIT
    {
        (CommonData&)m_output = m_input;
        m_output.suspend = m_input.suspend;
        m_output.Rrc     = m_input.Rrc;
        m_output.Rc      = m_input.Rc;
        m_output.Rcv     = m_input.Rcv;
    }
    return PIPE_CONTINUE;
}

Pipeline::DummyStage::DummyStage(const std::string& name, Pipeline& parent,
                                 const MemoryWritebackLatch& input, MemoryWritebackLatch& output)
  : Stage(name, parent),
    m_input(input),
    m_output(output)
{
}

}
}


text:
package com.github.maven_nar.cpptasks.compiler;

/**
 * A compiler.
 *
 * @author Adam Murdoch
 */
public interface Compiler extends Processor {
}


text:
<?php

class CM_Elasticsearch_Cluster extends CM_Class_Abstract implements CM_Service_ManagerAwareInterface {

    use CM_Service_ManagerAwareTrait;

    /** @var Elastica\Client[] */
    private $_clients;

    /** @var bool */
    private $_enabled;

    /**
     * @param array[]   $servers
     * @param bool|null $disabled
     */
    public function __construct(array $servers, $disabled = null) {
        $this->setEnabled(!$disabled);
        foreach ($servers as $server) {
            $config = array_merge($server, ['timeout' => 10]);
            $this->_clients[] = new Elastica\Client($config);
        }
    }

    /**
     * @return \Elastica\Client[]
     */
    public function getClientList() {
        return $this->_clients;
    }

    /**
     * @return \Elastica\Client
     */
    public function getRandomClient() {
        $index = array_rand($this->_clients);
        return $this->_clients[$index];
    }

    /**
     * @param bool $enabled
     */
    public function setEnabled($enabled) {
        $this->_enabled = (bool) $enabled;
    }

    /**
     * @return bool
     */
    public function getEnabled() {
        return $this->_enabled;
    }

    /**
     * @return CM_Elasticsearch_Type_Abstract[]
     */
    public function getTypes() {
        $types = CM_Util::getClassChildren('CM_Elasticsearch_Type_Abstract');
        return \Functional\map($types, function ($className) {
            return new $className($this->getRandomClient());
        });
    }

    /**
     * @param string $indexName
     * @return CM_Elasticsearch_Type_Abstract
     * @throws CM_Exception_Invalid
     */
    public function findType($indexName) {
        return \Functional\first($this->getTypes(), function (CM_Elasticsearch_Type_Abstract $type) use ($indexName) {
            return $type->getIndex()->getName() === $indexName;
        });
    }

    /**
     * @param CM_Elasticsearch_Type_Abstract[] $types
     * @param array|null                       $data
     * @return array
     */
    public function query(array $types, array $data = null) {
        if (!$this->getEnabled()) {
            return array();
        }
        $this->getServiceManager()->getDebug()->incStats('search', json_encode($data));
        $client = $this->getRandomClient();

        $search = new Elastica\Search($client);
        foreach ($types as $type) {
            $search->addIndex($type->getIndex());
            $search->addType($type->getType());
        }
        try {
            $response = $client->request($search->getPath(), 'GET', $data);
        } catch (Elastica\Exception\ConnectionException $ex) {
            foreach ($client->getConnections() as $connection) {
                $connection->setEnabled();
            }
            throw $ex;
        }
        return $response->getData();
    }
}


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution;

import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.ProjectExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.concurrency.Promises;

import javax.swing.*;

/**
 * This class is responsible for auxiliary tasks (like build process or project-specific scripts execution)
 * that might be called just before run configuration start.
 * Exact list of tasks should be specified for every run configuration (or template) by user in dedicated UI.
 */

public abstract class BeforeRunTaskProvider<T extends BeforeRunTask<?>> {
  public static final ProjectExtensionPointName<BeforeRunTaskProvider<BeforeRunTask<?>>> EP_NAME =
    new ProjectExtensionPointName<>("com.intellij.stepsBeforeRunProvider");

  /**
   * @deprecated Use {@link #EP_NAME}
   */
  @Deprecated(forRemoval = true)
  public static final ExtensionPointName<BeforeRunTaskProvider<BeforeRunTask<?>>> EXTENSION_POINT_NAME =
    new ExtensionPointName<>("com.intellij.stepsBeforeRunProvider");

  public abstract Key<T> getId();

  public abstract @Nls(capitalization = Nls.Capitalization.Title) String getName();

  public @Nullable Icon getIcon() {
    return null;
  }

  public @Nls(capitalization = Nls.Capitalization.Sentence) String getDescription(T task) {
    return getName();
  }

  public @Nullable Icon getTaskIcon(T task) {
    return null;
  }

  public boolean isConfigurable() {
    return false;
  }

  /**
   * @return 'before run' task for the configuration or null, if the task from this provider is not applicable to the specified configuration.
   */
  public abstract @Nullable T createTask(@NotNull RunConfiguration runConfiguration);

  /**
   * @return {@code true} if task configuration is changed
   * @deprecated do not call directly, use {@link #configureTask(DataContext, RunConfiguration, BeforeRunTask)} instead.
   */
  @SuppressWarnings("DeprecatedIsStillUsed")
  @Deprecated
  public boolean configureTask(@NotNull RunConfiguration runConfiguration, @NotNull T task) {
    return false;
  }

  /**
   * @return {@code true} a promise returning true, if the task was changed.
   */
  public Promise<Boolean> configureTask(@NotNull DataContext context, @NotNull RunConfiguration configuration, @NotNull T task) {
    return Promises.resolvedPromise(configureTask(configuration, task));
  }

  public boolean canExecuteTask(@NotNull RunConfiguration configuration, @NotNull T task) {
    return true;
  }

  public abstract boolean executeTask(@NotNull DataContext context, @NotNull RunConfiguration configuration, @NotNull ExecutionEnvironment environment, @NotNull T task);

  /**
   * @return {@code true} if at most one task may be configured.
   */
  public boolean isSingleton() {
    // by default false because user can configure chain (java compile, generate something, java compile again)
    return false;
  }

  public static @Nullable <T extends BeforeRunTask<?>> BeforeRunTaskProvider<T> getProvider(@NotNull Project project, Key<T> key) {
    for (BeforeRunTaskProvider<BeforeRunTask<?>> provider : EP_NAME.getIterable(project)) {
      if (provider.getId() == key) {
        //noinspection unchecked
        return (BeforeRunTaskProvider<T>)provider;
      }
    }
    return null;
  }
}


text:
namespace Cyclops.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Web;
    using XF.Common;

    public class FileDropController :  ServiceController
    {

        [HttpPost]
        public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (HttpPostedFileBase file in files)
            {
                string filePath = Path.Combine("", file.FileName);
                System.IO.File.WriteAllBytes(filePath, this.ReadData(file.InputStream));
            }
            return this.Json("All files have been successfully stored.");
        }

        private byte[] ReadData(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

    }
}


text:
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from phylogenetic_trees.views import *

class Command(BaseCommand):
    classes=['001','002','003','004','005','006']

    def handle(self, *args, **options):
        for cl in self.classes:
            Tree = Treeclass()
            Tree.Prepare_file('',cl)

if __name__ == '__main__':
    z = Command()
    z.handle()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kooboo.CMS.ExtensionTemplate.Areas.BlogModule.Persistence
{
    public interface IDbInitializer
    {
        void InitializeDb(string connectionString);
        void DeleteDb(string connectionString);
    }
}


text:
hqDefine('app_manager/js/source_files', [
    'jquery',
    'underscore',
    'knockout',
    'hqwebapp/js/initial_page_data',
    'app_manager/js/multimedia_size_util',
    'app_manager/js/widgets',       // version dropdown
], function ($, _, ko, initialPageData, multimediaSizeUtil) {
    $(function () {
        $('.toggle-next').click(function (e) {
            e.preventDefault();
            $(this).parents('tr').next('tr').toggleClass("hide");
        });

        var currentVersion = initialPageData.get('current_version'),
            $form = $("#compare-form"),
            $select = $form.find("select");

        $form.find("button").click(function () {
            var buildId = $select.val();
            if (!buildId) {
                alert(gettext("Please enter a version to compare"));
                return;
            }
            window.location = initialPageData.reverse('diff', buildId);
        });
        if ($('#multimedia-sizes-diff-container').length) {
            var firstAppID = initialPageData.get('first_app_id');
            var secondAppID = initialPageData.get('second_app_id');
            var multimediaSizesContainer = multimediaSizeUtil.multimediaSizesContainer(initialPageData.get('build_profiles'));
            $("#build-profile-select-for-multimedia").koApplyBindings(multimediaSizesContainer);

            var multimediaSizeApp1 = multimediaSizeUtil.multimediaSizeView(firstAppID);
            $("#multimedia-sizes-container-1").koApplyBindings(multimediaSizeApp1);

            var multimediaSizeApp2 = multimediaSizeUtil.multimediaSizeView(secondAppID);
            $("#multimedia-sizes-container-2").koApplyBindings(multimediaSizeApp2);

            var multimediaSizesDiff = multimediaSizeUtil.multimediaSizeView(firstAppID, secondAppID);
            $("#multimedia-sizes-diff").koApplyBindings(multimediaSizesDiff);

            multimediaSizesContainer.views = [multimediaSizeApp1, multimediaSizeApp2, multimediaSizesDiff];
        }
    });
});


text:
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;

using MonoMac.AppKit;
using MonoMac.Foundation;

#endregion

namespace BasicSpriteMovement
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            NSApplication.Init();

            using (var p = new NSAutoreleasePool())
            {
                NSApplication.SharedApplication.Delegate = new AppDelegate();
                NSApplication.Main(args);
            }
        }
    }

    class AppDelegate : NSApplicationDelegate
    {
        private static SpriteMovementGame game;

        public override void FinishedLaunching(MonoMac.Foundation.NSObject notification)
        {
            // Handle a Xamarin.Mac Upgrade
            AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs a) =>
            {
                if (a.Name.StartsWith("MonoMac"))
                {
                    return typeof(MonoMac.AppKit.AppKitFramework).Assembly;
                }
                return null;
            };
            game = new SpriteMovementGame();
            game.Run();
        }

        public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)
        {
            return true;
        }
    }

}


text:
//
//  PPImageTask.h
//  PPAsyncDrawingKit
//
//  Created by DSKcpp on 2017/3/1.
//  Copyright © 2017年 DSKcpp. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol PPImageTask <NSObject>

/**
 图片URL
 */
@property (nonatomic, strong, readonly) NSString *URL;

/**
 根据URL从队列中获取任务,如果队列中没有,将创建一个新的任务

 @param URL 文件URL
 @return 任务
 */
+ (id<PPImageTask>)taskForURL:(NSString *)URL;

/**
 根据URL创建任务

 @param URL 图片URL
 @return 任务
 */
- (id<PPImageTask>)initWithURL:(NSString *)URL;

/**
 是否需要取消任务

 @return YES 的话就取消IO任务
 */
- (BOOL)isCancelled;

/**
 取消任务
 */
- (void)cancel;
@end

#pragma mark - IO Task
@interface PPImageIOTask : NSObject <PPImageTask> @end

#pragma mark - Downloader Task
typedef void (^PPImageDownloaderProgress)(CGFloat progress);

typedef void(^PPImageDownloaderCompletion)(UIImage * _Nullable image, NSError * _Nullable error);

@interface PPImageDownloaderTask : NSObject <PPImageTask>
@property (nullable, nonatomic, copy) PPImageDownloaderProgress downloadProgress;
@property (nonatomic, copy) PPImageDownloaderCompletion completion;
@property (nonatomic, strong) NSURLSessionDownloadTask *sessionDownloadTask;

- (nullable NSURLSessionDownloadTask *)createSessionTaskIfNecessaryWithBlock:(NSURLSessionDownloadTask *(^)())creationBlock;
@end

NS_ASSUME_NONNULL_END