text:
import re
import classad
import datetime
import unittest

class TestClassad(unittest.TestCase):

    def test_classad_constructor(self):
        ad = classad.ClassAd('[foo = "1"; bar = 2]')
        self.assertEquals(ad['foo'], "1")
        self.assertEquals(ad['bar'], 2)
        self.assertRaises(KeyError, ad.__getitem__, 'baz')

    def test_load_classad_from_file(self):
        ad = classad.parse(open("tests/test.ad"))
        self.assertEqual(ad["foo"], "bar")
        self.assertEqual(ad["baz"], classad.Value.Undefined)
        self.assertRaises(KeyError, ad.__getitem__, "bar")

    def new_ads_verify(self, ads):
        ads = list(ads)
        self.assertEqual(len(ads), 2)
        ad1, ad2 = ads
        self.assertEqual(ad1["foo"], "bar")
        self.assertEqual(ad1["baz"], classad.Value.Undefined)
        self.assertEqual(ad2["bar"], 1)
        self.assertEqual(len(ad1), 2)
        self.assertEqual(len(ad2), 1)
        self.assertRaises(KeyError, ad1.__getitem__, "bar")

    def old_ads_verify(self, ads):
        ads = list(ads)
        self.assertEqual(len(ads), 2)
        ad1, ad2 = ads
        self.assertEqual(ad1["MaxHosts"], 1)
        self.assertEqual(ad1["Managed"], "Schedd")
        self.assertEqual(ad2["User"], "bbockelm@users.opensciencegrid.org")
        self.assertEqual(ad2["SUBMIT_x509userproxy"], "/tmp/x509up_u1221")
        self.assertEqual(len(ad1), 2)
        self.assertEqual(len(ad2), 2)

    def test_load_classads(self):
        self.new_ads_verify(classad.parseAds(open("tests/test_multiple.ad")))
        self.new_ads_verify(classad.parseAds(open("tests/test_multiple.ad").read()))
        self.old_ads_verify(classad.parseOldAds(open("tests/test_multiple.old.ad")))
        self.old_ads_verify(classad.parseOldAds(open("tests/test_multiple.old.ad").read()))

    def test_old_classad(self):
        ad = classad.parseOld(open("tests/test.old.ad"))
        contents = open("tests/test.old.ad").read()
        keys = []
        for line in contents.splitlines():
            info = line.split(" = ")
            if len(info) != 2:
                continue
            self.assertTrue(info[0] in ad)
            self.assertEqual(ad.lookup(info[0]).__repr__(), info[1])
            keys.append(info[0])
        for key in ad:
            self.assertTrue(key in keys)

    def test_exprtree(self):
        ad = classad.ClassAd()
        ad["foo"] = classad.ExprTree("2+2")
        expr = ad["foo"]
        self.assertEqual(expr.__repr__(), "2 + 2")
        self.assertEqual(expr.eval(), 4)

    def test_exprtree_func(self):
        ad = classad.ClassAd()
        ad["foo"] = classad.ExprTree('regexps("foo (bar)", "foo bar", "\\\\1")')
        self.assertEqual(ad.eval("foo"), "bar")

    def test_ad_assignment(self):
        ad = classad.ClassAd()
        ad["foo"] = 2.1
        self.assertEqual(ad["foo"], 2.1)
        ad["foo"] = 2
        self.assertEqual(ad["foo"], 2)
        ad["foo"] = "bar"
        self.assertEqual(ad["foo"], "bar")
        self.assertRaises(TypeError, ad.__setitem__, {})

    def test_ad_refs(self):
        ad = classad.ClassAd()
        ad["foo"] = classad.ExprTree("bar + baz")
        ad["bar"] = 2.1
        ad["baz"] = 4
        self.assertEqual(ad["foo"].__repr__(), "bar + baz")
        self.assertEqual(ad.eval("foo"), 6.1)

    def test_ad_special_values(self):
        ad = classad.ClassAd()
        ad["foo"] = classad.ExprTree('regexp(12, 34)')
        ad["bar"] = classad.Value.Undefined
        self.assertEqual(ad["foo"].eval(), classad.Value.Error)
        self.assertNotEqual(ad["foo"].eval(), ad["bar"])
        self.assertEqual(classad.Value.Undefined, ad["bar"])

    def test_ad_iterator(self):
        ad = classad.ClassAd()
        ad["foo"] = 1
        ad["bar"] = 2
        self.assertEqual(len(ad), 2)
        self.assertEqual(len(list(ad)), 2)
        self.assertEqual(list(ad)[1], "foo")
        self.assertEqual(list(ad)[0], "bar")
        self.assertEqual(list(ad.items())[1][1], 1)
        self.assertEqual(list(ad.items())[0][1], 2)
        self.assertEqual(list(ad.values())[1], 1)
        self.assertEqual(list(ad.values())[0], 2)

    def test_ad_lookup(self):
        ad = classad.ClassAd()
        ad["foo"] = classad.Value.Error
        self.assertTrue(isinstance(ad.lookup("foo"), classad.ExprTree))
        self.assertEquals(ad.lookup("foo").eval(), classad.Value.Error)

    def test_get(self):
        ad = classad.ClassAd()
        self.assertEquals(ad.get("foo"), None)
        self.assertEquals(ad.get("foo", "bar"), "bar")
        ad["foo"] = "baz"
        self.assertEquals(ad.get("foo"), "baz")
        self.assertEquals(ad.get("foo", "bar"), "baz")

    def test_setdefault(self):
        ad = classad.ClassAd()
        self.assertEquals(ad.setdefault("foo", "bar"), "bar")
        self.assertEquals(ad.get("foo"), "bar")
        ad["bar"] = "baz"
        self.assertEquals(ad.setdefault("bar", "foo"), "baz")

    def test_update(self):
        ad = classad.ClassAd()
        ad.update({"1": 2})
        self.assertTrue("1" in ad)
        self.assertEquals(ad["1"], 2)
        ad.update([("1",3)])
        self.assertEquals(ad["1"], 3)
        other = classad.ClassAd({"3": "5"})
        ad.update(other)
        del other
        self.assertTrue("3" in ad)
        self.assertEquals(ad["3"], "5")

    def test_invalid_ref(self):
        expr = classad.ExprTree("foo")
        self.assertEquals(classad.Value.Undefined, expr.eval())

    def test_temp_scope(self):
        expr = classad.ExprTree("foo")
        self.assertEquals("bar", expr.eval({"foo": "bar"}))
        ad = classad.ClassAd({"foo": "baz", "test": classad.ExprTree("foo")})
        expr = ad["test"]
        self.assertEquals("baz", expr.eval())
        self.assertEquals("bar", expr.eval({"foo": "bar"}))
        self.assertEquals("bar", expr.eval({"foo": "bar"}))
        self.assertEquals("baz", expr.eval())

    def test_abstime(self):
        expr = classad.ExprTree('absTime("2013-09-12T07:50:23")')
        dt = expr.eval()
        self.assertTrue(isinstance(dt, datetime.datetime))
        self.assertEquals(dt.year, 2013)
        self.assertEquals(dt.month, 9)
        self.assertEquals(dt.day, 12)
        self.assertEquals(dt.hour, 7)
        self.assertEquals(dt.minute, 50)
        self.assertEquals(dt.second, 23)

        ad = classad.ClassAd({"foo": dt})
        dt2 = ad["foo"]
        self.assertTrue(isinstance(dt2, datetime.datetime))
        self.assertEquals(dt, dt2)

        ad = classad.ClassAd({"foo": datetime.datetime.now()});
        td = (datetime.datetime.now()-ad["foo"])
        self.assertEquals(td.days, 0)
        self.assertTrue(td.seconds < 300)

    def test_reltime(self):
        expr = classad.ExprTree('relTime(5)')
        self.assertEquals(expr.eval(), 5)

    def test_quote(self):
        self.assertEquals(classad.quote("foo"), '"foo"')
        self.assertEquals(classad.quote('"foo'), '"\\"foo"')
        for i in ["foo", '"foo', '"\\"foo']:
            self.assertEquals(i, classad.unquote(classad.quote(i)))

    def test_literal(self):
        self.assertEquals(classad.ExprTree('"foo"'), classad.Literal("foo"))
        self.assertEquals(classad.Literal(1).eval(), 1)

    def test_operator(self):
        expr = classad.Literal(1) + 2
        self.assertTrue(isinstance(expr, classad.ExprTree))
        self.assertTrue(expr)
        self.assertTrue(expr.sameAs(classad.ExprTree('1 + 2')))
        expr = classad.Literal(1) & 2
        self.assertTrue(isinstance(expr, classad.ExprTree))
        self.assertEquals(expr.eval(), 0)
        self.assertTrue(expr.sameAs(classad.ExprTree('1 & 2')))
        expr = classad.Attribute("foo").is_(classad.Value.Undefined)
        self.assertTrue(expr.eval())
        ad = classad.ClassAd("[foo = 1]")
        expr = classad.Attribute("foo").isnt_(classad.Value.Undefined)
        self.assertTrue(expr.eval(ad))
        expr = classad.Literal(1).and_( classad.Literal(2) )
        self.assertRaises(RuntimeError, bool, expr)

    def test_subscript(self):
        ad = classad.ClassAd({'foo': [0,1,2,3]})
        expr = classad.Attribute("foo")[2]
        self.assertTrue(isinstance(expr, classad.ExprTree))
        self.assertEquals(expr.eval(), classad.Value.Undefined)
        self.assertEquals(expr.eval(ad), 2)

    def test_function(self):
        expr = classad.Function("strcat", "hello", " ", "world")
        self.assertTrue(isinstance(expr, classad.ExprTree))
        self.assertEquals(expr.eval(), "hello world")
        expr = classad.Function("regexp", ".*")
        self.assertEquals(expr.eval(), classad.Value.Error)

    def test_flatten(self):
        expr = classad.Attribute("foo") == classad.Attribute("bar")
        ad = classad.ClassAd({"bar": 1})
        self.assertTrue(ad.flatten(expr).sameAs( classad.ExprTree('foo == 1') ))

    def test_matches(self):
        left = classad.ClassAd('[requirements = other.foo == 3; bar=1]')
        right = classad.ClassAd('[foo = 3]')
        right2 = classad.ClassAd('[foo = 3; requirements = other.bar == 1;]')
        self.assertFalse(left.matches(right))
        self.assertTrue(right.matches(left))
        self.assertFalse(right.symmetricMatch(left))
        self.assertTrue(left.matches(right2))
        self.assertTrue(right2.symmetricMatch(left))

    def test_bool(self):
        self.assertTrue(bool( classad.ExprTree('true || false') ))
        self.assertTrue(bool( classad.Literal(True).or_(False) ))
        self.assertFalse(bool( classad.ExprTree('true && false') ))
        self.assertFalse(bool( classad.Literal(True).and_(False) ))

