text:
package org.apache.maven.toolchain.building;

import static org.junit.Assert.assertEquals;

import java.util.Collections;

import org.apache.maven.building.Problem;
import org.apache.maven.building.ProblemCollector;
import org.apache.maven.building.ProblemCollectorFactory;
import org.junit.Test;

public class ToolchainsBuildingExceptionTest
{
    private static final String LS = System.lineSeparator();

    @Test
    public void testNoProblems()
    {
        ToolchainsBuildingException e = new ToolchainsBuildingException( Collections.<Problem>emptyList() );
        assertEquals( "0 problems were encountered while building the effective toolchains" + LS, e.getMessage() );
    }

    @Test
    public void testOneProblem()
    {
        ProblemCollector problemCollector = ProblemCollectorFactory.newInstance( null );
        problemCollector.add( Problem.Severity.ERROR, "MESSAGE", 3, 5, new Exception() );
        ToolchainsBuildingException e = new ToolchainsBuildingException( problemCollector.getProblems() );
        assertEquals( "1 problem was encountered while building the effective toolchains" + LS +
                      "[ERROR] MESSAGE @ line 3, column 5" + LS, e.getMessage() );
    }

    @Test
    public void testUnknownPositionAndSource()
    {
        ProblemCollector problemCollector = ProblemCollectorFactory.newInstance( null );
        problemCollector.add( Problem.Severity.ERROR, "MESSAGE", -1, -1, new Exception() );
        ToolchainsBuildingException e = new ToolchainsBuildingException( problemCollector.getProblems() );
        assertEquals( "1 problem was encountered while building the effective toolchains" + LS +
                      "[ERROR] MESSAGE" + LS, e.getMessage() );
    }

    @Test
    public void testUnknownPosition()
    {
        ProblemCollector problemCollector = ProblemCollectorFactory.newInstance( null );
        problemCollector.setSource( "SOURCE" );
        problemCollector.add( Problem.Severity.ERROR, "MESSAGE", -1, -1, new Exception() );
        ToolchainsBuildingException e = new ToolchainsBuildingException( problemCollector.getProblems() );
        assertEquals( "1 problem was encountered while building the effective toolchains" + LS +
                      "[ERROR] MESSAGE @ SOURCE" + LS, e.getMessage() );
    }

}


text:
package org.xtuml.bp.core.test;

import junit.framework.TestCase;

public class CoreTestResultCreator extends TestCase {

