text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>squaremo/rabbit.js · GitHub</title>
    <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub" />
    <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub" />
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png" />
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png" />
    <link rel="logo" type="image/svg" href="https://github-media-downloads.s3.amazonaws.com/github-logo.svg" />
    <meta property="og:image" content="https://github.global.ssl.fastly.net/images/modules/logos_page/Octocat.png">
    <meta name="hostname" content="github-fe114-cp1-prd.iad.github.net">
    <meta name="ruby" content="ruby 1.9.3p194-tcs-github-tcmalloc (e1c0c3f392) [x86_64-linux]">
    <link rel="assets" href="https://github.global.ssl.fastly.net/">
    <link rel="conduit-xhr" href="https://ghconduit.com:25035/">
    <link rel="xhr-socket" href="/_sockets" />

    <meta name="msapplication-TileImage" content="/windows-tile.png" />
    <meta name="msapplication-TileColor" content="#ffffff" />
    <meta name="selected-link" value="repo_source" data-pjax-transient />
    <meta content="collector.githubapp.com" name="octolytics-host" /><meta content="collector-cdn.github.com" name="octolytics-script-host" /><meta content="github" name="octolytics-app-id" /><meta content="626FD489:2D7A:2C65CA:52902004" name="octolytics-dimension-request_id" />

    <link rel="icon" type="image/x-icon" href="/favicon.ico" />

    <meta content="authenticity_token" name="csrf-param" />
<meta content="5S9iWMfAGQAwY4uYK67HTfTED4W5E1ConBiL2xz6UDw=" name="csrf-token" />

    <link href="https://github.global.ssl.fastly.net/assets/github-98e5fdcb5f495c90432b9fa79429de457474a366.css" media="all" rel="stylesheet" type="text/css" />
    <link href="https://github.global.ssl.fastly.net/assets/github2-ba8344a0d63f96ce25c8bd5e556ee2d9fb1659c1.css" media="all" rel="stylesheet" type="text/css" />

      <meta http-equiv="x-pjax-version" content="8995ce1292f03ccb0ea6f7619d531aa9">

        <meta property="og:title" content="rabbit.js"/>
  <meta property="og:type" content="githubog:gitrepository"/>
  <meta property="og:url" content="https://github.com/squaremo/rabbit.js"/>
  <meta property="og:image" content="https://github.global.ssl.fastly.net/images/gravatars/gravatar-user-420.png"/>
  <meta property="og:site_name" content="GitHub"/>
  <meta property="og:description" content="rabbit.js - Messaging in Node.JS made easy using RabbitMQ"/>

  <meta name="description" content="rabbit.js - Messaging in Node.JS made easy using RabbitMQ" />

  <meta content="62033" name="octolytics-dimension-user_id" /><meta content="squaremo" name="octolytics-dimension-user_login" /><meta content="949801" name="octolytics-dimension-repository_id" /><meta content="squaremo/rabbit.js" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="949801" name="octolytics-dimension-repository_network_root_id" /><meta content="squaremo/rabbit.js" name="octolytics-dimension-repository_network_root_nwo" />
  <link href="https://github.com/squaremo/rabbit.js/commits/master.atom" rel="alternate" title="Recent Commits to rabbit.js:master" type="application/atom+xml" />

        Sign up
      Sign in

Explore

Features

Enterprise

Blog

        <form accept-charset="UTF-8" action="/search" class="command-bar-form" id="top_search_form" method="get">

<input type="text" data-hotkey=" s" name="q" id="js-command-bar-field" placeholder="Search or type a command" tabindex="1" autocapitalize="off"

      data-repo="squaremo/rabbit.js"
      data-branch="master"
      data-sha="b49b018fc7cba788ed0e20166e09840356408e6a"
  >

    <input type="hidden" name="nwo" value="squaremo/rabbit.js" />

        This repository

            <input type="radio" class="js-search-this-repository" name="search_target" value="repository" checked="checked" />

This repository

            <input type="radio" name="search_target" value="global" />

All repositories

  <input type="hidden" name="ref" value="cmdform">

</form>

    Star

      508

        Fork

        49

          public

            squaremo

          /
          rabbit.js

           Code

             Issues
            10

             Pull Requests
            2

           Pulse

           Graphs

           Network

HTTPS clone URL

    <input type="text" class="clone js-url-field"
           value="https://github.com/squaremo/rabbit.js.git" readonly="readonly">

Subversion checkout URL

    <input type="text" class="clone js-url-field"
           value="https://github.com/squaremo/rabbit.js" readonly="readonly">

You can clone with
      HTTPS,
      or Subversion.

                Download ZIP

Messaging in Node.JS made easy using RabbitMQ

              96

            commits

            4

          branches

            3

          releases

            Fetching contributors

                JavaScript
                100%

  JavaScript

    branch:
    master

        Switch branches/tags

          <input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="js-filterable-field js-navigation-enable" placeholder="Filter branches/tags">

              Branches

              Tags

              amqplib

              master

              proper_streams

              v0.3

Nothing to show

              v0.2.2

              v0.2.1-amqplib

              v0.2.1

Nothing to show

rabbit.js / <form action="/login?return_to=%2Fsquaremo%2Frabbit.js" class="js-new-blob-form tooltipped rightwards new-file-link" method="post" title="Sign in to make or propose changes"></form>

