text:
export SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )";

export DATE_CONV_SCRIPT="$SCRIPT_DIR/date_conv.js";
rm -f $DATE_CONV_SCRIPT;
echo "#!/usr/bin/env node" > $DATE_CONV_SCRIPT;
echo "var args = process.argv.slice(2);" >> $DATE_CONV_SCRIPT;
echo "var TIMESTAMP = ((args[args.indexOf(\"--timestamp\")] === (\"--timestamp\")) ? args[args.indexOf(\"--timestamp\")+1] : \"\");" >> $DATE_CONV_SCRIPT;
echo "var GUARDIAN = ((args[args.indexOf(\"--guardian\")] === (\"--guardian\")) ? args[args.indexOf(\"--guardian\")+1] : \"\");" >> $DATE_CONV_SCRIPT;
echo "var dateString = (new Date(parseInt(TIMESTAMP))).toISOString().substr(0,19).replace(/:/g,\"-\");" >> $DATE_CONV_SCRIPT;
echo "var s3Path = \"/\"+dateString.substr(0,4)+\"/\"+dateString.substr(5,2)+\"/\"+dateString.substr(8,2)+\"/\"+GUARDIAN+\"/\"+GUARDIAN+\"-\"+dateString;" >> $DATE_CONV_SCRIPT;
echo "console.log(s3Path+'*'+(new Date(parseInt(TIMESTAMP))).toISOString()+'*');" >> $DATE_CONV_SCRIPT;
chmod a+x $DATE_CONV_SCRIPT;

export API_USER=$1;
export API_TOKEN=$2;

export AUDIO_FORMAT=$3;

export GUARDIAN_GUID=$4;
export AUDIO_DIR=$5;

if [[ "$AUDIO_FORMAT" == "flac" ]]; then
  AUDIO_FORMAT_ID="13";
  AUDIO_FORMAT_SAMPLE_RATE="64000";
else
  AUDIO_FORMAT_ID="3";
  AUDIO_FORMAT_SAMPLE_RATE="12000";
fi

export PRE_PREP=`rm -rf $AUDIO_DIR/*.wav; mkdir $AUDIO_DIR/-complete;`;

for AUDIO_FILEPATH in $AUDIO_DIR/*.$AUDIO_FORMAT; do

  export AUDIO_FILENAME=`echo $AUDIO_FILEPATH | rev | cut -d'.' -f 2 | cut -d'/' -f 1 | rev`;
  export AUDIO_EXTENSION=`echo $AUDIO_FILEPATH | rev | cut -d'.' -f 1 | rev`;
  export AUDIO_SHA1=`openssl dgst -sha1 $AUDIO_FILEPATH | grep 'SHA1(' | cut -d'=' -f 2 | cut -d' ' -f 2`;
  export AUDIO_FILESIZE=`ls -l $AUDIO_FILEPATH | cut -d' ' -f 8`;  # -f 8 for OSX, -f 5 for linux

  export AUDIO_CONVERT=`ffmpeg -loglevel panic -i $AUDIO_FILEPATH -ar $AUDIO_FORMAT_SAMPLE_RATE $AUDIO_DIR/$AUDIO_FILENAME.wav`;
  export AUDIO_SAMPLE_COUNT=`soxi -s $AUDIO_DIR/$AUDIO_FILENAME.wav`;
  export AUDIO_WAV_DELETE=`rm -rf $AUDIO_DIR/$AUDIO_FILENAME.wav;`;

  export AUDIO_DATETIME_VALS=`$DATE_CONV_SCRIPT --timestamp $AUDIO_FILENAME --guardian $GUARDIAN_GUID;`;
  export AUDIO_S3_PATH=`echo $AUDIO_DATETIME_VALS | cut -d'*' -f 1`;
  export AUDIO_MEASURED_AT=`echo $AUDIO_DATETIME_VALS | cut -d'*' -f 2`;
  export AUDIO_S3_URL="s3://rfcx-ark/audio$AUDIO_S3_PATH.$AUDIO_EXTENSION";

  export AUDIO_S3_SAVE=`aws s3 cp $AUDIO_FILEPATH $AUDIO_S3_URL --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers;`;

  export CURL_JSON="{ \"format_id\": $AUDIO_FORMAT_ID, \"measured_at\" : \"$AUDIO_MEASURED_AT\", \"size\": $AUDIO_FILESIZE, \"sha1_checksum\": \"$AUDIO_SHA1\", \"capture_sample_count\": $AUDIO_SAMPLE_COUNT }";
  curl -X POST -H "x-auth-user: user/$API_USER" -H "x-auth-token: $API_TOKEN" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d "$CURL_JSON" "https://api.rfcx.org/v1/guardians/$GUARDIAN_GUID/audio";

  export AUDIO_FILE_CLEANUP=`mv $AUDIO_FILEPATH $AUDIO_DIR/-complete/.`;
  echo "$AUDIO_S3_URL — $AUDIO_SHA1 — $AUDIO_FILESIZE — $AUDIO_SAMPLE_COUNT";

done


text:
web-scripts
===========

A collection of scripts to install and manage a Django website on an Ubuntu machine.

redpajama_set_name: RedPajamaGithub


text:
@interface ASPOSESBackgroundEnvelop : JSONModel

@property(nonatomic, strong) NSString<Optional> *Type;
@property(nonatomic, strong) ASPOSEHrefToDocument<Optional> *SelfUri;
@property(nonatomic, strong) NSArray<ASPOSEHrefToDocument, Optional> *AlternateLinks;
@property(nonatomic, strong) NSArray<ASPOSEHrefToDocument, Optional> *Links;

@end


text:
const int TILE_HEIGHT = 16;
const int BLOCK_SIZE = 24;
const int SCALE = 4;
const int MOVE_VAL = BLOCK_SIZE * 0.75;

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RMUD
{
    public partial class CommandFactory
    {
        public static CommandTokenMatcher Sequence(params CommandTokenMatcher[] matchers)
        {
            return new Sequence(matchers);
        }
    }

    public class Sequence : CommandTokenMatcher
    {
        internal List<CommandTokenMatcher> Matchers = new List<CommandTokenMatcher>();

        public Sequence(params CommandTokenMatcher[] matchers)
        {
            Matchers.AddRange(matchers);
        }

        public List<PossibleMatch> Match(PossibleMatch State, MatchContext Context)
        {
            var Matches = new List<PossibleMatch>();
            Matches.Add(State);
            foreach (var Matcher in Matchers)
            {
                var NextMatches = new List<PossibleMatch>();
                foreach (var Match in Matches)
                    NextMatches.AddRange(Matcher.Match(Match, Context));
                Matches = NextMatches;
                if (Matches.Count == 0) return Matches; //Shortcircuit for when no matches are found.
            }
            return Matches;
        }

        public String FindFirstKeyWord()
        {
            foreach (var sub in Matchers)
            {
                var s = sub.FindFirstKeyWord();
                if (!String.IsNullOrEmpty(s)) return s;
            }
            return null;
        }

        public String Emit() { return String.Join(" ", Matchers.Select(m => m.Emit())); }
    }
}


text:
//
//  Test-MBStringFunctions.m
//  MockingbirdTests
//
//  Created by Evan Coyne Maloney on 8/8/14.
//  Copyright (c) 2014 Gilt Groupe. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <XCTest/XCTest.h>

#import "MBStringFunctions.h"

/******************************************************************************/
#pragma mark -
#pragma mark Tests
/******************************************************************************/

@interface MBStringFunctionTests : XCTestCase
@end

@implementation MBStringFunctionTests

- (void) testForceStringFunction
{
    NSString* str = MBForceString(nil);
    XCTAssertNotNil(str, @"MBForceString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBForceString() should always return an NSString instance");
    XCTAssertTrue(str.length == 0, @"MBForceString() should return an empty string with nil input");

    str = MBForceString([NSNull null]);
    XCTAssertNotNil(str, @"MBForceString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBForceString() should always return an NSString instance");
    XCTAssertTrue(str.length == 0, @"MBForceString() should return an empty string with an NSNull as input");

    NSString* inputStr = @"this is my input";
    str = MBForceString(inputStr);
    XCTAssertNotNil(str, @"MBForceString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBForceString() should always return an NSString instance");
    XCTAssertTrue([str isEqualToString:inputStr], @"MBForceString() should return the string provided as input");

    str = MBForceString(@(2.4));
    XCTAssertNotNil(str, @"MBForceString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBForceString() should always return an NSString instance");
    XCTAssertTrue([str isEqualToString:@"2.4"], @"MBForceString() should return the string version of the input provided");
}

- (void) testTrimStringFunction
{
    NSString* str = MBTrimString(nil);
    XCTAssertNotNil(str, @"MBTrimString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBTrimString() should always return an NSString instance");
    XCTAssertTrue(str.length == 0, @"MBTrimString() should return an empty string with nil input");

    str = MBTrimString([NSNull null]);
    XCTAssertNotNil(str, @"MBTrimString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBTrimString() should always return an NSString instance");
    XCTAssertTrue(str.length == 0, @"MBTrimString() should return an empty string with an NSNull as input");

    NSString* testStr = @"   \n   this is my test string. there are many like it but this one is mine\n\n\t\n  ";
    str = MBTrimString(testStr);
    XCTAssertNotNil(str, @"MBTrimString() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBTrimString() should always return an NSString instance");
    XCTAssertTrue([str isEqualToString:@"this is my test string. there are many like it but this one is mine"], @"MBTrimString() should return the trimmed version of the input provided");
}

- (void) testStringifyMacro
{
    NSString* str = MBStringify(NSUTF8StringEncoding);
    XCTAssertNotNil(str, @"MBStringify() should never return nil");
    XCTAssertTrue([str isKindOfClass:[NSString class]], @"MBStringify() should always return an NSString instance");
    XCTAssertTrue([str isEqualToString:@"NSUTF8StringEncoding"], @"MBStringify() should a string version of the input provided");
}

@end


text:
local gen_opts = vim.api.nvim_create_augroup("_general_settings", { clear = true })
vim.api.nvim_create_autocmd(
  "FileType", { group = gen_opts,
  pattern = { "qf", "help", "man", "lspinfo" },
  command = "nnoremap <silent> <buffer> q <Cmd>close<CR>" }
)

vim.api.nvim_create_autocmd(
  "TextYankPost", { group = gen_opts,
  command = "silent!lua require('vim.highlight').on_yank({higroup = 'Search', timeout = 200})" }
)

vim.api.nvim_create_autocmd(
  "FileType", { group = gen_opts,
  pattern = "qf",
  command = "set nobuflisted" }
)

local au_git = vim.api.nvim_create_augroup("_git", { clear = true })
vim.api.nvim_create_autocmd(
  "FileType", { group = au_git,
  pattern = "gitcommit",
  command = "setlocal wrap spell" }
)

local au_mark = vim.api.nvim_create_augroup("_markdown", { clear = true })
vim.api.nvim_create_autocmd(
  "FileType", { group = au_mark,
  pattern = "markdown",
  command = "setlocal wrap spell" }
)

local au_res = vim.api.nvim_create_augroup("_auto_resize", { clear = true })
vim.api.nvim_create_autocmd(
  "VimResized", { group = au_res, command = "tabdo wincmd =" }
)