	public void testCreateTestResults() throws Exception {

		try {

			DeleteTestGenerics dt = new DeleteTestGenerics("Core Delete Test Result Creator");
			dt.setUp();
			dt.setGenerateResults();

			FormalizeUnformalizeTest fut = new FormalizeUnformalizeTest(
					"Core Formalize Unformalize Test Result Creator");
			fut.setUp();
			fut.setGenerateResults();

			AssignClassTestGenerics act = new AssignClassTestGenerics(
					"Core Assign Class Test Result Creator");
			act.setUp();
			act.setGenerateResults();

			AssignRemoveEventsGenerics are = new AssignRemoveEventsGenerics(
					"Core Assign Remove Events and Transitions");
			are.setUp();
			are.setGenerateResults();

			AttributeMenuItemTestGenerics ami = new AttributeMenuItemTestGenerics(
					"Attribute Menu Item Test Result Creator");
			ami.setUp();
			ami.setGenerateResults();

			CombineSplitReferentialsTestGenerics csr = new CombineSplitReferentialsTestGenerics(
					"Combine Split Referentials Test Result Creator");
			csr.setUp();
			csr.setGenerateResults();

			SubtypeSupertypeFormalizeTest ssf = new SubtypeSupertypeFormalizeTest(
					"Subtype Supertype Formalize Test Result Creator");
			ssf.setUp();
			ssf.setGenerateResults();

			ModelTransactionTestGenerics mtt = new ModelTransactionTestGenerics("test");
			mtt.setUp();

			SequenceTestsGenerics st = new SequenceTestsGenerics("Sequence Test Results");
			st.setGenerateResults();

			CommunicationLinkTestsGenerics clt = new CommunicationLinkTestsGenerics(
					"Communication Link Test Results");
			clt.setGenerateResults();

			CommunicationMessageTestsGenerics cmt = new CommunicationMessageTestsGenerics(
					"Communication Message Test Results");
			cmt.setGenerateResults();

			CommunicationTestsGenerics cts = new CommunicationTestsGenerics(
					"Communication Test Results");
			cts.setGenerateResults();

            ModifyNonFullyLoadedModelTestsGenerics mnflm = new ModifyNonFullyLoadedModelTestsGenerics(
                "Modify Non Fully Loaded Test Results");
            mnflm.setGenerateResults();

			System.out
					.println("CoreTestResultCreator: Test results created OK");
		} catch (Exception e) {
			System.err.println("Exception encountered by test result creator: "
					+ e);
			throw e;
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
from functools import wraps
import json

from django.http import HttpResponse

def json_view(func):
    """装饰 JSON view ::

        @json_view
        def view(request):
            return {'data': [1, 2]}

        @json_view
        def view(request):
            return {'msg': '403'}, 403
    """
    @wraps(func)
    def wrapper(request, *args, **kwargs):
        status = 200
        content_type = 'application/json'
        response = func(request, *args, **kwargs)
        if isinstance(response, HttpResponse):
            return response

        if isinstance(response, (tuple, list)):
            status = response[1]
            context = response[0]
        else:
            context = response

        content = json.dumps(context)
        return HttpResponse(content, status=status,
                            content_type=content_type)
    return wrapper


text:
package com.networknt.info;

import com.networknt.client.Http2Client;
import com.networknt.exception.ClientException;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.client.ClientConnection;
import io.undertow.client.ClientRequest;
import io.undertow.client.ClientResponse;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnio.IoUtils;
import org.xnio.OptionMap;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by steve on 01/09/16.
 */
public class ServerInfoGetHandlerTest {
    static final Logger logger = LoggerFactory.getLogger(ServerInfoGetHandlerTest.class);

    static Undertow server = null;

    @BeforeClass
    public static void setUp() {
        if(server == null) {
            logger.info("starting server");
            HttpHandler handler = getTestHandler();
            server = Undertow.builder()
                    .addHttpListener(7080, "localhost")
                    .setHandler(handler)
                    .build();
            server.start();
        }
    }

    @AfterClass
    public static void tearDown() throws Exception {
        if(server != null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignored) {

            }
            server.stop();
            logger.info("The server is stopped.");
        }
    }

    static RoutingHandler getTestHandler() {
        return Handlers.routing().add(Methods.GET, "/server/info", new ServerInfoGetHandler());
    }

    @Test
    public void testServerInfo() throws Exception {
        final Http2Client client = Http2Client.getInstance();
        final CountDownLatch latch = new CountDownLatch(1);
        final ClientConnection connection;
        try {
            connection = client.connect(new URI("http://localhost:7080"), Http2Client.WORKER, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
        } catch (Exception e) {
            throw new ClientException(e);
        }
        final AtomicReference<ClientResponse> reference = new AtomicReference<>();
        try {
            ClientRequest request = new ClientRequest().setPath("/server/info").setMethod(Methods.GET);
            request.getRequestHeaders().put(Headers.HOST, "localhost");
            connection.sendRequest(request, client.createClientCallback(reference, latch));
            latch.await();
        } catch (Exception e) {
            logger.error("Exception: ", e);
            throw new ClientException(e);
        } finally {
            IoUtils.safeClose(connection);
        }
        int statusCode = reference.get().getResponseCode();
        String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
        logger.debug("body = " + body);
        Assert.assertEquals(200, statusCode);
        if(statusCode == 200) {
            Assert.assertNotNull(body);
        }
    }
}


text:
/**
 *
 * Please see the [Scaled Access integration](https://marketplace.auth0.com/integrations/scaled-access) for more information and detailed installation instructions.
 *
 * **Required configuration** (this Rule will be skipped if any of the below are not defined):
 *
 *    - `SCALED_ACCESS_AUDIENCE` The identifier of the Auth0 API
 *    - `SCALED_ACCESS_CLIENTID` The Client ID of the Auth0 machine-to-machine application.
 *    - `SCALED_ACCESS_CLIENTSECRET` The Client secret of the Auth0 machine-to-machine application.
 *    - `SCALED_ACCESS_BASEURL` The base URL for the Relationship Management API.
 *    - `SCALED_ACCESS_TENANT` Your tenant code provided by Scaled Access.
 *
 * **Optional configuration:**
 *
 *    - `SCALED_ACCESS_CUSTOMCLAIM` A namespaced ID token claim (defaults to `https://scaledaccess.com/relationships`)
 *
 * @title Scaled Access relationship-based claims
 * @overview Adds a claim based on the relationships the subject has in Scaled Access
 * @gallery false
 * @category marketplace
 */
function scaledAccessAddRelationshipsClaim(user, context, callback) {
  if (
    !configuration.SCALED_ACCESS_AUDIENCE ||
    !configuration.SCALED_ACCESS_CLIENTID ||
    !configuration.SCALED_ACCESS_CLIENTSECRET ||
    !configuration.SCALED_ACCESS_BASEURL ||
    !configuration.SCALED_ACCESS_TENANT
  ) {
    console.log('Missing required configuration. Skipping.');
    return callback(null, user, context);
  }

  const fetch = require('node-fetch');
  const { URLSearchParams } = require('url');

  const getM2mToken = () => {
    if (
      global.scaledAccessM2mToken &&
      global.scaledAccessM2mTokenExpiryInMillis > new Date().getTime() + 60000
    ) {
      return Promise.resolve(global.scaledAccessM2mToken);
    } else {
      const tokenUrl = `https://${context.request.hostname}/oauth/token`;
      return fetch(tokenUrl, {
        method: 'POST',
        body: new URLSearchParams({
          grant_type: 'client_credentials',
          client_id: configuration.SCALED_ACCESS_CLIENTID,
          client_secret: configuration.SCALED_ACCESS_CLIENTSECRET,
          audience: configuration.SCALED_ACCESS_AUDIENCE,
          scope: 'pg:tenant:admin'
        })
      })
        .then((response) => {
          if (!response.ok) {
            return response.text().then((error) => {
              console.error('Failed to obtain m2m token from ' + tokenUrl);
              throw Error(error);
            });
          } else {
            return response.json();
          }
        })
        .then(({ access_token, expires_in }) => {
          global.scaledAccessM2mToken = access_token;
          global.scaledAccessM2mTokenExpiryInMillis =
            new Date().getTime() + expires_in * 1000;
          return access_token;
        });
    }
  };

  const callRelationshipManagementApi = async (accessToken, path) => {
    const url = `${configuration.SCALED_ACCESS_BASEURL}/${configuration.SCALED_ACCESS_TENANT}/${path}`;
    return fetch(url, {
      method: 'GET',
      headers: {
        Authorization: 'Bearer ' + accessToken,
        'Content-Type': 'application/json'
      }
    }).then(async (response) => {
      if (response.status === 404) {
        return [];
      } else if (!response.ok) {
        return response.text().then((error) => {
          console.error('Failed to call relationship management API', url);
          throw Error(error);
        });
      } else {
        return response.json();
      }
    });
  };

  const getRelationships = (accessToken) => {
    return callRelationshipManagementApi(
      accessToken,
      `actors/user/${user.user_id}/relationships`
    );
  };

  const addClaimToToken = (apiResponse) => {
    const claimName =
      configuration.SCALED_ACCESS_CUSTOMCLAIM ||
      `https://scaledaccess.com/relationships`;
    context.accessToken[claimName] = apiResponse.map((relationship) => ({
      relationshipType: relationship.relationshipType,
      to: relationship.to
    }));
  };

  getM2mToken()
    .then(getRelationships)
    .then(addClaimToToken)
    .then(() => {
      callback(null, user, context);
    })
    .catch((err) => {
      console.error(err);
      console.log('Using configuration: ', JSON.stringify(configuration));
      callback(null, user, context); // fail gracefully, token just won't have extra claim
    });
}


text:
/*
 @ 0xCCCCCCCC
*/

#include "klog/klog_worker.h"

#include <cassert>

#include "klog/klog_file.h"

namespace {

namespace chrono = std::chrono;

const size_t kBufferSize = 4 * 1024 * 1024;

}   // namespace

namespace klog {

LogWorker::LogWorker(FileNameGenerator gen, chrono::seconds flush_interval, size_t roll_size,
                     chrono::hours roll_interval)
    : file_name_gen_(gen), flush_interval_(flush_interval), roll_size_(roll_size),
      roll_interval_(roll_interval), working_buffer_(new Buffer()), backlog_buffer_(new Buffer()),
      done_(false)
{
    working_buffer_->reserve(kBufferSize);
    backlog_buffer_->reserve(kBufferSize);
    thread_ = std::thread(&LogWorker::WorkFunc, this);
}

LogWorker::~LogWorker()
{
    done_.store(true, std::memory_order::memory_order_release);
    thread_.join();
}

void LogWorker::Send(std::string&& message)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (working_buffer_->capacity() - working_buffer_->size() > message.size()) {
        working_buffer_->insert(working_buffer_->end(), message.begin(), message.end());
    } else {
        buffer_bridge_.push_back(std::move(working_buffer_));

        // If backlog buffer is not available, usually when writing speed of front-end is
        // extremely faster than flusing speed of back-end, we create another buffer at hand.
        if (backlog_buffer_) {
            working_buffer_ = std::move(backlog_buffer_);
        } else {
            working_buffer_.reset(new Buffer());
            working_buffer_->reserve(kBufferSize);
        }

        working_buffer_->insert(working_buffer_->end(), message.begin(), message.end());
        bridge_not_empty_cond_.notify_one();
    }
}

void LogWorker::WorkFunc()
{
    auto relay_working_buffer = std::make_unique<Buffer>();
    relay_working_buffer->reserve(kBufferSize);
    auto relay_backlog_buffer = std::make_unique<Buffer>();
    relay_backlog_buffer->reserve(kBufferSize);
    BufferVector buffer_to_write;

    LogFile log_file(file_name_gen_, roll_size_, roll_interval_);
    while (!done_.load(std::memory_order::memory_order_acquire)) {
        assert(relay_working_buffer &&
               relay_working_buffer->empty() &&
               relay_working_buffer->capacity() == kBufferSize);
        assert(relay_backlog_buffer &&
               relay_backlog_buffer->empty() &&
               relay_backlog_buffer->capacity() == kBufferSize);
        assert(buffer_to_write.empty());

        {
            std::unique_lock<std::mutex> lock(mutex_);
            // If there is no buffer in the bridge, get a sleep until either
            // being signaled or a timeout is reached.
            if (buffer_bridge_.empty()) {
                bridge_not_empty_cond_.wait_for(lock, flush_interval_);
            }

            buffer_bridge_.push_back(std::move(working_buffer_));
            working_buffer_ = std::move(relay_working_buffer);
            if (!backlog_buffer_) {
                backlog_buffer_ = std::move(relay_backlog_buffer);
            }

            using std::swap;
            swap(buffer_bridge_, buffer_to_write);
        }

        // TODO: Try to drop excessive buffers.

        for (const auto& buffer : buffer_to_write) {
            if (!buffer->empty()) {
                log_file.Append(buffer->data(), buffer->size());
            }
        }

        if (buffer_to_write.size() > 2) {
            buffer_to_write.resize(2);
        }

        if (!relay_working_buffer) {
            relay_working_buffer = std::move(buffer_to_write.back());
            relay_working_buffer->clear();
            buffer_to_write.pop_back();
        }

        if (!relay_backlog_buffer) {
            relay_backlog_buffer = std::move(buffer_to_write.back());
            relay_backlog_buffer->clear();
            buffer_to_write.pop_back();
        }

        buffer_to_write.clear();
    }
}

}   // namespace klog


text:
  Diane-Capelle est
       un village
       situé dans le département de Moselle en Lorraine. Elle totalisait 223 habitants en 2008.

À proximité de Diane-Capelle sont localisées les villes de
Languimberg à 5 km, 214 habitants,
Gondrexange localisée à 4 km, 472 habitants,
Barchain localisée à 2 km, 108 habitants,
Neufmoulins à 5 km, 36 habitants,
Kerprich-aux-Bois localisée à 2 km, 127 habitants,
Héming à 4 km, 484 habitants,
 entre autres. De plus, Diane-Capelle est située à seulement huit km de Sarrebourg.

Le nombre de logements, à Diane-Capelle, se décomposait en 2011 en huit appartements et 367 maisons soit
 un marché relativement équilibré.

Si vous envisagez de demenager à Diane-Capelle, vous pourrez aisément trouver une maison à vendre.


text:
package org.ggp.base.apps.kiosk.games;

import java.awt.Color;
import java.awt.Graphics;

import org.ggp.base.apps.kiosk.templates.CommonGraphics;
import org.ggp.base.apps.kiosk.templates.GameCanvas_SimpleGrid;

public class GoldenRectangleCanvas extends GameCanvas_SimpleGrid {
    private static final long serialVersionUID = 1L;

    @Override
	public String getGameName() { return "Golden Rectangle"; }
    @Override
	protected String getGameKey() { return "golden_rectangle"; }
    @Override
	protected int getGridHeight() { return 8; }
    @Override
	protected int getGridWidth() { return 7; }

    private int selectedColumn = 0;

    @Override
    protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) {
        for (int y = 0; y <= 7; y++) {
            if(gameStateHasLegalMove("( mark " + xCell + " " + y + " )")) {
                selectedColumn = xCell;
                submitWorkingMove(stringToMove("( mark " + xCell + " " + y + " )"));
            }
        }
    }

    @Override
    protected void renderCell(Graphics g, int xCell, int yCell) {
        yCell = 8 - yCell;

        int width = g.getClipBounds().width;
        int height = g.getClipBounds().height;

        g.setColor(Color.BLACK);
        g.drawRect(1, 1, width-2, height-2);

        if(gameStateHasFact("( cell " + xCell + " " + yCell + " r )")) {
            g.setColor(Color.RED);
            CommonGraphics.drawDisc(g);
        } else if(gameStateHasFact("( cell " + xCell + " " + yCell + " y )")) {
            g.setColor(Color.YELLOW);
            CommonGraphics.drawDisc(g);
        } else {
            ;
        }

        if(selectedColumn == xCell) {
            g.setColor(Color.GREEN);
            g.drawRect(3, 3, width-6, height-6);
        }
    }

    @Override
    public void clearMoveSelection() {
        submitWorkingMove(null);
        selectedColumn = 0;

        repaint();
    }
}


text:
{% extends "base.html" %}

{% block contentClass %}content seethrough{% endblock %}

{% block content %}

The LocalWiki software is a web application you install on a
    server. If you're not familiar with this process but want
    to start a LocalWiki project in your community (and there isn't
    already one there) check out the FAQ!

Installing on Ubuntu

        LocalWiki is available as a prebuilt package for Ubuntu 10.04 LTS or newer.

        Just open a terminal and run these commands:

                        $

                        $

                        $

                        $

                        sudo apt-get install python-software-properties

                        sudo apt-add-repository ppa:localwiki

                        sudo apt-get update

                        sudo apt-get install localwiki

        That's it!  Follow the prompts to configure LocalWiki.

        After installing, be sure to add your new project to the
        LocalWiki Directory!

See the administrative documentation for more info.  Have a problem with installation?  Ask for help on IRC #localwiki on
        freenode.net or email contact@localwiki.org

    {% comment %}

Upgrading

        When a new version of LocalWiki is released, you should upgrade to it.  If you installed using the Ubuntu instructions above, then upgrading to a new release is very simple.

        Run these commands to upgrade:

                        $

                        $

                        sudo apt-get update

                        sudo apt-get upgrade

            This will upgrade all of your packages, including LocalWiki.  All of your data will be preserved during the upgrade.