Show File Finder

        Add syntax highlighting to Readme

      latest commit 58618c9fbb

        timoxley
        authored <time class="js-relative-date updated" datetime="2013-07-22T23:10:50-07:00" title="2013-07-22 23:10:50">July 22, 2013</time>

        example

        Use sockjs 0.2

      <time class="js-relative-date" datetime="2012-03-22T04:56:51-07:00" title="2012-03-22 04:56:51">March 22, 2012</time>

        lib

        Convert expirations to strings, to avoid surprises

      <time class="js-relative-date" datetime="2013-07-18T12:08:51-07:00" title="2013-07-18 12:08:51">July 18, 2013</time>

        test

        Convert expirations to strings, to avoid surprises

      <time class="js-relative-date" datetime="2013-07-18T12:08:51-07:00" title="2013-07-18 12:08:51">July 18, 2013</time>

        .gitignore

        Ignore emacs backups and npm logs

      <time class="js-relative-date" datetime="2013-05-02T08:48:26-07:00" title="2013-05-02 08:48:26">May 02, 2013</time>

        LICENSE

        License.

      <time class="js-relative-date" datetime="2010-11-15T07:49:20-08:00" title="2010-11-15 07:49:20">November 15, 2010</time>

        LICENSE-MPL

        License.

      <time class="js-relative-date" datetime="2010-11-15T07:49:20-08:00" title="2010-11-15 07:49:20">November 15, 2010</time>

        README.md

        Add syntax highlighting to Readme

      <time class="js-relative-date" datetime="2013-07-22T23:10:50-07:00" title="2013-07-22 23:10:50">July 22, 2013</time>

        RELEASE_NOTES

        Release notes and version bump for v0.2.2

      <time class="js-relative-date" datetime="2013-07-03T07:49:14-07:00" title="2013-07-03 07:49:14">July 03, 2013</time>

        index.js

        Tidy up packaging; bump minor version to denote change in API (major …

      <time class="js-relative-date" datetime="2012-01-06T04:18:31-08:00" title="2012-01-06 04:18:31">January 06, 2012</time>

        package.json

        Release notes and version bump for v0.2.2

      <time class="js-relative-date" datetime="2013-07-03T07:49:14-07:00" title="2013-07-03 07:49:14">July 03, 2013</time>

      README.md

Messaging in Node.JS with RabbitMQ

$ npm install rabbit.js

This library provides a simple, socket-oriented API* for messaging in
node.js, using
RabbitMQ as a backend.

var context = require('rabbit.js').createContext();
context.on('ready', function() {
  var pub = context.socket('PUB'), sub = context.socket('SUB');
  sub.pipe(process.stdout);
  sub.connect('events', function() {
    pub.connect('events', function() {
      pub.write(JSON.stringify({welcome: 'rabbit.js'}), 'utf8');
    });
  });
});

*Yes, rather like ZeroMQ. See below.

Status

Still on major version 0, though in use in a number of places, I
believe.

For the minute there are two branches: master continues the original
implementation, based on node-amqp. amqplib has a reimplementation
based on amqplib, which I believe to be the Way Forward. These are
available in npm as "regular" versions (e.g., 0.2.2), and "amqplib"
versions (e.g., 0.2.1-amqplib). The features and API are equivalent
in equivalent version numbers.

Version 0.2.2 will likely be the last version based on node-amqp.

Uses

This library is suitable for co-ordinating peers (e.g., Node.JS
programs), acting as a gateway to other kinds of network (e.g.,
relaying to browsers via SockJS), or simply as a really easy way to
use RabbitMQ.

API

The entry point is createContext, which gives you a factory for
sockets. You supply it the URL to your RabbitMQ server:

var context = require('rabbit.js').createContext('amqp://localhost');

A context emits 'error' with an Error object if there's a problem
with the underlying connection to the server. This invalidates the
context and all its sockets.

A context may be disconnected from the server with #close(). It will
emit 'close' once the underlying connection has been terminated.

To start sending or receiving messages you need to acquire a socket:

var pub = context.socket('PUB');
var sub = context.socket('SUB');

and connect it to something:

pub.connect('alerts');
sub.connect('alerts');

Sockets act like ("old style")
Streams; in
particular you will get 'data' events from those that are readable,
and you can write() to those that are writable. If you're expecting
data that is encoded strings, you can setEncoding() to get strings
instead of buffers as data events.

sub.setEncoding('utf8');
sub.on('data', function(note) { console.log("Alarum! " + note); });

pub.write("Emergency. There's an emergency going on", 'utf8');

You can also use pipe to forward messages to or from another stream,
making relaying simple:

sub.pipe(process.stdout);

A socket may be connected more than once, by calling
socket.connect(x) with different xs. What this entails depends on
the socket type (see below), but messages to and from different
connect()ions are not distinguished. For example

var sub2 = context.socket('SUB');
sub2.connect('system');
sub2.connect('notifications');

Here, the socket sub2 will receive all messages published to
'system' and all those published to 'notifications' as well, but
it is not possible to discriminate between the sources.

Some socket types have options that may be set with
#setsockopt. Presently there's just one option, on PUB and PUSH
sockets, which is message expiration, given as a stringified number of
milliseconds:

pub.setsockopt('expiration', '60000')

In the example, messages written to pub will be discarded by the
server if they've not been delivered after 60,000
milliseconds. Message expiration only works with versions of RabbitMQ
newer than 3.0.0.

Lastly, a socket may be closed using #end(); this will clean up
resources, and emit 'end' once it's done so.

Socket types

The socket types, passed as an argument to Context#socket, determine
whether the socket is readable and writable, and what happens to
messages written to it. Socket types (but not necessarily sockets
themselves) should be used in the pairs described below.

To make the descriptions a bit easier, we'll say if
connect(x) is called on a socket for some x, the socket has a
connection to x.

PUBlish / SUBscribe: every SUB socket connected to  gets
each message sent by a PUB socket connected to ; a PUB socket
sends every message to each of its connections. SUB sockets are
readable only, and PUB sockets are writable only.

PUSH / PULL: a PUSH socket will send each message to a
single connection, using round-robin. A PULL socket will receive a
share of the messages sent to each  to which it is connected,
determined by round-robin at . PUSH sockets are writable only, and
PULL sockets are readable only.

REQuest / REPly: a REQ socket sends each message to one of
its connections, and receives replies in turn; a REP socket receives a
share of the messages sent to each  to which it is connected, and
must send a reply in turn. REQ and REP sockets are both readable and
writable.

Using with servers

A few modules have a socket-server-like abstraction; canonically, the
net module, but also for example SockJS and Socket.IO. These can be
adapted using something similar to the following.

var context = new require('rabbit.js').createContext('amqp://localhost');
var inServer = net.createServer(function(connection) {
  var s = context.socket('PUB');
  s.connect('incoming');
  connection.pipe(s);
});
inServer.listen(5000);

This is a simplistic example; a bare TCP socket won't in general emit
data in chunks that are meaningful to applications, even if they are
written that way at the far end. A library such as
spb can be used encode and
decode message streams in byte streams if needed.

Examples

Each subdirectory of example has code demonstrating using
rabbit.js with other modules. Install the prerequisites for rabbit.js
first:

rabbit.js$ npm install

Now each example can be run with, e.g.,

rabbit.js$ cd example/sockjs
sockjs$ npm install && npm start

All of the examples assume there is a RabbitMQ server
running locally. The SockJS and
Socket.IO examples both start a website which you can visit at
http://localhost:8080.

Relation to ZeroMQ

rabbit.js was inspired by the RabbitMQ/ZeroMQ
adapter I developed with Martin
Sústrik. The rationale for using RabbitMQ in a ZeroMQ-based network is
largely transferable to rabbit.js:

RabbitMQ introduces a degree of monitoring and transparency,
especially if one uses the web management app;

RabbitMQ can bridge to other protocols (notably AMQP and STOMP);

RabbitMQ provides reliable, persistent queues if desired

with some additional benefits:

since rabbit.js sockets implement the Stream interface, one
can easily pipe messages around

using RabbitMQ as a backend obviates some configuration management
-- just supply all instances the broker URL and you're good to go.

there's room in the API for more involved routing and other
behaviour since AMQP is, well, more complicated let's say.

Here are some notable differences and similarities to ZeroMQ in
rabbit.js's API and semantics.

To start, there's no distinction in rabbit.js between clients and
servers (connect and bind in ZeroMQ, following the BSD socket
API), since RabbitMQ is effectively acting as a relaying server for
everyone to connect to. Relatedly, the argument supplied to
connect() is abstract, in the sense that it's just a name rather
than a transport-layer address.

Request and Reply sockets have very similar semantics to those in
ZeroMQ. Requesting sockets must take care not to issue more than
request at a time, or to label requests (and rely on repliers
preserving the label in replies) such that the answers can be
correlated with the requests. Actually this is much the same as
ZeroMQ; it follows from the possibility of replies coming back out of
order due to round-robining. Repliers must respond to requests in the
order that they come in, and respond exactly once to each request.

There are no DEALER or ROUTER sockets (a.k.a., XREQ and XREQ) in
rabbit.js. In ZeroMQ these are implemented by prefixing messages with
a reverse path, which then requires encoding and thereby complication
when relaying to other streams or protocols. Instead, rabbit.js notes
the reverse path as messages are relayed to a REP socket, and
reapplies it when the response appears (giving rise to the ordering
requirement on repliers).

Relation to AMQP and STOMP

rabbit.js makes some simplifying assumptions that must be kept in mind
when integrating with other protocols that RabbitMQ supports.

PUB and SUB sockets declare non-durable fanout exchanges named for the
argument given to connect. To send to SUB sockets or receive from
PUB sockets, publish or bind (or subscribe in the case of STOMP) to
the exchange with the same name.

PUSH, PULL, REQ and REP sockets use durable, non-exclusive queues
named for the argument given to connect. If you are replying, be
sure to follow the convention of sending the response to the queue
given in the 'replyTo' property of the request message.

What happened to listen()?

I removed it. It wasn't entirely wrong, but it did have two failings:
firstly, it exposed the socket type and the address to the (end)
client, while the client ought not to need know about them; secondly,
and more fatally, it required a dedicated client connection per
socket, which is a problem for e.g., browsers.

The new API avoids these problems by not requiring any particular
behaviour from a client connection -- that is totally up to you (if
you even use any client connections). If you need to multiplex on a
client connection you can do that by, say, prefixing each message with
a channel name; or, as the Socket.IO example does, combine two simplex
sockets onto a duplex client connection.

Status

API

Training

Shop

Blog

About

© 2013 GitHub, Inc.

Terms

Privacy

Security

Contact

      <textarea name="fullscreen-contents" id="fullscreen-contents" class="js-fullscreen-contents" placeholder="" data-suggester="fullscreen_suggester"></textarea>

      Something went wrong with that request. Please try again.


text:
package org.omg.GIOP;

//
// IDL:omg.org/GIOP/IORAddressingInfo:1.0
//
final public class IORAddressingInfoHelper
{
    public static void
    insert(org.omg.CORBA.Any any, IORAddressingInfo val)
    {
        org.omg.CORBA.portable.OutputStream out = any.create_output_stream();
        write(out, val);
        any.read_value(out.create_input_stream(), type());
    }

    public static IORAddressingInfo
    extract(org.omg.CORBA.Any any)
    {
        if(any.type().equivalent(type()))
            return read(any.create_input_stream());
        else
            throw new org.omg.CORBA.BAD_OPERATION();
    }

    private static org.omg.CORBA.TypeCode typeCode_;

    public static org.omg.CORBA.TypeCode
    type()
    {
        if(typeCode_ == null)
        {
            org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
            org.omg.CORBA.StructMember[] members = new org.omg.CORBA.StructMember[2];

            members[0] = new org.omg.CORBA.StructMember();
            members[0].name = "selected_profile_index";
            members[0].type = orb.get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong);

            members[1] = new org.omg.CORBA.StructMember();
            members[1].name = "ior";
            members[1].type = org.omg.IOP.IORHelper.type();

            typeCode_ = orb.create_struct_tc(id(), "IORAddressingInfo", members);
        }

        return typeCode_;
    }

    public static String
    id()
    {
        return "IDL:omg.org/GIOP/IORAddressingInfo:1.0";
    }

    public static IORAddressingInfo
    read(org.omg.CORBA.portable.InputStream in)
    {
        IORAddressingInfo _ob_v = new IORAddressingInfo();
        _ob_v.selected_profile_index = in.read_ulong();
        _ob_v.ior = org.omg.IOP.IORHelper.read(in);
        return _ob_v;
    }

    public static void
    write(org.omg.CORBA.portable.OutputStream out, IORAddressingInfo val)
    {
        out.write_ulong(val.selected_profile_index);
        org.omg.IOP.IORHelper.write(out, val.ior);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// This is a generated file. Not intended for manual editing.
package com.intellij.lang.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.lang.yang.psi.YangTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.psi.*;

public class YangDeviateAddStmtImpl extends ASTWrapperPsiElement implements YangDeviateAddStmt {

  public YangDeviateAddStmtImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof YangVisitor) ((YangVisitor)visitor).visitDeviateAddStmt(this);
    else super.accept(visitor);
  }

  @Override
  @NotNull
  public List<YangConfigStmt> getConfigStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangConfigStmt.class);
  }

  @Override
  @NotNull
  public List<YangDefaultStmt> getDefaultStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangDefaultStmt.class);
  }

  @Override
  @NotNull
  public List<YangIdentifierStmt> getIdentifierStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangIdentifierStmt.class);
  }

  @Override
  @NotNull
  public List<YangMandatoryStmt> getMandatoryStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangMandatoryStmt.class);
  }

  @Override
  @NotNull
  public List<YangMaxElementsStmt> getMaxElementsStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangMaxElementsStmt.class);
  }

  @Override
  @NotNull
  public List<YangMinElementsStmt> getMinElementsStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangMinElementsStmt.class);
  }

  @Override
  @NotNull
  public List<YangMustStmt> getMustStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangMustStmt.class);
  }

  @Override
  @NotNull
  public YangString getString() {
    return findNotNullChildByClass(YangString.class);
  }

  @Override
  @NotNull
  public List<YangUniqueStmt> getUniqueStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangUniqueStmt.class);
  }

  @Override
  @NotNull
  public List<YangUnitsStmt> getUnitsStmtList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, YangUnitsStmt.class);
  }

}


text:
using FizzWare.NBuilder.Implementation;
using FizzWare.NBuilder.Tests.Integration.Models;

using Shouldly;
using Xunit;

namespace FizzWare.NBuilder.Tests.Integration.Extensibility
{

    public class ExtensibilityTests
    {

        [Fact]
        public void AddingACustom_With_ExtensionForProducts()
        {
            BuilderSettings builderSettings = new RepositoryBuilderSetup().DoSetup();
            var products = new Builder(builderSettings)
                .CreateListOfSize<Product>(10)
                .All()
                .WithWarehouseLocations() // This will only appear when using Builder<Product>
                .Build();

            products[0].Location.Aisle.ShouldBe('A');
            products[0].Location.Shelf.ShouldBe(1);
            products[0].Location.Location.ShouldBe(7500);

            products[9].Location.Aisle.ShouldBe('J');
            products[9].Location.Shelf.ShouldBe(10);
            products[9].Location.Location.ShouldBe(16500);
        }

        [Fact]
        public void SpecifyingACustomPropertyNamerForASpecificType()
        {
            BuilderSettings builderSettings = new RepositoryBuilderSetup().DoSetup();
            builderSettings.SetPropertyNamerFor<Product>(new CustomProductPropertyNamer(new ReflectionUtil(),builderSettings));

            var products = new Builder(builderSettings).CreateListOfSize<Product>(10).Build();

            products[0].Location.Aisle.ShouldBe('A');
            products[0].Location.Shelf.ShouldBe(2);
            products[0].Location.Location.ShouldBe(1000);

            products[9].Location.Aisle.ShouldBe('J');
            products[9].Location.Shelf.ShouldBe(20);
            products[9].Location.Location.ShouldBe(10000);

            // Reset it afterwards so the other tests work as expected
            builderSettings.ResetToDefaults();
        }
    }
}


text:
package core

import (
	"bytes"
	"context"
	"fmt"

	"github.com/pingcap/failpoint"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/parser/mysql"
)

// canProjectionBeEliminatedLoose checks whether a projection can be eliminated,
// returns true if every expression is a single column.
func canProjectionBeEliminatedLoose(p *LogicalProjection) bool {
	for _, expr := range p.Exprs {
		_, ok := expr.(*expression.Column)
		if !ok {
			return false
		}
	}
	return true
}