local aulpha = vim.api.nvim_create_augroup("_alpha", { clear = true })
vim.api.nvim_create_autocmd(
  "User", { group = aulpha, pattern = "AlphaReady",
  command = "set showtabline=0 | autocmd BufUnload <buffer> set showtabline=2"
}
)

-- Autoformat
local au_lsp = vim.api.nvim_create_augroup("_lsp", { clear = true })
vim.api.nvim_create_autocmd(
  "BufWritePre", { group = au_lsp, command = "lua vim.lsp.buf.formatting_sync()" }
)


text:
layout: page
---

A bit about me ...

          I hold a BSc in Genetics (Hons 1) from the University of New South Wales.

          During my honours at the Garvan Institute of Medical Science my project used machine learning to investigate Parkinson's Disease and find preliminary biomarkers.

          I am currently working as a Data Scientist in a health consultancy. Very keen on using machine learning and Shiny wherever and whenever I can.

          See my associated pages and blog for my projects.

{% include JB/setup %}


text:
layout: postag
title: 'VERB'
shortdef: 'verb'
udver: '2'
---

#### Description

Verbs typically inflect for tense and mood. Verbs signal events and actions. Verbs can constitute a minimal predicate in a clause, and govern the number and types of other constituents which may occur in the clause.

Irish is a VSO language, thus the verb comes first.

Irish verbs sometimes inflect for person in the form of synthetic verbs. (e.g. _ithim_ "I eat"; _ithimid_ "we eat")

There are four moods: indicative, imperative, conditional and subjunctive. Tenses include present habitual, simple past, past habitual and future.

There is an autonomous verb form, which most closely correlates to the English passive. However it is not technically a passive form as the subject is "understood" and the nominal argument is an object (e.g. _tugadh an liathróid dó_ "the ball was given to him" (lit. somebody gave the ball to him)).

##### Copula vs substantive verb 'to be'