    {% endcomment %}

Installing on other systems

        If you have the option, we strongly recommend installing LocalWiki on Ubuntu 10.04 newer.  It makes both installing and keeping LocalWiki up to date much easier.

        If you still want to install on a different operating system,
        please see our development site.

        Find a project near you

Not quite ready to install?

        Find a LocalWiki project in your area and collaborate with others to make it happen.

{% endblock %}


text:
"use strict";

// Register the message handler.
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    // Check if a password field is selected.
    if (request.type === 'check') {
      var activeElement = document.activeElement;
      if (activeElement.tagName.toLowerCase() === 'input') {
        if (activeElement.type.toLowerCase() === 'password') {
          sendResponse({ type: 'password' });
          return;
        }
      }
      sendResponse({ type: 'not-password' });
      return;
    }

    // Fill in the selected password field.
    if (request.type === 'fill') {
      var activeElement = document.activeElement;
      if (activeElement.tagName.toLowerCase() === 'input') {
        if (activeElement.type.toLowerCase() === 'password') {
          activeElement.value = request.hash;
          sendResponse({ type: 'close' });
          return;
        }
      }
      sendResponse({ type: 'none' });
      return;
    }
  }
);


text:
package org.adligo.fabricate.models.project;

import java.util.List;

/**
 * This interface represents modifications made to a project, which
 * were discovered through use of the SCM tool (i.e. git status).
 *
 * @author scott
 *
 */
public interface I_ProjectModifications {

  /**
   * This is a list of relative system dependent paths
   * of new files for a project.
   * @return
   */
  public abstract List<String> getAdditions();
  /**
   * This is a list of relative system dependent paths
   * of files which were removed from a project.
   * @return
   */
  public abstract List<String> getDeletions();
  /**
   * This is a list of relative system dependent paths
   * of files which were modified in a project.  This
   * list does NOT include the additions or deletions.
   * @return
   */
  public abstract List<String> getModifications();

  /**
   * The name of the project.
   * @return
   */
  public String getName();
}


text:
class MoveFromDevelopersCanMergeToProtectedBranchesMergeAccess < ActiveRecord::Migration[4.2]
  DOWNTIME = true
  DOWNTIME_REASON = <<-HEREDOC
    We're creating a `merge_access_level` for each `protected_branch`. If a user creates a `protected_branch` while this
    is running, we might be left with a `protected_branch` _without_ an associated `merge_access_level`. The `protected_branches`
    table must not change while this is running, so downtime is required.

    https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/5081#note_13247410
  HEREDOC

  def up
    execute <<-HEREDOC
      INSERT into protected_branch_merge_access_levels (protected_branch_id, access_level, created_at, updated_at)
        SELECT id, (CASE WHEN developers_can_merge THEN 30 ELSE 40 END), now(), now()
          FROM protected_branches
    HEREDOC
  end

  def down
    execute <<-HEREDOC
      UPDATE protected_branches SET developers_can_merge = TRUE
        WHERE id IN (SELECT protected_branch_id FROM protected_branch_merge_access_levels
                       WHERE access_level = 30);
    HEREDOC
  end
end


text:
KfWebSocketMessage::KfWebSocketMessage(const WSMessagePtr& message) :
    m_message(message)
{
}

KfWebSocketMessage::KfWebSocketMessage(const KfWebSocketMessage& copy) :
    m_message(copy.m_message)
{
}

void KF_CALLCONV KfWebSocketMessage::setCompressed(const bool& isCompressed)
{
    m_message->set_compressed(isCompressed);
}

void KF_CALLCONV KfWebSocketMessage::setFin(const bool& isFin)
{
    m_message->set_fin(isFin);
}

void KF_CALLCONV KfWebSocketMessage::setHeader(const char* header)
{
    m_message->set_header(header);
}

void KF_CALLCONV KfWebSocketMessage::setOpcode(const KfWebSocketConnection::OpCode& opcode)
{
    m_message->set_opcode((websocketpp::frame::opcode::value) opcode);
}

void KF_CALLCONV KfWebSocketMessage::setPayload(const char* payload)
{
    m_message->set_payload(payload);
}

void KF_CALLCONV KfWebSocketMessage::appendPayload(const char* payload)
{
    m_message->append_payload(payload);
}

bool KF_CALLCONV KfWebSocketMessage::isCompressed() const
{
    return m_message->get_compressed();
}

bool KF_CALLCONV KfWebSocketMessage::isFin() const
{
    return m_message->get_fin();
}

bool KF_CALLCONV KfWebSocketMessage::isPrepared() const
{
    return m_message->get_prepared();
}

std::string KF_CALLCONV KfWebSocketMessage::getExtensionData() const
{
    return m_message->get_extension_data();
}

std::string KF_CALLCONV KfWebSocketMessage::getHeader() const
{
    return m_message->get_header();
}

std::string KF_CALLCONV KfWebSocketMessage::getPayload() const
{
    return m_message->get_payload();
}

std::string KF_CALLCONV KfWebSocketMessage::getRawPayload() const
{
    return m_message->get_raw_payload();
}

KfWebSocketConnection::OpCode KF_CALLCONV KfWebSocketMessage::getOpcode() const
{
    return (KfWebSocketConnection::OpCode) m_message->get_opcode();
}


text:
require 'helper'

describe Octokit::Client::Milestones do

  before do
    Octokit.reset!
    @client = oauth_client
  end

  describe ".list_milestones", :vcr do
    it "lists milestones belonging to repository" do
      milestones = @client.list_milestones(@test_repo)
      expect(milestones).to be_kind_of Array
      assert_requested :get, github_url("/repos/#{@test_repo}/milestones")
    end
  end # .list_milestones

  context "with milestone" do
    before(:each) do
      name = "Test Milestone #{Time.now.to_i}"
      @milestone = @client.create_milestone(@test_repo, name)
    end

    after(:each) do
      @client.delete_milestone @test_repo, @milestone.number
    end

    describe ".milestone", :vcr do
      it "gets a single milestone belonging to repository" do
        @client.milestone @test_repo, @milestone.number
        assert_requested :get, github_url("/repos/#{@test_repo}/milestones/#{@milestone.number}")
      end
    end # .milestone

    describe ".create_milestone", :vcr do
      it "creates a milestone" do
        expect(@milestone.title).not_to be_nil
        assert_requested :post, github_url("/repos/#{@test_repo}/milestones")
      end
    end # .create_milestone

    describe ".update_milestone", :vcr do
      it "updates a milestone" do
        @client.update_milestone(@test_repo, @milestone.number, {:description => "Add support for API v3"})
        assert_requested :patch, github_url("/repos/#{@test_repo}/milestones/#{@milestone.number}")
      end
    end # .update_milestone

    describe ".delete_milestone", :vcr do
      it "deletes a milestone from a repository" do
        @client.delete_milestone(@test_repo, @milestone.number)
        assert_requested :delete, github_url("/repos/#{@test_repo}/milestones/#{@milestone.number}")
      end
    end # .delete_milestone
  end # with milestone
end


text:
script_path='.'
if `readlink -f $0 &>/dev/null`; then
    script_path=`readlink -f $0 2>/dev/null`
fi
script_dir=`dirname $script_path`
cd $script_dir

# Ensure build.xml exists before starting
if [[ ! -f build.xml ]]; then
    echo 'Ant build.xml file not found! Check that you are in the right directory.'
    exit 9
fi

# Copy base classes from wlauto dist
class_dir=bin/classes/com/arm/wlauto/uiauto
base_classes=`python -c "import os, wlauto; print os.path.join(os.path.dirname(wlauto.__file__), 'common', 'android', '*.class')"`
mkdir -p $class_dir
cp $base_classes $class_dir

# Add multiapp workload dependencies
apps=("googlephotos" "gmail" "skype")

for app in "${apps[@]}"; do
  module_path="wlauto.workloads.${app}"
  app_path="'uiauto/bin/classes/com/arm/wlauto/uiauto/${app}'"
  app_class_dir=`python -c "import os, ${module_path}; print os.path.join(os.path.dirname(${module_path}.__file__), ${app_path})"`
  cp -r $app_class_dir $class_dir
done

# Build and return appropriate exit code if failed
ant build
exit_code=$?
if [[ $exit_code -ne 0 ]]; then
    echo "ERROR: 'ant build' exited with code $exit_code"
    exit $exit_code
fi

# If successful move JAR file to workload folder (overwrite previous)
package=com.arm.wlauto.uiauto.multiapp.jar
rm -f ../$package
if [[ -f bin/$package ]]; then
    cp bin/$package ..
else
    echo 'ERROR: UiAutomator JAR could not be found!'
    exit 9
fi


text:
#pragma once

#include <thrust/detail/config.h>
#include <thrust/detail/type_traits.h>
#include <thrust/detail/type_traits/function_traits.h>

#if __cplusplus >= 201103L || defined(__cpp_lib_result_of_sfinae)
// necessary for std::result_of
#include <type_traits>
#endif

namespace thrust
{
namespace detail
{

#if __cplusplus >= 201103L || defined(__cpp_lib_result_of_sfinae)

template<typename Signature>
  struct result_of
{
  typedef typename std::result_of<Signature>::type type;
};

#else

template<typename Signature, typename Enable = void> struct result_of;

// specialization for unary invocations of things which have result_type
template<typename Functor, typename Arg1>
  struct result_of<
    Functor(Arg1),
    typename thrust::detail::enable_if<thrust::detail::has_result_type<Functor>::value>::type
  >
{
  typedef typename Functor::result_type type;
}; // end result_of

// specialization for binary invocations of things which have result_type
template<typename Functor, typename Arg1, typename Arg2>
  struct result_of<
    Functor(Arg1,Arg2),
    typename thrust::detail::enable_if<thrust::detail::has_result_type<Functor>::value>::type
  >
{
  typedef typename Functor::result_type type;
};

#endif // __cplusplus >= 201103L

} // end detail
} // end thrust


text:
package org.zalando.intellij.swagger.completion.level;

