text:
package io.sipstack.transport.impl;

import io.pkts.packet.sip.SipRequest;
import io.pkts.packet.sip.SipResponse;
import io.pkts.packet.sip.Transport;
import io.pkts.packet.sip.address.SipURI;
import io.sipstack.config.SipConfiguration;
import io.sipstack.config.SipOptionsPingConfiguration;
import io.sipstack.config.TransportLayerConfiguration;
import io.sipstack.netty.codec.sip.Connection;
import io.sipstack.netty.codec.sip.SipTimer;
import io.sipstack.netty.codec.sip.event.IOEvent;
import io.sipstack.netty.codec.sip.event.SipRequestIOEvent;
import io.sipstack.netty.codec.sip.event.SipResponseIOEvent;
import io.sipstack.transport.Flow;
import io.sipstack.transport.FlowState;
import io.sipstack.transport.event.FlowEvent;
import org.junit.Before;
import org.junit.Test;

import java.time.Duration;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Contains all tests for testing pings in various variations.
 * This class itself is abstract but its just so that it would
 * be easy to run all tests with a different transport as
 * more and more gets added.
 *
 * @author jonas@jonasborjesson.com
 */
public abstract class PingTest extends TransportLayerTestBase {

    @Before
    public void setUp() throws Exception {
        super.setUp();
    }

    public abstract Transport getTransport();

    /**
     * If there is traffic flowing across the flow then we will not issue
     * a PING since the traffic itself is enough to keep the flow open.
     *
     * @throws Exception
     */
    @Test
    public void testNoPingDueToOtherTraffic() throws Exception {
        final Transport transport = getTransport();
        final TransportLayerConfiguration config =
                loadConfiguration(SipConfiguration.class, "PingTest001.yaml").getTransport();
        assertThat("You changed the config file, this test assumes an idle timeout of 40 seconds",
                config.getFlow().getKeepAliveConfiguration().getIdleTimeout().getSeconds(), is(40L));

        final Object[]  objects = initiateFlowToActive(config, transport);
        final Connection connection = (Connection)objects[0];
        final Flow flow = (Flow)objects[1];

        // 20 seconds pass...
        defaultClock.plusSeconds(20);

        // some message is passed through the flow...
        final IOEvent event = IOEvent.create(connection, defaultInviteRequest);
        transportLayer.channelRead(defaultChannelCtx, event);

        // another 10 seconds passes
        defaultClock.plusSeconds(10);

        // the timeout2 timer, which is the ping timer, fires but should now
        // not lead to a options being sent out because the previous message
        // is counted as a ping and that message was received only
        // 10 seconds ago...
        defaultScheduler.fire(SipTimer.Timeout2);
        defaultChannelCtx.assertNothingWritten();

        // the way the scheduling of the idle timer works is that we will
        // reschedule the timer based on the last "ping" or "pong" and since the
        // last message received was the invite request we will use that as
        // the base for when to schedule the next timeout... which will
        // be 30 seconds since the timeout is set for 40 seconds and
        // we received a message 10 seconds ago, which means that if
        // we don't receive another anything within 40 - 10 seconds
        // we should start pinging...
        assertTimerScheduled(SipTimer.Timeout2, Duration.ofSeconds(30));
    }

    /**
     * If we are in the ACTIVE ping mode and have SIP_OPTIONS specified as the
     * preferred mechanism then we should be issuing pings when the idle timer
     * fires. Test that...
     *
     * @throws Exception
     */
    @Test
    public void testSipOptionsPing() throws Exception {
        final Transport transport = getTransport();
        final Object[] objects = initiateFlowToSipOptionsPing(transport);
        final Connection connection = (Connection)objects[0];
        final SipRequest options = (SipRequest)objects[1];

        // Send in the 200 OK to that response which is our pong message.
        // Note, this one should be absorbed by the Flow and not forwarded
        // up the chain...
        final SipResponse response = options.toRequest().createResponse(200).build();
        final SipResponseIOEvent responseEvent = IOEvent.create(connection, response);
        transportLayer.channelRead(defaultChannelCtx, responseEvent);
        defaultChannelCtx.assertSipMessageNotForwarded(response);

        // also, since we are supposed to accept incoming SIP OPTIONS as pings and then
        // we should generate a 200 OK to that ping AND we should NOT forward that option
        // up the stack.
        //
    }

    /**
     * If we issue a SIP options as a ping we are typically waiting for the pong, which should be
     * in the form of a 200 OK. However, if we receive any other type of traffic, let's say
     * an INVITE, then we will use that as a sign that the client on the other side of this
     * flow is alive and healty and as such, we don't really care if we get the 200 OK to the
     * options or not.
     *
     * @param transport
     * @throws Exception
     */
    @Test
    public void testSipOptionsPingPongFromOtherTraffic() throws Exception {
        final Transport transport = getTransport();
        final Object[] objects = initiateFlowToSipOptionsPing(transport);
        final Connection connection = (Connection)objects[0];
        final SipRequest options = (SipRequest)objects[1];

        // Send in an INVITE, which should transition us over to the ACTIVE state again
        // and the invite itself should be forwarded up the stack.
        final SipRequestIOEvent requestEvent = IOEvent.create(connection, defaultInviteRequest);
        transportLayer.channelRead(defaultChannelCtx, requestEvent);
        defaultChannelCtx.assertSipMessageForwarded(defaultInviteRequest);
        final Flow flow = defaultChannelCtx.findForwardedMessageByType(FlowEvent.class).flow();
        assertThat(flow.getState(), is(FlowState.ACTIVE));

        // However, if we do get the 200 OK in we should detect it and NOT forward it
        // upstream...
        final SipResponse response = options.toRequest().createResponse(200).build();
        final SipResponseIOEvent responseEvent = IOEvent.create(connection, response);
        transportLayer.channelRead(defaultChannelCtx, responseEvent);
        defaultChannelCtx.assertSipMessageNotForwarded(response);
    }

    /**
     * If we end up in the PING state we will stay there until we receive something, either
     * a PONG or any other traffic. If we don't, then a timer will fire and we will re-issue
     * the PING and after a configurable amount of time we will give up and transition
     * to the CLOSING state, which will kill the flow.
     *
     * @throws Exception
     */
    @Test
    public void testSipOptionsPingNoResponseTimeout() throws Exception {
        initiateFlowToSipOptionsPing(getTransport());

    }

    /**
     * Convenience method for transitioning the Flow state machine over to waiting for a pong
     * @param transport
     * @throws Exception
     * @return first object, the connection, second, the SIP Options request
     *
     */
    public Object[] initiateFlowToSipOptionsPing(final Transport transport) throws Exception {
        final TransportLayerConfiguration config =
                loadConfiguration(SipConfiguration.class, "PingTest001.yaml").getTransport();
        final Connection connection = (Connection)initiateFlowToActive(config, transport)[0];

        defaultClock.plusSeconds(config.getFlow().getKeepAliveConfiguration().getIdleTimeout().plusSeconds(1).getSeconds());

        // Fire the idle timer, which then should trigger a SIP options to be sent out.
        // Note that the idle timer is scheduled as the Timeout2 timer
        defaultScheduler.fire(SipTimer.Timeout2);
        final SipRequestIOEvent optionsEvent = defaultChannelCtx.findWrittenMessageByType(SipRequestIOEvent.class);
        final SipRequest options = optionsEvent.request();

        // ensure that the options is indeed an options and that the
        // request-uri, to and from are all matching up that of the
        // configuration since the user can control this.
        final SipOptionsPingConfiguration sipOptionsConfig = config.getFlow().
                getKeepAliveConfiguration().
                getKeepAliveMethodConfiguration(transport).
                getSipOptionsConfiguration();
        assertThat(options.isOptions(), is(true));
        final SipURI actualFrom = options.getFromHeader().getAddress().getURI().toSipURI();
        final SipURI actualTo = options.getToHeader().getAddress().getURI().toSipURI();
        final String expectedFrom = sipOptionsConfig.getFromUser();
        final String expectedTo = sipOptionsConfig.getToUser();

        assertThat(actualFrom.getUser().toString(), is(expectedFrom));
        assertThat(actualTo.getUser().toString(), is(expectedTo));

        return new Object[]{connection, options};
    }
}


text:
/*
 * Created on Mar 1, 2004
 *
 */
package groovy.swt.guibuilder;

import groovy.jface.JFaceBuilder;
import groovy.jmx.builder.JmxBuilder;
import groovy.util.GroovyScriptEngine;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * WORK IN PROGRESS, don't use this one yet
 *
 * This will be the main guibuilder
 *
 * TODO provide entry point for pull tools (e.g. i18n, security)
 *
 * @author <a href:ckl at dacelo.nl">Christiaan ten Klooster </a>
 * @version $Revision: 1141 $
 */
