text:
package org.apache.guacamole.token;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Filtering object which replaces tokens of the form "${TOKEN_NAME}" with
 * their corresponding values. Unknown tokens are not replaced. If TOKEN_NAME
 * is a valid token, the literal value "${TOKEN_NAME}" can be included by using
 * "$${TOKEN_NAME}".
 */
public class TokenFilter {

    /**
     * Regular expression which matches individual tokens, with additional
     * capturing groups for convenient retrieval of leading text, the possible
     * escape character preceding the token, the name of the token, and the
     * entire token itself.
     */
    private final Pattern tokenPattern = Pattern.compile("(.*?)(^|.)(\\$\\{([A-Za-z0-9_]*)\\})");

    /**
     * The index of the capturing group within tokenPattern which matches
     * non-token text preceding a possible token.
     */
    private static final int LEADING_TEXT_GROUP = 1;

    /**
     * The index of the capturing group within tokenPattern which matches the
     * character immediately preceding a possible token, possibly denoting that
     * the token should instead be interpreted as a literal.
     */
    private static final int ESCAPE_CHAR_GROUP = 2;

    /**
     * The index of the capturing group within tokenPattern which matches the
     * entire token, including the leading "${" and terminating "}" strings.
     */
    private static final int TOKEN_GROUP = 3;

    /**
     * The index of the capturing group within tokenPattern which matches only
     * the token name contained within the "${" and "}" strings.
     */
    private static final int TOKEN_NAME_GROUP = 4;

    /**
     * The values of all known tokens.
     */
    private final Map<String, String> tokenValues = new HashMap<String, String>();

    /**
     * Sets the token having the given name to the given value. Any existing
     * value for that token is replaced.
     *
     * @param name
     *     The name of the token to set.
     *
     * @param value
     *     The value to set the token to.
     */
    public void setToken(String name, String value) {
        tokenValues.put(name, value);
    }

    /**
     * Returns the value of the token with the given name, or null if no such
     * token has been set.
     *
     * @param name
     *     The name of the token to return.
     *
     * @return
     *     The value of the token with the given name, or null if no such
     *     token exists.
     */
    public String getToken(String name) {
        return tokenValues.get(name);
    }

    /**
     * Removes the value of the token with the given name. If no such token
     * exists, this function has no effect.
     *
     * @param name
     *     The name of the token whose value should be removed.
     */
    public void unsetToken(String name) {
        tokenValues.remove(name);
    }

    /**
     * Returns a map of all tokens, with each key being a token name, and each
     * value being the corresponding token value. Changes to this map will
     * directly affect the tokens associated with this filter.
     *
     * @return
     *     A map of all token names and their corresponding values.
     */
    public Map<String, String> getTokens() {
        return tokenValues;
    }

    /**
     * Replaces all current token values with the contents of the given map,
     * where each map key represents a token name, and each map value
     * represents a token value.
     *
     * @param tokens
     *     A map containing the token names and corresponding values to
     *     assign.
     */
    public void setTokens(Map<String, String> tokens) {
        tokenValues.clear();
        tokenValues.putAll(tokens);
    }

    /**
     * Filters the given string, replacing any tokens with their corresponding
     * values.
     *
     * @param input
     *     The string to filter.
     *
     * @return
     *     A copy of the input string, with any tokens replaced with their
     *     corresponding values.
     */
    public String filter(String input) {

        StringBuilder output = new StringBuilder();
        Matcher tokenMatcher = tokenPattern.matcher(input);

        // Track last regex match
        int endOfLastMatch = 0;

        // For each possible token
        while (tokenMatcher.find()) {

            // Pull possible leading text and first char before possible token
            String literal = tokenMatcher.group(LEADING_TEXT_GROUP);
            String escape = tokenMatcher.group(ESCAPE_CHAR_GROUP);

            // Append leading non-token text
            output.append(literal);

            // If char before token is '$', the token itself is escaped
            if ("$".equals(escape)) {
                String notToken = tokenMatcher.group(TOKEN_GROUP);
                output.append(notToken);
            }

            // If char is not '$', interpret as a token
            else {

                // The char before the token, if any, is a literal
                output.append(escape);

                // Pull token value
                String tokenName = tokenMatcher.group(TOKEN_NAME_GROUP);
                String tokenValue = getToken(tokenName);

                // If token is unknown, interpret as literal
                if (tokenValue == null) {
                    String notToken = tokenMatcher.group(TOKEN_GROUP);
                    output.append(notToken);
                }

                // Otherwise, substitute value
                else
                    output.append(tokenValue);

            }

            // Update last regex match
            endOfLastMatch = tokenMatcher.end();

        }

        // Append any remaining non-token text
        output.append(input.substring(endOfLastMatch));

        return output.toString();

    }

    /**
     * Given an arbitrary map containing String values, replace each non-null
     * value with the corresponding filtered value.
     *
     * @param map
     *     The map whose values should be filtered.
     */
    public void filterValues(Map<?, String> map) {

        // For each map entry
        for (Map.Entry<?, String> entry : map.entrySet()) {

            // If value is non-null, filter value through this TokenFilter
            String value = entry.getValue();
            if (value != null)
                entry.setValue(filter(value));

        }

    }

}


text:
package engines.subengines;

import java.util.List;
import components.entityComponents.ComponentType;
import engines.CollisionPair;
import entity.Entity;
import entity.IEntity;
import entity.IEntityManager;
import gamedata.IRestrictedGameData;
/**
 * The ISubEngine interface is the interface for engines that are put into action when a collision occurs. Each subEngine will need to have a public method handleCollision that the CollisionHandler can call
 * @author Hamsa
 *
 */
public interface ISubEngine {

	/**
	 * Each subengine will handle a collision in a different way by checking different components and acting on them.
	 * The return type is List<Entity> since this method should return any new Entities created from handling the collision.
	 */
	IRestrictedGameData handleCollision(IEntity e0, IEntity e1, String side, IEntityManager myEM, IRestrictedGameData gameData);

}

redpajama_set_name: RedPajamaGithub


text:
import { ReactWrapper, EnzymeSelector } from 'enzyme';

export function waitForState(
    wrapper: ReactWrapper,
    stateValidationFn: (state: object) => boolean,
    config?: Config
): Promise<void>;

export function waitForElement(
    wrapper: ReactWrapper,
    elementSelector: EnzymeSelector,
    config?: Config
): Promise<void>;

export function waitForProps(
    wrapper: ReactWrapper,
    propsValidationFn: (props: object) => boolean,
    config?: Config
): Promise<void>;

export interface Config {
    interval?: number | undefined; // Default: 50, how often to check for validity
    timeout?: number | undefined; // Default: 2000 (2 seconds), how long to wait before timing out
    timeoutMessage?: string | undefined;
    logStructureOnTimeout?: boolean | undefined; // Default: true, logs the wrapper's rendered structure when the wait times out. An attempt to help out in finding what's wrong.
    logStructureOnSuccess?: boolean | undefined; // Default: false, logs the wrapper's rendered structure on success.
}


text:
package test.failedreporter;

import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import org.testng.xml.XmlGroups;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import test.SimpleBaseTest;
import test.failedreporter.issue1297.groups.GroupsPassSample;
import test.failedreporter.issue1297.groups.GroupsSampleBase;
import test.failedreporter.issue1297.inheritance.InheritanceFailureSample;
import test.failedreporter.issue1297.inheritance.InheritancePassSample;
import test.failedreporter.issue1297.straightforward.AllPassSample;
import test.failedreporter.issue1297.straightforward.FailureSample;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FailedReporterTest extends SimpleBaseTest {
  private File mTempDirectory;

  @BeforeMethod
  public void setUp() {
    mTempDirectory = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000);
  }

  @AfterMethod
  public void tearDown() {
    deleteDir(mTempDirectory);
  }

  @Test
  public void failedAndSkippedMethodsShouldBeIncluded() throws IOException {
    testFailedReporter(new String[] { "f1", "f2" }, "<include name=\"%s\"/>",
        FailedReporterSampleTest.class);
  }

  @Test
  public void failedMethodWithDataProviderShouldHaveInvocationNumbers() throws IOException {
    testFailedReporter(new String[] { "f1" }, "<include name=\"%s\" invocation-numbers=\"1\"/>",
        FailedReporter2SampleTest.class);
  }

  @Test(description = "github-1297")
  public void testExclusionOfPassedConfigs() {
    triggerTest(AllPassSample.class, FailureSample.class);
    String[] substitutions = new String[] {AllPassSample.class.getName()};
    runAssertions(mTempDirectory, substitutions, "<class name=\"%s\">",0);
    substitutions = new String[] {"newTest2", "beforeClassFailureSample","afterClassFailureSample"};
    runAssertions(mTempDirectory, substitutions, "<include name=\"%s\"/>",1);
  }

  @Test(description = "github-1297")
  public void testExclusionOfPassedConfigsAmidstInheritance() {
    triggerTest(InheritanceFailureSample.class, InheritancePassSample.class);
    String[] substitutions = new String[] {InheritancePassSample.class.getName()};
    runAssertions(mTempDirectory, substitutions, "<class name=\"%s\">", 0);
    substitutions = new String[] {"newTest2", "baseBeforeTest","baseAfterClass","baseBeforeClass","baseBeforeMethod"};
    runAssertions(mTempDirectory, substitutions, "<include name=\"%s\"/>",1);
  }

  @Test(description = "github-1297")
  public void testExclusionOfPassedConfigsInvolvingGroupsAtTestLevel() {
    triggerTest(GroupsSampleBase.class.getPackage().getName(),true);
    String[] substitutions = new String[] {GroupsPassSample.class.getName()};
    runAssertions(mTempDirectory, substitutions, "<class name=\"%s\">",0);
    substitutions = new String[] {"baseBeforeTest", "baseBeforeClassAlwaysRun","newTest2"};
    runAssertions(mTempDirectory, substitutions, "<include name=\"%s\"/>",1);
  }

  @Test(description = "github-1297")
  public void testExclusionOfPassedConfigsInvolvingGroupsAtSuiteLevel() {
    triggerTest(GroupsSampleBase.class.getPackage().getName(),false);
    String[] substitutions = new String[] {GroupsPassSample.class.getName()};
    runAssertions(mTempDirectory, substitutions, "<class name=\"%s\">",0);
    substitutions = new String[] {"baseBeforeTest", "baseBeforeClassAlwaysRun","newTest2"};
    runAssertions(mTempDirectory, substitutions, "<include name=\"%s\"/>",1);
  }

  private void triggerTest(String packageName, boolean applyGroupSelectionAtTest) {
    final XmlSuite suite = createXmlSuite("1297_suite");

    final XmlTest xmlTest = createXmlTestWithPackages(suite, "1297_test", packageName);
    if (applyGroupSelectionAtTest) {
      createXmlGroups(xmlTest, "run");
    } else {
      createXmlGroups(suite, "run");
    }
    TestNG tng = create(mTempDirectory.toPath(), suite);
    tng.setUseDefaultListeners(true);
    tng.run();
  }

  private void testFailedReporter(String[] expectedMethods, String expectedLine, Class<?>... cls) {
    triggerTest(cls);
    runAssertions(mTempDirectory,expectedMethods,expectedLine);
  }

  private void triggerTest(Class<?>... cls) {
    TestNG tng = create(mTempDirectory.toPath(), cls);
    tng.setUseDefaultListeners(true);
    tng.run();
  }

  static void runAssertions(File outputDir, String[] expectedMethods, String expectedLine) {
    runAssertions(outputDir, expectedMethods, expectedLine, 1);
  }

  private static void runAssertions(File outputDir, String[] expectedMethods, String expectedLine, int expected) {
    File failed = new File(outputDir, "testng-failed.xml");
    for (String s : expectedMethods) {
      List<String> resultLines = Lists.newArrayList();
      grep(failed, String.format(expectedLine, s), resultLines);
      Assert.assertEquals(resultLines.size(),expected );
    }
  }

}