import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import org.zalando.intellij.swagger.completion.style.CompletionStyle;

public class LookupElementBuilderFactory {

    public static LookupElementBuilder create(final String lookup,
                                              final CompletionStyle completionStyle) {
        final String value = completionStyle.isShouldQuote() ? "\"" + lookup + "\"" : lookup;
        LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(value);

        if (completionStyle.getFontWeight() == CompletionStyle.FontWeight.BOLD) {
            lookupElementBuilder = lookupElementBuilder.bold();
        }

        return lookupElementBuilder;
    }

    public static LookupElementBuilder create(final String lookup,
                                              final CompletionStyle completionStyle,
                                              final InsertHandler<LookupElement> insertHandler) {
        return create(lookup, completionStyle).withInsertHandler(insertHandler);
    }

}


text:
<?php

/**
 * @covers \Maenbn\OpenAmAuth\OpenAm
 */
class OpenAmUnitTest extends TestCase
{
    /**
     * @var \Maenbn\OpenAmAuth\OpenAm|PHPUnit_Framework_MockObject_MockObject
     */
    protected $openAm;

    /**
     * @var \Maenbn\OpenAmAuth\Config
     */
    protected $config;

    public function mockOpenAm($response, $mockOpenAm = true, $noCookieName = false)
    {
        $this->mockCurl($response);
        $cookieName = 'iPlanetDirectoryPro';
        $secureCookie = false;
        if($noCookieName){
            $cookieName = null;
            $secureCookie = null;
        }
        $this->config = new \Maenbn\OpenAmAuth\Config('https://myopenam.com', 'people', 'openam');
        $this->config->setCookieName($cookieName);
        $this->config->setSecureCookie($secureCookie);
        $strategiesFactory = new \Maenbn\OpenAmAuth\Factories\StrategiesFactory();
        $this->curl->setResultFormat($strategiesFactory->newJsonToObject());
        if($mockOpenAm) {
            $openAm = $this->getMockBuilder('Maenbn\OpenAmAuth\OpenAm')
                ->setConstructorArgs([$this->config, $this->curl]);
            $openAm->setMethods(['validateTokenId']);
            $this->openAm = $openAm->getMock();
        }
        else {
            $this->openAm = new \Maenbn\OpenAmAuth\OpenAm($this->config, $this->curl);
        }
    }

    public function testAuthenticate()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->tokenId = 1123123;
        $this->mockOpenAm($mockedResponse);
        $this->openAm->method('validateTokenId')->willReturn(true);
        $this->assertTrue($this->openAm->authenticate('abc123', 'password'));
        $this->assertEquals(1123123, $this->openAm->getTokenId());
    }

    public function testFailedAuthentication()
    {
        $this->mockOpenAm('dsadas');
        $this->assertFalse($this->openAm->authenticate('abc123', 'password'));
        $this->assertEquals(null, $this->openAm->getTokenId());
    }

    public function testValidateTokenReturnsTrue()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->valid = true;
        $mockedResponse->uid = 'abc123';
        $this->mockOpenAm($mockedResponse, false);
        $this->assertTrue($this->openAm->setTokenId('fasdfasdf')->validateTokenId());
        $this->assertEquals('abc123', $this->openAm->getUid());
    }

    public function testValidateTokenReturnsFalse()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->valid = false;
        $this->mockOpenAm($mockedResponse, false);
        $this->assertFalse($this->openAm->setTokenId('fasdfasdf')->validateTokenId());
        $this->assertNull($this->openAm->getUid());
    }

    /**
     * @expectedException Exception
     * @expectedExceptionMessage A tokenId has not been set
     */
    public function testValidateThrowsException()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->valid = false;
        $this->mockOpenAm($mockedResponse, false);
        $this->assertFalse($this->openAm->validateTokenId());
    }

    public function testSetUser()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->username = 'abc123';
        $mockedResponse->realm = 'people';
        $mockedResponse->mail = ['abc123@test.com'];
        $this->mockOpenAm($mockedResponse, false);
        $this->openAm->setTokenId('12321432')->setUid('abc123')->setUser();
        $this->assertObjectHasAttribute('username',$this->openAm->getUser());
        $this->assertInstanceOf(stdClass::class, $this->openAm->getUser());
    }

    public function testUserIsSetToNullWhenTokenOrUidHasNotBeenSet()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->username = 'abc123';
        $mockedResponse->realm = 'people';
        $mockedResponse->mail = ['abc123@test.com'];
        $this->mockOpenAm($mockedResponse, false);
        $this->openAm->setUser();
        $this->assertNull($this->openAm->getUser());
    }

    public function testCookieNameIsSetWhenNotSetOriginallyInConfig()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->cookieName = 'iPlanetDirectoryPro';
        $mockedResponse->secureCookie = false;
        $this->mockOpenAm($mockedResponse, false, true);
        $this->assertEquals('iPlanetDirectoryPro', $this->config->getCookieName());
    }

    public function testLogout()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->result = 'Successfully logged out';
        $this->mockOpenAm($mockedResponse, false);
        $result = $this->openAm->setTokenId('234124')->logout();
        $this->assertTrue($result);
        $this->assertNull($this->openAm->getTokenId());
        $this->assertNull($this->openAm->getUid());
        $this->assertNull($this->openAm->getUser());
    }

    public function testFailedLogout()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->result = 'Failed';
        $this->mockOpenAm($mockedResponse, false);
        $result = $this->openAm->setTokenId('234124')->logout();
        $this->assertFalse($result);
    }

    public function testConfigGetter()
    {
        $mockedResponse = new stdClass();
        $mockedResponse->cookieName = 'iPlanetDirectoryPro';
        $mockedResponse->secureCookie = false;
        $this->mockOpenAm($mockedResponse, false, true);
        $this->assertEquals('iPlanetDirectoryPro', $this->openAm->getConfig()->getCookieName());
        $this->assertFalse($this->openAm->getConfig()->getSecureCookie());
    }
}


text:
package com.ocdsoft.bacta.swg.archive.delta.packedmap;

import com.ocdsoft.bacta.swg.archive.delta.map.AutoDeltaIntObjectMap;
import com.ocdsoft.bacta.swg.server.quest.PlayerQuestData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by crush on 8/14/2014.
 * <p>
 * An AutoDeltaPackedMap is an AutoDeltaMap that will be packed into
 * a single value for storage.  It functions as an AutoDeltaMap in
 * all respects except that packDeltas() will send the entire map
 * on the network.
 */
public class AutoDeltaPackedPlayerQuestDataMap extends AutoDeltaIntObjectMap<PlayerQuestData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AutoDeltaPackedPlayerQuestDataMap.class);
    private static final String emptyPackedMap = "";

    public AutoDeltaPackedPlayerQuestDataMap() {
        super(PlayerQuestData::new);
    }

    /**
     * Packs a packed-string into a target byte buffer.
     *
     * @param target The target byte buffer.
     * @param buffer The string to pack into the buffer.
     */
    public static void packFromString(final ByteBuffer target, final String buffer) {
        final String[] entries = buffer.split(":");

        target.putInt(entries.length); //commandCount
        target.putInt(0); //baselineCommandCount

        if (entries.length <= 0)
            return;

        for (final String entry : entries) {
            final String[] entryTokens = entry.split(" ");

            final int key = Integer.parseInt(entryTokens[0]);

            //active quests
            if (entryTokens.length == 4) {
                target.put(Command.ADD);
                target.putInt(key);

                //in-progress quest.
                final PlayerQuestData data = new PlayerQuestData(
                        Long.parseLong(entryTokens[3]), //questGiver
                        Short.parseShort(entryTokens[1]), //activeTasks
                        Short.parseShort(entryTokens[2]), //completedTasks
                        false); //hasReceivedRewards
                data.writeToBuffer(target);
                //old-style completed quests which don't store extra flags.
            } else if (entryTokens.length == 1) {
                //completed quest
                target.put(Command.ADD);
                target.putInt(key);

                final PlayerQuestData data = new PlayerQuestData(true, true);
                data.writeToBuffer(target);
                //completed quests with store flags
            } else if (entryTokens.length == 2) {
                //completed quest
                target.put(Command.ADD);
                target.putInt(key);

                final short flags = Short.parseShort(entryTokens[1]);
                final boolean hasReceivedReward = (flags != 0);
                final PlayerQuestData data = new PlayerQuestData(true, hasReceivedReward);
                data.writeToBuffer(target);
            } else {
                LOGGER.error("Could not parse packed quest data {}", entry);
                throw new IllegalArgumentException("Could not parse packed quest data");
            }
        }
    }

    /**
     * Unpacks this source buffer into a packed string format.
     *
     * @param source The source buffer to unpack.
     * @return A string with the packed source buffer contents.
     */
    public static String unpackToString(final ByteBuffer source) {

        final int commandCount = source.getInt();
        final int baselineCommandCount = source.getInt();

        if (commandCount == 0) {
            return emptyPackedMap;
        } else {
            final StringBuilder sb = new StringBuilder();
            final List<QuestDataToSort> sortedList = new ArrayList<>(commandCount);

            for (int i = 0; i < commandCount; ++i) {
                final Command<PlayerQuestData> command = new Command<>(source, PlayerQuestData::new);
                sortedList.add(new QuestDataToSort(command.key, command.value));
            }

            Collections.sort(sortedList, (qd1, qd2) -> Integer.compare(qd1.questData.getRelativeAgeIndex(), qd2.questData.getRelativeAgeIndex()));

            for (int i = 0, size = sortedList.size(); i < size; ++i) {
                final QuestDataToSort qd = sortedList.get(i);
                final int key = qd.key;
                final PlayerQuestData data = qd.questData;

                if (data.isCompleted()) {
                    sb.append(String.format("%d %d:", key, data.hasReceivedReward() ? 1 : 0));
                } else {
                    sb.append(String.format("%d %d %d %s:", key, data.getActiveTasks(), data.getCompletedTasks(), Long.toString(data.getQuestGiver())));
                }
            }

            return sb.toString();
        }
    }

    @Override
    public void packDelta(final ByteBuffer target) {
        super.pack(target);
    }

    @Override
    public void unpackDelta(final ByteBuffer source) {
        super.unpack(source);
        onChanged();
    }

    private void onChanged() {
        //callback
    }

    private static class QuestDataToSort {
        private final int key;
        private final PlayerQuestData questData;

        public QuestDataToSort(final int key, final PlayerQuestData questData) {
            this.key = key;
            this.questData = questData;
        }
    }
}


