text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System;
using System.Diagnostics.Contracts;
using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Core.Rules
{
    public sealed class Rule : Cloneable<Rule>
    {
        private RuleTrigger trigger;
        private RuleAction action;
        private bool isEnabled = true;

        public RuleTrigger Trigger
        {
            get { return trigger; }
        }

        public RuleAction Action
        {
            get { return action; }
        }

        public bool IsEnabled
        {
            get { return isEnabled; }
        }

        public Rule(RuleTrigger trigger, RuleAction action)
        {
            Guard.NotNull(trigger, nameof(trigger));
            Guard.NotNull(action, nameof(action));

            this.trigger = trigger;
            this.trigger.Freeze();

            this.action = action;
            this.action.Freeze();
        }

        [Pure]
        public Rule Enable()
        {
            return Clone(clone =>
            {
                clone.isEnabled = true;
            });
        }

        [Pure]
        public Rule Disable()
        {
            return Clone(clone =>
            {
                clone.isEnabled = false;
            });
        }

        [Pure]
        public Rule Update(RuleTrigger newTrigger)
        {
            Guard.NotNull(newTrigger, nameof(newTrigger));

            if (newTrigger.GetType() != trigger.GetType())
            {
                throw new ArgumentException("New trigger has another type.", nameof(newTrigger));
            }

            newTrigger.Freeze();

            return Clone(clone =>
            {
                clone.trigger = newTrigger;
            });
        }

        [Pure]
        public Rule Update(RuleAction newAction)
        {
            Guard.NotNull(newAction, nameof(newAction));

            if (newAction.GetType() != action.GetType())
            {
                throw new ArgumentException("New action has another type.", nameof(newAction));
            }

            newAction.Freeze();

            return Clone(clone =>
            {
                clone.action = newAction;
            });
        }
    }
}


text:
<?php

namespace Magento\Framework\Interception\Custom\Module\Model\InterfaceValidator\ItemPlugin;

class ExtraParameters
{
    /**
     * @param \Magento\Framework\Interception\Custom\Module\Model\InterfaceValidator\Item $subject
     * @param string $name
     * @param string $surname
     * @return string
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetItem(
        \Magento\Framework\Interception\Custom\Module\Model\InterfaceValidator\Item $subject, $name, $surname
    ) {
        return $name . $surname;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ALTER TABLE label_class_history
  DROP CONSTRAINT "label_class_history_child_label_class_id_fkey",
  ADD CONSTRAINT "label_class_history_child_label_class_id_fkey"
    FOREIGN KEY (child_label_class_id) REFERENCES annotation_label_classes(id) ON DELETE CASCADE,
  DROP CONSTRAINT "label_class_history_parent_label_class_id_fkey",
  ADD CONSTRAINT "label_class_history_parent_label_class_id_fkey"
    FOREIGN KEY (parent_label_class_id) REFERENCES annotation_label_classes(id) ON DELETE CASCADE;


text:
<?php

namespace NasExt\Forms\Controls;

/**
 * Data object for RangeSlider.
 *
 * @author Dusan Hudak
 */

class Range implements \IteratorAggregate
{
	/** @var array */
	protected $range = array();

	/**
	 * @param $min
	 * @param $max
	 */
	public function __construct($min, $max)
	{
		$this->setRange($min, $max);
		return $this;
	}

	/**
	 * @param int $min
	 * @param int $max
	 * @return $this
	 */
	public function setRange($min, $max)
	{
		$this->range = array($min, $max);
		return $this;
	}

	/**
	 * @return array
	 */
	public function getRange()
	{
		return $this->range;
	}

	/**
	 * @param int $min
	 * @return $this
	 */
	public function setMin($min)
	{
		$this->range[0] = $min;
		return $this;
	}

	/**
	 * @return int
	 */
	public function getMin()
	{
		return $this->range[0];
	}

	/**
	 * @param int $max
	 * @return $this
	 */
	public function setMax($max)
	{
		$this->range[1] = $max;
		return $this;
	}

	/**
	 * @return int
	 */
	public function getMax()
	{
		return $this->range[1];
	}