public class ApplicationGuiBuilder extends JFaceBuilder {
    /** the logger */
    private Logger log = Logger.getLogger(getClass().getName());

    /** the caching script engine */
    private GroovyScriptEngine scriptEngine;

    /**
     * the constructor
     *
     * @param rootUrl
     * @throws IOException
     */
    public ApplicationGuiBuilder(String rootUrl) throws IOException {
    	super(true);
        scriptEngine = new GroovyScriptEngine(rootUrl);
    }

    /*
     * @see groovy.swt.SwtBuilder#registerWidgets()
     */
    public void registerApplicationWidgets() {
        registerFactory("rebuild", new RebuildFactory(this));
        registerFactory("runScript", new RunScriptFactory(this));
    }

    /**
     * @return Returns the scriptEngine.
     */
    public GroovyScriptEngine getScriptEngine() {
        return scriptEngine;
    }

}

redpajama_set_name: RedPajamaGithub


text:
See first the [ruby article](https://github.com/swhalley/KnowledgeBase/blob/master/Ruby_Install.md). Permission errors and other dependency problems may arise if a user copy of Ruby isn't installed.

### Jekyll Install
* If Ruby is installed ok, it should be as simple as running `gem install jekyll` from a command line

Most recent updates here https://jekyllrb.com/docs/quickstart/

Creating a new project or running from command line, see the Jekyll documentation

### Webstorm integration - Add Jekyll Launcher
* Preferences (command + ,)
* External Tools
* Add (+)
    * Give it any name (i.e. Jekyll Launcher) and description
    * For Program field use `jekyll`
    * For Parameters use `serve --watch` which auto updates the server with changes
    * For Working Directory there are a few choices
        * Add your projects path
        * Use a variable `insert macro` and choose ProjectFileDir, Projectpath, or another choice which points to your jekyll project

At this point, launch the application normall. use `run` `edit configuration` `new` pick a javascript runner/debug and in the URL field put in `http://127.0.0.1:4000` which is the URL that jekyll will serve from by default

### Working with Multiple Environments
Best way may be to set the `--config _config.yml` on the command line. this is done as part of the `jekyll serve --config _config.yml`. This way we can have a local and prod version. Add this to the Webstorm integration as well to work easier in local environment. In the config, change things like the `url` which can not be switched at the command line.


text:
export const enum sex {
    Male,
    Female
}

export enum category {
    Home,
    Work
}

export enum phoneCatgory {
    Home,
    Work,
    Mobile
}

export interface IEMail {
    id?: number;
    cat?: category;
    body: string;
}

export interface IEnterprise {
    id: number;
    title: string;
}

export interface IUnit {
    id: number;
    title: string;
    parent?: any;
    enterprise: IEnterprise;
}

export interface IPosition {
    id: number;
    unit: IUnit;
    title: string;
    since: string;
    until?: any;
}

export interface IPhone {
    id: number;
    cat: phoneCatgory;
    country_code: number;
    area_code: number;
    number: string;
}

export interface IPerson {
    id: number;
    user: number;
    first_name: string;
    last_name: string;
    mid_name: string;
    date_of_birth: string;
    sex: sex;
    bio: string;
    emails?: IEMail[];
    positions?: IPosition[];
    phones?: IPhone[];
}

export interface IUser {
    id?: number;
    username: string;
    password?: string;
    person?: IPerson;
    is_auth: boolean;
}


text:
=================
Contributing Code
=================

How to contribute Code


text:
/**
 * @author: @AngularClass
 */

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

/*
 * Webpack Plugins
 */
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/*
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Hunt',
  baseUrl: '/'
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * Cache generated modules and chunks to improve performance for multiple incremental builds.
   * This is enabled by default in watch mode.
   * You can pass false to disable it.
   *
   * See: http://webpack.github.io/docs/configuration.html#cache
   * cache: false,
   *
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts'

  },

  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules'],

    alias: {
      'angular2': helpers.root('node_modules/@angularclass/angular2-beta-to-rc-alias/dist/beta-17')
    }

  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
       // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material'),
          helpers.root('node_modules/@angular')
        ]
      }

    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

      /*
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      /*
       * Raw loader support for *.css files
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },

      /* Sass loader for *.scss
       *
       * See https://github.com/jtangelder/sass-loader
       */
      {
        test: /\.scss$/,
        include: [helpers.root('src/assets/styles')],
        loader: 'style!css!!sass'
      }

    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /*
     * Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurenceOrderPlugin(true),

    /*
     * Plugin: CommonsChunkPlugin
     * Description: Shares common code between the pages.
     * It identifies common modules and put them into a commons chunk.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
     * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
     */
     new webpack.optimize.CommonsChunkPlugin({
       name: ['polyfills', 'vendor'].reverse()
     }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    /*
     * Plugin: HtmlWebpackPlugin
     * Description: Simplifies creation of HTML files to serve your webpack bundles.
     * This is especially useful for webpack bundles that include a hash in the filename
     * which changes every compilation.
     *
     * See: https://github.com/ampedandwired/html-webpack-plugin
     */
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: helpers.packageSort(['polyfills', 'vendor', 'main'])
    })

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};