text:
import errno
import itertools
import os
import signal

import netaddr
from neutron_lib import constants
from neutron_lib import exceptions
from neutron_lib.utils import file as file_utils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import fileutils

from neutron._i18n import _
from neutron.agent.linux import external_process
from neutron.cmd import runtime_checks as checks
from neutron.common import utils

VALID_STATES = ['MASTER', 'BACKUP']
VALID_AUTH_TYPES = ['AH', 'PASS']
HA_DEFAULT_PRIORITY = 50
PRIMARY_VIP_RANGE_SIZE = 24
KEEPALIVED_SERVICE_NAME = 'keepalived'
KEEPALIVED_EMAIL_FROM = 'neutron@openstack.local'
KEEPALIVED_ROUTER_ID = 'neutron'
GARP_PRIMARY_DELAY = 60
HEALTH_CHECK_NAME = 'ha_health_check'
_IS_NO_TRACK_SUPPORTED = None

LOG = logging.getLogger(__name__)
SIGTERM_TIMEOUT = 5

def _is_keepalived_use_no_track_supported():
    global _IS_NO_TRACK_SUPPORTED
    if _IS_NO_TRACK_SUPPORTED is None:
        _IS_NO_TRACK_SUPPORTED = (
            checks.keepalived_use_no_track_support())
    return _IS_NO_TRACK_SUPPORTED

def get_free_range(parent_range, excluded_ranges, size=PRIMARY_VIP_RANGE_SIZE):
    """Get a free IP range, from parent_range, of the specified size.

    :param parent_range: String representing an IP range. E.g: '169.254.0.0/16'
    :param excluded_ranges: A list of strings to be excluded from parent_range
    :param size: What should be the size of the range returned?
    :return: A string representing an IP range
    """
    free_cidrs = netaddr.IPSet([parent_range]) - netaddr.IPSet(excluded_ranges)
    for cidr in free_cidrs.iter_cidrs():
        if cidr.prefixlen <= size:
            return '%s/%s' % (cidr.network, size)

    raise ValueError(_('Network of size %(size)s, from IP range '
                       '%(parent_range)s excluding IP ranges '
                       '%(excluded_ranges)s was not found.') %
                     {'size': size,
                      'parent_range': parent_range,
                      'excluded_ranges': excluded_ranges})

class InvalidInstanceStateException(exceptions.NeutronException):
    message = _('Invalid instance state: %(state)s, valid states are: '
                '%(valid_states)s')

    def __init__(self, **kwargs):
        if 'valid_states' not in kwargs:
            kwargs['valid_states'] = ', '.join(VALID_STATES)
        super(InvalidInstanceStateException, self).__init__(**kwargs)

class InvalidAuthenticationTypeException(exceptions.NeutronException):
    message = _('Invalid authentication type: %(auth_type)s, '
                'valid types are: %(valid_auth_types)s')

    def __init__(self, **kwargs):
        if 'valid_auth_types' not in kwargs:
            kwargs['valid_auth_types'] = ', '.join(VALID_AUTH_TYPES)
        super(InvalidAuthenticationTypeException, self).__init__(**kwargs)

class KeepalivedVipAddress(object):
    """A virtual address entry of a keepalived configuration."""

    def __init__(self, ip_address, interface_name, scope=None, track=True):
        self.ip_address = ip_address
        self.interface_name = interface_name
        self.scope = scope
        self.track = track

    def __eq__(self, other):
        return (isinstance(other, KeepalivedVipAddress) and
                self.ip_address == other.ip_address)

    def __str__(self):
        return '[%s, %s, %s, %s]' % (self.ip_address,
                                     self.interface_name,
                                     self.scope,
                                     self.track)

    def build_config(self):
        result = '%s dev %s' % (self.ip_address, self.interface_name)
        if self.scope:
            result += ' scope %s' % self.scope
        if cfg.CONF.keepalived_use_no_track and not self.track:
            if _is_keepalived_use_no_track_supported():
                result += ' no_track'
            else:
                LOG.warning("keepalived_use_no_track cfg option is True but "
                            "keepalived on host seems to not support this "
                            "option")
        return result

class KeepalivedVirtualRoute(object):
    """A virtual route entry of a keepalived configuration."""

    def __init__(self, destination, nexthop, interface_name=None,
                 scope=None):
        self.destination = destination
        self.nexthop = nexthop
        self.interface_name = interface_name
        self.scope = scope

    def build_config(self):
        output = self.destination
        if self.nexthop:
            output += ' via %s' % self.nexthop
        if self.interface_name:
            output += ' dev %s' % self.interface_name
        if self.scope:
            output += ' scope %s' % self.scope
        if cfg.CONF.keepalived_use_no_track:
            if _is_keepalived_use_no_track_supported():
                output += ' no_track'
            else:
                LOG.warning("keepalived_use_no_track cfg option is True but "
                            "keepalived on host seems to not support this "
                            "option")
        return output

class KeepalivedInstanceRoutes(object):
    def __init__(self):
        self.gateway_routes = []
        self.extra_routes = []
        self.extra_subnets = []

    def remove_routes_on_interface(self, interface_name):
        self.gateway_routes = [gw_rt for gw_rt in self.gateway_routes
                               if gw_rt.interface_name != interface_name]
        # NOTE(amuller): extra_routes are initialized from the router's
        # 'routes' attribute. These routes do not have an interface
        # parameter and so cannot be removed via an interface_name lookup.
        self.extra_subnets = [route for route in self.extra_subnets if
                              route.interface_name != interface_name]

    @property
    def routes(self):
        return self.gateway_routes + self.extra_routes + self.extra_subnets

    def __len__(self):
        return len(self.routes)

    def build_config(self):
        return itertools.chain(['    virtual_routes {'],
                               ('        %s' % route.build_config()
                                for route in self.routes),
                               ['    }'])

class KeepalivedInstance(object):
    """Instance section of a keepalived configuration."""

    def __init__(self, state, interface, vrouter_id, ha_cidrs,
                 priority=HA_DEFAULT_PRIORITY, advert_int=None,
                 mcast_src_ip=None, nopreempt=False,
                 garp_primary_delay=GARP_PRIMARY_DELAY,
                 vrrp_health_check_interval=0,
                 ha_conf_dir=None):
        self.name = 'VR_%s' % vrouter_id

        if state not in VALID_STATES:
            raise InvalidInstanceStateException(state=state)

        self.state = state
        self.interface = interface
        self.vrouter_id = vrouter_id
        self.priority = priority
        self.nopreempt = nopreempt
        self.advert_int = advert_int
        self.mcast_src_ip = mcast_src_ip
        self.garp_primary_delay = garp_primary_delay
        self.track_interfaces = []
        self.vips = []
        self.virtual_routes = KeepalivedInstanceRoutes()
        self.authentication = None
        self.track_script = None
        self.primary_vip_range = get_free_range(
            parent_range=constants.PRIVATE_CIDR_RANGE,
            excluded_ranges=[constants.METADATA_CIDR,
                             constants.DVR_FIP_LL_CIDR] + ha_cidrs,
            size=PRIMARY_VIP_RANGE_SIZE)

        if vrrp_health_check_interval > 0:
            self.track_script = KeepalivedTrackScript(
                vrrp_health_check_interval, ha_conf_dir, self.vrouter_id)

    def set_authentication(self, auth_type, password):
        if auth_type not in VALID_AUTH_TYPES:
            raise InvalidAuthenticationTypeException(auth_type=auth_type)

        self.authentication = (auth_type, password)

    def add_vip(self, ip_cidr, interface_name, scope):
        track = interface_name in self.track_interfaces
        vip = KeepalivedVipAddress(ip_cidr, interface_name, scope, track=track)
        if vip not in self.vips:
            self.vips.append(vip)
        else:
            LOG.debug('VIP %s already present in %s', vip, self.vips)

    def remove_vips_vroutes_by_interface(self, interface_name):
        self.vips = [vip for vip in self.vips
                     if vip.interface_name != interface_name]

        self.virtual_routes.remove_routes_on_interface(interface_name)

    def remove_vip_by_ip_address(self, ip_address):
        self.vips = [vip for vip in self.vips
                     if vip.ip_address != ip_address]

    def get_existing_vip_ip_addresses(self, interface_name):
        return [vip.ip_address for vip in self.vips
                if vip.interface_name == interface_name]

    def _build_track_interface_config(self):
        return itertools.chain(
            ['    track_interface {'],
            ('        %s' % i for i in self.track_interfaces),
            ['    }'])

    def get_primary_vip(self):
        """Return an address in the primary_vip_range CIDR, with the router's
        VRID in the host section.

        For example, if primary_vip_range is 169.254.0.0/24, and this router's
        VRID is 5, the result is 169.254.0.5. Using the VRID assures that
        the primary VIP is consistent amongst HA router instances on different
        nodes.
        """

        ip = (netaddr.IPNetwork(self.primary_vip_range).network +
              self.vrouter_id)
        return str(netaddr.IPNetwork('%s/%s' % (ip, PRIMARY_VIP_RANGE_SIZE)))

    def _build_vips_config(self):
        # NOTE(amuller): The primary VIP must be consistent in order to avoid
        # keepalived bugs. Changing the VIP in the 'virtual_ipaddress' and
        # SIGHUP'ing keepalived can remove virtual routers, including the
        # router's default gateway.
        # We solve this by never changing the VIP in the virtual_ipaddress
        # section, herein known as the primary VIP.
        # The only interface known to exist for HA routers is the HA interface
        # (self.interface). We generate an IP on that device and use it as the
        # primary VIP. The other VIPs (Internal interfaces IPs, the external
        # interface IP and floating IPs) are placed in the
        # virtual_ipaddress_excluded section.

        primary = KeepalivedVipAddress(self.get_primary_vip(), self.interface)
        vips_result = ['    virtual_ipaddress {',
                       '        %s' % primary.build_config(),
                       '    }']

        if self.vips:
            vips_result.extend(
                itertools.chain(['    virtual_ipaddress_excluded {'],
                                ('        %s' % vip.build_config()
                                 for vip in
                                 sorted(self.vips,
                                        key=lambda vip: vip.ip_address)),
                                ['    }']))

        return vips_result

    def _build_virtual_routes_config(self):
        return itertools.chain(['    virtual_routes {'],
                               ('        %s' % route.build_config()
                                for route in self.virtual_routes),
                               ['    }'])

    def build_config(self):
        if self.track_script:
            config = self.track_script.build_config_preamble()
            self.track_script.routes = self.virtual_routes.gateway_routes
            self.track_script.vips = self.vips
        else:
            config = []

        config.extend(['vrrp_instance %s {' % self.name,
                       '    state %s' % self.state,
                       '    interface %s' % self.interface,
                       '    virtual_router_id %s' % self.vrouter_id,
                       '    priority %s' % self.priority,
                       '    garp_master_delay %s' % self.garp_primary_delay])

        if self.nopreempt:
            config.append('    nopreempt')

        if self.advert_int:
            config.append('    advert_int %s' % self.advert_int)

        if self.authentication:
            auth_type, password = self.authentication
            authentication = ['    authentication {',
                              '        auth_type %s' % auth_type,
                              '        auth_pass %s' % password,
                              '    }']
            config.extend(authentication)

        if self.mcast_src_ip:
            config.append('    mcast_src_ip %s' % self.mcast_src_ip)

        if self.track_interfaces:
            config.extend(self._build_track_interface_config())

        config.extend(self._build_vips_config())

        if len(self.virtual_routes):
            config.extend(self.virtual_routes.build_config())

        if self.track_script:
            config.extend(self.track_script.build_config())

        config.append('}')

        return config