	/**
	 * @return \ArrayIterator|\Traversable
	 */
	public function getIterator()
	{
		return new \ArrayIterator($this->range);
	}

}


text:
package com.cloudlbs.sls.ui;

import android.app.Activity;

import com.cloudlbs.sls.SLSService;
import com.cloudlbs.sls.ui.mvp.Presenter;

/**
 * @author Dan Mascenik
 *
 */
public interface ServiceBoundPresenter<V extends Activity> extends
		Presenter<V> {

	public void onServiceConnected(SLSService service);

	public void onServiceDisconnected();

}


text:
This sample demonstrates CordovaPluginFileDemo feature basic functionalities, include:

* The demo CordovaPluginFileDemo can build and work well on test device

This usecase covers following method:

* open CordovaPluginFileDemo.xcworkspace
* CordovaPluginFileDemo can be built with Xcode


text:
title: Open Link in a New Window When Clicked
page_title: Open Link in a New Window When Clicked - RadEditor
description: Check our Web Forms article about Open Link in a New Window When Clicked.
slug: editor/how-to/open-link-in-a-new-window-when-clicked
tags: open,link,in,a,new,window,when,clicked
published: True
position: 6
---

# Open Link in a New Window When Clicked

The code below demonstrates how to iterate RadEditor document links when the editor is loaded. The code sets the link target attribute to so that the link is opened in a new window when clicked. You can use this approach to modify the attributes and events of all HTML elements in the editor content area. This example opens the editor in **Preview EditorMode** so that clicking the links will have the expected behavior.

![](images/editor-handlingcontent002.png)

````JavaScript
<script type="text/javascript">
	function OnClientLoad(editor)
	{
		var links = editor.get_document().getElementsByTagName("A");
		for (var i = 0; i < links.length; i++)
		{
			var link = links[i];
			link.setAttribute("target", "#");
		}
	}
</script>
````

````ASP.NET
<telerik:RadEditor RenderMode="Lightweight" ID="RadEditor1" runat="server" Skin="Default" OnClientLoad="OnClientLoad"
	EditModes="Preview">
	<Content>
		Sample Content
		<a href="httpwww.telerik.com">www.telerik.com</a>
		test
		<a href="https://www.yahoo.com">www.yahoo.com</a>
		test
		<a href="http://www.test.com/some.pdf">some.pdf</a>
	</Content>
</telerik:RadEditor>
````


text:
> Reporter for the TestNG XML format.

## Installation

The easiest way is to keep `karma-testng-reporter` as a devDependency in your `package.json`.
```json
{
  "devDependencies": {
    "karma": "~0.10",
    "karma-testng-reporter": "0.1"
  }
}
```

You can simple do it by:
```bash
npm install karma-testng-reporter --save-dev
```

## Configuration
```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    reporters: ['progress', 'testng'],

    // the default configuration
    testngReporter: {
      outputFile: 'unit/testng-results.xml',
      suite: ''
    }
  });
};
```
If you want to tag your test cases you can simply put the tag names separated with '|' in the describe section .
e.g. describe('Logger Module|UT|CT',function(){});
This will tag the specs present inside the describe with two tags UT and CT. As many number of tags can be added.
You can pass list of reporters as a CLI argument too:
```bash
karma start --reporters testng,dots
```

----

For more information on Karma see the [homepage].

[homepage]: http://karma-runner.github.com


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "freerds.h"
#include <freerds/module_connector.h>
#include <winpr/wtypes.h>
#include <winpr/thread.h>
#include <winpr/synch.h>

rdsModuleConnector* freerds_module_connector_new(rdsConnection* connection)
{
	rdpSettings* settings;
	rdsModuleConnector* connector;

	settings = connection->settings;

	connector = (rdsModuleConnector*) malloc(sizeof(rdsModuleConnector));
	ZeroMemory(connector, sizeof(rdsModuleConnector));

	connector->connection = connection;
	connector->settings = connection->settings;

	connector->client = freerds_client_outbound_interface_new();
	connector->server = freerds_server_outbound_interface_new();

	connector->OutboundStream = Stream_New(NULL, 8192);
	connector->InboundStream = Stream_New(NULL, 8192);

	connector->InboundTotalLength = 0;
	connector->InboundTotalCount = 0;

	connector->OutboundTotalLength = 0;
	connector->OutboundTotalCount = 0;

	connector->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	return connector;
}

void freerds_module_connector_free(rdsModuleConnector* connector)
{
	SetEvent(connector->StopEvent);

	WaitForSingleObject(connector->ServerThread, INFINITE);
	CloseHandle(connector->ServerThread);

	Stream_Free(connector->OutboundStream, TRUE);
	Stream_Free(connector->InboundStream, TRUE);

	CloseHandle(connector->StopEvent);
	CloseHandle(connector->hClientPipe);

	free(connector);
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18444
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Fhwk.MsSql.Resources {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class ExceptionMessages {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal ExceptionMessages() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Fhwk.MsSql.Resources.ExceptionMessages", typeof(ExceptionMessages).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Error setting up the {0}. Custom convention value has been selected but no custom function has been provided..
        /// </summary>
        public static string CustomConventionNotFound {
            get {
                return ResourceManager.GetString("CustomConventionNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Missing identifier property. Wrong mapping or missing mapping class for the type {0}.
        /// </summary>
        public static string MemberNotFound {
            get {
                return ResourceManager.GetString("MemberNotFound", resourceCulture);
            }
        }
    }
}


text:
package com.keifermiller.inkbar;

import java.io.File;

import android.os.Environment;

/**
 * @author keifer
 *
 */
public final class Constants {
	public static final File DOCUMENTS_DIRECTORY = new File(
			Environment.getExternalStorageDirectory(), "Documents");
	public static final File HISTORY_DIRECTORY = new File(
			Environment.getExternalStorageDirectory(),
			"/Android/data/com.keifermiller.inkbar/files/history");
	public static final int MAX_EDITABLE_SHARE_SIZE = 1024 * 100; // Conservative
	public static final int MAX_TEXT_SIZE=50;
	public static final int MIN_TEXT_SIZE=10;
	public static final int DEFAULT_TEXT_SIZE=18;

}


text:
package io.quarkus.arc.test.interceptors.noclassinterceptors;

import io.quarkus.arc.NoClassInterceptors;

public interface SuperSuperinterface {
    @NoClassInterceptors
    default void inheritedDefaultMethod() {
    }
}


text:
// Copyright 2000-2017 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.jetbrains.python;

import com.google.common.collect.Lists;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.PsiTestUtil;
import com.jetbrains.python.codeInsight.PyCustomMember;
import com.jetbrains.python.fixtures.PyMultiFileResolveTestCase;
import com.jetbrains.python.fixtures.PyResolveTestCase;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyImportResolver;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yole
 */
public class PyMultiFileResolveTest extends PyMultiFileResolveTestCase {

  private static void checkInitPyDir(PsiElement elt, String dirname) {
    assertTrue(elt instanceof PyFile);
    PyFile f = (PyFile)elt;
    assertEquals(f.getName(), "__init__.py");
    assertEquals(f.getContainingDirectory().getName(), dirname);
  }

  public void testSimple() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyFile);
    assertEquals("ImportedFile.py", ((PyFile)element).getName());
  }

  public void testFromImport() {
    List<PsiElement> results = doMultiResolve();
    assertSize(2, results); // func and import stmt
    PsiElement funcElt = results.get(0);
    assertTrue("is PyFunction?", funcElt instanceof PyFunction);
    assertEquals("named 'func'?", "func", ((PyFunction)funcElt).getName());
    PsiElement importElt = results.get(1);
    assertTrue("is import?", importElt instanceof PyImportElement);
  }

  public void testFromImportStar() {
    List<PsiElement> results = doMultiResolve();
    assertSize(2, results); // func and import-* stmt
    PsiElement funcElt = results.get(0);
    assertTrue("is PyFunction?", funcElt instanceof PyFunction);
    assertEquals("named 'func'?", "func", ((PyFunction)funcElt).getName());
    PsiElement importElt = results.get(1);
    assertTrue("is import?", importElt instanceof PyStarImportElement);
  }

  public void testFromPackageImport() {
    PsiElement element = doResolve();
    checkInitPyDir(element, "mypackage");
  }

  public void testFromPackageImportFile() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PsiFile);
    assertEquals("myfile.py", ((PyFile)element).getName());
  }

  public void testFromQualifiedPackageImport() {
    PsiElement element = doResolve();
    checkInitPyDir(element, "mypackage");
  }

  public void testFromQualifiedFileImportClass() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PsiFile);
    assertEquals("myfile.py", ((PsiFile)element).getName());
    assertEquals("mypackage", ((PsiFile)element).getContainingDirectory().getName());
  }

  public void testCustomPackageIdentifier() {
    PlatformTestUtil.registerExtension(PyCustomPackageIdentifier.EP_NAME, new PyCustomPackageIdentifier() {
      @Override
      public boolean isPackage(PsiDirectory directory) {
        return true;
      }

      @Override
      public boolean isPackageFile(PsiFile file) {
        return false;
      }
    }, getTestRootDisposable());
    PsiElement element = doResolve();
    assertTrue(element instanceof PsiFile);
    assertEquals("myfile.py", ((PyFile)element).getName());
  }

  public void testImportAs() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyFunction);
    assertEquals("func", ((PyFunction)element).getName());
  }

  public void testFromQualifiedPackageImportFile() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PsiFile);
    assertEquals("testfile.py", ((PsiFile)element).getName());
  }

  public void testFromInitPyImportFunction() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyFunction);
  }

  public void testTransitiveImport() {
    List<PsiElement> results = doMultiResolve();
    assertSize(2, results); // func and import stmt
    PsiElement elt = results.get(0);
    assertTrue("is target?", elt instanceof PyTargetExpression);
  }

  public void testFromPackageImportIntoInit() {  // PY-6305
    myFixture.copyDirectoryToProject("fromPackageImportIntoInit/pack", "pack");
    final PsiFile psiFile = myFixture.configureByFile("pack/__init__.py");
    final PsiElement result = doResolve(psiFile);
    assertInstanceOf(result, PyFile.class);
    assertEquals("mod.py", ((PyFile)result).getName());
  }

  public void testResolveInPkg() {
    List<PsiElement> results = doMultiResolve();
    assertSize(2, results); // func and import stmt
    final PsiElement funcElt = results.get(0);
    assertTrue("is PyFunction?", funcElt instanceof PyFunction);
    assertEquals("named 'token'?", "token", ((PyFunction)funcElt).getName());
    PsiElement importElt = results.get(1);
    assertTrue("is import?", importElt instanceof PyImportElement);
  }

  public void testCircularImport() {
    PsiElement element = doResolve();
    assertTrue(element == null ? "resolve failed" : element.toString(), element instanceof PyTargetExpression);
  }

  public void testRelativeSimple() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyTargetExpression);
    PsiElement value = ((PyTargetExpression)element).findAssignedValue();
    assertEquals("local", ((PyStringLiteralExpression)value).getStringValue());
  }

  public void testRelativeFromInit() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyTargetExpression);
    PsiElement value = ((PyTargetExpression)element).findAssignedValue();
    assertEquals("unimaginable", ((PyStringLiteralExpression)value).getStringValue());
  }

  public void testRelativeDotsOnly() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyTargetExpression);
    PsiElement value = ((PyTargetExpression)element).findAssignedValue();
    assertEquals("silicate", ((PyStringLiteralExpression)value).getStringValue());
  }

  public void testModuleValueCollision() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyTargetExpression);
    PsiElement value = ((PyTargetExpression)element).findAssignedValue();
    assertEquals("only kidding", ((PyStringLiteralExpression)value).getStringValue());
  }

  public void testModuleClassCollision() {
    PsiElement element = doResolve();
    assertTrue(element instanceof PyClass);
    assertEquals("boo", ((PyClass)element).getName());
  }

  public void testModulePackageCollision() {  // PY-3194
    assertResolvesTo(PyFile.class, "module1.py");
  }

  public void testDirectoryVsClass() {
    assertResolvesTo(PyClass.class, "Context");
  }

  public void testReimportStar() {
    assertResolvesTo(PyClass.class, "CharField");
  }

  public void testStackOverflowOnEmptyFile() {
    assertNull(doResolve());  // make sure we don't have a SOE here
  }

  public void testResolveQualifiedSuperClass() {
    assertResolvesTo(PyFunction.class, "copy");
  }

  public void testResolveQualifiedSuperClassInPackage() {
    assertResolvesTo(PyFunction.class, "copy");
  }

  public void testNestedPackage() {
    assertResolvesTo(PyFile.class, "__init__.py");
  }

  public void testNestedPackageElement() {
    PsiElement element = doResolve();
    element = element.getNavigationElement();
    assertInstanceOf(element, PyFile.class);
    assertEquals("__init__.py", ((PyFile)element).getName());
  }

  public void testImportOsPath() {
    assertResolvesTo(PyFunction.class, "makedir");
  }

  public void testImportOsPath2() {
    assertResolvesTo(PyFunction.class, "do_stuff");
  }

  // PY-1153
  // TODO: This case requires collecting transitive imports in all imported submodules
  public void _testReimportExported() {
    assertResolvesTo(PyFunction.class, "dostuff");
  }

  public void testFromImportExplicit() {
    assertResolvesTo(PyFunction.class, "dostuff");
  }

  public void testLocalImport() {
    assertResolvesTo(PyFunction.class, "dostuff");
  }

  public void testNameConflict() {
    assertResolvesTo(PyFunction.class, "do_stuff", "/src/pack2.py");
  }

  public void testDunderAll() {
    assertResolvesTo(PyTargetExpression.class, "__all__");
  }

  public void testDunderAllConflict() {
    assertResolvesTo(PyFunction.class, "do_stuff", "/src/mypackage1.py");
  }

  // TODO: Create package attributes for its imported submodules
  public void _testImportPackageIntoSelf() {
    assertResolvesTo(PyFunction.class, "foo", "/src/mygame/display.py");
  }

  public void testImportPackageIntoSelfInit() {
    myTestFileName = "mygame/__init__.py";
    try {
      assertResolvesTo(PyFile.class, "display.py");
    }
    finally {
      myTestFileName = null;
    }
  }

  public void testFromImportPackageIntoSelf() {
    myTestFileName = "mygame/__init__.py";
    try {
      assertResolvesTo(PyFile.class, "display.py");
    }
    finally {
      myTestFileName = null;
    }
  }

  public void testImportPrivateNameWithStar() { // PY-2717
    PsiElement psiElement = doResolve();
    assertNull(psiElement);
  }

  public void testModulePackageConflict() {  // PY-6011
    assertResolvesTo(PyFunction.class, "foo");
  }

  public void testRelativePackageStarImport() {   // PY-7204
    myTestFileName = "b/c/__init__.py";
    try {
      assertResolvesTo(PyFunction.class, "foo", "/src/b/__init__.py");
    }
    finally {
      myTestFileName = null;
    }
  }
  // PY-2813
  public void testFromNamespacePackageImport() {
    assertResolvesTo(PyFunction.class, "foo");
  }

  // PY-2813
  public void testNamespacePackage() {
    assertResolvesTo(PsiDirectory.class, "p1");
  }

  // PY-2813
  public void testNamespacePackageImport() {
    assertResolvesTo(PsiDirectory.class, "p1");
  }

  // PY-2813
  public void testFromNamespacePackageImportModule() {
    assertResolvesTo(PyFile.class, "m1.py");
  }

  public void testImportSubmodule() {
    assertResolvesTo(PyFile.class, "m1.py");
  }

  // PY-6575
  public void testRelativeFromSubmodule() {
    assertResolvesTo(PyFile.class, "m2.py");
  }

  public void _testImplicitFromImport() {   // PY-7929
    assertResolvesTo(PyClass.class, "Database");
  }

  // PY-6866
  public void testFunctionAndSubmoduleNamedIdentically() {
    assertResolvesTo(PyFunction.class, "m1");
  }

  // PY-7026
  public void testFromImportStarReassignment() {
    assertResolvesTo(PyFunction.class, "foo");
  }

  // PY-7156
  public void testPython33NamespacePackage() {
    runWithLanguageLevel(LanguageLevel.PYTHON33, () -> assertResolvesTo(PsiDirectory.class, "p1"));
  }

  // PY-7156
  public void testFromPython33NamespacePackageImport() {
    runWithLanguageLevel(LanguageLevel.PYTHON33, () -> assertResolvesTo(PyFunction.class, "foo"));
  }

  // PY-7775
  public void testProjectSourcesFirst() {
    myTestFileName = "mod/" + getTestName(false) + ".py";
    assertResolvesTo(PyFunction.class, "foobar");
  }

  // PY-6805
  public void testAttributeDefinedInNew() {
    assertResolvesTo(PyTargetExpression.class, "foo");
  }

  // PY-10819
  public void testFromPackageModuleImportElementNamedAsModule() {
    assertResolvesTo(PyFunction.class, "foo");
    final PsiManager psiManager = myFixture.getPsiManager();
    PyTestCase.assertNotParsed(psiManager.findFile(myFixture.findFileInTempDir("p1/__init__.py")));
    PyTestCase.assertNotParsed(psiManager.findFile(myFixture.findFileInTempDir("p1/foo.py")));
  }

  // PY-10819
  public void testFromPackageModuleImportStarElementNamedAsModule() {
    assertResolvesTo(PyFunction.class, "foo");
  }

  // PY-13140
  public void testModulePrivateName() {
    assertNull(doResolve());
  }

  // PY-13140
  public void testModulePrivateNameInDunderAll() {
    assertResolvesTo(PyTargetExpression.class, "_private_name");
  }

  // PY-7378
  public void testModuleInDeeplyNestedNamespacePackage() {
    runWithLanguageLevel(LanguageLevel.PYTHON33, () -> assertResolvesTo(PyFile.class, "m1.py"));
  }

  public void testKeywordArgument() {
    final PsiFile file = prepareFile();
    final PsiManager psiManager = myFixture.getPsiManager();
    final VirtualFile dir = myFixture.findFileInTempDir("a.py");
    final PsiFile psiFile = psiManager.findFile(dir);
    //noinspection ConstantConditions   we need to unstub a.py here
    ((PsiFileImpl)psiFile).calcTreeElement();
    final PsiElement element;
    try {
      element = doResolve(file);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
    assertResolveResult(element, PyClass.class, "A");
  }

  public void testRelativeImport() {
    assertResolvesTo(PyFile.class, "z.py");
  }

  // PY-11454
  public void testImportSubModuleDunderAll() {
    assertResolvesTo(PyFile.class, "m1.py");
  }

  // PY-11454
  public void testFromImportSubModuleDunderAll() {
    assertResolvesTo(PyFile.class, "m1.py");
  }

  // PY-17941
  public void testEmptyModuleNamesake() {
    final PsiElement module = doResolve();
    assertNotNull(module);
    final Sdk moduleSdk = PythonSdkType.findPythonSdk(myFixture.getModule());
    assertFalse(PythonSdkType.isStdLib(module.getContainingFile().getVirtualFile(), moduleSdk));
  }

  // PY-18626
  public void testManySourceRoots() {
    myFixture.copyDirectoryToProject("manySourceRoots", "");
    withSourceRoots(Lists.newArrayList(myFixture.findFileInTempDir("root1"), myFixture.findFileInTempDir("root2")), () -> {
      final PsiFile psiFile = myFixture.configureByFile("a.py");
      final PsiReference ref = PyResolveTestCase.findReferenceByMarker(psiFile);
      assertInstanceOf(ref, PsiPolyVariantReference.class);
      final List<PsiElement> elements = PyUtil.multiResolveTopPriority((PsiPolyVariantReference)ref);
      assertEquals(1, elements.size());
      final PsiElement element = elements.get(0);
      assertInstanceOf(element, PyFile.class);
      final VirtualFile file = ((PyFile)element).getVirtualFile();
      assertEquals("root1", file.getParent().getName());
    });
  }

  // PY-22522
  public void testBothForeignAndSourceRootImportResultsReturned() {
    myFixture.copyDirectoryToProject("bothForeignAndSourceRootImportResultsReturned", "");

    VirtualFile vf = myFixture.findFileInTempDir("ext/m1.py");

    withSourceRoots(Lists.newArrayList(myFixture.findFileInTempDir("root")), () -> {
      final PsiFile extSource = myFixture.getPsiManager().findFile(vf);
      PyImportResolver foreignResolver = (name, context, withRoots) -> name.toString().equals("m1") ? extSource : null;
      PlatformTestUtil.registerExtension(PyImportResolver.EP_NAME, foreignResolver, getTestRootDisposable());

      final PsiFile psiFile = myFixture.configureByFile("a.py");
      final PsiReference ref = PyResolveTestCase.findReferenceByMarker(psiFile);
      assertInstanceOf(ref, PsiPolyVariantReference.class);
      final List<PsiElement> elements = PyUtil.multiResolveTopPriority((PsiPolyVariantReference)ref);
      assertEquals(2, elements.size());
      final Set<String> parentNames = elements.stream()
        .filter(e -> e instanceof PyFile)
        .map(e -> ((PyFile)e).getVirtualFile().getParent().getName()).collect(Collectors.toSet());
      assertContainsElements(parentNames, "root", "ext");
    });
  }

  private void withSourceRoots(@NotNull List<VirtualFile> sourceRoots, @NotNull Runnable f) {
    final Module module = myFixture.getModule();
    for (VirtualFile root : sourceRoots) {
      PsiTestUtil.addSourceRoot(module, root);
    }
    try {
      f.run();
    }
    finally {
      for (VirtualFile root : sourceRoots) {
        PsiTestUtil.removeSourceRoot(module, root);
      }
    }
  }

  // PY-19989
  public void testAmbiguousImplicitRelativeImport() {
    prepareTestDirectory();
    assertSameElements(doMultiResolveAndGetFileUrls("pkg2/__init__.py"), "pkg2/mod.py");
    assertSameElements(doMultiResolveAndGetFileUrls("pkg/__init__.py"), "pkg/mod.py");
  }

  // PY-21088
  public void testDontResolveToMissingNameInDynamicDunderAll() {
    assertNull(doResolve());
  }

  @NotNull
  private List<String> doMultiResolveAndGetFileUrls(@NotNull String currentFilePath) {
    myFixture.configureByFile(currentFilePath);
    final PsiReference reference = PyResolveTestCase.findReferenceByMarker(myFixture.getFile());
    final VirtualFile root = ModuleRootManager.getInstance(myFixture.getModule()).getSourceRoots()[0];

    final Stream<PsiFileSystemItem> fileSystemItems;
    if (reference instanceof PsiPolyVariantReference) {
      final ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false);
      fileSystemItems = Arrays.stream(results).map(r -> PyPsiUtils.getFileSystemItem(r.getElement()));
    }
    else {
      fileSystemItems = Stream.of(PyPsiUtils.getFileSystemItem(reference.resolve()));
    }
    return fileSystemItems.map(f -> VfsUtilCore.getRelativeLocation(f.getVirtualFile(), root)).collect(Collectors.toList());

  }

  public void testCustomMemberTargetClass(){
    prepareTestDirectory();

    final PyCustomMember customMember = new PyCustomMember("Clazz").resolvesToClass("pkg.mod1.Clazz");
    final PsiFile context = myFixture.configureByText("a.py", "");

    final TypeEvalContext typeEvalContext = TypeEvalContext.codeAnalysis(myFixture.getProject(), context);
    final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(typeEvalContext);

    final PsiElement resolved = customMember.resolve(context, resolveContext);
    assertInstanceOf(resolved, PyTypedElement.class);

    final PyType type = typeEvalContext.getType((PyTypedElement) resolved);
    assertInstanceOf(type, PyClassType.class);
  }
}


