text:
package edu.wpi.first.wpilib.plugins.core.installer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;

import edu.wpi.first.wpilib.plugins.core.WPILibCore;

public abstract class AbstractInstaller {
	protected File installLocation;
	protected String version, installedVersion;

	public AbstractInstaller(String version, String installedVersion, String path) {
		this.installLocation = new File(path);
		this.version = version;
		this.installedVersion = installedVersion;
	}

	/**
	 * @return The name of the feature being installed.
	 */
	protected abstract String getFeatureName();

	/**
	 * Update the installed version to the latest version.
	 * @param version The latest version installed.
	 */
	protected abstract void updateInstalledVersion(String version);

	/**
	 * @return The input stream to the zip file being installed.
	 */
	protected abstract InputStream getInstallResourceStream();

	/**
	 *
	 * @param sourcePath the file location of the zip file EX "/resources/simuation.zip"
	 * @param destinationPath the file location to unzip into EX "/home/peter/wpilib/simulation/plugins"
	 */
	public void installIfNecessary(String sourcePath, String destinationPath, boolean clean){
		//we're installing from this directory
		InputStream sourceStream;
		try {
			sourceStream = new FileInputStream(sourcePath);
			File destFile = new File(destinationPath);
			installIfNecessary(sourceStream, destFile, clean);
		} catch (FileNotFoundException e) {
			WPILibCore.logInfo("source zip file was not found: "+sourcePath);
		}
	}

	/**
	 * This function will delete an old wpilib subfolder if necessary and then copy
	 * the resource stream to the intended directory.
	 *
	 * @throws InstallException if bad things happen ...
	 */
	public void installIfNecessary(boolean clean){
		installIfNecessary(getInstallResourceStream(), installLocation, clean);
	}

	/**
	 * I'm thinking maybe instead of final things,
	 * create a UnzipJob class to extend Job and have these as parameters to the constructor*
	 */
	public void installIfNecessary(final InputStream sourceStream,final File destination, final boolean clean) {
		final Job installJob = new Job("Install " + getFeatureName()) {

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				monitor.beginTask(getTaskMessage(), IProgressMonitor.UNKNOWN);
				WPILibCore.logInfo("Installing "+getFeatureName()+" if necessary");

				if (!isInstalled()) {
					WPILibCore.logInfo("Install necessary for " + getFeatureName());
					try {
						install(sourceStream,destination, clean);
					} catch (InstallException e) {
						WPILibCore.logError("Error installing "+getFeatureName(), e);
						return new Status(IStatus.ERROR, WPILibCore.PLUGIN_ID,
								getErrorMessage(e));
					}
				}

				updateInstalledVersion(version);
				WPILibCore.logInfo("Installed" + getFeatureName());

				return Status.OK_STATUS;
			}

			private String getErrorMessage(InstallException ex) {
				String message = "Unable to install " + getFeatureName();
				if (ex.getCause() != null) {
					message += ": " + ex.getCause().getMessage();
				} else if (ex.getMessage() != null) {
					message += ": " + ex.getMessage();
				}

				message += ". See console for details.";
				return message;
			}

			private String getTaskMessage() {
				try {
					return "Extracting to " + installLocation.getCanonicalPath();
				} catch (IOException ex) {
					WPILibCore.logError("installIfNecessary().getTaskMessage()", ex);
					return "Extracting";
				}
			}
		};

		installJob.setUser(true);
		installJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
		installJob.schedule();
		try{
			installJob.join();
		} catch (InterruptedException e) {
			WPILibCore.logError("Install job interrupted", e);
		}
	}

	/**
	 *
	 * This function has been updated to guarantee that the wpilib folder date
	 * is older than the jar file being run, which ensures up to date tools.
	 *
	 * @return True for is there and newer, false otherwise.
	 */
	protected boolean isInstalled() {
		return installLocation.exists() && version.equals(installedVersion);
	}

	/**
	 *
	 * @TODO this function is very long and complicated. If all it does is unzip, it shouldn't be so hard.
	 *
	 * @param sourceStream input stream of zip file
	 * @param destination desired location for output of unzipping
	 * @throws InstallException
	 */
	protected void install(InputStream sourceStream, File destination, boolean clean) throws InstallException {
		if(destination.exists()) {
			if(!removeFileHandler(destination, !clean)) {
				Display.getDefault().asyncExec(new Runnable() {
					 public void run() {
							MessageDialog.openError(null, "Error",
								String.format("Could not update the wpilib folder.%n"
								+ "Close any WPILib tools or files and restart Eclipse."));
					 }
				});
			}
		}

		destination.mkdirs();
		final String osName = System.getProperty("os.name");
		try {
			// Unix-like OSes must preserve the executable bit; call unzip
			if (osName.startsWith("Mac OS X") || osName.startsWith("Linux")) {
				final File tmpFile = File.createTempFile(getFeatureName()+"-", ".zip");
				try {
					// Copy to temporary file
					try (final InputStream zip = sourceStream;
							final FileOutputStream fout = new FileOutputStream(tmpFile)) {
						copyStreams(zip, fout);
					}

					// Call 'unzip'
					final String[] cmd = {"unzip", "-q", "-o", tmpFile.getAbsolutePath(), "-d", destination.getAbsolutePath()};
					WPILibCore.logInfo("unzip "+tmpFile.getAbsolutePath()+" -d "+destination.getAbsolutePath());
					final Process unzipProcess = DebugPlugin.exec(cmd, destination);
					try (final InputStream is = unzipProcess.getInputStream()) {
						copyStreams(is, System.out); // Copy output to console
					}

					// Check result
					final int exitCode = unzipProcess.waitFor();
					if (exitCode > 1 || exitCode < 0) { // Exit code 1 indicates success with warnings
						throw new InstallException("Unzip process failed with code " + exitCode);
					}
				} finally {
					tmpFile.delete();
				}
			} else {
				ZipInputStream zip = new ZipInputStream(sourceStream);
				ZipEntry entry = zip.getNextEntry();
				while (entry != null) {
					File f = new File(destination, entry.getName());
					if (entry.isDirectory()) {
						f.mkdirs();
					} else {
						FileOutputStream fo = new FileOutputStream(f);
						copyStreams(zip, fo);
						fo.close();
					}

					zip.closeEntry();
					entry = zip.getNextEntry();
				}
				zip.close();
			}
		} catch (IOException | CoreException | InterruptedException ex) {
			throw new InstallException("Install encountered a problem", ex);
		}
	}

	private static void copyStreams(InputStream source, OutputStream destination) throws IOException {
		byte[] buffer = new byte[1024];
		int len;

		while((len = source.read(buffer)) >= 0){
			destination.write(buffer,0,len);
		}
	}

	/**
	 * Recursively remove all of the files and folders described by this file handler.
	 *
	 * @param file The file to remove
	 * @param testRun True to just test if the files can be deleted
	 * @return True if this and all subFiles were removed, false otherwise.
	 */
	private static boolean removeFileHandler(File file, boolean testRun) {
		// if normal files (data files and the like)
		if(file.isFile()) {
			if(testRun) return file.getParentFile().canWrite();
			else return file.delete();
		}
		// if folders
		else if(file.isDirectory()) {
			for(File f : file.listFiles()) {
				if(!removeFileHandler(f, testRun))
				{
					WPILibCore.logInfo("Can't acquire write handle on file: " + f.toString());
					return false;
				}
			}
			if(testRun) return file.getParentFile().canWrite();
			else return file.delete();
		}
		// I'm not sure what to do if the file is not normal or a directory ...
		else return false;
	}

	/**
	 * Indicates that an attempt to install a resource failed.
	 */
	private static class InstallException extends Exception {
		private static final long serialVersionUID = 4883122446098399588L;

		/**
		 * @see Exception#Exception()
		 */
		@SuppressWarnings("unused")
		public InstallException() {
			super();
		}

		/**
		 * @see Exception#Exception(String)
		 */
		public InstallException(String message) {
			super(message);
		}

		/**
		 * @see Exception#Exception(String, Throwable)
		 */
		public InstallException(String message, Throwable cause) {
			super(message, cause);
		}
	}
}


text:
# Deprecation