class KeepalivedConf(object):
    """A keepalived configuration."""

    def __init__(self):
        self.reset()

    def reset(self):
        self.instances = {}

    def add_instance(self, instance):
        self.instances[instance.vrouter_id] = instance

    def get_instance(self, vrouter_id):
        return self.instances.get(vrouter_id)

    def build_config(self):
        config = ['global_defs {',
                  '    notification_email_from %s' % KEEPALIVED_EMAIL_FROM,
                  '    router_id %s' % KEEPALIVED_ROUTER_ID,
                  '}'
                  ]

        for instance in self.instances.values():
            config.extend(instance.build_config())

        return config

    def get_config_str(self):
        """Generates and returns the keepalived configuration.

        :return: Keepalived configuration string.
        """
        return '\n'.join(self.build_config())

class KeepalivedManager(object):
    """Wrapper for keepalived.

    This wrapper permits to write keepalived config files, to start/restart
    keepalived process.

    """

    def __init__(self, resource_id, config, process_monitor, conf_path,
                 namespace=None, throttle_restart_value=None):
        self.resource_id = resource_id
        self.config = config
        self.namespace = namespace
        self.process_monitor = process_monitor
        self.conf_path = conf_path
        # configure throttler for spawn to introduce delay between SIGHUPs,
        # otherwise keepalived primary may unnecessarily flip to backup
        if throttle_restart_value is not None:
            self._throttle_spawn(throttle_restart_value)

    # pylint: disable=method-hidden
    def _throttle_spawn(self, threshold):
        self.spawn = utils.throttler(threshold)(self.spawn)

    def get_conf_dir(self):
        confs_dir = os.path.abspath(os.path.normpath(self.conf_path))
        conf_dir = os.path.join(confs_dir, self.resource_id)
        return conf_dir

    def get_full_config_file_path(self, filename, ensure_conf_dir=True):
        conf_dir = self.get_conf_dir()
        if ensure_conf_dir:
            fileutils.ensure_tree(conf_dir, mode=0o755)
        return os.path.join(conf_dir, filename)

    def _output_config_file(self):
        config_str = self.config.get_config_str()
        LOG.debug("Router %s keepalived config: %s",
                  self.resource_id, config_str)
        config_path = self.get_full_config_file_path('keepalived.conf')
        file_utils.replace_file(config_path, config_str)

        return config_path

    @staticmethod
    def _safe_remove_pid_file(pid_file):
        try:
            os.remove(pid_file)
        except OSError as e:
            if e.errno != errno.ENOENT:
                LOG.error("Could not delete file %s, keepalived can "
                          "refuse to start.", pid_file)

    def get_vrrp_pid_file_name(self, base_pid_file):
        return '%s-vrrp' % base_pid_file

    def get_conf_on_disk(self):
        config_path = self.get_full_config_file_path('keepalived.conf')
        try:
            with open(config_path) as conf:
                return conf.read()
        except (OSError, IOError) as e:
            if e.errno != errno.ENOENT:
                raise

    def spawn(self):
        config_path = self._output_config_file()

        for key, instance in self.config.instances.items():
            if instance.track_script:
                instance.track_script.write_check_script()

        keepalived_pm = self.get_process()
        vrrp_pm = self._get_vrrp_process(
            self.get_vrrp_pid_file_name(keepalived_pm.get_pid_file_name()))

        keepalived_pm.default_cmd_callback = (
            self._get_keepalived_process_callback(vrrp_pm, config_path))

        keepalived_pm.enable(reload_cfg=True)

        self.process_monitor.register(uuid=self.resource_id,
                                      service_name=KEEPALIVED_SERVICE_NAME,
                                      monitored_process=keepalived_pm)

        LOG.debug('Keepalived spawned with config %s', config_path)

    def disable(self):
        self.process_monitor.unregister(uuid=self.resource_id,
                                        service_name=KEEPALIVED_SERVICE_NAME)

        pm = self.get_process()
        pm.disable(sig=str(int(signal.SIGTERM)))
        try:
            utils.wait_until_true(lambda: not pm.active,
                                  timeout=SIGTERM_TIMEOUT)
        except utils.WaitTimeout:
            LOG.warning('Keepalived process %s did not finish after SIGTERM '
                        'signal in %s seconds, sending SIGKILL signal',
                        pm.pid, SIGTERM_TIMEOUT)
            pm.disable(sig=str(int(signal.SIGKILL)))

    def check_processes(self):
        keepalived_pm = self.get_process()
        vrrp_pm = self._get_vrrp_process(
            self.get_vrrp_pid_file_name(keepalived_pm.get_pid_file_name()))
        return keepalived_pm.active and vrrp_pm.active

    def get_process(self):
        return external_process.ProcessManager(
            cfg.CONF,
            self.resource_id,
            self.namespace,
            service=KEEPALIVED_SERVICE_NAME,
            pids_path=self.conf_path)

    def _get_vrrp_process(self, pid_file):
        return external_process.ProcessManager(
            cfg.CONF,
            self.resource_id,
            self.namespace,
            pid_file=pid_file)

    def _get_keepalived_process_callback(self, vrrp_pm, config_path):

        def callback(pid_file):
            # If keepalived process crashed unexpectedly, the vrrp process
            # will be orphan and prevent keepalived process to be spawned.
            # A check here will let the l3-agent to kill the orphan process
            # and spawn keepalived successfully.
            if vrrp_pm.active:
                vrrp_pm.disable()

            self._safe_remove_pid_file(pid_file)
            self._safe_remove_pid_file(self.get_vrrp_pid_file_name(pid_file))

            cmd = ['keepalived', '-P',
                   '-f', config_path,
                   '-p', pid_file,
                   '-r', self.get_vrrp_pid_file_name(pid_file)]
            if logging.is_debug_enabled(cfg.CONF):
                cmd.append('-D')
            return cmd

        return callback

class KeepalivedTrackScript(KeepalivedConf):
    """Track script generator for Keepalived"""

    def __init__(self, interval, conf_dir, vr_id):
        self.interval = interval
        self.conf_dir = conf_dir
        self.vr_id = vr_id
        self.routes = []
        self.vips = []

    def build_config_preamble(self):
        config = ['',
                  'vrrp_script %s_%s {' % (HEALTH_CHECK_NAME, self.vr_id),
                  '    script "%s"' % self._get_script_location(),
                  '    interval %s' % self.interval,
                  '    fall 2',
                  '    rise 2',
                  '}',
                  '']

        return config

    def _is_needed(self):
        """Check if track script is needed by checking amount of routes.

        :return: True/False
        """
        return len(self.routes) > 0

    def build_config(self):
        if not self._is_needed():
            return ''

        config = ['    track_script {',
                  '        %s_%s' % (HEALTH_CHECK_NAME, self.vr_id),
                  '    }']

        return config

    def build_script(self):
        return itertools.chain(['#!/bin/bash -eu'],
                               ['%s' % self._check_ip_assigned()],
                               ('%s' % self._add_ip_addr(route.nexthop)
                                for route in self.routes if route.nexthop),
                               )

    def _add_ip_addr(self, ip_addr):
        cmd = {
            4: 'ping',
            6: 'ping6',
        }.get(netaddr.IPAddress(ip_addr).version)

        return '%s -c 1 -w 1 %s 1>/dev/null || exit 1' % (cmd, ip_addr)

    def _check_ip_assigned(self):
        cmd = 'ip a | grep %s || exit 0'
        return cmd % netaddr.IPNetwork(self.vips[0].ip_address).ip if len(
            self.vips) else ''

    def _get_script_str(self):
        """Generates and returns bash script to verify connectivity.

        :return: Bash script code
        """
        return '\n'.join(self.build_script())

    def _get_script_location(self):
        return os.path.join(self.conf_dir,
                            'ha_check_script_%s.sh' % self.vr_id)

    def write_check_script(self):
        if not self._is_needed():
            return

        file_utils.replace_file(
            self._get_script_location(), self._get_script_str(), 0o520)