text:
package com.dozenx.game.engine.command;

import com.dozenx.util.ByteBufferWrap;
import com.dozenx.util.ByteUtil;

/**
 * Created by luying on 17/2/7.
 */
public class LoginCmd extends   BaseGameCmd{
    private String userName;

    private int threadId;
    private String pwd;
    final CmdType cmdType = CmdType.LOGIN;

    public LoginCmd(byte[] bytes){

        parse(bytes);
    }
    public LoginCmd(String userName, String pwd,int threadId){
        this.userName = userName;
        this.pwd =pwd;
        this.threadId =threadId;

    }

    //|length|threadId|userName|lengthPwd|
    public byte[] toBytes(){

        return ByteUtil.createBuffer().put(cmdType.getType())

                .put(this.threadId)
                .putLenStr(this.userName)
                .putLenStr(this.pwd).array();
       // ByteUtil.createBuffer().put(userNameLength);

    }

    public int getThreadId() {
        return threadId;
    }

    public void setThreadId(int threadId) {
        this.threadId = threadId;
    }

    public static void main(String args[]){
        LoginCmd cmd =new LoginCmd("nihao","imma",0);
        System.out.println(cmd.toBytes().length);

        cmd = new LoginCmd(cmd.toBytes());

        System.out.println(cmd.userName);
        System.out.println(cmd.pwd);
    }
    public void parse(byte[] bytes){

        ByteBufferWrap byteBufferWrap = ByteUtil.createBuffer(bytes);
        byteBufferWrap.getInt();
        this.threadId = byteBufferWrap.getInt();
        this.userName= byteBufferWrap.getLenStr();
        this.pwd = byteBufferWrap.getLenStr();

    }
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public CmdType getCmdType() {
        return cmdType;
    }
}