if __name__ == '__main__':
    unittest.main()


text:
using System;

namespace Azure.ResourceManager.DataProtectionBackup.Models
{
    /// <summary> Delete option with duration. </summary>
    public partial class DataProtectionBackupAbsoluteDeleteSetting : DataProtectionBackupDeleteSetting
    {
        /// <summary> Initializes a new instance of DataProtectionBackupAbsoluteDeleteSetting. </summary>
        /// <param name="duration"> Duration of deletion after given timespan. </param>
        public DataProtectionBackupAbsoluteDeleteSetting(TimeSpan duration) : base(duration)
        {
            ObjectType = "AbsoluteDeleteOption";
        }

        /// <summary> Initializes a new instance of DataProtectionBackupAbsoluteDeleteSetting. </summary>
        /// <param name="duration"> Duration of deletion after given timespan. </param>
        /// <param name="objectType"> Type of the specific object - used for deserializing. </param>
        internal DataProtectionBackupAbsoluteDeleteSetting(TimeSpan duration, string objectType) : base(duration, objectType)
        {
            ObjectType = objectType ?? "AbsoluteDeleteOption";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRProvenance;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRProvenance\FHIRProvenanceEntity;

/**
 * Class FHIRProvenanceEntityTest
 * @package \DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRProvenance
 */
class FHIRProvenanceEntityTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRProvenanceEntity();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRProvenance\FHIRProvenanceEntity', $type);
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.plugins.git.GitSCM" plugin="git@3.7.0">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>{insert-repository-url}</url>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>*/master</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
    <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
    <submoduleCfg class="list"/>
    <extensions/>
  </scm>
  <assignedNode>{insert-aci-container}</assignedNode>
  <canRoam>false</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers>
    <hudson.triggers.SCMTrigger>
      <spec>* * * * *</spec>
      <ignorePostCommitHooks>false</ignorePostCommitHooks>
    </hudson.triggers.SCMTrigger>
  </triggers>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Maven>
      <targets>package</targets>
      <pom>jenkins-cicd-webapp/pom.xml</pom>
      <usePrivateRepository>false</usePrivateRepository>
      <settings class="jenkins.mvn.DefaultSettingsProvider"/>
      <globalSettings class="jenkins.mvn.DefaultGlobalSettingsProvider"/>
      <injectBuildVariables>false</injectBuildVariables>
    </hudson.tasks.Maven>
    <hudson.tasks.Shell>
      <command>cd "${WORKSPACE}"
mv jenkins-cicd-webapp/target/helloworld*.war ROOT.war</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers>
    <com.microsoftopentechnologies.windowsazurestorage.WAStoragePublisher plugin="windows-azure-storage@0.3.7">
      <storageType>blobstorage</storageType>
      <containerName>builds</containerName>
      <fileShareName></fileShareName>
      <blobProperties>
        <cacheControl></cacheControl>
        <contentEncoding></contentEncoding>
        <contentLanguage></contentLanguage>
        <contentType></contentType>
        <detectContentType>true</detectContentType>
      </blobProperties>
      <pubAccessible>false</pubAccessible>
      <cleanUpContainerOrShare>false</cleanUpContainerOrShare>
      <allowAnonymousAccess>false</allowAnonymousAccess>
      <uploadArtifactsOnlyIfSuccessful>true</uploadArtifactsOnlyIfSuccessful>
      <doNotFailIfArchivingReturnsNothing>false</doNotFailIfArchivingReturnsNothing>
      <uploadZips>false</uploadZips>
      <doNotUploadIndividualFiles>false</doNotUploadIndividualFiles>
      <filesPath>*.war</filesPath>
      <excludeFilesPath></excludeFilesPath>
      <virtualPath>${BUILD_ID}/</virtualPath>
      <doNotWaitForPreviousBuild>false</doNotWaitForPreviousBuild>
      <storageCredentialId>{insert-credentials-storage-id}</storageCredentialId>
    </com.microsoftopentechnologies.windowsazurestorage.WAStoragePublisher>
    <com.microsoft.jenkins.appservice.WebAppDeploymentRecorder plugin="azure-app-service@0.2.0">
      <azureCredentialsId>{insert-credentials-sp-id}</azureCredentialsId>
      <resourceGroup>{insert-resourcegroup-name}</resourceGroup>
      <appName>{insert-webapp-name}</appName>
      <filePath>*.war</filePath>
      <sourceDirectory></sourceDirectory>
      <targetDirectory>webapps</targetDirectory>
      <deployOnlyIfSuccessful>true</deployOnlyIfSuccessful>
      <publishType>file</publishType>
      <dockerImageName></dockerImageName>
      <dockerImageTag></dockerImageTag>
      <dockerFilePath>**/Dockerfile</dockerFilePath>
      <dockerRegistryEndpoint plugin="docker-commons@1.11"/>
      <deleteTempImage>true</deleteTempImage>
      <slotName></slotName>
    </com.microsoft.jenkins.appservice.WebAppDeploymentRecorder>
  </publishers>
  <buildWrappers/>
</project>


text:
"""
This module provides a wx.Window that hosts ActiveX Controls using
just the ctypes and comtypes packages.  This provides a light-weight
COM implementation with full dynamic dispatch support.

The only requirements are ctypes (included with Python 2.5 and
available separately for earlier versions of Python) and the comtypes
package, which is available from
http://starship.python.net/crew/theller/comtypes/.  Be sure to get at
least version 0.5, which at the time of this writing is only available
from SVN.  You can fetch it with easy_install with a command like
this:

    easy_install http://svn.python.org/projects/ctypes/trunk/comtypes

"""

import wx

import ctypes as ct
import ctypes.wintypes as wt
import comtypes
import comtypes.client as cc
import comtypes.hresult as hr

import sys, os

try:
    if not hasattr(sys, 'frozen'):
        f = os.path.join(os.path.dirname(__file__), 'myole4ax.tlb')
        cc.GetModule(f)
    from comtypes.gen import myole4ax
except Exception:
    import traceback
    traceback.print_exc()
    myole4ax = None

kernel32 = ct.windll.kernel32
user32 = ct.windll.user32
atl = ct.windll.atl

WS_CHILD    = 0x40000000
WS_VISIBLE    = 0x10000000
WS_CLIPCHILDREN = 0x2000000
WS_CLIPSIBLINGS = 0x4000000
CW_USEDEFAULT   = 0x80000000
WM_KEYDOWN      = 256
WM_DESTROY      = 2

#------------------------------------------------------------------------------

class ActiveXCtrl(wx.AxBaseWindow):
    """
    A wx.Window for hosting ActiveX controls.  The COM interface of
    the ActiveX control is accessible through the ctrl property of
    this class, and this class is also set as the event sink for COM
    events originating from the ActiveX control.  In other words, to
    catch the COM events you mearly have to derive from this class and
    provide a method with the correct name.  See the comtypes package
    documentation for more details.
    """

    def __init__(self, parent, axID, wxid=-1, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, name="activeXCtrl"):
        """
        All parameters are like those used in normal wx.Windows with
        the addition of axID which is a string that is either a ProgID
        or a CLSID used to identify the ActiveX control.
        """

        x = pos.x
        y = pos.y
        if x == -1: x = CW_USEDEFAULT
        if y == -1: y = 20
        w = size.width
        h = size.height
        if w == -1: w = 20
        if h == -1: h = 20

        # create the control
        atl.AtlAxWinInit()
        hInstance = kernel32.GetModuleHandleA(None)
        hwnd = user32.CreateWindowExA(0, "AtlAxWin", axID,
                                      WS_CHILD | WS_VISIBLE
                                      | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
                                      x,y, w,h, parent.GetHandle(), None,
                                      hInstance, 0)
        assert hwnd != 0

        # get the Interface for the Ax control
        unknown = ct.POINTER(comtypes.IUnknown)()
        res = atl.AtlAxGetControl(hwnd, ct.byref(unknown))
        assert res == hr.S_OK
        self._ax = cc.GetBestInterface(unknown)

        # Fetch the interface for IOleInPlaceActiveObject. We'll use this
        # later to call its TranslateAccelerator method so the AX Control can
        # deal with things like tab traversal and such within itself.
        IOleInPlaceActiveObject = getattr(myole4ax, 'IOleInPlaceActiveObject', None)
        if IOleInPlaceActiveObject is not None:
            self.ipao = self._ax.QueryInterface(myole4ax.IOleInPlaceActiveObject)
        else:
            self.ipao = None

        # Use this object as the event sink for the ActiveX events
        self._evt_connections = []
        self.AddEventSink(self)

        # Turn the window handle into a wx.Window and set this object to be that window
        #win = wx.AxBaseWindow_FromHWND(parent, hwnd)
        #self.PostCreate(win)
        wx.AxBaseWindow.__init__(self, parent, hwnd)

        # Set some wx.Window properties
        if wxid == wx.ID_ANY:
            wxid = wx.Window.NewControlId()
        self.SetId(wxid)
        self.SetName(name)
        self.SetMinSize(size)

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroyWindow)