text:
package io.github.jsbd.common.serialization.kv.codec;

public interface StringConverterFactory {
  StringConverter getCodecOf(Class<?> clazz);
}


text:
Defines constants that are general for neural networks, etc.

## tcga.py

Defines constants related to tcga data sources.

## locations.py

Defines data and results directories.


text:
//
//  WeatherTableHeaderView.m
//  Travel3
//
//  Created by lanou on 15/8/1.
//  Copyright (c) 2015年 XXL. All rights reserved.
//

#import "WeatherTableHeaderView.h"
#import "XLTool.h"

@implementation WeatherTableHeaderView
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createdMyView];
    }
    return self;
}

-(void)createdMyView
{
    UIImageView *backView = [[UIImageView alloc]initWithFrame:CGRectMakeAdaptationScreen(0, 0, 375, 270)];
    backView.image = [UIImage imageNamed:@"Weatherbeijing.jpg"];
    [self addSubview:backView];

    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMakeAdaptationScreen(0, 0, 375, 270)];
    self.imageView.alpha = 0.2;
    self.imageView.image = [UIImage imageNamed:@"0"];
    [backView addSubview:self.imageView];

    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < 22; i++) {
        NSString *name = [NSString stringWithFormat: @"%d",i];
        UIImage *image = [UIImage imageNamed:name];
        [array addObject:image];
    }
    self.imageView.animationImages = array;
    self.imageView.animationDuration = 2;
    self.imageView.animationRepeatCount = LONG_MAX;
    [self.imageView startAnimating];

    //当前温度
    self.temp = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 10, 100, 20)];
    self.temp.font = [UIFont boldSystemFontOfSize:heightScaleMakeAdaptationScreen(23)];
    [self addSubview:self.temp];

    //当天温度区间
    self.temperature = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 40, 200, 20)];
    self.temperature.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.temperature];
    //天气情况
    self.weather = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 70, 200, 20)];
    self.weather.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.weather];

    //风向和风力
    self.wind = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 100, 200, 20)];
    self.wind.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.wind];

    //发布日期 /星期几
    self.date_y = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 130, 200, 20)];
    self.date_y.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.date_y];

    //穿着建议
    self.dressing_advice = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 160, 300, 40)];
    self.dressing_advice.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    self.dressing_advice.numberOfLines = 0;
    [self addSubview:self.dressing_advice];

    //发布时间
    self.time = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 210, 200, 20)];
    self.time.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.time];

    self.Logo = [[UIImageView alloc]initWithFrame:CGRectMakeAdaptationScreen(20, 240, 20, 20)];
    self.Logo.image = [UIImage imageNamed:@"weizhi"];
    [self addSubview:self.Logo];

    self.city = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(50, 240, 200, 20)];
    self.city.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    [self addSubview:self.city];

    self.weatherResource = [[UILabel alloc]initWithFrame:CGRectMakeAdaptationScreen(375 - 120, 240, 100, 20)];
    self.weatherResource.font = [UIFont systemFontOfSize:heightScaleMakeAdaptationScreen(14)];
    self.weatherResource.textAlignment = NSTextAlignmentRight;
    [self addSubview:self.weatherResource];
}