text:
namespace base {
class SingleThreadTaskRunner;
class TaskRunner;
}  // namespace base

namespace media {
class GpuVideoAcceleratorFactories;
}  // namespace media

namespace content {

// MediaStreamVideoRendererSink is a VideoFrameProvider designed for rendering
// Video MediaStreamTracks [1], MediaStreamVideoRendererSink implements
// MediaStreamVideoSink in order to render video frames provided from a
// MediaStreamVideoTrack, to which it AddToVideoTrack()s itself when the
// VideoFrameProvider is Start()ed and RemoveFromVideoTrack()s itself when the
// latter is Stop()ed.
//
// [1] http://dev.w3.org/2011/webrtc/editor/getusermedia.html#mediastreamtrack
//
// TODO(wuchengli): Add unit test. See the link below for reference.
// http://src.chromium.org/viewvc/chrome/trunk/src/content/renderer/media/rtc_vi
// deo_decoder_unittest.cc?revision=180591&view=markup
class CONTENT_EXPORT MediaStreamVideoRendererSink
    : NON_EXPORTED_BASE(public VideoFrameProvider),
      NON_EXPORTED_BASE(public MediaStreamVideoSink) {
 public:
  MediaStreamVideoRendererSink(
      const blink::WebMediaStreamTrack& video_track,
      const base::Closure& error_cb,
      const RepaintCB& repaint_cb,
      const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
      const scoped_refptr<base::TaskRunner>& worker_task_runner,
      media::GpuVideoAcceleratorFactories* gpu_factories);

  // VideoFrameProvider implementation. Called on the main thread.
  void Start() override;
  void Stop() override;
  void Play() override;
  void Pause() override;
  void SetGpuMemoryBufferVideoForTesting(
      media::GpuMemoryBufferVideoFramePool* gpu_memory_buffer_pool);

 protected:
  ~MediaStreamVideoRendererSink() override;

 private:
  friend class MediaStreamVideoRendererSinkTest;
  enum State {
    STARTED,
    PAUSED,
    STOPPED,
  };

  void OnVideoFrame(const scoped_refptr<media::VideoFrame>& frame,
                    base::TimeTicks estimated_capture_time);
  void FrameReady(const scoped_refptr<media::VideoFrame>& frame);

  // MediaStreamVideoSink implementation. Called on the main thread.
  void OnReadyStateChanged(
      blink::WebMediaStreamSource::ReadyState state) override;

  void RenderSignalingFrame();

  const base::Closure error_cb_;
  const RepaintCB repaint_cb_;

  const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  State state_;
  gfx::Size frame_size_;
  const blink::WebMediaStreamTrack video_track_;

  // Pool of GpuMemoryBuffers and resources used to create hardware frames.
  scoped_ptr<media::GpuMemoryBufferVideoFramePool> gpu_memory_buffer_pool_;
  const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;

  base::WeakPtrFactory<MediaStreamVideoRendererSink> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(MediaStreamVideoRendererSink);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_RTC_VIDEO_RENDERER_H_


text:
namespace content {

namespace {

static ImageTransportFactoryAndroid* g_factory = NULL;

class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid {
 public:
  DirectGLImageTransportFactory();
  virtual ~DirectGLImageTransportFactory();

  virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; }
  virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {}
  virtual uint32_t CreateTexture() OVERRIDE {
    return context_->createTexture();
  }
  virtual void DeleteTexture(uint32_t id) OVERRIDE {
    context_->deleteTexture(id);
  }
  virtual void AcquireTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
  virtual void ReleaseTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
  virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
    return context_.get();
  }
  virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; }

 private:
  scoped_ptr<webkit::gpu::WebGraphicsContext3DInProcessImpl> context_;

  DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory);
};

DirectGLImageTransportFactory::DirectGLImageTransportFactory() {
  WebKit::WebGraphicsContext3D::Attributes attrs;
  attrs.shareResources = false;
  attrs.noAutomaticFlushes = true;
  context_.reset(
      webkit::gpu::WebGraphicsContext3DInProcessImpl::CreateForWindow(
          attrs,
          NULL,
          NULL));
}

DirectGLImageTransportFactory::~DirectGLImageTransportFactory() {
}

class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid {
 public:
  CmdBufferImageTransportFactory();
  virtual ~CmdBufferImageTransportFactory();

  virtual uint32_t InsertSyncPoint() OVERRIDE;
  virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE;
  virtual uint32_t CreateTexture() OVERRIDE;
  virtual void DeleteTexture(uint32_t id) OVERRIDE;
  virtual void AcquireTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
  virtual void ReleaseTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
  virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
    return context_.get();
  }
  virtual GLHelper* GetGLHelper() OVERRIDE;

 private:
  scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
  scoped_ptr<GLHelper> gl_helper_;

  DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory);
};

CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() {
  WebKit::WebGraphicsContext3D::Attributes attrs;
  attrs.shareResources = true;
  GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance();
  GURL url("chrome://gpu/ImageTransportFactoryAndroid");
  base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client;
  context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen
                                                           url,
                                                           factory,
                                                           swap_client));
  context_->Initialize(
      attrs,
      false,
      CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
}

CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() {
}

uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return 0;
  }
  return context_->insertSyncPoint();
}

void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->waitSyncPoint(sync_point);
}

uint32_t CmdBufferImageTransportFactory::CreateTexture() {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return false;
  }
  return context_->createTexture();
}

void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->deleteTexture(id);
}

void CmdBufferImageTransportFactory::AcquireTexture(
    uint32 texture_id, const signed char* mailbox_name) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->bindTexture(GL_TEXTURE_2D, texture_id);
  context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
  context_->flush();
}

void CmdBufferImageTransportFactory::ReleaseTexture(
    uint32 texture_id, const signed char* mailbox_name) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->bindTexture(GL_TEXTURE_2D, texture_id);
  context_->produceTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
}

GLHelper* CmdBufferImageTransportFactory::GetGLHelper() {
  if (!gl_helper_.get())
    gl_helper_.reset(new GLHelper(GetContext3D(), NULL));

  return gl_helper_.get();
}

}  // anonymous namespace

// static
ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() {
  if (!g_factory) {
    if (CompositorImpl::UsesDirectGL())
      g_factory = new DirectGLImageTransportFactory();
    else
      g_factory = new CmdBufferImageTransportFactory();
  }

  return g_factory;
}

ImageTransportFactoryAndroid::ImageTransportFactoryAndroid() {
}

ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() {
}

} // namespace content


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

    <groupId>com.quickforce</groupId>
    <artifactId>quickforcelibrary</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <kotlin.version>1.1.4-3</kotlin.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>testCompile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jre8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>


text:
game = Game.deployed();
game.initialize(15, 15, 4, 500000000000000000, 1000000000000000000, CreatureBuilder.address, {gasPrice: 100000000000}).
  then(function() { game.set_devcon_map({gasPrice: 100000000000}) }).
  then(function() { process.exit(); });


text:
from hakoblog.model.blog import Blog

class BlogLoader:
    @classmethod
    def find_by_id(cls, db, blog_id):
        with db.cursor() as cursor:
            cursor.execute(
                """
                SELECT id, owner_id, title
                FROM blog
                WHERE id = %s
                LIMIT 1
                """,
                (blog_id,),
            )
            row = cursor.fetchone()

            if row is None:
                return None

        return Blog(**row)

    @classmethod
    def find_by_owner_id(cls, db, owner_id):
        with db.cursor() as cursor:
            cursor.execute(
                """
                SELECT id, owner_id, title
                FROM blog
                WHERE owner_id = %s
                LIMIT 1
                """,
                (owner_id,),
            )
            row = cursor.fetchone()

            if row is None:
                return None

        return Blog(**row)


text:
App.DeckView = Backbone.View.extend({
  tagName: "div",
  events: {
    "click": "doClick"
  },
  name: '',
  initialize: function(attributes, options) {
    this.name = attributes.name;
    App.log('DeckView initialize ' + this.name);
    this.template = _.template($('#item-template').html());
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.model, 'destroy', this.remove);
  },
  doClick: function(event) {
    App.log(this.name + ' clicked');
    this.model.destroy();
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  },
});


text:
package org.helianto.core.domain;

import javax.persistence.Column;

import org.helianto.core.def.PhoneType;

/**
 * Phone basic info.
 *
 * @author Mauricio Fernandes de Castro
 */