// canProjectionBeEliminatedStrict checks whether a projection can be
// eliminated, returns true if the projection just copy its child's output.
func canProjectionBeEliminatedStrict(p *PhysicalProjection) bool {
	// This is due to the in-compatibility between TiFlash and TiDB:
	// For TiDB, the output schema of final agg is all the aggregated functions and for
	// TiFlash, the output schema of agg(TiFlash not aware of the aggregation mode) is
	// aggregated functions + group by columns, so to make the things work, for final
	// mode aggregation that need to be running in TiFlash, always add an extra Project
	// the align the output schema. In the future, we can solve this in-compatibility by
	// passing down the aggregation mode to TiFlash.
	if physicalAgg, ok := p.Children()[0].(*PhysicalHashAgg); ok {
		if physicalAgg.MppRunMode == Mpp1Phase || physicalAgg.MppRunMode == Mpp2Phase || physicalAgg.MppRunMode == MppScalar {
			if physicalAgg.IsFinalAgg() {
				return false
			}
		}
	}
	if physicalAgg, ok := p.Children()[0].(*PhysicalStreamAgg); ok {
		if physicalAgg.MppRunMode == Mpp1Phase || physicalAgg.MppRunMode == Mpp2Phase || physicalAgg.MppRunMode == MppScalar {
			if physicalAgg.IsFinalAgg() {
				return false
			}
		}
	}
	// If this projection is specially added for `DO`, we keep it.
	if p.CalculateNoDelay {
		return false
	}
	if p.Schema().Len() == 0 {
		return true
	}
	child := p.Children()[0]
	if p.Schema().Len() != child.Schema().Len() {
		return false
	}
	for i, expr := range p.Exprs {
		col, ok := expr.(*expression.Column)
		if !ok || !col.Equal(nil, child.Schema().Columns[i]) {
			return false
		}
	}
	return true
}

func resolveColumnAndReplace(origin *expression.Column, replace map[string]*expression.Column) {
	dst := replace[string(origin.HashCode(nil))]
	if dst != nil {
		retType, inOperand := origin.RetType, origin.InOperand
		*origin = *dst
		origin.RetType, origin.InOperand = retType, inOperand
	}
}

// ResolveExprAndReplace replaces columns fields of expressions by children logical plans.
func ResolveExprAndReplace(origin expression.Expression, replace map[string]*expression.Column) {
	switch expr := origin.(type) {
	case *expression.Column:
		resolveColumnAndReplace(expr, replace)
	case *expression.CorrelatedColumn:
		resolveColumnAndReplace(&expr.Column, replace)
	case *expression.ScalarFunction:
		for _, arg := range expr.GetArgs() {
			ResolveExprAndReplace(arg, replace)
		}
	}
}

func doPhysicalProjectionElimination(p PhysicalPlan) PhysicalPlan {
	for i, child := range p.Children() {
		p.Children()[i] = doPhysicalProjectionElimination(child)
	}

	// eliminate projection in a coprocessor task
	tableReader, isTableReader := p.(*PhysicalTableReader)
	if isTableReader && tableReader.StoreType == kv.TiFlash {
		tableReader.tablePlan = eliminatePhysicalProjection(tableReader.tablePlan)
		tableReader.TablePlans = flattenPushDownPlan(tableReader.tablePlan)
		return p
	}

	proj, isProj := p.(*PhysicalProjection)
	if !isProj || !canProjectionBeEliminatedStrict(proj) {
		return p
	}
	child := p.Children()[0]
	if childProj, ok := child.(*PhysicalProjection); ok {
		childProj.SetSchema(p.Schema())
	}
	return child
}

// eliminatePhysicalProjection should be called after physical optimization to
// eliminate the redundant projection left after logical projection elimination.
func eliminatePhysicalProjection(p PhysicalPlan) PhysicalPlan {
	failpoint.Inject("DisableProjectionPostOptimization", func(val failpoint.Value) {
		if val.(bool) {
			failpoint.Return(p)
		}
	})

	oldSchema := p.Schema()
	newRoot := doPhysicalProjectionElimination(p)
	newCols := newRoot.Schema().Columns
	for i, oldCol := range oldSchema.Columns {
		oldCol.Index = newCols[i].Index
		oldCol.ID = newCols[i].ID
		oldCol.UniqueID = newCols[i].UniqueID
		oldCol.VirtualExpr = newCols[i].VirtualExpr
		newRoot.Schema().Columns[i] = oldCol
	}
	return newRoot
}

type projectionEliminator struct {
}

// optimize implements the logicalOptRule interface.
func (pe *projectionEliminator) optimize(ctx context.Context, lp LogicalPlan, opt *logicalOptimizeOp) (LogicalPlan, error) {
	root := pe.eliminate(lp, make(map[string]*expression.Column), false, opt)
	return root, nil
}

// eliminate eliminates the redundant projection in a logical plan.
func (pe *projectionEliminator) eliminate(p LogicalPlan, replace map[string]*expression.Column, canEliminate bool, opt *logicalOptimizeOp) LogicalPlan {
	proj, isProj := p.(*LogicalProjection)
	childFlag := canEliminate
	if _, isUnion := p.(*LogicalUnionAll); isUnion {
		childFlag = false
	} else if _, isAgg := p.(*LogicalAggregation); isAgg || isProj {
		childFlag = true
	} else if _, isWindow := p.(*LogicalWindow); isWindow {
		childFlag = true
	}
	for i, child := range p.Children() {
		p.Children()[i] = pe.eliminate(child, replace, childFlag, opt)
	}

	switch x := p.(type) {
	case *LogicalJoin:
		x.schema = buildLogicalJoinSchema(x.JoinType, x)
	case *LogicalApply:
		x.schema = buildLogicalJoinSchema(x.JoinType, x)
	default:
		for _, dst := range p.Schema().Columns {
			resolveColumnAndReplace(dst, replace)
		}
	}
	p.replaceExprColumns(replace)
	if isProj {
		if child, ok := p.Children()[0].(*LogicalProjection); ok && !ExprsHasSideEffects(child.Exprs) {
			for i := range proj.Exprs {
				proj.Exprs[i] = ReplaceColumnOfExpr(proj.Exprs[i], child, child.Schema())
				foldedExpr := expression.FoldConstant(proj.Exprs[i])
				// the folded expr should have the same null flag with the original expr, especially for the projection under union, so forcing it here.
				foldedExpr.GetType().SetFlag((foldedExpr.GetType().GetFlag() & ^mysql.NotNullFlag) | (proj.Exprs[i].GetType().GetFlag() & mysql.NotNullFlag))
				proj.Exprs[i] = foldedExpr
			}
			p.Children()[0] = child.Children()[0]
			appendDupProjEliminateTraceStep(proj, child, opt)
		}
	}

	if !(isProj && canEliminate && canProjectionBeEliminatedLoose(proj)) {
		return p
	}
	exprs := proj.Exprs
	for i, col := range proj.Schema().Columns {
		replace[string(col.HashCode(nil))] = exprs[i].(*expression.Column)
	}
	appendProjEliminateTraceStep(proj, opt)
	return p.Children()[0]
}

// ReplaceColumnOfExpr replaces column of expression by another LogicalProjection.
func ReplaceColumnOfExpr(expr expression.Expression, proj *LogicalProjection, schema *expression.Schema) expression.Expression {
	switch v := expr.(type) {
	case *expression.Column:
		idx := schema.ColumnIndex(v)
		if idx != -1 && idx < len(proj.Exprs) {
			return proj.Exprs[idx]
		}
	case *expression.ScalarFunction:
		for i := range v.GetArgs() {
			v.GetArgs()[i] = ReplaceColumnOfExpr(v.GetArgs()[i], proj, schema)
		}
	}
	return expr
}

func (p *LogicalJoin) replaceExprColumns(replace map[string]*expression.Column) {
	for _, equalExpr := range p.EqualConditions {
		ResolveExprAndReplace(equalExpr, replace)
	}
	for _, leftExpr := range p.LeftConditions {
		ResolveExprAndReplace(leftExpr, replace)
	}
	for _, rightExpr := range p.RightConditions {
		ResolveExprAndReplace(rightExpr, replace)
	}
	for _, otherExpr := range p.OtherConditions {
		ResolveExprAndReplace(otherExpr, replace)
	}
}

func (p *LogicalProjection) replaceExprColumns(replace map[string]*expression.Column) {
	for _, expr := range p.Exprs {
		ResolveExprAndReplace(expr, replace)
	}
}

func (la *LogicalAggregation) replaceExprColumns(replace map[string]*expression.Column) {
	for _, agg := range la.AggFuncs {
		for _, aggExpr := range agg.Args {
			ResolveExprAndReplace(aggExpr, replace)
		}
	}
	for _, gbyItem := range la.GroupByItems {
		ResolveExprAndReplace(gbyItem, replace)
	}
}

func (p *LogicalSelection) replaceExprColumns(replace map[string]*expression.Column) {
	for _, expr := range p.Conditions {
		ResolveExprAndReplace(expr, replace)
	}
}

func (la *LogicalApply) replaceExprColumns(replace map[string]*expression.Column) {
	la.LogicalJoin.replaceExprColumns(replace)
	for _, coCol := range la.CorCols {
		dst := replace[string(coCol.Column.HashCode(nil))]
		if dst != nil {
			coCol.Column = *dst
		}
	}
}

func (ls *LogicalSort) replaceExprColumns(replace map[string]*expression.Column) {
	for _, byItem := range ls.ByItems {
		ResolveExprAndReplace(byItem.Expr, replace)
	}
}

func (lt *LogicalTopN) replaceExprColumns(replace map[string]*expression.Column) {
	for _, byItem := range lt.ByItems {
		ResolveExprAndReplace(byItem.Expr, replace)
	}
}

func (p *LogicalWindow) replaceExprColumns(replace map[string]*expression.Column) {
	for _, desc := range p.WindowFuncDescs {
		for _, arg := range desc.Args {
			ResolveExprAndReplace(arg, replace)
		}
	}
	for _, item := range p.PartitionBy {
		resolveColumnAndReplace(item.Col, replace)
	}
	for _, item := range p.OrderBy {
		resolveColumnAndReplace(item.Col, replace)
	}
}

func (*projectionEliminator) name() string {
	return "projection_eliminate"
}

func appendDupProjEliminateTraceStep(parent, child *LogicalProjection, opt *logicalOptimizeOp) {
	action := func() string {
		buffer := bytes.NewBufferString(
			fmt.Sprintf("%v_%v is eliminated, %v_%v's expressions changed into[", child.TP(), child.ID(), parent.TP(), parent.ID()))
		for i, expr := range parent.Exprs {
			if i > 0 {
				buffer.WriteString(",")
			}
			buffer.WriteString(expr.String())
		}
		buffer.WriteString("]")
		return buffer.String()
	}
	reason := func() string {
		return fmt.Sprintf("%v_%v's child %v_%v is redundant", parent.TP(), parent.ID(), child.TP(), child.ID())
	}
	opt.appendStepToCurrent(child.ID(), child.TP(), reason, action)
}

func appendProjEliminateTraceStep(proj *LogicalProjection, opt *logicalOptimizeOp) {
	reason := func() string {
		return fmt.Sprintf("%v_%v's Exprs are all Columns", proj.TP(), proj.ID())
	}
	action := func() string {
		return fmt.Sprintf("%v_%v is eliminated", proj.TP(), proj.ID())
	}
	opt.appendStepToCurrent(proj.ID(), proj.TP(), reason, action)
}