There are two translations of the English verb `to be' in Irish:

* Copula `is'
* Substantive Verb `bí'

These forms behave very differently syntactically. In UD v2, the copula is tagged as [AUX]().

***substantive bí***
The substantive verb behaves just like normal Irish verbs. It inflects for person, number and tense.
It can never be used for an identity construction with two noun phrases. If it is used for identity, it follows the pattern of Verb NP PP (e.g. _tá sé ina mhúinteoir_ "he is a teacher" (lit. He is in his teacher))
The pattern followed here is: VERB SUBJ PRED

The substantive verb is also used in conjunction with a verbal noun to form  progressive aspectual phrases.
(e.g. _tá sé ag rith_ "he is running" (lit. he is at running)).

#### Examples

* _D'imigh mé_ "I left"
* _D'imíomar_ "We left"
* _Imím_ "I leave"
* _Imímid_ "We leave"
* _Imeoidh mé_ "I will leave"
* _Imeoimid_ "We will leave"
* _Cuirtear an leabhar ar an mbord_ "the book was put on the table"

Source: Studies in Irish Syntax. Nancy Stenson (1981), Tübingen: Gunter Narr Verlag.


text:
package io.druid.indexer.path;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Sets;

import io.druid.java.util.common.granularity.Granularity;
import io.druid.indexer.HadoopDruidIndexerConfig;
import io.druid.indexer.hadoop.FSSpideringIterator;
import io.druid.java.util.common.guava.Comparators;
import io.druid.java.util.common.logger.Logger;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.IOException;
import java.util.Set;
import java.util.regex.Pattern;

/**
 */
public class GranularityPathSpec implements PathSpec
{
  private static final Logger log = new Logger(GranularityPathSpec.class);

  private String inputPath;
  private String filePattern;
  private Granularity dataGranularity;
  private String pathFormat;
  private Class<? extends InputFormat> inputFormat;

  @JsonProperty
  public String getInputPath()
  {
    return inputPath;
  }

  public void setInputPath(String inputPath)
  {
    this.inputPath = inputPath;
  }

  @JsonProperty
  public Class<? extends InputFormat> getInputFormat()
  {
    return inputFormat;
  }

  public void setInputFormat(Class<? extends InputFormat> inputFormat)
  {
    this.inputFormat = inputFormat;
  }

  @JsonProperty
  public String getFilePattern()
  {
    return filePattern;
  }

  public void setFilePattern(String filePattern)
  {
    this.filePattern = filePattern;
  }

  @JsonProperty
  public Granularity getDataGranularity()
  {
    return dataGranularity;
  }

  public void setDataGranularity(Granularity dataGranularity)
  {
    this.dataGranularity = dataGranularity;
  }

  @JsonProperty
  public String getPathFormat()
  {
    return pathFormat;
  }

  public void setPathFormat(String pathFormat)
  {
    this.pathFormat = pathFormat;
  }

  @Override
  public Job addInputPaths(HadoopDruidIndexerConfig config, Job job) throws IOException
  {
    final Set<Interval> intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd());
    for (Interval inputInterval : config.getInputIntervals()) {
      for (Interval interval : dataGranularity.getIterable(inputInterval)) {
        intervals.add(trim(inputInterval, interval));
      }
    }

    Path betaInput = new Path(inputPath);
    FileSystem fs = betaInput.getFileSystem(job.getConfiguration());
    Set<String> paths = Sets.newTreeSet();
    Pattern fileMatcher = Pattern.compile(filePattern);

    DateTimeFormatter customFormatter = null;
    if (pathFormat != null) {
      customFormatter = DateTimeFormat.forPattern(pathFormat);
    }

    for (Interval interval : intervals) {
      DateTime t = interval.getStart();
      String intervalPath;
      if (customFormatter != null) {
        intervalPath = customFormatter.print(t);
      } else {
        intervalPath = dataGranularity.toPath(t);
      }

      Path granularPath = new Path(betaInput, intervalPath);
      log.info("Checking path[%s]", granularPath);
      for (FileStatus status : FSSpideringIterator.spiderIterable(fs, granularPath)) {
        final Path filePath = status.getPath();
        if (fileMatcher.matcher(filePath.toString()).matches()) {
          paths.add(filePath.toString());
        }
      }
    }

    log.info("Appending path %s", paths);
    StaticPathSpec.addToMultipleInputs(config, job, paths, inputFormat);

    return job;
  }

  private Interval trim(Interval inputInterval, Interval interval)
  {
    long start = interval.getStartMillis();
    long end = interval.getEndMillis();

    boolean makeNew = false;
    if (start < inputInterval.getStartMillis()) {
      start = inputInterval.getStartMillis();
      makeNew = true;
    }
    if (end > inputInterval.getEndMillis()) {
      end = inputInterval.getEndMillis();
      makeNew = true;
    }
    return makeNew ? new Interval(start, end) : interval;
  }

}


text:
package com.consid.react;

import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Verticle;

public class Receiver extends Verticle {
    public void start() {
        vertx.eventBus().registerHandler("ping-address", new Handler<Message<JsonObject>>() {
            // @Override
            public void handle(Message<JsonObject> message) {
            // Reply to it
            System.out.println("Received message: " + message.body());
            container.logger().info("Websockets message received: " + message.body());

            final JsonObject replyMessage = new JsonObject();
            replyMessage.putString("results", "ok");
            replyMessage.putString("action", message.body().getString("action"));
            message.reply(replyMessage);
            }
        });
    }
}


text:
'use strict';

// node_modules
var minifyHTML = require('html-minifier').minify;
var _          = require('lodash');

var minify = function(str, options) {
  try {
    return minifyHTML(str, _.extend({
      collapseBooleanAttributes: false,
      collapseWhitespace: true,
      removeAttributeQuotes: false,
      removeCDATASectionsFromCDATA: false,
      removeComments: false,
      removeCommentsFromCDATA: false,
      removeEmptyAttributes: false,
      removeEmptyElements: false,
      removeOptionalTags: false,
      removeRedundantAttributes: false,
      useShortDoctype: false
    }, options));
  } catch (err) {
    console.warn(err);
  }
};

module.exports.register = function(Handlebars, options, params) {
  var opts = options.minify || {};

  Handlebars.registerHelper('minify', function (options) {
    options = _.extend(options, opts, options.hash || {});
    return new Handlebars.SafeString(minify(options.fn(this), options));
  });
};


text:
for (var line = "#"; line.length < 8; line += "#")
console.log(line);


text: AccountBook::Application.config.session_store :cookie_store, key: '_accountBook_session'


text:
package com.haru.push.mqtt.internal;

import com.haru.push.mqtt.MqttException;

import java.io.IOException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 * A network module for connecting over SSL.
 */
public class SSLNetworkModule extends TCPNetworkModule {
	private String[] enabledCiphers;
	private int handshakeTimeoutSecs;

	/**
	 * Constructs a new SSLNetworkModule using the specified host and
	 * port.  The supplied SSLSocketFactory is used to supply the network
	 * socket.
	 */
	public SSLNetworkModule(SSLSocketFactory factory, String host, int port, String resourceContext) {
		super(factory, host, port, resourceContext);
	}

	/**
	 * Returns the enabled cipher suites.
	 */
	public String[] getEnabledCiphers() {
		return enabledCiphers;
	}

	/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
	public void setEnabledCiphers(String[] enabledCiphers) {
		this.enabledCiphers = enabledCiphers;
		if ((socket != null) && (enabledCiphers != null)) {
			((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
		}
	}

	public void setSSLhandshakeTimeout(int timeout) {
		super.setConnectTimeout(timeout);
		this.handshakeTimeoutSecs = timeout;
	}

	public void start() throws IOException, MqttException {
		super.start();
		setEnabledCiphers(enabledCiphers);
		int soTimeout = socket.getSoTimeout();
		if ( soTimeout == 0 ) {
			// RTC 765: Set a timeout to avoid the SSL handshake being blocked indefinitely
			socket.setSoTimeout(this.handshakeTimeoutSecs*1000);
		}
		((SSLSocket)socket).startHandshake();
		// reset timeout to default value
		socket.setSoTimeout(soTimeout);
	}
}


text:
<!DOCTYPE html>

        <title>Hello</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Hi there! it is JSQUAD


text:
$('body').on('dragend', 'li', function(){
$("ul[id$='sortable'").trigger('sortupdate');
});


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h"

#include "base/bind.h"
#include "chromecast/cast_core/runtime/common/cors_exempt_headers.h"
#include "chromecast/renderer/cast_url_loader_throttle_provider.h"
#include "components/cast_streaming/renderer/public/resource_provider.h"
#include "components/cast_streaming/renderer/public/resource_provider_factory.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_media_playback_options.h"
#include "media/base/demuxer.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"

namespace chromecast {

CastRuntimeContentRendererClient::CastRuntimeContentRendererClient() = default;

CastRuntimeContentRendererClient::~CastRuntimeContentRendererClient() = default;

std::unique_ptr<blink::URLLoaderThrottleProvider>
CastRuntimeContentRendererClient::CreateURLLoaderThrottleProvider(
    blink::URLLoaderThrottleProviderType type) {
  return std::make_unique<CastURLLoaderThrottleProvider>(
      type, /*url_filter_manager=*/nullptr, this,
      base::BindRepeating(&IsHeaderCorsExempt));
}

std::unique_ptr<cast_streaming::ResourceProvider>
CastRuntimeContentRendererClient::CreateCastStreamingResourceProvider() {
  return cast_streaming::CreateResourceProvider();
}

}  // namespace chromecast


text:
<!DOCTYPE html>

<title>Canvas test: 2d.gradient.interpolate.vertical</title>
<meta name="author" content="Philip Taylor">

<link rel="stylesheet" href="common/canvas-tests.css">

2d.gradient.interpolate.vertical

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
""" Contains functions to view and interrogate chi-squared minimisation

Attributes:
  MAIN_FONT (dict): style properties for the main font to use in plot labels

"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.colorbar import make_axes_gridspec
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import FixedLocator, ScalarFormatter
import numpy

import echidna.calc.decay as decay

MAIN_FONT = {"size": 22}
BOLD_FONT = {"size": 22, "weight": "bold"}

def chi_squared_vs_signal(signal_config, converter=None, fig_num=1,
                          n_atoms=None, *args, **kwargs):
    """ Plot the chi squared as a function of signal counts

    Args:
      signal_config (:class:`echidna.limit.limit_config.LimitConfig`): Signal
        config class, where chi squareds have been stored.
      converter (:class:`echidna.calc.decay.DBIsotope`, optional): Converter
        used to convert between counts and half-life/effective mass.
      fig_num (int): Fig number. When creating multiple plots in the
        same script, ensures matplotlib doesn't overwrite them.
      n_atoms (float): Number of atoms for converter to use in
        calculations of half life or effective mass.
      *args: Arguments to pass to converter methods.
      **kwargs: Keyword arguments.

    .. note::

      Keyword arguments include:

        * penalty (:class:`echidna.limit.limit_config.LimitConfig`): config
          for signal with penalty term.
        * effective_mass (*bool*): if True, plot the x-axis as the
          signal contribution effective mass.
        * half_life (*bool*): if True, plot the x-axis as the signal
          contribution half life.

    Raises:
      TypeError: If 'half_life' or 'effective_mass' keyword arguments
        are used without :class:`echidna.calc.decay.DBIsotope` object
        to use as converter.
    """
    if (converter is None and
        (kwargs.get("half_life") or kwargs.get("effective_mass"))):
        raise TypeError("converter is None. Cannot use 'half_life' or "
                        "'effective_mass' keywords without converter")

    fig = plt.figure(fig_num, figsize=(10, 10))  # Fig. 1 (axes generated automatically)

    # X axis values
    if kwargs.get("effective_mass"):
        x = numpy.zeros(shape=(signal_config.get_chi_squareds()[2].shape))
        for i_bin, count in enumerate(signal_config.get_chi_squareds()[2]):
            effective_mass = converter.counts_to_eff_mass(count, *args,
                                                          **kwargs)
            x[i_bin] = effective_mass
        plt.xlabel(r"$m_{\beta\beta}$", **BOLD_FONT)
    elif kwargs.get("half_life"):
        x = numpy.zeros(shape=(signal_config.get_chi_squareds()[2].shape))
        for i_bin, count in enumerate(signal_config.get_chi_squareds()[2]):
            x.append(1./converter.counts_to_half_life(count, *args, **kwargs))
        plt.xlabel(r"$1/T_{1/2}^{0\nu}$", **BOLD_FONT)
    else:
        x = signal_config.get_chi_squareds()[2]
        plt.xlabel("Signal counts", **BOLD_FONT)
    # Y axis values
    y_1 = signal_config.get_chi_squareds()[0]
    plt.ylabel(r"$\chi^{2}$", **BOLD_FONT)
    if kwargs.get("penalty") is not None:
        y_2 = kwargs.get("penalty").get_chi_squareds()[0]
        plt.plot(x, y_1, "bo-", label="no systematic uncertainties")
        plt.plot(x, y_2, "ro-", label="systematic uncertainties")  # lines and dots
        plt.legend(loc="upper left")
    else:
        plt.plot(x, y_1, "o-")  # lines and dots

    # Set the tick labels, via Axes instance
    ax = fig.gca()  # Get current Axes instance
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(MAIN_FONT.get("size"))  # Set other properties here e.g. colour, rotation

    if kwargs.get("save_as") is not None:
        plt.savefig(kwargs.get("save_as") + ".png", dpi=400)

    if kwargs.get("show") is not None:
        plt.show()
    return fig

def chi_squared_map(syst_analyser, fig_num=1, **kwargs):
    """ Plot chi squared surface for systematic vs. signal counts

    Args:
      syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic
        analyser object, created during limit setting. Can be used
        during limit setting setting or can load an instance from
        hdf5
      fig_num (int): Fig number. When creating multiple plots in the
        same script, ensures matplotlib doesn't overwrite them.

    .. note::

      Keyword arguments include:

        * contours (*bool*): if True produces a contour plot of chi
          squared surface. Default (*False*).
        * preferred_values (*bool*): if False "preferred values" curve
          is not overlayed on colour map. Default (*True*)
        * minima (*bool*): if False "minima" are not overlayed on
          colour map. Default (*True*)
        * save_as (*string*): supply file name to save image

      Default is to produce a colour map, with "preferred values" curve
      and "minima" overlayed.

    """
    # Set kwargs defaults
    if kwargs.get("preferred_values") is None:
        kwargs["preferred_values"] = True
    if kwargs.get("minima") is None:
        kwargs["minima"] = True

    # Set x and y axes
    x = syst_analyser.get_actual_counts()
    y = syst_analyser.get_syst_values()

    # Set chi squared map values
    data = numpy.average(syst_analyser.get_chi_squareds(), axis=1)
    data = numpy.transpose(data)  # transpose it so that axes are correct

    # Set preferred value values
    y_2 = numpy.average(syst_analyser.get_preferred_values(), axis=1)

    # Set minima values
    x_3 = syst_analyser.get_minima()[0]
    y_3 = syst_analyser.get_minima()[1]

    # Create meshgrid
    X, Y = numpy.meshgrid(x, y)

    # Set sensible levels, pick the desired colormap and define normalization
    color_map = plt.get_cmap('hot_r')

    linear = numpy.linspace(numpy.sqrt(data.min()), numpy.sqrt(data.max()),
                            num=100)
    locator = FixedLocator(linear**2)
    levels = locator.tick_values(data.min(), data.max())
    norm = BoundaryNorm(levels, ncolors=color_map.N)

    if kwargs.get("contours"):
        fig = plt.figure(fig_num, figsize=(16, 10))  # Fig. 2
        fig.text(0.1, 0.9, syst_analyser._name, **BOLD_FONT)
        ax = Axes3D(fig)
        ax.view_init(elev=17.0, azim=-136.0)  # set intial viewing position

        # Plot surface
        surf = ax.plot_surface(X, Y, data, rstride=1, cstride=1,
                               cmap=color_map, norm=norm, linewidth=0,
                               antialiased=False)
        ax.zaxis.set_minor_locator(locator)
        ax.ticklabel_format(style="scientific", scilimits=(3, 4))

        # Set axis labels
        ax.set_xlabel("\nSignal counts", **BOLD_FONT)
        ax.set_ylabel("\nValue of systematic", **BOLD_FONT)
        for label in (ax.get_xticklabels() +
                      ax.get_yticklabels() +
                      ax.get_zticklabels()):
            label.set_fontsize(MAIN_FONT.get("size"))  # tick label size

        ax.dist = 11  # Ensures tick labels are not cut off
        ax.margins(0.05, 0.05, 0.05)  # Adjusts tick margins

        # Draw colorbar
        color_bar = fig.colorbar(surf, ax=ax, orientation="vertical",
                                 fraction=0.2, shrink=0.5, aspect=10)
        # kwargs here control axes that the colorbar is drawn in
        color_bar.set_label(r"$\chi^2$", size=MAIN_FONT.get("size"))
        color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size"))

        plt.show()
        if kwargs.get("save_as") is not None:
            fig.savefig(kwargs.get("save_as") + "_contour.png", dpi=300)
    else:
        fig = plt.figure(fig_num, figsize=(12, 10))  # Fig. 2
        fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT)
        ax = fig.add_subplot(1, 1, 1)

        # Set labels
        ax.set_xlabel("Signal counts", **BOLD_FONT)
        ax.set_ylabel("Value of systematic", **BOLD_FONT)

        # Plot color map
        color_map = ax.pcolormesh(X, Y, data, cmap=color_map, norm=norm)
        color_bar = fig.colorbar(color_map)
        color_bar.set_label("$\chi^2$", size=MAIN_FONT.get("size"))
        color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size"))  # tick label size

        # Set axes limits
        ax.set_xlim([X.min(), X.max()])
        ax.set_ylim([Y.min(), Y.max()])

        if kwargs.get("preferred_values"):
            ax.plot(x, y_2, "bo-", label="Preferred values")
        if kwargs.get("minima"):
            ax.plot(x_3, y_3, "ko", label="Minima")

        # Set axes tick label size
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontsize(MAIN_FONT.get("size"))

        ax.legend(loc="upper left")
        if kwargs.get("save_as") is not None:
            fig.savefig(kwargs.get("save_as") + "_color_map.png", dpi=300)
    return fig

def penalty_vs_systematic(syst_analyser, fig_num=1, **kwargs):
    """ Plot penalty_value vs. systematic

    Args:
      syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic
        analyser object, created during limit setting. Can be used
        during limit setting setting or can load an instance from
        hdf5
      fig_num (int): Fig number. When creating multiple plots in the
        same script, ensures matplotlib doesn't overwrite them.

    .. note::

      Keyword arguments include:

        * save_as (*string*): supply file name to save image
    """
    fig = plt.figure(fig_num, figsize=(9, 7))  # Fig. 3
    fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT)
    ax = fig.add_subplot(1, 1, 1)

    x = syst_analyser._penalty_values[0]
    y = syst_analyser._penalty_values[1]
    plt.xlabel("Value of systematic", **BOLD_FONT)
    plt.ylabel("Value of penalty term", **BOLD_FONT)
    plt.plot(x, y, "bo")

    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(MAIN_FONT.get("size"))  # Set other properties here e.g. colour, rotation

    if kwargs.get("save_as") is not None:
        plt.savefig(kwagrs.get("save_as"))
    return fig

def turn_on(syst_analyser, signal_config, fig=1, **kwargs):
    """ Plot deviation from chi-squared with no floated systematics.

    When does the effect of floating the systematic "turn on"?

    Args:
      syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic
        analyser object, created during limit setting. Can be used
        during limit setting setting or can load an instance from
        hdf5
      signal_config (:class:`echidna.limit.limit_config.LimitConfig`): Signal
        config class, where chi squareds have been stored.
      fig_num (int): Fig number. When creating multiple plots in the
        same script, ensures matplotlib doesn't overwrite them.

    .. note::

      Keyword arguments include:

        * save_as (*string*): supply file name to save image
    """
    # Set x and y axes
    x = syst_analyser.get_actual_counts()
    y = syst_analyser.get_syst_values()

    # Set chi squared map values
    data = numpy.average(syst_analyser.get_chi_squareds(), axis=1)
    data = numpy.transpose(data)  # transpose it so that axes are correct

    # Create meshgrid
    X, Y = numpy.meshgrid(x, y)

    # Define an array of \chi_0 values - chi squared without floating systematics
    chi_squareds = signal_config.get_chi_squareds()[0]
    data_np = numpy.zeros(data.shape)  # zeroed array the same size as data
    for y in range(len(data_np)):
        for x, chi_squared in enumerate(chi_squareds):
            data_np[y][x] = chi_squared
    #if numpy.any((numpy.average(data_np, axis=0) != chi_squareds)):
    #    raise AssertionError("Incorrect chi squareds (no floating) array.")

    # Make an array of the offsets
    offsets = data - data_np

    # Set sensible levels, pick the desired colormap and define normalization
    color_map = plt.get_cmap('coolwarm')

    positives = numpy.linspace(numpy.log10(offsets.max())*-1.,
                               numpy.log10(offsets.max()), num=50)
    # linear array in log space
    if offsets.min() < 0.:
        negatives = numpy.linspace(offsets.min(), 0.0, num=51)
    else:
        negatives = numpy.zeros((51))

    # Add the positive part to the negative part
    full_scale = numpy.append(negatives, numpy.power(10, positives))
    locator = FixedLocator(full_scale)
    levels = locator.tick_values(offsets.min(), offsets.max())
    norm = BoundaryNorm(levels, ncolors=color_map.N)
    fig = plt.figure(fig, figsize=(12, 10))  # Fig. 4
    fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT)
    ax = fig.add_subplot(1, 1, 1)

    # Set labels
    ax.set_xlabel("Signal counts", **BOLD_FONT)
    ax.set_ylabel("Value of systematic", **BOLD_FONT)

    # Plot color map
    color_map = ax.pcolormesh(X, Y, offsets, cmap=color_map, norm=norm)
    color_bar = fig.colorbar(color_map)
    color_bar.set_label("$\chi^2 - \chi_0^2$", size=MAIN_FONT.get("size"))
    color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size"))  # tick label size

    # Set axes limits
    ax.set_xlim([X.min(), X.max()])
    ax.set_ylim([Y.min(), Y.max()])

    # Set axes tick label size
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(MAIN_FONT.get("size"))

    ax.legend(loc="upper left")
    if kwargs.get("save_as") is not None:
        fig.savefig(kwargs.get("save_as") + "_turn_on.png", dpi=300)
    return fig

def push_pull(syst_analyser, fig=1, **kwargs):
    """ Plot penalty value - poisson likelihood chi squared.

    When does minimising chi squared, which wants to "pull" the away
    from the data/prior value dominate and when does the penalty term,
    which wants to "pull" towards the data/prior, constraining the fit
    dominate?

    Args:
      syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic
        analyser object, created during limit setting. Can be used
        during limit setting setting or can load an instance from
        hdf5
      fig_num (int): Fig number. When creating multiple plots in the
        same script, ensures matplotlib doesn't overwrite them.

    .. note::

      Keyword arguments include:

        * save_as (*string*): supply file name to save image
    """
    # Set x and y axes
    x = syst_analyser.get_actual_counts()
    y = syst_analyser.get_syst_values()

    # Set chi squared map values
    data = numpy.average(syst_analyser.get_chi_squareds(), axis=1)
    data = numpy.transpose(data)  # transpose it so that axes are correct

    # Create meshgrid
    X, Y = numpy.meshgrid(x, y)

    # Define an array penalty values
    penalty_values = syst_analyser._penalty_values[1, 0:len(y)]
    penalty_array = numpy.zeros(data.shape)  # zeroed array the same size as data
    for y, penalty_value in enumerate(penalty_values):
        for x in range(len(penalty_array[y])):
            penalty_array[y][x] = penalty_value

    # Define the push pull array penalty term - chi_squared
    # --> push_pull > 0 when penalty_value > chi_squared
    # --> push_pull < 1 when penalty_value < chi_squared
    push_pull = (2.*penalty_array) - data

    # Set sensible levels, pick the desired colormap and define normalization
    color_map = plt.get_cmap('coolwarm')

    if push_pull.min() < 0.:
        negatives = numpy.linspace(push_pull.min(), 0.,
                                   num=50, endpoint=False)
    else:
        negatives = numpy.zeros((50))
    if push_pull.max() > 0.:
        positives = numpy.linspace(0., push_pull.max(), num=51)
    else:
        positives = numpy.zeros((51))

    # Add the pull part to the push part
    full_scale = numpy.append(negatives, positives)
    locator = FixedLocator(full_scale)
    levels = locator.tick_values(push_pull.min(), push_pull.max())
    norm = BoundaryNorm(levels, ncolors=color_map.N)
    fig = plt.figure(fig, figsize=(12, 10))  # Fig. 4
    fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT)
    ax = fig.add_subplot(1, 1, 1)

    # Set labels
    ax.set_xlabel("Signal counts", **BOLD_FONT)
    ax.set_ylabel("Value of systematic", **BOLD_FONT)

    # Plot color map
    color_map = ax.pcolormesh(X, Y, push_pull, cmap=color_map, norm=norm)
    color_bar = fig.colorbar(color_map)
    color_bar.set_label("$s-\chi^{2}_{\lambda,p}$", size=MAIN_FONT.get("size"))
    color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size"))  # tick label size

    # Set axes limits
    ax.set_xlim([X.min(), X.max()])
    ax.set_ylim([Y.min(), Y.max()])

    # Set axes tick label size
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(MAIN_FONT.get("size"))

    ax.legend(loc="upper left")
    if kwargs.get("save_as") is not None:
        fig.savefig(kwargs.get("save_as") + "_push_pull.png", dpi=300)
    return fig

def main(args):
    """ Script to produce chi squared plots for a given systematic.

    .. note:: Produces

      * Plot of chi squared vs. signal counts
      * Plot of systematic vs. signal chi squared surface, either
        contour plot or color map
      * Plot of systematic value vs. penalty term value

    Args:
      args (dict): command line arguments from argparse.

    """
    # Load signal config from hdf5
    signal_config = LimitConfig(0, [0])
    signal_config = store.load_ndarray(args.signal_config, signal_config)
    if args.penalty_config is not None:
        penalty_config = LimitConfig(0, [0])
        penalty_config = store.load_ndarray(args.penalty_config,
                                            penalty_config)
    else:
        penalty_config = None

    # Loaf systematic analyser from hdf5
    syst_analyser = SystAnalyser("", numpy.zeros((1)), numpy.zeros((1)))
    syst_analyser = store.load_ndarray(args.syst_analyser, syst_analyser)

    # Produce plots
    # Currently not possible to produce chi squared vs signal plot with half
    # life or effective mass on x-axis, from outside of limit setting code.
    # Just produce with signal counts on x-axis here.
    fig_1 = chi_squared_vs_signal(signal_config, fig_num=1,
                                  penalty=penalty_config,
                                  save_as=args.image_name)
    fig_2 = penalty_vs_systematic(syst_analyser, 2)
    fig_3 = turn_on(syst_analyser, signal_config, 3, save_as=args.image_name)
    fig_4 = push_pull(syst_analyser, 4, save_as=args.image_name)
    fig_5 = chi_squared_map(syst_analyser, 5,
                            contours=args.contours,
                            save_as=args.image_name)

    plt.show()
    raw_input("RETURN to exit")

if __name__ == "__main__":
    import echidna.output.store as store
    from echidna.limit.limit_config import LimitConfig
    from echidna.limit.limit_setting import SystAnalyser
    from echidna.scripts.zero_nu_limit import ReadableDir

    import argparse

    parser = argparse.ArgumentParser(description="Produce chi squared plots "
                                     "for a systematic")
    parser.add_argument("-s", "--signal_config", action=ReadableDir,
                        help="Supply location of signal config hdf5 file")
    parser.add_argument("-p", "--penalty_config", action=ReadableDir,
                        help="Supply location of signal config with "
                        "penalty term")
    parser.add_argument("-a", "--syst_analyser", action=ReadableDir,
                        help="Supply location of syst analyser hdf5 file")
    parser.add_argument("-i", "--image_name", type=str, default="output",
                        help="Supply an image name")
    parser.add_argument("-c", "--contours", action="store_true",
                        help="If true produces a contour plot, "
                        "defualt is colour map")
    args = parser.parse_args()

    main(args)


text:
package net.signalr.client.hub;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.signalr.client.Connection;
import net.signalr.client.ConnectionAdapter;
import net.signalr.client.json.JsonElement;
import net.signalr.client.json.JsonMapper;
import net.signalr.client.util.concurrent.promise.Compose;
import net.signalr.client.util.concurrent.promise.Deferred;
import net.signalr.client.util.concurrent.promise.Promise;

/**
 * Represents the default hub dispatcher.
 */
final class DefaultHubDispatcher extends ConnectionAdapter implements HubDispatcher {

    /**
     * The private logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultHubDispatcher.class);

    /**
     * The connection.
     */
    private final Connection _connection;

    /**
     * The next callback ID.
     */
    private final AtomicLong _nextCallbackId;

    /**
     * The proxies.
     */
    private final Map<String, DefaultHubProxy> _proxies;

    /**
     * The deferred responses.
     */
    private final Map<String, Deferred<HubResponse>> _responses;

    /**
     * Initializes a new instance of the {@link DefaultHubDispatcher} class.
     *
     * @param connection The connection.
     */
    public DefaultHubDispatcher(final Connection connection) {
        if (connection == null) {
            throw new IllegalArgumentException("Connection must not be null");
        }

        _connection = connection;

        _nextCallbackId = new AtomicLong(0);
        _proxies = new ConcurrentHashMap<>();
        _responses = new ConcurrentHashMap<>();
    }

    /**
     * Updates the connection data.
     *
     * @param newHubName The new hub name.
     */
    private void updateConnectionData(final String newHubName) {
        final HubNames hubNames = new HubNames();

        hubNames.addAll(_proxies.keySet());
        hubNames.add(newHubName);
        final JsonMapper mapper = _connection.getMapper();
        final String connectionData = mapper.toJson(hubNames);

        _connection.setConnectionData(connectionData);
    }

    /**
     * Returns the next callback ID.
     *
     * @return The next callback ID.
     */
    private String nextCallbackId() {
        final long callbackId = _nextCallbackId.incrementAndGet();

        return String.valueOf(callbackId);
    }

    /**
     * Handles a hub response.
     *
     * @param callbackId The callback ID.
     * @param response The hub response.
     */
    private void handleResponse(final String callbackId, final HubResponse response) {
        final Deferred<HubResponse> deferred = _responses.remove(callbackId);

        if (deferred == null) {
            LOGGER.warn("Received response for unknown callback ID {}", callbackId);
            return;
        }
        deferred.setSuccess(response);
    }

    /**
     * Handles hub messages.
     *
     * @param messages The hub messages.
     */
    private void handleMessages(final HubMessage[] messages) {
        for (final HubMessage message : messages) {
            final String hubName = message.getHubName();
            final String lowerCaseHubName = hubName.toLowerCase();
            final DefaultHubProxy proxy = _proxies.get(lowerCaseHubName);

            if (proxy == null) {
                continue;
            }
            proxy.onInvoke(message);
        }
    }

    @Override
    public void onReceived(final String message) {
        final JsonMapper mapper = _connection.getMapper();
        final JsonElement element = mapper.toElement(message);
        final HubResponse response = new HubResponse(element);
        final String callbackId = response.getCallbackId();

        if (callbackId != null) {
            handleResponse(callbackId, response);
        } else {
            final HubMessage[] messages = response.getMessages();

            handleMessages(messages);
        }
    }

    @Override
    public HubProxy newHubProxy(final String hubName) {
        if (hubName == null) {
            throw new IllegalArgumentException("Hub name must not be null");
        }

        final String lowerCaseHubName = hubName.toLowerCase();
        DefaultHubProxy proxy = _proxies.get(lowerCaseHubName);

        if (proxy == null) {
            // Update the connection data before adding the new hub proxy
            // since it could fail when the underlying connection is not disconnected.
            updateConnectionData(hubName);
            proxy = new DefaultHubProxy(hubName, this);
            _proxies.put(lowerCaseHubName, proxy);
        }

        return proxy;
    }

    @Override
    public Promise<HubResponse> invoke(final HubRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("Request must not be null");
        }

        final String callbackId = nextCallbackId();

        request.setCallbackId(callbackId);
        final JsonMapper mapper = _connection.getMapper();
        final String message = mapper.toJson(request);
        final Deferred<HubResponse> deferred = new Deferred<>();

        _responses.put(callbackId, deferred);

        return _connection.send(message).then(new Compose<Void, HubResponse>() {
            @Override
            protected Promise<HubResponse> doCompose(final Void value) throws Exception {
                return deferred;
            }

            @Override
            protected void onFailure(final Throwable cause) throws Exception {
                _responses.remove(callbackId);
            }
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <!--  회의실관리 ID -->
    <bean name="egovMtgPlaceManageIdGnrService" class="egovframework.rte.fdl.idgnr.impl.EgovTableIdGnrServiceImpl" destroy-method="destroy">
        <property name="dataSource" ref="egov.dataSource" />
        <property name="strategy"   ref="mtgPlaceManageIdStrategy" />
        <property name="blockSize"  value="10"/>
        <property name="table"      value="COMTECOPSEQ"/>
        <property name="tableName"  value="MTG_PLACE_ID"/>
    </bean>
    <bean name="mtgPlaceManageIdStrategy" class="egovframework.rte.fdl.idgnr.impl.strategy.EgovIdGnrStrategyImpl">
        <property name="prefix"   value="MTGP_" />
        <property name="cipers"   value="15" />
        <property name="fillChar" value="0" />
    </bean>
    <!-- 회의실관리 ID -->

    <!--  회의실예약 ID -->
    <bean name="egovMtgPlaceResveIdGnrService" class="egovframework.rte.fdl.idgnr.impl.EgovTableIdGnrServiceImpl" destroy-method="destroy">
        <property name="dataSource" ref="egov.dataSource" />
        <property name="strategy"   ref="mtgPlaceResveIdStrategy" />
        <property name="blockSize"  value="10"/>
        <property name="table"      value="COMTECOPSEQ"/>
        <property name="tableName"  value="RESVE_ID"/>
    </bean>
    <bean name="mtgPlaceResveIdStrategy" class="egovframework.rte.fdl.idgnr.impl.strategy.EgovIdGnrStrategyImpl">
        <property name="prefix"   value="RESVE_" />
        <property name="cipers"   value="14" />
        <property name="fillChar" value="0" />
    </bean>
    <!-- 회의실예약 ID -->

</beans>


text:
package thobe.mapview.kernel.mapprovider;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import thobe.mapview.kernel.tilesystem.GeoCoord;

/**
 * {@link MapURLBuilder} implementation (for OpenStreetMaps) that enables to build {@link URL}s for loading static map-images from
 * http://staticmap.openstreetmap.de/staticmap.php.
 * @author Thomas Obenaus
 */
public class OSMStaticMapLite extends OpenStreetMapURLBuilder
{
	public static final String	URLBase	= "http://staticmap.openstreetmap.de/staticmap.php";

	@Override
	public URL buildURL( GeoCoord center, int zoomLevel, int width, int height, MapType mapType ) throws MalformedURLException
	{
		URLQuery query = new URLQuery( );
		query.addParameter( "zoom", zoomLevel );
		query.addParameter( "center", center.toString( ) );
		query.addParameter( "maptype", mapType.toString( ) );
		query.addParameter( "size", width + "x" + height );

		return new URL( URLBase + query );
	}

	@Override
	public MapProvider getProvider( )
	{
		return MapProvider.OSMStaticMapLite;
	}

	@Override
	public URL buildURL( GeoCoord center, int zoomLevel, int width, int height, MapType mapType, List<Marker> markers ) throws MalformedURLException
	{
		URLQuery query = new URLQuery( );
		query.addParameter( "zoom", zoomLevel );
		query.addParameter( "center", center.toString( ) );
		query.addParameter( "maptype", mapType.toString( ) );
		query.addParameter( "size", width + "x" + height );

		if ( !markers.isEmpty( ) )
		{
			String markerStr = "";
			int markersProcessed = 0;
			for ( Marker marker : markers )
			{
				markerStr += "color:" + marker.getColorHex( ) + "%%7Clabel:" + marker.getLabel( ) + "%%7C" + marker.getPosition( );
				markersProcessed++;

				// add separator
				if ( markersProcessed < markers.size( ) )
				{
					markerStr += "%%7C";
				}// if ( markersProcessed < markers.size( ) ).
			}// for ( Marker marker : markers ).
			query.addParameter( "markers", markerStr );
		}//	if ( !markers.isEmpty( ) ).

		return new URL( URLBase + query );
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2014 Evolveum
  ~
  ~ 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.
  -->

<org oid="00000000-8888-6666-0000-100000000001"
	xmlns='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
       xmlns:org='http://midpoint.evolveum.com/xml/ns/public/common/org-3'>
	<name>TOP</name>
	<displayName>Top</displayName>
	<identifier>0000</identifier>
	<orgType>functional</orgType>
</org>


text:
- *Stellae::Gateway* - main access point
- *Stellae::Types::Base* - business objects for interacting with the gateway
- *Stellae::Xml* - namespace responsible for serializing to/from XML

###### Operation contracts
https://webservice.stellae.us/SIIServices_multi/SIIService.svc?wsdl=wsdl0

###### Message transport definitions, including their insane shorthand entity names
https://webservice.stellae.us/SIIServices_multi/SIIService.svc?xsd=xsd0

###### Moar complex types
https://webservice.stellae.us/SIIServices_multi/SIIService.svc?xsd=xsd2

###### These are pretty un-useful, but for completion's sake...
https://webservice.stellae.us/SIIServices_multi/SIIService.svc?xsd=xsd1
https://webservice.stellae.us/SIIServices_multi/SIIService.svc?xsd=xsd3


text:
<?php declare(strict_types=1);

namespace SebastianBergmann\CodeCoverage\Report;

use function date;
use function dirname;
use function file_put_contents;
use function htmlspecialchars;
use function is_string;
use function round;
use DOMDocument;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\WriteOperationFailedException;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\Util\Filesystem;

final class Crap4j
{
    private int $threshold;

    public function __construct(int $threshold = 30)
    {
        $this->threshold = $threshold;
    }

    /**
     * @throws WriteOperationFailedException
     */
    public function process(CodeCoverage $coverage, ?string $target = null, ?string $name = null): string
    {
        $document               = new DOMDocument('1.0', 'UTF-8');
        $document->formatOutput = true;

        $root = $document->createElement('crap_result');
        $document->appendChild($root);

        $project = $document->createElement('project', is_string($name) ? $name : '');
        $root->appendChild($project);
        $root->appendChild($document->createElement('timestamp', date('Y-m-d H:i:s')));

        $stats       = $document->createElement('stats');
        $methodsNode = $document->createElement('methods');

        $report = $coverage->getReport();
        unset($coverage);

        $fullMethodCount     = 0;
        $fullCrapMethodCount = 0;
        $fullCrapLoad        = 0;
        $fullCrap            = 0;

        foreach ($report as $item) {
            $namespace = 'global';

            if (!$item instanceof File) {
                continue;
            }

            $file = $document->createElement('file');
            $file->setAttribute('name', $item->pathAsString());

            $classes = $item->classesAndTraits();

            foreach ($classes as $className => $class) {
                foreach ($class['methods'] as $methodName => $method) {
                    $crapLoad = $this->crapLoad((float) $method['crap'], $method['ccn'], $method['coverage']);

                    $fullCrap += $method['crap'];
                    $fullCrapLoad += $crapLoad;
                    $fullMethodCount++;

                    if ($method['crap'] >= $this->threshold) {
                        $fullCrapMethodCount++;
                    }

                    $methodNode = $document->createElement('method');

                    if (!empty($class['namespace'])) {
                        $namespace = $class['namespace'];
                    }

                    $methodNode->appendChild($document->createElement('package', $namespace));
                    $methodNode->appendChild($document->createElement('className', $className));
                    $methodNode->appendChild($document->createElement('methodName', $methodName));
                    $methodNode->appendChild($document->createElement('methodSignature', htmlspecialchars($method['signature'])));
                    $methodNode->appendChild($document->createElement('fullMethod', htmlspecialchars($method['signature'])));
                    $methodNode->appendChild($document->createElement('crap', (string) $this->roundValue((float) $method['crap'])));
                    $methodNode->appendChild($document->createElement('complexity', (string) $method['ccn']));
                    $methodNode->appendChild($document->createElement('coverage', (string) $this->roundValue($method['coverage'])));
                    $methodNode->appendChild($document->createElement('crapLoad', (string) round($crapLoad)));

                    $methodsNode->appendChild($methodNode);
                }
            }
        }

        $stats->appendChild($document->createElement('name', 'Method Crap Stats'));
        $stats->appendChild($document->createElement('methodCount', (string) $fullMethodCount));
        $stats->appendChild($document->createElement('crapMethodCount', (string) $fullCrapMethodCount));
        $stats->appendChild($document->createElement('crapLoad', (string) round($fullCrapLoad)));
        $stats->appendChild($document->createElement('totalCrap', (string) $fullCrap));

        $crapMethodPercent = 0;

        if ($fullMethodCount > 0) {
            $crapMethodPercent = $this->roundValue((100 * $fullCrapMethodCount) / $fullMethodCount);
        }

        $stats->appendChild($document->createElement('crapMethodPercent', (string) $crapMethodPercent));

        $root->appendChild($stats);
        $root->appendChild($methodsNode);

        $buffer = $document->saveXML();

        if ($target !== null) {
            Filesystem::createDirectory(dirname($target));

            if (@file_put_contents($target, $buffer) === false) {
                throw new WriteOperationFailedException($target);
            }
        }

        return $buffer;
    }

    private function crapLoad(float $crapValue, int $cyclomaticComplexity, float $coveragePercent): float
    {
        $crapLoad = 0;

        if ($crapValue >= $this->threshold) {
            $crapLoad += $cyclomaticComplexity * (1.0 - $coveragePercent / 100);
            $crapLoad += $cyclomaticComplexity / $this->threshold;
        }

        return $crapLoad;
    }

    private function roundValue(float $value): float
    {
        return round($value, 2);
    }
}


text:
/* @LICENSE(MUSLC_MIT) */

#include <netinet/in.h>

const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;


text:
export default class Message extends String {
  constructor(message, bindings) {
    super();

    this.message = message;
    this.bindings = bindings;
  }

  static formatMessage(message, bindings) {
    Object.entries(bindings).forEach(([k, v]) => {
      message = message.replace(new RegExp(`\\{${k}\\}`, 'g'), v);
    });

    return message;
  }

  toString() {
    return Message.formatMessage(this.message, this.bindings);
  }
}


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Smidge.Cache;
using Smidge.CompositeFiles;
using Smidge.FileProcessors;
using Smidge.Hashing;
using Smidge.Models;
using Smidge.Options;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Smidge.Tests")]

namespace Smidge
{

    public static class SmidgeStartup
    {
        //For .net core 3.0, call this before AddControllers/AddControllersWithViews etc
        //If you call it after, then if AddControllersAsServices was used before you need
        //to tell smidge to do so

        public static IServiceCollection AddSmidge(this IServiceCollection services, IConfiguration smidgeConfiguration = null)
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

            services.AddTransient<IConfigureOptions<SmidgeOptions>, SmidgeOptionsSetup>();

            services.AddSingleton<IPreProcessManager, PreProcessManager>();
            services.AddSingleton<IRequestHelper, RequestHelper>();
            services.AddSingleton<IWebsiteInfo, AutoWebsiteInfo>();
            services.AddSingleton<IBundleFileSetGenerator, BundleFileSetGenerator>();
            services.AddSingleton<IHasher, Crc32Hasher>();
            services.AddSingleton<IFileProviderFilter, DefaultFileProviderFilter>();
            services.AddSingleton<IBundleManager, BundleManager>();
            services.AddSingleton<PreProcessPipelineFactory>();
            services.AddSingleton<ISmidgeFileSystem>(p =>
            {
                var hosting = p.GetRequiredService<IWebHostEnvironment>();

                //resolve the ISmidgeFileProvider if there is one
                var provider = p.GetService<ISmidgeFileProvider>() ?? hosting.WebRootFileProvider;
                return new SmidgeFileSystem(
                    provider,
                    p.GetRequiredService<IFileProviderFilter>(),
                    p.GetRequiredService<ICacheFileSystem>(),
                    p.GetRequiredService<IWebsiteInfo>());
            });

            services.AddSingleton<ICacheFileSystem>(p => PhysicalFileCacheFileSystem.CreatePhysicalFileCacheFileSystem(
                p.GetRequiredService<IHasher>(),
                p.GetRequiredService<ISmidgeConfig>(),
                p.GetRequiredService<IHostEnvironment>()));

            services.AddSingleton<ISmidgeConfig>((p) =>
            {
                if (smidgeConfiguration == null)
                {
                    return new SmidgeConfig();
                }
                return new SmidgeConfig(smidgeConfiguration);
            });

            services.AddSingleton<ICacheBuster, ConfigCacheBuster>();
            services.AddSingleton<ICacheBuster, AppDomainLifetimeCacheBuster>();
            services.AddSingleton<ICacheBuster, TimestampCacheBuster>();
            services.AddSingleton<CacheBusterResolver>();

            //These all execute as part of the request/scope
            services.AddScoped<DynamicallyRegisteredWebFiles>();
            services.AddScoped<SmidgeHelper>();
            services.AddScoped<IUrlManager, DefaultUrlManager>();

            //pre-processors
            services.AddSingleton<IPreProcessor, JsMinifier>();
            services.AddSingleton<IPreProcessor, JsSourceMapProcessor>();
            services.AddSingleton<IPreProcessor, CssMinifier>();
            services.AddSingleton<IPreProcessor, CssImportProcessor>();
            services.AddSingleton<IPreProcessor, CssUrlProcessor>();
            services.AddSingleton<Lazy<IEnumerable<IPreProcessor>>>(provider => new Lazy<IEnumerable<IPreProcessor>>(provider.GetRequiredService<IEnumerable<IPreProcessor>>));

            //conventions
            services.AddSingleton<FileProcessingConventions>();
            services.AddSingleton<IFileProcessingConvention, MinifiedFilePathConvention>();

            //Add the controller models as DI services - these get auto created for model binding
            services.AddTransient<BundleRequestModel>();
            services.AddTransient<CompositeFileModel>();

            // NOTE: This wasn't explicitly requred for app previous to .net core 3, however it seems like it should have always been there for
            // previous versions anyways. Seems sort of odd that this ever worked without it?
            var builder = services.AddMvcCore();
            builder.AddApplicationPart(typeof(SmidgeStartup).Assembly);

            return services;
        }

        public static void UseSmidge(this IApplicationBuilder app, Action<IBundleManager> configureBundles = null, bool useEndpointRouting = true)
        {
            //Creates custom routes
            var options = app.ApplicationServices.GetRequiredService<IOptions<SmidgeOptions>>();

            //NOTE: It's no longer polite to just call UseMVC as it enables things that the developer may
            //not need and the dev must disable EndpointRouting - so we let the dev decide.
            //with core 3.0 you have to explicitly disable EndpointRouting se we default to on here
            if (useEndpointRouting)
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                            name: "SmidgeComposite",
                            pattern: options.Value.UrlOptions.CompositeFilePath + "/{file}",
                            defaults: new { controller = "Smidge", action = "Composite" });
                    endpoints.MapControllerRoute(
                            name: "SmidgeBundle",
                            pattern: options.Value.UrlOptions.BundleFilePath + "/{bundle}",
                            defaults: new { controller = "Smidge", action = "Bundle" });
                });

            }
            else
            {

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        "SmidgeComposite",
                        options.Value.UrlOptions.CompositeFilePath + "/{file}",
                        new { controller = "Smidge", action = "Composite" });

                    routes.MapRoute(
                        "SmidgeBundle",
                        options.Value.UrlOptions.BundleFilePath + "/{bundle}",
                        new { controller = "Smidge", action = "Bundle" });
                });
            }

            if (configureBundles != null)
            {
                var bundleManager = app.ApplicationServices.GetRequiredService<IBundleManager>();
                configureBundles(bundleManager);

                var cacheBusterResolver = app.ApplicationServices.GetRequiredService<CacheBusterResolver>();
                var fileSystem = app.ApplicationServices.GetRequiredService<ISmidgeFileSystem>();

                //TODO: Now that they are configured we need to wire up the file watching event handlers
                // to the bundle manager, currently these are on the Bundle, but that is not good enough
                // since we need the bundle name
                foreach (var webFileType in new[] { WebFileType.Css, WebFileType.Js })
                {
                    var bundles = bundleManager.GetBundles(webFileType);
                    foreach (var bundle in bundles)
                    {
                        WireUpFileWatchEventHandlers(cacheBusterResolver, fileSystem, bundle);
                    }
                }
            }
        }

        private static void WireUpFileWatchEventHandlers(CacheBusterResolver cacheBusterResolver, ISmidgeFileSystem fileSystem, Bundle bundle)
        {
            if (bundle.BundleOptions == null) return;

            if (bundle.BundleOptions.DebugOptions.FileWatchOptions.Enabled)
            {
                bundle.BundleOptions.DebugOptions.FileWatchOptions.FileModified += FileWatchOptions_FileModified(cacheBusterResolver, fileSystem, bundle.Name);
            }
            if (bundle.BundleOptions.ProductionOptions.FileWatchOptions.Enabled)
            {
                bundle.BundleOptions.ProductionOptions.FileWatchOptions.FileModified += FileWatchOptions_FileModified(cacheBusterResolver, fileSystem, bundle.Name);
            }
        }

        private static EventHandler<FileWatchEventArgs> FileWatchOptions_FileModified(CacheBusterResolver cacheBusterResolver, ISmidgeFileSystem fileSystem, string bundleName)
        {
            return (sender, args) =>
            {
                FileWatchOptions_FileModified(cacheBusterResolver, fileSystem, bundleName, args);
            };
        }

        //async void = ok here sincew this is an event handler
        private static async void FileWatchOptions_FileModified(CacheBusterResolver cacheBusterResolver, ISmidgeFileSystem fileSystem, string bundleName, FileWatchEventArgs e)
        {
            var bundleOptions = e.File.BundleOptions;
            var cacheBuster = cacheBusterResolver.GetCacheBuster(bundleOptions.GetCacheBusterType());
            var cacheBusterValue = cacheBuster.GetValue();

            //this file is part of this bundle, so the persisted processed/combined/compressed will need to be
            // invalidated/deleted/renamed
            foreach (var compressionType in CompressionType.All)
            {
                await fileSystem.CacheFileSystem.ClearCachedCompositeFileAsync(cacheBusterValue, compressionType, bundleName);
            }
        }
    }
}


text:
@charset "utf-8";
body,h1,h2,h3,h4,h5,h6,hr,p,dl,dt,dd,ul,ol,li,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;}
body,button,input,select,textarea{font:12px/1.5 arial,tahoma,\5b8b\4f53;color:#333;}
h1,h2,h3,h4,h5,h6{font-size:100%;}
em,i{font-style:normal;}
fieldset,img{border:0;}
img{vertical-align:top;}
ul,ol{list-style:none;}
a{color:#2272CB;text-decoration:none;outline:none;}
a:hover{color:#F70;text-decoration:underline;}
.clear{clear:both;display:block;height:0;overflow:hidden;font-size:0;}
button,input,select,textarea{font-size:100%;outline:none}
table{border-collapse:collapse;border-spacing:0;}
body{font:12px/1.5 'Microsoft YaHei';}

/* 弹出框 */
/*pop-box*/
.pop-box{width:800px; height:80%; position:absolute; display:none; z-index:1000;overflow:hidden; -moz-box-shadow:0 0 10px #999; -webkit-box-shadow:0 0 10px #999; -o-box-shadow:0 0 10px #999;box-shadow:0 0 10px #999;background-color:#fff;}
.pop-box .pop-box-bg{position:absolute;left:0;top:0;width:9999px;background:#000;opacity:.4;filter:alpha(opacity=40);z-index:10;}
.pop-box .pop-box-title{position:relative;padding-left:15px;height:40px;background:#f9f9f9;border-bottom:1px solid #eee;font:700 16px/40px 'Microsoft YaHei';line-height:40px;color:#666666;z-index:20;}
.pop-box .pop-box-title .close{position:absolute;top:14px;right:15px;display:block;width:12px;height:12px;background:url(images/icon_editArea.png) no-repeat 0 -113px;overflow:hidden;}
.pop-box .pop-box-title .close:hover{background-position:-15px -113px;}
.pop-box .pop-box-main{position:relative;background:#FFF;z-index:20; padding:15px;}
.pop-scroll .pop-box-main{overflow:hidden;overflow-y:scroll;}

#cover{position:fixed;left:0;top:0;z-index:999;filter:alpha(opacity=0);opacity:0.4;display:block;background-color:#666;}

/* 分页 */
/*pages*/
.s-pages{padding:10px 0;height:24px;color:#666;overflow:hidden; font-family:Arial, Helvetica, sans-serif;}
.s-pages .pages{float:right;height:24px;overflow:hidden;}
.s-pages a{float:left;margin-right:5px;padding:0 8px;background:#FFF;border:1px solid #d7d7d7;line-height:22px;color:#666;}
.s-pages a:hover{color:#F70;text-decoration:none;}
.s-pages span{float:left;margin-right:5px;line-height:22px;font-weight:700;}
.s-pages span.prev,
.s-pages span.next{height:22px;line-height:22px;background:#FFF;border:1px solid #d7d7d7;font-weight:400;}
.s-pages a.prev,
.s-pages a.next{height:22px;line-height:22px;background:#FFF;border:1px solid #d7d7d7;overflow:hidden;}
.s-pages span.prev em,
.s-pages span.next em,
.s-pages a.prev em,
.s-pages a.next em{float:left;display:inline;margin-top:6px;width:0;height:0;line-height:0;font-size:0;border:5px solid;}
.s-pages span.prev i,
.s-pages span.next i{float:left;color:#999;}
.s-pages a.prev i,
.s-pages a.next i{float:left;color:#333;font-weight:400;*line-height:24px;cursor:pointer;}
.s-pages a.prev:hover i,
.s-pages a.next:hover i{color:#F70;}
.s-pages span.prev{padding:0 10px 0 0;}
.s-pages span.next{padding:0 0 0 10px;}
.s-pages span.prev em{margin-right:6px;border-color:#FFF #CCC #FFF #FFF;}
.s-pages a.prev em{margin-right:6px;border-color:#FFF #333 #FFF #FFF;}
.s-pages span.next em{margin-left:6px;border-color:#FFF #FFF #FFF #CCC;}
.s-pages a.next em{margin-left:6px;border-color:#FFF #FFF #FFF #333;}
.s-pages b{float:left;padding:0 8px; margin-right:4px; color:#ff6600; line-height:22px; border:1px solid #d7d7d7;}
.s-pages .page-inp{float:left;display:inline;margin-left:25px;}
.s-pages .page-inp span{margin-right:5px;color:#333;font-weight:400;}
.s-pages .page-inp .inp{float:left;margin-right:5px;padding:2px 5px;width:26px;height:18px;background:#FFF;border:1px solid #CCC;font-weight:700;color:#666;text-align:center;}
.s-pages .page-inp .submit{float:left;width:46px;height:24px;background:#FFF;border:1px solid #CCC;line-height:22px;*line-height:20px;color:#333;text-align:center;cursor:pointer;}
.s-pages .page-inp .submit:hover{color:#F70;text-decoration:none;}
/* 输入框 */
.sText{float:left;padding-right:10px;}
.sText input{float:left;height:18px;background:#FFF;border:1px solid #BFBFBF;}
.sText .err{border-color:#F00;}
.sText .focus{border-color:#37C;}
.sText-h26{height:26px;}
.sText-h26 input{padding:3px 5px;}
.sText-h30{height:30px;}
.sText-h30 input{padding:5px;}
.sText-h32{height:32px;}
.sText-h32 input{padding:6px 5px;}
.sTxt{float:left;margin-right:10px;}
.sTxt textarea{padding:0 5px;background:#FFF;border:1px solid #BFBFBF;resize:none;}
.sTxt .err{border-color:#F00;}
.sTxt .focus{border-color:#37C;}
.sSelect{float:left;margin-right:10px;background:#FFF;border:1px solid #BFBFBF;}
.sSelect-h26{padding:3px 2px;height:26px;*height:auto;}
.sSelect-h30{padding:5px 2px;height:30px;*height:auto;}

.l{float:left;}
.r{float:right;}
.hide{display:none;}


text:
# BS mark.1-55
# /* coding: utf-8 */

#  BlackSmith plugin
#  remote_ctrl_plugin.py

# Coded by: WitcherGeralt (WitcherGeralt@jabber.ru)
# http://witcher-team.ucoz.ru/

def handler_remote_control(type, source, body):
	confs = GROUPCHATS.keys()
	confs.sort()
	if body:
		args = body.split()
		if len(args) >= 3:
			item = args[0].strip().lower()
			if item in confs:
				conf = item
			elif check_number(item):
				number = int(item) - 1
				if number >= 0 and number <= len(confs):
					conf = confs[number]
				else:
					conf = False
			else:
				conf = False
			if conf:
				mtype = args[1].strip().lower()
				if mtype == u'чат':
					msgtype = 'public'
				elif mtype == u'приват':
					msgtype = 'private'
				else:
					msgtype = False
				if msgtype:
					command = args[2].strip().lower()
					if len(args) >= 4:
						Parameters = body[((body.lower()).find(command) + (len(command) + 1)):].strip()
					else:
						Parameters = ''
					if len(Parameters) <= 96:
						if COMMANDS.has_key(command):
							call_command_handlers(command, msgtype, [source[0], conf, source[2]], Parameters, command)
						else:
							reply(type, source, u'нет такой команды')
					else:
						reply(type, source, u'слишком длинные параметры')
				else:
					reply(type, source, u'тип указан не корректно')
			else:
				reply(type, source, u'нет такой конференции')
		else:
			reply(type, source, u'инвалид синтакс')
	else:
		col, list = 0, ''
		for conf in confs:
			col = col + 1
			list += u'\n№ '+str(col)+'. - '+conf
		reply(type, source, list)

command_handler(handler_remote_control, 100, "remote-ctrl")


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 |  The MIT License (MIT)
 |
 |  Copyright (c) 2016 Bounteous.
 |
 |  Permission is hereby granted, free of charge, to any person obtaining a copy
 |  of this software and associated documentation files (the "Software"), to deal
 |  in the Software without restriction, including without limitation the rights
 |  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 |  copies of the Software, and to permit persons to whom the Software is
 |  furnished to do so, subject to the following conditions:
 |
 |  The above copyright notice and this permission notice shall be included in all
 |  copies or substantial portions of the Software.
 |
 |  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 |  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 |  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 |  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 |  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 |  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 |  SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- ====================================================================== -->
    <!-- P A R E N T  P R O J E C T  D E S C R I P T I O N                      -->
    <!-- ====================================================================== -->
    <parent>
        <groupId>com.hs2solutions.aem</groupId>
        <artifactId>hotfix-msm-lockable-deep-properties</artifactId>
        <version>1.0.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <!-- ====================================================================== -->
    <!-- P R O J E C T  D E S C R I P T I O N                                   -->
    <!-- ====================================================================== -->
    <artifactId>hotfix-msm-lockable-deep-properties.ui.apps</artifactId>
    <packaging>content-package</packaging>
    <name>Bounteous Hotfix for MSM Inheritance Breaking for Deep Properties - UI apps</name>
    <description>Bounteous Hotfix for MSM Inheritance Breaking for Deep Properties</description>

    <!-- <scm>
        <connection></connection>
        <developerConnection></developerConnection>
        <url></url>
        <tag>HEAD</tag>
    </scm-->

    <!-- ====================================================================== -->
    <!-- B U I L D   D E F I N I T I O N                                        -->
    <!-- ====================================================================== -->
    <build>
        <resources>
            <!-- define the resources that will go into the package -->
            <resource>
                <!--
                    we want to keep some of the META-INF files and not configure
                    everything in the plugin.
                -->
                <directory>${basedir}/src/main/content/META-INF</directory>
                <targetPath>../vault-work/META-INF</targetPath>
            </resource>
            <resource>
                <directory>${basedir}/src/main/content/jcr_root</directory>
                <excludes>
                    <!-- exclude .vlt control files in the package -->
                    <exclude>**/.vlt</exclude>
                    <exclude>**/.vltignore</exclude>
                    <exclude>**/.gitignore</exclude>
                    <exclude>**/*.iml</exclude>
                    <exclude>**/.classpath</exclude>
                    <exclude>**/.project</exclude>
                    <exclude>**/.settings</exclude>
                    <exclude>**/.DS_Store</exclude>
                    <exclude>**/target/**</exclude>
                    <exclude>**/pom.xml</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <!--
                we want to keep some of the META-INF files and not configure
                everything in the plugin (mainly the filters).

                copy the resource explicitly instead of attaching it to the default resources
            -->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <!-- ensure that the empty directories are copied -->
                <configuration>
                    <includeEmptyDirs>true</includeEmptyDirs>
                </configuration>

                <executions>
                    <execution>
                        <id>copy-metainf-vault-resources</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/vault-work/META-INF</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${basedir}/META-INF</directory>
                                    <filtering>false</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <!-- ====================================================================== -->
            <!-- V A U L T   P A C K A G E   P L U G I N                                -->
            <!-- ====================================================================== -->
            <plugin>
                <groupId>com.day.jcr.vault</groupId>
                <artifactId>content-package-maven-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <filterSource>${basedir}/META-INF/vault/filter.xml</filterSource>
                    <verbose>true</verbose>
                    <failOnError>true</failOnError>
                    <group>hs2solutions/consulting</group>
                    <embeddeds>
                        <embedded>
                            <groupId>com.hs2solutions.aem</groupId>
                            <artifactId>hotfix-msm-lockable-deep-properties.core</artifactId>
                            <target>/apps/hs2solutions/hotfix-msm-lockable-deep-properties/install</target>
                        </embedded>
                    </embeddeds>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <!-- ====================================================================== -->
    <!-- P R O F I L E S                                                        -->
    <!-- ====================================================================== -->
    <profiles>
        <profile>
            <id>autoInstallPackage</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.day.jcr.vault</groupId>
                        <artifactId>content-package-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-package</id>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <targetURL>http://${aem.host}:${aem.port}/crx/packmgr/service.jsp</targetURL>
                            <failOnError>true</failOnError>
                            <failOnMissingEmbed>true</failOnMissingEmbed>
                        </configuration>
                     </plugin>
                 </plugins>
            </build>
        </profile>
        <profile>
            <id>autoInstallPackagePublish</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.day.jcr.vault</groupId>
                        <artifactId>content-package-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-package</id>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <targetURL>http://${aem.publish.host}:${aem.publish.port}/crx/packmgr/service.jsp</targetURL>
                            <failOnError>true</failOnError>
                            <failOnMissingEmbed>true</failOnMissingEmbed>
                        </configuration>
                     </plugin>
                 </plugins>
            </build>
        </profile>
    </profiles>

    <!-- ====================================================================== -->
    <!-- D E P E N D E N C I E S                                                -->
    <!-- ====================================================================== -->
    <dependencies>
        <dependency>
            <groupId>com.hs2solutions.aem</groupId>
            <artifactId>hotfix-msm-lockable-deep-properties.core</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.adobe.aem</groupId>
            <artifactId>aem-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.jcr</groupId>
            <artifactId>jcr</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </dependency>

        <dependency>
            <groupId>com.day.cq.wcm</groupId>
            <artifactId>cq-wcm-taglib</artifactId>
        </dependency>
    </dependencies>
</project>


text:
<title>Ogre::EdgeData::Edge Struct Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

EdgeData

Edge

Public Attributes

Ogre::EdgeData::Edge Struct Reference

Edge data.
 More...

#include <OgreEdgeListBuilder.h>

List of all members.

Public Attributes

size_t 	triIndex [2]

 	The indexes of the 2 tris attached, note that tri 0 is the one where the indexes run _anti_ clockwise along the edge.

size_t 	vertIndex [2]

 	The vertex indices for this edge.

size_t 	sharedVertIndex [2]

 	Vertex indices as used in the shared vertex list, not exposed.

bool 	degenerate

 	Indicates if this is a degenerate edge, ie it does not have 2 triangles.

Detailed Description

Edge data.

Definition at line 68 of file OgreEdgeListBuilder.h.

Member Data Documentation

          bool Ogre::EdgeData::Edge::degenerate

Indicates if this is a degenerate edge, ie it does not have 2 triangles.

Definition at line 79 of file OgreEdgeListBuilder.h.

          size_t Ogre::EdgeData::Edge::sharedVertIndex[2]

Vertex indices as used in the shared vertex list, not exposed.

Definition at line 77 of file OgreEdgeListBuilder.h.

          size_t Ogre::EdgeData::Edge::triIndex[2]

The indexes of the 2 tris attached, note that tri 0 is the one where the indexes run _anti_ clockwise along the edge.

Indexes must be reversed for tri 1.

Definition at line 72 of file OgreEdgeListBuilder.h.

          size_t Ogre::EdgeData::Edge::vertIndex[2]

The vertex indices for this edge.

Note that both vertices will be in the vertex set as specified in 'vertexSet', which will also be the same as tri 0

Definition at line 75 of file OgreEdgeListBuilder.h.

The documentation for this struct was generated from the following file:

OgreEdgeListBuilder.h

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 2012 07:27:27


text:
<tr-book-list-element
  *ngFor="let book of books"
  [book]="book"
  (rate)="sort($event)">
</tr-book-list-element>


text:
	#define ATTRIBUTE_TLS static __thread
#elif defined (_MSC_VER)
	#define ATTRIBUTE_TLS static __declspec(thread)
#else
	#error "Unknown thread local storage qualifier"
#endif

static unsigned int GetRandomSeed()
{
	ATTRIBUTE_TLS bool SeedCounterInitialized = 0;
	ATTRIBUTE_TLS unsigned int SeedCounter = 0;

	if (!SeedCounterInitialized)
	{
		std::random_device rd;
		std::uniform_int_distribution<unsigned int> dist;
		SeedCounter = dist(rd);
		SeedCounterInitialized = true;
	}
	return ++SeedCounter;
}

////////////////////////////////////////////////////////////////////////////////
// cFastRandom:

#if 0 && defined(_DEBUG)
// Self-test
// Both ints and floats are quick-tested to see if the random is calculated correctly, checking the range in ASSERTs,
// and if it performs well in terms of distribution (checked by avg, expected to be in the range midpoint
class cFastRandomTest
{
public:
	cFastRandomTest(void)
	{
		TestInts();
		TestFloats();
	}

	void TestInts(void)
	{
		printf("Testing ints...\n");
		cFastRandom rnd;
		int sum = 0;
		const int BUCKETS = 8;
		int Counts[BUCKETS];
		memset(Counts, 0, sizeof(Counts));
		const int ITER = 10000;
		for (int i = 0; i < ITER; i++)
		{
			int v = rnd.NextInt(1000);
			ASSERT(v >= 0);
			ASSERT(v < 1000);
			Counts[v % BUCKETS]++;
			sum += v;
		}
		double avg = (double)sum / ITER;
		printf("avg: %f\n", avg);
		for (int i = 0; i < BUCKETS; i++)
		{
			printf("  bucket %d: %d\n", i, Counts[i]);
		}
	}

	void TestFloats(void)
	{
		printf("Testing floats...\n");
		cFastRandom rnd;
		float sum = 0;
		const int BUCKETS = 8;
		int Counts[BUCKETS];
		memset(Counts, 0, sizeof(Counts));
		const int ITER = 10000;
		for (int i = 0; i < ITER; i++)
		{
			float v = rnd.NextFloat(1000);
			ASSERT(v >= 0);
			ASSERT(v <= 1000);
			Counts[((int)v) % BUCKETS]++;
			sum += v;
		}
		sum = sum / ITER;
		printf("avg: %f\n", sum);
		for (int i = 0; i < BUCKETS; i++)
		{
			printf("  bucket %d: %d\n", i, Counts[i]);
		}
	}
} g_Test;

#endif

cFastRandom::cFastRandom(void) :
	m_LinearRand(GetRandomSeed())
{
}

int cFastRandom::NextInt(int a_Range)
{
	std::uniform_int_distribution<> distribution(0, a_Range - 1);
	return distribution(m_LinearRand);
}

float cFastRandom::NextFloat(float a_Range)
{
	std::uniform_real_distribution<float> distribution(0, a_Range);
	return distribution(m_LinearRand);
}

int cFastRandom::GenerateRandomInteger(int a_Begin, int a_End)
{
	std::uniform_int_distribution<> distribution(a_Begin, a_End);
	return distribution(m_LinearRand);
}

////////////////////////////////////////////////////////////////////////////////
// MTRand:

MTRand::MTRand() :
	m_MersenneRand(GetRandomSeed())
{
}

int MTRand::randInt(int a_Range)
{
	std::uniform_int_distribution<> distribution(0, a_Range);
	return distribution(m_MersenneRand);
}

int MTRand::randInt()
{
	std::uniform_int_distribution<> distribution(0, std::numeric_limits<int>::max());
	return distribution(m_MersenneRand);
}

double MTRand::rand(double a_Range)
{
	std::uniform_real_distribution<> distribution(0, a_Range);
	return distribution(m_MersenneRand);
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleLabel.cs">
//   Copyright (c) by respective owners including Yahoo!, Microsoft, and
//   individual contributors. All rights reserved.  Released under a BSD
//   license as described in the file LICENSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using VW.Interfaces;
using System.Globalization;
using System.Text;

namespace VW.Labels
{
    /// <summary>
    /// Helper to ease construction of simple label.
    /// </summary>
    public sealed class SimpleLabel : ILabel
    {
        /// <summary>
        /// Gets or sets the float label.
        /// </summary>
        public float Label { get; set; }

        /// <summary>
        /// Gets or sets the optional weight.
        /// </summary>
        public float? Weight { get; set; }

        /// <summary>
        /// Gets or sets the optional initial value.
        /// </summary>
        public float? Initial { get; set; }

        /// <summary>
        /// Serialize to Vowpal Wabbit string format.
        /// </summary>
        /// <remarks>see simple_label.cc: parse_simple_label</remarks>
        public string ToVowpalWabbitFormat()
        {
            // Note: this code was inspected closely as it is on the hot performance path.
            if (Weight == null)
            {
                return this.Label.ToString(CultureInfo.InvariantCulture);
            }

            var sb = new StringBuilder();
            sb.Append(this.Label.ToString(CultureInfo.InvariantCulture));
            sb.Append(' ');
            sb.Append(this.Weight.Value.ToString(CultureInfo.InvariantCulture));

            if (Initial != null)
            {
                sb.Append(' ');
                sb.Append(this.Initial.Value.ToString(CultureInfo.InvariantCulture));
            }
            return sb.ToString();
        }
    }
}


text:
using System;
using Robust.Shared.Serialization;

namespace Content.Shared.GameObjects.Components.Atmos
{
    [Serializable, NetSerializable]
    public enum PumpVisuals
    {
        VisualState
    }

    [Serializable, NetSerializable]
    public class PumpVisualState
    {
        public readonly PipeDirection InletDirection;
        public readonly PipeDirection OutletDirection;
        public readonly ConduitLayer InletConduitLayer;
        public readonly ConduitLayer OutletConduitLayer;
        public readonly bool PumpEnabled;

        public PumpVisualState(PipeDirection inletDirection, PipeDirection outletDirection, ConduitLayer inletConduitLayer, ConduitLayer outletConduitLayer, bool pumpEnabled)
        {
            InletDirection = inletDirection;
            OutletDirection = outletDirection;
            InletConduitLayer = inletConduitLayer;
            OutletConduitLayer = outletConduitLayer;
            PumpEnabled = pumpEnabled;
        }
    }
}


text:
import expect from 'expect.js';
import Common from 'common/TravelhubApiSDKCommon.js';

describe('TravelHubApiSDKCommon', function () {
  it('should be a class (function)', function () {
    expect(Common).to.be.a('function');
  });

  beforeEach(function () {
    this.responseSuccess = {
      headers: {
        'x-correlation-id': 'X-Correlation-Id',
      },
      statusCode: 200,
      body: {},
    };
  });

  describe('functions', function () {
    describe('parseResponse', function () {
      it('should be a function', function () {
        expect(Common.parseResponse).to.be.a('function');
      });

      it('should parse a success response', function () {
        return Common.parseResponse(this.responseSuccess)
          .then((parsedResponse) => {
            expect(parsedResponse).to.be.eql({
              headers: {
                'x-correlation-id': 'X-Correlation-Id',
              },
              correlationId: 'X-Correlation-Id',
              statusCode: 200,
              content: {},
            });
          });
      });

      it('should parse a success response without body', function () {
        const responseWithoutBody = {};

        Object.assign(responseWithoutBody, this.responseSuccess);

        delete responseWithoutBody.body;

        responseWithoutBody.statusCode = 204;

        return Common.parseResponse(responseWithoutBody)
          .then((parsedResponse) => {
            expect(parsedResponse).to.be.eql({
              headers: {
                'x-correlation-id': 'X-Correlation-Id',
              },
              correlationId: 'X-Correlation-Id',
              statusCode: 204,
              content: undefined,
            });
          });
      });
    });
  });
});


text:
from PyQt5.QtCore import QSize, QRectF, Qt
from PyQt5.QtGui import QPainter, QFontMetrics, QFont
from PyQt5.QtWidgets import *

from GUI.init import gui_scale, get_stylesheet

__author__ = 'magnus'

class RibbonButton(QToolButton):
	def __init__(self, owner, action, is_large):
		QPushButton.__init__(self, owner)
		# sc = 1
		sc = gui_scale()
		self.text = action.text()
		self._action = action
		self.textWidth = 50;

		self.clicked.connect(self._action.trigger)
		self._action.changed.connect(self.update_button_status_from_action)
		self.font = QFont()
		self.font.setPointSizeF(10*sc)
		fm = QFontMetrics(QFont())
		for t in self.text.split("\n"):
			self.textWidth = max(self.textWidth, fm.width(t)+10)

		if is_large:
			self.setStyleSheet(get_stylesheet("ribbonButton"))
			self.setToolButtonStyle(3)
			self.setIconSize(QSize(32 * sc, 32 * sc))
			self.setMaximumWidth(90 * sc)
			self.setMinimumWidth(50 * sc)
			self.setMinimumHeight(80 * sc)
			self.setMaximumHeight(95 * sc)
		else:
			self.setToolButtonStyle(2)
			self.setMaximumWidth(120 * sc)
			self.setIconSize(QSize(16 * sc, 16 * sc))
			self.setStyleSheet(get_stylesheet("ribbonSmallButton"))

		self.update_button_status_from_action()

	def paintEvent(self, event):
		if self.toolButtonStyle() == 3:
			qp = QPainter()
			qp.begin(self)
			qp.setFont(self.font)
			qp.drawText(QRectF(0, 32, self.textWidth,60), Qt.AlignHCenter | Qt.AlignVCenter, self.text)
			qp.end()

		return super(RibbonButton, self).paintEvent(event)

	def sizeHint(self):
		return QSize(self.textWidth, 85*gui_scale())

	def update_button_status_from_action(self):
		if self.toolButtonStyle() == 3:
			pass
		else:
			self.setText(self._action.text())
		self.setStatusTip(self._action.statusTip())
		self.setToolTip(self._action.toolTip())
		self.setIcon(self._action.icon())
		self.setEnabled(self._action.isEnabled())
		self.setCheckable(self._action.isCheckable())
		self.setChecked(self._action.isChecked())