@javax.persistence.Embeddable
public class Phone implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    @Column(length=20)
    private String phoneNumber = "";

    @Column(length=3)
    private String areaCode = "";

    @Column(length=10)
    private String branch = "";

    private char phoneType = PhoneType.MAIN.getValue();

    /**
     * Default constructor
     */
    public Phone() {
    	super();
    }

    /**
     * Phone constructor.
     *
     * @param areaCode
     * @param phoneNumber
     */
    public Phone(String areaCode, String phoneNumber) {
    	this(phoneNumber, areaCode, PhoneType.MAIN);
    }

    /**
     * Phone type constructor.
     *
     * @param areaCode
     * @param phoneNumber
     * @param phoneType
     */
    public Phone(String areaCode, String phoneNumber, PhoneType phoneType) {
    	super();
    	setPhoneNumber(phoneNumber);
    	setAreaCode(areaCode);
    	setPhoneTypeAsEnum(phoneType);
    }

    /**
     * Phone number.
     */
    public String getPhoneNumber() {
        return this.phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    /**
     * Area code.
     */
    public String getAreaCode() {
        return this.areaCode;
    }
    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }

    /**
     * Branch.
     */
    public String getBranch() {
		return branch;
	}
    public void setBranch(String branch) {
		this.branch = branch;
	}

    /**
     * Phone type.
     */
    public char getPhoneType() {
        return this.phoneType;
    }
    public void setPhoneType(char phoneType) {
        this.phoneType = phoneType;
    }
    public void setPhoneTypeAsEnum(PhoneType phoneType) {
        this.phoneType = phoneType.getValue();
    }

    /**
     * toString
     * @return String
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();

        buffer
        .append("(")
        .append(getAreaCode())
        .append(") ")
        .append(getPhoneNumber());

        if (getBranch()!=null && getBranch().length()>0) {
        	buffer
        	.append(" - ")
            .append(getBranch());
        }

        return buffer.toString();
    }

}


text:
/* -*- c++ -*- */
#ifndef JAWS_CONCURRENCY_H
#define JAWS_CONCURRENCY_H

#include "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ace/Task.h"
#include "JAWS_IO.h"

class JAWS_Concurrency_Base : public ACE_Task<ACE_SYNCH>
  // = TITLE
  //     Base class for different concurrency models
  //
  // = DESCRIPTION
  //     Provides a default implementaion of the virtual put() method
  //     which calls putq(), but can be overloaded to do something
  //     synchronously, such as call put_next().

{
public:
  JAWS_Concurrency_Base (void);
  virtual int put (ACE_Message_Block *mb, ACE_Time_Value *tv = 0);
  virtual int svc (void);
};

class JAWS_Dispatch_Policy
  // = TITLE
  //     Policy mechanism for choosing different concurrency models.
  //
  // = DESCRIPTION
  //     Given some (unspecified) state, decides what the concurrency
  //     model should be.  (For now, we always return the same model.)
{
public:
  JAWS_Dispatch_Policy (void);
  virtual ~JAWS_Dispatch_Policy (void);
  virtual JAWS_Concurrency_Base * update (void *state = 0) = 0;
};

class JAWS_Dispatcher
  // = TITLE
  //     The class that is responsible to delivering events to the
  //     appropriate concurrency mechanism.
  //
  // = DESCRIPTION
  //     JAWS_IO_Handler calls into the dispatcher so that the completed
  //     IO can find a thread to take care of it.
{
public:
  JAWS_Dispatcher (JAWS_Dispatch_Policy *policy);

  int dispatch (JAWS_IO_Handler *ioh);

private:
  JAWS_Dispatch_Policy *policy_;
};

class JAWS_Thread_Pool_Task : public JAWS_Concurrency_Base
  // = TITLE
  //     Used to implement Thread Pool Concurrency Strategy
  //
  // = DESCRIPTION
  //     This task is created to hold a pool of threads that receive
  //     requests through the message queue.
{
public:
  JAWS_Thread_Pool_Task (long flags = THR_NEW_LWP,
                         int nthreads = 5,
                         int maxthreads = 20);

private:
  int nthreads_;
  int maxthreads_;
};

class JAWS_Thread_Per_Task : public JAWS_Concurrency_Base
  // = TITLE
  //     Used to implement Thread Per Request Concurrency Strategy
  //
  // = DESCRIPTION
  //     As each new message arrives from the queue, a new thread is
  //     spawned to handle it.  This is done by overloading put to call
  //     activate.
{
public:
  JAWS_Thread_Per_Task (long flags = THR_NEW_LWP, int maxthreads = 20);

  virtual int put (ACE_Message_Block *mb, ACE_Time_Value *tv = 0);

private:
  long flags_;
  int maxthreads_;
};

#endif /* !defined (JAWS_CONCURRENCY_H) */