text:
#include "fudge/status.h"

const char * FudgeStatus_strerror ( FudgeStatus status )
{
    switch ( status )
    {
        case FUDGE_OK:                            return "OK";
        case FUDGE_OUT_OF_MEMORY:                 return "Out of Memory";
        case FUDGE_NULL_POINTER:                  return "Null Pointer";
        case FUDGE_INVALID_INDEX:                 return "Invalid Index";
        case FUDGE_INVALID_NAME:                  return "Invalid Name";
        case FUDGE_INVALID_ORDINAL:               return "Invalid Ordinal";
        case FUDGE_NAME_TOO_LONG:                 return "Name Too Long";
        case FUDGE_PAYLOAD_TOO_LONG:              return "Payload Too Long";
        case FUDGE_INVALID_TYPE_COERCION:         return "Invaild Type Coercion";
        case FUDGE_COERCION_NOT_REQUIRED:         return "Coercion Not Required";
        case FUDGE_INVALID_TYPE_ACCESSOR:         return "Cannot use this accessor/field type combination";
        case FUDGE_INVALID_USER_TYPE:             return "Invalid User Type";
        case FUDGE_STRING_INVALID_ASCII:          return "Invalid ASCII char in string";
        case FUDGE_STRING_INVALID_UNICODE:        return "Invalid Unicode char encountered";
        case FUDGE_STRING_INCOMPLETE_UNICODE:     return "Incomplete Unicode char encountered";
        case FUDGE_STRING_UNCONSUMED_UNICODE:     return "Unicode conversion did not consume all source chars";
        case FUDGE_STRING_INVALID_SURROGATE:      return "Invalid 3-byte modified UTF8 sequence";
        case FUDGE_STRING_UNKNOWN_UNICODE_TYPE:   return "Unicode type was not recognised";
        case FUDGE_OUT_OF_BYTES:                  return "Out of Bytes";
        case FUDGE_UNKNOWN_FIELD_WIDTH:           return "Unknown Field Width";
        case FUDGE_DATETIME_INVALID_YEAR:         return "Invalid value for Year";
        case FUDGE_DATETIME_INVALID_MONTH:        return "Invalid value for Month";
        case FUDGE_DATETIME_INVALID_DAY:          return "Invalid value for Day of Month";
        case FUDGE_DATETIME_INVALID_SECONDS:      return "Invalid value for Seconds since midnight";
        case FUDGE_DATETIME_INVALID_NANOSECONDS:  return "Invalid value for Nanoseconds since start of second";
        case FUDGE_PTHREAD_MUTEX_RESOURCES:       return "Insufficient resources to create pthread Mutex";
        case FUDGE_PTHREAD_MUTEX_BUSY:            return "Cannot destroy pthread mutex that's locked by another thread";
        case FUDGE_PTHREAD_MUTEX_INVALID:         return "Invalid pthread mutex handle";
        case FUDGE_PTHREAD_MUTEX_UNKNOWN:         return "Unknown pthread mutex error";
        case FUDGE_INTERNAL_LIST_STATE:           return "Internal List State";
        case FUDGE_INTERNAL_PAYLOAD:              return "Internal Type Payload Is Invalid";
        case FUDGE_REGISTRY_UNINITIALISED:        return "Fudge Registry Not Initialised";
        case FUDGE_CHANGED_MEMORY_MANAGER:        return "Called Fudge_Init with different memory manager than first call";
        default:                                  return "Unknown Status";
    }
}


text:
"""
Simple example of a db checker: define a L{ICredentialsChecker} implementation
that deals with a database backend to authenticate a user.
"""

from twisted.cred import error
from twisted.cred.credentials import IUsernameHashedPassword, IUsernamePassword
from twisted.cred.checkers import ICredentialsChecker
from twisted.internet.defer import Deferred

from zope.interface import implements

class DBCredentialsChecker(object):
    """
    This class checks the credentials of incoming connections
    against a user table in a database.
    """
    implements(ICredentialsChecker)

    def __init__(self, runQuery,
        query="SELECT username, password FROM user WHERE username = %s",
        customCheckFunc=None, caseSensitivePasswords=True):
        """
        @param runQuery: This will be called to get the info from the db.
            Generally you'd want to create a
            L{twisted.enterprice.adbapi.ConnectionPool} and pass it's runQuery
            method here. Otherwise pass a function with the same prototype.
        @type runQuery: C{callable}

        @type query: query used to authenticate user.
        @param query: C{str}

        @param customCheckFunc: Use this if the passwords in the db are stored
            as hashes. We'll just call this, so you can do the checking
            yourself. It takes the following params:
            (username, suppliedPass, dbPass) and must return a boolean.
        @type customCheckFunc: C{callable}

        @param caseSensitivePasswords: If true requires that every letter in
            C{credentials.password} is exactly the same case as the it's
            counterpart letter in the database.
            This is only relevant if C{customCheckFunc} is not used.
        @type caseSensitivePasswords: C{bool}
        """
        self.runQuery = runQuery
        self.caseSensitivePasswords = caseSensitivePasswords
        self.customCheckFunc = customCheckFunc
        # We can't support hashed password credentials if we only have a hash
        # in the DB
        if customCheckFunc:
            self.credentialInterfaces = (IUsernamePassword,)
        else:
            self.credentialInterfaces = (
                IUsernamePassword, IUsernameHashedPassword,)

        self.sql = query

    def requestAvatarId(self, credentials):
        """
        Authenticates the kiosk against the database.
        """
        # Check that the credentials instance implements at least one of our
        # interfaces
        for interface in self.credentialInterfaces:
            if interface.providedBy(credentials):
                break
        else:
            raise error.UnhandledCredentials()
        # Ask the database for the username and password
        dbDeferred = self.runQuery(self.sql, (credentials.username,))
        # Setup our deferred result
        deferred = Deferred()
        dbDeferred.addCallbacks(self._cbAuthenticate, self._ebAuthenticate,
                callbackArgs=(credentials, deferred),
                errbackArgs=(credentials, deferred))
        return deferred

    def _cbAuthenticate(self, result, credentials, deferred):
        """
        Checks to see if authentication was good. Called once the info has
        been retrieved from the DB.
        """
        if len(result) == 0:
            # Username not found in db
            deferred.errback(error.UnauthorizedLogin('Username unknown'))
        else:
            username, password = result[0]
            if self.customCheckFunc:
                # Let the owner do the checking
                if self.customCheckFunc(
                        username, credentials.password, password):
                    deferred.callback(credentials.username)
                else:
                    deferred.errback(
                        error.UnauthorizedLogin('Password mismatch'))
            else:
                # It's up to us or the credentials object to do the checking
                # now
                if IUsernameHashedPassword.providedBy(credentials):
                    # Let the hashed password checker do the checking
                    if credentials.checkPassword(password):
                        deferred.callback(credentials.username)
                    else:
                        deferred.errback(
                            error.UnauthorizedLogin('Password mismatch'))
                elif IUsernamePassword.providedBy(credentials):
                    # Compare the passwords, deciging whether or not to use
                    # case sensitivity
                    if self.caseSensitivePasswords:
                        passOk = (
                            password.lower() == credentials.password.lower())
                    else:
                        passOk = password == credentials.password
                    # See if they match
                    if passOk:
                        deferred.callback(credentials.username)
                    else:
                        deferred.errback(
                            error.UnauthorizedLogin('Password mismatch'))
                else:
                    # OK, we don't know how to check this
                    deferred.errback(error.UnhandledCredentials())

    def _ebAuthenticate(self, message, credentials, deferred):
        """
        The database lookup failed for some reason.
        """
        deferred.errback(error.LoginFailed(message))

def main():
    """
    Run a simple echo pb server to test the checker. It defines a custom query
    for dealing with sqlite special quoting, but otherwise it's a
    straightforward use of the object.

    You can test it running C{pbechoclient.py}.
    """
    import sys
    from twisted.python import log
    log.startLogging(sys.stdout)
    import os
    if os.path.isfile('testcred'):
        os.remove('testcred')
    from twisted.enterprise import adbapi
    pool = adbapi.ConnectionPool('pysqlite2.dbapi2', 'testcred')
    # Create the table that will be used
    query1 = """CREATE TABLE user (
            username string,
            password string
        )"""
    # Insert a test user
    query2 = """INSERT INTO user VALUES ('guest', 'guest')"""
    def cb(res):
        pool.runQuery(query2)
    pool.runQuery(query1).addCallback(cb)

    checker = DBCredentialsChecker(pool.runQuery,
        query="SELECT username, password FROM user WHERE username = ?")
    from twisted.cred.portal import Portal

    import pbecho
    from twisted.spread import pb
    portal = Portal(pbecho.SimpleRealm())
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))

if __name__ == "__main__":
    from twisted.internet import reactor
    reactor.callWhenRunning(main)
    reactor.run()


text:
### 示例

##### 示例 1: 每2秒对源 observable 取样