This README serves as documentation of the way chrome developers can alert web developers to their use of deprecated/removed features.
These alerts can include information on the deprecated feature, alternate features to use, and the removal timeline.
Follow the steps below to dispatch alerts via the [DevTools Issues](https://developer.chrome.com/docs/devtools/issues/) system.

## (1) Add new enum values

The three enums below should have consistent naming, and are all required to implement a new deprecation.

### (1a) [WebFeature](/third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom)

This should be named `kFeatureName` and placed at the bottom of the file.
If you have an existing `WebFeature` that can be used instead.

### (1b) C++ [DeprecationIssueType](/third_party/blink/renderer/core/inspector/inspector_audits_issue.h)

This should be called `kFeatureName`, and the list should be kept alphabetical.

### (1c) Browser Protocol [DeprecationIssueType](/third_party/blink/public/devtools_protocol/browser_protocol.pdl)

This should be called `FeatureName`, and the list should be kept alphabetical.

## (2) Count the deprecation

Pick one (or both if needed) of the following methods.

### (2a) Call `Deprecation::CountDeprecation`

This function requires a subclass of `ExecutionContext` and your new `WebFeature` to be passed in.
If you're already counting use with an existing `WebFeature`, you should swap `LocalDOMWindow::CountUse` with `ExecutionContext::CountDeprecation` as it will bump the counter for you.
If you only care about cross-site iframes, you can call `Deprecation::CountDeprecationCrossOriginIframe`.

### (2b) Add `DeprecateAs` to the relevant IDL

The [`DeprecateAs`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/bindings/IDLExtendedAttributes.md#DeprecateAs_m_a_c) attribute can be added to the IDL as follows:

```
[DeprecateAs=FeatureName] void myDeprecatedFunction();
```

## (3) Update [GetDeprecationInfo](/third_party/blink/renderer/core/frame/deprecation/deprecation.cc)

The new case statement should look like:
```
case WebFeature::kFeatureName:
  return DeprecationInfo::WithTranslation(feature, DeprecationIssueType::kFeatureName);
```

## (4) Update [AuditsIssue::ReportDeprecationIssue](/third_party/blink/renderer/core/inspector/inspector_audits_issue.cc)

The new case statement should look like:
```
case DeprecationIssueType::kFeatureName:
  type = protocol::Audits::DeprecationIssueTypeEnum::FeatureName;
  break;
```

## (5) Test

Please do not skip this step! Examples can be found in:
(/third_party/blink/web_tests/http/tests/inspector-protocol/issues/deprecation-issue.js)

Tests in this folder can be run like:
```
third_party/blink/tools/run_web_tests.py http/tests/inspector-protocol/issues
```

## (6) Merge steps 1-5 in a `chromium/src` CL

Please tag deprecation-devtool-issues@chromium.org for review.

## (7) Manually roll dependencies from `chromium/src` to `devtools/devtools-frontend`

[Check out](https://chromium.googlesource.com/devtools/devtools-frontend/+/refs/heads/main/docs/workflows.md) `devtools/devtools-frontend` on the same dev machine where you have `chromium/src` checked out.
Check new branch out in `devtools/devtools-frontend`, and run (adjusting directories as needed):
```
./scripts/deps/roll_deps.py ~/chromium/src ~/devtools/devtools-frontend
npm run generate-protocol-resources
```
This pushes the change from (1c) into `devtools/devtools-frontend` so you can use it in (9).

## (8) Merge step 7 in a `devtools/devtools-frontend` CL

Please tag deprecation-devtool-issues@chromium.org for review.

## (9) Update [DeprecationIssue](/third_party/devtools-frontend/src/front_end/models/issues_manager/DeprecationIssue.ts)

You'll need to add a new string and [description](https://chromium.googlesource.com/devtools/devtools-frontend/+/refs/heads/main/docs/localization/descriptions.md) to `UIStrings` with your deprecation message, for example:
```
/**
  *@description Additional information for translator on how and when this string is used
  */
  featureName: 'This is the message shown to the web developer in the issue.',
```

You'll also need to handle the new case in `DeprecationIssue::getDescription`, for example:
```
case Protocol.Audits.DeprecationIssueType.FeatureName:
  messageFunction = i18nLazyString(UIStrings.featureName);
  break;
```

If your deprecation has an associated [chrome platform status](https://chromestatus.com/features) and/or [chrome milestone](https://chromiumdash.appspot.com/schedule) be sure to set `feature` and/or `milestone` to include the relevant links, for example:
```
case Protocol.Audits.DeprecationIssueType.FeatureName:
  messageFunction = i18nLazyString(UIStrings.featureName);
  feature = 5684289032159232;
  milestone = 100;
  break;
```

## (10) Test

Please do not skip this step! Examples can be found in:
(/third_party/devtools-frontend/src/test/e2e/issues/deprecation-issues_test.ts)

Tests in this folder can be run like:
```
node scripts/test/run_test_suite.js --test-suite-path=gen/test/e2e --test-suite-source-dir=test/e2e --test-file-pattern=issues/*
```

## (11) Merge steps 9 and 10 in a `devtools/devtools-frontend` CL

Please tag deprecation-devtool-issues@chromium.org for review.

## (12) Wait for automatic roll dependencies from `devtools/devtools-frontend` to `chromium/src`

This will be done by the [AutoRoller](https://autoroll.skia.org/r/devtools-frontend-chromium) within a few hours.

## (13) Build Chrome from tip-of-trunk

Verify everything is working as expected.
If something is broken and you can't figure out why, reach out to deprecation-devtool-issues@chromium.org.

redpajama_set_name: RedPajamaGithub


text:
`some languages do not distinguish between different types of numeric value, a float is not an integer even without fractional part`

# [`jayschema`](https://github.com/natesilva/jayschema) failed tests

Some validators have deliberately chosen not to support parts of the spec. Go to the [`jayschema`](https://github.com/natesilva/jayschema) homepage to learn if
that is the case for these tests.

|test failed|reason
|-----------|------
|`maxLength validation, two supplementary Unicode code points is long enough`|Expected result: `true` but validator returned: `false`
|`minLength validation, one supplementary Unicode code point is not long enough`|Expected result: `false` but validator returned: `true`
|`validation of URIs, an invalid URI though valid URI reference`|Expected result: `false` but validator returned: `true`
|`remote ref, remote ref valid`|Expected result: `true` but validator returned: `false`
|`fragment within remote ref, remote fragment valid`|Expected result: `true` but validator returned: `"Cannot convert undefined or null to object"`
|`fragment within remote ref, remote fragment invalid`|Expected result: `false` but validator returned: `"Cannot convert undefined or null to object"`
|`ref within remote ref, ref within ref valid`|Expected result: `true` but validator returned: `"Cannot convert undefined or null to object"`
|`ref within remote ref, ref within ref invalid`|Expected result: `false` but validator returned: `"Cannot convert undefined or null to object"`
|`change resolution scope, changed scope ref valid`|Expected result: `true` but validator returned: `false`

**All other tests passed**.

[back to benchmarks](https://github.com/ebdrup/json-schema-benchmark)


text:
import XAxis from './XAxis';
import YAxis from './YAxis';

import Config from '../../Config';
import Component from './Component';

class XYAxis extends Component {
    private _x: XAxis;
    private _y: YAxis;

    constructor() {
        super();

        this._x = new XAxis();
        this._y = new YAxis();
    }

    public render(): void {
        this._y.render();
        this._x.render();

    }

    public update(data: any): void {
        this._y.update(data);
        this._x.update(data);
    }

    public configure(config: Config, svg: any) {
        super.configure(config, svg);
        this._y.configure(config, svg);
        this._x.configure(config, svg);
    }
    public transition() {
        this._x.transition();
        this._y.transition();
    }

    get x(): XAxis {
        return this._x;
    }

    get y(): YAxis {
        return this._y;
    }

    public clear() {
        this._x.clear();
        this._y.clear();
    }

}

export default XYAxis;


text:
> This page is a placeholder

deck.gl supports several models of event handling and viewport controls

## Viewport Controls

## States

...

## Customizing Controls

## About Event Handling


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

.paragraph-col {
  margin: 0;
  padding: 0;
}

.paragraph {
  padding: 2px 8px 4px 8px;
  min-height: 32px;
}

.labelBtn {
  padding: .2em .6em .3em;
  font-size: 75%;
  font-weight: bold;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  border-radius: .25em;
}

.note-jump {
  margin-top: 20px;
}

/*
  Add New Paragraph
 */

.new-paragraph{
  text-align: center;
  height: 7px;
  margin: -7px 2px 0 2px;
  cursor: pointer;
}

.new-paragraph:hover{
  background: #d3e5ea;
}

.new-paragraph:hover .plus-sign{
  display: block;
}

.plus-sign{
  display: none;
  height: 7px;
  margin: 0;
  color: #3071a9;
  line-height: 5px;
  font-size: 11.5px;
}

.noteBtnfa {
    margin-left: 3px;
}

.disable {
  opacity: 0.6!important;
  pointer-events: none;
}

.navbar-fixed-top,
.navbar-fixed-top .dropdown-menu {
  z-index: 10002;
}

.noteAction {
  margin-left: -10px;
  margin-right: -10px;
  font-family: 'Roboto', sans-serif;
  background: white;
  position: fixed;
  top: 50px;
  width: 100%;
  height: 54px;
  z-index: 10001;
}

.noteAction h3 {
  margin-top: 0;
  margin-bottom: 0;
  padding-top: 4px;
  padding-bottom: 4px;
}

.noteAction li {
  font-size: 12px;
  margin-bottom: 4px;
  color: #333333;
}

.form-control2 {
  width: 100%;
  height: 40px;
  font-size: 29px;
  line-height: 1.2;
  color: #555;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  padding: 7px 0;
  margin: 2px 0 0 14px;
}

.form-control-static2 {
  padding-top: 7px;
  font-size: 29px;
  margin-left: 15px;
  padding-bottom: 7px;
  margin-bottom: 0;
  display: inline-block;
}

.noOverflow {
    overflow: hidden !important;
}

/*
  Note Permissions Panel
*/

.permissions {
  background: white;
  padding: 10px 15px 15px 15px;
  margin-left: -10px;
  margin-right: -10px;
  font-family: 'Roboto', sans-serif;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  border-bottom: 1px solid #E5E5E5;
}

.permissions .permissionsForm {
  list-style-type: none;
  background: #EFEFEF;
  padding: 10px 10px 10px 10px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  border: 1px solid #E5E5E5;
}

.permissions .owners {
    width:60px;
    display: inline-block;
}

.permissions .readers {
    width:60px;
    display: inline-block;
}

.permissions .writers {
    width:60px;
    display: inline-block;
}
/*
  Note Setting Panel
*/

.setting {
  background: white;
  padding: 10px 15px 15px 15px;
  margin-left: -10px;
  margin-right: -10px;
  font-family: 'Roboto', sans-serif;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  border-bottom: 1px solid #E5E5E5;
}

.setting .interpreterSettings {
  list-style-type: none;
  background: #EFEFEF;
  padding: 10px 10px 10px 10px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  border: 1px solid #E5E5E5;
}

.setting .interpreterSettings div div {
  margin: 2px 0 2px 0;
}

.setting .interpreterSettings div div {
  cursor: pointer;
}

.setting .modal-header {
  border: 0;
}

.setting .modal-body {
  border: 0;
}

.setting .modal-footer {
  border: 0;
}

.cron-preset-container {
  padding: 10px 20px 0 20px;
  font-weight: normal;
  word-wrap: break-word;
  white-space: initial;
}

.cron-preset-container > div {
  margin: 10px 0;
}

.cron-preset {
  margin: 0px 2px;
  cursor: pointer;
}

.cron-info {
  margin: 5px;
  font-size: 11px;
}

.cron-preset.selected {
  color: #000;
  text-decoration: none;
  cursor: default;
}

.userlist {
  width: 230px;
  font-family: Georgia, Times, serif;
  font-size: 15px;
  position: absolute;
  z-index: 9999;
}

.userlist ul {
  list-style: none;
}

.userlist ul li {
  box-shadow: 3px 3px 5px #888888;
  display: list-item;
  text-decoration: none;
  color: #000000;
  background-color: #FFFFFF;
  line-height: 30px;
  border-bottom-style: none;
  border-bottom-width: 1px;
  border-bottom:1px  #CCCCCC solid;
  padding-left: 10px;
  cursor: pointer;
}

.userlist ul li:first-child {
  border-top-right-radius: 5px;
  border-top-left-radius: 5px;
}

.userlist ul li:last-child {
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
}

.userlist ul li strong {
  margin-right: 10px;
}

.userlist li:hover {
  background-color: #E0E0E0;
}

.userlist li:active,
.userlist li.active {
  background-color: #428BCA;
}


text:
package org.drools.workbench.screens.drltext.client.resources;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import org.drools.workbench.screens.drltext.client.resources.css.StylesCss;
import org.drools.workbench.screens.drltext.client.resources.images.DRLTextEditorImageResources;

public interface DRLTextEditorResources
        extends
        ClientBundle {

    public static final DRLTextEditorResources INSTANCE = GWT.create( DRLTextEditorResources.class );

    @Source("css/Styles.css")
    StylesCss CSS();

    DRLTextEditorImageResources images();

}


text:
package **PROJECT**;
//=====================================================================
//
// File:      $RCSfile$
// Version:   $Revision$
// Modified:  $Date$
//
//(c) Copyright 2006-2014 by Mentor Graphics Corp.  All rights reserved.
//
//========================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//========================================================================
//
// This class is responsible for providing the help ids for the
// **PLUGIN_NAME** plugin.
//
import org.eclipse.ui.PlatformUI;

/**
 * Help context ids for the **VIEW_NAME**.
 * <p>
 * This interface contains constants only; it is not intended to be implemented
 * or extended.
 * </p>
 *
 */
public interface I**HELPCONTEXTIDS_PREFIX**HelpContextIds {
  public static final String PREFIX = "**PROJECT**."; //$NON-NLS-1$

  // Actions
  public static final String FILTER_SELECTION_ACTION = PREFIX + "filter_selection_action_context"; //$NON-NLS-1$
  public static final String GOTO_RESOURCE_ACTION = PREFIX + "goto_resource_action_context"; //$NON-NLS-1$
  public static final String **PREFIX**_MOVE_ACTION = PREFIX + "**PREFIX**_move_action_context"; //$NON-NLS-1$
  public static final String **PREFIX**_RENAME_ACTION = PREFIX + "**PREFIX**_rename_action_context"; //$NON-NLS-1$
  public static final String SHOW_IN_EXPLORER_ACTION = PREFIX + "show_in_explorer_action_context"; //$NON-NLS-1$
  public static final String SORT_VIEW_ACTION = PREFIX + "sort_view_action_context"; //$NON-NLS-1$
  public static final String COPY_ACTION = PREFIX + "**PREFIX**_copy_action_context"; //$NON-NLS-1$
  public static final String PASTE_ACTION = PREFIX + "**PREFIX**_paste_action_context"; //$NON-NLS-1$
  public static final String COLLAPSE_ALL_ACTION = PREFIX + "collapse_all_action_context"; //$NON-NLS-1$

  // Dialogs
  public static final String GOTO_RESOURCE_DIALOG = PREFIX + "goto_resource_dialog_context"; //$NON-NLS-1$

  // Views
  public static final String **VIEW_NAME**Id = PREFIX + "**VIEW_NAME**Id"; //$NON-NLS-1$
}


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.integer :comment_thread_id
      t.integer :user_id
      t.text :body
      t.boolean :published

      t.timestamps
    end

    add_index :comments, :comment_thread_id
    add_index :comments, :user_id
    add_index :comments, :published
    add_index :comments, [:comment_thread_id, :published]

    add_column :photographs, :enable_comments, :boolean, default: false
    add_column :users, :enable_comments, :boolean, default: false
  end
end


text:
package com.knewton.titanik;

import com.tinkerpop.blueprints.Edge;

public interface TitanikEdge extends Edge, TitanikElement {
}


text:
<?php

/* PrognozMagazineBundle:Photo:show.html.twig */
class __TwigTemplate_a2437f3ad7a840539375b8ebe289a836 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
Photo

                Id
                ";
        // line 10
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "id"), "html", null, true);
        echo "

                Name
                ";
        // line 14
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "name"), "html", null, true);
        echo "

        env->getExtension('routing')->getPath("api_photo");
        echo "\">
            Back to the list

        env, $this->env->getExtension('routing')->getPath("api_photo_edit", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
        echo "\">
            Edit

";
        // line 30
        echo         $this->env->getExtension('form')->renderer->renderBlock($this->getContext($context, "delete_form"), 'form');
        echo "

";
    }

    public function getTemplateName()
    {
        return "PrognozMagazineBundle:Photo:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  71 => 30,  64 => 26,  56 => 21,  46 => 14,  39 => 10,  31 => 4,  28 => 3,);
    }
}


text:
class SidebarField
  attr_accessor :key, :options, :default

  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::FormTagHelper
  include ActionView::Helpers::FormOptionsHelper

  def initialize(key, default, options = {})
    @key = key.to_s
    @default = default
    @options = options
  end

  def label
    options[:label] || key.humanize.gsub(/url/i, "URL")
  end

  def label_html(_sidebar)
    tag.label(label)
  end

  def input_html(sidebar)
    text_field_tag(input_name(sidebar), current_value(sidebar), class: "form-control")
  end

  def line_html(sidebar)
    tag.div(label_html(sidebar) + input_html(sidebar), class: "form-group")
  end

  def input_name(sidebar)
    "configure[#{sidebar.id}][#{key}]"
  end

  def canonicalize(value)
    value
  end

  def current_value(sidebar)
    canonicalize(sidebar.config[key])
  end

  class SelectField < self
    def input_html(sidebar)
      select_tag(input_name(sidebar),
                 options_for_select(options[:choices], current_value(sidebar)),
                 options)
    end
  end

  class TextAreaField < self
    def input_html(sidebar)
      html_options = { "rows" => "10", "class" => "form-control" }.
        update(options.stringify_keys)
      text_area_tag(input_name(sidebar), current_value(sidebar), html_options)
    end
  end

  class RadioField < self
    def input_html(sidebar)
      choices = options[:choices].map do |choice|
        value = value_for(choice)
        radio_button = radio_button_tag(input_name(sidebar),
                                        value,
                                        value == current_value(sidebar),
                                        options)
        tag.div(tag.label(radio_button + label_for(choice)), class: "radio")
      end
      safe_join(choices)
    end

    def label_for(choice)
      choice.is_a?(Array) ? choice.last : choice.to_s.humanize
    end

    def value_for(choice)
      choice.is_a?(Array) ? choice.first : choice
    end
  end

  class CheckBoxField < self
    def line_html(sidebar)
      content = hidden_field_tag(input_name(sidebar), 0) +
        tag.label(check_box_tag(input_name(sidebar), 1,
                                current_value(sidebar), options) + label)
      tag.div(content, class: "checkbox")
    end

    def canonicalize(value)
      case value
      when "0"
        false
      else
        true
      end
    end
  end

  def self.build(key, default, options)
    class_for(options).new(key, default, options)
  end

  def self.class_for(options)
    case options[:input_type]
    when :text_area
      TextAreaField
    when :textarea
      TextAreaField
    when :radio
      RadioField
    when :checkbox
      CheckBoxField
    when :select
      SelectField
    else
      if options[:choices]
        SelectField
      else
        self
      end
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.ai.metricsadvisor.implementation.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The AzureSQLConnectionStringParamPatch model. */
@Fluent
public final class AzureSQLConnectionStringParamPatch {
    /*
     * The connection string to access the Azure SQL.
     */
    @JsonProperty(value = "connectionString")
    private String connectionString;

    /**
     * Get the connectionString property: The connection string to access the Azure SQL.
     *
     * @return the connectionString value.
     */
    public String getConnectionString() {
        return this.connectionString;
    }

    /**
     * Set the connectionString property: The connection string to access the Azure SQL.
     *
     * @param connectionString the connectionString value to set.
     * @return the AzureSQLConnectionStringParamPatch object itself.
     */
    public AzureSQLConnectionStringParamPatch setConnectionString(String connectionString) {
        this.connectionString = connectionString;
        return this;
    }
}


text:
package com.google.errorprone.bugpatterns.testdata;

import junit.framework.TestCase;
import org.junit.Test;

/** @author alexeagle@google.com (Alex Eagle) */
public class DeadExceptionTestingNegativeCases extends TestCase {

  public void testShouldAllowTestingOfExceptionConstructorSideEffects() {
    try {
      new IllegalArgumentException((Throwable) null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }
  }

  @Test
  public void shouldAllowTestingOfExceptionConstructorSideEffects() {
    try {
      new IllegalArgumentException((Throwable) null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }
  }
}


text:
using System;
using System.Net;
//using System.Windows;
//using System.Windows.Controls;
//using System.Windows.Documents;
//using System.Windows.Ink;
//using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Animation;
//using System.Windows.Shapes;
using System.Collections.Generic;
using Csla;
using Csla.Serialization;
using Csla.DataPortalClient;
using Csla.Core;

namespace SilverlightClassLibrary
{
  public class SLIdentity : Csla.Security.CslaIdentity
  {
    public bool InRole(string role)
    {
      return base.IsInRole(role);
    }

    [Serializable()]
    public class CredentialsCriteria : CriteriaBase
    {
      private string _username;
      private string _password;
      private string _roles;

      public string Username
      {
        get
        {
          return _username;
        }
      }

      public string Password
      {
        get
        {
          return _password;
        }
      }

      public string Roles
      {
        get
        {
          return _roles;
        }
      }

#if !SILVERLIGHT
      private CredentialsCriteria()
      { }
#endif

      public CredentialsCriteria(string username, string password, string roles)
        : base(typeof(SLIdentity))
      {
        _username = username;
        _password = password;
        _roles = roles;
      }

      protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
      {
        info.AddValue("_username", _username);
        info.AddValue("_password", _password);
        info.AddValue("_roles", _roles);
        base.OnGetState(info, mode);
      }

      protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
      {
        _username = (string)info.Values["_username"].Value;
        _password = (string)info.Values["_password"].Value;
        _roles = (string)info.Values["_roles"].Value;
        base.OnSetState(info, mode);
      }
    }

#if SILVERLIGHT
    public void DataPortal_Fetch(LocalProxy<SLIdentity>.CompletedHandler completed, CredentialsCriteria criteria)
    {
      if (criteria.Username == "TestUser" && criteria.Password == "1234")
      {
        SetCslaIdentity(new MobileList<string>(criteria.Roles.Split(';')), true, criteria.Username);
        completed(this, null);
      }
      else
      {
        SetCslaIdentity(null, false, "");
        completed(this, null);
      }
    }

    public static void GetIdentity(string username, string password, string roles, EventHandler<DataPortalResult<SLIdentity>> completed)
    {
      GetCslaIdentity<SLIdentity>(completed, new CredentialsCriteria(username, password, roles));
    }
#endif
  }
}


text:
package org.deviceconnect.android.deviceplugin.host.profile;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import org.deviceconnect.android.deviceplugin.host.BuildConfig;
import org.deviceconnect.android.deviceplugin.host.HostDeviceService;
import org.deviceconnect.android.deviceplugin.host.file.FileData;
import org.deviceconnect.android.deviceplugin.host.file.FileDataManager;
import org.deviceconnect.android.deviceplugin.host.file.FileDataManager.FileModifiedListener;
import org.deviceconnect.android.event.Event;
import org.deviceconnect.android.event.EventError;
import org.deviceconnect.android.event.EventManager;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.FileDescriptorProfile;
import org.deviceconnect.message.DConnectMessage;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * FileDescriptorプロファイル.
 *
 * @author NTT DOCOMO, INC.
 */
public class HostFileDescriptorProfile extends FileDescriptorProfile {

    /** Error. */
    private static final int ERROR_VALUE_IS_NULL = 100;

    /** ファイルデータ管理クラス. */
    private FileDataManager mFileDataManager;

    /** 時刻フォーマット. */
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss+0900", Locale.getDefault());

    /**
     * コンストラクタ.
     *
     * @param mgr ファイルデータ管理クラス.
     */
    public HostFileDescriptorProfile(final FileDataManager mgr) {
        mFileDataManager = mgr;
        mFileDataManager.setFileModifiedListener(new FileModifiedListener() {
            @Override
            public void onWatchFile(final List<File> files) {
                sendWatchFileEvent(files);
            }
        });
    }

    @Override
    protected boolean onGetOpen(final Intent request, final Intent response, final String serviceId, final String path,
            final Flag flag) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (path == null) {
            MessageUtils.setInvalidRequestParameterError(response, "path is invalid.");
        } else if (path.trim().equals("") || path.trim().equals("/")) {
            MessageUtils.setInvalidRequestParameterError(response, "path is invalid.");
        } else if (flag == Flag.UNKNOWN) {
            MessageUtils.setInvalidRequestParameterError(response, "flag is invalid.");
        } else {
            FileDataManager mgr = getFileDataManager();
            FileData file = mgr.getFileData(path);
            if (file != null) {
                MessageUtils.setIllegalDeviceStateError(response, "Already file is open.");
            } else {
                try {
                    file = mgr.openFileData(path, flag);
                    if (BuildConfig.DEBUG) {
                        if (file != null) {
                            Log.e("Host", "file is opened.");
                        }
                    }
                    setResult(response, DConnectMessage.RESULT_OK);
                } catch (IOException e) {
                    MessageUtils.setIllegalDeviceStateError(response, "file cannot open.");
                } catch (IllegalStateException e) {
                    MessageUtils.setIllegalDeviceStateError(response, "file is already opened.");
                }
            }
        }
        return true;
    }

    @Override
    protected boolean onGetRead(final Intent request, final Intent response, final String serviceId, final String path,
            final Long length, final Long position) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (path == null) {
            MessageUtils.setInvalidRequestParameterError(response, "path is invalid.");
        } else if (length == null || length < 0) {
            MessageUtils.setInvalidRequestParameterError(response, "length is invalid.");
        } else if (position != null && position < 0) {
            MessageUtils.setInvalidRequestParameterError(response, "position is invalid.");
        } else {
            long pos = 0;
            if (position != null) {
                pos = position;
            }

            FileDataManager mgr = getFileDataManager();
            FileData file = mgr.getFileData(path);
            if (file == null) {
                MessageUtils.setInvalidRequestParameterError(response, "file is not opened.");
            } else {
                mgr.readFile(file, (int) pos, length.intValue(), new FileDataManager.ReadFileCallback() {
                    @Override
                    public void onSuccess(@NonNull final String data) {
                        setResult(response, DConnectMessage.RESULT_OK);
                        setSize(response, data.length());
                        setFileData(response, data);
                        sendResponse(response);
                    }

                    @Override
                    public void onFail() {
                        MessageUtils.setIllegalDeviceStateError(response, "file cannot be read.");
                        sendResponse(response);
                    }
                });
            }
            return false;
        }
        return true;
    }

    @Override
    protected boolean onPutClose(final Intent request, final Intent response, final String serviceId,
            final String path) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (path == null) {
            MessageUtils.setInvalidRequestParameterError(response, "path is invalid.");
        } else {
            FileDataManager mgr = getFileDataManager();
            FileData file = mgr.getFileData(path);
            if (file != null) {
                boolean isSuccess = mgr.closeFileData(path);
                if (isSuccess) {
                    setResult(response, DConnectMessage.RESULT_OK);
                } else {
                    MessageUtils.setIllegalServerStateError(response, "file is not opened.");
                }
            } else {
                MessageUtils.setIllegalServerStateError(response, "file is not opened.");
            }
        }
        return true;
    }

    @Override
    protected boolean onPutWrite(final Intent request, final Intent response, final String serviceId, final String path,
            final byte[] data, final Long position) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (path == null) {
            MessageUtils.setInvalidRequestParameterError(response, "path is invalid.");
        } else if (data == null) {
            MessageUtils.setInvalidRequestParameterError(response, "data is invalid.");
        } else if (position != null && position < 0) {
            MessageUtils.setInvalidRequestParameterError(response, "position is invalid.");
        } else {
            int pos = 0;
            if (position != null) {
                pos = position.intValue();
            }

            FileDataManager mgr = getFileDataManager();
            FileData file = mgr.getFileData(path);
            if (file == null) {
                MessageUtils.setInvalidRequestParameterError(response, "file is not opened.");
            } else if (file.getFlag() != Flag.RW) {
                MessageUtils.setInvalidRequestParameterError(response, "file must be opened with Read & Write mode.");
            } else {
                if (pos < 0 || data.length < pos) {
                    MessageUtils.setInvalidRequestParameterError(response, "position is invalid.");
                } else {
                    mgr.writeFile(file, data, pos, new FileDataManager.WriteFileCallback() {
                        @Override
                        public void onSuccess() {
                            setResult(response, DConnectMessage.RESULT_OK);
                            sendResponse(response);
                        }

                        @Override
                        public void onFail() {
                            MessageUtils.setUnknownError(response, "file cannot write.");
                            sendResponse(response);
                        }
                    });
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected boolean onGetOnWatchFile(final Intent request, final Intent response, final String serviceId) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else {
            FileDataManager mgr = getFileDataManager();
            mgr.getUpdatedFiles(new FileDataManager.CheckUpdatedFilesCallback() {
                @Override
                public void onSuccess(@NonNull List<File> files) {
                    if (files.size() > 0) {
                        Bundle f = createFile(files.get(0));
                        if (f != null) {
                            setFile(response, f);
                        }
                    }
                    setResult(response, DConnectMessage.RESULT_OK);
                    sendResponse(response);
                }

                @Override
                public void onFail() {
                    MessageUtils.setIllegalServerStateError(response,
                            "READ_EXTERNAL_STORAGE permission not granted.");
                    sendResponse(response);
                }
            });
            return false;
        }
        return true;
    }

    @Override
    protected boolean onPutOnWatchFile(final Intent request, final Intent response, final String serviceId,
            final String sessionKey) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (sessionKey == null) {
            MessageUtils.setInvalidRequestParameterError(response);
        } else {
            EventError error = EventManager.INSTANCE.addEvent(request);
            if (error == EventError.NONE) {
                List<Event> events = EventManager.INSTANCE.getEventList(request);
                if (events.size() == 1) {
                    mFileDataManager.startTimer();
                }
                setResult(response, DConnectMessage.RESULT_OK);
            } else {
                MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not register event.");
            }
        }
        return true;
    }

    @Override
    protected boolean onDeleteOnWatchFile(final Intent request, final Intent response, final String serviceId,
            final String sessionKey) {
        if (serviceId == null) {
            createEmptyServiceId(response);
        } else if (!checkServiceId(serviceId)) {
            createNotFoundService(response);
        } else if (sessionKey == null) {
            MessageUtils.setInvalidRequestParameterError(response);
        } else {
            EventError error = EventManager.INSTANCE.removeEvent(request);
            if (error == EventError.NONE) {
                List<Event> events = EventManager.INSTANCE.getEventList(request);
                if (events.size() == 0) {
                    mFileDataManager.stopTimer();
                }
                setResult(response, DConnectMessage.RESULT_OK);
            } else {
                MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not unregister event.");
            }
        }
        return true;
    }

    /**
     * サービスIDをチェックする.
     *
     * @param serviceId サービスID
     * @return serviceIdがテスト用サービスIDに等しい場合はtrue、そうでない場合はfalse
     */
    private boolean checkServiceId(final String serviceId) {
        return HostServiceDiscoveryProfile.SERVICE_ID.equals(serviceId);
    }

    /**
     * サービスIDが空の場合のエラーを作成する.
     *
     * @param response レスポンスを格納するIntent
     */
    private void createEmptyServiceId(final Intent response) {
        MessageUtils.setEmptyServiceIdError(response, "Service ID is empty.");
    }

    /**
     * サービスが発見できなかった場合のエラーを作成する.
     *
     * @param response レスポンスを格納するIntent
     */
    private void createNotFoundService(final Intent response) {
        MessageUtils.setNotFoundServiceError(response, "Service is not found.");
    }

    /**
     * onwatchイベントを送信する.
     *
     * @param files 変更のあったファイル一覧
     */
    private void sendWatchFileEvent(final List<File> files) {
        HostDeviceService service = (HostDeviceService) getContext();

        List<Event> events = EventManager.INSTANCE.getEventList(HostServiceDiscoveryProfile.SERVICE_ID, PROFILE_NAME,
                null, ATTRIBUTE_ON_WATCH_FILE);
        synchronized (events) {
            for (File f : files) {
                Bundle file = createFile(f);
                if (file != null) {
                    for (Event event : events) {
                        Intent intent = EventManager.createEventMessage(event);
                        setFile(intent, file);
                        service.sendEvent(intent, event.getAccessToken());
                    }
                }
            }
        }
    }

    /**
     * Fileデータを作成する.
     *
     * @param f ファイル
     * @return Fileデータ
     */
    private Bundle createFile(final File f) {
        String path = mFileDataManager.getPath(f);
        if (path == null) {
            return null;
        }

        Bundle file = new Bundle();
        setPath(file, path);
        setCurr(file, mDateFormat.format(new Date(f.lastModified())));
        return file;
    }

    /**
     * ファイル管理クラスを取得する.
     *
     * @return ファイル管理クラス
     */
    private FileDataManager getFileDataManager() {
        return mFileDataManager;
    }
}


text:
"""
log.py

Created by Thomas Mangin on 2011-11-29.
Copyright (c) 2011-2013  Exa Networks. All rights reserved.
"""

import time
import logging

from .message import message_store
from .message import usage_store
from .history import History

class Logger:
	mailbox = message_store
	history = History()

	def __init__ (self, name, active=True, loglevel=logging.DEBUG):
		self.name = str(name)
		self.active = active
		self.loglevel = loglevel

	def log (self, text, loglevel):
		now = time.localtime()
		self.history.record(now, self.name, loglevel, text)

		if self.active is True and loglevel >= self.loglevel:
			self.mailbox.addMessage((self.name, loglevel, now, text))
			res = True
		else:
			res = None

		return res

	def stdout (self, message):
		print message

	def debug (self, message):
		self.log(message, logging.DEBUG)

	def info (self, message):
		self.log(message, logging.INFO)

	def notice (self, message):
		self.log(message, logging.INFO)

	def warning (self, message):
		self.log(message, logging.WARNING)

	def error (self, message):
		self.log(message, logging.ERROR)

	def critical (self, message):
		self.log(message, logging.CRITICAL)

	def alert (self, message):
		self.log(message, logging.WARNING)

	def emergency (self, message):
		self.log(message, logging.CRITICAL)

class UsageLogger (Logger):
	mailbox = usage_store

	def logRequest (self, client_id, client_ip, command, url, status, destination):
		if self.active:
			now = time.time()
			line = '%s %.02f %s %s %s %s %s/%s' % (
				time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
				now, client_id, client_ip, command, url, status, destination
			)

			res = self.log(line, logging.INFO)
		else:
			res = None

		return res


text:
module Kafka.Protocol.ProtocolSpec where

import SpecHelper
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as BS

import Kafka.Client

spec :: Spec
spec = do
  describe "Kafka.Protocol" $ do
    context "MessageSet" $ do
      it "Test1: Default Value" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "Test"
        testMs ms
      it "Test2: No Value" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture ""
        testMs ms
      it "Test3: Value with special characters" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "[*+!^^!{}//\\%ç]"
        testMs ms
      it "Test4: JSON Value" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "[ obj : { value : 123 }]"
        testMs ms

    context "ProduceRequest" $ do
      it "Serialize/Parse: No Topic" $ do
        let r = getRequestMessageFixture $ getProduceRequestFixture []
        testPrRq r

      it "Serialize/Parse: One Topic, No Partition" $ do
        let t = getTopicFixture "A" []
        let r = getRequestMessageFixture $ getProduceRequestFixture [t]
        testPrRq r

      it "Serialize/Parse: Multi Topic, No Partition" $ do
        let t1 = getTopicFixture "A" []
        let t2 = getTopicFixture "B" []
        let t3 = getTopicFixture "C" []
        let r = getRequestMessageFixture $ getProduceRequestFixture [t1, t2, t3]
        testPrRq r

      it "Serialize/Parse: One Topic, One Partition, No MessageSet" $ do
        let p = getRqPrPartitionFixture []
        let t = getTopicFixture "A" [p]
        let r = getRequestMessageFixture $ getProduceRequestFixture [t]
        testPrRq r

      it "Serialize/Parse: One Topic, Multi Partition, No MessageSet" $ do
        let p =  getRqPrPartitionFixture  []
        let t = getTopicFixture "A" [p, p, p]
        let r = getRequestMessageFixture $ getProduceRequestFixture [t]
        testPrRq r

      it "Serialize/Parse: One Topic, One Partition, One MessageSet" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "Test"
        let p = getRqPrPartitionFixture [ms]
        let t = getTopicFixture "A" [p]
        let r = getRequestMessageFixture $ getProduceRequestFixture [t]
        testPrRq r

      it "Serialize/Parse: One Topic, One Partition, Multi MessageSet" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "Test"
        let p = getRqPrPartitionFixture [ms, ms, ms]
        let t = getTopicFixture "A" [p]
        let r = getRequestMessageFixture $ getProduceRequestFixture [t]
        testPrRq r

      it "Serialize/Parse: One Topic, One Partition, One MessageSet" $ do
        let ms = getMessageSetFixture $ getMessageFixture $ getPayloadFixture "Test"
        let p = getRqPrPartitionFixture [ms, ms, ms]
        let t1 = getTopicFixture "A" [p,p,p]
        let t2 = getTopicFixture "B" [p,p,p]
        let t3 = getTopicFixture "C" [p,p,p]
        let r = getRequestMessageFixture $ getProduceRequestFixture [t1, t2, t3]
        testPrRq r

main :: IO()
main = hspec spec

testMs :: MessageSet -> Expectation
testMs m = (runGet messageSetParser $ runPut $ buildMessageSet m) `shouldBe` m

testPrRq :: RequestMessage -> Expectation
testPrRq req = (runGet requestMessageParser $ runPut $ buildRqMessage req) `shouldBe` req


text:
FROM gcr.io/oss-fuzz-base/base-builder@sha256:1b6a6993690fa947df74ceabbf6a1f89a46d7e4277492addcd45a8525e34be5a
RUN apt-get update && apt-get install -y build-essential ruby bison ninja-build \
    cmake zlib1g-dev libbz2-dev liblzma-dev
RUN git clone --depth 1 https://github.com/mruby/mruby mruby
RUN git clone --depth 1 https://github.com/bshastry/mruby_seeds.git mruby_seeds
WORKDIR mruby
COPY build.sh *.c *.options *.dict $SRC/


text:
package org.apache.flink.runtime.resourcemanager.slotmanager;

import org.apache.flink.api.common.JobID;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.instance.InstanceID;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.resourcemanager.WorkerResourceSpec;
import org.apache.flink.runtime.resourcemanager.registration.TaskExecutorConnection;
import org.apache.flink.runtime.rest.messages.taskmanager.SlotInfo;
import org.apache.flink.runtime.slots.ResourceRequirements;
import org.apache.flink.runtime.taskexecutor.SlotReport;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * The slot manager is responsible for maintaining a view on all registered task manager slots,
 * their allocation and all pending slot requests. Whenever a new slot is registered or an allocated
 * slot is freed, then it tries to fulfill another pending slot request. Whenever there are not
 * enough slots available the slot manager will notify the resource manager about it via {@link
 * ResourceActions#allocateResource(WorkerResourceSpec)}.
 *
 * <p>In order to free resources and avoid resource leaks, idling task managers (task managers whose
 * slots are currently not used) and pending slot requests time out triggering their release and
 * failure, respectively.
 */
public interface SlotManager extends AutoCloseable {
    int getNumberRegisteredSlots();

    int getNumberRegisteredSlotsOf(InstanceID instanceId);

    int getNumberFreeSlots();

    int getNumberFreeSlotsOf(InstanceID instanceId);

    /**
     * Get number of workers SlotManager requested from {@link ResourceActions} that are not yet
     * fulfilled.
     *
     * @return a map whose key set is all the unique resource specs of the pending workers, and the
     *     corresponding value is number of pending workers of that resource spec.
     */
    Map<WorkerResourceSpec, Integer> getRequiredResources();

    ResourceProfile getRegisteredResource();

    ResourceProfile getRegisteredResourceOf(InstanceID instanceID);

    ResourceProfile getFreeResource();

    ResourceProfile getFreeResourceOf(InstanceID instanceID);

    Collection<SlotInfo> getAllocatedSlotsOf(InstanceID instanceID);

    /**
     * Starts the slot manager with the given leader id and resource manager actions.
     *
     * @param newResourceManagerId to use for communication with the task managers
     * @param newMainThreadExecutor to use to run code in the ResourceManager's main thread
     * @param newResourceActions to use for resource (de-)allocations
     */
    void start(
            ResourceManagerId newResourceManagerId,
            Executor newMainThreadExecutor,
            ResourceActions newResourceActions);

    /** Suspends the component. This clears the internal state of the slot manager. */
    void suspend();

    /**
     * Notifies the slot manager that the resource requirements for the given job should be cleared.
     * The slot manager may assume that no further updates to the resource requirements will occur.
     *
     * @param jobId job for which to clear the requirements
     */
    void clearResourceRequirements(JobID jobId);

    /**
     * Notifies the slot manager about the resource requirements of a job.
     *
     * @param resourceRequirements resource requirements of a job
     */
    void processResourceRequirements(ResourceRequirements resourceRequirements);

    /**
     * Registers a new task manager at the slot manager. This will make the task managers slots
     * known and, thus, available for allocation.
     *
     * @param taskExecutorConnection for the new task manager
     * @param initialSlotReport for the new task manager
     * @param totalResourceProfile for the new task manager
     * @param defaultSlotResourceProfile for the new task manager
     * @return True if the task manager has not been registered before and is registered
     *     successfully; otherwise false
     */
    boolean registerTaskManager(
            TaskExecutorConnection taskExecutorConnection,
            SlotReport initialSlotReport,
            ResourceProfile totalResourceProfile,
            ResourceProfile defaultSlotResourceProfile);

    /**
     * Unregisters the task manager identified by the given instance id and its associated slots
     * from the slot manager.
     *
     * @param instanceId identifying the task manager to unregister
     * @param cause for unregistering the TaskManager
     * @return True if there existed a registered task manager with the given instance id
     */
    boolean unregisterTaskManager(InstanceID instanceId, Exception cause);

    /**
     * Reports the current slot allocations for a task manager identified by the given instance id.
     *
     * @param instanceId identifying the task manager for which to report the slot status
     * @param slotReport containing the status for all of its slots
     * @return true if the slot status has been updated successfully, otherwise false
     */
    boolean reportSlotStatus(InstanceID instanceId, SlotReport slotReport);

    /**
     * Free the given slot from the given allocation. If the slot is still allocated by the given
     * allocation id, then the slot will be marked as free and will be subject to new slot requests.
     *
     * @param slotId identifying the slot to free
     * @param allocationId with which the slot is presumably allocated
     */
    void freeSlot(SlotID slotId, AllocationID allocationId);

    void setFailUnfulfillableRequest(boolean failUnfulfillableRequest);
}


text:
/* */
"use strict";
var nwmatcher = require("nwmatcher/src/nwmatcher-noqsa");
var memoizeQuery = require("../utils").memoizeQuery;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
module.exports = function(core) {
  [core.Document, core.DocumentFragment, core.Element].forEach(function(Class) {
    Class.prototype.querySelector = memoizeQuery(function(selectors) {
      return addNwmatcher(this).first(String(selectors), this);
    });
    Class.prototype.querySelectorAll = memoizeQuery(function(selectors) {
      return new core.NodeList(addNwmatcher(this).select(String(selectors), this));
    });
  });
  core.Element.prototype.matches = memoizeQuery(function(selectors) {
    return addNwmatcher(this).match(this, selectors);
  });
};
module.exports.querySelector = function(parentNode, selectors) {
  if (!domSymbolTree.hasChildren(parentNode) || (parentNode === parentNode._ownerDocument && !parentNode._documentElement)) {
    return null;
  }
  return addNwmatcher(parentNode).first(selectors, parentNode);
};
function addNwmatcher(parentNode) {
  var document = parentNode._ownerDocument;
  if (!document._nwmatcher) {
    document._nwmatcher = nwmatcher({document: document});
    document._nwmatcher.configure({UNIQUE_ID: false});
  }
  return document._nwmatcher;
}


text:
[![Build Status](https://travis-ci.org/TalAter/Corti.svg?branch=master)](https://travis-ci.org/TalAter/Corti)

Corti is a drop in replacement for the browser's SpeechRecognition object. It mocks some of the behaviour of the native object to facilitate automated testing, and provides a number of extra methods beyond the spec to help testing.

For an example of using Corti to test a real project, check out [SpeechKITT](https://github.com/TalAter/SpeechKITT).

To easily use Speech Recognition in your own project, check out [annyang](https://github.com/TalAter/annyang).

### Sample Test With Corti

````javascript
// Patch the current environment with a mock Speech Recognition object
Corti.patch();

// Interact with the mock object, like you would with the real SpeechRecognition object
var recognition = new window.SpeechRecognition();
recognition.onstart = function() {console.log("I'm listening");};
recognition.addEventListener('result', function(sre) {
  console.log(sre.results.item(sre.resultIndex).item(0).transcript);
});
recognition.addEventListener('end', function() {console.log("Quiet");});
recognition.continuous = true;

// Use extra utility methods added to the mock object to assist with testing
expect(recognition.isStarted()).toBe(false);
recognition.start();
expect(recognition.isStarted()).toBe(true);
recognition.abort();
expect(recognition.isStarted()).toBe(false);

// Simulate speech recognition
recognition.addEventListener('result', mySpyFunction);
expect(mySpyFunction).not.toHaveBeenCalled();
recognition.say("Next time you want to stab me in the back, have the guts to do it to my face");
expect(mySpyFunction).toHaveBeenCalled();
````

### Methods Mocked

* start()
* abort()
* stop()
* addEventListener()

### Attributes Mocked

* interimResults
* lang
* continuous
* maxAlternatives
* onstart
* onend
* onresult

### Events Mocked

* start
* end
* result

### Event Objects Mocked

* SpeechRecognitionEvent
* SpeechRecognitionResultList
* SpeechRecognitionResult
* SpeechRecognitionAlternative

### Extra Utility Methods Added To Object

* isStarted()
* say()

### Author
Tal Ater: [@TalAter](https://twitter.com/TalAter)

### License
Licensed under [MIT](https://github.com/TalAter/SpeechKITT/blob/master/LICENSE).


text:
<?php

namespace Fxp\Component\RequireAsset\Exception;

/**
 * Base InvalidArgumentException for the Require asset.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}


text:
using System.Collections.Generic;
using Tibia.Constants;

namespace Tibia.Packets.Incoming
{
    public class AvalibleOutfit
    {
        public ushort Id { get; set; }
        public string Name { get; set; }
        public byte Addons { get; set; }

        public AvalibleOutfit() { }
    }

    public class MountDescription
    {
        public ushort Id { get; set; }
        public string Name { get; set; }
    }

    public class OutfitWindowPacket : IncomingPacket
    {
        public List<AvalibleOutfit> OutfitList { get; set; }
        public List<MountDescription> MountList { get; set; }
        public Objects.Outfit Default { get; set; }

        public OutfitWindowPacket(Objects.Client c)
            : base(c)
        {
            Type = IncomingPacketType.OutfitWindow;
            Destination = PacketDestination.Client;
        }

        public override bool ParseMessage(NetworkMessage msg, PacketDestination destination)
        {
            int position = msg.Position;

            if (msg.GetByte() != (byte)IncomingPacketType.OutfitWindow)
                return false;

            Destination = destination;
            Type = IncomingPacketType.OutfitWindow;

            Default = msg.GetOutfit();

            byte count = msg.GetByte();
            OutfitList = new List<AvalibleOutfit> { };

            for (int i = 0; i < count; i++)
            {
                AvalibleOutfit outfit = new AvalibleOutfit();

                outfit.Id = msg.GetUInt16();
                outfit.Name = msg.GetString();
                outfit.Addons = msg.GetByte();

                OutfitList.Add(outfit);
            }

            if (Client.VersionNumber >= 870)
            {
                count = msg.GetByte();
                MountList = new List<MountDescription> { };

                for (int i = 0; i < count; i++)
                {
                    MountDescription mount = new MountDescription();

                    mount.Id = msg.GetUInt16();
                    mount.Name = msg.GetString();

                    MountList.Add(mount);
                }
            }

            return true;
        }

        public override void ToNetworkMessage(NetworkMessage msg)
        {
            msg.AddByte((byte)Type);

            msg.AddOutfit(Default);

            msg.AddByte((byte)OutfitList.Count);

            foreach (AvalibleOutfit i in OutfitList)
            {
                msg.AddUInt16(i.Id);
                msg.AddString(i.Name);
                msg.AddByte(i.Addons);
            }

            if (Client.VersionNumber >= 870)
            {
                msg.AddByte((byte)MountList.Count);

                foreach (MountDescription i in MountList)
                {
                    msg.AddUInt16(i.Id);
                    msg.AddString(i.Name);
                }
            }
        }
    }
}


text: export {DomainsClient} from './domains_client';


text:
package jacobi.core.decomp.svd;

import jacobi.api.Matrix;
import jacobi.core.decomp.qr.Householder;
import java.util.function.Consumer;

/**
 * Bi-Diagonal decomposition is to decompose a m-by-n matrix A into Q * E * V^t s.t. Q and V are othogonal, and E
 * is a bi-diagonal matrix. E can be chosen to be upper triangular and lower triangular.
 *
 *
This class mutates the value of the input matrix A and the resultant value is in-determined. Only the returned
 * bi-diagonal elements should be relied upon.

 *
 *
The bi-diagonal elements are returned as {a1, b1, a2, b2, ...}
 * where diag(E) = {a1, a2, ...}, sup-diag(E) = {b1, b2, ...}

 *
 * @author Y.K. Chan
 */
public interface BiDiagDecomp {

    /**
     * Compute bi-diagonal decomposition.
     * @param mode  Indicate E to be upper or lower triangular matrix
     * @param input  Input matrix A
     * @return Bi-diagonal elements as {a1, b1, a2, b2, ...} where diag(E) = {a1, a2, ...}, sup-diag(E) = {b1, b2, ...}
     */
    public default double[] compute(Mode mode, Matrix input) {
        return this.compute(mode, input, (hh) -> {}, (hh) -> {});
    }

    /**
     * Compute bi-diagonal decomposition.
     * @param mode  Indicate E to be upper or lower triangular matrix
     * @param input  Input matrix A
     * @param qFunc  Listener of Q1, Q2, ... where Q^t = Qn*...Q2*Q1
     * @param vFunc  Listener of V1, V2, ... where V^t = V1*V2*...*Vn
     * @return  Bi-diagonal elements as {a1, b1, a2, b2, ...} where diag(E) = {a1, a2, ...}, sup-diag(E) = {b1, b2, ...}
     */
    public double[] compute(Mode mode, Matrix input, Consumer<Householder> qFunc, Consumer<Householder> vFunc);

    /**
     * Mode of decomposition.
     */
    public enum Mode {
        /**
         * Decompose to upper triangular matrix
         */
        UPPER,
        /**
         * Decompose to lower triangular matrix
         */
        LOWER
    }

}


text:
QUnit.test('methods#getData', function (assert) {
  var done = assert.async();
  var util = window.Util;
  var image = util.createImage();

  assert.expect(7);

  return new Cropper(image, {
    ready: function () {
      var cropper = this.cropper;
      var data = cropper.getData();

      assert.ok(util.isNumber(data.x));
      assert.ok(util.isNumber(data.y));
      assert.ok(util.isNumber(data.width));
      assert.ok(util.isNumber(data.height));
      assert.ok(util.isNumber(data.rotate));
      assert.ok(util.isNumber(data.scaleX));
      assert.ok(util.isNumber(data.scaleY));

      done();
    }
  });
});

QUnit.test('methods#getData: rounded', function (assert) {
  var done = assert.async();
  var util = window.Util;
  var image = util.createImage();

  assert.expect(4);

  return new Cropper(image, {
    ready: function () {
      var cropper = this.cropper;
      var data = cropper.getData(true);

      assert.ok(data.x % 1 === 0);
      assert.ok(data.y % 1 === 0);
      assert.ok(data.width % 1 === 0);
      assert.ok(data.height % 1 === 0);

      done();
    }
  });
});


text:
"""
Class and program to colorize python source code for ANSI terminals.

Based on an HTML code highlighter by Jurgen Hermann found at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298

Modifications by Fernando Perez (fperez@colorado.edu).

Information on the original HTML highlighter follows:

MoinMoin - Python Source Parser

Title: Colorize Python source using the built-in tokenizer

Submitter: Jurgen Hermann
Last Updated:2001/04/06

Version no:1.2

Description:

This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
Python source code to HTML markup, rendering comments, keywords,
operators, numeric and string literals in different colors.

It shows how to use the built-in keyword, token and tokenize modules to
scan Python source code and re-emit it with no changes to its original
formatting (which is the hard part).
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

__all__ = ['ANSICodeColors','Parser']

_scheme_default = 'Linux'

# Imports
import keyword
import os
import sys
import token
import tokenize

try:
    generate_tokens = tokenize.generate_tokens
except AttributeError:
    # Python 3. Note that we use the undocumented _tokenize because it expects
    # strings, not bytes. See also Python issue #9969.
    generate_tokens = tokenize._tokenize

from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
from IPython.utils.py3compat import PY3

from .colorable import Colorable

if PY3:
    from io import StringIO
else:
    from StringIO import StringIO

#############################################################################
### Python Source Parser (does Hilighting)
#############################################################################

_KEYWORD = token.NT_OFFSET + 1
_TEXT    = token.NT_OFFSET + 2

#****************************************************************************
# Builtin color schemes

Colors = TermColors  # just a shorthand

# Build a few color schemes
NoColor = ColorScheme(
    'NoColor',{
    'header'         : Colors.NoColor,
    token.NUMBER     : Colors.NoColor,
    token.OP         : Colors.NoColor,
    token.STRING     : Colors.NoColor,
    tokenize.COMMENT : Colors.NoColor,
    token.NAME       : Colors.NoColor,
    token.ERRORTOKEN : Colors.NoColor,

    _KEYWORD         : Colors.NoColor,
    _TEXT            : Colors.NoColor,

    'in_prompt'      : InputTermColors.NoColor,  # Input prompt
    'in_number'      : InputTermColors.NoColor,  # Input prompt number
    'in_prompt2'     : InputTermColors.NoColor, # Continuation prompt
    'in_normal'      : InputTermColors.NoColor,  # color off (usu. Colors.Normal)

    'out_prompt'     : Colors.NoColor, # Output prompt
    'out_number'     : Colors.NoColor, # Output prompt number

    'normal'         : Colors.NoColor  # color off (usu. Colors.Normal)
    }  )

LinuxColors = ColorScheme(
    'Linux',{
    'header'         : Colors.LightRed,
    token.NUMBER     : Colors.LightCyan,
    token.OP         : Colors.Yellow,
    token.STRING     : Colors.LightBlue,
    tokenize.COMMENT : Colors.LightRed,
    token.NAME       : Colors.Normal,
    token.ERRORTOKEN : Colors.Red,

    _KEYWORD         : Colors.LightGreen,
    _TEXT            : Colors.Yellow,

    'in_prompt'      : InputTermColors.Green,
    'in_number'      : InputTermColors.LightGreen,
    'in_prompt2'     : InputTermColors.Green,
    'in_normal'      : InputTermColors.Normal,  # color off (usu. Colors.Normal)

    'out_prompt'     : Colors.Red,
    'out_number'     : Colors.LightRed,

    'normal'         : Colors.Normal  # color off (usu. Colors.Normal)
    } )

NeutralColors = ColorScheme(
    'Neutral',{
    'header'         : Colors.Red,
    token.NUMBER     : Colors.Cyan,
    token.OP         : Colors.Blue,
    token.STRING     : Colors.Blue,
    tokenize.COMMENT : Colors.Red,
    token.NAME       : Colors.Normal,
    token.ERRORTOKEN : Colors.Red,

    _KEYWORD         : Colors.Green,
    _TEXT            : Colors.Blue,

    'in_prompt'      : InputTermColors.Blue,
    'in_number'      : InputTermColors.LightBlue,
    'in_prompt2'     : InputTermColors.Blue,
    'in_normal'      : InputTermColors.Normal,  # color off (usu. Colors.Normal)

    'out_prompt'     : Colors.Red,
    'out_number'     : Colors.LightRed,

    'normal'         : Colors.Normal  # color off (usu. Colors.Normal)
    }  )

# Hack: the 'neutral' colours are not very visible on a dark background on
# Windows. Since Windows command prompts have a dark background by default, and
# relatively few users are likely to alter that, we will use the 'Linux' colours,
# designed for a dark background, as the default on Windows. Changing it here
# avoids affecting the prompt colours rendered by prompt_toolkit, where the
# neutral defaults do work OK.

if os.name == 'nt':
    NeutralColors = LinuxColors.copy(name='Neutral')

LightBGColors = ColorScheme(
    'LightBG',{
    'header'         : Colors.Red,
    token.NUMBER     : Colors.Cyan,
    token.OP         : Colors.Blue,
    token.STRING     : Colors.Blue,
    tokenize.COMMENT : Colors.Red,
    token.NAME       : Colors.Normal,
    token.ERRORTOKEN : Colors.Red,

    _KEYWORD         : Colors.Green,
    _TEXT            : Colors.Blue,

    'in_prompt'      : InputTermColors.Blue,
    'in_number'      : InputTermColors.LightBlue,
    'in_prompt2'     : InputTermColors.Blue,
    'in_normal'      : InputTermColors.Normal,  # color off (usu. Colors.Normal)

    'out_prompt'     : Colors.Red,
    'out_number'     : Colors.LightRed,

    'normal'         : Colors.Normal  # color off (usu. Colors.Normal)
    }  )

# Build table of color schemes (needed by the parser)
ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
                                  _scheme_default)

class Parser(Colorable):
    """ Format colored Python source.
    """

    def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
        """ Create a parser with a specified color table and output channel.

        Call format() to process code.
        """

        super(Parser, self).__init__(parent=parent)

        self.color_table = color_table and color_table or ANSICodeColors
        self.out = out

    def format(self, raw, out = None, scheme = ''):
        return self.format2(raw, out, scheme)[0]

    def format2(self, raw, out = None, scheme = ''):
        """ Parse and send the colored source.

        If out and scheme are not specified, the defaults (given to
        constructor) are used.

        out should be a file-type object. Optionally, out can be given as the
        string 'str' and the parser will automatically return the output in a
        string."""

        string_output = 0
        if out == 'str' or self.out == 'str' or \
           isinstance(self.out,StringIO):
            # XXX - I don't really like this state handling logic, but at this
            # point I don't want to make major changes, so adding the
            # isinstance() check is the simplest I can do to ensure correct
            # behavior.
            out_old = self.out
            self.out = StringIO()
            string_output = 1
        elif out is not None:
            self.out = out

        # Fast return of the unmodified input for NoColor scheme
        if scheme == 'NoColor':
            error = False
            self.out.write(raw)
            if string_output:
                return raw,error
            else:
                return None,error

        # local shorthands
        colors = self.color_table[scheme].colors
        self.colors = colors # put in object so __call__ sees it

        # Remove trailing whitespace and normalize tabs
        self.raw = raw.expandtabs().rstrip()

        # store line offsets in self.lines
        self.lines = [0, 0]
        pos = 0
        raw_find = self.raw.find
        lines_append = self.lines.append
        while 1:
            pos = raw_find('\n', pos) + 1
            if not pos: break
            lines_append(pos)
        lines_append(len(self.raw))

        # parse the source and write it
        self.pos = 0
        text = StringIO(self.raw)

        error = False
        try:
            for atoken in generate_tokens(text.readline):
                self(*atoken)
        except tokenize.TokenError as ex:
            msg = ex.args[0]
            line = ex.args[1][0]
            self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
                           (colors[token.ERRORTOKEN],
                            msg, self.raw[self.lines[line]:],
                            colors.normal)
                           )
            error = True
        self.out.write(colors.normal+'\n')
        if string_output:
            output = self.out.getvalue()
            self.out = out_old
            return (output, error)
        return (None, error)

    def __call__(self, toktype, toktext, start_pos, end_pos, line):
        """ Token handler, with syntax highlighting."""
        (srow,scol) = start_pos
        (erow,ecol) = end_pos
        colors = self.colors
        owrite = self.out.write

        # line separator, so this works across platforms
        linesep = os.linesep

        # calculate new positions
        oldpos = self.pos
        newpos = self.lines[srow] + scol
        self.pos = newpos + len(toktext)

        # send the original whitespace, if needed
        if newpos > oldpos:
            owrite(self.raw[oldpos:newpos])

        # skip indenting tokens
        if toktype in [token.INDENT, token.DEDENT]:
            self.pos = newpos
            return

        # map token type to a color group
        if token.LPAR <= toktype <= token.OP:
            toktype = token.OP
        elif toktype == token.NAME and keyword.iskeyword(toktext):
            toktype = _KEYWORD
        color = colors.get(toktype, colors[_TEXT])

        #print '<%s>' % toktext,    # dbg

        # Triple quoted strings must be handled carefully so that backtracking
        # in pagers works correctly. We need color terminators on _each_ line.
        if linesep in toktext:
            toktext = toktext.replace(linesep, '%s%s%s' %
                                      (colors.normal,linesep,color))

        # send text
        owrite('%s%s%s' % (color,toktext,colors.normal))

def main(argv=None):
    """Run as a command-line script: colorize a python file or stdin using ANSI
    color escapes and print to stdout.

    Inputs:

      - argv(None): a list of strings like sys.argv[1:] giving the command-line
        arguments. If None, use sys.argv[1:].
    """

    usage_msg = """%prog [options] [filename]

Colorize a python file or stdin using ANSI color escapes and print to stdout.
If no filename is given, or if filename is -, read standard input."""

    import optparse
    parser = optparse.OptionParser(usage=usage_msg)
    newopt = parser.add_option
    newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
           choices=['Linux','LightBG','NoColor'],default=_scheme_default,
           help="give the color scheme to use. Currently only 'Linux'\
 (default) and 'LightBG' and 'NoColor' are implemented (give without\
 quotes)")

    opts,args = parser.parse_args(argv)

    if len(args) > 1:
        parser.error("you must give at most one filename.")

    if len(args) == 0:
        fname = '-' # no filename given; setup to read from stdin
    else:
        fname = args[0]

    if fname == '-':
        stream = sys.stdin
    else:
        try:
            stream = open(fname)
        except IOError as msg:
            print(msg, file=sys.stderr)
            sys.exit(1)

    parser = Parser()

    # we need nested try blocks because pre-2.5 python doesn't support unified
    # try-except-finally
    try:
        try:
            # write colorized version to stdout
            parser.format(stream.read(),scheme=opts.scheme_name)
        except IOError as msg:
            # if user reads through a pager and quits, don't print traceback
            if msg.args != (32,'Broken pipe'):
                raise
    finally:
        if stream is not sys.stdin:
            stream.close() # in case a non-handled exception happened above

if __name__ == "__main__":
    main()


text:
import { Component, OnInit, EventEmitter, Output } from '@angular/core';

import { FileUploader } from 'ng2-file-upload';
import { Constants } from './../../constants/constants';

@Component({
    moduleId: module.id,
    selector: 'post-upload',
    templateUrl: './post-upload.component.html'
})
export class PostUploadComponent implements OnInit {
    public uploader: FileUploader = new FileUploader({ url: `${Constants.hostUrl}api/posts/upload` });
    @Output() onUploaded = new EventEmitter<any>();

    public ngOnInit() {
        this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
            let file = JSON.parse(response).file;
            this.onUploaded.emit(file);
        };
    }

    public uploadImage(): void {
        this.uploader.uploadAll();
    }

    public removeImage(): void {
        this.uploader.clearQueue();
    }
}


text:
module DropboxApi::Errors
  class SearchError < BasicError
    ErrorSubtypes = {
      path: LookupError
    }.freeze
  end
end