text:
function tictactoe(){
  var $wnd_0 = window, $doc_0 = document, $stats = $wnd_0.__gwtStatsEvent?function(a){
    return $wnd_0.__gwtStatsEvent(a);
  }
  :null, $sessionId_0 = $wnd_0.__gwtStatsSessionId?$wnd_0.__gwtStatsSessionId:null, scriptsDone, loadDone, bodyDone, base = '', metaProps = {}, values = [], providers = [], answers = [], softPermutationId = 0, onLoadErrorFunc, propertyErrorFunc;
  $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'bootstrap', millis:(new Date).getTime(), type:'begin'});
  if (!$wnd_0.__gwt_stylesLoaded) {
    $wnd_0.__gwt_stylesLoaded = {};
  }
  if (!$wnd_0.__gwt_scriptsLoaded) {
    $wnd_0.__gwt_scriptsLoaded = {};
  }
  function isHostedMode(){
    var result = false;
    try {
      var query = $wnd_0.location.search;
      return (query.indexOf('gwt.codesvr=') != -1 || (query.indexOf('gwt.hosted=') != -1 || $wnd_0.external && $wnd_0.external.gwtOnLoad)) && query.indexOf('gwt.hybrid') == -1;
    }
     catch (e) {
    }
    isHostedMode = function(){
      return result;
    }
    ;
    return result;
  }

  function maybeStartModule(){
    if (scriptsDone && loadDone) {
      var iframe = $doc_0.getElementById('tictactoe');
      var frameWnd = iframe.contentWindow;
      if (isHostedMode()) {
        frameWnd.__gwt_getProperty = function(name_0){
          return computePropValue(name_0);
        }
        ;
      }
      tictactoe = null;
      frameWnd.gwtOnLoad(onLoadErrorFunc, 'tictactoe', base, softPermutationId);
      $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date).getTime(), type:'end'});
    }
  }

  function computeScriptBase(){
    function getDirectoryOfFile(path){
      var hashIndex = path.lastIndexOf('#');
      if (hashIndex == -1) {
        hashIndex = path.length;
      }
      var queryIndex = path.indexOf('?');
      if (queryIndex == -1) {
        queryIndex = path.length;
      }
      var slashIndex = path.lastIndexOf('/', Math.min(queryIndex, hashIndex));
      return slashIndex >= 0?path.substring(0, slashIndex + 1):'';
    }

    function ensureAbsoluteUrl(url){
      if (url.match(/^\w+:\/\//)) {
      }
       else {
        var img = $doc_0.createElement('img');
        img.src = url + 'clear.cache.gif';
        url = getDirectoryOfFile(img.src);
      }
      return url;
    }

    function tryMetaTag(){
      var metaVal = __gwt_getMetaProperty('baseUrl');
      if (metaVal != null) {
        return metaVal;
      }
      return '';
    }

    function tryNocacheJsTag(){
      var scriptTags = $doc_0.getElementsByTagName('script');
      for (var i = 0; i < scriptTags.length; ++i) {
        if (scriptTags[i].src.indexOf('tictactoe.nocache.js') != -1) {
          return getDirectoryOfFile(scriptTags[i].src);
        }
      }
      return '';
    }

    function tryMarkerScript(){
      var thisScript;
      if (typeof isBodyLoaded == 'undefined' || !isBodyLoaded()) {
        var markerId = '__gwt_marker_tictactoe';
        var markerScript;
        $doc_0.write('<script id="' + markerId + '"><\/script>');
        markerScript = $doc_0.getElementById(markerId);
        thisScript = markerScript && markerScript.previousSibling;
        while (thisScript && thisScript.tagName != 'SCRIPT') {
          thisScript = thisScript.previousSibling;
        }
        if (markerScript) {
          markerScript.parentNode.removeChild(markerScript);
        }
        if (thisScript && thisScript.src) {
          return getDirectoryOfFile(thisScript.src);
        }
      }
      return '';
    }

    function tryBaseTag(){
      var baseElements = $doc_0.getElementsByTagName('base');
      if (baseElements.length > 0) {
        return baseElements[baseElements.length - 1].href;
      }
      return '';
    }

    function isLocationOk(){
      var loc = $doc_0.location;
      return loc.href == loc.protocol + '//' + loc.host + loc.pathname + loc.search + loc.hash;
    }

    var tempBase = tryMetaTag();
    if (tempBase == '') {
      tempBase = tryNocacheJsTag();
    }
    if (tempBase == '') {
      tempBase = tryMarkerScript();
    }
    if (tempBase == '') {
      tempBase = tryBaseTag();
    }
    if (tempBase == '' && isLocationOk()) {
      tempBase = getDirectoryOfFile($doc_0.location.href);
    }
    tempBase = ensureAbsoluteUrl(tempBase);
    base = tempBase;
    return tempBase;
  }

  function processMetas(){
    var metas = document.getElementsByTagName('meta');
    for (var i = 0, n = metas.length; i < n; ++i) {
      var meta = metas[i], name_0 = meta.getAttribute('name'), content_0;
      if (name_0) {
        name_0 = name_0.replace('tictactoe::', '');
        if (name_0.indexOf('::') >= 0) {
          continue;
        }
        if (name_0 == 'gwt:property') {
          content_0 = meta.getAttribute('content');
          if (content_0) {
            var value, eq = content_0.indexOf('=');
            if (eq >= 0) {
              name_0 = content_0.substring(0, eq);
              value = content_0.substring(eq + 1);
            }
             else {
              name_0 = content_0;
              value = '';
            }
            metaProps[name_0] = value;
          }
        }
         else if (name_0 == 'gwt:onPropertyErrorFn') {
          content_0 = meta.getAttribute('content');
          if (content_0) {
            try {
              propertyErrorFunc = eval(content_0);
            }
             catch (e) {
              alert('Bad handler "' + content_0 + '" for "gwt:onPropertyErrorFn"');
            }
          }
        }
         else if (name_0 == 'gwt:onLoadErrorFn') {
          content_0 = meta.getAttribute('content');
          if (content_0) {
            try {
              onLoadErrorFunc = eval(content_0);
            }
             catch (e) {
              alert('Bad handler "' + content_0 + '" for "gwt:onLoadErrorFn"');
            }
          }
        }
      }
    }
  }

  function __gwt_getMetaProperty(name_0){
    var value = metaProps[name_0];
    return value == null?null:value;
  }

  function unflattenKeylistIntoAnswers(propValArray, value){
    var answer = answers;
    for (var i = 0, n = propValArray.length - 1; i < n; ++i) {
      answer = answer[propValArray[i]] || (answer[propValArray[i]] = []);
    }
    answer[propValArray[n]] = value;
  }

  function computePropValue(propName){
    var value = providers[propName](), allowedValuesMap = values[propName];
    if (value in allowedValuesMap) {
      return value;
    }
    var allowedValuesList = [];
    for (var k in allowedValuesMap) {
      allowedValuesList[allowedValuesMap[k]] = k;
    }
    if (propertyErrorFunc) {
      propertyErrorFunc(propName, allowedValuesList, value);
    }
    throw null;
  }

  var frameInjected;
  function maybeInjectFrame(){
    if (!frameInjected) {
      frameInjected = true;
      var iframe = $doc_0.createElement('iframe');
      iframe.src = "javascript:''";
      iframe.id = 'tictactoe';
      iframe.style.cssText = 'position:absolute;width:0;height:0;border:none';
      iframe.tabIndex = -1;
      $doc_0.body.appendChild(iframe);
      $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date).getTime(), type:'moduleRequested'});
      iframe.contentWindow.location.replace(base + initialHtml);
    }
  }

  providers['user.agent'] = function(){
    var ua = navigator.userAgent.toLowerCase();
    var makeVersion = function(result){
      return parseInt(result[1]) * 1000 + parseInt(result[2]);
    }
    ;
    if (function(){
      return ua.indexOf('opera') != -1;
    }
    ())
      return 'opera';
    if (function(){
      return ua.indexOf('webkit') != -1;
    }
    ())
      return 'safari';
    if (function(){
      return ua.indexOf('msie') != -1 && $doc_0.documentMode >= 9;
    }
    ())
      return 'ie9';
    if (function(){
      return ua.indexOf('msie') != -1 && $doc_0.documentMode >= 8;
    }
    ())
      return 'ie8';
    if (function(){
      var result = /msie ([0-9]+)\.([0-9]+)/.exec(ua);
      if (result && result.length == 3)
        return makeVersion(result) >= 6000;
    }
    ())
      return 'ie6';
    if (function(){
      return ua.indexOf('gecko') != -1;
    }
    ())
      return 'gecko1_8';
    return 'unknown';
  }
  ;
  values['user.agent'] = {gecko1_8:0, ie6:1, ie8:2, ie9:3, opera:4, safari:5};
  tictactoe.onScriptLoad = function(){
    if (frameInjected) {
      loadDone = true;
      maybeStartModule();
    }
  }
  ;
  tictactoe.onInjectionDone = function(){
    scriptsDone = true;
    $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'loadExternalRefs', millis:(new Date).getTime(), type:'end'});
    maybeStartModule();
  }
  ;
  processMetas();
  computeScriptBase();
  var strongName;
  var initialHtml;
  if (isHostedMode()) {
    if ($wnd_0.external && ($wnd_0.external.initModule && $wnd_0.external.initModule('tictactoe'))) {
      $wnd_0.location.reload();
      return;
    }
    initialHtml = 'hosted.html?tictactoe';
    strongName = '';
  }
  $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'bootstrap', millis:(new Date).getTime(), type:'selectingPermutation'});
  if (!isHostedMode()) {
    try {
      unflattenKeylistIntoAnswers(['ie6'], '0D6670660F6D14D157244BB84C5524C9');
      unflattenKeylistIntoAnswers(['safari'], '3B52EB58A1E3D3E8253A8C17605BA9D7');
      unflattenKeylistIntoAnswers(['opera'], '54411454F2A1ACFA69461FF925632C5A');
      unflattenKeylistIntoAnswers(['ie9'], '57A2A860E49C08853EF2945C4D3488B5');
      unflattenKeylistIntoAnswers(['gecko1_8'], 'B3B92D6A034D391394E9D2475401F401');
      unflattenKeylistIntoAnswers(['ie8'], 'F48B666F7FB02AF6D3FA42663EE940DD');
      strongName = answers[computePropValue('user.agent')];
      var idx = strongName.indexOf(':');
      if (idx != -1) {
        softPermutationId = Number(strongName.substring(idx + 1));
        strongName = strongName.substring(0, idx);
      }
      initialHtml = strongName + '.cache.html';
    }
     catch (e) {
      return;
    }
  }
  var onBodyDoneTimerId;
  function onBodyDone(){
    if (!bodyDone) {
      bodyDone = true;
      maybeStartModule();
      if ($doc_0.removeEventListener) {
        $doc_0.removeEventListener('DOMContentLoaded', onBodyDone, false);
      }
      if (onBodyDoneTimerId) {
        clearInterval(onBodyDoneTimerId);
      }
    }
  }

  if ($doc_0.addEventListener) {
    $doc_0.addEventListener('DOMContentLoaded', function(){
      maybeInjectFrame();
      onBodyDone();
    }
    , false);
  }
  var onBodyDoneTimerId = setInterval(function(){
    if (/loaded|complete/.test($doc_0.readyState)) {
      maybeInjectFrame();
      onBodyDone();
    }
  }
  , 50);
  $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'bootstrap', millis:(new Date).getTime(), type:'end'});
  $stats && $stats({moduleName:'tictactoe', sessionId:$sessionId_0, subSystem:'startup', evtGroup:'loadExternalRefs', millis:(new Date).getTime(), type:'begin'});
  $doc_0.write('<script defer="defer">tictactoe.onInjectionDone(\'tictactoe\')<\/script>');
}

tictactoe();


text:
'use strict';

eventsApp.directive('dateKeys',function ($compile) {
    return {
        restrict:'A',
        replace:true,

        //isolating scope
        scope:{

        },
        link:function (scope,element,attrs,controller) {
            element.on('keydown',function(event){
                if(isNumericKey(event.keyCode) || isForwardSlashKeyCode(event.keyCode)||isNavigationKeyCode(event.keyCode)){
                    return true;
                }else{
                    return false;
                }
            });
        }
    }

    function isNumericKey(keyCode){
        return (event.keyCode>=48 && event.keyCode<=57)
        ||(event.keyCode>=96 && event.keyCode<=105);
    }

    function isForwardSlashKeyCode(keyCode){
        return event.keyCode===191;
    }

    function isNavigationKeyCode(keyCode){
        switch (keyCode){
            case 8:
            case 35:
            case 36:
            case 37:
            case 38:
            case 39:
            case 40:
            case 45:
            case 46:
                return true;
            default:
                return false;
        }
    }
});


text:
package edu.rit.csh.wikiData;

/**
 * Created by jd on 6/23/15.
 */
public class Rating {
    public Long userId;
    public Long movieId;
    public Double rating;
    public Long timestamp;

    public Rating() { }
}


text:
Items

    <jh-alert></jh-alert>

                    Title
                    Description
                    PublishedDate

                      {{item.title}}

                    {{item.publishedDate | date:"EEE, dd MMM yyyy HH:mm:ss Z"}}


text:
import numpy as np
from math import ceil

def replicator(A, x, inds, tol, max_iter):
    error = tol + 1.0
    count = 0
    while error > tol and count < max_iter:
        x_old = np.copy(x)
        for i in inds:
            x[i] = x_old[i] * (A[i] @ x_old)
        x /= np.sum(x)
        error = np.linalg.norm(x - x_old)
        count += 1
    return x

def dominant_sets(graph_mat, max_k=0, tol=1e-5, max_iter=1000):
    graph_cardinality = graph_mat.shape[0]
    if max_k == 0:
        max_k = graph_cardinality
    clusters = np.zeros(graph_cardinality)
    already_clustered = np.full(graph_cardinality, False, dtype=np.bool)

    for k in range(max_k):
        if graph_cardinality - already_clustered.sum() <= ceil(0.05 * graph_cardinality):
            break
        # 1000 is added to obtain more similar values when x is normalized
        # x = np.random.random_sample(graph_cardinality) + 1000.0
        x = np.full(graph_cardinality, 1.0)
        x[already_clustered] = 0.0
        x /= x.sum()

        y = replicator(graph_mat, x, np.where(~already_clustered)[0], tol, max_iter)
        cluster = np.where(y >= 1.0 / (graph_cardinality * 1.5))[0]
        already_clustered[cluster] = True
        clusters[cluster] = k
    clusters[~already_clustered] = k
    return clusters


text:
<?php

namespace GlobalBundle\Entity;

/**
 * AboutRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AboutRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
import PageManager from '../page-manager';

export default class RSS extends PageManager {}


text:
import axios from 'axios'

axios.defaults.baseURL = 'https://api.fullstackweekly.com'

const appService = {
  getPosts (categoryId) {
    return new Promise((resolve) => {
      axios.get(`/wp-json/wp/v2/posts?categories=${categoryId}&per_page=6`)
        .then(response => {
          resolve(response.data)
        })
    })
  }
}

export default appService


text:
package com.alibaba.otter.canal.common.zookeeper;

import java.text.MessageFormat;

import org.apache.commons.lang.StringUtils;

/**
 * 存储结构:
 *
 *

 * /otter
 *    canal
 *      cluster
 *      destinations
 *        dest1
 *          running (EPHEMERAL)
 *          cluster
 *          client1
 *            running (EPHEMERAL)
 *            cluster
 *            filter
 *            cursor
 *            mark
 *              1
 *              2
 *              3
 *

 *
 * @author zebin.xuzb @ 2012-6-21
 * @version 1.0.0
 */