    def AddEventSink(self, sink, interface=None):
        """
        Add a new target to search for method names that match the COM
        Event names.
        """
        self._evt_connections.append(cc.GetEvents(self._ax, sink, interface))

    def GetCtrl(self):
        """Easy access to the COM interface for the ActiveX Control"""
        return self._ax
    # And an even easier property
    ctrl = property(GetCtrl)

    def MSWTranslateMessage(self, msg):
        #  Pass any WM_KEYDOWN messages to the IOleInPlaceActiveObject
        #  interface so navigation keys will be able to be processed
        #  by the AX control.  MSWTranslateMessage is called before
        #  wxWidgets handles and eats the navigation keys itself.
        m = wt.MSG.from_address(msg)
        if self.ipao is not None and m.message == WM_KEYDOWN:
            # This should take the MSG object, but the COM interface I used
            # was hacked to just use a long...
            res = self.ipao.TranslateAccelerator(msg)
            return res == hr.S_OK
        return wx.AxBaseWindow.MSWTranslateMessage(self, msg)

    # TBD: Are the focus handlers needed?
    def OnSetFocus(self, evt):
        if self.ipao is not None:
            self.ipao.OnFrameWindowActivate(True)

    def OnKillFocus(self, evt):
        if self.ipao is not None:
            self.ipao.OnFrameWindowActivate(False)

    def OnDestroyWindow(self, evt):
        # release our event sinks while the window still exists
        self._evt_connections = None


text:
<?php

namespace TreeHouse\BehatCommon;

use Behat\MinkExtension\Context\RawMinkContext;
use PHPUnit\Framework\Assert;

class FormContext extends RawMinkContext
{
    /**
     * @var string
     */
    private $fieldContainerClass;

    /**
     * @param string $field_container_class
     */
    public function __construct($field_container_class = 'controls')
    {
        $this->fieldContainerClass = $field_container_class;
    }

    /**
     * @Then the field :name should have an error containing :message
     */
    public function theFieldShouldHaveAnErrorContaining($name, $message)
    {
        $field = $this->assertSession()->fieldExists($name);
        $parent = $field->getParent();

        if (false === stripos($parent->getAttribute('class'), $this->fieldContainerClass)) {
            $parent = $parent->getParent();
        }

        Assert::assertContains($message, $parent->getText());
    }

    /**
     * @Then the field :name should not have an error containing :message
     */
    public function theFieldShouldNotHaveAnErrorContaining($name, $message)
    {
        $field = $this->assertSession()->fieldExists($name);
        $parent = $field->getParent();

        if (false === stripos($parent->getAttribute('class'), $this->fieldContainerClass)) {
            $parent = $parent->getParent();
        }

        Assert::assertNotContains($message, $parent->getText());
    }

    /**
     * @When I fill in the :element element with :value
     */
    public function fillElement($element, $value)
    {
        $field = $this->assertSession()->elementExists('css', $element);
        $field->setValue($value);
    }
}


text:
package im.bci.jnuit.lwjgl.controls;

import org.lwjgl.glfw.GLFW;

import im.bci.jnuit.controls.Control;

public class GamepadButtonControl extends AbstractGamepadControl implements Control {

    private final int button;

    public GamepadButtonControl(int pad, int button, String name) {
        super(pad, name);
        this.button = button;
    }

    @Override
    public float getDeadZone() {
        return 0.1f;
    }

    @Override
    public float getValue() {
        GLFW.glfwGetGamepadState(pad, states[pad]);
        return GLFW.GLFW_PRESS == states[pad].buttons(button) ? 1f : 0f;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + button;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        GamepadButtonControl other = (GamepadButtonControl) obj;
        if (button != other.button)
            return false;
        return true;
    }

}


text:
package com.zxy.commons.memcache;

import java.util.List;
import java.util.Map;

import com.zxy.commons.lang.exception.DatasAccessException;

import net.rubyeye.xmemcached.MemcachedClient;

/**
 * Memcached客户端操作工具类
 *
 *

 * View Source
 *
 * @author zhaoxunyong@qq.com
 * @version 1.0
 * @since 1.0
 */
public abstract class AbstractMemcacheClient {

    protected abstract MemcachedClient getClient();

    /**
     * set value
     *
     * @param key key
     * @param value value
     */
    public void set(String key, Object value) {
        set(key, 0, value);
    }