(
[StackBlitz](https://stackblitz.com/edit/typescript-envpsp?file=index.ts&devtoolsheight=100)
| [jsBin](http://jsbin.com/gemebopifu/1/edit?js,console) |
[jsFiddle](https://jsfiddle.net/btroncone/8wsbuvjb/) )

```js
// RxJS v6+
import { interval } from 'rxjs';
import { sample } 'rxjs/operators';

// 每1秒发出值
const source = interval(1000);
// 每2秒对源 observable 最新发出的值进行取样
const example = source.pipe(sample(interval(2000)));
// 输出: 2..4..6..8..
const subscribe = example.subscribe(val => console.log(val));
```

##### 示例 2: 当 interval 发出时对源 observable 取样

(
[StackBlitz](https://stackblitz.com/edit/typescript-sgat7t?file=index.ts&devtoolsheight=100)
| [jsBin](http://jsbin.com/cunicepube/1/edit?js,console) |
[jsFiddle](https://jsfiddle.net/btroncone/b33kg9dn/) )

```js
// RxJS v6+
import { interval, zip, from } from 'rxjs';
import { sample } from 'rxjs/operators';

const source = zip(
  // 发出 'Joe', 'Frank' and 'Bob' in sequence
  from(['Joe', 'Frank', 'Bob']),
  // 每2秒发出值
  interval(2000)
);
// 每2.5秒对源 observable 最新发出的值进行取样
const example = source.pipe(sample(interval(2500)));
// 输出: ["Joe", 0]...["Frank", 1]...........
const subscribe = example.subscribe(val => console.log(val));
```

##### 示例 3: 区分拖拽和点击

来源: [Stack Overflow](https://stackoverflow.com/a/44865892/2774547)
作者: [Dorus](https://stackoverflow.com/users/402027/dorus)

(
[StackBlitz](https://stackblitz.com/edit/typescript-vk8p3e?file=index.ts&devtoolsheight=100)
| [jsBin](http://jsbin.com/riwipicilo/1/edit?html,js,console,output) |
[jsFiddle](https://jsfiddle.net/6yy6q0Lo/1/) )

```js
// RxJS v6+
import { fromEvent, merge } from 'rxjs';
import { sample, mapTo } from 'rxjs/operators';

const listener = merge(
  fromEvent(document, 'mousedown').pipe(mapTo(false)),
  fromEvent(document, 'mousemove').pipe(mapTo(true))
)
  .pipe(sample(fromEvent(document, 'mouseup')))
  .subscribe(isDragging => {
    console.log('Were you dragging?', isDragging);
  });
```

### 其他资源

- [sample](https://cn.rx.js.org/class/es6/Observable.js~Observable.html#instance-method-sample) :newspaper: - 官方文档

---
> :file_folder: 源码:  [https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/sample.ts](https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/sample.ts)


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>DnD test dragging tree children</title>

This page includes a simple example demonstrating ability to drag both
			tree parents and children.  Note that this requires Dojo 1.8 or higher.


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

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>paha-ets</artifactId>
        <groupId>com.oalnet.paha</groupId>
        <version>5.0-SNAPSHOT</version>
    </parent>
    <artifactId>paha-ets-server</artifactId>
    <packaging>war</packaging>

    <properties>
        <gwtVersion>2.6.0</gwtVersion>
        <appengine.target.version>1.9.1</appengine.target.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${appengine.target.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-servlet</artifactId>
            <version>${gwtVersion}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <version>${gwtVersion}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-testing</artifactId>
            <version>${appengine.target.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-stubs</artifactId>
            <version>${appengine.target.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <outputDirectory>target/${project.artifactId}-${project.version}/WEB-INF/classes</outputDirectory>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>gwt-maven-plugin</artifactId>
                <version>${gwtVersion}</version>
                <configuration>
                    <runTarget>planhoraire.html</runTarget>
                    <workDir>src/main/webapp</workDir>
                    <server>com.google.appengine.tools.development.gwt.AppEngineLauncher</server>
                    <appEngineVersion>${appengine.target.version}</appEngineVersion>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>generateAsync</goal>
                            <goal>test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.google.appengine</groupId>
                <artifactId>appengine-maven-plugin</artifactId>
                <version>${appengine.target.version}</version>
                <configuration>
                    <jvmFlags>
                        <jvmFlag>-Xdebug</jvmFlag>
                        <jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
                    </jvmFlags>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="common.css" />
    <link rel="stylesheet" href="settings.css" />


text:
Editar Sala

                            <?php if(isset($_SESSION['save_ok'])){?>

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                Atualizado com sucesso

                            <?php }
                            if(isset($_SESSION['save_fail'])){ ?>

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                Erro ao atualizar

                            <?php }
                            ?>

                            <form action="<?php echo base_url('sala/update').'/'.$sala->id ?>" enctype="multipart/form-data" method="post">

                                            Nome
                                            <input type="text" name="nome" class="form-control" value="<?php echo $sala->nome; ?>"/>

                                            Observações
<textarea class="form-control" name="observacoes" placeholder="Observações sobre a sala Exemplo: sala com ar condicionado"><?php echo $sala->observacao; ?></textarea>

                                            <button class="btn btn-primary">Atualizar</button>

                            </form>


text:
{% load markup i18n %}
{% if nav %}

    {% for page in page.get_children_related %}

            {{ page.get_menu_title }}
            {% if page.new %}Neu
            {% elif page.fresh %}Kürzlich aktualisiert{% endif %}

    {% endfor %}

{% endif %}
{% for page in page.get_children_related %}
    {% with page=page.get_object start=start|default:1|add:1 %}

        {% if page.show_title %}
            <h{{ start|default:1 }}>
                {{ page.title }}
                ¶
            </h{{ start|default:1 }}>
        {% endif %}
        {% if page.text and page.fresh %}
Aktualisiert {{ page.modified|date:"DATETIME_FORMAT" }}
{% endif %}
        {{ page.text|markdown }}
        {{ page.subpages }}
        {% if user.is_staff %}

{% trans "Edit this page" %}

        {% endif %}

    {% endwith %}
{% endfor %}


text:
layout: page
title: "Eu"
description: "Gênio, Bilionário, Playboy, Filantropo..."
header-img: "img/about-bg.jpg"
---

Em breve


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F9F9F8">
    <com.google.android.material.card.MaterialCardView
        android:id="@+id/welcome_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@color/white"
        app:cardElevation="1dp"
        app:cardCornerRadius="0dp">

    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:text="Sign in to Simplicity"
        android:textSize="22sp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        tools:ignore="HardcodedText" />

    </com.google.android.material.card.MaterialCardView>

    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Sign in with your Simplicity Account to sync your bookmarks and history on all of your devices."
        android:textSize="12sp"
        android:layout_below="@id/welcome_card"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        tools:ignore="HardcodedText" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/welcome_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="No Thanks"
        android:textColor="@color/md_blue_600"
        android:backgroundTint="@color/other"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="8dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="16dp"
        android:outlineProvider="none"
        app:cornerRadius="4dp"
        tools:ignore="HardcodedText"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/welcome_sign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Sign in"
        android:textColor="@android:color/white"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="8dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:backgroundTint="@color/md_blue_600"
        app:cornerRadius="4dp"
        app:backgroundTint="@color/md_blue_600"
        tools:ignore="HardcodedText"/>

    <View
        android:layout_width="match_parent"
        android:layout_height=".9dp"
        android:background="#CCCCCC"
        android:alpha=".4"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>


text:
<?php

namespace Drupal\taxonomy\Tests\Views;

use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\views\Tests\ViewTestData;
use Drupal\views_ui\Tests\UITestBase;

/**
 * Tests the taxonomy index filter handler UI.
 *
 * @group taxonomy
 * @see \Drupal\taxonomy\Plugin\views\field\TaxonomyIndexTid
 */
class TaxonomyIndexTidUiTest extends UITestBase {

  use EntityReferenceTestTrait;

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array('test_filter_taxonomy_index_tid', 'test_taxonomy_term_name');

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node', 'taxonomy', 'views', 'views_ui', 'taxonomy_test_views'];

  /**
   * A nested array of \Drupal\taxonomy\TermInterface objects.
   *
   * @var \Drupal\taxonomy\TermInterface[][]
   */
  protected $terms = [];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->adminUser = $this->drupalCreateUser(['administer taxonomy', 'administer views']);
    $this->drupalLogin($this->adminUser);

    Vocabulary::create([
      'vid' => 'tags',
      'name' => 'Tags',
    ])->save();

    // Setup a hierarchy which looks like this:
    // term 0.0
    // term 1.0
    // - term 1.1
    // term 2.0
    // - term 2.1
    // - term 2.2
    for ($i = 0; $i < 3; $i++) {
      for ($j = 0; $j <= $i; $j++) {
        $this->terms[$i][$j] = $term = Term::create([
          'vid' => 'tags',
          'name' => "Term $i.$j",
          'parent' => isset($terms[$i][0]) ? $terms[$i][0]->id() : 0,
        ]);
        $term->save();
      }
    }
    ViewTestData::createTestViews(get_class($this), array('taxonomy_test_views'));

    Vocabulary::create([
      'vid' => 'empty_vocabulary',
      'name' => 'Empty Vocabulary',
    ])->save();
  }

  /**
   * Tests the filter UI.
   */
  public function testFilterUI() {
    $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid');

    $result = $this->xpath('//select[@id="edit-options-value"]/option');

    // Ensure that the expected hierarchy is available in the UI.
    $counter = 0;
    for ($i = 0; $i < 3; $i++) {
      for ($j = 0; $j <= $i; $j++) {
        $option = $result[$counter++];
        $prefix = $this->terms[$i][$j]->parent->target_id ? '-' : '';
        $attributes = $option->attributes();
        $tid = (string) $attributes->value;

        $this->assertEqual($prefix . $this->terms[$i][$j]->getName(), (string) $option);
        $this->assertEqual($this->terms[$i][$j]->id(), $tid);
      }
    }

    // Ensure the autocomplete input element appears when using the 'textfield'
    // type.
    $view = entity_load('view', 'test_filter_taxonomy_index_tid');
    $display =& $view->getDisplay('default');
    $display['display_options']['filters']['tid']['type'] = 'textfield';
    $view->save();
    $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid');
    $this->assertFieldByXPath('//input[@id="edit-options-value"]');

    // Tests \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid::calculateDependencies().
    $expected = [
      'config' => [
        'taxonomy.vocabulary.tags',
      ],
      'content' => [
        'taxonomy_term:tags:' . Term::load(2)->uuid(),
      ],
      'module' => [
        'node',
        'taxonomy',
        'user',
      ],
    ];
    $this->assertIdentical($expected, $view->calculateDependencies()->getDependencies());
  }

  /**
   * Tests exposed taxonomy filters.
   */
  public function testExposedFilter() {
    $node_type = $this->drupalCreateContentType(['type' => 'page']);

    // Create the tag field itself.
    $field_name = 'taxonomy_tags';
    $this->createEntityReferenceField('node', $node_type->id(), $field_name, NULL, 'taxonomy_term');

    // Create 4 nodes: 1 without a term, 2 with the same term, and 1 with a
    // different term.
    $node1 = $this->drupalCreateNode();
    $node2 = $this->drupalCreateNode([
      $field_name => [['target_id' => $this->terms[1][0]->id()]],
    ]);
    $node3 = $this->drupalCreateNode([
      $field_name => [['target_id' => $this->terms[1][0]->id()]],
    ]);
    $node4 = $this->drupalCreateNode([
      $field_name => [['target_id' => $this->terms[2][0]->id()]],
    ]);

    // Only the nodes with the selected term should be shown.
    $this->drupalGet('test-filter-taxonomy-index-tid');
    $xpath = $this->xpath('//div[@class="view-content"]//a');
    $this->assertIdentical(2, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node2->url()]);
    $this->assertIdentical(1, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node3->url()]);
    $this->assertIdentical(1, count($xpath));

    // Expose the filter.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid', [], 'Expose filter');
    // Set the operator to 'empty' and remove the default term ID.
    $this->drupalPostForm(NULL, [
      'options[operator]' => 'empty',
      'options[value][]' => [],
    ], 'Apply');
    // Save the view.
    $this->drupalPostForm(NULL, [], 'Save');

    // After switching to 'empty' operator, the node without a term should be
    // shown.
    $this->drupalGet('test-filter-taxonomy-index-tid');
    $xpath = $this->xpath('//div[@class="view-content"]//a');
    $this->assertIdentical(1, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node1->url()]);
    $this->assertIdentical(1, count($xpath));

    // Set the operator to 'not empty'.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid', ['options[operator]' => 'not empty'], 'Apply');
    // Save the view.
    $this->drupalPostForm(NULL, [], 'Save');

    // After switching to 'not empty' operator, all nodes with terms should be
    // shown.
    $this->drupalGet('test-filter-taxonomy-index-tid');
    $xpath = $this->xpath('//div[@class="view-content"]//a');
    $this->assertIdentical(3, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node2->url()]);
    $this->assertIdentical(1, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node3->url()]);
    $this->assertIdentical(1, count($xpath));
    $xpath = $this->xpath('//div[@class="view-content"]//a[@href=:href]', [':href' => $node4->url()]);
    $this->assertIdentical(1, count($xpath));

    // Select 'Term ID' as the field to be displayed.
    $edit = ['name[taxonomy_term_field_data.tid]' => TRUE];
    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_taxonomy_term_name/default/field', $edit, 'Add and configure fields');
    // Select 'Term' and 'Vocabulary' as filters.
    $edit = [
      'name[taxonomy_term_field_data.tid]' => TRUE,
      'name[taxonomy_term_field_data.vid]' => TRUE
    ];
    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_taxonomy_term_name/default/filter', $edit, 'Add and configure filter criteria');
    // Select 'Empty Vocabulary' and 'Autocomplete' from the list of options.
    $this->drupalPostForm('admin/structure/views/nojs/handler-extra/test_taxonomy_term_name/default/filter/tid', [], 'Apply and continue');
    // Expose the filter.
    $edit = ['options[expose_button][checkbox][checkbox]' => TRUE];
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_taxonomy_term_name/default/filter/tid', $edit, 'Expose filter');
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_taxonomy_term_name/default/filter/tid', $edit, 'Apply');
    // Filter 'Taxonomy terms' belonging to 'Empty Vocabulary'.
    $edit = ['options[value][empty_vocabulary]' => TRUE];
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_taxonomy_term_name/default/filter/vid', $edit, 'Apply');
    $this->drupalPostForm('admin/structure/views/view/test_taxonomy_term_name/edit/default', [], 'Save');
    $this->drupalPostForm(NULL, [], t('Update preview'));
    $preview = $this->xpath("//div[@class='view-content']");
    $this->assertTrue(empty($preview), 'No results.');
  }

}


text: groovy auto_mvp.groovy


text:
"""\
Nox test runner configuration.
"""
import os
import sys
import re
from functools import partial
from itertools import chain
import shutil
import nox

_PY_VERSIONS = ('2.7', '3.7', '3.8', '3.9', '3.10', 'pypy', 'pypy3')
_PY_DEFAULT_VERSION = '3.10'

nox.options.sessions = ['test-2.7', 'test-{}'.format(_PY_DEFAULT_VERSION), 'test-pypy', 'test-pypy3']

@nox.session(python=_PY_VERSIONS)
def test(session):
    """\
    Run test suite.
    """
    if session.python == 'pypy':
        # See <https://github.com/heuer/segno/issues/80>
        pip_ver = session.run('pip', '--version', silent=True)
        m = re.search(r'pip ([0-9.]{4})', pip_ver)
        assert m
        if m.group(1) in ('20.2', '20.3'):
            session.run('pip', 'uninstall', '-y', 'pip')
            session.run('easy_install', 'pip==20.1.1')
    session.install('-Ur', 'requirements-testing.txt')
    session.install('.')
    session.run('py.test')

@nox.session(python=_PY_DEFAULT_VERSION)
def docs(session):
    """\
    Build the documentation.
    """
    session.install('-Ur', 'requirements-rtd.txt')
    output_dir = os.path.abspath(os.path.join(session.create_tmp(), 'output'))
    shutil.rmtree(output_dir, ignore_errors=True)
    doctrees, html, man = map(partial(os.path.join, output_dir), ['doctrees', 'html', 'man'])
    session.install('.')
    session.cd('docs')
    sphinx_build = partial(session.run, 'sphinx-build', '-W', '-d', doctrees, '.')
    sphinx_build('-b', 'html', html)
    sphinx_build('-b', 'man', man)
    sys.path.insert(0, os.path.abspath('..'))
    import segno
    if 'dev' not in segno.__version__:
        shutil.copyfile(os.path.join(man, 'segno.1'),
                        os.path.abspath(os.path.join(os.path.dirname(__file__), 'man', 'segno.1')))
        session.log("'man/segno.1' has been modified, don't forget to commit")

@nox.session(python=_PY_DEFAULT_VERSION)
def coverage(session):
    """\
    Run coverage.
    """
    session.install('coverage', '-Ur', 'requirements-testing.txt')
    session.install('.')
    output_dir = os.path.abspath(os.path.join(session.create_tmp(), 'html'))
    cover = partial(session.run, 'coverage')
    cover('erase')
    cover('run', './tests/alltests.py')
    cover('report')
    cover('html', '-d', output_dir)

@nox.session(python=_PY_DEFAULT_VERSION)
def lint(session):
    """\
    Run flake8
    """
    session.install('flake8', 'mypy')
    session.run('mypy', 'segno')
    session.run('flake8', 'segno')
    session.run('flake8', 'tests/')

@nox.session(python=_PY_DEFAULT_VERSION)
def benchmarks(session):
    """\
    Run the benchmarks and create the charts.
    """
    session.install('qrcode', 'Pillow', 'pyqrcode', 'pypng', 'qrcodegen', 'pygal')
    session.install('.')
    sandbox_dir = os.path.join(os.path.dirname(__file__), 'sandbox')
    session.run('python', os.path.join(sandbox_dir, 'benchmarks.py'))
    session.run('python', os.path.join(sandbox_dir, 'make_charts.py'))

#
# Release related tasks
# 1. nox -e start-release -- version-number
# 2. run tests, update docs, update changes
# 3. nox -e finish-release -- version-number
# 4. git push / git push origin --tags
# 5. nox -e build-release -- version-number
# 6. nox -e upload-release
#

@nox.session(name='start-release', python=_PY_DEFAULT_VERSION)
def start_release(session):
    """\
    Prepares a release.

    * Creates a new branch release-VERSION_NUMBER
    * Changes the version number in segno.__version__ to VERSION_NUMBER
    """
    session.install('packaging')
    git = partial(session.run, 'git', external=True)
    git('checkout', 'master')
    prev_version = _get_current_version(session)
    version = _validate_version(session)
    valid_version = bool(int(session.run('python', '-c', 'from packaging.version import parse;'
                                                         'prev_version = parse("{0}");'
                                                         'next_version = parse("{1}");'
                                                         'print(1 if prev_version < next_version else 0)'
                                         .format(prev_version, version), silent=True)))
    if not valid_version:
        session.error('Invalid version')
    release_branch = 'release-{}'.format(version)
    git('checkout', '-b', release_branch, 'master')
    _change_version(session, prev_version, version)
    git('add', 'segno/__init__.py')
    session.log('Now on branch "{}". Run the tests, run nox -e docs. Update and add CHANGES'.format(release_branch))
    session.log('Commit any changes.')
    session.log('When done, call nox -e finish-release -- {}'.format(version))

@nox.session(name='finish-release', python=_PY_DEFAULT_VERSION)
def finish_release(session):
    """\
    Finishes the release.

    * Merges the branch release-VERSION_NUMBER into master
    * Creates a tag VERSION_NUMBER
    * Increments the development version
    """
    version = _validate_version(session)
    release_branch = 'release-{}'.format(version)
    git = partial(session.run, 'git', external=True)
    git('checkout', 'master')
    git('merge', '--no-ff', release_branch, '-m', 'Merge release branch {}'.format(release_branch))
    git('tag', '-a', version, '-m', 'Release {}'.format(version))
    git('branch', '-d', release_branch)
    version_parts = version.split('.')
    patch = str(int(version_parts[2]) + 1)
    next_version = '.'.join(chain(version_parts[:2], patch)) + '.dev'
    _change_version(session, version, next_version)
    git('add', 'segno/__init__.py')
    git('commit', '-m', 'Incremented development version')
    session.log('Finished. Run git push / git push origin --tags and '
                'nox -e build-release -- {} / nox -e upload-release'.format(version))

@nox.session(name='build-release', python=_PY_DEFAULT_VERSION)
def build_release(session):
    """\
    Builds a release: Creates sdist and wheel
    """
    version = _validate_version(session)
    session.install('build', 'wheel')
    git = partial(session.run, 'git', external=True)
    git('fetch')
    git('fetch', '--tags')
    git('checkout', version)
    shutil.rmtree('dist', ignore_errors=True)
    session.run('python', '-m', 'build', '--no-isolation')
    git('checkout', 'master')

@nox.session(name='upload-release', python=_PY_DEFAULT_VERSION)
def upload_release(session):
    """\
    Uploads a release to PyPI
    """
    session.install('twine')
    twine = partial(session.run, 'twine')
    twine('check', 'dist/*')
    twine('upload', 'dist/*')

def _validate_version(session):
    if not session.posargs:
        session.error('No release version provided')
    elif len(session.posargs) > 1:
        session.error('Too many arguments')
    version = session.posargs[0]
    if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+$', version):
        session.error('Invalid version number: "{}"'.format(version))
    return version

def _get_current_version(session):
    """\
    Returns the current Segno version.
    """
    fn = os.path.abspath(os.path.join(os.path.dirname(__file__), 'segno/__init__.py'))
    with open(fn, 'r', encoding='utf-8') as f:
        content = f.read()
    m = re.search(r'^__version__ = ["\']([^"\']+)["\']$', content, flags=re.MULTILINE)
    if m:
        return m.group(1)
    session.error('Cannot find any version information')

def _change_version(session, previous_version, next_version):
    """\
    Changes the segno.__init__.__version__ from previous_version to next_version.
    """
    fn = os.path.abspath(os.path.join(os.path.dirname(__file__), 'segno/__init__.py'))
    with open(fn, 'r', encoding='utf-8') as f:
        content = f.read()
    new_content = re.sub(r'^(__version__ = ["\'])({0})(["\'])$'
                         .format(re.escape(previous_version)),
                         r'\g<1>{}\g<3>'.format(next_version), content,
                         flags=re.MULTILINE)
    if content != new_content:
        with open(fn, 'w', encoding='utf-8') as f:
            f.write(new_content)
        return
    session.error('Cannot modify version. Provided: "{}" (previous) "{}" (next)'
                  .format(previous_version, next_version))


text:
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;

namespace Subtext.Framework.Configuration
{
    public class MimeTypesMapper
    {
        public static readonly MimeTypesMapper Mappings =
            new MimeTypesMapper((NameValueCollection)ConfigurationManager.GetSection("EnclosureMimetypes"));

        public MimeTypesMapper(NameValueCollection config)
        {
            if(config == null)
            {
                throw new ArgumentNullException("config");
            }
            List = config;
            Count = config.Keys.Count;
        }

        public int Count { get; private set; }

        public NameValueCollection List { get; private set; }

        /// <summary>
        /// Returns the mimetype that corresponds to a file extension.
        /// </summary>
        /// <param name="ext">Extension of a file.</param>
        /// <returns>The MimeType</returns>
        public string GetMimeType(string ext)
        {
            if(ext == null)
            {
                throw new ArgumentNullException("ext");
            }
            if(List[ext] != null)
            {
                return List[ext];
            }
            return null;
        }

        /// <summary>
        /// Detect the mimetype of the url of a file.
        /// </summary>
        /// <param name="url">Url of the file</param>
        /// <returns>The MimeType.</returns>
        public string ParseUrl(string url)
        {
            if(url == null)
            {
                throw new ArgumentNullException("url");
            }
            Uri uri;

            if(!Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                throw new ArgumentException("Url not valid.", "url");
            }

            string path = uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);

            string ext = Path.GetExtension(path);

            return GetMimeType(ext);
        }
    }
}


text:
// .NAME vtkMPEG2Writer - Writes MPEG2 Movie files.
//
// .SECTION Description
// vtkMPEG2Writer writes Movie files. The data type
// of the file is unsigned char regardless of the input type.
//
// This class is conditionally compiled into VTK only if VTK's CMake
// option VTK_USE_MPEG2_ENCODER is ON. It is OFF by default.
//
// Portions of the mpeg2 library are patented. VTK does not enable linking to
// this library by default so VTK can remain "patent free". Users who wish to
// link in mpeg2 functionality must build that library separately and then
// turn on VTK_USE_MPEG2_ENCODER when configuring VTK. After turning on
// VTK_USE_MPEG2_ENCODER, you must also set the CMake variables
// vtkMPEG2Encode_INCLUDE_PATH and vtkMPEG2Encode_LIBRARIES.
//
// You are solely responsible for any legal issues associated with using
// patented code in your software.
//
// You can download a "CMake-ified" source tree of the MPEG2 library by
// visiting the download page at http://www.vtk.org and scrolling down to
// the "Download Additional Components" section.
//
// .SECTION See Also
// vtkGenericMovieWriter vtkAVIWriter vtkFFMPEGWriter

#ifndef __vtkMPEG2Writer_h
#define __vtkMPEG2Writer_h

#include "vtkIOMovieModule.h" // For export macro
#include "vtkGenericMovieWriter.h"

class vtkMPEG2WriterInternal;
class vtkImageData;
struct MPEG2_structure;

class VTKIOMOVIE_EXPORT vtkMPEG2Writer : public vtkGenericMovieWriter
{
public:
  static vtkMPEG2Writer *New();
  vtkTypeMacro(vtkMPEG2Writer,vtkGenericMovieWriter);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // These methods start writing an Movie file, write a frame to the file
  // and then end the writing process.
  void Start();
  void Write();
  void End();

protected:
  vtkMPEG2Writer();
  ~vtkMPEG2Writer();

  vtkMPEG2WriterInternal *Internals;

  long Time;
  int ActualWrittenTime;

  void Initialize();

  int Initialized;

  MPEG2_structure* MPEGStructure;

private:
  vtkMPEG2Writer(const vtkMPEG2Writer&); // Not implemented
  void operator=(const vtkMPEG2Writer&); // Not implemented
};

#endif


text:
import tables
from pylab import *

def get_values(filename, complib=''):
    f = tables.openFile(filename)
    nrows = f.root.small.create_best.cols.nrows[:]
    corrected_sizes = nrows/10.**6
    if mb_units:
        corrected_sizes = 16*nrows/10.**6
    if insert:
        values = corrected_sizes/f.root.small.create_best.cols.tfill[:]
    if table_size:
        values = f.root.small.create_best.cols.fsize[:]/nrows
    if query:
        values = corrected_sizes/f.root.small.search_best.inkernel.int.cols.time1[:]
    if query_cache:
        values = corrected_sizes/f.root.small.search_best.inkernel.int.cols.time2[:]

    f.close()
    return nrows, values

def show_plot(plots, yaxis, legends, gtitle):
    xlabel('Number of rows')
    ylabel(yaxis)
    xlim(10**3, 10**8)
    title(gtitle)
    grid(True)

#     legends = [f[f.find('-'):f.index('.out')] for f in filenames]
#     legends = [l.replace('-', ' ') for l in legends]
    if table_size:
        legend([p[0] for p in plots], legends, loc = "upper right")
    else:
        legend([p[0] for p in plots], legends, loc = "upper left")

    #subplots_adjust(bottom=0.2, top=None, wspace=0.2, hspace=0.2)
    if outfile:
        savefig(outfile)
    else:
        show()

if __name__ == '__main__':

    import sys, getopt

    usage = """usage: %s [-o file] [-t title] [--insert] [--table-size] [--query] [--query-cache] [--MB-units] files
 -o filename for output (only .png and .jpg extensions supported)
 -t title of the plot
 --insert -- Insert time for table
 --table-size -- Size of table
 --query -- Time for querying the integer column
 --query-cache -- Time for querying the integer (cached)
 --MB-units -- Express speed in MB/s instead of MRows/s
 \n""" % sys.argv[0]

    try:
        opts, pargs = getopt.getopt(sys.argv[1:], 'o:t:',
                                    ['insert',
                                     'table-size',
                                     'query',
                                     'query-cache',
                                     'MB-units',
                                     ])
    except:
        sys.stderr.write(usage)
        sys.exit(0)

    progname = sys.argv[0]
    args = sys.argv[1:]

    # if we pass too few parameters, abort
    if len(pargs) < 1:
        sys.stderr.write(usage)
        sys.exit(0)

    # default options
    outfile = None
    insert = 0
    table_size = 0
    query = 0
    query_cache = 0
    mb_units = 0
    yaxis = "No axis name"
    tit = None
    gtitle = "Please set a title!"

    # Get the options
    for option in opts:
        if option[0] == '-o':
            outfile = option[1]
        elif option[0] == '-t':
            tit = option[1]
        elif option[0] == '--insert':
            insert = 1
            yaxis = "MRows/s"
            gtitle = "Writing with small (16 bytes) record size"
        elif option[0] == '--table-size':
            table_size = 1
            yaxis = "Bytes/row"
            gtitle = "Disk space taken by a record (original record size: 16 bytes)"
        elif option[0] == '--query':
            query = 1
            yaxis = "MRows/s"
            gtitle = "Selecting with small (16 bytes) record size (file not in cache)"
        elif option[0] == '--query-cache':
            query_cache = 1
            yaxis = "MRows/s"
            gtitle = "Selecting with small (16 bytes) record size (file in cache)"
        elif option[0] == '--MB-units':
            mb_units = 1

    filenames = pargs

    if mb_units and yaxis == "MRows/s":
        yaxis = "MB/s"

    if tit:
        gtitle = tit

    plots = []
    legends = []
    for filename in filenames:
        plegend = filename[filename.find('cl-')+3:filename.index('.h5')]
        plegend = plegend.replace('-', ' ')
        xval, yval = get_values(filename, '')
        print "Values for %s --> %s, %s" % (filename, xval, yval)
        #plots.append(loglog(xval, yval, linewidth=5))
        plots.append(semilogx(xval, yval, linewidth=4))
        legends.append(plegend)
    if 0:  # Per a introduir dades simulades si es vol...
        xval = [1000, 10000, 100000, 1000000, 10000000,
                100000000, 1000000000]
#         yval = [0.003, 0.005, 0.02, 0.06, 1.2,
#                 40, 210]
        yval = [0.0009, 0.0011, 0.0022, 0.005, 0.02,
                0.2, 5.6]
        plots.append(loglog(xval, yval, linewidth=5))
        legends.append("PyTables Std")
    show_plot(plots, yaxis, legends, gtitle)


text:
from tests.fixtures import TEST_USER

def test_login(selenium):
    selenium.implicitly_wait(10)
    selenium.set_window_size(1124, 850)
    selenium.get('http://127.0.0.1:8000')
    selenium.find_element_by_id("navbar-login").click()
    assert selenium.title == "StarterWeppy | Account"
    email_input = selenium.find_element_by_id("email")
    email_input.clear()
    email_input.send_keys(TEST_USER.email)
    password_input = selenium.find_element_by_id("password")
    password_input.send_keys(TEST_USER.password)
    login_btn = selenium.find_element_by_css_selector("form > div:nth-child(4) > input")
    login_btn.click()
    loggedin_header = selenium.find_element_by_id("loggedin-header")
    assert loggedin_header.text == "Profile"


text: {{numResults}} Jedis found


text:
"use strict";

/**
 * The TypingPublisher's job is not to transition from one
 * state (say `started`) to another (`paused` for example)...
 * It's only purpose is not to flood the server with too
 * many ephemeral events whenever user calls the `setState('started')`
 *
 * A few rules for the *publisher*:
 *
 *  - it maintains an indicator state for the current conversation
 *  - if user calls  `setState('started');` publisher sends the event immediately
 *  - if user calls the same method under _2.5 seconds_ with the same typing indicator state (`started`), publisher waits
 *    for those 2.5 seconds to pass and then publishes the ephemeral event
 *  - if user calls the same methods multiple times within _2.5 seconds_ with the same value,
 *    publisher waits until end of 2.5 second period and sends the state only once.
 *  - if user calls the same method under _2.5 seconds_ with a different typing indicator state (say `paused`), publisher immediately sends the event
 *  - if 2.5 seconds passes without any events, state transitions from 'started' to 'paused'
 *  - if 2.5 seconds passes without any events, state transitions from 'paused' to 'finished'
 *
 * @class layer.TypingPublisher
 */

var INTERVAL = 2500;

window.layer.TypingPublisher = TypingPublisher;

/**
 * @constructor
 * @param {Object} args
 * @param {WebSocket} websocket - The Websocket your app is using to listen/send messages
 * @param {Conversation} conversation - The Conversation that messages are being typed to.
 */

function TypingPublisher(args) {
    this.websocket = args.websocket;
    this.conversation = args.conversation;
    this.state = "finished";
    this.lastMessageTime = 0;
}

/**
 * Change which conversation the user is typing into
 *
 * @method
 * @param  {[type]} c [description]
 */
TypingPublisher.prototype.setConversation = function setConversation(c) {
    this.setState("finished");
    this.conversation = c;
    this.state = "finished";
};

/**
 * Sets the state and either sends the state to the server or schedules it to be sent.
 *
 * @method
 * @param  {string} state - One of 'started', 'paused', 'finished'
 */

TypingPublisher.prototype.setState = function setState(state) {
    if (this.pauseLoopId) {
        clearInterval(this.pauseLoopId);
        this.pauseLoopId = 0;
    }
    if (!this.conversation) {
        return;
    } // If its a new state, send it immediately.
    if (this.state != state) {
        this.state = state;
        this.send(state);
    }

    // No need to resend 'finished' state
    else if (state == "finished") {
        return;
    }

    // If its an existing state that hasn't been sent in the
    // last 2.5 seconds, send it immediately.
    else if (Date.now() > this.lastMessageTime + INTERVAL) {
        this.send(state);
    }

    // Else schedule it to be sent.
    else {
        this.scheduleNextMessage(state);
    }

    // Start test to automatically transition if 2.5 seconds without any setState calls
    if (this.state != "finished") this.startPauseLoop();
};

/**
 * Any time we are set to 'started' or 'paused' we should transition
 * to the next state after 2.5 seconds of no setState calls.
 *
 * The 2.5 second setTimeout is canceled/restarted every call to setState()
 *
 * @method startPauseLoop
 */

TypingPublisher.prototype.startPauseLoop = function startPauseLoop() {
    if (this.pauseLoopId) {
        return;
    }this.pauseLoopId = window.setInterval((function () {
        if (this.state == "paused") {
            this.setState("finished");
        } else if (this.state == "started") {
            this.setState("paused");
        }
    }).bind(this), INTERVAL);
}

/**
 * Schedule the next state refresh message so as to be at least INTERVAL ms after
 * the last state message of the same state
 *
 * @method
 * @param  {string} state - One of 'started', 'paused', 'finished'
 */

TypingPublisher.prototype.scheduleNextMessage = function scheduleNextMessage(state) {
    if (this.scheduleId) clearTimeout(this.scheduleId);
    this.scheduleId = setTimeout((function () {
        this.scheduleId = 0;

        // If the state didn't change while waiting...
        if (this.state == state) this.send(state);
    }).bind(this), Date.now() - this.lastMessageTime + INTERVAL);
};

/**
 * Send a state change to the server
 *
 * @method
 * @param  {string} state - One of 'started', 'paused', 'finished'
 */

TypingPublisher.prototype.send = function send(state) {
    this.lastMessageTime = Date.now();
    this.websocket.send(JSON.stringify({
        type: "signal",
        body: {
            type: "typing_indicator",
            object: {
                id: this.conversation.id
            },
            data: {
                action: state
            }
        }
    }));
}


text:
<?php

namespace spec\Sylius\Bundle\ShippingBundle\Form\Type;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 */
class ShippingMethodTranslationTypeSpec extends ObjectBehavior
{
    public function let()
    {
        $this->beConstructedWith('ShippingMethodTranslation', array('sylius'));
    }

    public function it_is_a_form_type()
    {
        $this->shouldImplement('Symfony\Component\Form\FormTypeInterface');
    }

    public function it_builds_form_with_proper_fields(FormBuilder $builder)
    {
        $builder->addEventSubscriber(Argument::any())->willReturn($builder);
        $builder
            ->add('name', 'text', Argument::any())
            ->willReturn($builder)
        ;

        $this->buildForm($builder, array());
    }

    public function it_defines_assigned_data_class(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults(array(
                'data_class' => 'ShippingMethodTranslation',
                'validation_groups' => array('sylius'),
            ))
            ->shouldBeCalled()
        ;

        $this->setDefaultOptions($resolver);
    }
}


text:
This work is licensed under the Creative Commons CC0 License

---

# Stop using org.eclipse.jface.util.ListenerList
### xtUML Project Implementation Note

### 1. Abstract

BridgePoint cannot run in eclipse oxygen because is uses an API for class
`ListenerList` that is now removed.  The first step to migrating from mars to
oxygen is to fix these invalid API calls.

### 2. Document References

2.1 [BridgePoint DEI #10278](https://support.onefact.net/issues/10278)
2.2 [Old JFace packaged API](https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjface%2Futil%2FListenerList.html)
2.3 [New Platform packaged API](https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcore%2Fruntime%2FListenerList.html)
2.4 [Code change example for ListenerList](http://git.eclipse.org/c/sourceediting/webtools.sourceediting.git/commit/?id=a689fd308c5fdb8d06ed45c41bd39a51a8e3d368)
2.5 [Eclipse bug calling out requied change for ListenerList](https://bugs.eclipse.org/bugs/show_bug.cgi?id=513385)

### 3. Background

The BridgePoint code must stop using `org.eclipse.jface.util.ListenerList [2.2]`
and start using `org.eclipse.core.runtime.ListenerList [2.3]`.

The Jface version has been deprecated for quite a while and is fully removed in
Eclipse Oxygen. The BP plugins will not run in an Oxygen installation because of
this.

With the old API in place, the symptom is that "xtUML Modeling" shows up in the
perspective list, but selecting it doesn't do anything. The error log shows
(among other things) what looks like one root cause:

> Caused by: java.lang.NoClassDefFoundError: org/eclipse/jface/util/ListenerList
>   at org.xtuml.bp.core.common.ModelRoot.<init>(ModelRoot.java:173)

An example fix from a different eclipse plugin dealing with this same situation
is in [[2.4]](#2.4), which is the fix for eclipse bug 513385 [[2.5]](#2.5).

During the initial investigation of a fix, it was also noted that
`org.eclipse.jface.util.Assert` and `junit.framework.Assert` fall into the same
scenario.  The former has been migrated to `org.eclipse.core.runtime.Assert`.
And `junit.framework.Assert` is migrated to `org.junit.Assert`.

### 4. Requirements

4.1  BridgePoint source code shall not use `ListenerList` from the
  `org.eclipse.jface` package.

4.2  BridgePoint source code shall not use `Assert` from the `org.eclipse.jface`
  or `junit` package.

### 5. Work Required

5.1   Look for all uses of `org.eclipse.jface.util.ListenerList` in BP source
  code and tests and transition to the new API.

5.2   Look for all uses of `org.eclipse.jface.util.Assert` in BP source
  code and tests and transition to the new API.

5.3   Look for all uses of `junit.framework.Assert` in BP source code and tests
  and transition to the new API.

### 6. Implementation Comments

None.

### 7. Unit Test

7.1 Build and run with test on the build server
* __R__ Test results match the current nightly build
  * The test results from this branch build [are here](https://s3.amazonaws.com/xtuml-releases/10278-build/surefire-report.html).
  * The test results from the nightly build [are here](https://s3.amazonaws.com/xtuml-releases/nightly-build/surefire-report.html).

7.2  Install the plugins from the branch build into eclipse oxygen
* __R__ The xtUML Modeling perspective can be opened.
  * The result of running this test can be seen in the following screenshot.

![Running BP in oxygen](bp_in_oxygen.png)

### 8. User Documentation

None.

### 9. Code Changes

Fork/Repository: __keithbrown/bridgepoint__
Branch: __10278_ListenerList__

 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/ModelRoot.java |   12 +-
 .../src/org/xtuml/bp/core/common/TransactionManager.java          |   12 +-
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/Selection.java     |   12 +-
 .../src/org/xtuml/bp/core/ui/tree/ModelCheckedTreeViewer.java     |   12 +-
 .../org/xtuml/bp/debug/ui/launch/VerifiableElementComposite.java  | 2278 ++++++++++++++---------------
 .../src/org/xtuml/bp/ui/explorer/ExplorerTreeViewer.java          |   10 +-
 .../bp/ui/explorer/decorators/DanglingReferenceDecorator.java     |   12 +-
 .../src/org/xtuml/bp/ui/text/DocumentProvider.java                |   13 +-
 .../xtuml/bp/ui/text/editor/SyntaxHighlightingPreferences.java    |   14 +-

Fork/Repository: __keithbrown/bptest__
Branch: __10278_ListenerList__

 src/org.xtuml.bp.core.test/arc/generate_test_matrix_for_copy_paste.arc                 |  2 +-
 src/org.xtuml.bp.debug.ui.test/src/org/xtuml/bp/debug/engine/MDATest.java              | 10 +---------
 src/org.xtuml.bp.debug.ui.test/src/org/xtuml/bp/debug/test/VerifierTest.java           | 10 +---------
 .../src/org/xtuml/bp/io/mdl/test/pkgcm/EditorTestUtilities.java                        |  2 +-
 src/org.xtuml.bp.test/src/org/xtuml/bp/test/common/ExplorerUtil.java                   | 10 +---------
 src/org.xtuml.bp.test/src/org/xtuml/bp/test/common/GenericEditorUtil.java              |  5 +----
 src/org.xtuml.bp.test/src/org/xtuml/bp/test/common/TestingUtilities.java               | 10 +---------
 src/org.xtuml.bp.test/src/org/xtuml/bp/test/common/UITestingUtilities.java             | 10 +---------

### End


text:
package com.currencyfair.minfraud.model;

import com.currencyfair.minfraud.util.Stringifiable;

/**
 * Enumeration representing the 4-state match result of yes, no, not found or
 * not applicable.
 * @since 1.0.0
 */
public enum MatchType implements Stringifiable {
    YES("Yes", true),
    NO("No", false),
    NOT_FOUND("NotFound", false),
    NA("NA", false);

    private String encodedValue;
    private boolean matched;

    private MatchType(String encodedValue, boolean matched) {
        this.encodedValue = encodedValue;
        this.matched = matched;
    }

    /**
     * Return the <tt>MatchType</tt> corresponding to <tt>encodedValue</tt>.
     * @param encodedValue The encoded value to obtain the <tt>MatchType</tt>
     *                     for.
     * @return The corresponding <tt>MatchType</tt> or <tt>null</tt> if
     * <tt>encodedValue</tt> is null.
     * @throws IllegalArgumentException If <tt>encodedValue</tt> is non-null
     * but does not correspond to a defined <tt>MatchType</tt>.
     */
    public static MatchType extract(String encodedValue) {
        if (encodedValue == null) {
            return null;
        }
        for (MatchType matchType : MatchType.values()) {
            if (matchType.getEncodedValue().equals(encodedValue)) {
                return matchType;
            }
        }
        throw new IllegalArgumentException("Invalid match type: " + encodedValue);
    }

    /**
     * Get the string representation of this match type as it
     * would appear on the wire.
     * @return The encode representation of this match type.
     */
    public String getEncodedValue() {
        return encodedValue;
    }

    /**
     * Determine if this <tt>MatchType</tt> represents a positive match.
     * @return <tt>true</tt> if this match type represents a positive
     * match, <tt>false</tt> otherwise.
     */
    public boolean isMatched() {
        return matched;
    }

    @Override
    public String stringify() {
        return encodedValue;
    }
}


text:
package com.example.yang.test.activity.xunfei;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;

import com.iflytek.cloud.SpeechUtility;

/**
 * 弹出提示框,下载服务组件
 */
public class ApkInstaller {
	private Activity mActivity ;

	public ApkInstaller(Activity activity) {
		mActivity = activity;
	}

	public void install(){
		Builder builder = new Builder(mActivity);
		builder.setMessage("检测到您未安装语记!\n是否前往下载语记?");
		builder.setTitle("下载提示");
		builder.setPositiveButton("确认前往", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				String url = SpeechUtility.getUtility().getComponentUrl();
				String assetsApk="SpeechService.apk";
				processInstall(mActivity, url,assetsApk);
			}
		});
		builder.setNegativeButton("残忍拒绝", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
		return;
	}
	/**
	 * 如果服务组件没有安装打开语音服务组件下载页面,进行下载后安装。
	 */
	private boolean processInstall(Context context ,String url,String assetsApk){
		//直接下载方式
		Uri uri = Uri.parse(url);
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		context.startActivity(it);
		return true;
	}
}


text:
import scrapy

from yjbys.items import YjbysItem

class JianliSpider(scrapy.Spider):
    name = "jianli"
    allowed_domains = ["jianlimoban.yjbys.com", "jianli.yjbys.com"]
    start_urls = (
        'http://jianli.yjbys.com/jianlixiazai/',
        'http://jianli.yjbys.com/jianlixiazai/jianlibiaogexiazai/',
    )

    def parse(self, response):
        download_list = response.xpath("//div[@id='mainleft']//ul[@class='listimg']//li")
        for one in download_list:
            name = one.xpath(".//a[@class='atext']/text()").extract_first()
            path = one.xpath(".//input/@onclick").extract_first()
            path = path.lstrip("window.open('").rstrip("')")
            yield YjbysItem(name=name, url=response.urljoin(path))

        next_page = response.xpath(u"//ul[@id='page_slice']//a[text()='下一页']/@href").extract_first()
        if next_page is not None:
            yield scrapy.Request(response.urljoin(next_page), self.parse)