public class ZookeeperPathUtils {

    public static final String ZOOKEEPER_SEPARATOR                          = "/";

    public static final String OTTER_ROOT_NODE                              = ZOOKEEPER_SEPARATOR + "otter";

    public static final String CANAL_ROOT_NODE                              = OTTER_ROOT_NODE + ZOOKEEPER_SEPARATOR
                                                                              + "canal";

    public static final String DESTINATION_ROOT_NODE                        = CANAL_ROOT_NODE + ZOOKEEPER_SEPARATOR
                                                                              + "destinations";

    public static final String FILTER_NODE                                  = "filter";

    public static final String BATCH_MARK_NODE                              = "mark";

    public static final String PARSE_NODE                                   = "parse";

    public static final String CURSOR_NODE                                  = "cursor";

    public static final String RUNNING_NODE                                 = "running";

    public static final String CLUSTER_NODE                                 = "cluster";

    public static final String DESTINATION_NODE                             = DESTINATION_ROOT_NODE
                                                                              + ZOOKEEPER_SEPARATOR + "{0}";

    public static final String DESTINATION_PARSE_NODE                       = DESTINATION_NODE + ZOOKEEPER_SEPARATOR
                                                                              + PARSE_NODE;

    public static final String DESTINATION_CLIENTID_NODE                    = DESTINATION_NODE + ZOOKEEPER_SEPARATOR
                                                                              + "{1}";

    public static final String DESTINATION_CURSOR_NODE                      = DESTINATION_CLIENTID_NODE
                                                                              + ZOOKEEPER_SEPARATOR + CURSOR_NODE;

    public static final String DESTINATION_CLIENTID_FILTER_NODE             = DESTINATION_CLIENTID_NODE
                                                                              + ZOOKEEPER_SEPARATOR + FILTER_NODE;

    public static final String DESTINATION_CLIENTID_BATCH_MARK_NODE         = DESTINATION_CLIENTID_NODE
                                                                              + ZOOKEEPER_SEPARATOR + BATCH_MARK_NODE;

    public static final String DESTINATION_CLIENTID_BATCH_MARK_WITH_ID_PATH = DESTINATION_CLIENTID_BATCH_MARK_NODE
                                                                              + ZOOKEEPER_SEPARATOR + "{2}";

    /**
     * 服务端当前正在提供服务的running节点
     */
    public static final String DESTINATION_RUNNING_NODE                     = DESTINATION_NODE + ZOOKEEPER_SEPARATOR
                                                                              + RUNNING_NODE;

    /**
     * 客户端当前正在工作的running节点
     */
    public static final String DESTINATION_CLIENTID_RUNNING_NODE            = DESTINATION_CLIENTID_NODE
                                                                              + ZOOKEEPER_SEPARATOR + RUNNING_NODE;

    /**
     * 整个canal server的集群列表
     */
    public static final String CANAL_CLUSTER_ROOT_NODE                      = CANAL_ROOT_NODE + ZOOKEEPER_SEPARATOR
                                                                              + CLUSTER_NODE;

    public static final String CANAL_CLUSTER_NODE                           = CANAL_CLUSTER_ROOT_NODE
                                                                              + ZOOKEEPER_SEPARATOR + "{0}";

    /**
     * 针对某个destination的工作的集群列表
     */
    public static final String DESTINATION_CLUSTER_ROOT                     = DESTINATION_NODE + ZOOKEEPER_SEPARATOR
                                                                              + CLUSTER_NODE;
    public static final String DESTINATION_CLUSTER_NODE                     = DESTINATION_CLUSTER_ROOT
                                                                              + ZOOKEEPER_SEPARATOR + "{1}";

    /**
     * 获取Instance工作目录,/otter/canal/destinations/{instance_name}
     */
    public static String getDestinationPath(String destinationName) {
        return MessageFormat.format(DESTINATION_NODE, destinationName);
    }

    /**
     * 获取instance客户端工作目录,otter/canal/destinations/{instance_name}/{client_id}
     */
    public static String getClientIdNodePath(String destinationName, short clientId) {
        return MessageFormat.format(DESTINATION_CLIENTID_NODE, destinationName, String.valueOf(clientId));
    }

    /**
     * 获取instance客户端filter节点,/otter/canal/destinations/{instance_name}/{client_id}/filter
     */
    public static String getFilterPath(String destinationName, short clientId) {
        return MessageFormat.format(DESTINATION_CLIENTID_FILTER_NODE, destinationName, String.valueOf(clientId));
    }

    /**
     * 获取batch工作目录,/otter/canal/destinations/{destination}/{client_id}/mark
     */
    public static String getBatchMarkPath(String destinationName, short clientId) {
        return MessageFormat.format(DESTINATION_CLIENTID_BATCH_MARK_NODE, destinationName, String.valueOf(clientId));
    }

    public static String getBatchMarkWithIdPath(String destinationName, short clientId, Long batchId) {
        return MessageFormat.format(DESTINATION_CLIENTID_BATCH_MARK_WITH_ID_PATH,
            destinationName,
            String.valueOf(clientId),
            getBatchMarkNode(batchId));
    }

    /**
     * 获取instance客户端cursor节点,/otter/canal/destinations/{instance_name}/{client_id}/cursor
     */
    public static String getCursorPath(String destination, short clientId) {
        return MessageFormat.format(DESTINATION_CURSOR_NODE, destination, String.valueOf(clientId));
    }

    public static String getCanalClusterNode(String node) {
        return MessageFormat.format(CANAL_CLUSTER_NODE, node);
    }

    /**
     *

     *   yzy: 获取一个指定instance保存正在运行Server地址的目录,otter/canal/destinations/{instance_name}/running
     *

     *
     * @param destination:instance名称
     *
     * 服务端当前正在提供服务的running节点
     */
    public static String getDestinationServerRunning(String destination) {
        return MessageFormat.format(DESTINATION_RUNNING_NODE, destination);
    }

    /**
     * 客户端当前正在工作的running节点
     */
    public static String getDestinationClientRunning(String destination, short clientId) {
        return MessageFormat.format(DESTINATION_CLIENTID_RUNNING_NODE, destination, String.valueOf(clientId));
    }

    /**
     * 获得Instance对应的集群节点名称,/otter/canal/destinations/{instance_name}/cluster/{ip_address}。
     *
     * @param destination
     * @param node
     * @return
     */
    public static String getDestinationClusterNode(String destination, String node) {
        return MessageFormat.format(DESTINATION_CLUSTER_NODE, destination, node);
    }

    /**
     * 获得Instance集群节点根目录/otter/canal/destinations/{instance_name}/cluster/
     *
     * @param destination
     * @return
     */
    public static String getDestinationClusterRoot(String destination) {
        return MessageFormat.format(DESTINATION_CLUSTER_ROOT, destination);
    }

    public static String getParsePath(String destination) {
        return MessageFormat.format(DESTINATION_PARSE_NODE, destination);
    }

    /**
     * 将batchNode转换为Long
     */
    public static short getClientId(String clientNode) {
        return Short.valueOf(clientNode);
    }

    /**
     * 将batchNode转换为Long
     */
    public static long getBatchMarkId(String batchMarkNode) {
        return Long.valueOf(batchMarkNode);
    }

    /**
     * 将batchId转化为zookeeper中的node名称
     */
    public static String getBatchMarkNode(Long batchId) {
        return StringUtils.leftPad(String.valueOf(batchId.intValue()), 10, '0');
    }
}


text:
<?php
require_once '../tests/bootstrap.php';
use Respect\Rest\Router;

$r3 = new Router;

$r3->any('/**', function ($url) {
    return 'Welcome to Respect/Rest the url you want is: /'.implode('/', $url);
});


text:
> There are 10 types of people in the world: Those who understand
> binary, and those who don't.

You and your fellow cohort of those in the "know" when it comes to
binary decide to come up with a secret "handshake".

```text
1 = wink
10 = double blink
100 = close your eyes
1000 = jump

10000 = Reverse the order of the operations in the secret handshake.
```

Given a decimal number, convert it to the appropriate sequence of events for a secret handshake.

Here's a couple of examples:

Given the input 3, the function would return the array
["wink", "double blink"] because 3 is 11 in binary.

Given the input 19, the function would return the array
["double blink", "wink"] because 19 is 10011 in binary.
Notice that the addition of 16 (10000 in binary)
has caused the array to be reversed.

## Coding the solution

Look for a stub file having the name secret_handshake.go
and place your solution code in that file.

## Running the tests

To run the tests run the command `go test` from within the exercise directory.

If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:

    go test -v --bench . --benchmem

Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.

## Further information

For more detailed information about the Go track, including how to get help if
you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/resources).

## Source