    /**
     * set value
     *
     * @param key key
     * @param exp 过期时间,单位:秒
     * @param value value
     */
    public void set(String key, int exp, Object value) {
        try {
            getClient().set(key, exp, value);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * Append value
     *
     * @param key key
     * @param value value
     */
    public void append(String key, Object value) {
        try {
            getClient().append(key, value);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * Append value
     *
     * @param key key
     * @param timeout 超时时间,单位:秒
     * @param value value
     */
    public void append(String key, int timeout, Object value) {
        try {
            getClient().append(key, value, timeout);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * add value
     *
     * @param key key
     * @param value value
     */
    public void add(String key, Object value) {
        add(key, 0, value);
    }

    /**
     * add value
     *
     * @param key key
     * @param exp 过期时间,单位:秒
     * @param value value
     */
    public void add(String key, int exp, Object value) {
        try {
            getClient().add(key, exp, value);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * get value
     *
     * @param <T> This is a type parameter
     * @param key key
     * @return value
     */
    public <T> T get(String key) {
        try {
            return getClient().get(key);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * delete key
     *
     * @param key key
     */
    public void delete(String key) {
        try {
            getClient().delete(key);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * incr value
     *
     * @param key key
     * @param value value
     * @return incr后的值
     */
    public long incr(String key, long value) {
        try {
            return getClient().incr(key, value);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * incr value
     *
     * @param key key
     * @param delta increment delta
     * @param initValue the initial value to be added when value is not found
     * @param exp the initial vlaue expire time, in seconds. Can be up to 30
     *            days. After 30 days, is treated as a unix timestamp of an
     *            exact date.
     * @return incr后的值
     */
    public long incr(String key, long delta, long initValue, int exp) {
        try {
            return getClient().incr(key, delta, initValue, getClient().getOpTimeout(), exp);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * decr value
     *
     * @param key key
     * @param value value
     * @return decr后的值
     */
    public long decr(String key, long value) {
        try {
            return getClient().decr(key, value);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }

    /**
     * 批量获取数据
     *
     * @param <T> This is a type parameter
     * @param keys keys
     * @return values
     */
    public <T> Map<String, T> getBatch(List<String> keys) {
        try {
            return getClient().get(keys);
        } catch (Exception e) {
            throw new DatasAccessException(e.getMessage(), e);
        }
    }
}


text:
Documentation 1.0.0: https://rogi29.github.io/webguru-calendar/docs/

Webguru-calendar is an easy to use and flexible datepicker that fully utilize both `pickmeup` and `MomentJS` functionality.

#### Example Instantiation

```js
//Instantiating Calendar Object
var twoCalendars = new Calendar('#calendars', {format: 'DD-MM-YY'});
```

#### Example On Render (using: MomentJS)

```js
//Render event (using: MomentJS)
var today = moment(new Date());

twoCalendars.onRender(function(date) {
    if (today.isAfter(date.unparsed))
        return {disabled : true, class_name : 'date-history'};

    return {};
});
```

#### Example Initialization

```js
//Initializing the calendar
twoCalendars.initialise(new Date());
```


text:
import sys, signal, commands

DEFAULT_TIMEOUT = 5.0

class TimeoutException(Exception):
    """A timeout has occurred."""
    pass

class call_with_timeout:
    def __init__(self, function, timeout=DEFAULT_TIMEOUT):
        self.timeout = timeout
        self.function = function

    def handler(self, signum, frame):
        raise TimeoutException()

    def __call__(self, *args):
        # get the old SIGALRM handler
        old = signal.signal(signal.SIGALRM, self.handler)
        # set the alarm
        signal.setitimer(signal.ITIMER_REAL, self.timeout)
        try:
            result = self.function(*args)
        finally:
            # restore existing SIGALRM handler
            signal.signal(signal.SIGALRM, old)
        signal.setitimer(signal.ITIMER_REAL, 0)
        return result

def timeout(timeout):
    """This decorator takes a timeout parameter in seconds."""
    def wrap_function(function):
        return call_with_timeout(function, timeout)
    return wrap_function

def default_timeout(function):
    """This simple decorator 'timesout' after DEFAULT_TIMEOUT seconds."""
    return call_with_timeout(function)

def getstatusoutput(command, timeout=DEFAULT_TIMEOUT):
    """This is a timeout wrapper aroung getstatusoutput."""
    _gso = call_with_timeout(commands.getstatusoutput, timeout)
    try:
        return _gso(command)
    except TimeoutException, e:
        return (-1, "The command '%s' timed-out after %i seconds." % (command, timeout))


text:
meta-title: Tocome
title: Tocome
layout: blank
---
<!doctype html>

  <meta charset="utf-8" />
  <title>The European Bioinformatics Institute < EMBL-EBI</title>
  <meta name="description" content="EMBL-EBI Search result boilerplate page" />
  <meta name="keywords" content="bioinformatics, europe, institute" />
  <meta name="author" content="EMBL-EBI" />
  <meta name="HandheldFriendly" content="true" />
  <meta name="MobileOptimized" content="width" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="theme-color" content="#70BDBD" />

  <meta name="ebi:owner" content="John Doe" />
  <meta name="ebi:review-cycle" content="30" />
  <meta name="ebi:last-review" content="2015-12-20" />
  <meta name="ebi:expiry" content="2016-01-20" />

  <link rel="dns-prefetch" href="//embl.de" />

  <link rel="icon" type="image/x-icon" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/favicon.ico" />
  <link rel="icon" type="image/png" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/favicon-32x32.png" />
  <link rel="icon" type="image/png" sizes="192x192" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/android-chrome-192x192.png" />
  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/apple-icon-114x114.png" />
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/apple-icon-72x72.png" />
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/apple-icon-144x144.png" />
  <link rel="apple-touch-icon-precomposed" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/apple-icon-57x57.png" />
  <link rel="mask-icon" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/safari-pinned-tab.svg" color="#ffffff" />
  <meta name="msapplication-TileColor" content="#2b5797" />
  <meta name="msapplication-TileImage" content="//ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/images/logos/EMBL-EBI/favicons/mstile-144x144.png" />

  <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/css/ebi-global.css" type="text/css" media="all" />
  <link rel="stylesheet" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Icon-fonts/v1.2/fonts.css" type="text/css" media="all" />

  <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.3/css/theme-embl-petrol.css" type="text/css" media="all" />

    Skip to main content

            Optional title

          <form id="ebi_search" action="/ebisearch/search.ebi">
            <fieldset>

                <input id="query" class="input-group-field" title="EB-eye Search" tabindex="1" type="text" name="query" value="" size="35" maxlength="2048" placeholder="Search service" />

                  <input id="search_submit" class="button icon icon-functional" tabindex="2" type="submit" name="submit1" value="1" />
                  <input id="allebi" type="hidden" name="db" value="allebi" checked="checked" />
                  <input type="hidden" name="requestFrom" value="ebi_index" />

            </fieldset>

          </form>

Overview

Download

Support

 Login

EBI Framework

Sample pages

              Current:  Search results boilerplate

Search results

Showing X results from a total of Y (page 1 of 13). You can also use the advanced search.

Your results go here in whatever format is most suitable: list, table, tiled images... etc

You may wish to precede them with pagination and details of which page out of how many this is.

Previous page

You're on page 1

2

3

4

12

13

Next page

                <legend>
Sub-categories
</legend>

Facet One

Facet Two

Sub-facets

Sub-facet One

Sub-facet Two

Sub-facet Three

Sub-facet Four

Facet Three

Facet Four

                <legend>
Facets
</legend>

<input id="checkbox12" type="checkbox">Multi-filter 1

<input id="checkbox13" type="checkbox">Multi-filter 2

<input id="checkbox14" type="checkbox">Multi-filter 3

<input id="checkbox15" type="checkbox">Multi-filter 4

                <legend>
Binary facets
</legend>

<input id="radio12" name="binary" type="radio">Single-filter 1

<input id="radio13" name="binary" type="radio">Single-filter 2

<input id="radio14" name="binary" type="radio">Single-filter 3

<input id="radio15" name="binary" type="radio">Single-filter 4

Right sidebar

This is a sample item with a vertical menu.

Sample link

Sample link

Active link

Sample link

    {{> footer_global}}


text:
package com.google.cloud.spring.data.spanner.core.mapping.event;

import com.google.cloud.spanner.Statement;
import org.springframework.context.ApplicationEvent;

/** An event holding a DML statement. */
public class ExecuteDmlEvent extends ApplicationEvent {

  /**
   * Constructor.
   *
   * @param statement the DML statement which is (never {@code null})
   */
  public ExecuteDmlEvent(Statement statement) {
    super(statement);
  }

  /**
   * Get the DML statement.
   *
   * @return the DML statement.
   */
  public Statement getStatement() {
    return (Statement) getSource();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ExecuteDmlEvent that = (ExecuteDmlEvent) o;
    return getStatement().equals(that.getStatement());
  }

  @Override
  public int hashCode() {
    return getStatement().hashCode();
  }
}


text:
<?
$page->title('Preferences')
     ->navbar_image('preferences')
     ->header('Preferences')
     ->breadcrumb_home();

$page->content_begin(); ?>

Use the up and down links to customize the order of icons on your homepage. Use the checkboxes to toggle visibility. Changes are automatically saved, but you may need to manually refresh your homepage after you're finished here.

<? $index = 0;
   foreach($menu as $item) { ?>

		  	<? if($item['toggle_url']) { ?><a href="<?=$item['toggle_url']?>"><?=$check_imgs[$item['status']]?><? } ?>
		  	<?=Modules::title($item['name'])?>
		  	<? if($item['swap_up_url']) { ?><a href="<?=$item['swap_up_url']?>"><?=$up_img?><? } else {?><?=$spacer?><? } ?>
		  	<? if($item['swap_down_url']) { ?><a href="<?=$item['swap_down_url']?>"><?=$down_img?><? } ?>

<? } ?>

			Return to home

<? $page->content_end(); ?>


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="27dp"
        android:layout_marginTop="7dp"
        android:background="@drawable/newmsg_divider">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:layout_marginRight="10dp"
            android:paddingTop="2dp"
            android:src="@drawable/ic_ab_new" />

        <TextView
            android:id="@+id/chat_message_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="1dp"
            android:textColor="#4a7297"
            android:textSize="14dp" />

    </FrameLayout>

</FrameLayout>


text:
layout: default
permalink: /categories/javascript
---

{% include components/categories.html %}

{%
	include components/category-title.html
	category="JavaScript"
	icon="js"
	text="All articles on JavaScript, ES6 and tips and tricks"
%}

<div class="posts">
	{% for post in site.posts %}
		{% if post.tag == 'js' %}
			{% include components/post-card.html %}
		{% endif %}
  {% endfor %}
</div>


text:
//=============================================================================================================

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "dummytoolbox.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace DUMMYTOOLBOXPLUGIN;
using namespace SCSHAREDLIB;
using namespace SCMEASLIB;
using namespace UTILSLIB;
using namespace Eigen;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

DummyToolbox::DummyToolbox()
: m_pCircularBuffer(QSharedPointer<CircularBuffer_Matrix_double>(new CircularBuffer_Matrix_double(40)))
{
}

//=============================================================================================================

DummyToolbox::~DummyToolbox()
{
    if(this->isRunning()) {
        stop();
    }
}

//=============================================================================================================

QSharedPointer<AbstractPlugin> DummyToolbox::clone() const
{
    QSharedPointer<DummyToolbox> pClone(new DummyToolbox);
    return pClone;
}

//=============================================================================================================

void DummyToolbox::init()
{
    // Input
    m_pInput = PluginInputData<RealTimeMultiSampleArray>::create(this, "DummyIn", "Dummy input data");
    connect(m_pInput.data(), &PluginInputConnector::notify,
            this, &DummyToolbox::update, Qt::DirectConnection);
    m_inputConnectors.append(m_pInput);

    // Output - Uncomment this if you don't want to send processed data (in form of a matrix) to other plugins.
    // Also, this output stream will generate an online display in your plugin
    m_pOutput = PluginOutputData<RealTimeMultiSampleArray>::create(this, "DummyOut", "Dummy output data");
    m_pOutput->measurementData()->setName(this->getName());
    m_outputConnectors.append(m_pOutput);
}

//=============================================================================================================

void DummyToolbox::unload()
{
}

//=============================================================================================================

bool DummyToolbox::start()
{
    //Start thread
    QThread::start();

    return true;
}

//=============================================================================================================

bool DummyToolbox::stop()
{
    requestInterruption();
    wait(500);

    // Clear all data in the buffer connected to displays and other plugins
    m_pOutput->measurementData()->clear();
    m_pCircularBuffer->clear();

    m_bPluginControlWidgetsInit = false;

    return true;
}

//=============================================================================================================

AbstractPlugin::PluginType DummyToolbox::getType() const
{
    return _IAlgorithm;
}

//=============================================================================================================

QString DummyToolbox::getName() const
{
    return "Dummy Toolbox";
}

//=============================================================================================================

QWidget* DummyToolbox::setupWidget()
{
    DummySetupWidget* setupWidget = new DummySetupWidget(this);
    return setupWidget;
}

//=============================================================================================================

void DummyToolbox::update(SCMEASLIB::Measurement::SPtr pMeasurement)
{
    if(QSharedPointer<RealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<RealTimeMultiSampleArray>()) {
        //Fiff information
        if(!m_pFiffInfo) {
            m_pFiffInfo = pRTMSA->info();

            m_pOutput->measurementData()->initFromFiffInfo(m_pFiffInfo);
            m_pOutput->measurementData()->setMultiArraySize(1);
        }

        if(!m_bPluginControlWidgetsInit) {
            initPluginControlWidgets();
        }

        for(unsigned char i = 0; i < pRTMSA->getMultiArraySize(); ++i) {
            // Please note that we do not need a copy here since this function will block until
            // the buffer accepts new data again. Hence, the data is not deleted in the actual
            // Mesaurement function after it emitted the notify signal.
            while(!m_pCircularBuffer->push(pRTMSA->getMultiSampleArray()[i])) {
                //Do nothing until the circular buffer is ready to accept new data again
            }
        }
    }
}

//=============================================================================================================

void DummyToolbox::initPluginControlWidgets()
{
    if(m_pFiffInfo) {
        QList<QWidget*> plControlWidgets;

        // The plugin's control widget
        DummyYourWidget* pYourWidget = new DummyYourWidget(QString("MNESCAN/%1").arg(this->getName()));
        pYourWidget->setObjectName("group_tab_Settings_Your Widget");

        plControlWidgets.append(pYourWidget);

        emit pluginControlWidgetsChanged(plControlWidgets, this->getName());

        m_bPluginControlWidgetsInit = true;
    }
}

//=============================================================================================================

void DummyToolbox::run()
{
    MatrixXd matData;

    // Wait for Fiff Info
    while(!m_pFiffInfo) {
        msleep(10);
    }

    while(!isInterruptionRequested()) {
        // Get the current data
        if(m_pCircularBuffer->pop(matData)) {
            //ToDo: Implement your algorithm here

            //Send the data to the connected plugins and the online display
            //Unocmment this if you also uncommented the m_pOutput in the constructor above
            if(!isInterruptionRequested()) {
                m_pOutput->measurementData()->setValue(matData);
            }
        }
    }
}


text:
def possible_solution?(array)
  sum = 0
  array.each.with_index do |elem, index|
    next  if elem.zero?
    break if index + 1 > array.size
    array[index + 1, array.size].each do |ee|
      next if ee.zero?
      sum += 1 if elem > ee
    end
  end
  sum.even?
end


text:
require 'rubygems'
require 'net/dns'

module Reedland
	module Command
		class Host
			def self.run(address)
				regular = Net::DNS::Resolver.start address.join(" ")
				mx = Net::DNS::Resolver.new.search(address.join(" "), Net::DNS::MX)

				return "#{regular}\n#{mx}"
			end
		end
	end
end


text:
#include "tensorflow/core/grappler/utils/functions.h"

#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/substitute.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/strings/scanner.h"

namespace tensorflow {
namespace grappler {

namespace {

Status RegisterFunctionBodyOutputs(const OpRegistrationData& registration,
                                   const NodeDef& node,
                                   GrapplerFunctionConnectivity* connectivity) {
  tensorflow::NameRangeMap outputs_range_map;
  TF_RETURN_IF_ERROR(tensorflow::NameRangesForNode(
      node, registration.op_def, nullptr, &outputs_range_map));
  connectivity->RegisterFunctionBodyOutputs(node.name(),
                                            std::move(outputs_range_map));
  return Status::OK();
}

Status RegisterFunctionBodyOutputs(const FunctionLibraryDefinition& flib,
                                   const NodeDef& node,
                                   GrapplerFunctionConnectivity* connectivity) {
  const OpRegistrationData* registration;
  TF_RETURN_IF_ERROR(flib.LookUp(node.op(), &registration));
  return RegisterFunctionBodyOutputs(*registration, node, connectivity);
}

// Replace the placeholder attribute values with the values specified in
// instantiation attributes.
Status ResolveFunctionBodyNodeAttrPlaceholders(
    const AttrSlice& func_instantiation_attr, NodeDef* node) {
  for (auto& attr : *node->mutable_attr()) {
    const string& placeholder = attr.second.placeholder();
    if (placeholder.empty()) continue;

    const AttrValue* attr_value = func_instantiation_attr.Find(placeholder);
    if (attr_value) {
      attr.second = *attr_value;
    } else {
      return errors::InvalidArgument("Can't resolve placeholder: ",
                                     placeholder);
    }
  }
  return Status::OK();
}

}  // namespace

void GrapplerFunctionConnectivity::RegisterInputArgExpansion(
    InputArgExpansion input_arg_expansion) {
  string input_name = input_arg_expansion.input_name;
  const auto& placeholders = input_arg_expansion.placeholders;

  for (int i = 0; i < placeholders.size(); ++i) {
    const string& placeholder = input_arg_expansion.placeholders[i];
    input_arg_placeholders_.insert(
        {placeholder, InputArgPlaceholder{input_name, /*input_index=*/i}});
  }
  input_arg_expansions_.insert(
      {std::move(input_name), std::move(input_arg_expansion)});
}

void GrapplerFunctionConnectivity::RegisterFunctionBodyOutputs(
    const string& node_name, tensorflow::NameRangeMap&& outputs) {
  function_body_outputs_[node_name] = std::move(outputs);
}

Status GrapplerFunctionConnectivity::ExpandFunctionDefInput(
    const string& func_def_input, std::vector<string>* graph_def_inputs) const {
  using ::tensorflow::strings::Scanner;

  if (IsControlInput(func_def_input)) {
    graph_def_inputs->push_back(func_def_input);
    return Status::OK();
  }

  // Parse input format: "node_name[:node_output][:position]"
  string node_name;
  string node_output;
  int position = -1;

  StringPiece capture;
  StringPiece remaining;

  // Parse "node_name"
  if (Scanner(func_def_input)
          .One(strings::Scanner::LETTER_DIGIT_DOT_UNDERSCORE)
          .Any(strings::Scanner::LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE)
          .GetResult(&remaining, &capture)) {
    node_name = string(capture.data(), capture.size());
  }

  // Parse "node_output" if it exists
  if (Scanner(remaining)
          .OneLiteral(":")
          .RestartCapture()
          .One(strings::Scanner::LETTER)
          .Any(strings::Scanner::LETTER_DIGIT_UNDERSCORE)
          .GetResult(&remaining, &capture)) {
    node_output = string(capture.data(), capture.size());
  }

  // Parse "position" if it exists
  if (Scanner(remaining)
          .OneLiteral(":")
          .RestartCapture()
          .Many(strings::Scanner::DIGIT)
          .GetResult(nullptr, &capture)) {
    CHECK(strings::safe_strto32(capture, &position));
  }

  // If "node_output" is not empty, it must be an output of a function body node
  bool is_function_body_output = !node_output.empty();

  // Function input argument: "node_name[:position]"
  if (!is_function_body_output) {
    auto input_arg = input_arg_expansions_.find(node_name);
    if (input_arg != input_arg_expansions_.end()) {
      const InputArgExpansion& input_arg_expansion = input_arg->second;
      const auto& placeholders = input_arg_expansion.placeholders;

      if (position == -1) {
        // If position is not defined use all placeholders
        graph_def_inputs->reserve(placeholders.size());
        for (const string& placeholder : placeholders) {
          graph_def_inputs->push_back(placeholder);
        }
      } else {
        if (position > input_arg_expansion.placeholders.size() - 1) {
          return errors::InvalidArgument("Invalid input ", node_name,
                                         "position: ", position,
                                         " (out of range)");
        }
        graph_def_inputs->push_back(input_arg_expansion.placeholders[position]);
      }

      return Status::OK();
    }
  }

  // Function body output: "node_name:node_output[:position]"
  if (is_function_body_output) {
    auto function_body_outputs = function_body_outputs_.find(node_name);
    if (function_body_outputs != function_body_outputs_.end()) {
      const tensorflow::NameRangeMap& outputs = function_body_outputs->second;
      auto output = outputs.find(node_output);
      if (output != outputs.end()) {
        const auto& output_range = output->second;

        if (position == -1) {
          graph_def_inputs->reserve(graph_def_inputs->size() +
                                    output_range.second - output_range.first);
          // If position is not defined expand node output range
          for (int i = output_range.first; i < output_range.second; ++i) {
            graph_def_inputs->push_back(
                i == 0 ? node_name : absl::StrCat(node_name, ":", i));
          }
        } else {
          if (position > (output_range.second - output_range.first)) {
            return errors::InvalidArgument(
                "Invalid node ", node_name, " output ", node_output,
                " position: ", position, " (out of range)");
          }
          int pos = output_range.first + position;
          graph_def_inputs->push_back(
              pos == 0 ? node_name : absl::StrCat(node_name, ":", pos));
        }

        return Status::OK();
      }
    }
  }

  return errors::InvalidArgument("Failed to expand a function def input: ",
                                 func_def_input);
}

Status GrapplerFunctionConnectivity::ExpandNodeInputs(
    NodeDef* function_body_node) const {
  std::vector<string> expanded_inputs;

  for (const string& function_def_input : function_body_node->input()) {
    TF_RETURN_IF_ERROR(
        ExpandFunctionDefInput(function_def_input, &expanded_inputs));
  }

  function_body_node->clear_input();
  for (string& expanded_input : expanded_inputs)
    function_body_node->add_input(std::move(expanded_input));
  return Status::OK();
}

Status GrapplerFunctionConnectivity::AsFunctionDefInput(
    const string& graph_def_input, string* func_def_input) const {
  if (IsControlInput(graph_def_input)) {
    *func_def_input = graph_def_input;
    return Status::OK();
  }

  const TensorId tensor = ParseTensorName(graph_def_input);
  DCHECK_GE(tensor.index(), 0);

  const absl::string_view node_name = tensor.node();
  const int index = tensor.index();

  // Check if it's an input arg placeholder
  if (tensor.index() == 0) {
    const auto is_input_placeholder = input_arg_placeholders_.find(node_name);
    if (is_input_placeholder != input_arg_placeholders_.end()) {
      const InputArgPlaceholder& placeholder = is_input_placeholder->second;
      *func_def_input =
          absl::StrCat(placeholder.input_name, ":", placeholder.input_index);
      return Status::OK();
    }
  }

  // It must be output from one of the function body nodes
  const auto is_body_output = function_body_outputs_.find(tensor.node());
  if (is_body_output != function_body_outputs_.end()) {
    const tensorflow::NameRangeMap& outputs_range_map = is_body_output->second;

    for (const auto& el : outputs_range_map) {
      const auto& output_name = el.first;
      const auto& output_range = el.second;
      if (index >= output_range.first && index < output_range.second) {
        int pos = index - output_range.first;
        *func_def_input = absl::StrCat(node_name, ":", output_name, ":", pos);
        return Status::OK();
      }
    }
  }

  return errors::InvalidArgument("Unknown graph def input: ", graph_def_input);
}

Status GrapplerFunctionConnectivity::AsFunctionDefNode(
    NodeDef* function_body_node) const {
  string func_def_input;

  for (int i = 0; i < function_body_node->input_size(); ++i) {
    TF_RETURN_IF_ERROR(
        AsFunctionDefInput(function_body_node->input(i), &func_def_input));
    function_body_node->set_input(i, func_def_input);
  }

  return Status::OK();
}

Status GrapplerFunctionItemInstantiation::GetTypeAttr(
    const string& type_attr_name, DataType* data_type) const {
  const AttrValue* type_attr = func_instantiation_attr_.Find(type_attr_name);
  if (type_attr == nullptr) {
    return errors::InvalidArgument("Type attribute ", type_attr_name,
                                   " is not defined");
  } else if (type_attr->type() == DT_INVALID) {
    return errors::InvalidArgument("Type attribute ", type_attr_name,
                                   " is not defined with a valid type");
  } else {
    *data_type = type_attr->type();
  }
  return Status::OK();
}

Status GrapplerFunctionItemInstantiation::GetArgType(
    const OpDef::ArgDef& arg, DataType* data_type) const {
  if (arg.type() != DT_INVALID) {
    *data_type = arg.type();
  } else {
    if (!arg.type_list_attr().empty() || !arg.number_attr().empty()) {
      return errors::InvalidArgument(
          "Arguments with sequence of tensors are not supported. Unsupported "
          "argument name: ",
          arg.name());
    }
    TF_RETURN_IF_ERROR(GetTypeAttr(arg.type_attr(), data_type));
  }
  return Status::OK();
}

GrapplerFunctionItem::GrapplerFunctionItem(
    string func_name, string description, AttrSlice func_attr,
    std::vector<InputArgExpansion> input_arg_expansions,
    std::vector<OutputArgExpansion> output_arg_expansions,
    std::vector<string> keep_nodes, const int graph_def_version,
    const bool is_stateful, GraphDef&& function_body)
    : description_(std::move(description)),
      func_attr_(func_attr),
      input_arg_expansions_(std::move(input_arg_expansions)),
      output_arg_expansions_(std::move(output_arg_expansions)),
      is_stateful_(is_stateful) {
  // Move assign GrapplerItem members.
  keep_ops = std::move(keep_nodes);
  id = std::move(func_name);
  graph = std::move(function_body);

  graph.mutable_versions()->set_producer(graph_def_version);
  // Fill the feed nodes with input placeholders.
  for (const InputArgExpansion& input_arg : input_arg_expansions_) {
    for (const string& placeholder : input_arg.placeholders) {
      feed.push_back({placeholder, Tensor()});
    }
  }
  // Fill the fetch nodes with outputs.
  for (const OutputArgExpansion& output_arg : output_arg_expansions_) {
    for (const string& output_node : output_arg.output_nodes) {
      fetch.push_back(output_node);
    }
  }

  // Tensorflow functions execution semantics is different from the main graph,
  // and we need to preserve it when we do graph optimizations.
  optimization_options().allow_pruning_stateful_and_dataset_ops = false;
}

const string& GrapplerFunctionItem::description() const { return description_; }

const std::vector<InputArgExpansion>& GrapplerFunctionItem::inputs() const {
  return input_arg_expansions_;
}

const InputArgExpansion& GrapplerFunctionItem::input(int i) const {
  return input_arg_expansions_[i];
}

const std::size_t GrapplerFunctionItem::input_size() const {
  return input_arg_expansions_.size();
}

const std::vector<OutputArgExpansion>& GrapplerFunctionItem::outputs() const {
  return output_arg_expansions_;
}

const OutputArgExpansion& GrapplerFunctionItem::output(int i) const {
  return output_arg_expansions_[i];
}

const std::size_t GrapplerFunctionItem::output_size() const {
  return output_arg_expansions_.size();
}

const AttrSlice& GrapplerFunctionItem::func_attr() const { return func_attr_; }

const GraphDef& GrapplerFunctionItem::function_body() const { return graph; }

GraphDef& GrapplerFunctionItem::mutable_function_body() { return graph; }

bool GrapplerFunctionItem::is_stateful() const { return is_stateful_; }

GrapplerFunctionItem& GrapplerFunctionItem::SwapFunctionBody(GraphDef&& other) {
  graph.Swap(&other);
  return *this;
}

bool HasParametrizedType(const FunctionDef& func) {
  const auto is_type_parametrized = [](const OpDef::ArgDef& arg) {
    return !arg.type_attr().empty() || !arg.number_attr().empty() ||
           !arg.type_list_attr().empty();
  };

  const auto& input = func.signature().input_arg();
  const auto& output = func.signature().output_arg();
  return std::any_of(input.begin(), input.end(), is_type_parametrized) ||
         std::any_of(output.begin(), output.end(), is_type_parametrized);
}

bool HasParametrizedBody(const FunctionDef& func) {
  const auto is_parametrized = [&](const NodeDef& node) {
    for (const auto& attr : node.attr()) {
      if (!attr.second.placeholder().empty()) return true;
    }
    return false;
  };
  return std::any_of(func.node_def().begin(), func.node_def().end(),
                     is_parametrized);
}

bool IsParametrized(const FunctionDef& func) {
  return HasParametrizedType(func) || HasParametrizedBody(func);
}

Status InstantiationTypeParameters(
    const FunctionDef& func, const AttrSlice& func_instantiation_attr,
    absl::flat_hash_map<string, DataType>* type_parameters) {
  if (!type_parameters->empty()) {
    return errors::InvalidArgument("Type parameters output map must be empty");
  }

  GrapplerFunctionItemInstantiation instantiation(func_instantiation_attr);

  const auto resolve_type_attr = [&](const OpDef::ArgDef& arg) {
    // Check if it's unknown and unresolved type.
    if (arg.type() == DT_INVALID &&
        type_parameters->find(arg.type_attr()) == type_parameters->end()) {
      DataType data_type;
      TF_RETURN_IF_ERROR(instantiation.GetArgType(arg, &data_type));
      type_parameters->insert({arg.type_attr(), data_type});
    }
    return Status::OK();
  };

  for (const auto& input : func.signature().input_arg())
    TF_RETURN_IF_ERROR(resolve_type_attr(input));
  for (const auto& output : func.signature().output_arg())
    TF_RETURN_IF_ERROR(resolve_type_attr(output));

  return Status::OK();
}

Status InstantiationBodyParameters(
    const FunctionDef& func, const AttrSlice& func_instantiation_attr,
    absl::flat_hash_map<string, AttrValue>* body_parameters) {
  if (!body_parameters->empty()) {
    return errors::InvalidArgument("Body parameters output map must be empty");
  }

  for (const NodeDef& func_body_node : func.node_def()) {
    for (auto& attr : func_body_node.attr()) {
      const string& placeholder = attr.second.placeholder();

      if (placeholder.empty() ||
          body_parameters->find(placeholder) != body_parameters->end()) {
        continue;
      }

      const AttrValue* placeholder_value =
          func_instantiation_attr.Find(placeholder);
      if (placeholder_value) {
        body_parameters->insert({placeholder, *placeholder_value});
      } else {
        return errors::InvalidArgument("Can't resolve placeholder: ",
                                       placeholder);
      }
    }
  }

  return Status::OK();
}

Status MakeGrapplerFunctionItem(const FunctionDef& func,
                                const AttrSlice& func_instantiation_attr,
                                const FunctionLibraryDefinition& flib,
                                const int graph_def_version,
                                GrapplerFunctionItem* item) {
  const OpDef& signature = func.signature();

  if (signature.name().empty()) {
    return errors::InvalidArgument("Function name must be specified");
  }

  // Function types will be resolved from function instantiation attributes. All
  // other attributes will be lost during conversion to FunctionDef.
  for (const OpDef::AttrDef& attr : signature.attr()) {
    if (attr.type() != "type") {
      return errors::InvalidArgument(
          "Function signature must have only type attributes");
    }
  }

  // Helper methods to lookup function instantiation attributes
  GrapplerFunctionItemInstantiation instantiation(func_instantiation_attr);

  // Mapping from FunctionDef input format (name[:output][:position]) to
  // GraphDef input format (name[:position])
  GrapplerFunctionConnectivity connectivity;

  // Instantiate function body into a statically defined graph def.
  GraphDef function_body;

  // Function body shares the library with the graph that instantiated it. We do
  // not need a full copy of the function library, just the reachable subset.
  *function_body.mutable_library() = flib.ReachableDefinitions(func).ToProto();

  VLOG(3) << absl::Substitute(
      "Deleted $0 unreachable functions from the Grappler function item "
      "instantiation of $1 (library size = $2)",
      flib.num_functions() - function_body.library().function_size(),
      signature.name(), function_body.library().function_size());

  // TODO(ezhulenev): support functions with tensor sequence inputs/outputs

  // Make sure that there are no tensor lists in inputs or outputs.
  for (const OpDef::ArgDef& input : signature.input_arg()) {
    if (!input.type_list_attr().empty() || !input.number_attr().empty()) {
      return errors::InvalidArgument(
          "Inputs with lists of tensors are not supported. Input: ",
          input.name());
    }
  }
  for (const OpDef::ArgDef& output : signature.output_arg()) {
    if (!output.type_list_attr().empty() || !output.number_attr().empty()) {
      return errors::InvalidArgument(
          "Outputs with lists of tensors are not supported. Output: ",
          output.name());
    }
  }

  std::vector<InputArgExpansion> inputs;
  inputs.reserve(signature.input_arg_size());

  // For each input argument create a placeholder in function body.
  for (const OpDef::ArgDef& input : signature.input_arg()) {
    DataType input_data_type;
    TF_RETURN_IF_ERROR(instantiation.GetArgType(input, &input_data_type));

    NodeDef* placeholder = function_body.add_node();
    placeholder->set_name(input.name());
    placeholder->set_op("Placeholder");
    (*placeholder->mutable_attr())["dtype"].set_type(input_data_type);
    (*placeholder->mutable_attr())["shape"].mutable_shape()->set_unknown_rank(
        true);

    InputArgExpansion input_expansion{/*input_name=*/input.name(),
                                      /*data_type=*/input_data_type,
                                      /*is_ref=*/input.is_ref(),
                                      /*placeholders=*/{input.name()}};
    connectivity.RegisterInputArgExpansion(input_expansion);
    inputs.push_back(std::move(input_expansion));
  }

  // Keep names of all nodes in the function body to guarantee that we do not
  // add an identity with a duplicate name.
  absl::flat_hash_set<absl::string_view> func_body_nodes;

  // Generate unique output node name: "${out_arg_name}_output_node_${index}".
  const auto output_node_name = [&func_body_nodes](const OpDef::ArgDef& out,
                                                   int index) -> string {
    string name = absl::StrCat(out.name(), "_output_node_", index);
    int i = 1;
    while (func_body_nodes.find(name) != func_body_nodes.end()) {
      name = absl::StrCat(out.name(), "_output_node_", index, "_", i++);
    }
    return name;
  };

  // Add all function nodes to the function body.
  for (const NodeDef& func_def_node : func.node_def()) {
    func_body_nodes.insert(func_def_node.name());

    NodeDef* new_node = function_body.add_node();
    *new_node = func_def_node;

    const OpRegistrationData* registration;
    TF_RETURN_IF_ERROR(flib.LookUp(func_def_node.op(), &registration));

    // Resolve all placeholder values using function instantiation attributes.
    TF_RETURN_IF_ERROR(ResolveFunctionBodyNodeAttrPlaceholders(
        func_instantiation_attr, new_node));

    // Register node output range in a function connectivity.
    TF_RETURN_IF_ERROR(RegisterFunctionBodyOutputs(*registration, func_def_node,
                                                   &connectivity));
  }

  // Rewrite inputs to use GraphDef format
  for (NodeDef& node : *function_body.mutable_node()) {
    TF_RETURN_IF_ERROR(connectivity.ExpandNodeInputs(&node));
  }

  std::vector<OutputArgExpansion> outputs;
  outputs.reserve(signature.output_arg_size());

  // For each function output argument we create an Identity node in the
  // function body, that reads output tensor from the function body node.
  for (const OpDef::ArgDef& out : signature.output_arg()) {
    DataType output_data_type;
    TF_RETURN_IF_ERROR(instantiation.GetArgType(out, &output_data_type));

    std::vector<string> output_tensors;
    auto ret = func.ret().find(out.name());
    TF_RETURN_IF_ERROR(
        ret != func.ret().end()
            // Expand outputs using provided output mapping
            ? connectivity.ExpandFunctionDefInput(ret->second, &output_tensors)
            // Otherwise output must be one of the function inputs
            : connectivity.ExpandFunctionDefInput(out.name(), &output_tensors));

    absl::InlinedVector<string, 1> output_nodes;
    for (int i = 0; i < output_tensors.size(); ++i) {
      const string& output_tensor = output_tensors[i];

      NodeDef* identity = function_body.add_node();
      identity->set_name(output_node_name(out, i));
      identity->set_op("Identity");
      (*identity->mutable_attr())["T"].set_type(output_data_type);
      identity->add_input(output_tensor);

      output_nodes.push_back(identity->name());
    }

    OutputArgExpansion output{/*output_name=*/out.name(),
                              /*data_type=*/output_data_type,
                              /*is_ref=*/out.is_ref(),
                              /*output_nodes=*/std::move(output_nodes)};
    outputs.push_back(std::move(output));
  }

  std::vector<string> keep_ops;
  bool is_stateful = signature.is_stateful();

  *item = GrapplerFunctionItem(
      /*func_name=*/signature.name(),
      /*description=*/signature.description(),
      /*func_attr=*/AttrSlice(&func.attr()), std::move(inputs),
      std::move(outputs), std::move(keep_ops), graph_def_version, is_stateful,
      std::move(function_body));
  return Status::OK();
}

Status MakeGrapplerFunctionItem(const FunctionDef& func,
                                const FunctionLibraryDefinition& flib,
                                const int graph_def_version,
                                GrapplerFunctionItem* item) {
  return MakeGrapplerFunctionItem(func, AttrSlice(), flib, graph_def_version,
                                  item);
}

// Register GrapplerFunctionItem input arg expansion and function body outputs
// in the GrapplerFunctionConnectivity.
Status RegisterGrapplerFunctionConnectivity(
    const GrapplerFunctionItem& item, const FunctionLibraryDefinition& flib,
    GrapplerFunctionConnectivity* connectivity) {
  for (const InputArgExpansion& input : item.inputs()) {
    connectivity->RegisterInputArgExpansion(input);
  }
  for (const NodeDef& func_body_node : item.function_body().node()) {
    TF_RETURN_IF_ERROR(
        RegisterFunctionBodyOutputs(flib, func_body_node, connectivity));
  }
  return Status::OK();
}

Status ReplaceInputWithConst(const NodeDef& input_const, int input_index,
                             GrapplerFunctionItem* item) {
  if (!IsConstant(input_const)) {
    return errors::InvalidArgument("Input node ", input_const.name(),
                                   " is not a constant");
  }

  auto& inputs = item->input_arg_expansions_;

  // Find input arg expansion and input placeholder position in it for the
  // given function input position.
  InputArgExpansion* input_arg_expansion = nullptr;
  int placeholder_idx = input_index;

  for (InputArgExpansion& input : inputs) {
    if (placeholder_idx < input.placeholders.size()) {
      input_arg_expansion = &input;
      break;
    }
    placeholder_idx -= input.placeholders.size();
  }

  if (input_arg_expansion == nullptr) {
    return errors::InvalidArgument("Input placeholder not found: input_index=",
                                   input_index, " function=", item->id);
  }

  // Delete placeholder from input expansion.
  string placeholder_name = input_arg_expansion->placeholders[placeholder_idx];
  input_arg_expansion->placeholders.erase(
      input_arg_expansion->placeholders.begin() + placeholder_idx);

  // Delete empty input expansions.
  inputs.erase(std::remove_if(inputs.begin(), inputs.end(),
                              [](const InputArgExpansion& input) {
                                return input.placeholders.empty();
                              }),
               inputs.end());

  // Replace placeholder node in the function body with a const node.
  for (NodeDef& node : *item->graph.mutable_node()) {
    if (node.name() == placeholder_name) {
      node = input_const;
      node.set_name(placeholder_name);
      node.clear_input();   // remove potential control inputs
      node.clear_device();  // device placement is defined by instantiating node
    }
  }

  return Status::OK();
}

Status RemoveFunctionOutputs(const absl::flat_hash_set<int>& remove_outputs,
                             GrapplerFunctionItem* item,
                             std::vector<std::pair<int, int>>* output_mapping) {
  DCHECK(output_mapping->empty());

  // Code below assumes that we do not support tensor list outputs and there is
  // a 1-to-1 mapping between output tensor and output argument expansion.
  for (const OutputArgExpansion& out_arg : item->outputs()) {
    DCHECK(out_arg.output_nodes.size() == 1)
        << "Output arg expansion must have single output";
  }

  // Do some sanity checking of the removed outputs positions.
  for (int remove_output : remove_outputs) {
    if (remove_output < 0 || remove_output >= item->output_size()) {
      return errors::InvalidArgument(
          "Function output index is out of bound: index=", remove_output,
          " max_output_index=", item->output_size());
    }
  }

  absl::flat_hash_set<const OutputArgExpansion*> remove_output_args;
  const auto is_remove_output_arg = [&](const OutputArgExpansion& output) {
    return remove_output_args.find(&output) != remove_output_args.end();
  };

  for (int i = 0; i < item->output_size(); ++i) {
    const OutputArgExpansion& output = item->output(i);
    if (remove_outputs.find(i) != remove_outputs.end()) {
      VLOG(3) << "Remove functions output: output_name=" << output.output_name
              << "(index = " << i << ")";
      remove_output_args.insert(&output);
    } else if (!remove_output_args.empty()) {
      // Add output mapping only if output position changed.
      output_mapping->push_back({i, i - remove_output_args.size()});
    }
  }

  auto& o = item->output_arg_expansions_;
  o.erase(std::remove_if(o.begin(), o.end(), is_remove_output_arg), o.end());

  return Status::OK();
}

Status MakeFunctionDef(const GrapplerFunctionItem& item,
                       const FunctionLibraryDefinition& flib,
                       FunctionDef* func) {
  func->mutable_signature()->set_name(item.id);
  func->mutable_signature()->set_description(item.description());
  func->mutable_signature()->set_is_stateful(item.is_stateful());

  // Keep track of placeholders that were added to the graph in place of
  // expanded function input arguments.
  absl::flat_hash_set<absl::string_view> input_placeholders;
  for (const InputArgExpansion& input_arg : item.inputs()) {
    for (const string& placeholder : input_arg.placeholders) {
      input_placeholders.insert(placeholder);
    }
  }

  // Keep track of identity nodes that were added to the graph in place of
  // expanded function output arguments.
  absl::flat_hash_set<absl::string_view> output_nodes;
  for (const OutputArgExpansion& output_arg : item.outputs()) {
    for (const string& output_node : output_arg.output_nodes) {
      output_nodes.insert(output_node);
    }
  }

  // If the output identity node was not modified by any optimizer, we can
  // bypass it and returns the function value from its input.
  absl::flat_hash_map<absl::string_view, string> output_tensors;
  for (const NodeDef& func_body_node : item.function_body().node()) {
    if (!IsIdentity(func_body_node)) continue;

    const string& node_name = func_body_node.name();
    if (output_nodes.find(node_name) != output_nodes.end()) {
      // Grappler optimizers might optimize nodes in the fanin of the output
      // node, and forward their control dependencies. We can't express control
      // dependencies in a function signature, so we have to keep the node.
      if (func_body_node.input_size() == 1) {
        VLOG(3) << "Bypass function output node: " << node_name << " -> "
                << func_body_node.input(0);
        output_tensors.emplace(node_name, func_body_node.input(0));
      } else {
        VLOG(3) << "Keep function output node: " << node_name;
      }
    }
  }

  // Return output tensor name (input of the output node) if it's safe to bypass
  // output node, otherwise returns the output node name.
  const auto output_tensor =
      [&output_tensors](const OutputArgExpansion& output_arg) -> const string& {
    const string& output_node = output_arg.output_nodes[0];
    const auto is_output_tensor = output_tensors.find(output_node);
    return is_output_tensor == output_tensors.end() ? output_node
                                                    : is_output_tensor->second;
  };

  // Build a GrapplerFunctionConnectivity from inputs and new function body.
  GrapplerFunctionConnectivity connectivity;
  TF_RETURN_IF_ERROR(
      RegisterGrapplerFunctionConnectivity(item, flib, &connectivity));

  // Add function input arguments.
  for (const InputArgExpansion& input_arg : item.inputs()) {
    DCHECK(input_arg.placeholders.size() == 1)  // do some sanity checking
        << "Inputs of tensor lists are not supported";

    OpDef::ArgDef arg_def;
    arg_def.set_name(input_arg.input_name);
    arg_def.set_type(input_arg.data_type);
    arg_def.set_is_ref(input_arg.is_ref);
    *func->mutable_signature()->add_input_arg() = arg_def;
  }

  // Add function output arguments.
  for (const OutputArgExpansion& output_arg : item.outputs()) {
    DCHECK(output_arg.output_nodes.size() == 1)  // do some sanity checking
        << "Outputs of tensor lists are not supported";

    OpDef::ArgDef arg_def;
    arg_def.set_name(output_arg.output_name);
    arg_def.set_type(output_arg.data_type);
    arg_def.set_is_ref(output_arg.is_ref);
    *func->mutable_signature()->add_output_arg() = arg_def;

    TF_RETURN_IF_ERROR(connectivity.AsFunctionDefInput(
        output_tensor(output_arg),
        &(*func->mutable_ret())[output_arg.output_name]));
  }

  // Copy function definition specific attributes.
  for (const auto& attr : item.func_attr()) {
    const auto& attr_name = attr.first;
    const auto& attr_value = attr.second;
    (*func->mutable_attr())[attr_name] = attr_value;
  }

  // Copy function body nodes to the FunctionDef and update input format
  for (const NodeDef& func_node : item.function_body().node()) {
    const string& name = func_node.name();

    // Do not copy input placeholders.
    if (IsPlaceholder(func_node) && input_placeholders.count(name)) continue;
    // Do not copy output nodes that we bypassed.
    if (IsIdentity(func_node) && output_tensors.count(name)) continue;

    NodeDef* func_def_node = func->add_node_def();
    *func_def_node = func_node;
    TF_RETURN_IF_ERROR(connectivity.AsFunctionDefNode(func_def_node));
  }

  return Status::OK();
}

}  // end namespace grappler
}  // end namespace tensorflow


text:
@protocol MembersTableViewDelegate <NSObject>

@optional
-(void)onSelctedMemeberWithIndex:(NSInteger)index;

@end
@interface MembersTableViewController : UITableViewController
@property (nonatomic,strong)NSMutableArray<UserAccount *> *menbersDataSource;
@property (nonatomic,weak)id<MembersTableViewDelegate> memberDelegate;
@end


text:
/*
 * $Id: JavaTemplates.xml 53870 2013-02-12 10:32:44Z tlangfeld $
 */
package org.ops4j.pax.shiro.faces.tags;

import javax.faces.component.FacesComponent;

@FacesComponent("org.ops4j.pax.shiro.component.LacksPermission")
public class LacksPermissionComponent extends HasPermissionComponent {

    @Override
    public boolean isRendered() {
        return !super.isRendered();
    }
}


text:
require "spec_helper"
require "hamster/list"

describe Hamster::List do
  describe "#each" do
    context "on a really big list" do
      it "doesn't run out of stack" do
        -> { Hamster.interval(0, STACK_OVERFLOW_DEPTH).each { |item| } }.should_not raise_error
      end
    end

    [
      [],
      ["A"],
      %w[A B C],
    ].each do |values|
      context "on #{values.inspect}" do
        let(:list) { Hamster.list(*values) }

        context "with a block" do
          it "iterates over the items in order" do
            yielded = []
            list.each { |item| yielded << item }
            yielded.should == values
          end

          it "returns nil" do
            list.each { |item| item }.should be_nil
          end
        end

        context "without a block" do
          it "returns an Enumerator" do
            list.each.class.should be(Enumerator)
            list.each.to_list.should eql(list)
          end
        end
      end
    end
  end
end


text:
import {SparkRoutes} from "helpers/spark_routes";
import {MithrilViewComponent} from "jsx/mithril-component";
import m from "mithril";
import {Link} from "views/components/link";
import styles from "./edit_pipelines.scss";

interface Attrs {
  dataTestId?: string;
  configRepoId: string;
}

export class ConfigRepoLink extends MithrilViewComponent<Attrs> {
  view(vnode: m.Vnode<Attrs>) {
    return <span data-test-id={vnode.attrs.dataTestId} className={styles.configRepoLink}>
                                      (Config Repository:
                                      <Link target="_blank" href={SparkRoutes.ConfigRepoViewPath(vnode.attrs.configRepoId)}>
                                        {vnode.attrs.configRepoId}
                                      </Link>
                                      )
                                    </span>;
  }
}