text:
Autowatch Jira
==============
A simple plugin for [Atlassian](http://atlassian.com) [JIRA](http://atlassian.com/jira/) that
automatically adds users to the list of watchers for a ticket when they touch the ticket, changing
watching from an opt-in into an opt-out (users who, for some reason, don't want to watch an issue
after editing it can still opt-out by unwatching with a single click).

Installation
------------
Use JIRA's awesome plugin manager to install from the plugin repository.

Configuration
-------------
Within JIRA with Autowatch Jira installed, navigate to `Administration > System > Advanced > Listeners`
and you should see an `Autowatch Jira Listener` entry.  If you click on the Edit link for this listener, you
will see two settings:

1. Comma-separated project keys to exclude.  Enter the project key(s) for any project(s) that you do
   not want automatic watching to affect.  If there is more than one, place commas between them.  If you enter
   keys in this list, projects not in this list will still have automatic watching enabled.
2. Comma-separated project keys to include.  If you only want a automatic watching for a few of your
   projects, then enter the key(s) for those project(s) here and all other projects (not in this list) will
   not have automatic watching.

In general, you should be using either one of the above settings, but not both.  If you want automatic watching
for most projects, list the exclusions; if you have lots of projects and only want a few to use automatic watching,
then list the projects to include (all others will be excluded).


text:
HidingHerFace
=============

Hiding Her Face


text:
package org.usergrid.rest.test.resource.app.queue;

import org.codehaus.jackson.JsonNode;
import org.usergrid.rest.test.resource.CollectionResource;
import org.usergrid.rest.test.resource.NamedResource;

import com.sun.jersey.api.client.WebResource;

/**
 * A resource for testing queues
 *
 * @author tnine
 *
 */
public class Transaction extends CollectionResource {

  private String clientId;
  private long timeout = 0;

  /**
   *
   */
  public Transaction(String transactionName, NamedResource parent) {
    super(transactionName, parent);
  }

  /**
   * Set the client id with the string
   *
   * @param clientId
   * @return
   */
  public Transaction withClientId(String clientId) {
    this.clientId = clientId;
    return this;
  }

  /**
   * post to the entity set
   *
   * @param entity
   * @return
   */
  public JsonNode delete() {
    return jsonMedia(withParams(withToken(resource()))).delete(JsonNode.class);
  }

  /**
   * Renew this transaction to the set timeout
   *
   * @param timeout
   * @return
   */
  public JsonNode renew(long timeout) {
    this.timeout = timeout;
    return super.putInternal(null);
  }

  /**
   * Set the queue client ID if set
   *
   * @param resource
   * @return
   */
  protected WebResource withParams(WebResource resource) {
    if (clientId != null) {
      resource = resource.queryParam("consumer", clientId);
    }
    if (timeout > 0) {
      resource = resource.queryParam("timeout", String.valueOf(timeout));
    }

    return resource;
  }

}


text:
package org.neuroph.nnet.learning;

import org.neuroph.core.Connection;
import org.neuroph.core.learning.DataSet;
import org.neuroph.core.learning.UnsupervisedLearning;
import org.neuroph.nnet.comp.layer.CompetitiveLayer;
import org.neuroph.nnet.comp.neuron.CompetitiveNeuron;

/**
 * Competitive learning rule.
 *
 * @author Zoran Sevarac <sevarac@gmail.com>
 */
public class CompetitiveLearning extends UnsupervisedLearning {

	/**
	 * The class fingerprint that is set to indicate serialization
	 * compatibility with a previous version of the class.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Creates new instance of CompetitiveLearning
	 */
	public CompetitiveLearning() {
		super();
	}

	/**
	 * This method does one learning epoch for the unsupervised learning rules.
	 * It iterates through the training set and trains network weights for each
	 * element. Stops learning after one epoch.
	 *
	 * @param trainingSet
	 *            training set for training network
	 */
	@Override
	public void doLearningEpoch(DataSet trainingSet) {
		super.doLearningEpoch(trainingSet);
		stopLearning(); // stop learning ahter one learning epoch - because we dont have any stopping criteria  for unsupervised...
	}

	/**
	 * Adjusts weights for the winning neuron
	 */
	protected void updateNetworkWeights() {
		// find active neuron in output layer
		// TODO : change idx, in general case not 1
		CompetitiveNeuron winningNeuron = ((CompetitiveLayer) neuralNetwork
				.getLayerAt(1)).getWinner();

		Connection[] inputConnections = winningNeuron
				.getConnectionsFromOtherLayers();

		for(Connection connection : inputConnections) {
			double weight = connection.getWeight().getValue();
			double input = connection.getInput();
			double deltaWeight = this.learningRate * (input - weight);
			connection.getWeight().inc(deltaWeight);
		}
	}

}


text:
require_migration

describe AddNotificationTablesToReplicationExcludes do
  let(:settings_change_stub) { migration_stub(:SettingsChange) }
  let(:server_one)           { FactoryGirl.create(:miq_server) }
  let(:server_two)           { FactoryGirl.create(:miq_server) }

  migration_context :up do
    it "adds notification tables to the replication excludes" do
      server_one.settings_changes
                .create!(:key   => described_class::EXCLUDES_KEY,
                         :value => %w(schema_migrations))
      server_two.settings_changes
                .create!(:key   => described_class::EXCLUDES_KEY,
                         :value => %w(ar_internal_metadata))

      migrate

      changes = settings_change_stub.where(:key => described_class::EXCLUDES_KEY)
      changes.each do |c|
        expect(c.value).to include("notifications")
        expect(c.value).to include("notification_types")
        expect(c.value).to include("notification_recipients")
      end
    end
  end

  migration_context :down do
    it "removes notification tables from the replication excludes" do
      server_one.settings_changes
                .create!(:key   => described_class::EXCLUDES_KEY,
                         :value => %w(notification_types notifications schema_migrations))
      server_two.settings_changes
                .create!(:key   => described_class::EXCLUDES_KEY,
                         :value => %w(notification_types notification_recipients ar_internal_metadata))

      migrate

      changes = settings_change_stub.where(:key => described_class::EXCLUDES_KEY)
      changes.each do |c|
        expect(c.value).not_to include("notifications")
        expect(c.value).not_to include("notification_types")
        expect(c.value).not_to include("notification_recipients")
      end
    end
  end
end


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>@yield('title', Config::get('site.title'))</title>
    <meta name="description" content="@yield('description', Config::get('site.description'))">

    <link rel="canonical" href="{{ URL::current() }}">

    <meta name="base_url" content="{{ URL::to('/') }}">
    <meta name="_token" content="{{ csrf_token() }}" />

    <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" type="image/x-icon">

    <link rel="stylesheet" href="{{ assets_url('css/vendors/bootstrap/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ assets_url('css/site.prefixed.min.css') }}?v={{ filemtime(public_path() . '/assets/css/site.prefixed.min.css') }}">

    @yield('styles')

    <link rel="author" href="{{ asset('humans.txt') }}">

    <script>
      window.base_url = '{{ URL::to('/') }}';
    </script>
  </head>
  <body>
    @yield('content')

    <script src="{{ assets_url('js/vendors/jquery-1.11.0.min.js') }}"></script>
    <script src="{{ assets_url('js/vendors/bootstrap.min.js') }}"></script>

    @yield('scripts')

  </body>
</html>


text:
a swift 3.0 demo project

include library:

>[RxAlamofire](https://github.com/RxSwiftCommunity/RxAlamofire)

>[ObjectMapper](https://github.com/Hearst-DD/ObjectMapper)

>[Kingfisher](https://github.com/onevcat/Kingfisher)

>[SnapKit](https://github.com/SnapKit/SnapKit)


text:
[![Build Status](https://secure.travis-ci.org/lawrencepit/ruby-saml-idp.png)](http://travis-ci.org/lawrencepit/ruby-saml-idp?branch=master)
[![Code Climate](https://codeclimate.com/github/lawrencepit/ruby-saml-idp/badges/gpa.svg)](https://codeclimate.com/github/lawrencepit/ruby-saml-idp)
[![Gem Version](https://fury-badge.herokuapp.com/rb/ruby-saml-idp.png)](http://badge.fury.io/rb/ruby-saml-idp)

The ruby SAML Identity Provider library is for implementing the server side of SAML authentication. It allows your application to act as an IdP (Identity Provider) using the [SAML v2.0](http://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) protocol. It provides a means for managing authentication requests and confirmation responses for SPs (Service Providers).

Setting up a "real" IdP is such an undertaking I didn't care for such an achievement. I wanted something very simple that just works without having to install extra components and setup extra infrastructure. In it's current form it's basic. This is because currently I use it for manual and end-to-end testing purposes of the Service Provider side only. It is reversed engineered from real-world SAML Responses sent by ADFS systems.

Installation and Usage
----------------------

Add this to your Gemfile:

    gem 'ruby-saml-idp'

### Not using rails?

Include `SamlIdp::Controller` and see the examples that use rails. It should be straightforward for you.

Basically you call `decode_SAMLRequest(params[:SAMLRequest])` on an incoming request and then use the value `saml_acs_url` to determine the source for which you need to authenticate a user. How you authenticate a user is entirely up to you.

Once a user has successfully authenticated on your system send the Service Provider a SAMLReponse by posting to `saml_acs_url` the parameter `SAMLResponse` with the return value from a call to `encode_SAMLResponse(user_email)`.

### Using rails?

Add to your `routes.rb` file, for example:

``` ruby
get '/saml/auth' => 'saml_idp#new'
post '/saml/auth' => 'saml_idp#create'
```

Create a controller that looks like this, customize to your own situation:

``` ruby
class SamlIdpController < SamlIdp::IdpController
  before_filter :find_account
  # layout 'saml_idp'

  def idp_authenticate(email, password)
    user = @account.users.where(:email => params[:email]).first
    user && user.valid_password?(params[:password]) ? user : nil
  end

  def idp_make_saml_response(user)
    encode_SAMLResponse(user.email)
  end

  private

    def find_account
      @subdomain = saml_acs_url[/https?:\/\/(.+?)\.example.com/, 1]
      @account = Account.find_by_subdomain(@subdomain)
      render :status => :forbidden unless @account.saml_enabled?
    end

end
```

The most minimal example controller would look like:

``` ruby
class SamlIdpController < SamlIdp::IdpController

  def idp_authenticate(email, password)
    true
  end

  def idp_make_saml_response(user)
    encode_SAMLResponse("you@example.com")
  end

end
```

Keys and Secrets
----------------

To generate the SAML Response it uses a default X.509 certificate and secret key... which isn't so secret. You can find them in `SamlIdp::Default`. The X.509 certificate is valid until year 2032. Obviously you shouldn't use these if you intend to use this in production environments. In that case, within the controller set the properties `x509_certificate` and `secret_key` using a `prepend_before_filter` callback within the current request context or set them globally via the `SamlIdp.config.x509_certificate` and `SamlIdp.config.secret_key` properties.

The fingerprint to use, if you use the default X.509 certificate of this gem, is:

```
9E:65:2E:03:06:8D:80:F2:86:C7:6C:77:A1:D9:14:97:0A:4D:F4:4D
```

Service Providers
-----------------

To act as a Service Provider which generates SAML Requests and can react to SAML Responses use the excellent [ruby-saml](https://github.com/onelogin/ruby-saml) gem.

Author
----------

Lawrence Pit, lawrence.pit@gmail.com, [lawrencepit.com](http://lawrencepit.com), [@lawrencepit](http://twitter.com/lawrencepit)

Copyright
-----------

Copyright (c) 2012 Lawrence Pit. See MIT-LICENSE for details.


text:
title: Christmas Gifts
created_at: 2011-01-05
kind: article
tags: ['sensing-data', 'doodles', 'music']
---

How many gifts did my true love give to me on all twelve nights of Christmas?

After seeing Information is Beautiful's recent information animation,
I decided that I'd make my own.

<iframe
  width="560" height="315"
  src="http://www.youtube.com/embed/rLZDvXPIDa0"
  frameborder="0" allowfullscreen
></iframe>

I used R to [generate a PDF](http://gitorious.org/tlevine/12daysplot/blobs/master/12daysslideshow.R)
and then did a screencast of the PDF.


text:
export * from './details/details.controller';
export * from './details/IKubernetesSecurityGroup';


text:
layout: post
title: "Periodically sending JVM stats to StatsD in Scala"
date: 2014-01-01 15:10
comments: true
tags: [scala, stats, akka]

---

I have written a small library in Scala to allow periodic sending of JVM stats to StatsD server. One can include it in server written in Scala so that its JVM stats can be monitored over time. I am using the following [Scala class](https://github.com/etsy/statsd/blob/master/examples/StatsD.scala) to send the stats to StatsD. Also the technique to extract JVM stats is borrowed from twitter's excellent [Ostrich library](https://github.com/twitter/ostrich)

Following is the class that schedules sending of the stats periodically

{% highlight scala %}
package com.parthpatil.jvmstatsd

import scala.collection.mutable
import java.util.concurrent.{TimeUnit, Executors}

class StatsSender(statsd: StatsD, numSchedulerThreads: Int = 2) {
  // Tasks that need to be scheduled to send stats to statsd
  private val tasks = mutable.ArrayBuffer[(StatsTask, Int)]()
  val fScheduler    = Executors.newScheduledThreadPool(numSchedulerThreads)

  def addTask(task: StatsTask, secs: Int) {
    task.setStatsD(statsd)
    tasks += ((task, secs))
    fScheduler.scheduleWithFixedDelay(task, 0, secs, TimeUnit.SECONDS)
  }

  def getTasks(): Seq[(StatsTask, Int)] = {
    tasks.toSeq
  }
}
{% endhighlight %}

Following is the interface base class for a stats task that publishes stats to StatsD using the StatsD class

{% highlight scala %}
package com.parthpatil.jvmstatsd

import java.text.DecimalFormat

class StatsTask() extends Runnable {
  protected var statsd: StatsD = null

  // formatter to remove scientific notation from doubles
  val formatter = new DecimalFormat("#")

  override def run() { }
  def setStatsD(sd: StatsD) { statsd = sd }
}
{% endhighlight %}

Following is a sample implementation of the StatsTask that publishes JVM stats. You can write your won periodic stats publisher by extending StatsTask and adding it to StatsSender via addTask() method.

{% highlight scala %}
package com.parthpatil.jvmstatsd

import java.lang.management.ManagementFactory
import scala.collection.mutable
import scala.collection.JavaConverters._
import com.twitter.conversions.string._

class JvmStatsTask extends StatsTask {
  override def run() {
    getJvmGauges() foreach { case (k, v)  => statsd.gauge(k, formatter.format(v)) }
    getJvmCounters() foreach { case (k,v) => statsd.increment(k, v) }
  }

  def getJvmGauges(): Map[String, Long] = {
    val out = mutable.Map[String, Long]()

    val mem = ManagementFactory.getMemoryMXBean()

    val heap = mem.getHeapMemoryUsage()
    out += ("jvm.heap.committed" -> heap.getCommitted())
    out += ("jvm.heap.max" -> heap.getMax())
    out += ("jvm.heap.used" -> heap.getUsed())

    val nonheap = mem.getNonHeapMemoryUsage()
    out += ("jvm.nonheap.committed" -> nonheap.getCommitted())
    out += ("jvm.nonheap.max" -> nonheap.getMax())
    out += ("jvm.nonheap.used" -> nonheap.getUsed())

    val threads = ManagementFactory.getThreadMXBean()
    out += ("jvm.thread.daemon_count" -> threads.getDaemonThreadCount().toLong)
    out += ("jvm.thread.count" -> threads.getThreadCount().toLong)
    out += ("jvm.thread.peak_count" -> threads.getPeakThreadCount().toLong)

    val runtime = ManagementFactory.getRuntimeMXBean()
    out += ("jvm.start_time" -> runtime.getStartTime())
    out += ("jvm.uptime" -> runtime.getUptime())

    val os = ManagementFactory.getOperatingSystemMXBean()
    out += ("jvm.num_cpus" -> os.getAvailableProcessors().toLong)
    os match {
      case unix: com.sun.management.UnixOperatingSystemMXBean =>
        out += ("jvm.fd.count" -> unix.getOpenFileDescriptorCount)
        out += ("jvm.fd.limit" -> unix.getMaxFileDescriptorCount)
      case _ =>   // ew, Windows... or something
    }

    var postGCTotalUsage = 0L
    var currentTotalUsage = 0L
    ManagementFactory.getMemoryPoolMXBeans().asScala.foreach { pool =>
      val name = pool.getName.regexSub("""[^\w]""".r) { m => "." }
      Option(pool.getCollectionUsage).foreach { usage =>
        out += ("jvm.post_gc." + name + ".used" -> usage.getUsed)
        postGCTotalUsage += usage.getUsed
        out += ("jvm.post_gc." + name + ".max" -> usage.getMax)
      }
      Option(pool.getUsage) foreach { usage =>
        out += ("jvm.current_mem." + name + ".used" -> usage.getUsed)
        currentTotalUsage += usage.getUsed
        out += ("jvm.current_mem." + name + ".max" -> usage.getMax)
      }
    }
    out += ("jvm.post_gc.used" -> postGCTotalUsage)
    out += ("jvm.current_mem.used" -> currentTotalUsage)

    out.toMap
  }

  def getJvmCounters(): Map[String, Long] = {
    val out = mutable.Map[String, Long]()

    var totalCycles = 0L
    var totalTime = 0L

    ManagementFactory.getGarbageCollectorMXBeans().asScala.foreach { gc =>
      val name = gc.getName.regexSub("""[^\w]""".r) { m => "." }
      val collectionCount = gc.getCollectionCount
      out += ("jvm.gc." + name + ".cycles" -> collectionCount)
      val collectionTime = gc.getCollectionTime
      out += ("jvm.gc." + name + ".msec" -> collectionTime)
      // note, these could be -1 if the collector doesn't have support for it.
      if (collectionCount > 0)
        totalCycles += collectionCount
      if (collectionTime > 0)
        totalTime += gc.getCollectionTime
    }
    out += ("jvm.gc.cycles" -> totalCycles)
    out += ("jvm.gc.msec" -> totalTime)

    out.toMap
  }
}
{% endhighlight %}

Sample Usage

{% highlight scala %}
package com.parthpatil.jvmstatsd

import akka.actor.ActorSystem
import scala.concurrent.ExecutionContext.Implicits.global

class SampleUsage {
  def main(args: Array[String]) {
    val actorSystem = ActorSystem("statsd-actor-system")
    val statsD = new StatsD(
      context = actorSystem,
      host = "localhost",
      port = 8192)

    val statsSender = new StatsSender(statsD)

    // Create the JvmStatsTask that publishes stats every 10 secs
    statsSender.addTask(task = new JvmStatsTask, secs = 10)
  }
}
{% endhighlight %}

You can find the full source in this [repo](https://github.com/parth-patil/JvmStatsD)


text:
from django_tables2 import SingleTableView

from .filters import PhoneFilter
from .forms import CustomerListFormHelper

class PagedFilteredTableView(SingleTableView):
    filter_class = PhoneFilter
    formhelper_class = CustomerListFormHelper
    context_filter_name = 'filter'

    def get_queryset(self, **kwargs):
        qs = super(PagedFilteredTableView, self).get_queryset()
        self.filter = self.filter_class(self.request.GET, queryset=qs)
        self.filter.form.helper = self.formhelper_class()
        return self.filter.qs

    def get_context_data(self, **kwargs):
        context = super(PagedFilteredTableView, self).get_context_data()
        context[self.context_filter_name] = self.filter
        return context


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License. See accompanying LICENSE file.
-->
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-project</artifactId>
    <version>3.3.0-SNAPSHOT</version>
    <relativePath>../../hadoop-project</relativePath>
  </parent>
  <artifactId>hadoop-client-integration-tests</artifactId>
  <version>3.3.0-SNAPSHOT</version>

  <description>Checks that we can use the generated artifacts</description>
  <name>Apache Hadoop Client Packaging Integration Tests</name>

  <properties>
    <failsafe.timeout>400</failsafe.timeout>
  </properties>

  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <profiles>
    <profile>
      <id>shade</id>
      <activation>
        <property><name>!skipShade</name></property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client-api</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client-runtime</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client-minicluster</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <!-- Because our tests rely on our shaded artifacts, we can't compile
               them until after the package phase has run.
            -->
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <executions>
            <!--
               First, let's make sure the normal test-compile doesn't try to
               compile our integration tests.
            -->
              <execution>
                <id>default-testCompile</id>
                <phase>test-compile</phase>
                <configuration>
                  <testExcludes>
                    <testExclude>**/IT*</testExclude>
                    <testExclude>**/*IT</testExclude>
                  </testExcludes>
                </configuration>
              </execution>
            <!--
               Finally, let's make a 'just for integration tests'-compile that
               fires off prior to our integration tests but after the package
               phase has created our shaded artifacts.
            -->
              <execution>
                <id>compile-integration-tests</id>
                <phase>pre-integration-test</phase>
                <goals>
                  <goal>testCompile</goal>
                </goals>
                <configuration>
                  <testIncludes>
                    <testInclude>**/IT*</testInclude>
                    <testInclude>**/*IT</testInclude>
                  </testIncludes>
                </configuration>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <trimStackTrace>false</trimStackTrace>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>noshade</id>
      <activation>
        <property><name>skipShade</name></property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-common</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-hdfs-client</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-hdfs</artifactId>
          <scope>test</scope>
          <type>test-jar</type>
        </dependency>
      </dependencies>
    </profile>
  </profiles>

</project>


text:
A Roc plugin that adds support for API testing using dredd

## Documentation
- [Actions](docs/Actions.md)
- [Commands](docs/Commands.md)
- [Configuration](docs/Configuration.md)
- [Dependencies](docs/Dependencies.md)
- [Hooks](docs/Hooks.md)
- [Settings](docs/Settings.md)
- [Extensions](docs/Extensions.md)

---
_Generated by [Roc](https://github.com/rocjs/roc)_


text:
<?php
class Shop extends Eloquent  {

       protected $fillable = array('Nameshop','Detail','Price','City','Type','Email','Seat');
	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'shop';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	*/
	/* Define primary key for Identifier */
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto"
        tools:layout_height="250dp"
        tools:layout_width="200dp"
        android:background="@color/cardview_shadow_start_color"
>

    <ImageView
            android:id="@+id/imag_center"
            android:layout_width="120dp"
            android:layout_height="150dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:src="@mipmap/img_006"
            app:layout_constraintEnd_toEndOf="parent"
            android:scaleType="fitXY"
    />

    <TextView
            android:id="@+id/text_title"
            android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintTop_toBottomOf="@id/imag_center"
              app:layout_constraintStart_toStartOf="@id/imag_center"
              app:layout_constraintEnd_toEndOf="@id/imag_center"
              android:layout_marginTop="10dp"
              android:text="主标题"
    />

    <TextView
            android:id="@+id/text_sub_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/text_title"
            app:layout_constraintStart_toStartOf="@id/imag_center"
            app:layout_constraintEnd_toEndOf="@id/imag_center"
            android:layout_marginTop="10dp"
            android:text="副标题"
    />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
require "helper"

module Nokogiri
  module XML
    class TestBuilder < Nokogiri::TestCase
      def test_attribute_sensitivity
        xml = Nokogiri::XML::Builder.new { |x|
          x.tag "hello", "abcDef" => "world"
        }.to_xml
        doc = Nokogiri.XML xml
        assert_equal 'world', doc.root['abcDef']
      end

      def test_builder_multiple_nodes
        Nokogiri::XML::Builder.new do |xml|
          0.upto(10) do
            xml.text "test"
          end
        end
      end

      def test_builder_with_utf8_text
        text = "test ﺵ "
        doc = Nokogiri::XML::Builder.new(:encoding => "UTF-8") { |xml| xml.test text }.doc
        assert_equal text, doc.content
      end

      def test_builder_escape
        xml = Nokogiri::XML::Builder.new { |x|
          x.condition "value < 1", :attr => "value < 1"
        }.to_xml
        doc = Nokogiri.XML xml
        assert_equal 'value < 1', doc.root['attr']
        assert_equal 'value < 1', doc.root.content
      end

      def test_builder_namespace
        doc = Nokogiri::XML::Builder.new { |xml|
          xml.a("xmlns:a" => "x") do
            xml.b("xmlns:a" => "x", "xmlns:b" => "y")
          end
        }.doc

        b = doc.at('b')
        assert b
        assert_equal({"xmlns:a"=>"x", "xmlns:b"=>"y"}, b.namespaces)
        assert_equal({"xmlns:b"=>"y"}, namespaces_defined_on(b))
      end

      def test_builder_namespace_part_deux
        doc = Nokogiri::XML::Builder.new { |xml|
          xml.a("xmlns:b" => "y") do
            xml.b("xmlns:a" => "x", "xmlns:b" => "y", "xmlns:c" => "z")
          end
        }.doc

        b = doc.at('b')
        assert b
        assert_equal({"xmlns:a"=>"x", "xmlns:b"=>"y", "xmlns:c"=>"z"}, b.namespaces)
        assert_equal({"xmlns:a"=>"x", "xmlns:c"=>"z"}, namespaces_defined_on(b))
      end

      def test_builder_with_unlink
        b = Nokogiri::XML::Builder.new do |xml|
          xml.foo do
            xml.bar { xml.parent.unlink }
            xml.bar2
          end
        end
        assert b
      end

      def test_with_root
        doc = Nokogiri::XML(File.read(XML_FILE))
        Nokogiri::XML::Builder.with(doc.at('employee')) do |xml|
          xml.foo
        end
        assert_equal 1, doc.xpath('//employee/foo').length
      end

      def test_root_namespace_default_decl
        b = Nokogiri::XML::Builder.new { |xml| xml.root(:xmlns => 'one:two') }
        doc = b.doc
        assert_equal 'one:two', doc.root.namespace.href
        assert_equal({ 'xmlns' => 'one:two' }, doc.root.namespaces)
      end

      def test_root_namespace_multi_decl
        b = Nokogiri::XML::Builder.new { |xml|
          xml.root(:xmlns => 'one:two', 'xmlns:foo' => 'bar') do
            xml.hello
          end
        }
        doc = b.doc
        assert_equal 'one:two', doc.root.namespace.href
        assert_equal({ 'xmlns' => 'one:two', 'xmlns:foo' => 'bar' }, doc.root.namespaces)

        assert_equal 'one:two', doc.at('hello').namespace.href
      end

      def test_non_root_namespace
        b = Nokogiri::XML::Builder.new { |xml|
          xml.root { xml.hello(:xmlns => 'one') }
        }
        assert_equal 'one', b.doc.at('hello', 'xmlns' => 'one').namespace.href
      end

      def test_specify_namespace
        b = Nokogiri::XML::Builder.new { |xml|
          xml.root('xmlns:foo' => 'bar') do
            xml[:foo].bar
            xml['foo'].baz
          end
        }
        doc = b.doc
        assert_equal 'bar', doc.at('foo|bar', 'foo' => 'bar').namespace.href
        assert_equal 'bar', doc.at('foo|baz', 'foo' => 'bar').namespace.href
      end

      def test_dtd_in_builder_output
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.doc.create_internal_subset(
                                         'html',
                                         "-//W3C//DTD HTML 4.01 Transitional//EN",
                                         "http://www.w3.org/TR/html4/loose.dtd"
                                         )
          xml.root do
            xml.foo
          end
        end
        assert_match(/<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/loose.dtd">/,
                     builder.to_xml)
      end

      def test_specify_namespace_nested
        b = Nokogiri::XML::Builder.new { |xml|
          xml.root('xmlns:foo' => 'bar') do
            xml.yay do
              xml[:foo].bar

              xml.yikes do
                xml['foo'].baz
              end
            end
          end
        }
        doc = b.doc
        assert_equal 'bar', doc.at('foo|bar', 'foo' => 'bar').namespace.href
        assert_equal 'bar', doc.at('foo|baz', 'foo' => 'bar').namespace.href
      end

      def test_specified_namespace_postdeclared
        doc = Nokogiri::XML::Builder.new { |xml|
          xml.a do
            xml[:foo].b("xmlns:foo" => "bar")
          end
        }.doc
        a = doc.at('a')
        assert_equal({}, a.namespaces)

        b = doc.at_xpath('//foo:b', {:foo=>'bar'})
        assert b
        assert_equal({"xmlns:foo"=>"bar"}, b.namespaces)
        assert_equal("b", b.name)
        assert_equal("bar", b.namespace.href)
      end

      def test_specified_namespace_undeclared
        Nokogiri::XML::Builder.new { |xml|
          xml.root do
            assert_raises(ArgumentError) do
              xml[:foo].bar
            end
          end
        }
      end

      def test_set_encoding
        builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
          xml.root do
            xml.bar 'blah'
          end
        end
        assert_match 'UTF-8', builder.to_xml
      end

      def test_bang_and_underscore_is_escaped
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.root do
            xml.p_('adsfadsf')
            xml.p!('adsfadsf')
          end
        end
        assert_equal 2, builder.doc.xpath('//p').length
      end

      def test_square_brackets_set_attributes
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.root do
            foo = xml.foo
            foo['id'] = 'hello'
            assert_equal 'hello', foo['id']
          end
        end
        assert_equal 1, builder.doc.xpath('//foo[@id = "hello"]').length
      end

      def test_nested_local_variable
        @ivar     = 'hello'
        local_var = 'hello world'
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.root do
            xml.foo local_var
            xml.bar @ivar
            xml.baz {
              xml.text @ivar
            }
          end
        end

        assert_equal 'hello world', builder.doc.at('//root/foo').content
        assert_equal 'hello', builder.doc.at('//root/bar').content
        assert_equal 'hello', builder.doc.at('baz').content
      end

      def test_raw_append
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.root do
            xml << 'hello'
          end
        end

        assert_equal 'hello', builder.doc.at('/root').content
      end

      def test_raw_append_with_instance_eval
        builder = Nokogiri::XML::Builder.new do
          root do
            self << 'hello'
          end
        end

        assert_equal 'hello', builder.doc.at('/root').content
      end

      def test_raw_xml_append
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.root do
            xml << '<aaa><bbb/><ccc/></aaa>'
          end
        end

        assert_equal ["aaa"],       builder.doc.at_css("root").children.collect(&:name)
        assert_equal ["bbb","ccc"], builder.doc.at_css("aaa").children.collect(&:name)
      end

      def test_raw_xml_append_with_namespaces
        doc = Nokogiri::XML::Builder.new do |xml|
          xml.root("xmlns:foo" => "x", "xmlns" => "y") do
            xml << '<Element foo:bar="bazz"/>'
          end
        end.doc

        el = doc.at 'Element'
        assert_not_nil el

        assert_equal 'y', el.namespace.href
        assert_nil el.namespace.prefix

        attr = el.attributes["bar"]
        assert_not_nil attr
        assert_not_nil attr.namespace
        assert_equal "foo", attr.namespace.prefix
      end

      def test_cdata
        builder = Nokogiri::XML::Builder.new do
          root {
            cdata "hello world"
          }
        end
        assert_equal("<?xml version=\"1.0\"?><root><![CDATA[hello world]]></root>",
          builder.to_xml.gsub(/\n/, ""))
      end

      def test_comment
        builder = Nokogiri::XML::Builder.new do
          root {
            comment "this is a comment"
          }
        end
        assert builder.doc.root.children.first.comment?
      end

      def test_builder_no_block
        string = "hello world"
        builder = Nokogiri::XML::Builder.new
        builder.root {
          cdata string
        }
        assert_equal("<?xml version=\"1.0\"?><root><![CDATA[hello world]]></root>",
          builder.to_xml.gsub(/\n/, ''))
      end

    private

      def namespaces_defined_on(node)
        Hash[*node.namespace_definitions.collect{|n| ["xmlns:" + n.prefix, n.href]}.flatten]
      end
    end
  end
end


text:
local Button = require('cherry.components.button')
local foo = display.newGroup()

describe('[Button]', function()
  it('should prevent a button without any options', function()
    local round = Button:round()
    assert.is.falsy(round)

    local icon = Button:icon()
    assert.is.falsy(icon)
  end)

  it('should instanciate a round button', function()
    local action = spy.new(function() end)
    local button = Button:round({
      parent = foo,
      type   = 'play',
      action = action,
      x      = 100,
      y      = 100
    })

    assert.spy(action).was.called(0)
    assert.are.equal(button.x, 100)
    assert.are.equal(button.y, 100)

    button:touch()
    assert.spy(action).was.called(1)
  end)

  it('should instanciate an icon button', function()
    local action = spy.new(function() end)
    local button = Button:icon({
      parent = foo,
      type   = 'settings',
      action = action,
      x      = 100,
      y      = 100
    })

    assert.spy(action).was.called(0)
    assert.are.equal(button.x, 100)
    assert.are.equal(button.y, 100)

    button:tap()
    assert.spy(action).was.called(1)
  end)

  it('should scale and bouncs icon buttons', function()
    local plop = Button:icon({type = 'play'})
    assert.are.equal(plop.xScale, 1)

    local plup = Button:icon({type = 'play', scale = 2})
    assert.are.equal(plup.xScale, 2)

    local plip = Button:icon({type = 'play', bounce = true})
    assert.are.equal(plip.xScale, 1)

    local ploup = Button:icon({
      type = 'play',
      bounce = true,
      scale = 3
    })

    assert.are.equal(ploup.xScale, 3)
  end)
end)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="4829db54-361b-49bb-9a42-075bb716b476" name="Default" comment="" />
    <ignored path="$PROJECT_DIR$/.tmp/" />
    <ignored path="$PROJECT_DIR$/temp/" />
    <ignored path="$PROJECT_DIR$/tmp/" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="FileEditorManager">
    <leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
      <file leaf-file-name="index.html" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/index.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="387">
              <caret line="125" column="18" lean-forward="true" selection-start-line="125" selection-start-column="18" selection-end-line="125" selection-end-column="18" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="base.css" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/css/base.css">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="221">
              <caret line="46" column="16" lean-forward="true" selection-start-line="46" selection-start-column="16" selection-end-line="46" selection-end-column="16" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="index.css" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/css/index.css">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="350">
              <caret line="314" column="20" lean-forward="false" selection-start-line="314" selection-start-column="20" selection-end-line="314" selection-end-column="20" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="common.js" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/js/common.js">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="0">
              <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="index.js" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/js/index.js">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="0">
              <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="FileTemplateManagerImpl">
    <option name="RECENT_TEMPLATES">
      <list>
        <option value="HTML File" />
        <option value="CSS File" />
        <option value="JavaScript File" />
      </list>
    </option>
  </component>
  <component name="FindInProjectRecents">
    <findStrings>
      <find>jd_cont</find>
      <find>jd_sea</find>
      <find>icon_</find>
      <find>margin-left</find>
      <find>jd_search</find>
      <find>last-</find>
      <find>border-bo</find>
      <find>h</find>
      <find>clearfix</find>
    </findStrings>
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/demo/01流式布局.html" />
        <option value="$PROJECT_DIR$/js/common.js" />
        <option value="$PROJECT_DIR$/js/index.js" />
        <option value="$PROJECT_DIR$/css/base.css" />
        <option value="$PROJECT_DIR$/css/index.css" />
        <option value="$PROJECT_DIR$/index.html" />
      </list>
    </option>
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsFlowSettings">
    <service-enabled>true</service-enabled>
    <exe-path />
    <annotation-enable>false</annotation-enable>
    <other-services-enabled>true</other-services-enabled>
    <auto-save>true</auto-save>
  </component>
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <sorting>DEFINITION_ORDER</sorting>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="385" />
    <option name="y" value="25" />
    <option name="width" value="876" />
    <option name="height" value="705" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="Scratches" />
      <pane id="ProjectPane">
        <subPane>
          <expand>
            <path>
              <item name="jd" type="b2602c69:ProjectViewProjectNode" />
              <item name="jd" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="jd" type="b2602c69:ProjectViewProjectNode" />
              <item name="jd" type="462c0819:PsiDirectoryNode" />
              <item name="css" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="jd" type="b2602c69:ProjectViewProjectNode" />
              <item name="jd" type="462c0819:PsiDirectoryNode" />
              <item name="image" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="jd" type="b2602c69:ProjectViewProjectNode" />
              <item name="jd" type="462c0819:PsiDirectoryNode" />
              <item name="js" type="462c0819:PsiDirectoryNode" />
            </path>
          </expand>
          <select />
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="nodejs_interpreter_path" value="D:/nodejs/node" />
    <property name="settings.editor.selected.configurable" value="editor.preferences.completion" />
    <property name="JavaScriptPreferStrict" value="false" />
    <property name="JavaScriptWeakerCompletionTypeGuess" value="true" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="HbShouldOpenHtmlAsHb" value="" />
    <property name="DefaultHtmlFileTemplate" value="HTML File" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
    <property name="list.type.of.created.stylesheet" value="CSS" />
  </component>
  <component name="RecentsManager">
    <key name="CopyFile.RECENT_KEYS">
      <recent name="D:\GitSource\myresource\play\jd\image" />
    </key>
  </component>
  <component name="RunDashboard">
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="4829db54-361b-49bb-9a42-075bb716b476" name="Default" comment="" />
      <created>1519977323710</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1519977323710</updated>
      <workItem from="1519977326089" duration="780000" />
      <workItem from="1520236595965" duration="23071000" />
    </task>
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="23851000" />
  </component>
  <component name="ToolWindowManager">
    <frame x="385" y="25" width="876" height="705" extended-state="0" />
    <editor active="true" />
    <layout>
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.19866666" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
    </layout>
    <layout-to-restore>
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.19866666" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
    </layout-to-restore>
  </component>
  <component name="TypeScriptGeneratedFilesManager">
    <option name="version" value="1" />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/demo/01流式布局.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/common.js">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/index.js">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/demo/01流式布局.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="102">
          <caret line="6" column="6" lean-forward="true" selection-start-line="6" selection-start-column="6" selection-end-line="6" selection-end-column="6" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/image/search.png">
      <provider selected="true" editor-type-id="images">
        <state />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/image/n1.png">
      <provider selected="true" editor-type-id="images">
        <state />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/base.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="221">
          <caret line="46" column="16" lean-forward="true" selection-start-line="46" selection-start-column="16" selection-end-line="46" selection-end-column="16" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/index.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="350">
          <caret line="314" column="20" lean-forward="false" selection-start-line="314" selection-start-column="20" selection-end-line="314" selection-end-column="20" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="387">
          <caret line="125" column="18" lean-forward="true" selection-start-line="125" selection-start-column="18" selection-end-line="125" selection-end-column="18" />
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
using System;

namespace DeepStreamNet
{
    internal class DisposableAction : IDisposable
    {
        private readonly System.Action _action;

        public DisposableAction(System.Action action)
        {
            _action = action;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _action();
            }
        }
    }
}


text:
import asyncio
import logging
from typing import Optional, TYPE_CHECKING

from azure.core.exceptions import ClientAuthenticationError
from azure.core.credentials import AccessToken
from .._internal import AsyncContextManager
from ... import CredentialUnavailableError
from ..._credentials.chained import _get_error_message
from ..._internal import within_credential_chain

if TYPE_CHECKING:
    from azure.core.credentials_async import AsyncTokenCredential

_LOGGER = logging.getLogger(__name__)

class ChainedTokenCredential(AsyncContextManager):
    """A sequence of credentials that is itself a credential.

    Its :func:`get_token` method calls ``get_token`` on each credential in the sequence, in order, returning the first
    valid token received.

    :param credentials: credential instances to form the chain
    :type credentials: :class:`azure.core.credentials.AsyncTokenCredential`
    """

    def __init__(self, *credentials: "AsyncTokenCredential") -> None:
        if not credentials:
            raise ValueError("at least one credential is required")

        self._successful_credential = None  # type: Optional[AsyncTokenCredential]
        self.credentials = credentials

    async def close(self):
        """Close the transport sessions of all credentials in the chain."""

        await asyncio.gather(*(credential.close() for credential in self.credentials))

    async def get_token(self, *scopes: str, **kwargs) -> AccessToken:
        """Asynchronously request a token from each credential, in order, returning the first token received.

        If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError`
        with an error message from each credential.

        This method is called automatically by Azure SDK clients.

        :param str scopes: desired scopes for the access token. This method requires at least one scope.
        :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token
        """
        within_credential_chain.set(True)
        history = []
        for credential in self.credentials:
            try:
                token = await credential.get_token(*scopes, **kwargs)
                _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__)
                self._successful_credential = credential
                return token
            except CredentialUnavailableError as ex:
                # credential didn't attempt authentication because it lacks required data or state -> continue
                history.append((credential, ex.message))
            except Exception as ex:  # pylint: disable=broad-except
                # credential failed to authenticate, or something unexpectedly raised -> break
                history.append((credential, str(ex)))
                _LOGGER.debug(
                    '%s.get_token failed: %s raised unexpected error "%s"',
                    self.__class__.__name__,
                    credential.__class__.__name__,
                    ex,
                    exc_info=True,
                )
                break

        within_credential_chain.set(False)
        attempts = _get_error_message(history)
        message = self.__class__.__name__ + " failed to retrieve a token from the included credentials." + attempts \
                  + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " \
                    "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot."
        raise ClientAuthenticationError(message=message)


text:
<?php
namespace AlibabaSDK\Aliyun;

use AlibabaSDK\Base\Response;

/**
 * 阿里云api返回结果json解析器:把返回结果当作json解析,并解析为数组
 * @author horseluke
 *
 */
class ResponseJson extends Response
{

    /**
     * 把返回结果当作json解析,并解析为数组
     * @return boolean
     */
    protected function parseResult(){
        $result = json_decode($this->rawResult, true);

        if(!is_array($result)) {
            return $this->setError('PARSE_ERROR_RESPONSE_JSON');
        }

        $this->result = $result;

        $detectError = $this->parseResultErrorByArray();
        if(!empty($detectError)){
            return $this->setError('API_RETURN_ERROR_CODE', $detectError);
        }

        return true;
    }

    /**
     * 解析结果数组是否有错误
     * 仅供特定方法parseResult使用
     * @return string
     */
    protected function parseResultErrorByArray(){
        $errorMsg = '';
        if(!empty($this->result['Code'])){
            $errorMsg = $this->result['Code']. ':'. $this->result['Message']. ':[RequestId '. $this->result['RequestId']. ']:[HostId '. $this->result['HostId']. ']';
        }

        return $errorMsg;
    }

}


text:
namespace Erpiko {

SCENARIO("Construct EnvelopedData") {
  GIVEN("Certificate and private key and data") {
    auto srcCert = DataSource::fromFile("assets/cert.pem");
    auto v = srcCert->readAll();
    std::string pemCert(v.begin(),v.end());
    auto cert = Certificate::fromPem(pemCert);

    auto srcKey = DataSource::fromFile("assets/private.key");
    v = srcKey->readAll();
    std::string pemKey(v.begin(),v.end());
    auto key = RsaKey::fromPem(pemKey);

    auto srcCert1 = DataSource::fromFile("assets/certx1.pem");
    v = srcCert1->readAll();
    std::string pemCert1(v.begin(),v.end());
    auto cert1 = Certificate::fromPem(pemCert1);

    auto srcKey1 = DataSource::fromFile("assets/keyx1.pem");
    v = srcKey1->readAll();
    std::string pemKey1(v.begin(),v.end());
    auto key1 = RsaKey::fromPem(pemKey1);

    auto srcCert2 = DataSource::fromFile("assets/certx2.pem");
    v = srcCert2->readAll();
    std::string pemCert2(v.begin(),v.end());
    auto cert2 = Certificate::fromPem(pemCert2);

    auto srcKey2 = DataSource::fromFile("assets/keyx2.pem");
    v = srcKey2->readAll();
    std::string pemKey2(v.begin(),v.end());
    auto key2 = RsaKey::fromPem(pemKey2);

    auto srcCert3 = DataSource::fromFile("assets/certx3.pem");
    v = srcCert3->readAll();
    std::string pemCert3(v.begin(),v.end());
    auto cert3 = Certificate::fromPem(pemCert3);

    auto srcKey3 = DataSource::fromFile("assets/keyx3.pem");
    v = srcKey3->readAll();
    std::string pemKey3(v.begin(),v.end());
    auto key3 = RsaKey::fromPem(pemKey3);

    DataSource* src = DataSource::fromFile("assets/data.txt");

    THEN("Create the EnvelopedData") {
      REQUIRE_FALSE(src == nullptr);
      auto v = src->readAll();
      EnvelopedData* p7 = new EnvelopedData(*cert, ObjectId("2.16.840.1.101.3.4.1.42"));
      DataSource* data = DataSource::fromFile("assets/data.txt");
      auto dataVector = data->readAll();
      p7->addRecipient(*cert1);
      p7->addRecipient(*cert2);
      p7->addRecipient(*cert3);
      p7->encrypt(dataVector);
      auto der = p7->toDer();
      THEN("And can be decrypted by each recipient") {
        EnvelopedData* p7v = EnvelopedData::fromDer(der);
        auto data = p7v->decrypt(*cert, *key);
        REQUIRE(v == data);
        data.clear();

        EnvelopedData* p7v1 = EnvelopedData::fromDer(der);
        data = p7v1->decrypt(*cert1, *key1);
        REQUIRE(v == data);
        data.clear();

        EnvelopedData* p7v2 = EnvelopedData::fromDer(der);
        data = p7v2->decrypt(*cert2, *key2);
        REQUIRE(v == data);
        data.clear();

        EnvelopedData* p7v3 = EnvelopedData::fromDer(der);
        data = p7v3->decrypt(*cert3, *key3);
        REQUIRE(v == data);
      }
    }
  }
}

// TODO: test for importing data from DER

} //namespace Erpiko


text:
chrome.runtime.onInstalled.addListener(function(details) {
    chrome.storage.sync.set({bool_sound: false});
});

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

// show the popup when the user clicks on the page action.
chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.pageAction.show(tab.id);
});

// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// If the tabs url starts with "http://specificsite.com"...
if (tab.url.indexOf("https://pollev.com/") == 0) {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (~tab.url.indexOf('pollev')) {

    chrome.pageAction.show(tabId);
  }
});

// update the icon when the user's settings change
// chrome.storage.onChanged.addListener(function(changes, areaName){
//     alert("changed settings");
//     console.log("changed settings");
//     if (localStorage["be_a_buzzkill"] == "true"){
//         path = "active-icon.jpeg";
//     } else {
//         path = "inactive-icon.jpeg";
//     }
//     chrome.tabs.getCurrent( function(tab){
//         chrome.pageAction.setIcon({
//             "tabId": tab.id,
//             "path": path
//         });
//     });
// });


text:
package de.matthiasmann.twl;

import de.matthiasmann.twl.model.DefaultTableSelectionModel;
import de.matthiasmann.twl.model.TableSelectionModel;

/**
 * A row selection model manages table selection on a per row base. Cells are
 * never selected by this model.
 *
 * @see #isCellSelected(int, int)
 * @author Matthias Mann
 */
public class TableRowSelectionManager implements TableSelectionManager {

	protected final ActionMap actionMap;
	protected final TableSelectionModel selectionModel;

	protected TableBase tableBase;

	@SuppressWarnings("LeakingThisInConstructor")
	public TableRowSelectionManager(TableSelectionModel selectionModel) {
		if (selectionModel == null) {
			throw new NullPointerException("selectionModel");
		}
		this.selectionModel = selectionModel;
		this.actionMap = new ActionMap();

		actionMap.addMapping(this);
	}

	/**
	 * Creates a row selection model with a multi selection model.
	 *
	 * @see DefaultTableSelectionModel
	 */
	public TableRowSelectionManager() {
		this(new DefaultTableSelectionModel());
	}

	public TableSelectionModel getSelectionModel() {
		return selectionModel;
	}

	public void setAssociatedTable(TableBase base) {
		if (tableBase != base) {
			if (tableBase != null && base != null) {
				throw new IllegalStateException(
						"selection manager still in use");
			}
			this.tableBase = base;
			modelChanged();
		}
	}

	public SelectionGranularity getSelectionGranularity() {
		return SelectionGranularity.ROWS;
	}

	public boolean handleKeyStrokeAction(String action, Event event) {
		return actionMap.invoke(action, event);
	}

	public boolean handleMouseEvent(int row, int column, Event event) {
		boolean isShift = (event.getModifiers() & Event.MODIFIER_SHIFT) != 0;
		boolean isCtrl = (event.getModifiers() & Event.MODIFIER_CTRL) != 0;
		if (event.getType() == Event.Type.MOUSE_BTNDOWN
				&& event.getMouseButton() == Event.MOUSE_LBUTTON) {
			handleMouseDown(row, column, isShift, isCtrl);
			return true;
		}
		if (event.getType() == Event.Type.MOUSE_CLICKED) {
			return handleMouseClick(row, column, isShift, isCtrl);
		}
		return false;
	}

	public boolean isRowSelected(int row) {
		return selectionModel.isSelected(row);
	}

	/**
	 * In a row selection model no cell can be selected. So this method always
	 * returns false
	 *
	 * @param row
	 *            ignored
	 * @param column
	 *            ignored
	 * @return always false
	 */
	public boolean isCellSelected(int row, int column) {
		return false;
	}

	public int getLeadRow() {
		return selectionModel.getLeadIndex();
	}

	public int getLeadColumn() {
		return -1;
	}

	public void modelChanged() {
		selectionModel.clearSelection();
		selectionModel.setAnchorIndex(-1);
		selectionModel.setLeadIndex(-1);
	}

	public void rowsInserted(int index, int count) {
		selectionModel.rowsInserted(index, count);
	}

	public void rowsDeleted(int index, int count) {
		selectionModel.rowsDeleted(index, count);
	}

	public void columnInserted(int index, int count) {
	}

	public void columnsDeleted(int index, int count) {
	}

	@ActionMap.Action
	public void selectNextRow() {
		handleRelativeAction(1, SET);
	}

	@ActionMap.Action
	public void selectPreviousRow() {
		handleRelativeAction(-1, SET);
	}

	@ActionMap.Action
	public void selectNextPage() {
		handleRelativeAction(getPageSize(), SET);
	}

	@ActionMap.Action
	public void selectPreviousPage() {
		handleRelativeAction(-getPageSize(), SET);
	}

	@ActionMap.Action
	public void selectFirstRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleAbsoluteAction(0, SET);
		}
	}

	@ActionMap.Action
	public void selectLastRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleRelativeAction(numRows - 1, SET);
		}
	}

	@ActionMap.Action
	public void extendSelectionToNextRow() {
		handleRelativeAction(1, EXTEND);
	}

	@ActionMap.Action
	public void extendSelectionToPreviousRow() {
		handleRelativeAction(-1, EXTEND);
	}

	@ActionMap.Action
	public void extendSelectionToNextPage() {
		handleRelativeAction(getPageSize(), EXTEND);
	}

	@ActionMap.Action
	public void extendSelectionToPreviousPage() {
		handleRelativeAction(-getPageSize(), EXTEND);
	}

	@ActionMap.Action
	public void extendSelectionToFirstRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleAbsoluteAction(0, EXTEND);
		}
	}

	@ActionMap.Action
	public void extendSelectionToLastRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleRelativeAction(numRows - 1, EXTEND);
		}
	}

	@ActionMap.Action
	public void moveLeadToNextRow() {
		handleRelativeAction(1, MOVE);
	}

	@ActionMap.Action
	public void moveLeadToPreviousRow() {
		handleRelativeAction(-1, MOVE);
	}

	@ActionMap.Action
	public void moveLeadToNextPage() {
		handleRelativeAction(getPageSize(), MOVE);
	}

	@ActionMap.Action
	public void moveLeadToPreviousPage() {
		handleRelativeAction(-getPageSize(), MOVE);
	}

	@ActionMap.Action
	public void moveLeadToFirstRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleAbsoluteAction(0, MOVE);
		}
	}

	@ActionMap.Action
	public void moveLeadToLastRow() {
		int numRows = getNumRows();
		if (numRows > 0) {
			handleAbsoluteAction(numRows - 1, MOVE);
		}
	}

	@ActionMap.Action
	public void toggleSelectionOnLeadRow() {
		int leadIndex = selectionModel.getLeadIndex();
		if (leadIndex > 0) {
			selectionModel.invertSelection(leadIndex, leadIndex);
		}
	}

	@ActionMap.Action
	public void selectAll() {
		int numRows = getNumRows();
		if (numRows > 0) {
			selectionModel.setSelection(0, numRows - 1);
		}
	}

	@ActionMap.Action
	public void selectNone() {
		selectionModel.clearSelection();
	}

	protected static final int TOGGLE = 0;
	protected static final int EXTEND = 1;
	protected static final int SET = 2;
	protected static final int MOVE = 3;

	protected void handleRelativeAction(int delta, int mode) {
		int numRows = getNumRows();
		if (numRows > 0) {
			int leadIndex = Math.max(0, selectionModel.getLeadIndex());
			int index = Math.max(0, Math.min(numRows - 1, leadIndex + delta));

			handleAbsoluteAction(index, mode);
		}
	}

	protected void handleAbsoluteAction(int index, int mode) {
		if (tableBase != null) {
			tableBase.adjustScrollPosition(index);
		}

		switch (mode) {
		case MOVE:
			selectionModel.setLeadIndex(index);
			break;
		case EXTEND:
			int anchorIndex = Math.max(0, selectionModel.getAnchorIndex());
			selectionModel.setSelection(anchorIndex, index);
			break;
		case TOGGLE:
			selectionModel.invertSelection(index, index);
			break;
		default:
			selectionModel.setSelection(index, index);
			break;
		}
	}

	protected void handleMouseDown(int row, int column, boolean isShift,
			boolean isCtrl) {
		if (row < 0 || row >= getNumRows()) {
			if (!isShift) {
				selectionModel.clearSelection();
			}
		} else {
			tableBase.adjustScrollPosition(row);
			int anchorIndex = selectionModel.getAnchorIndex();
			boolean anchorSelected;
			if (anchorIndex == -1) {
				anchorIndex = 0;
				anchorSelected = false;
			} else {
				anchorSelected = selectionModel.isSelected(anchorIndex);
			}

			if (isCtrl) {
				if (isShift) {
					if (anchorSelected) {
						selectionModel.addSelection(anchorIndex, row);
					} else {
						selectionModel.removeSelection(anchorIndex, row);
					}
				} else if (selectionModel.isSelected(row)) {
					selectionModel.removeSelection(row, row);
				} else {
					selectionModel.addSelection(row, row);
				}
			} else if (isShift) {
				selectionModel.setSelection(anchorIndex, row);
			} else {
				selectionModel.setSelection(row, row);
			}
		}
	}

	protected boolean handleMouseClick(int row, int column, boolean isShift,
			boolean isCtrl) {
		return false;
	}

	protected int getNumRows() {
		if (tableBase != null) {
			return tableBase.getNumRows();
		}
		return 0;
	}

	protected int getPageSize() {
		if (tableBase != null) {
			return Math.max(1, tableBase.getNumVisibleRows());
		}
		return 1;
	}
}