Bert, in Mary Poppins [http://www.imdb.com/title/tt0058331/quotes/qt0437047](http://www.imdb.com/title/tt0058331/quotes/qt0437047)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
package gedi.gui.genovis.tracks.boxrenderer;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

import gedi.core.data.annotation.NarrowPeakAnnotation;
import gedi.core.data.annotation.ScoreProvider;
import gedi.core.data.mapper.StorageSource;
import gedi.core.reference.ReferenceSequence;
import gedi.core.reference.Strand;
import gedi.core.region.GenomicRegion;
import gedi.util.MathUtils;
import gedi.util.PaintUtils;
import gedi.util.functions.EI;
import gedi.util.gui.PixelBasepairMapper;
import gedi.util.gui.ValueToColorMapper;

public class NarrowPeakRenderer extends BoxRenderer<NarrowPeakAnnotation> {

	private ValueToColorMapper mapper = new ValueToColorMapper(Color.WHITE,Color.BLACK);

	private Color summitColor=Color.RED;

	public NarrowPeakRenderer() {
		setBackground(t->mapper.apply(t.getScore()));
		setForeground(t->PaintUtils.isDarkColor(mapper.apply(t.getScore()))?Color.WHITE:Color.BLACK);
		stringer = s->s.getData().toString();
	}

	public void linear(double min, double max) {
		mapper = new ValueToColorMapper(MathUtils.linearRange(min,max), mapper.getColors());
	}

	public void linear(StorageSource<? extends ScoreProvider> src) {
		double[] minmax = EI.wrap(src.getStorages()).demultiplex(s->s.ei()).mapToDouble(r->r.getData().getScore()).saveMinMax(0,1000);
		linear(minmax[0],minmax[1]);
	}

	public void colors(Color... colors) {
		mapper = new ValueToColorMapper(mapper.getRange(), colors);
	}

	public void summit(Color color) {
		this.summitColor=color;
	}

	@Override
	public GenomicRegion renderBox(Graphics2D g2, PixelBasepairMapper locationMapper,
			ReferenceSequence reference, Strand strand, GenomicRegion region,
			NarrowPeakAnnotation d, double xOffset, double y, double h,boolean boxes, boolean lines) {
		GenomicRegion re = super.renderBox(g2, locationMapper, reference, strand, region, d, xOffset, y, h,boxes,lines);

		if (d.getSummit()>=0 && d.getSummit()<region.getTotalLength()) {
			Rectangle2D tile = getTile(reference, region.map(d.getSummit()), region.map(d.getSummit())+1, locationMapper, xOffset, y, h);
			g2.setPaint(summitColor);
			g2.fill(tile);
			g2.draw(tile);
		}

		return re;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.colorimetry.tristimulus Module — Colour 0.3.3 documentation</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.3 documentation" href="index.html" />
    <link rel="up" title="colour.colorimetry Package" href="colour.colorimetry.html" />
    <link rel="next" title="colour.colorimetry.whiteness Module" href="colour.colorimetry.whiteness.html" />
    <link rel="prev" title="colour.colorimetry.transformations Module" href="colour.colorimetry.transformations.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

    « colour.colorimet...

    colour.colorimet... »

<form class="navbar-form navbar-right" action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

colour.colorimetry.tristimulus Module¶

Tristimulus Values¶

Defines objects for tristimulus values computation from spectral data.

See also

Colour Matching Functions IPython Notebook
Spectrum IPython Notebook

<tt class="descclassname">colour.colorimetry.tristimulus.</tt><tt class="descname">spectral_to_XYZ</tt><big>(</big>spd, cmfs=<colour.colorimetry.cmfs.XYZ_ColourMatchingFunctions object at 0x2b3679ab5690>, illuminant=None<big>)</big>[source]¶

Converts given spectral power distribution to CIE XYZ colourspace using
given colour matching functions and illuminant.

<col class="field-name" />
<col class="field-body" />

Parameters:

spd (SpectralPowerDistribution) – Spectral power distribution.

cmfs (XYZ_ColourMatchingFunctions) – Standard observer colour matching functions.

illuminant (SpectralPowerDistribution, optional) – Illuminant spectral power distribution.

Returns:
CIE XYZ colourspace matrix.

Return type:
ndarray, (3,)

Warning

The output domain of that definition is non standard!

Notes

Output CIE XYZ colourspace matrix is in domain [0, 100].

References

<colgroup><col class="label" /><col /></colgroup>

[1]	Wyszecki, G., & Stiles, W. S. (2000). Integration Replace by
Summation. In Color Science: Concepts and Methods, Quantitative
Data and Formulae (pp. 158–163). Wiley. ISBN:978-0471399186

Examples

>>> from colour import CMFS, ILLUMINANTS_RELATIVE_SPDS, SpectralPowerDistribution
>>> cmfs = CMFS.get('CIE 1931 2 Degree Standard Observer')
>>> data = {380: 0.0600, 390: 0.0600}
>>> spd = SpectralPowerDistribution('Custom', data)
>>> illuminant = ILLUMINANTS_RELATIVE_SPDS.get('D50')
>>> spectral_to_XYZ(spd, cmfs, illuminant)
array([  4.5764852...e-04,   1.2964866...e-05,   2.1615807...e-03])

<tt class="descclassname">colour.colorimetry.tristimulus.</tt><tt class="descname">wavelength_to_XYZ</tt><big>(</big>*args, **kwds<big>)</big>[source]¶

Converts given wavelength \(\lambda\) to CIE XYZ colourspace using
given colour matching functions.

If the wavelength \(\lambda\) is not available in the colour matching
function, its value will be calculated using CIE recommendations:
The method developed by Sprague (1880) should be used for interpolating
functions having a uniformly spaced independent variable and a
Cubic Spline method for non-uniformly spaced independent variable.

<col class="field-name" />
<col class="field-body" />

Parameters:

wavelength (numeric) – Wavelength \(\lambda\) in nm.

cmfs (XYZ_ColourMatchingFunctions, optional) – Standard observer colour matching functions.

Returns:
CIE XYZ colourspace matrix.

Return type:
ndarray, (3,)

Raises:
<tt class="xref py py-exc docutils literal">ValueError</tt> –
If wavelength \(\lambda\) is not in the colour matching
functions domain.

Notes

Output CIE XYZ colourspace matrix is in domain [0, 1].

If scipy is not unavailable the Cubic Spline method will
fallback to legacy Linear interpolation.

Examples

>>> from colour import CMFS
>>> cmfs = CMFS.get('CIE 1931 2 Degree Standard Observer')
>>> wavelength_to_XYZ(480)
array([ 0.09564  ,  0.13902  ,  0.812950...])

      Back to top

        © Copyright 2013 - 2014, Colour Developers.

      Created using Sphinx 1.2.2.


text:
'use strict';

const logger = require('../logger');

class TQTimer {

    constructor (id, fire_time, cb) {
        this.id = id;
        this.fire_time = fire_time;
        this.cb = cb;
    }

    cancel () {
        this.cb = null;
    }

}

class TimerQueue {

    constructor (interval) {
        const self = this;
        interval = interval || 1000;
        this.queue = [];
        this.interval_timer = setInterval(() => { self.fire(); }, interval);
    }

    add (id, ms, cb) {
        const fire_time = Date.now() + ms;

        const timer = new TQTimer(id, fire_time, cb);

        if ((this.queue.length === 0) ||
            fire_time >= this.queue[this.queue.length - 1].fire_time) {
            this.queue.push(timer);
            return timer;
        }

        for (let i=0; i < this.queue.length; i++) {
            if (this.queue[i].fire_time > fire_time) {
                this.queue.splice(i, 0, timer);
                return timer;
            }
        }

        throw "Should never get here";
    }

    discard (id) {
        for (let i = 0; i < this.queue.length; i++) {
            if (this.queue[i].id === id) {
                this.queue[i].cancel();
                return this.queue.splice(i, 1);
            }
        }

        throw `${id} not found`;
    }

    fire () {
        if (this.queue.length === 0) return;

        const now = Date.now();

        while (this.queue.length && this.queue[0].fire_time <= now) {
            const to_run = this.queue.shift();
            if (to_run.cb) to_run.cb();
        }
    }

    length () {
        return this.queue.length;
    }

    drain () {
        logger.logdebug("Draining " + this.queue.length + " items from the queue");
        while (this.queue.length) {
            const to_run = this.queue.shift();
            if (to_run.cb) to_run.cb();
        }
    }

    shutdown () {
        clearInterval(this.interval_timer);
    }
}

module.exports = TimerQueue;


text:
<!--
  Author:       Sam Ruby (http://intertwingly.net/) and Mark Pilgrim (http://diveintomark.org/)
  Copyright:    Copyright (c) 2003 Sam Ruby and Mark Pilgrim
-->

<!--
  Description:  entry link is required
  Expect:       MissingElement{parent:entry,element:updated}
-->

<feed xmlns="http://www.w3.org/2005/Atom">
<entry>
</entry>
</feed>


text:
package com.theoryinpractice.testng.referenceContributor;

import com.intellij.openapi.application.PluginPathManager;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.util.ui.UIUtil;
import org.testng.annotations.*;

/**
 * User: anna
 * Date: Sep 3, 2010
 */
@Test
public class TestNGDataProviderTest extends LightCodeInsightFixtureTestCase {
  @BeforeMethod
  @Override
  protected void setUp() throws Exception {
    super.setUp();
  }

  @AfterMethod
  @Override
  protected void tearDown() throws Exception {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          TestNGDataProviderTest.super.tearDown();
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  }

  @DataProvider
  public Object[][] data() {
    return new Object[][]{
       new Object[]{"private", new String[]{"data"}},
       new Object[]{"privateinsuper", new String[0]},
       new Object[]{"protectedinsuper", new String[]{"data"}},
       new Object[]{"privateindataproviderclass", new String[]{"data"}},
    };
  }

  public void testNothing(){}

  @Test(dataProvider = "data")
  public void test(final String path, final String... results) throws Throwable {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          myFixture.addClass("package org.testng.annotations; public @interface DataProvider {}");
          myFixture.addClass("package org.testng.annotations; public @interface Test {}");
          myFixture.testCompletionVariants(path + "provider.java", results);
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  }

  @Override
  protected String getBasePath() {
    return PluginPathManager.getPluginHomePathRelative("testng") + "/testData/references";
  }

}