text:
__author__ = 'mr.S'
from entities.s_user import User as UserEntity

class User(object):
    def __init__(self, session, db):
        self._session = session
        self._user = None
        self._db = db

    def get(self):
        if not self._session:
            return None
        user_id = self._session.get('user', {}).get('id', None)

        if not self._user and user_id:
            self._user = self._db(UserEntity).get_by_id(user_id)
        return self._user

    def set(self, user):
        s = self._session
        if user:
            s.setdefault('user', {})['id'] = user.id
            s.save()
            s.persist()
            self._user = user
        else:
            if 'user' in s:
                del s['user']
            s.save()
            s.persist()
            self._user = None
        return self._user

    def role(self, name):
        name = name.strip().lower()
        user = self.get()
        return False if not user else bool([role.code.lower() for role in user.roles if role.code.lower() in(name, 'superadmin')])


text:
def process_feed(feed)
	puts "Processing #{feed.feed_url}"
	options = {}
	options[:if_modified_since] = feed.feed_updated unless feed.feed_updated.nil?
	options[:if_none_match] = feed.feed_etag unless feed.feed_etag.nil?
	f = Feedzirra::Feed.fetch_and_parse(feed.feed_url, options)
	return if f.nil? || f == 304
	feed.feed_title = f.title unless f.title.nil?
	feed.feed_updated = f.last_modified unless f.last_modified.nil?
	feed.feed_etag = f.etag unless f.etag.nil?
	feed.save

	f.entries.each do |e|
		process_entry(feed, e)
	end
end

def process_entry(feed, e)
	entry = feed.entries.create(title: e.title, url: e.url, summary: e.summary, author: e.author, content: e.content, published: e.published, entry_id: e.entry_id, categories: e.categories) unless feed.entries.where(:entry_id => e.entry_id).count > 0
	puts "Added entry #{e.title}"
	doc = Nokogiri::HTML(open(e.url))
	img = doc.xpath('//img[contains(@class,"attachment-article")]').first
  article = doc.xpath('//div[contains(@class,"article")]').first
	entry.image_url = img['src'] unless img.nil? || img['src'].nil?
  entry.body = article.to_s
	entry.save
	puts " - Set image_url to #{entry.image_url}"
end

def generate_feed(feed)
	File.open("#{feed.feed_name}.json", 'w') do |f|
		f.write(feed.entries.order_by([:published, :desc]).limit(10).to_json)
		puts " - Generated #{feed.feed_name}.json"
	end
	File.open("#{feed.feed_name}-all.json", 'w') do |f|
		f.write(feed.entries.order_by([:published, :desc]).to_json)
		puts " - Generated #{feed.feed_name}-all.json"
	end
end


text:
// -*-  Mode:ObjC; c-basic-offset:4; tab-width:8; indent-tabs-mode:nil -*-

#import "DataModel.h"
#import "URLComponent.h"
#import "WebApi.h"
#import "Yahoo.h"
#import "dom.h"

///////////////////////////////////////////////////////////////////////////////////////////////
// Yahoo shopping api

@implementation YahooApi

- (instancetype)init
{
    self = [super init];
    return self;
}

/////////////////////////////////////////////////////////////////////////////////////
// カテゴリ

- (NSArray *)categoryStrings
{
    return @[@"All"];
}

/**
   Get default category (should be override)
*/
- (NSInteger)defaultCategoryIndex
{
    return 0; // all
}

/////////////////////////////////////////////////////////////////////////////////////
// 検索処理

/**
   Execute item search

   @note you must set searchKey/searchKeyType property before call this.
   And you can set searchIndex.
*/
- (void)itemSearch
{
    NSString *baseURI = @"http://itemshelf.com/cgi-bin/yahoojp.cgi?";
    URLComponent *comp = [[URLComponent alloc] initWithURLString:baseURI];

    NSString *param = nil;

    if (searchKeyType == SearchKeyCode) {
        // バーコード検索
        param = @"jan";
    } else {
        // キーワード検索
        param = @"keyword";
    }
    [comp setQuery:param value:searchKey];

    [comp log];

    NSURL *url = [comp url];
    [super sendHttpRequest:url];
}

/////////////////////////////////////////////////////////////////////////////////////
// HttpClientDelegate

/**
   @name HttpClientDelegate
*/
//@{

- (void)httpClientDidFinish:(HttpClient*)client
{
    [super httpClientDidFinish:client];

    // Parse XML
    DomParser *domParser = [[DomParser alloc] init];
    XmlNode *root = [domParser parse:client.receivedData];
    //[root dump];

    if (!root) {
        // XML error
        [delegate webApiDidFailed:self reason:WEBAPI_ERROR_BADREPLY message:nil];
        return;
    }

    NSMutableArray *itemArray = [[NSMutableArray alloc] init];
    XmlNode *hit;
    for (hit = [root findNode:@"Hit"]; hit; hit = [hit findSibling]) {
        NSString *hitIndex = (hit.attributes)[@"index"];
        if (hitIndex == nil || [hitIndex isEqualToString:@"0"]) {
            continue;
        }

        Item *item = [[Item alloc] init];
        [itemArray addObject:item];

        item.serviceId = serviceId;
        item.category = @"Other"; // とりあえず

        XmlNode *n;
        n = [hit findNode:@"IsbnCode"];
        if (n) {
            item.idString = n.text;
        } else {
            n = [hit findNode:@"JanCode"];
            if (n) item.idString = [NSString stringWithString:n.text];
        }

        item.name = [hit findNode:@"Name"].text;
        item.detailURL = [hit findNode:@"Url"].text;
        item.imageURL = [hit findNode:@"Medium"].text;
        n = [hit findNode:@"Price"];
        if (n) {
            double price = (n.text).doubleValue;
            item.price = [Common currencyString:price withLocaleString:@"ja_JP"];
        }
    }

    if (itemArray.count > 0) {
        // success
        [delegate webApiDidFinish:self items:itemArray];
    } else {
        // no data
        NSString *message = @"No items";
        [delegate webApiDidFailed:self reason:WEBAPI_ERROR_NOTFOUND message:message]; //###
    }
}

//@}

@end


text:
// Copyright (c) 2010-2011 Vincent Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_HOOKS_H
#define BITCOIN_HOOKS_H

class CHooks
{
public:
    virtual bool IsStandard(const CScript& scriptPubKey) = 0;
    virtual void AddToWallet(CWalletTx& tx) = 0;
    virtual bool CheckTransaction(const CTransaction& tx) = 0;
    virtual bool ConnectInputs(CTxDB& txdb,
            std::map<uint256, CTxIndex>& mapTestPool,
            const CTransaction& tx,
            std::vector<CTransaction>& vTxPrev,
            std::vector<CTxIndex>& vTxindex,
            CBlockIndex* pindexBlock,
            CDiskTxPos& txPos,
            bool fBlock,
            bool fMiner) = 0;
    virtual bool DisconnectInputs(CTxDB& txdb,
            const CTransaction& tx,
            CBlockIndex* pindexBlock) = 0;
    virtual bool ConnectBlock(CBlock& block, CTxDB& txdb, CBlockIndex* pindex, int64 &nFees, unsigned int nPosAfterTx) = 0;
    virtual bool DisconnectBlock(CBlock& block, CTxDB& txdb, CBlockIndex* pindex) = 0;
    virtual bool ExtractAddress(const CScript& script, std::string& address) = 0;
    virtual bool GenesisBlock(CBlock& block) = 0;
    virtual bool Lockin(int nHeight, uint256 hash) = 0;
    virtual int LockinHeight() = 0;
    virtual std::string IrcPrefix() = 0;
    virtual void MessageStart(char* pchMessageStart) = 0;
    virtual void AcceptToMemoryPool(CTxDB& txdb, const CTransaction& tx) = 0;
    virtual void RemoveFromMemoryPool(const CTransaction& tx) = 0;

    /* These are for display and wallet management purposes.  Not for use to decide
     * whether to spend a coin. */
    virtual bool IsMine(const CTransaction& tx) = 0;
    virtual bool IsMine(const CTransaction& tx, const CTxOut& txout, bool ignore_name_new = false) = 0;

    // Allows overriding of the default fee for certain transaction types
    virtual void GetMinFee(int64 &nMinFee, int64 &nBaseFee, const CTransaction &tx,
        unsigned int nBlockSize, bool fAllowFree, bool fForRelay,
        unsigned int nBytes, unsigned int nNewBlockSize) = 0;

    virtual std::string GetAlertPubkey1() = 0;
    virtual std::string GetAlertPubkey2() { return GetAlertPubkey1(); }
};

// A simple wrapper (pImpl pattern) to remove dependency on the game-related headers when miner just wants to check transactions
class GameStepMiner
{
    class GameStepMinerImpl *pImpl;
public:
    GameStepMiner(CTxDB &txdb, CBlockIndex *pindex);
    ~GameStepMiner();
    bool AddTx(const CTransaction& tx);
    int64 ComputeTax();
};