-(void)setHeaderModel:(WeatherTableHeaderModel *)headerModel
{
    _headerModel = headerModel;
    self.temp.text = headerModel.temp;
    self.temperature.text = headerModel.temperature;
    self.weather.text = headerModel.weather;
    self.wind.text = headerModel.wind;
    self.date_y.text = headerModel.date_y;
    self.time.text = headerModel.time;
    self.city.text = headerModel.city;
    self.dressing_advice.text = [NSString stringWithFormat:@"穿着建议:%@",headerModel.dressing_advice];
    if (headerModel != nil) {
        self.weatherResource.text = @"全国天气预报";

    }
//    if ([self.weather.text containsString:@"阴"]) {
//      self.weatherLogo.image = [UIImage imageNamed:@"qingtian"];
//    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
//-CRE-

using System;

namespace Glass.Mapper.Sc.Configuration
{
    /// <summary>
    /// Enum SitecoreInfoUrlOptions
    /// </summary>
    [Flags]
    public enum SitecoreInfoUrlOptions
    {
        /// <summary>
        /// The default
        /// </summary>
        Default = 0,
        /// <summary>
        /// The add aspx extension
        /// </summary>
        AddAspxExtension = 1,
        /// <summary>
        /// The always include server URL
        /// </summary>
        AlwaysIncludeServerUrl = 2,
        /// <summary>
        /// The encode names
        /// </summary>
        EncodeNames = 4,

        /// <summary>
        /// Do not use with LanguageEmbeddingAsNeeded, LanguageEmbeddingNever
        /// </summary>
        LanguageEmbeddingAlways = 8,

        /// <summary>
        /// Do not use with LanguageEmbeddingAlways, LanguageEmbeddingNever
        /// </summary>
        LanguageEmbeddingAsNeeded = 16,

        /// <summary>
        /// Do not use with LanguageEmbeddingAlways, LanguageEmbeddingAsNeeded
        /// </summary>
        LanguageEmbeddingNever = 32,

        /// <summary>
        /// Do not use with LanguageLocationQueryString
        /// </summary>
        LanguageLocationFilePath = 64,

        /// <summary>
        /// Do not use with LanguageLocationFilePath
        /// </summary>
        LanguageLocationQueryString = 128,

        /// <summary>
        /// The shorten urls
        /// </summary>
        ShortenUrls = 256,
        /// <summary>
        /// The site resolving
        /// </summary>
        SiteResolving = 512,
        /// <summary>
        /// The use use display name
        /// </summary>
        UseUseDisplayName = 1024

    }
}


text:
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace Patroclus.Avalonia.Views
{
    public class FakeHermesView : UserControl
    {
        public FakeHermesView()
        {
            this.InitializeComponent();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}


text:
@protocol WindowTouchBarDelegate <NSObject>

// Creates and returns a touch bar for the browser window.
- (NSTouchBar*)makeTouchBar;

@end

#endif  // COMPONENTS_REMOTE_COCOA_APP_SHIM_WINDOW_TOUCH_BAR_DELEGATE_H_


text:
package org.sagebionetworks.web.unitclient.widget.login;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.widget.login.LoginWidget;
import org.sagebionetworks.web.client.widget.login.LoginWidgetView;

public class LoginWidgetTest {

  LoginWidget loginWidget;

  @Mock
  LoginWidgetView mockView;

  @Mock
  AuthenticationController mockAuthController;

  @Before
  public void setup() throws JSONObjectAdapterException {
    MockitoAnnotations.initMocks(this);
    loginWidget = new LoginWidget(mockView, mockAuthController);
    when(mockAuthController.isLoggedIn()).thenReturn(false);
  }

  @Test
  public void testAsWidget() {
    loginWidget.asWidget();

    verify(mockView).setVisible(true);
    verify(mockView).asWidget();
  }

  @Test
  public void testAsWidgetLoggedIn() {
    when(mockAuthController.isLoggedIn()).thenReturn(true);

    loginWidget.asWidget();

    verify(mockView).setVisible(false);
    verify(mockView).asWidget();
  }

  @Test
  public void testClear() {
    loginWidget.clear();

    verify(mockView).clear();
  }
}


text:
package org.codinjutsu.tools.jenkins.util;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.ui.ComponentContainer;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

@UtilityClass
public class GuiUtil {

    public static void runInSwingThread(Runnable runnable) {
        Application application = ApplicationManager.getApplication();
        if (application.isDispatchThread()) {
            runnable.run();
        } else {
            application.invokeLater(runnable);
        }
    }

    public static void installActionGroupInToolBar(ActionGroup actionGroup,
                                                   SimpleToolWindowPanel toolWindowPanel,
                                                   ActionManager actionManager, String toolBarName) {
        if (actionManager == null) {
            return;
        }

        final ActionToolbar actionToolbar = ActionManager.getInstance() .createActionToolbar(toolBarName, actionGroup, true);
        actionToolbar.setTargetComponent(toolWindowPanel.getComponent());
        toolWindowPanel.setToolbar(actionToolbar.getComponent());
    }

    public static void showInToolWindow(ToolWindow toolWindow, ComponentContainer consoleView, String tabName) {
        showInToolWindow(toolWindow, consoleView.getComponent(), consoleView, tabName);
    }

    public static void showInToolWindow(ToolWindow toolWindow, JComponent toolWindowComponent,
                                        @NotNull Disposable toolWindowDisposable, String tabName) {
        runInSwingThread(() -> {
            toolWindow.setAvailable(true, null);
            toolWindow.activate(null);
            toolWindow.show(null);
            ContentManager contentManager = toolWindow.getContentManager();
            Content content = contentManager.getFactory().createContent(toolWindowComponent, tabName, false);
            Disposer.register(content, toolWindowDisposable);
            contentManager.addContent(content);
            contentManager.setSelectedContent(content);
        });
    }
}


text:
KyImplementRTTI(KyUnitEntity, KyObject);

KyUnitEntity::~KyUnitEntity()
{
    auto it = mPropertyMap.begin();
    auto itEnd = mPropertyMap.end();
    while (it != itEnd)
    {
        it->second->Deactivate();
        DI_DELETE(it->second);
        it++;
    }
    mPropertyMap.clear();
}

void KyUnitEntity::Update(float deltaTime)
{
    auto it = mPropertyMap.begin();
    auto itEnd = mPropertyMap.end();
    while (it != itEnd)
    {
        it->second->Update(deltaTime);
        it++;
    }
}

void KyUnitEntity::Init()
{
    //auto world = ArGameApp::Get()->GetWorld();
    //mRenderObj = world->CreateRenderObject(type);
}


text:
var triggerCount = 0; GoalCheck = "", PageEventCheck = "", CampaignCheck = "", popupCheck = 0;

function triggerCampaign(campaignId, shouldTriggerCampaign, campaignData) {
    $.ajax({
        url: "/Events/Handler/TrackedLinkHandler.ashx",
        type: "GET",
        data: { cid: campaignId, triggerCampaign: shouldTriggerCampaign, campaignData },
        context: this,
        success: function (data) {

        },
        error: function (data) {
            alert("Campaign is not been triggered", data);
        }
    });
}

function triggerGoal(goalId, shouldTriggerGoal, goalData) {
    $.ajax({
        url: "/Events/Handler/TrackedLinkHandler.ashx",
        type: "GET",
        data: { gid: goalId, triggerGoal: shouldTriggerGoal, goalData },
        context: this,
        success: function (data) {

        },
        error: function (data) {
            alert("Goal is not been triggered", data);
        }
    });
}

function triggerPageEvent(pageEventId, shouldTriggerPageEvent, pageEventData) {
    $.ajax({
        url: "/Events/Handler/TrackedLinkHandler.ashx",
        type: "GET",
        data: { peid: pageEventId, triggerPageEvent: shouldTriggerPageEvent, pageEventData },
        context: this,
        success: function (data) {

        },
        error: function (data) {
            alert("PageEvent is not been triggered", data);
        }
    });
}


text:
apetools.commands.ipconfig.Ipconfig.address
===========================================

.. currentmodule:: apetools.commands.ipconfig

.. autoattribute:: Ipconfig.address


text:
<auditor>
 <appender name="server" class="ch.qos.logback.audit.client.SocketAuditAppender"/>
</auditor>


text:
package LinkFuture.Core.JsonManager;

import LinkFuture.Init.Config;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;

/**
 * User: Cyokin Zhang
 * Date: 10/23/13
 * Time: 12:19 PM
 */
public class JsonController {
    public static boolean isJsonObject(String jsonString){
        jsonString = jsonString.trim();
        return jsonString.startsWith("{") && jsonString.endsWith("}");
    }
    public static String convertJsonToXml(String jsonString)
    {
        if(jsonString.startsWith("{"))
        {
            JSONObject jsonObject=  new JSONObject(jsonString);
            return XML.toString(jsonObject);
        }
        else
        {
            JSONArray jsonObject=  new JSONArray(jsonString);
            return XML.toString(jsonObject);
        }
    }
    public static String convertXmlToJson(String xmlString,JsonOptionInfo option) {
        try(JsonObjectReader reader = new JsonObjectReader(xmlString))
        {
            JsonObjectInfo root = reader.toJsonObj();
            if(option.IgnoreRoot)
            {
                return root.toChildJson(option);
            }
            return root.toJson(option);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static String convertXmlToJson(String xmlString) {
        JsonOptionInfo option = new JsonOptionInfo();
        option.AttributePrefix= Config.Empty;
        option.NamespacePrefix = Config.Empty;
        option.IgnoreNamespace = true;
        option.IgnoreRoot = false;
        option.CDataNodeName = "Content";
        option.ValueOption = JsonValueOption.AllString;
        return convertXmlToJson(xmlString,option);
    }
}


text:
* Fixing Issue 114: Blank strings in brackets being casted to 0

## 1.0.2 / 2015-11-10
* Fixing Issue 113: &attributes on Mixin not working

## 1.0.1 / 2015-11-10
* Fixing Issue 112: Fixed ++ and -- recognition
* Fixing Issue 111: Maven Upgrade auf 3.2.5
* Added Testcases for closed Issues

## 1.0.0 / 2015-11-06
* In this version we updated to a lot of features of JadeJs 1.11 (2015-06-12).
* Breaking Change: Instead of 'id = 5' you must use '- var id = 5'
* Breaking Change: Instead of 'h1(attributes, class = "test")' you must use 'h1(class= "test")&attributes(attributes)'
* Breaking Change: Instead of '!!! 5' you must use 'doctype html'
* Breaking Change: Instead of '!!! 5' you must use 'doctype html'
* Jade Syntax for Conditional Comments is not supported anymore
* Thanks to rzara for contributing to issue-108

## 0.4.3 / 2015-05-27
* Accepted pull request from dusanmsk (#91) regarding mixin argument splitting and added further tests.

## 0.4.2 / 2015-03-18
* added issue89: Test files renamed (was #89 instead of #90).

## 0.4.1 / 2014-11-29
* fixed tab support #79
* .jade file extension appending is now done before the template loader #71
* added support for mixin default blocks #80

## 0.4.0 / 2013-11-20
* we are now on maven central #25
* adapted pom to meet sonatype requirements
* changed artifact group id
* fixed double output of objects implementing Map and Iterable interfaces #63

## 0.3.17 / 2013-10-09
* added sources to maven repository
* added support for multiple block statements in one mixin
* fixed issues when using if/case statements inside a mixin

## 0.3.16 / 2013-10-07
* allowed including files without having to register a specific filter
* enabled self closing tags with trailing "/" #57

## 0.3.15 / 2013-09-12
* added support for including non jade files (js, css, ...) inside a template

## 0.3.14 / 2013-08-24
* added ability to clear expression and template caches
* added new convenience method to Jade4J thats lets you use Reader #49

## 0.3.13 / 2013-08-21
* the indentation exception shows the expected indent sequence #50
* code nodes can have sub blocks #44
* better error message for invalid attribute definition #37
* blockquotes are now parsed correctly and don't interfere with "layout blocks" #45
* ExpressionStrings are now evaluated multiple times to support expressions that point to expressions #47

## 0.3.12 / 2013-06-20
* reduced jexl log level for 'unknown variable' messages


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the ServiceDiagnosticSettingsResource class.
 * @constructor
 * Description of a service diagnostic setting
 *
 * @member {string} [storageAccountId] The resource ID of the storage account
 * to which you would like to send Diagnostic Logs.
 *
 * @member {string} [serviceBusRuleId] The service bus rule ID of the service
 * bus namespace in which you would like to have Event Hubs created for
 * streaming Diagnostic Logs. The rule ID is of the format: '{service bus
 * resource ID}/authorizationrules/{key name}'.
 *
 * @member {array} [metrics] the list of metric settings.
 *
 * @member {array} [logs] the list of logs settings.
 *
 * @member {string} [workspaceId] The workspace ID (resource ID of a Log
 * Analytics workspace) for a Log Analytics workspace to which you would like
 * to send Diagnostic Logs. Example:
 * /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2
 *
 */
class ServiceDiagnosticSettingsResource extends models['Resource'] {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ServiceDiagnosticSettingsResource
   *
   * @returns {object} metadata of ServiceDiagnosticSettingsResource
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ServiceDiagnosticSettingsResource',
      type: {
        name: 'Composite',
        className: 'ServiceDiagnosticSettingsResource',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: true,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          storageAccountId: {
            required: false,
            serializedName: 'properties.storageAccountId',
            type: {
              name: 'String'
            }
          },
          serviceBusRuleId: {
            required: false,
            serializedName: 'properties.serviceBusRuleId',
            type: {
              name: 'String'
            }
          },
          metrics: {
            required: false,
            serializedName: 'properties.metrics',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'MetricSettingsElementType',
                  type: {
                    name: 'Composite',
                    className: 'MetricSettings'
                  }
              }
            }
          },
          logs: {
            required: false,
            serializedName: 'properties.logs',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'LogSettingsElementType',
                  type: {
                    name: 'Composite',
                    className: 'LogSettings'
                  }
              }
            }
          },
          workspaceId: {
            required: false,
            serializedName: 'properties.workspaceId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ServiceDiagnosticSettingsResource;


text:
package com.artemis.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * InputStream bridge helper.
 *
 * @author Daan van Yperen
 */
public class InputStreamHelper {
	private InputStreamHelper() {}

	/** Reset input stream */
	public static void reset(InputStream is) throws IOException {
		is.reset();
	}

	/**
	 * Tests if this input stream supports the mark and
	 * reset methods. Whether or not mark and
	 * reset are supported is an invariant property of a
	 * particular input stream instance. The markSupported method
	 * of InputStream returns false.
	 *
	 * @return  true if this stream instance supports the mark
	 *          and reset methods; false otherwise.
	 * @see     InputStream#mark(int)
	 * @see     InputStream#reset()
	 */
	public static boolean isMarkSupported(InputStream is)
	{
		return is.markSupported();
	}
}


text:
Bomberman_unix:
	g++ `sdl-config --cflags --libs` src/main.cpp src/Game.cpp src/global.cpp src/Bomb.cpp src/Map.cpp src/Item.cpp src/Character.cpp -o Bomberman_unix -lSDL -lSDL_ttf -lSDL_image -lSDL_mixer -std=c++0x

clean:
	rm Bomberman_unix

run:
	./Bomberman_unix


text:
================
Django Citations
================

Contents
--------

.. toctree::
   :maxdepth: 2

   quickstart
   tags
   advanced

Citations is a simple Django app which lets you use a citations and
reference lists within your templates.

 - The source code is available from https://github.com/will-hart/django-citations under an MIT license.
 - You can find the package on the Python Packing Index https://pypi.python.org/pypi/django-citations/.
 - The latest documentation for the `develop` branch is available from http://django-citations.readthedocs.org/en/latest/

Supported Fields
----------------

The fields currently supported by the django-citations database include:

 - type (currently one of book, electronic journal, journal or website)
 - slug (unique ID for the reference, max 128 characters)
 - author (max 512 characters)
 - title (max 512 characters)
 - year (a number)
 - series (max 512 characters)
 - volume (a number)
 - edition (a number)
 - isbn (up to 17 characters - can include dashes)
 - url (the URL where the resource was accessed online)
 - publisher (max 128 characters)
 - place (place of publishing, max 128 characters)
 - abstract (free text)
 - comments (free text)
 - keywords (free text)
 - accessed (the date the resource was first accessed)

Change Log
----------

**Version 0.3**
 - Improved documentation
 - Add new fields to database
 - Add bibtex upload function, where `bibtexparser` is installed
 - Add `show_all_references` tag for complete bibliography

**Version 0.2.1**
 - Fix tags in README

**Version 0.2**

 - Improved citation database - more fields available
 - Improved reference output (uses a Harvard referencing format)

**Version 1.0**

 - Initial version