extern CHooks* InitHook();
extern std::string GetDefaultDataDirSuffix();

#endif


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mobile Device Manager</title>

    <link rel="icon" href="favicon.png" type="image/x-icon" />
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/custom-common.css" rel="stylesheet">
    <link href="css/custom-desktop.css" rel="stylesheet">
    <link href="css/custom-theme.css" rel="stylesheet">

Mobile Device Manager

                            Administrator

                            Logout

                    Go Back To Dashboard

Profile is added to the policy

                    Please select a policy and click "Add to a policy", if you wish to add the profile to a policy or click "Finish" to complete the process and go back to the profiles list

                                <select class="form-control">
                                    <option>Select..</option>
                                </select>

                                Create Policy

                    <button class="wr-btn"  onclick="window.location.href='profiles.html'">Finish</button><button class="wr-btn" onclick="window.location.href='profile-added-to-policy.html'">Add to a policy</button>

Mobile Device Manager v.2.0.0 | ©   Inc. All Rights Reserved.

Sort By

    	Device Name
    	OS
    	User
    	Model


text:
import {Services} from '../../src/services';
import {SsrTemplateHelper} from '../../src/ssr-template-helper';

describes.fakeWin(
  'ssr-template-helper',
  {
    amp: true,
  },
  (env) => {
    let ampdoc;
    let hasCapabilityStub;
    let ssrTemplateHelper;
    const sourceComponent = 'amp-list';
    let maybeFindTemplateStub;
    let templates;
    let viewer;
    let win;

    beforeEach(() => {
      ampdoc = env.ampdoc;
      win = env.win;
      templates = Services.templatesForDoc(ampdoc);
      viewer = Services.viewerForDoc(ampdoc);
      viewer.isTrustedViewer = () => Promise.resolve(true);
      hasCapabilityStub = env.sandbox.stub(viewer, 'hasCapability');
      maybeFindTemplateStub = env.sandbox.stub(templates, 'maybeFindTemplate');
      ssrTemplateHelper = new SsrTemplateHelper(
        sourceComponent,
        viewer,
        templates
      );
    });

    afterEach(() => {
      win.document.documentElement.removeAttribute(
        'allow-viewer-render-template'
      );
    });

    describe('isEnabled', () => {
      it('should return true if doc level opt-in', () => {
        win.document.documentElement.setAttribute(
          'allow-viewer-render-template',
          true
        );
        hasCapabilityStub.withArgs('viewerRenderTemplate').returns(true);
        expect(ssrTemplateHelper.isEnabled()).to.be.true;
      });

      it('should return false if not doc level opt-in', () => {
        hasCapabilityStub.withArgs('viewerRenderTemplate').returns(true);
        expect(ssrTemplateHelper.isEnabled()).to.be.false;
      });

      it(
        'should return false if doc level opt-in but viewer does not have ' +
          'capability',
        () => {
          win.document.documentElement.setAttribute(
            'allow-viewer-render-template',
            true
          );
          hasCapabilityStub.withArgs('viewerRenderTemplate').returns(false);
          expect(ssrTemplateHelper.isEnabled()).to.be.false;
        }
      );
    });

    describe('ssr', () => {
      it('Should refuse to SSR with an untrusted viewer', async () => {
        viewer.isTrustedViewer = () => Promise.resolve(false);
        const errorMsg = /Refused to attempt SSR in untrusted viewer: /;
        expectAsyncConsoleError(errorMsg);

        return ssrTemplateHelper.ssr({}, {}, {}).then(
          () => Promise.reject(),
          (err) => {
            expect(err).match(errorMsg);
          }
        );
      });

      it('should build payload', async () => {
        const request = {
          'xhrUrl': 'https://www.abracadabra.org/some-json',
          'fetchOpt': {
            'body': {},
            'credentials': undefined,
            'headers': undefined,
            'method': 'GET',
            'ampCors': true,
          },
        };
        const sendMessage = env.sandbox
          .stub(viewer, 'sendMessageAwaitResponse')
          .returns(Promise.resolve({}));
        maybeFindTemplateStub.returns(null);
        const templates = {
          successTemplate: {'innerHTML': '
much success
'},
          errorTemplate: {'innerHTML': '
try again
'},
        };
        await ssrTemplateHelper.ssr({}, request, templates, {attr: 'test'});

        expect(sendMessage).calledWith('viewerRenderTemplate', {
          'ampComponent': {
            'type': 'amp-list',
            'successTemplate': {
              'type': 'amp-mustache',
              'payload': '
much success
',
            },
            'errorTemplate': {
              'type': 'amp-mustache',
              'payload': '
try again
',
            },
            'attr': 'test',
          },
          'originalRequest': {
            'init': {
              'ampCors': true,
              'body': {},
              'credentials': undefined,
              'headers': undefined,
              'method': 'GET',
            },
            'input': 'https://www.abracadabra.org/some-json',
          },
        });
      });
    });

    describe('rendering templates', () => {
      let findAndSetHtmlForTemplate;
      let findAndRenderTemplate;
      let findAndRenderTemplateArray;
      beforeEach(() => {
        win.document.documentElement.setAttribute(
          'allow-viewer-render-template',
          true
        );
        hasCapabilityStub.withArgs('viewerRenderTemplate').returns(true);
        findAndSetHtmlForTemplate = env.sandbox.stub(
          templates,
          'findAndSetHtmlForTemplate'
        );
        findAndRenderTemplate = env.sandbox.stub(
          templates,
          'findAndRenderTemplate'
        );
        findAndRenderTemplateArray = env.sandbox.stub(
          templates,
          'findAndRenderTemplateArray'
        );
      });

      describe('applySsrOrCsrTemplate', () => {
        it('should set html template', () => {
          // Not a real document element. This variable is used to ensure the
          // value returned by findAndSetHtmlForTemplate is returned by
          // applySsrOrCsrTemplate.
          const element = {};
          findAndSetHtmlForTemplate.returns(element);

          return ssrTemplateHelper
            .applySsrOrCsrTemplate({}, {html: '
some template
'})
            .then((renderedHTML) => {
              expect(findAndSetHtmlForTemplate).to.have.been.calledWith(
                {},
                '
some template
'
              );
              expect(renderedHTML).to.equal(element);
            });
        });

        it('should throw error if html template is not defined', () => {
          allowConsoleError(() => {
            expect(() => {
              ssrTemplateHelper.applySsrOrCsrTemplate({}, {html: null});
            }).to.throw(/Server side html response must be defined/);
          });
        });

        it('should throw if trying to ssr from an untrusted viewer', () => {
          viewer.isTrustedViewer = () => Promise.resolve(false);
          const errorMsg = /Refused to attempt SSR in untrusted viewer: /;
          expectAsyncConsoleError(errorMsg);

          ssrTemplateHelper
            .applySsrOrCsrTemplate({}, {html: '
some templates
'})
            .then(
              () => Promise.reject(),
              (error) => expect(error).to.match(errorMsg)
            );
        });

        it('should render template ', () => {
          hasCapabilityStub.withArgs('viewerRenderTemplate').returns(false);
          ssrTemplateHelper.applySsrOrCsrTemplate(
            {},
            {data: '
some template
'}
          );
          expect(findAndRenderTemplate).to.have.been.calledWith(
            {},
            {data: '
some template
'}
          );
        });

        it('should set template array ', () => {
          hasCapabilityStub.withArgs('viewerRenderTemplate').returns(false);
          ssrTemplateHelper.applySsrOrCsrTemplate({}, [
            {data: '
some template
'},
          ]);
          expect(findAndRenderTemplateArray).to.have.been.calledWith({}, [
            {data: '
some template
'},
          ]);
        });
      });
    });
  }
);


text:
package org.onosproject.routing.impl;

import com.google.common.collect.Sets;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.EthType;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.core.CoreServiceAdapter;
import org.onosproject.incubator.net.intf.Interface;
import org.onosproject.incubator.net.intf.InterfaceEvent;
import org.onosproject.incubator.net.intf.InterfaceListener;
import org.onosproject.incubator.net.intf.InterfaceService;
import org.onosproject.incubator.net.intf.InterfaceServiceAdapter;
import org.onosproject.mastership.MastershipService;
import org.onosproject.mastership.MastershipServiceAdapter;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.NetTestTools;
import org.onosproject.net.PortNumber;
import org.onosproject.net.config.Config;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigEvent.Type;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.config.NetworkConfigServiceAdapter;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flowobjective.DefaultForwardingObjective;
import org.onosproject.net.flowobjective.DefaultNextObjective;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.NextObjective;
import org.onosproject.net.host.HostService;
import org.onosproject.net.host.InterfaceIpAddress;
import org.onosproject.routing.RoutingService;
import org.onosproject.routing.config.RouterConfig;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;

/**
 * UnitTests for ControlPlaneRedirectManager.
 */
public class ControlPlaneRedirectManagerTest {

    private DeviceService deviceService;
    private FlowObjectiveService flowObjectiveService;
    private NetworkConfigService networkConfigService;
    private final Set<Interface> interfaces = Sets.newHashSet();
    static Device dev3 = NetTestTools.device("0000000000000001");
    private static final int OSPF_IP_PROTO = 0x59;
    private CoreService coreService = new TestCoreService();
    private InterfaceService interfaceService;
    private static final ApplicationId APPID = TestApplicationId.create("org.onosproject.cpredirect");

    private static final DeviceId DEVICE_ID = DeviceId.deviceId("of:0000000000000001");

    private ConnectPoint controlPlaneConnectPoint = new ConnectPoint(DEVICE_ID,
            PortNumber.portNumber(1));

    private static final ConnectPoint SW1_ETH1 = new ConnectPoint(DEVICE_ID,
            PortNumber.portNumber(1));

    private static final ConnectPoint SW1_ETH2 = new ConnectPoint(DEVICE_ID,
            PortNumber.portNumber(2));

    private static final ConnectPoint SW1_ETH3 = new ConnectPoint(DEVICE_ID,
            PortNumber.portNumber(3));

    private ControlPlaneRedirectManager controlPlaneRedirectManager = new ControlPlaneRedirectManager();
    private RouterConfig routerConfig = new TestRouterConfig();
    private NetworkConfigListener networkConfigListener;
    private DeviceListener deviceListener;
    private MastershipService mastershipService = new InternalMastershipServiceTest();
    private InterfaceListener interfaceListener;

    @Before
    public void setUp() {
        networkConfigListener = createMock(NetworkConfigListener.class);
        deviceService = new TestDeviceService();
        deviceListener = createMock(DeviceListener.class);

        interfaceListener = createMock(InterfaceListener.class);
        deviceService.addListener(deviceListener);
        setUpInterfaceService();
        interfaceService = new InternalInterfaceService();
        interfaceService.addListener(interfaceListener);
        networkConfigService = new TestNetworkConfigService();
        networkConfigService.addListener(networkConfigListener);
        flowObjectiveService = createMock(FlowObjectiveService.class);
        setUpFlowObjectiveService();
        controlPlaneRedirectManager.coreService = coreService;
        controlPlaneRedirectManager.flowObjectiveService = flowObjectiveService;
        controlPlaneRedirectManager.networkConfigService = networkConfigService;
        controlPlaneRedirectManager.interfaceService = interfaceService;
        controlPlaneRedirectManager.deviceService = deviceService;
        controlPlaneRedirectManager.hostService = createNiceMock(HostService.class);
        controlPlaneRedirectManager.mastershipService = mastershipService;
        controlPlaneRedirectManager.activate();
        verify(flowObjectiveService);
    }

    /**
     * Tests adding new Device to a openflow router.
     */
    @Test
    public void testAddDevice() {
        ConnectPoint sw1eth4 = new ConnectPoint(DEVICE_ID, PortNumber.portNumber(4));
        Set<InterfaceIpAddress> interfaceIpAddresses4 = Sets.newHashSet();
        interfaceIpAddresses4
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.40.101"), IpPrefix.valueOf("192.168.40.0/24")));

        Interface sw1Eth4 = new Interface(sw1eth4.deviceId().toString(), sw1eth4, interfaceIpAddresses4,
                MacAddress.valueOf("00:00:00:00:00:04"), VlanId.NONE);
        interfaces.add(sw1Eth4);
        EasyMock.reset(flowObjectiveService);
        setUpFlowObjectiveService();
        deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED, dev3));
        verify(flowObjectiveService);
    }

    /**
     * Tests adding while updating the networkConfig.
     */
    @Test
    public void testUpdateNetworkConfig() {
        ConnectPoint sw1eth4 = new ConnectPoint(DEVICE_ID, PortNumber.portNumber(4));
        Set<InterfaceIpAddress> interfaceIpAddresses4 = Sets.newHashSet();
        interfaceIpAddresses4
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.40.101"), IpPrefix.valueOf("192.168.40.0/24")));

        Interface sw1Eth4 = new Interface(sw1eth4.deviceId().toString(), sw1eth4, interfaceIpAddresses4,
                MacAddress.valueOf("00:00:00:00:00:04"), VlanId.NONE);
        interfaces.add(sw1Eth4);
        EasyMock.reset(flowObjectiveService);
        setUpFlowObjectiveService();
        networkConfigListener
                .event(new NetworkConfigEvent(Type.CONFIG_UPDATED, dev3, RoutingService.ROUTER_CONFIG_CLASS));
        networkConfigService.addListener(networkConfigListener);
        verify(flowObjectiveService);
    }

    /**
     * Tests adding while updating the networkConfig.
     */
    @Test
    public void testAddInterface() {
        ConnectPoint sw1eth4 = new ConnectPoint(DEVICE_ID, PortNumber.portNumber(4));
        Set<InterfaceIpAddress> interfaceIpAddresses4 = Sets.newHashSet();
        interfaceIpAddresses4
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.40.101"), IpPrefix.valueOf("192.168.40.0/24")));

        Interface sw1Eth4 = new Interface(sw1eth4.deviceId().toString(), sw1eth4, interfaceIpAddresses4,
                MacAddress.valueOf("00:00:00:00:00:04"), VlanId.NONE);
        interfaces.add(sw1Eth4);

        EasyMock.reset(flowObjectiveService);
        expect(flowObjectiveService.allocateNextId()).andReturn(1).anyTimes();

        setUpInterfaceConfiguration(sw1Eth4, true);
        replay(flowObjectiveService);
        interfaceListener.event(new InterfaceEvent(InterfaceEvent.Type.INTERFACE_ADDED, sw1Eth4, 500L));
        verify(flowObjectiveService);
    }

    @Test
    public void testRemoveInterface() {
        ConnectPoint sw1eth4 = new ConnectPoint(DEVICE_ID, PortNumber.portNumber(4));
        Set<InterfaceIpAddress> interfaceIpAddresses4 = Sets.newHashSet();
        interfaceIpAddresses4
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.40.101"), IpPrefix.valueOf("192.168.40.0/24")));

        Interface sw1Eth4 = new Interface(sw1eth4.deviceId().toString(), sw1eth4, interfaceIpAddresses4,
                MacAddress.valueOf("00:00:00:00:00:04"), VlanId.NONE);
        EasyMock.reset(flowObjectiveService);
        expect(flowObjectiveService.allocateNextId()).andReturn(1).anyTimes();

        setUpInterfaceConfiguration(sw1Eth4, false);
        replay(flowObjectiveService);
        interfaceListener.event(new InterfaceEvent(InterfaceEvent.Type.INTERFACE_REMOVED, sw1Eth4, 500L));
        verify(flowObjectiveService);
    }

    /**
     * Setup flow Configuration for all configured Interfaces.
     *
     **/
    private void setUpFlowObjectiveService() {
        expect(flowObjectiveService.allocateNextId()).andReturn(1).anyTimes();
        for (Interface intf : interfaceService.getInterfaces()) {
            setUpInterfaceConfiguration(intf, true);
        }
        replay(flowObjectiveService);
    }

    /**
     * Setting up flowobjective expectations for basic forwarding and ospf.
     **/
    private void setUpInterfaceConfiguration(Interface intf, boolean install) {
        DeviceId deviceId = controlPlaneConnectPoint.deviceId();
        PortNumber controlPlanePort = controlPlaneConnectPoint.port();

        for (InterfaceIpAddress ip : intf.ipAddresses()) {
            int cpNextId, intfNextId;

            cpNextId = modifyNextObjective(deviceId, controlPlanePort,
                    VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN), true, install);
            intfNextId = modifyNextObjective(deviceId, intf.connectPoint().port(),
                    VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN), true, install);

            // IPv4 to router
            TrafficSelector toSelector = DefaultTrafficSelector.builder().matchInPort(intf.connectPoint().port())
                    .matchEthDst(intf.mac()).matchEthType(EthType.EtherType.IPV4.ethType().toShort())
                    .matchVlanId(intf.vlan()).matchIPDst(ip.ipAddress().toIpPrefix()).build();

            flowObjectiveService.forward(deviceId, buildForwardingObjective(toSelector, null, cpNextId, install));
            expectLastCall().once();
            // IPv4 from router
            TrafficSelector fromSelector = DefaultTrafficSelector.builder().matchInPort(controlPlanePort)
                    .matchEthSrc(intf.mac()).matchVlanId(intf.vlan())
                    .matchEthType(EthType.EtherType.IPV4.ethType().toShort()).matchIPSrc(ip.ipAddress().toIpPrefix())
                    .build();

            flowObjectiveService.forward(deviceId, buildForwardingObjective(fromSelector, null, intfNextId, install));
            expectLastCall().once();
            // ARP to router
            toSelector = DefaultTrafficSelector.builder().matchInPort(intf.connectPoint().port())
                    .matchEthType(EthType.EtherType.ARP.ethType().toShort()).matchVlanId(intf.vlan()).build();

            TrafficTreatment puntTreatment = DefaultTrafficTreatment.builder().punt().build();

            flowObjectiveService.forward(deviceId,
                    buildForwardingObjective(toSelector, puntTreatment, cpNextId, install));
            expectLastCall().once();
            // ARP from router
            fromSelector = DefaultTrafficSelector.builder().matchInPort(controlPlanePort).matchEthSrc(intf.mac())
                    .matchVlanId(intf.vlan()).matchEthType(EthType.EtherType.ARP.ethType().toShort())
                    .matchArpSpa(ip.ipAddress().getIp4Address()).build();

            flowObjectiveService.forward(deviceId,
                    buildForwardingObjective(fromSelector, puntTreatment, intfNextId, install));
            expectLastCall().once();
        }
        // setting expectations for ospf forwarding.
        TrafficSelector toSelector = DefaultTrafficSelector.builder().matchInPort(intf.connectPoint().port())
                .matchEthType(EthType.EtherType.IPV4.ethType().toShort()).matchVlanId(intf.vlan())
                .matchIPProtocol((byte) OSPF_IP_PROTO).build();

        modifyNextObjective(deviceId, controlPlanePort, VlanId.vlanId((short) 4094), true, install);
        flowObjectiveService.forward(controlPlaneConnectPoint.deviceId(),
                buildForwardingObjective(toSelector, null, 1, install));
        expectLastCall().once();
    }

    /**
     * Setup expectations on flowObjectiveService.next for NextObjective.
     *
     **/
    private int modifyNextObjective(DeviceId deviceId, PortNumber portNumber, VlanId vlanId, boolean popVlan,
            boolean modifyFlag) {
        NextObjective.Builder nextObjBuilder = DefaultNextObjective.builder().withId(1)
                .withType(NextObjective.Type.SIMPLE).fromApp(APPID);

        TrafficTreatment.Builder ttBuilder = DefaultTrafficTreatment.builder();
        if (popVlan) {
            ttBuilder.popVlan();
        }
        ttBuilder.setOutput(portNumber);

        TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
        metabuilder.matchVlanId(vlanId);

        nextObjBuilder.withMeta(metabuilder.build());
        nextObjBuilder.addTreatment(ttBuilder.build());
        if (modifyFlag) {
            flowObjectiveService.next(deviceId, nextObjBuilder.add());
            expectLastCall().once();
        } else {
            flowObjectiveService.next(deviceId, nextObjBuilder.remove());
            expectLastCall().once();
        }
        return 1;
    }

    /**
     * Setup Interface expectation for all Testcases.
     **/
    private void setUpInterfaceService() {
        Set<InterfaceIpAddress> interfaceIpAddresses1 = Sets.newHashSet();
        interfaceIpAddresses1
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.10.101"), IpPrefix.valueOf("192.168.10.0/24")));
        Interface sw1Eth1 = new Interface(SW1_ETH1.deviceId().toString(), SW1_ETH1, interfaceIpAddresses1,
                MacAddress.valueOf("00:00:00:00:00:01"), VlanId.NONE);
        interfaces.add(sw1Eth1);

        Set<InterfaceIpAddress> interfaceIpAddresses2 = Sets.newHashSet();
        interfaceIpAddresses2
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.20.101"), IpPrefix.valueOf("192.168.20.0/24")));
        Interface sw1Eth2 = new Interface(SW1_ETH1.deviceId().toString(), SW1_ETH2, interfaceIpAddresses2,
                MacAddress.valueOf("00:00:00:00:00:02"), VlanId.NONE);
        interfaces.add(sw1Eth2);

        Set<InterfaceIpAddress> interfaceIpAddresses3 = Sets.newHashSet();
        interfaceIpAddresses3
                .add(new InterfaceIpAddress(IpAddress.valueOf("192.168.30.101"), IpPrefix.valueOf("192.168.30.0/24")));
        Interface sw1Eth3 = new Interface(SW1_ETH1.deviceId().toString(), SW1_ETH3, interfaceIpAddresses3,
                MacAddress.valueOf("00:00:00:00:00:03"), VlanId.NONE);
        interfaces.add(sw1Eth3);

    }

    private ForwardingObjective buildForwardingObjective(TrafficSelector selector, TrafficTreatment treatment,
            int nextId, boolean add) {
        DefaultForwardingObjective.Builder fobBuilder = DefaultForwardingObjective.builder();
        fobBuilder.withSelector(selector);
        if (treatment != null) {
            fobBuilder.withTreatment(treatment);
        }
        if (nextId != -1) {
            fobBuilder.nextStep(nextId);
        }
        fobBuilder.fromApp(APPID).withPriority(40001).withFlag(ForwardingObjective.Flag.VERSATILE);

        return add ? fobBuilder.add() : fobBuilder.remove();
    }

    private class TestCoreService extends CoreServiceAdapter {

        @Override
        public ApplicationId getAppId(String name) {
            return APPID;
        }

        @Override
        public ApplicationId registerApplication(String name) {
            return new TestApplicationId(name);
        }

    }

    private class TestDeviceService extends DeviceServiceAdapter {

        @Override
        public boolean isAvailable(DeviceId deviceId) {
            boolean flag = false;
            if (deviceId.equals(controlPlaneConnectPoint.deviceId())) {
                flag = true;
            }
            return flag;
        }

        @Override
        public void addListener(DeviceListener listener) {
            ControlPlaneRedirectManagerTest.this.deviceListener = listener;
        }

    }

    private class TestRouterConfig extends RouterConfig {

        @Override
        public ConnectPoint getControlPlaneConnectPoint() {
            return controlPlaneConnectPoint;
        }

        @Override
        public boolean getOspfEnabled() {
            return true;
        }

        @Override
        public List<String> getInterfaces() {
            ArrayList<String> interfaces = new ArrayList<>();
            interfaces.add("of:0000000000000001");
            interfaces.add("of:0000000000000001/2");
            interfaces.add("of:0000000000000001/3");
            return interfaces;
        }

    }

    private class TestNetworkConfigService extends NetworkConfigServiceAdapter {

        @Override
        public void addListener(NetworkConfigListener listener) {
            ControlPlaneRedirectManagerTest.this.networkConfigListener = listener;
        }

        @Override
        public <S, C extends Config<S>> C getConfig(S subject, Class<C> configClass) {
            return (C) ControlPlaneRedirectManagerTest.this.routerConfig;
        }

    }

    private static class TestApplicationId implements ApplicationId {

        private final String name;
        private final short id;

        public TestApplicationId(String name) {
            this.name = name;
            this.id = (short) Objects.hash(name);
        }

        public static ApplicationId create(String name) {
            return new TestApplicationId(name);
        }

        @Override
        public short id() {
            return id;
        }

        @Override
        public String name() {
            return name;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + id;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            TestApplicationId other = (TestApplicationId) obj;
            if (id != other.id) {
                return false;
            }
            if (name == null) {
                if (other.name != null) {
                    return false;
                }
            } else if (!name.equals(other.name)) {
                return false;
            }
            return true;
        }
    }

    private class InternalMastershipServiceTest extends MastershipServiceAdapter {

        @Override
        public boolean isLocalMaster(DeviceId deviceId) {
            boolean flag = deviceId.equals(controlPlaneConnectPoint.deviceId());
            return flag;
        }

    }

    private class InternalInterfaceService extends InterfaceServiceAdapter {

        @Override
        public void addListener(InterfaceListener listener) {
            ControlPlaneRedirectManagerTest.this.interfaceListener = listener;
        }

        @Override
        public Set<Interface> getInterfaces() {
            return interfaces;
        }

        @Override
        public Set<Interface> getInterfacesByPort(ConnectPoint port) {
            Set<Interface> setIntf = new HashSet<Interface>();
            for (Interface intf : interfaces) {
                if (intf.connectPoint().equals(port)) {
                    setIntf.add(intf);
                }
            }
            return setIntf;
        }

        @Override
        public Interface getMatchingInterface(IpAddress ip) {
            Interface intff = null;
            for (Interface intf : interfaces) {
                for (InterfaceIpAddress address : intf.ipAddresses()) {
                    if (address.ipAddress().equals(ip)) {
                        intff = intf;
                        break;
                    }
                }
            }

            return intff;
        }

    }
}


text:
module powerbi.visuals {
    export var slicerCapabilities: VisualCapabilities = {
        dataRoles: [
            {
                name: 'Values',
                kind: VisualDataRoleKind.Grouping,
                displayName: powerbi.data.createDisplayNameGetter('Role_DisplayName_Field'),
            }
        ],
        dataViewMappings: [{
            conditions: [{ 'Values': { max: 1 } }],
            categorical: {
                categories: {
                    for: { in: 'Values' },
                    dataReductionAlgorithm: { window: {} }
                },
                includeEmptyGroups: true,
            }
        }],
        objects: {
            general: {
                properties: {
                    selected: {
                        type: { bool: true }
                    },
                    filter: {
                        type: { filter: {} },
                        rule: {
                            output: {
                                property: 'selected',
                                selector: ['Values'],
                            }
                        }
                    },
                    formatString: {
                        type: { formatting: { formatString: true } },
                    },
                }
            }
        },
        sorting: {
            default: {},
        },
        suppressDefaultTitle: true,
    };

    export var slicerProps = {
        selectedPropertyIdentifier: <DataViewObjectPropertyIdentifier>{
            objectName: 'general',
            propertyName: 'selected'
        },

        filterPropertyIdentifier: <DataViewObjectPropertyIdentifier> {
            objectName: 'general',
            propertyName: 'filter'
        },

        formatString: <DataViewObjectPropertyIdentifier> {
            objectName: 'general',
            propertyName: 'formatString'
        },
    };

}


text:
#ifndef _DAC_UTIL_H_
#define _DAC_UTIL_H_

#define __STDC_LIMIT_MACROS
#include <stdint.h>

// --- DAC_config_t

struct _DAC_config_t
{
  uint8_t num_bits;
  uint16_t resolution;
  float vref;
};
typedef _DAC_config_t DAC_config_t;

uint16_t dac_config_max_code(DAC_config_t *dac_config);

// --- DAC_data_t

struct _DAC_data_t
{
  DAC_config_t *config;
  bool gain;
  uint16_t code;
};
typedef struct _DAC_data_t DAC_data_t;

bool dac_data_set_code(DAC_data_t *dac_data, uint16_t code);

bool dac_data_increment_code(DAC_data_t *dac_data);
bool dac_data_decrement_code(DAC_data_t *dac_data);

bool dac_data_set_voltage(DAC_data_t *dac_data, float voltage);

#endif


text:
#include "stdafx.h"
#include "jsonrpc/response_serializer.h"
#include "jsonrpc/value.h"
#include "jsonrpc/writer.h"
#include "rpc/value.h"
#include "rpc/exception.h"
#include <cassert>

namespace JsonRpc
{

const std::string kMIME_TYPE = "application/json";

struct ResponseSerializerImpl {
    Json::FastWriter writer;
};

ResponseSerializer::ResponseSerializer()
    :
    impl_(new ResponseSerializerImpl)
{}

ResponseSerializer::~ResponseSerializer()
{
    delete impl_;
}

void convertRpcValueToJsonRpcValue(const Rpc::Value& rpc_value, Json::Value* json_rpc_value); // throws Rpc::Exception

void ResponseSerializer::serializeSuccess(const Rpc::Value& root_response, std::string* response) const
{
    Json::Value jsonrpc_response;
    convertRpcValueToJsonRpcValue(root_response, &jsonrpc_response);
    jsonrpc_response["jsonrpc"] = "2.0";

    *response = impl_->writer.write(jsonrpc_response);
}

void ResponseSerializer::serializeFault(const Rpc::Value& root_request, const std::string& error_msg, int error_code, std::string* response) const
{
    Json::Value response_value;

    if ( root_request.isMember("id") ) {
        convertRpcValueToJsonRpcValue(root_request["id"], &response_value["id"]);
    } else {
        response_value["id"] = Json::Value::null;
    }

    response_value["jsonrpc"] = "2.0";

    Json::Value& error = response_value["error"];
    error["message"] = error_msg;
    error["code"] = error_code;

    *response = impl_->writer.write(response_value);
}

const std::string& ResponseSerializer::mimeType() const
{
    return kMIME_TYPE;
}

void convertRpcValueToJsonRpcValue(const Rpc::Value& rpc_value, Json::Value* json_rpc_value) // throws Rpc::Exception
{
    assert(json_rpc_value);

    switch ( rpc_value.type() ) {
    case Rpc::Value::TYPE_NONE:
        // treat none rpc value as null json value. ///???
    case Rpc::Value::TYPE_NULL:
        Json::Value().swap(*json_rpc_value);
        break;
    case Rpc::Value::TYPE_BOOL:
        *json_rpc_value = bool(rpc_value);
        break;
    case Rpc::Value::TYPE_INT:
        *json_rpc_value = int(rpc_value);
        break;
    case Rpc::Value::TYPE_UINT:
        *json_rpc_value = unsigned int(rpc_value);
        break;
    case Rpc::Value::TYPE_DOUBLE:
        *json_rpc_value = double(rpc_value);
        break;
    case Rpc::Value::TYPE_STRING:
        *json_rpc_value = static_cast<const std::string&>(rpc_value);
        break;
    case Rpc::Value::TYPE_ARRAY:
        json_rpc_value->resize( rpc_value.size() );
        for (size_t i = 0, size = json_rpc_value->size(); i != size; ++i) {
            convertRpcValueToJsonRpcValue(rpc_value[i], &((*json_rpc_value)[i]));
        }
        break;
    case Rpc::Value::TYPE_OBJECT:
        {
        *json_rpc_value = Json::Value();
        auto member_it = rpc_value.getObjectMembersBegin(),
             end       = rpc_value.getObjectMembersEnd();
        for (; member_it != end; ++member_it) {
            convertRpcValueToJsonRpcValue( member_it->second, &((*json_rpc_value)[member_it->first]) );
        }
        }
        break;
    default:
        throw Rpc::Exception("unknown type", Rpc::TYPE_ERROR);
    }
}

} // namespace JsonRpc


text:
import React from 'react';
import StyleSheet from 'react-inline';
import cx from 'classnames';

//require('requirish')._(module);
//var SuperButton = require('src/other/SuperButton');
//var appUtil = require('src/appUtil');

//import SuperButton from './src/other/SuperButton';
//import appUtil from './src/appUtil';
//appUtil.hi();

const { oneOf, bool } = React.PropTypes;

class Button extends React.Component {
  render() {
    const { size, busy, block, className } = this.props;
    const classes = cx(styles.default, styles[size], block && styles.block, className);

    return <button {...this.props} className={classes} disabled={busy} >adda</button>;
  }
}

Button.propTypes = {
  size:   oneOf(['large', 'small']),
  block:  bool,
  busy:   bool
};

export default Button;
export function rixContext() {
	//
	var a = 33;
	var b = 44;
	return { size: a+b / a, lineHeight: a+"px" };
};

const { size, lineHeight } = rixContext();

	//rixContext: function() {
//
	//}
//};

const styles = StyleSheet.create({
  default: {
    padding: '6px 12px',
    fontSize: size,
    lineHeight: lineHeight,
    cursor: 'pointer',
    border: '1px solid #2e6da4',
    borderRadius: 40,
    color: '#fff',
    backgroundColor: '#337ab7',

    '@media only screen and (max-width: 640px)': {
      display: 'block',
      width: '100%'
    },

    ':focus': {
      color: '#fff',
      backgroundColor: '#286090',
      borderColor: '#122b40'
    },

    '[disabled]': {
      backgroundColor: '#337ab7',
      borderColor: '#2e6da4',
      cursor: 'not-allowed',
      boxShadow: 'none',
      opacity: .65,
      pointerEvents: 'none'
    }
  },

  large: {
    padding: '10px 16px',
    fontSize: 18,
    lineHeight: 1.33,
    borderRadius: 6
  },

  small: {
    padding: '5px 10px',
    fontSize: 12,
    lineHeight: 1.5,
    borderRadius: 3
  },

  block: {
    display: 'block',
    width: '100%'
  }
});


text:
using namespace boost;
using namespace gil;

BOOST_AUTO_TEST_SUITE( toolbox_tests )

BOOST_AUTO_TEST_CASE( pixel_bit_size_test )
{
    typedef bit_aligned_image5_type< 16, 16, 16, 8, 8, devicen_layout_t< 5 > >::type image_t;
    BOOST_STATIC_ASSERT(( pixel_bit_size<image_t::view_t::reference>::value == 64 ));
}

BOOST_AUTO_TEST_SUITE_END()


text:
#pragma once
#ifdef WIN32

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif
#define _CRT_SECURE_NO_DEPRECATE 1
#define _CRT_NONSTDC_NO_DEPRECATE 1

#include <iostream>
#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here
//&&Str Class Support
//Do not remove any lines from this block; refer to documentation
//  about conditional defines and their function
#define STR_WIN32
#define STR_THREAD_SAFE
#define STR_DEFINES_DONE
#define STR_USE_REGEX
#include "../libbiokanga/str.h"
//&&End of Str Class Support
#endif


text: a simple wiki


text:
<!DOCTYPE html>

<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script type="text/javascript">
'use strict';
for (let eventType of ["GamepadEvent"]) {
    test(function() {
        let before = performance.now();
        let e = new window[eventType]('test');
        let after = performance.now();
        assert_greater_than_equal(e.timeStamp, before, "Event timestamp should be greater than performance.now() timestamp taken before its creation");
        assert_less_than_equal(e.timeStamp, after, "Event timestamp should be less than performance.now() timestamp taken after its creation");
    }, `Constructed ${eventType} timestamp should be high resolution and have the same time origin as performance.now()`);
}
</script>


text:
<?php

namespace Oro\Bundle\SearchBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class FilterTypesPass implements CompilerPassInterface
{
    const FILTER_EXTENSION_ID = 'oro_search.extension.search_filter';
    const TAG_NAME            = 'oro_search.extension.search_filter.filter';

    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        /**
         * Find and add available filters to extension
         */
        $extension = $container->getDefinition(self::FILTER_EXTENSION_ID);
        if ($extension) {
            $filters = $container->findTaggedServiceIds(self::TAG_NAME);
            foreach ($filters as $serviceId => $tags) {
                $tagAttrs = reset($tags);
                if (!isset($tagAttrs['datasource']) || 'search' !== $tagAttrs['datasource']) {
                    continue;
                }
                if ($container->hasDefinition($serviceId)) {
                    $container->getDefinition($serviceId)->setPublic(false);
                }
                $extension->addMethodCall('addFilter', [$tagAttrs['type'], new Reference($serviceId)]);
            }
        }
    }
}


text:
/**
 * @fileoverview Prevent creating unstable components inside components
 * @author Ari Perkkiö
 */

'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const RuleTester = require('eslint').RuleTester;
const rule = require('../../../lib/rules/no-unstable-nested-components');

const parsers = require('../../helpers/parsers');

const parserOptions = {
  ecmaVersion: 2018,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true,
  },
};

const ERROR_MESSAGE = 'Declare this component outside parent component "ParentComponent" or memoize it.';
const ERROR_MESSAGE_WITHOUT_NAME = 'Declare this component outside parent component or memoize it.';
const ERROR_MESSAGE_COMPONENT_AS_PROPS = `${ERROR_MESSAGE} If you want to allow component creation in props, set allowAsProps option to true.`;

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = new RuleTester({ parserOptions });
ruleTester.run('no-unstable-nested-components', rule, {
  valid: parsers.all([
    {
      code: `
        function ParentComponent() {
          return (

              <OutsideDefinedFunctionComponent />

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return React.createElement(
            "div",
            null,
            React.createElement(OutsideDefinedFunctionComponent, null)
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return (
            <SomeComponent
              footer={<OutsideDefinedComponent />}
              header={
}
              />
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return React.createElement(SomeComponent, {
            footer: React.createElement(OutsideDefinedComponent, null),
            header: React.createElement("div", null)
          });
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          const MemoizedNestedComponent = React.useCallback(() =>
, []);

          return (

              <MemoizedNestedComponent />

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          const MemoizedNestedComponent = React.useCallback(
            () => React.createElement("div", null),
            []
          );

          return React.createElement(
            "div",
            null,
            React.createElement(MemoizedNestedComponent, null)
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          const MemoizedNestedFunctionComponent = React.useCallback(
            function () {
              return
;
            },
            []
          );

          return (

              <MemoizedNestedFunctionComponent />

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          const MemoizedNestedFunctionComponent = React.useCallback(
            function () {
              return React.createElement("div", null);
            },
            []
          );

          return React.createElement(
            "div",
            null,
            React.createElement(MemoizedNestedFunctionComponent, null)
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          // Should not interfere handler declarations
          function onClick(event) {
            props.onClick(event.target.value);
          }

          const onKeyPress = () => null;

          function getOnHover() {
            return function onHover(event) {
              props.onHover(event.target);
            }
          }

          return (

              <button
                onClick={onClick}
                onKeyPress={onKeyPress}
                onHover={getOnHover()}

                // These should not be considered as components
                maybeComponentOrHandlerNull={() => null}
                maybeComponentOrHandlerUndefined={() => undefined}
                maybeComponentOrHandlerBlank={() => ''}
                maybeComponentOrHandlerString={() => 'hello-world'}
                maybeComponentOrHandlerNumber={() => 42}
                maybeComponentOrHandlerArray={() => []}
                maybeComponentOrHandlerObject={() => {}} />

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          function getComponent() {
            return
;
          }

          return (

              {getComponent()}

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          function getComponent() {
            return React.createElement("div", null);
          }

          return React.createElement("div", null, getComponent());
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
            return (
              <RenderPropComponent>
                {() =>
}
              </RenderPropComponent>
            );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
            return (
              <RenderPropComponent children={() =>
} />
            );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return (
            <ComplexRenderPropComponent
              listRenderer={data.map((items, index) => (

                  {items[index].map((item) =>

                      {item}

                  )}

              ))
              }
            />
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return React.createElement(
              RenderPropComponent,
              null,
              () => React.createElement("div", null)
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          return (

              {props.items.map(item => (

                  {item.name}

              ))}

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          return (
            <List items={props.items.map(item => {
              return (

                  {item.name}

              );
            })}
            />
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          return React.createElement(
            "ul",
            null,
            props.items.map(() =>
              React.createElement(
                "li",
                { key: item.id },
                item.name
              )
            )
          )
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          return (

              {props.items.map(function Item(item) {
                return (

                    {item.name}

                );
              })}

          );
        }
      `,
    },
    {
      code: `
        function ParentComponent(props) {
          return React.createElement(
            "ul",
            null,
            props.items.map(function Item() {
              return React.createElement(
                "li",
                { key: item.id },
                item.name
              );
            })
          );
        }
      `,
    },
    {
      code: `
        function createTestComponent(props) {
          return (

          );
        }
      `,
    },
    {
      code: `
        function createTestComponent(props) {
          return React.createElement("div", null);
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return (
            <ComponentWithProps footer={() =>
} />
          );
        }
      `,
      options: [{ allowAsProps: true }],
    },
    {
      code: `
        function ParentComponent() {
          return React.createElement(ComponentWithProps, {
            footer: () => React.createElement("div", null)
          });
        }
      `,
      options: [{ allowAsProps: true }],
    },
    {
      code: `
        function ParentComponent() {
          return (
            <SomeComponent item={{ children: () =>
 }} />
          )
        }
      `,
      options: [{ allowAsProps: true }],
    },
    {
      code: `
      function ParentComponent() {
        return (
          <SomeComponent>
            {
              thing.match({
                renderLoading: () =>
,
                renderSuccess: () =>
,
                renderFailure: () =>
,
              })
            }
          </SomeComponent>
        )
      }
      `,
    },
    {
      code: `
      function ParentComponent() {
        const thingElement = thing.match({
          renderLoading: () =>
,
          renderSuccess: () =>
,
          renderFailure: () =>
,
        });
        return (
          <SomeComponent>
            {thingElement}
          </SomeComponent>
        )
      }
      `,
    },
    {
      code: `
      function ParentComponent() {
        return (
          <SomeComponent>
            {
              thing.match({
                loading: () =>
,
                success: () =>
,
                failure: () =>
,
              })
            }
          </SomeComponent>
        )
      }
      `,
      options: [{
        allowAsProps: true,
      }],
    },
    {
      code: `
      function ParentComponent() {
        const thingElement = thing.match({
          loading: () =>
,
          success: () =>
,
          failure: () =>
,
        });
        return (
          <SomeComponent>
            {thingElement}
          </SomeComponent>
        )
      }
      `,
      options: [{
        allowAsProps: true,
      }],
    },
    {
      code: `
        function ParentComponent() {
          return (
            <ComponentForProps renderFooter={() =>
} />
          );
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return React.createElement(ComponentForProps, {
            renderFooter: () => React.createElement("div", null)
          });
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          useEffect(() => {
            return () => null;
          });

          return
;
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return (
            <SomeComponent renderers={{ Header: () =>
 }} />
          )
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return (
            <SomeComponent renderMenu={() => (
              <RenderPropComponent>
                {items.map(item => (

{item}

                ))}
              </RenderPropComponent>
            )} />
          )
        }
      `,
    },
    {
      code: `
        const ParentComponent = () => (
          <SomeComponent
            components={[

                {list.map(item => (

{item}

                ))}

,
            ]}
          />
        );
     `,
    },
    {
      code: `
        function ParentComponent() {
          const rows = [
            {
              name: 'A',
              render: (props) => <Row {...props} />
            },
          ];

          return
;
        }
      `,
    },
    {
      code: `
        function ParentComponent() {
          return <SomeComponent renderers={{ notComponent: () => null }} />;
        }
      `,
    },
    {
      code: `
        const ParentComponent = createReactClass({
          displayName: "ParentComponent",
          statics: {
            getSnapshotBeforeUpdate: function () {
              return null;
            },
          },
          render() {
            return
;
          },
        });
      `,
    },
    {
      code: `
        function ParentComponent() {
          const rows = [
            {
              name: 'A',
              notPrefixedWithRender: (props) => <Row {...props} />
            },
          ];

          return
;
        }
      `,
      options: [{
        allowAsProps: true,
      }],
    },
    /* TODO These minor cases are currently falsely marked due to component detection
    {
      code: `
        function ParentComponent() {
          const _renderHeader = () =>
;
          return
{_renderHeader()}
;
        }
      `
    },
    {
      // https://github.com/emotion-js/emotion/blob/a89d4257b0246a1640a99f77838e5edad4ec4386/packages/jest/test/react-enzyme.test.js#L26-L28
      code: `
        const testCases = {
          basic: {
            render() {
              const Component = () =>
;
              return
;
            }
          }
        }
        `
    },
    */
  ]),

  invalid: parsers.all([
    {
      code: `
        function ParentComponent() {
          function UnstableNestedFunctionComponent() {
            return
;
          }

          return (

              <UnstableNestedFunctionComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          function UnstableNestedFunctionComponent() {
            return React.createElement("div", null);
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedFunctionComponent, null)
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          const UnstableNestedVariableComponent = () => {
            return
;
          }

          return (

              <UnstableNestedVariableComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          const UnstableNestedVariableComponent = () => {
            return React.createElement("div", null);
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedVariableComponent, null)
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        const ParentComponent = () => {
          function UnstableNestedFunctionComponent() {
            return
;
          }

          return (

              <UnstableNestedFunctionComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        const ParentComponent = () => {
          function UnstableNestedFunctionComponent() {
            return React.createElement("div", null);
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedFunctionComponent, null)
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        export default () => {
          function UnstableNestedFunctionComponent() {
            return
;
          }

          return (

              <UnstableNestedFunctionComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE_WITHOUT_NAME }],
    },
    {
      code: `
        export default () => {
          function UnstableNestedFunctionComponent() {
            return React.createElement("div", null);
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedFunctionComponent, null)
          );
        };
      `,
      errors: [{ message: ERROR_MESSAGE_WITHOUT_NAME }],
    },
    {
      code: `
        const ParentComponent = () => {
          const UnstableNestedVariableComponent = () => {
            return
;
          }

          return (

              <UnstableNestedVariableComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        const ParentComponent = () => {
          const UnstableNestedVariableComponent = () => {
            return React.createElement("div", null);
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedVariableComponent, null)
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          class UnstableNestedClassComponent extends React.Component {
            render() {
              return
;
            }
          };

          return (

              <UnstableNestedClassComponent />

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          class UnstableNestedClassComponent extends React.Component {
            render() {
              return React.createElement("div", null);
            }
          }

          return React.createElement(
            "div",
            null,
            React.createElement(UnstableNestedClassComponent, null)
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            class UnstableNestedClassComponent extends React.Component {
              render() {
                return
;
              }
            };

            return (

                <UnstableNestedClassComponent />

            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            class UnstableNestedClassComponent extends React.Component {
              render() {
                return React.createElement("div", null);
              }
            }

            return React.createElement(
              "div",
              null,
              React.createElement(UnstableNestedClassComponent, null)
            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            function UnstableNestedFunctionComponent() {
              return
;
            }

            return (

                <UnstableNestedFunctionComponent />

            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            function UnstableNestedClassComponent() {
              return React.createElement("div", null);
            }

            return React.createElement(
              "div",
              null,
              React.createElement(UnstableNestedClassComponent, null)
            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            const UnstableNestedVariableComponent = () => {
              return
;
            }

            return (

                <UnstableNestedVariableComponent />

            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            const UnstableNestedClassComponent = () => {
              return React.createElement("div", null);
            }

            return React.createElement(
              "div",
              null,
              React.createElement(UnstableNestedClassComponent, null)
            );
          }
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          function getComponent() {
            function NestedUnstableFunctionComponent() {
              return
;
            };

            return <NestedUnstableFunctionComponent />;
          }

          return (

              {getComponent()}

          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ParentComponent() {
          function getComponent() {
            function NestedUnstableFunctionComponent() {
              return React.createElement("div", null);
            }

            return React.createElement(NestedUnstableFunctionComponent, null);
          }

          return React.createElement("div", null, getComponent());
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ComponentWithProps(props) {
          return
;
        }

        function ParentComponent() {
          return (
            <ComponentWithProps
              footer={
                function SomeFooter() {
                  return
;
                }
              } />
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ComponentWithProps(props) {
          return React.createElement("div", null);
        }

        function ParentComponent() {
          return React.createElement(ComponentWithProps, {
            footer: function SomeFooter() {
              return React.createElement("div", null);
            }
          });
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ComponentWithProps(props) {
          return
;
        }

        function ParentComponent() {
            return (
              <ComponentWithProps footer={() =>
} />
            );
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ComponentWithProps(props) {
          return React.createElement("div", null);
        }

        function ParentComponent() {
          return React.createElement(ComponentWithProps, {
            footer: () => React.createElement("div", null)
          });
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ParentComponent() {
            return (
              <RenderPropComponent>
                {() => {
                  function UnstableNestedComponent() {
                    return
;
                  }

                  return (

                      <UnstableNestedComponent />

                  );
                }}
              </RenderPropComponent>
            );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function RenderPropComponent(props) {
          return props.render({});
        }

        function ParentComponent() {
          return React.createElement(
            RenderPropComponent,
            null,
            () => {
              function UnstableNestedComponent() {
                return React.createElement("div", null);
              }

              return React.createElement(
                "div",
                null,
                React.createElement(UnstableNestedComponent, null)
              );
            }
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
        function ComponentForProps(props) {
          return
;
        }

        function ParentComponent() {
          return (
            <ComponentForProps notPrefixedWithRender={() =>
} />
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ComponentForProps(props) {
          return React.createElement("div", null);
        }

        function ParentComponent() {
          return React.createElement(ComponentForProps, {
            notPrefixedWithRender: () => React.createElement("div", null)
          });
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        function ParentComponent() {
          return (
            <ComponentForProps someMap={{ Header: () =>
 }} />
          );
        }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
    {
      code: `
        class ParentComponent extends React.Component {
          render() {
            const List = (props) => {
              const items = props.items
                .map((item) => (

                    {item.name}

                ));

              return
{items}
;
            };

            return <List {...this.props} />;
          }
        }
      `,
      // Only a single error should be shown. This can get easily marked twice.
      errors: [{ message: ERROR_MESSAGE }],
    },
    {
      code: `
      function ParentComponent() {
        return (
          <SomeComponent>
            {
              thing.match({
                loading: () =>
,
                success: () =>
,
                failure: () =>
,
              })
            }
          </SomeComponent>
        )
      }
      `,
      errors: [
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
      ],
    },
    {
      code: `
      function ParentComponent() {
        const thingElement = thing.match({
          loading: () =>
,
          success: () =>
,
          failure: () =>
,
        });
        return (
          <SomeComponent>
            {thingElement}
          </SomeComponent>
        )
      }
      `,
      errors: [
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
        { message: ERROR_MESSAGE_COMPONENT_AS_PROPS },
      ],
    },
    {
      code: `
      function ParentComponent() {
        const rows = [
          {
            name: 'A',
            notPrefixedWithRender: (props) => <Row {...props} />
          },
        ];

        return
;
      }
      `,
      errors: [{ message: ERROR_MESSAGE_COMPONENT_AS_PROPS }],
    },
  ]),
});


text:
make DEBUG=1 clean
make DEBUG=1


text:
/*	$NetBSD: radix.h,v 1.1.1.2.4.1 2014/12/24 00:05:18 riz Exp $	*/

/*
 * Copyright (C) 2007, 2008  Internet Systems Consortium, Inc. ("ISC")
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* Id: radix.h,v 1.13 2008/12/01 23:47:45 tbox Exp  */

/*
 * This source was adapted from MRT's RCS Ids:
 * Id: radix.h,v 1.6 1999/08/03 03:32:53 masaki Exp
 * Id: mrt.h,v 1.57.2.6 1999/12/28 23:41:27 labovit Exp
 * Id: defs.h,v 1.5.2.2 2000/01/15 14:19:16 masaki Exp
 */

#include <isc/magic.h>
#include <isc/types.h>
#include <isc/mutex.h>
#include <isc/net.h>
#include <isc/refcount.h>

#include <string.h>

#ifndef _RADIX_H
#define _RADIX_H

#define NETADDR_TO_PREFIX_T(na,pt,bits) \
	do { \
		memset(&(pt), 0, sizeof(pt)); \
		if((na) != NULL) { \
			(pt).family = (na)->family; \
			(pt).bitlen = (bits); \
			if ((pt).family == AF_INET6) { \
				memcpy(&(pt).add.sin6, &(na)->type.in6, \
				       ((bits)+7)/8); \
			} else \
				memcpy(&(pt).add.sin, &(na)->type.in, \
				       ((bits)+7)/8); \
		} else { \
			(pt).family = AF_UNSPEC; \
			(pt).bitlen = 0; \
		} \
		isc_refcount_init(&(pt).refcount, 0); \
	} while(0)

typedef struct isc_prefix {
    unsigned int family;	/* AF_INET | AF_INET6, or AF_UNSPEC for "any" */
    unsigned int bitlen;	/* 0 for "any" */
    isc_refcount_t refcount;
    union {
		struct in_addr sin;
		struct in6_addr sin6;
    } add;
} isc_prefix_t;

typedef void (*isc_radix_destroyfunc_t)(void *);
typedef void (*isc_radix_processfunc_t)(isc_prefix_t *, void **);

#define isc_prefix_tochar(prefix) ((char *)&(prefix)->add.sin)
#define isc_prefix_touchar(prefix) ((u_char *)&(prefix)->add.sin)

#define BIT_TEST(f, b)  ((f) & (b))

/*
 * We need "first match" when we search the radix tree to preserve
 * compatibility with the existing ACL implementation. Radix trees
 * naturally lend themselves to "best match". In order to get "first match"
 * behavior, we keep track of the order in which entries are added to the
 * tree--and when a search is made, we find all matching entries, and
 * return the one that was added first.
 *
 * An IPv4 prefix and an IPv6 prefix may share a radix tree node if they
 * have the same length and bit pattern (e.g., 127/8 and 7f::/8).  To
 * disambiguate between them, node_num and data are two-element arrays;
 * node_num[0] and data[0] are used for IPv4 addresses, node_num[1]
 * and data[1] for IPv6 addresses.  The only exception is a prefix of
 * 0/0 (aka "any" or "none"), which is always stored as IPv4 but matches
 * IPv6 addresses too.
 */

#define ISC_IS6(family) ((family) == AF_INET6 ? 1 : 0)
typedef struct isc_radix_node {
   isc_uint32_t bit;			/* bit length of the prefix */
   isc_prefix_t *prefix;		/* who we are in radix tree */
   struct isc_radix_node *l, *r;	/* left and right children */
   struct isc_radix_node *parent;	/* may be used */
   void *data[2];			/* pointers to IPv4 and IPV6 data */
   int node_num[2];			/* which node this was in the tree,
					   or -1 for glue nodes */
} isc_radix_node_t;

#define RADIX_TREE_MAGIC         ISC_MAGIC('R','d','x','T');
#define RADIX_TREE_VALID(a)      ISC_MAGIC_VALID(a, RADIX_TREE_MAGIC);

typedef struct isc_radix_tree {
   unsigned int		magic;
   isc_mem_t		*mctx;
   isc_radix_node_t 	*head;
   isc_uint32_t		maxbits;	/* for IP, 32 bit addresses */
   int num_active_node;			/* for debugging purposes */
   int num_added_node;			/* total number of nodes */
} isc_radix_tree_t;

isc_result_t
isc_radix_search(isc_radix_tree_t *radix, isc_radix_node_t **target,
		 isc_prefix_t *prefix);
/*%<
 * Search 'radix' for the best match to 'prefix'.
 * Return the node found in '*target'.
 *
 * Requires:
 * \li	'radix' to be valid.
 * \li	'target' is not NULL and "*target" is NULL.
 * \li	'prefix' to be valid.
 *
 * Returns:
 * \li	ISC_R_NOTFOUND
 * \li	ISC_R_SUCCESS
 */

isc_result_t
isc_radix_insert(isc_radix_tree_t *radix, isc_radix_node_t **target,
		 isc_radix_node_t *source, isc_prefix_t *prefix);
/*%<
 * Insert 'source' or 'prefix' into the radix tree 'radix'.
 * Return the node added in 'target'.
 *
 * Requires:
 * \li	'radix' to be valid.
 * \li	'target' is not NULL and "*target" is NULL.
 * \li	'prefix' to be valid or 'source' to be non NULL and contain
 *	a valid prefix.
 *
 * Returns:
 * \li	ISC_R_NOMEMORY
 * \li	ISC_R_SUCCESS
 */

void
isc_radix_remove(isc_radix_tree_t *radix, isc_radix_node_t *node);
/*%<
 * Remove the node 'node' from the radix tree 'radix'.
 *
 * Requires:
 * \li	'radix' to be valid.
 * \li	'node' to be valid.
 */

isc_result_t
isc_radix_create(isc_mem_t *mctx, isc_radix_tree_t **target, int maxbits);
/*%<
 * Create a radix tree with a maximum depth of 'maxbits';
 *
 * Requires:
 * \li	'mctx' to be valid.
 * \li	'target' to be non NULL and '*target' to be NULL.
 * \li	'maxbits' to be less than or equal to RADIX_MAXBITS.
 *
 * Returns:
 * \li	ISC_R_NOMEMORY
 * \li	ISC_R_SUCCESS
 */

void
isc_radix_destroy(isc_radix_tree_t *radix, isc_radix_destroyfunc_t func);
/*%<
 * Destroy a radix tree optionally calling 'func' to clean up node data.
 *
 * Requires:
 * \li	'radix' to be valid.
 */

void
isc_radix_process(isc_radix_tree_t *radix, isc_radix_processfunc_t func);
/*%<
 * Walk a radix tree calling 'func' to process node data.
 *
 * Requires:
 * \li	'radix' to be valid.
 * \li	'func' to point to a function.
 */

#define RADIX_MAXBITS 128
#define RADIX_NBIT(x)        (0x80 >> ((x) & 0x7f))
#define RADIX_NBYTE(x)       ((x) >> 3)

#define RADIX_DATA_GET(node, type) (type *)((node)->data)
#define RADIX_DATA_SET(node, value) ((node)->data = (void *)(value))

#define RADIX_WALK(Xhead, Xnode) \
    do { \
	isc_radix_node_t *Xstack[RADIX_MAXBITS+1]; \
	isc_radix_node_t **Xsp = Xstack; \
	isc_radix_node_t *Xrn = (Xhead); \
	while ((Xnode = Xrn)) { \
	    if (Xnode->prefix)

#define RADIX_WALK_ALL(Xhead, Xnode) \
do { \
	isc_radix_node_t *Xstack[RADIX_MAXBITS+1]; \
	isc_radix_node_t **Xsp = Xstack; \
	isc_radix_node_t *Xrn = (Xhead); \
	while ((Xnode = Xrn)) { \
	    if (1)

#define RADIX_WALK_BREAK { \
	    if (Xsp != Xstack) { \
		Xrn = *(--Xsp); \
	     } else { \
		Xrn = (radix_node_t *) 0; \
	    } \
	    continue; }

#define RADIX_WALK_END \
	    if (Xrn->l) { \
		if (Xrn->r) { \
		    *Xsp++ = Xrn->r; \
		} \
		Xrn = Xrn->l; \
	    } else if (Xrn->r) { \
		Xrn = Xrn->r; \
	    } else if (Xsp != Xstack) { \
		Xrn = *(--Xsp); \
	    } else { \
		Xrn = (isc_radix_node_t *) 0; \
	    } \
	} \
    } while (0)

#endif /* _RADIX_H */


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jupyterkernel.json.messages;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.jupyterkernel.util.JSONField;

/**
 *
 * @author kay schluehr
 */
public class T_message extends T_JSON {

    @JSONField(type = "T_JSON")
    public T_header header;

    @JSONField(type = "T_JSON")
    public T_header parent_header;

    @JSONField
    public JSONObject metadata = new JSONObject();

    @JSONField(type = "T_JSON")
    public T_JSON content;

}


text:
layout: page
title: Cohen Media Trade Fair
date: 2016-05-24
author: Nicholas Warren
tags: weekly links, java
status: published
summary: Vivamus aliquam neque nec dolor maximus blandit. Cras egestas varius.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/25/2019
  endDate: 07/30/2019
  ctyhocn: GSPGHHX
  groupCode: CMTF
published: true
---
Praesent lacus augue, scelerisque vel interdum in, mollis ac quam. Nunc scelerisque mauris sed vehicula consectetur. Vivamus eleifend sem ac mauris tincidunt, quis rhoncus diam aliquet. In congue enim dolor, posuere malesuada ipsum fermentum nec. Quisque a nunc elit. Duis et nunc mi. Curabitur fringilla non nunc non eleifend.

* Praesent ac metus vel ipsum tristique pellentesque
* Donec non felis ac sapien finibus sodales
* Ut at urna sed nulla commodo pulvinar sit amet at lectus
* Vivamus sed augue congue, tristique arcu nec, posuere lacus.

Vivamus vitae convallis nibh. Sed diam lacus, condimentum vel feugiat nec, suscipit posuere odio. Sed libero sapien, tristique a risus vel, auctor vulputate mauris. Sed in erat libero. Donec maximus condimentum nisl a euismod. In hac habitasse platea dictumst. Praesent faucibus massa sed purus bibendum, quis tincidunt nulla euismod. Quisque pretium ex et lorem hendrerit, vel mattis sem fringilla.