text:
"""
Splits a PDB file into several, each containing one MODEL.

Usage:
    python pdb_splitmodel.py <pdb file>

Example:
    python pdb_splitmodel.py 1CTF.pdb

This program is part of the `pdb-tools` suite of utilities and should not be
distributed isolatedly. The `pdb-tools` were created to quickly manipulate PDB
files using the terminal, and can be used sequentially, with one tool streaming
data to another. They are based on old FORTRAN77 code that was taking too much
effort to maintain and compile. RIP.
"""

import os
import sys

__author__ = "Joao Rodrigues"
__email__ = "j.p.g.l.m.rodrigues@gmail.com"

USAGE = __doc__.format(__author__, __email__)

def check_input(args):
    """Checks whether to read from stdin/file and validates user input/options.
    """

    # Defaults
    fh = sys.stdin  # file handle

    if not len(args):
        # Reading from pipe with default option
        if sys.stdin.isatty():
            sys.stderr.write(__doc__)
            sys.exit(1)

    elif len(args) == 1:
        if not os.path.isfile(args[0]):
            emsg = 'ERROR!! File not found or not readable: \'{}\'\n'
            sys.stderr.write(emsg.format(args[0]))
            sys.stderr.write(__doc__)
            sys.exit(1)

        fh = open(args[0], 'r')

    else:  # Whatever ...
        emsg = 'ERROR!! Script takes 1 argument, not \'{}\'\n'
        sys.stderr.write(emsg.format(len(args)))
        sys.stderr.write(__doc__)
        sys.exit(1)

    return fh

def run(fhandle, outname=None):
    """
    Split PDB into MODELS.

    Each MODELS is saved to a different file. Non-records lines are
    ignored.

    Parameters
    ----------
    fhandle : a line-by-line iterator of the original PDB file.

    outname : str
        The base name of the output files. If None is given, tries to
        extract a name from the `.name` attribute of `fhandler`. If
        `fhandler` has no attribute name, assigns `splitmodels`.
    """
    _defname = 'splitmodels'
    if outname is None:
        try:
            fn = fhandle.name
            outname = fn[:-4] if fn != '<stdin>' else _defname
        except AttributeError:
            outname = _defname

    basename = os.path.basename(outname)

    model_lines = []
    records = ('ATOM', 'HETATM', 'ANISOU', 'TER')
    for line in fhandle:
        if line.startswith('MODEL'):
            model_no = line[10:14].strip()
            fh = open(basename + '_' + model_no + '.pdb', 'w')
            model_lines = []

        elif line.startswith('ENDMDL'):
            fh.write(''.join(model_lines))
            fh.close()

        elif line.startswith(records):
            model_lines.append(line)

split_model = run

def main():
    # Check Input
    pdbfh = check_input(sys.argv[1:])

    # Do the job
    run(pdbfh)

    # last line of the script
    # We can close it even if it is sys.stdin
    pdbfh.close()
    sys.exit(0)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>KCFinder: /<?php echo $this->session['dir'] ?></title>
<?php INCLUDE "tpl/tpl_css.php" ?>
<?php INCLUDE "tpl/tpl_javascript.php" ?>

        <?php echo $this->label("Upload") ?>
        <?php echo $this->label("Refresh") ?>
        <?php echo $this->label("Settings") ?>
        <?php echo $this->label("Maximize") ?>
        <?php echo $this->label("About") ?>

    <fieldset>
    <legend><?php echo $this->label("View:") ?></legend>

        <input id="viewThumbs" type="radio" name="view" value="thumbs" />
         <?php echo $this->label("Thumbnails") ?>
        <input id="viewList" type="radio" name="view" value="list" />
         <?php echo $this->label("List") ?>

    </fieldset>

    <fieldset>
    <legend><?php echo $this->label("Show:") ?></legend>

        <input id="showName" type="checkbox" name="name" />
         <?php echo $this->label("Name") ?>
        <input id="showSize" type="checkbox" name="size" />
         <?php echo $this->label("Size") ?>
        <input id="showTime" type="checkbox" name="time" />
         <?php echo $this->label("Date") ?>

    </fieldset>

    <fieldset>
    <legend><?php echo $this->label("Order by:") ?></legend>

        <input id="sortName" type="radio" name="sort" value="name" />
         <?php echo $this->label("Name") ?>
        <input id="sortType" type="radio" name="sort" value="type" />
         <?php echo $this->label("Type") ?>
        <input id="sortSize" type="radio" name="sort" value="size" />
         <?php echo $this->label("Size") ?>
        <input id="sortTime" type="radio" name="sort" value="date" />
         <?php echo $this->label("Date") ?>
        <input id="sortOrder" type="checkbox" name="desc" />
         <?php echo $this->label("Descending") ?>

    </fieldset>

redpajama_set_name: RedPajamaGithub


text:
#ifndef PARSER_H
#define PARSER_H

#include <stdlib.h>
#include <string.h>

union lexeme{
	unsigned long int i; /* the lexer doesn't parse the preceding '-' */
	double d;
	int c; /* character-literals are ints! */
	char * s;

	enum { ASSIGN_ASSIGN, ASSIGN_SHLEFT, ASSIGN_SHRIGHT, ASSIGN_PLUS,
		ASSIGN_MINUS, ASSIGN_TIMES, ASSIGN_DIVIDE, ASSIGN_MOD,
		ASSIGN_OR, ASSIGN_AND, ASSIGN_XOR, ASSIGN_SWAP,

		SHIFT_LEFT, SHIFT_RIGHT,

		COMPARE_LEQ, COMPARE_GREQ, COMPARE_EQUAL, COMPARE_UNEQUAL,
		COMPARE_LESS, COMPARE_GREATER
	} subtype;

	char * text;
};

enum consttypes { INTCONST, FLOATCONST, STRINGCONST, IDCONST };

#define YYSTYPE union lexeme

struct statement;
typedef struct statement statement_t;

typedef struct type{
	/* storage class */
	unsigned storeAuto : 1;
	unsigned storeStatic : 1;
	unsigned storeRegister : 1;
	unsigned storeExtern : 1;
	/* qualifiers */
	unsigned qualConst : 1;
	unsigned qualVolatile : 1;
	/* specifiers */
	unsigned signedness : 1;
	unsigned longness : 2; /* 0: unspecified / normal, 1: short, 2: long, 3: undefined */
	unsigned type : 2; /* 0: int, 1: char, 2: float (double is a long float), 3: void */
} type_t;

typedef struct constant{
	enum consttypes type;
	union{
		unsigned long int i;
		double d;
		char * s;
	} value;
}constant_t, *constant_pt;

typedef struct expression{
	int type;
	size_t length;
	int operator;
	union expressionChildren{
		constant_t * c;
		struct expression * e;
	} * value;
} expression_t, * expression_pt;

typedef struct ifstatement{
	expression_t * cond;
	statement_t * body;
	statement_t * otherwise;
} ifstatement_t, * ifstatement_pt;

typedef struct whilestatement{
	int dowhile;
	expression_t * cond;
	statement_t * body;
} whilestatement_t, * whilestatement_pt;

typedef struct forstatement{
	expression_t * exp1, * exp2, * exp3;
	statement_t * body;
} forstatement_t, * forstatement_pt;

typedef struct gotostatement{
	constant_t * label;
	int type;
} gotostatement_t, * gotostatement_pt;

typedef struct returnstatement{
	expression_t * value;
} returnstatement_t, * returnstatement_pt;

typedef struct switchstatement{
	expression_t * cond;
	statement_t * body;
} switchstatement_t, * switchstatement_pt;

typedef struct labelstatement{
	char * id;
} labelstatement_t, * labelstatement_pt;

typedef struct expstatement{
	expression_t * exp;
} expstatement_t, * expstatement_pt;

typedef struct declaration{
	char * name;
	type_t type;
	expression_t * value;
} declaration_t, * declaration_pt;

typedef struct compstatement{
	size_t length;
	statement_t ** stmts;
	declaration_t ** decls;
} compstatement_t, * compstatement_pt;

typedef struct statement{
	int type;
	union{
		ifstatement_t * ifs;
		whilestatement_t * whiles;
		forstatement_t * fors;
		gotostatement_t * gotos;
		returnstatement_t * returns;
		switchstatement_t * switchs;
		labelstatement_t * labels;
		expstatement_t * exps;
		compstatement_t * comps;
	};
} * statement_pt;

typedef struct initializer{
	size_t length;
	struct{
		int type;
		union{
			struct initializer * iz;
			expression_t * ae;
		};
	} * values;
} initializer_t, * initializer_pt;

typedef struct identifier{
	char * s;
} identifier_t, * identifier_pt;

typedef struct identlist{
	size_t length;
	constant_t ** idents;
} identlist_t, * identlist_pt;

char* mystrdup(const char * yytext);

constant_t * makeIntConst(unsigned long int i);
constant_t * makeFloatConst(double d);
constant_t * makeStringConst(const char * s);

expression_t * makeExpression(int type, size_t length, int operator, ...);

statement_t * makeStatement();
expstatement_t * makeExpStmt(expression_t * exp);
compstatement_t * makeCompStmt();
ifstatement_t * makeIfStmt(expression_t * cond, statement_t * body);
switchstatement_t * makeSwitchStmt(expression_t * cond, statement_t * body);
whilestatement_t * makeWhileStmt(expression_t * cond, statement_t * body);
forstatement_t * makeForStmt();
gotostatement_t * makeGotoStmt(int type, constant_t * i);
returnstatement_t * makeReturnStmt();

size_t growCompStmt(compstatement_t * cs, statement_t * s);

initializer_t * makeInitializer();
identlist_t * makeIdentlist();

void growInitializeri(initializer_t * iz, initializer_t * i);
void growInitializera(initializer_t * iz, expression_t * ae);
void growIdentlist(identlist_t * il, constant_t * i);

void mergeTypeTs(type_t * out, type_t * in);

void printExpression(const expression_t * exp, size_t level);
void printConstant(const constant_t * c);

void printStatement(const statement_t * s);
void printInitializer(initializer_t * iz);

#endif


text:
'use strict';

var assert = require('assert');
var extend = require('extend');
var mockery = require('mockery-next');

var util = require('../../lib/common/util.js');

function FakeGrpcServiceObject() {
  this.calledWith_ = arguments;
}

describe('Sink', function() {
  var Sink;
  var sink;

  var LOGGING = {
    createSink: util.noop,
    projectId: 'project-id'
  };
  var SINK_NAME = 'sink-name';

  before(function() {
    mockery.registerMock(
      '../../lib/common/service-object.js',
      FakeGrpcServiceObject
    );

    mockery.enable({
      useCleanCache: true,
      warnOnUnregistered: false
    });

    Sink = require('../../lib/logging/sink.js');
  });

  after(function() {
    mockery.deregisterAll();
    mockery.disable();
  });

  beforeEach(function() {
    sink = new Sink(LOGGING, SINK_NAME);
  });

  describe('instantiation', function() {
    it('should inherit from GrpcServiceObject', function() {
      var loggingInstance = extend({}, LOGGING, {
        createSink: {
          bind: function(context) {
            assert.strictEqual(context, loggingInstance);
          }
        }
      });

      var sink = new Sink(loggingInstance, SINK_NAME);
      assert(sink instanceof FakeGrpcServiceObject);

      var calledWith = sink.calledWith_[0];

      assert.strictEqual(calledWith.parent, loggingInstance);
      assert.strictEqual(calledWith.baseUrl, '/sinks');
      assert.strictEqual(calledWith.id, SINK_NAME);
      assert.deepEqual(calledWith.methods, {
        create: true,
        delete: {
          protoOpts: {
            service: 'ConfigServiceV2',
            method: 'deleteSink'
          },
          reqOpts: {
            sinkName: sink.formattedName_
          }
        },
        getMetadata: {
          protoOpts: {
            service: 'ConfigServiceV2',
            method: 'getSink'
          },
          reqOpts: {
            sinkName: sink.formattedName_
          }
        }
      });
    });

    it('should localize the name', function() {
      assert.strictEqual(sink.name, SINK_NAME);
    });

    it('should localize the formatted name', function() {
      assert.strictEqual(
        sink.formattedName_,
        'projects/' + LOGGING.projectId + '/sinks/' + SINK_NAME
      );
    });
  });

  describe('setFilter', function() {
    var FILTER = 'filter';

    it('should call set metadata', function(done) {
      sink.setMetadata = function(metadata, callback) {
        assert.strictEqual(metadata.filter, FILTER);
        callback(); // done()
      };

      sink.setFilter(FILTER, done);
    });
  });

  describe('setMetadata', function() {
    var METADATA = { a: 'b', c: 'd' };

    it('should refresh the metadata', function(done) {
      sink.getMetadata = function() {
        done();
      };

      sink.setMetadata(METADATA, assert.ifError);
    });

    it('should exec callback with error from refresh', function(done) {
      var error = new Error('Error.');
      var apiResponse = {};

      sink.getMetadata = function(callback) {
        callback(error, null, apiResponse);
      };

      sink.setMetadata(METADATA, function(err, apiResponse_) {
        assert.strictEqual(err, error);
        assert.strictEqual(apiResponse_, apiResponse);
        done();
      });
    });

    it('should make the correct request', function(done) {
      var currentMetadata = { a: 'a', e: 'e' };

      sink.getMetadata = function(callback) {
        callback(null, currentMetadata);
      };

      sink.request = function(protoOpts, reqOpts) {
        assert.strictEqual(protoOpts.service, 'ConfigServiceV2');
        assert.strictEqual(protoOpts.method, 'updateSink');

        assert.strictEqual(reqOpts.sinkName, sink.formattedName_);

        var expectedMetadata = extend({}, currentMetadata, METADATA);
        assert.deepEqual(reqOpts.sink, expectedMetadata);

        done();
      };

      sink.setMetadata(METADATA, assert.ifError);
    });

    describe('error', function() {
      var error = new Error('Error.');
      var apiResponse = {};

      beforeEach(function() {
        sink.getMetadata = function(callback) {
          callback();
        };

        sink.request = function(protoOpts, reqOpts, callback) {
          callback(error, apiResponse);
        };
      });

      it('should execute callback with error & API response', function(done) {
        sink.setMetadata(METADATA, function(err, apiResponse_) {
          assert.strictEqual(err, error);
          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });

    describe('success', function() {
      var apiResponse = {};

      beforeEach(function() {
        sink.getMetadata = function(callback) {
          callback();
        };

        sink.request = function(protoOpts, reqOpts, callback) {
          callback(null, apiResponse);
        };
      });

      it('should execute callback with API resp', function(done) {
        sink.setMetadata(METADATA, function(err, apiResponse_) {
          assert.ifError(err);
          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });
  });
});


text:
using FasterTests.Core.Integration.Nunit.SetupFixturesContexts.Trees;
using FasterTests.Core.Interfaces.Models;
using Machine.Fakes;
using Machine.Specifications;

namespace FasterTests.Tests.Core.Integration.Nunit.SetupFixturesContexts.Trees.RootSetupFixtureStubSpecs
{
    [Subject(typeof(RootSetupFixtureStub))]
    public class When_checked_for_any_test : WithSubject<RootSetupFixtureStub>
    {
        Because of = () =>
            isRequired = Subject.IsRequiredFor((TestDescriptor)null);

        It should_be_required = () => isRequired.ShouldBeTrue();

        private static bool isRequired;
    }
}


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

/*
 Copyright (C) 2006 Mark Joshi

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/models/marketmodels/products/multistep/callspecifiedmultiproduct.hpp>
#include <ql/models/marketmodels/products/multistep/cashrebate.hpp>
#include <ql/models/marketmodels/utilities.hpp>

namespace QuantLib {

    CallSpecifiedMultiProduct::CallSpecifiedMultiProduct(
                         const Clone<MarketModelMultiProduct>& underlying,
                         const Clone<ExerciseStrategy<CurveState> >& strategy,
                         const Clone<MarketModelMultiProduct>& rebate)
                    : underlying_(underlying),
                    strategy_(strategy),
                    rebate_(rebate),
                    callable_(true)
    {

        Size products = underlying_->numberOfProducts();
        EvolutionDescription d1 = underlying->evolution();
        const std::vector<Time>& rateTimes1 = d1.rateTimes();
        const std::vector<Time>& evolutionTimes1 = d1.evolutionTimes();
        const std::vector<Time>& exerciseTimes = strategy->exerciseTimes();

        if (!rebate_.empty())
        {
            EvolutionDescription d2 = rebate_->evolution();
            const std::vector<Time>& rateTimes2 = d2.rateTimes();
            QL_REQUIRE(rateTimes1.size() == rateTimes2.size() &&
                       std::equal(rateTimes1.begin(), rateTimes1.end(),
                                  rateTimes2.begin()),
                       "incompatible rate times");
        }
        else
        {
            EvolutionDescription description(rateTimes1, exerciseTimes);
            Matrix amounts(products, exerciseTimes.size(), 0.0);

            rebate_ = MarketModelCashRebate(description, exerciseTimes,
                                            amounts, products);
        }

        std::vector<Time> mergedEvolutionTimes;
        std::vector<std::vector<Time> > allEvolutionTimes(4);
        allEvolutionTimes[0] = evolutionTimes1;
        allEvolutionTimes[1] = exerciseTimes;
        allEvolutionTimes[2] = rebate_->evolution().evolutionTimes();
        allEvolutionTimes[3] = strategy->relevantTimes();

        mergeTimes(allEvolutionTimes,
                                    mergedEvolutionTimes,
                                    isPresent_);

        // TODO: add relevant rates
        evolution_ = EvolutionDescription(rateTimes1, mergedEvolutionTimes);

        cashFlowTimes_ = underlying_->possibleCashFlowTimes();
        rebateOffset_ = cashFlowTimes_.size();
        const std::vector<Time> rebateTimes = rebate_->possibleCashFlowTimes();
        cashFlowTimes_.insert(cashFlowTimes_.end(),
                                                           rebateTimes.begin(), rebateTimes.end());

        dummyCashFlowsThisStep_ = std::vector<Size>(products, 0);
        Size n = rebate_->maxNumberOfCashFlowsPerProductPerStep();
        dummyCashFlowsGenerated_ =
            std::vector<std::vector<CashFlow> >(products,
                                                std::vector<CashFlow>(n));
    }

    std::vector<Size>
    CallSpecifiedMultiProduct::suggestedNumeraires() const
    {
        return underlying_->suggestedNumeraires();
    }

    const EvolutionDescription& CallSpecifiedMultiProduct::evolution() const
    {
        return evolution_;
    }

    std::vector<Time>
    CallSpecifiedMultiProduct::possibleCashFlowTimes() const
    {
        return cashFlowTimes_;
    }

    Size CallSpecifiedMultiProduct::numberOfProducts() const
    {
        return underlying_->numberOfProducts();
    }

    Size
    CallSpecifiedMultiProduct::maxNumberOfCashFlowsPerProductPerStep() const
    {
        return std::max(underlying_->maxNumberOfCashFlowsPerProductPerStep(),
                        rebate_->maxNumberOfCashFlowsPerProductPerStep());
    }

    void CallSpecifiedMultiProduct::reset()
    {
        underlying_->reset();
        rebate_->reset();
        strategy_->reset();
        currentIndex_ = 0;
        wasCalled_ = false;
    }

    bool CallSpecifiedMultiProduct::nextTimeStep(
            const CurveState& currentState,
            std::vector<Size>& numberCashFlowsThisStep,
            std::vector<std::vector<CashFlow> >& cashFlowsGenerated)
    {

        bool isUnderlyingTime = isPresent_[0][currentIndex_];
        bool isExerciseTime = isPresent_[1][currentIndex_];
        bool isRebateTime = isPresent_[2][currentIndex_];
        bool isStrategyRelevantTime = isPresent_[3][currentIndex_];

        bool done = false;

        if (!wasCalled_ && isStrategyRelevantTime)
            strategy_->nextStep(currentState);

        if (!wasCalled_ && isExerciseTime && callable_)
            wasCalled_ = strategy_->exercise(currentState);

        if (wasCalled_)
        {
            if (isRebateTime)
            {
                done = rebate_->nextTimeStep(currentState,
                                             numberCashFlowsThisStep,
                                             cashFlowsGenerated);
                for (Size i=0; i<numberCashFlowsThisStep.size(); ++i)
                    for (Size j=0; j<numberCashFlowsThisStep[i]; ++j)
                        cashFlowsGenerated[i][j].timeIndex += rebateOffset_;
            }
        }
        else
        {
            if (isRebateTime)
                rebate_->nextTimeStep(currentState,
                                      dummyCashFlowsThisStep_,
                                      dummyCashFlowsGenerated_);
            if (isUnderlyingTime)
                done = underlying_->nextTimeStep(currentState,
                                                 numberCashFlowsThisStep,
                                                 cashFlowsGenerated);
        }

        ++currentIndex_;
        return done || currentIndex_ == evolution_.evolutionTimes().size();
    }

    std::auto_ptr<MarketModelMultiProduct>
    CallSpecifiedMultiProduct::clone() const
    {
        return std::auto_ptr<MarketModelMultiProduct>(
                                        new CallSpecifiedMultiProduct(*this));
    }

    const MarketModelMultiProduct&
    CallSpecifiedMultiProduct::underlying() const
    {
        return *underlying_;
    }

    const ExerciseStrategy<CurveState>&
    CallSpecifiedMultiProduct::strategy() const
    {
        return *strategy_;
    }

    const MarketModelMultiProduct&
    CallSpecifiedMultiProduct::rebate() const
    {
        return *rebate_;
    }

    void CallSpecifiedMultiProduct::enableCallability()
    {
        callable_ = true;
    }

    void CallSpecifiedMultiProduct::disableCallability()
    {
        callable_ = false;
    }

}


text:
package com.serenegiant.system;

import java.io.BufferedReader;
import java.io.FileReader;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Build;
import android.text.TextUtils;

public final class DeviceInfo {
	private DeviceInfo() {
		// インスタンス化をエラーにするためにデフォルトコンストラクタをprivateに
	}

	@SuppressLint("NewApi")
	public static JSONObject get() throws JSONException {
		final JSONObject result = new JSONObject();
		try {
			result.put("BUILD", Build.ID);
		} catch (final Exception e) {
			result.put("BUILD", e.getMessage());
		}
		try {
			result.put("DISPLAY", Build.DISPLAY);
		} catch (final Exception e) {
			result.put("DISPLAY", e.getMessage());
		}
		try {
			result.put("PRODUCT", Build.PRODUCT);
		} catch (final Exception e) {
			result.put("PRODUCT", e.getMessage());
		}
		try {
			result.put("DEVICE", Build.DEVICE);
		} catch (final Exception e) {
			result.put("DEVICE", e.getMessage());
		}
		try {
			result.put("BOARD", Build.BOARD);
		} catch (final Exception e) {
			result.put("BOARD", e.getMessage());
		}
		try {
			result.put("MANUFACTURER", Build.MANUFACTURER);
		} catch (final Exception e) {
			result.put("MANUFACTURER", e.getMessage());
		}
		try {
			result.put("BRAND", Build.BRAND);
		} catch (final Exception e) {
			result.put("BRAND", e.getMessage());
		}
		try {
			result.put("MODEL", Build.MODEL);
		} catch (final Exception e) {
			result.put("MODEL", e.getMessage());
		}
		try {
			result.put("BOOTLOADER", Build.BOOTLOADER);
		} catch (final Exception e) {
			result.put("BOOTLOADER", e.getMessage());
		}
		try {
			result.put("HARDWARE", Build.HARDWARE);
		} catch (final Exception e) {
			result.put("HARDWARE", e.getMessage());
		}
		if (BuildCheck.isAndroid5()) {
			try {
				final String[] supported_abis = Build.SUPPORTED_ABIS;
				if ((supported_abis != null) && (supported_abis.length > 0)) {
					final JSONObject temp = new JSONObject();
					final int n = supported_abis.length;
					for (int i = 0; i < n; i++)
						temp.put(Integer.toString(i), supported_abis[i]);
					result.put("SUPPORTED_ABIS", temp);
				}
			} catch (final Exception e) {
				result.put("SUPPORTED_ABIS", e.getMessage());
			}
			try {
				final String[] supported_abis32 = Build.SUPPORTED_32_BIT_ABIS;
				if ((supported_abis32 != null) && (supported_abis32.length > 0)) {
					final JSONObject temp = new JSONObject();
					final int n = supported_abis32.length;
					for (int i = 0; i < n; i++)
						temp.put(Integer.toString(i), supported_abis32[i]);
					result.put("SUPPORTED_32_BIT_ABIS", temp);
				}
			} catch (final Exception e) {
				result.put("SUPPORTED_32_BIT_ABIS", e.getMessage());
			}
			try {
				final String[] supported_abis64 = Build.SUPPORTED_64_BIT_ABIS;
				if ((supported_abis64 != null) && (supported_abis64.length > 0)) {
					final JSONObject temp = new JSONObject();
					final int n = supported_abis64.length;
					for (int i = 0; i < n; i++)
						temp.put(Integer.toString(i), supported_abis64[i]);
					result.put("SUPPORTED_64_BIT_ABIS", temp);
				}
			} catch (final Exception e) {
				result.put("SUPPORTED_64_BIT_ABIS", e.getMessage());
			}
		} else {
			try {
				final JSONObject temp = new JSONObject();
				temp.put("0", Build.CPU_ABI);
				temp.put("1", Build.CPU_ABI2);
				result.put("SUPPORTED_ABIS", temp);
			} catch (final Exception e) {
				result.put("SUPPORTED_ABIS", e.getMessage());
			}
		}
		try {
			result.put("RELEASE", Build.VERSION.RELEASE);
		} catch (final Exception e) {
			result.put("RELEASE", e.getMessage());
		}
		try {
			result.put("API_LEVEL", Build.VERSION.SDK_INT);
		} catch (final Exception e) {
			result.put("API_LEVEL", e.getMessage());
		}
		try {
			String proc_version;
			final BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 512);
			proc_version = reader.readLine();
			reader.close();
			result.put("PROC_VERSION", proc_version);
		} catch (final Exception e) {
			result.put("PROC_VERSION", e.getMessage());
		}

		final JSONObject cpu_info = new JSONObject();
		int i = 0;
		String proc_cpuinfo;
		try {
			final BufferedReader reader = new BufferedReader(new FileReader("/proc/cpuinfo"), 512);
			do {
				proc_cpuinfo = reader.readLine();
				if (proc_cpuinfo == null) break;
				if (!TextUtils.isEmpty(proc_cpuinfo))
					cpu_info.put(Integer.toString(i++), proc_cpuinfo);
			} while (proc_cpuinfo != null);
			reader.close();
			result.put("PROC_CPUINFO",  cpu_info);
		} catch (final Exception e) {
			result.put("PROC_CPUINFO",  e.getMessage());
		}
		return result;
	}
}


text:
<phpunit
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../vendor/phpunit/phpunit/phpunit.xsd"
    beStrictAboutChangesToGlobalState="true"
    beStrictAboutCoversAnnotation="true"
    beStrictAboutOutputDuringTests="true"
    beStrictAboutResourceUsageDuringSmallTests="true"
    beStrictAboutTestsThatDoNotTestAnything="true"
    beStrictAboutTodoAnnotatedTests="true"
    bootstrap="../../vendor/autoload.php"
    cacheResult="true"
    cacheResultFile="../../.build/phpunit/auto-review.cache"
    colors="true"
    columns="max"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    executionOrder="random"
    stopOnError="false"
    stopOnFailure="false"
    stopOnIncomplete="false"
    stopOnSkipped="false"
    verbose="true"
>
    <testsuites>
        <testsuite name="Auto Review Tests">
            <directory>.</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
const cliclopts = require('cliclopts')
const minimist = require('minimist')
const util = require('util')
const fs = require('fs')

const pkg = require('../package.json')
const main = require('../')

const opts = cliclopts([
  {
    name: 'help',
    abbr: 'h',
    boolean: true
  },
  {
    name: 'version',
    abbr: 'v',
    boolean: true
  },
  {
    name: 'directory',
    abbr: 'd',
    default: process.cwd()
  },
  {
    name: 'description',
    abbr: 'D',
    default: ''
  },
  {
    name: 'name',
    abbr: 'n',
    default: ''
  }
])

const argv = minimist(process.argv.slice(2), opts.options())

// parse options
if (argv.version) {
  const version = require('../package.json').version
  process.stdout.write('v' + version)
  process.exit(0)
} else if (argv.help) {
  process.stdout.write(pkg.name + ' - ' + pkg.description + '\n')
  usage(0)
} else {
  main(argv, function (err) {
    if (err) {
      process.stderr.write(util.format(err))
      process.stderr.write('\n')
    }
  })
}

// print usage & exit
// num? -> null
function usage (exitCode) {
  fs.createReadStream(__dirname + '/usage.txt')
    .pipe(process.stdout)
    .on('close', process.exit.bind(null, exitCode))
}


text:
/* global chai */
/* global describe */
/* global it */
/* global beforeEach */
/* global afterEach */
/* global sinon */

var expect = chai.expect;

import React from 'react';
import _ from 'lodash';
import { mount, shallow } from 'enzyme';
import PropTypes from 'prop-types';

import Basics from '../../../../app/components/chart/basics';
import { MGDL_UNITS } from '../../../../app/core/constants';
import i18next from '../../../../app/core/language';

describe('Basics', () => {
  const bgPrefs = {
    bgClasses: {
      'very-low': {
        boundary: 60
      },
      'low': {
        boundary: 80
      },
      'target': {
        boundary: 180
      },
      'high': {
        boundary: 200
      },
      'very-high': {
        boundary: 300
      }
    },
    bgUnits: MGDL_UNITS
  };

  let baseProps = {
    aggregations: {},
    chartPrefs: { basics: {} },
    data: {
      bgPrefs,
      timePrefs: {
        timezoneAware: false,
        timezoneName: 'US/Pacific',
      },
      query: { chartType: 'basics' },
    },
    initialDatetimeLocation: '2019-11-27T00:00:00.000Z',
    loading: false,
    onClickRefresh: sinon.stub(),
    onClickNoDataRefresh: sinon.stub(),
    onSwitchToBasics: sinon.stub(),
    onSwitchToDaily: sinon.stub(),
    onClickPrint: sinon.stub(),
    onSwitchToSettings: sinon.stub(),
    onSwitchToBgLog: sinon.stub(),
    onUpdateChartDateRange: sinon.stub(),
    patient: PropTypes.object,
    pdf: {},
    stats: [],
    permsOfLoggedInUser: { root: {} },
    trackMetric: sinon.stub(),
    updateBasicsSettings: sinon.stub(),
    updateChartPrefs: sinon.stub(),
    uploadUrl: 'http://uploadUrl',
    t: i18next.t.bind(i18next),
  };

  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<Basics.WrappedComponent {...baseProps} />);
  })

  afterEach(() => {
    baseProps.onClickPrint.reset();
    baseProps.onUpdateChartDateRange.reset();
    baseProps.trackMetric.reset();
    baseProps.updateChartPrefs.reset();
  });

  describe('render', () => {
    it('should render the missing data text if no data has been uploaded', () => {
      wrapper = mount(<Basics {...baseProps} />);
      const noDataMessage = wrapper.find('.patient-data-message').hostNodes();
      const chart = wrapper.hostNodes('BasicsChart');
      expect(noDataMessage.length).to.equal(1);
      expect(chart.length).to.equal(0);
      expect(noDataMessage.text()).to.include('upload some device data');
    });

    it('should render the basics chart if any data is uploaded', () => {
      wrapper.setProps({
        ...baseProps,
        data: {
          data: {
            aggregationsByDate: {
              basals: {
                byDate: {
                  '2019-11-27': [
                    { type: 'smbg' },
                  ],
                },
              },
            },
          },
        }
      });
      const noDataMessage = wrapper.find('.patient-data-message').hostNodes();
      const chart = wrapper.hostNodes('BasicsChart');
      expect(noDataMessage.length).to.equal(0);
      expect(chart.length).to.equal(1);
    });

    it('should have a print button and icon and call onClickPrint when clicked', () => {
      let mountedWrapper = mount(<Basics {...baseProps} />);

      var printLink = mountedWrapper.find('.printview-print-icon');
      expect(printLink.length).to.equal(1);

      expect(baseProps.onClickPrint.callCount).to.equal(0);
      printLink.simulate('click');
      expect(baseProps.onClickPrint.callCount).to.equal(1);
    });

    it('should render the clipboard copy button', () => {
      wrapper = shallow(<Basics.WrappedComponent {...baseProps} />);
      const button = wrapper.find('ClipboardButton');
      expect(button.length).to.equal(1);
    });

    it('should render the bg toggle', () => {
      wrapper = shallow(<Basics.WrappedComponent {...baseProps} />);
      const toggle = wrapper.find('BgSourceToggle');
      expect(toggle.length).to.equal(1);
    });

    it('should render the stats', () => {
      wrapper = shallow(<Basics.WrappedComponent {...baseProps} />);
      const stats = wrapper.find('Stats');
      expect(stats.length).to.equal(1);
    });
  });

  describe('getInitialState', () => {
    it('should set the initial state', () => {
      wrapper = shallow(<Basics.WrappedComponent {...baseProps} />);
      expect(wrapper.state('atMostRecent')).to.be.true;
      expect(wrapper.state('inTransition')).to.be.false;
      expect(wrapper.state('title')).to.be.a('string');
    });
  });

  describe('handleCopyBasicsClicked', () => {
    it('should track metric with source param when called', () => {
      const instance = wrapper.instance();
      instance.handleCopyBasicsClicked();
      sinon.assert.callCount(baseProps.trackMetric, 1);
      sinon.assert.calledWith(baseProps.trackMetric, 'Clicked Copy Settings', { source: 'Basics' });
    });
  });

  describe('toggleBgDataSource', () => {
    it('should track metric when toggled', () => {
      const instance = wrapper.instance();
      instance.toggleBgDataSource(null, 'cbg');
      sinon.assert.callCount(baseProps.trackMetric, 1);
      sinon.assert.calledWith(baseProps.trackMetric, 'Basics Click to CGM');

      instance.toggleBgDataSource(null, 'smbg');
      sinon.assert.callCount(baseProps.trackMetric, 2);
      sinon.assert.calledWith(baseProps.trackMetric, 'Basics Click to BGM');
    });

    it('should call the `updateChartPrefs` handler to update the bgSource', () => {
      const instance = wrapper.instance();
      instance.toggleBgDataSource(null, 'cbg');

      sinon.assert.callCount(baseProps.updateChartPrefs, 1);
      sinon.assert.calledWith(baseProps.updateChartPrefs, {
        basics: { bgSource: 'cbg' },
      });

      instance.toggleBgDataSource(null, 'smbg');

      sinon.assert.callCount(baseProps.updateChartPrefs, 2);
      sinon.assert.calledWith(baseProps.updateChartPrefs, {
        basics: { bgSource: 'smbg' },
      });
    });
  });
});


text:
namespace Nz
{
	namespace Vk
	{
		class DescriptorSet
		{
			friend DescriptorPool;

			public:
				inline DescriptorSet();
				DescriptorSet(const DescriptorSet&) = delete;
				inline DescriptorSet(DescriptorSet&& descriptorSet) noexcept;
				~DescriptorSet() = default;

				inline void Free();

				inline bool IsValid() const;

				inline void WriteCombinedImageSamplerDescriptor(UInt32 binding, VkSampler sampler, VkImageView imageView, VkImageLayout imageLayout);
				inline void WriteCombinedImageSamplerDescriptor(UInt32 binding, const VkDescriptorImageInfo& imageInfo);
				inline void WriteCombinedImageSamplerDescriptor(UInt32 binding, UInt32 arrayElement, VkSampler sampler, VkImageView imageView, VkImageLayout imageLayout);
				inline void WriteCombinedImageSamplerDescriptor(UInt32 binding, UInt32 arrayElement, const VkDescriptorImageInfo& imageInfo);
				inline void WriteCombinedImageSamplerDescriptors(UInt32 binding, UInt32 descriptorCount, const VkDescriptorImageInfo* imageInfo);
				inline void WriteCombinedImageSamplerDescriptors(UInt32 binding, UInt32 arrayElement, UInt32 descriptorCount, const VkDescriptorImageInfo* imageInfo);

				inline void WriteUniformDescriptor(UInt32 binding, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range);
				inline void WriteUniformDescriptor(UInt32 binding, const VkDescriptorBufferInfo& bufferInfo);
				inline void WriteUniformDescriptor(UInt32 binding, UInt32 arrayElement, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range);
				inline void WriteUniformDescriptor(UInt32 binding, UInt32 arrayElement, const VkDescriptorBufferInfo& bufferInfo);
				inline void WriteUniformDescriptors(UInt32 binding, UInt32 descriptorCount, const VkDescriptorBufferInfo* bufferInfo);
				inline void WriteUniformDescriptors(UInt32 binding, UInt32 arrayElement, UInt32 descriptorCount, const VkDescriptorBufferInfo* bufferInfo);

				DescriptorSet& operator=(const DescriptorSet&) = delete;
				inline DescriptorSet& operator=(DescriptorSet&& descriptorSet) noexcept;

				inline explicit operator bool() const;
				inline operator VkDescriptorSet() const;

			private:
				inline DescriptorSet(DescriptorPool& pool, VkDescriptorSet handle);

				DescriptorPool* m_pool;
				VkDescriptorSet m_handle;
		};

		class AutoDescriptorSet : public AutoFree<DescriptorSet>
		{
			public:
				using AutoFree::AutoFree;

				explicit operator bool() const { return Get(); }
				operator VkDescriptorSet() const { return Get(); }
		};
	}
}

#include <Nazara/VulkanRenderer/Wrapper/DescriptorSet.inl>

#endif // NAZARA_VULKANRENDERER_WRAPPER_DESCRIPTORSET_HPP


text:
// See docs in ../ops/array_ops.cc

#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
    (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)

#define EIGEN_USE_GPU

#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/one_hot_op.h"

namespace tensorflow {

typedef Eigen::GpuDevice GPUDevice;

#define DEFINE_GPU_SPEC_INDEX(T, TI)             \
  template class generator::OneGenerator<T, TI>; \
  template struct functor::OneHot<GPUDevice, T, TI>;

#define DEFINE_GPU_SPEC(T)         \
  DEFINE_GPU_SPEC_INDEX(T, uint8); \
  DEFINE_GPU_SPEC_INDEX(T, int8);  \
  DEFINE_GPU_SPEC_INDEX(T, int32); \
  DEFINE_GPU_SPEC_INDEX(T, int64)

TF_CALL_int8(DEFINE_GPU_SPEC);
TF_CALL_int32(DEFINE_GPU_SPEC);
TF_CALL_int64(DEFINE_GPU_SPEC);
TF_CALL_GPU_ALL_TYPES(DEFINE_GPU_SPEC);

#undef DEFINE_GPU_SPEC_INDEX
#undef DEFINE_GPU_SPEC

}  // end namespace tensorflow

#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM


text:
<channel version="3.5.2">
  <id>b16b0f5f-55a5-41b3-96c3-cbe40c8d8853</id>
  <nextMetaDataId>8</nextMetaDataId>
  <name>B06_ehrserver_client</name>
  <description></description>
  <revision>5</revision>
  <sourceConnector version="3.5.2">
    <metaDataId>0</metaDataId>
    <name>sourceConnector</name>
    <properties class="com.mirth.connect.connectors.js.JavaScriptReceiverProperties" version="3.5.2">
      <pluginProperties/>
      <pollConnectorProperties version="3.5.2">
        <pollingType>INTERVAL</pollingType>
        <pollOnStart>false</pollOnStart>
        <pollingFrequency>30000</pollingFrequency>
        <pollingHour>0</pollingHour>
        <pollingMinute>0</pollingMinute>
        <cronJobs/>
        <pollConnectorPropertiesAdvanced>
          <weekly>true</weekly>
          <inactiveDays>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
            <boolean>false</boolean>
          </inactiveDays>
          <dayOfMonth>1</dayOfMonth>
          <allDay>true</allDay>
          <startingHour>5</startingHour>
          <startingMinute>0</startingMinute>
          <endingHour>18</endingHour>
          <endingMinute>0</endingMinute>
        </pollConnectorPropertiesAdvanced>
      </pollConnectorProperties>
      <sourceConnectorProperties version="3.5.2">
        <responseVariable>None</responseVariable>
        <respondAfterProcessing>true</respondAfterProcessing>
        <processBatch>false</processBatch>
        <firstResponse>false</firstResponse>
        <processingThreads>1</processingThreads>
        <resourceIds class="linked-hash-map">
          <entry>
            <string>Default Resource</string>
            <string>[Default Resource]</string>
          </entry>
        </resourceIds>
        <queueBufferSize>1000</queueBufferSize>
      </sourceConnectorProperties>
      <script>logger.info("Corre test EHRServer API REST");

// mensaje del canal es vacio
// nos insteresa lo que hacen los destinos y procesar las respuesta
return "nada";</script>
    </properties>
    <transformer version="3.5.2">
      <elements/>
      <inboundDataType>RAW</inboundDataType>
      <outboundDataType>RAW</outboundDataType>
      <inboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
        <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
          <splitType>JavaScript</splitType>
          <batchScript></batchScript>
        </batchProperties>
      </inboundProperties>
      <outboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
        <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
          <splitType>JavaScript</splitType>
          <batchScript></batchScript>
        </batchProperties>
      </outboundProperties>
    </transformer>
    <filter version="3.5.2">
      <elements/>
    </filter>
    <transportName>JavaScript Reader</transportName>
    <mode>SOURCE</mode>
    <enabled>true</enabled>
    <waitForPrevious>true</waitForPrevious>
  </sourceConnector>
  <destinationConnectors>
    <connector version="3.5.2">
      <metaDataId>7</metaDataId>
      <name>ehrs</name>
      <properties class="com.mirth.connect.connectors.http.HttpDispatcherProperties" version="3.5.2">
        <pluginProperties/>
        <destinationConnectorProperties version="3.5.2">
          <queueEnabled>false</queueEnabled>
          <sendFirst>false</sendFirst>
          <retryIntervalMillis>10000</retryIntervalMillis>
          <regenerateTemplate>false</regenerateTemplate>
          <retryCount>0</retryCount>
          <rotate>false</rotate>
          <includeFilterTransformer>false</includeFilterTransformer>
          <threadCount>1</threadCount>
          <threadAssignmentVariable></threadAssignmentVariable>
          <validateResponse>false</validateResponse>
          <resourceIds class="linked-hash-map">
            <entry>
              <string>Default Resource</string>
              <string>[Default Resource]</string>
            </entry>
          </resourceIds>
          <queueBufferSize>1000</queueBufferSize>
          <reattachAttachments>true</reattachAttachments>
        </destinationConnectorProperties>
        <host>${base_url}/api/v1/ehrs</host>
        <useProxyServer>false</useProxyServer>
        <proxyAddress></proxyAddress>
        <proxyPort></proxyPort>
        <method>get</method>
        <headers class="linked-hash-map">
          <entry>
            <string>Authorization</string>
            <list>
              <string>Bearer ${token}</string>
            </list>
          </entry>
        </headers>
        <parameters class="linked-hash-map">
          <entry>
            <string>format</string>
            <list>
              <string>json</string>
            </list>
          </entry>
        </parameters>
        <responseXmlBody>false</responseXmlBody>
        <responseParseMultipart>true</responseParseMultipart>
        <responseIncludeMetadata>false</responseIncludeMetadata>
        <responseBinaryMimeTypes></responseBinaryMimeTypes>
        <responseBinaryMimeTypesRegex>false</responseBinaryMimeTypesRegex>
        <multipart>false</multipart>
        <useAuthentication>false</useAuthentication>
        <authenticationType>Basic</authenticationType>
        <usePreemptiveAuthentication>false</usePreemptiveAuthentication>
        <username></username>
        <password></password>
        <content></content>
        <contentType>text/plain</contentType>
        <dataTypeBinary>false</dataTypeBinary>
        <charset>UTF-8</charset>
        <socketTimeout>10000</socketTimeout>
      </properties>
      <transformer version="3.5.2">
        <elements/>
        <inboundDataType>RAW</inboundDataType>
        <outboundDataType>RAW</outboundDataType>
        <inboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </inboundProperties>
        <outboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </outboundProperties>
      </transformer>
      <responseTransformer version="3.5.2">
        <elements>
          <com.mirth.connect.plugins.javascriptstep.JavaScriptStep>
            <name>New Step</name>
            <sequenceNumber>0</sequenceNumber>
            <script>var resp = JSON.parse(msg);

logger.info('ehrs: '+ msg);

resp.ehrs.forEach( function(element, index, array) {

   logger.info(element.uid);
} );</script>
          </com.mirth.connect.plugins.javascriptstep.JavaScriptStep>
        </elements>
        <inboundTemplate encoding="base64"></inboundTemplate>
        <outboundTemplate encoding="base64"></outboundTemplate>
        <inboundDataType>RAW</inboundDataType>
        <outboundDataType>RAW</outboundDataType>
        <inboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </inboundProperties>
        <outboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </outboundProperties>
      </responseTransformer>
      <filter version="3.5.2">
        <elements/>
      </filter>
      <transportName>HTTP Sender</transportName>
      <mode>DESTINATION</mode>
      <enabled>true</enabled>
      <waitForPrevious>true</waitForPrevious>
    </connector>
    <connector version="3.5.2">
      <metaDataId>6</metaDataId>
      <name>query data diabetes</name>
      <properties class="com.mirth.connect.connectors.http.HttpDispatcherProperties" version="3.5.2">
        <pluginProperties/>
        <destinationConnectorProperties version="3.5.2">
          <queueEnabled>false</queueEnabled>
          <sendFirst>false</sendFirst>
          <retryIntervalMillis>10000</retryIntervalMillis>
          <regenerateTemplate>false</regenerateTemplate>
          <retryCount>0</retryCount>
          <rotate>false</rotate>
          <includeFilterTransformer>false</includeFilterTransformer>
          <threadCount>1</threadCount>
          <threadAssignmentVariable></threadAssignmentVariable>
          <validateResponse>false</validateResponse>
          <resourceIds class="linked-hash-map">
            <entry>
              <string>Default Resource</string>
              <string>[Default Resource]</string>
            </entry>
          </resourceIds>
          <queueBufferSize>1000</queueBufferSize>
          <reattachAttachments>true</reattachAttachments>
        </destinationConnectorProperties>
        <host>${base_url}/api/v1/queries/2dc60054-feef-45d6-8c06-6680de48889c/execute</host>
        <useProxyServer>false</useProxyServer>
        <proxyAddress></proxyAddress>
        <proxyPort></proxyPort>
        <method>get</method>
        <headers class="linked-hash-map">
          <entry>
            <string>Authorization</string>
            <list>
              <string>Bearer ${token}</string>
            </list>
          </entry>
        </headers>
        <parameters class="linked-hash-map">
          <entry>
            <string>format</string>
            <list>
              <string>json</string>
            </list>
          </entry>
          <entry>
            <string>ehrUid</string>
            <list>
              <string>2f625da8-4cd1-44de-b159-aa88da6039a9</string>
            </list>
          </entry>
        </parameters>
        <responseXmlBody>false</responseXmlBody>
        <responseParseMultipart>true</responseParseMultipart>
        <responseIncludeMetadata>false</responseIncludeMetadata>
        <responseBinaryMimeTypes></responseBinaryMimeTypes>
        <responseBinaryMimeTypesRegex>false</responseBinaryMimeTypesRegex>
        <multipart>false</multipart>
        <useAuthentication>false</useAuthentication>
        <authenticationType>Basic</authenticationType>
        <usePreemptiveAuthentication>false</usePreemptiveAuthentication>
        <username></username>
        <password></password>
        <content></content>
        <contentType>text/plain</contentType>
        <dataTypeBinary>false</dataTypeBinary>
        <charset>UTF-8</charset>
        <socketTimeout>10000</socketTimeout>
      </properties>
      <transformer version="3.5.2">
        <elements/>
        <inboundDataType>RAW</inboundDataType>
        <outboundDataType>RAW</outboundDataType>
        <inboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </inboundProperties>
        <outboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </outboundProperties>
      </transformer>
      <responseTransformer version="3.5.2">
        <elements>
          <com.mirth.connect.plugins.javascriptstep.JavaScriptStep>
            <name>New Step</name>
            <sequenceNumber>0</sequenceNumber>
            <script>var resp = JSON.parse(msg);

logger.info('query results: '+ msg);

for (ehr_uid in resp.results)
{
   logger.info(ehr_uid);

   resp.results[ehr_uid].forEach( function(compo, index, array) {

      logger.info(compo.uid);
      logger.info(compo.archetypeId);
   } );
}</script>
          </com.mirth.connect.plugins.javascriptstep.JavaScriptStep>
        </elements>
        <inboundTemplate encoding="base64"></inboundTemplate>
        <outboundTemplate encoding="base64"></outboundTemplate>
        <inboundDataType>RAW</inboundDataType>
        <outboundDataType>RAW</outboundDataType>
        <inboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </inboundProperties>
        <outboundProperties class="com.mirth.connect.plugins.datatypes.raw.RawDataTypeProperties" version="3.5.2">
          <batchProperties class="com.mirth.connect.plugins.datatypes.raw.RawBatchProperties" version="3.5.2">
            <splitType>JavaScript</splitType>
            <batchScript></batchScript>
          </batchProperties>
        </outboundProperties>
      </responseTransformer>
      <filter version="3.5.2">
        <elements/>
      </filter>
      <transportName>HTTP Sender</transportName>
      <mode>DESTINATION</mode>
      <enabled>true</enabled>
      <waitForPrevious>true</waitForPrevious>
    </connector>
  </destinationConnectors>
  <preprocessingScript>// Modify the message variable below to pre process data
return message;</preprocessingScript>
  <postprocessingScript>// This script executes once after a message has been processed
// Responses returned from here will be stored as "Postprocessor" in the response map
return;</postprocessingScript>
  <deployScript>// This script executes once when the channel is deployed
// You only have access to the globalMap and globalChannelMap here to persist data

globalChannelMap.put('base_url', 'http://server001.cloudehrserver.com');
globalChannelMap.put('token','eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFwaWtleWl2bWlmYXRpY3h5dmh3eHZodXVhYmhhc2Z5bWxrYWVwaGZubWhpZ2NrdmxmcWZ1cHpkIiwiZXh0cmFkYXRhIjp7Im9yZ2FuaXphdGlvbiI6IjcyMzcyMiIsIm9yZ191aWQiOiI1NzkxOTk5MS1mYWExLTQ0YzQtODM2ZC1kYTgyY2I4MjkwZGMifSwiaXNzdWVkX2F0IjoiMjAxOC0wNS0wMlQxNToxMjozMy4xOTktMDM6MDAifQ==.33IX3XSXDoxu3sWPI68VKZfgxQN++G3iyaW4Nbd00ls=')

return;</deployScript>
  <undeployScript>// This script executes once when the channel is undeployed
// You only have access to the globalMap and globalChannelMap here to persist data
return;</undeployScript>
  <properties version="3.5.2">
    <clearGlobalChannelMap>true</clearGlobalChannelMap>
    <messageStorageMode>DEVELOPMENT</messageStorageMode>
    <encryptData>false</encryptData>
    <removeContentOnCompletion>false</removeContentOnCompletion>
    <removeOnlyFilteredOnCompletion>false</removeOnlyFilteredOnCompletion>
    <removeAttachmentsOnCompletion>false</removeAttachmentsOnCompletion>
    <initialState>STOPPED</initialState>
    <storeAttachments>false</storeAttachments>
    <metaDataColumns>
      <metaDataColumn>
        <name>SOURCE</name>
        <type>STRING</type>
        <mappingName>mirth_source</mappingName>
      </metaDataColumn>
      <metaDataColumn>
        <name>TYPE</name>
        <type>STRING</type>
        <mappingName>mirth_type</mappingName>
      </metaDataColumn>
    </metaDataColumns>
    <attachmentProperties version="3.5.2">
      <type>None</type>
      <properties/>
    </attachmentProperties>
    <resourceIds class="linked-hash-map">
      <entry>
        <string>Default Resource</string>
        <string>[Default Resource]</string>
      </entry>
    </resourceIds>
  </properties>
  <exportData>
    <metadata>
      <enabled>true</enabled>
      <lastModified>
        <time>1527536293570</time>
        <timezone>America/Montevideo</timezone>
      </lastModified>
      <pruningSettings>
        <archiveEnabled>true</archiveEnabled>
      </pruningSettings>
    </metadata>
    <channelTags>
      <channelTag>
        <id>ae17732c-874d-4c3c-9795-d3fa41c2b3e9</id>
        <name>clase2</name>
        <channelIds>
          <string>0ec7ab6e-f548-426a-99f6-18858cefc2d5</string>
          <string>517d4a5b-597c-46db-9f6b-d9799ca43ea6</string>
          <string>375900e8-4214-4c96-a46f-2b4046514e9a</string>
          <string>9e7ac5d5-16dd-426c-a118-f6863624e735</string>
          <string>4eba1e2f-95cd-42c7-a326-2c392949658c</string>
          <string>2f826fbf-f7bb-40b7-a2ff-64d367acc0ea</string>
          <string>b16b0f5f-55a5-41b3-96c3-cbe40c8d8853</string>
          <string>5742662b-8601-4c45-910f-a772ee267945</string>
        </channelIds>
        <backgroundColor>
          <red>255</red>
          <green>0</green>
          <blue>0</blue>
          <alpha>255</alpha>
        </backgroundColor>
      </channelTag>
    </channelTags>
  </exportData>
</channel>


text:
These HTML5 tags should pass through just fine.

hello

head

footsies

navigation

read me

ignore me

read
  me

  ignore me

the end

    Foo

    Bar

    Foo

    Bar

    Bar

<audio class="podcastplayer" controls>
  <source src="foobar.mp3" type="audio/mp3" preload="none"></source>
  <source src="foobar.off" type="audio/ogg" preload="none"></source>
</audio>

<video src="foo.ogg">
  <track kind="subtitles" src="foo.en.vtt" srclang="en" label="English">
  <track kind="subtitles" src="foo.sv.vtt" srclang="sv" label="Svenska">
</video>

<address>My street</address>

<canvas id="canvas" width="300" height="300">
  Sorry, your browser doesn't support the <canvas> element.
</canvas>

Caption for the awesome picture

<hgroup>

Main title

Secondary title

</hgroup>

<output name="result"></output>


text:
namespace Blam::Math
{
	struct RealVector3D
	{
		float I;
		float J;
		float K;

		RealVector3D();
		RealVector3D(const float i, const float j, const float k);

		bool operator==(const RealVector3D &other) const;
		bool operator!=(const RealVector3D &other) const;

		explicit operator const float *() const;

		RealVector3D &operator+=(const RealVector3D &other);
		RealVector3D &operator+=(const float other);
		RealVector3D operator+(const RealVector3D &other) const;
		RealVector3D operator+(const float other) const;
		friend RealVector3D operator+(const float a, const RealVector3D &b);

		RealVector3D &operator-=(const RealVector3D &other);
		RealVector3D &operator-=(const float other);
		RealVector3D operator-(const RealVector3D &other) const;
		RealVector3D operator-(const float other) const;
		friend RealVector3D operator-(const float a, const RealVector3D &b);

		RealVector3D &operator*=(const RealVector3D &other);
		RealVector3D &operator*=(const float other);
		RealVector3D operator*(const RealVector3D &other) const;
		RealVector3D operator*(const float other) const;
		friend RealVector3D operator*(const float a, const RealVector3D &b);

		RealVector3D &operator/=(const RealVector3D &other);
		RealVector3D &operator/=(const float other);
		RealVector3D operator/(const RealVector3D &other) const;
		RealVector3D operator/(const float other) const;
		friend RealVector3D operator/(const float a, const RealVector3D &b);
	};
}


text:
#ifdef __cplusplus
extern "C" {
#endif

#ifndef PUTRES_H
#define PUTRES_H

#include <stddef.h>
#include "arena.h"
#include "oec_values.h"
#define T PutRes
struct putres_T {
    //oe_time expiretime;
    oe_id   lease_id;
};
typedef struct putres_T *T;

T PutRes_new(Arena_T arena);

//RES PUT corid:number expiretime:number lease_id:number
//extern void    PutRes_set_expiretime(T, oe_time expiretime);
//extern oe_time PutRes_get_expiretime(T);
extern void    PutRes_set_lease_id(T, oe_id lid);
extern oe_id   PutRes_get_lease_id(T);

#undef T
#endif

#ifdef __cplusplus
}
#endif


text:
layout: post
title: "openSUSE.Asia Summit 2016 Venue Direction"
description: "openSUSE.Asia Summit 2016 Venue Direction"
comments: false
keywords: "openSUSE.Asia Summit 2016, openSUSE, Venue Direction"
---
* [openSUSE.Asia Summit 2016 venue direction from airport](https://www.youtube.com/watch?v=_C8kjy6xJ6c)

* [openSUSE.Asia Summit 2016 venue direction from Tugu Station](https://www.youtube.com/watch?v=YRFWC0IB7lA)


text:
class CGunTarget : public CBaseToggle
{
	DECLARE_CLASS( CGunTarget, CBaseToggle );

public:

	virtual void Spawn( void );
	virtual void Activate( void );
	bool CreateVPhysics( void );

	virtual int BloodColor( void ) { return DONT_BLEED; }

#if defined( HL2_DLL )
	virtual Class_T Classify( void ) { return CLASS_MILITARY; }
#elif defined( HL1_DLL )
	virtual Class_T Classify( void ) { return CLASS_MACHINE; }
#else
	virtual Class_T Classify( void ) { return CLASS_NONE; }
#endif
	virtual int OnTakeDamage( const CTakeDamageInfo &info );
	virtual Vector BodyTarget( const Vector &posSrc, bool bNoisy = true ) { return GetAbsOrigin(); }

	// Input handlers
	void InputStart( inputdata_t &inputdata );
	void InputStop( inputdata_t &inputdata );
	void InputToggle( inputdata_t &inputdata );

	DECLARE_DATADESC();

protected:

	void Next( void );
	void Start( void );
	void Wait( void );
	void Stop( void );

private:

	bool			m_on;
	EHANDLE			m_hTargetEnt;

	// Outputs
	COutputEvent	m_OnDeath;
};

LINK_ENTITY_TO_CLASS( func_guntarget, CGunTarget );

BEGIN_DATADESC( CGunTarget )

	DEFINE_FIELD( m_on, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_hTargetEnt, FIELD_EHANDLE ),

	// Function Pointers
	DEFINE_FUNCTION( Next ),
	DEFINE_FUNCTION( Start ),
	DEFINE_FUNCTION( Wait ),

	// Inputs
	DEFINE_INPUTFUNC( FIELD_VOID, "Start", InputStart ),
	DEFINE_INPUTFUNC( FIELD_VOID, "Stop", InputStop ),
	DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),

	// Outputs
	DEFINE_OUTPUT(m_OnDeath, "OnDeath"),

END_DATADESC()

void CGunTarget::Spawn( void )
{
	SetSolid( SOLID_BSP );
	SetMoveType( MOVETYPE_PUSH );

	SetModel( STRING( GetModelName() ) );

	if ( m_flSpeed == 0 )
		m_flSpeed = 100;

	// Don't take damage until "on"
	m_takedamage = DAMAGE_NO;
	AddFlag( FL_NPC );

	m_on = false;
	m_iMaxHealth = m_iHealth;

	if ( HasSpawnFlags(FGUNTARGET_START_ON) )
	{
		SetMoveDone( &CGunTarget::Start );
		SetMoveDoneTime( 0.3 );
	}
	CreateVPhysics();
}

bool CGunTarget::CreateVPhysics( void )
{
	VPhysicsInitShadow( false, false );
	return true;
}

void CGunTarget::Activate( void )
{
	BaseClass::Activate();

	CBaseEntity	*pTarg;
	// now find our next target
	pTarg = GetNextTarget();
	if ( pTarg )
	{
		m_hTargetEnt = pTarg;
		Vector nextPos = pTarg->GetAbsOrigin();
		Teleport( &nextPos, NULL, NULL );
	}
}

void CGunTarget::Start( void )
{
	m_takedamage = DAMAGE_YES;
	AddFlag( FL_AIMTARGET );
	m_hTargetEnt = GetNextTarget();
	if ( m_hTargetEnt == NULL )
		return;
	m_iHealth = m_iMaxHealth;
	Next();
}

void CGunTarget::Next( void )
{
	SetThink( NULL );

	m_hTargetEnt = GetNextTarget();
	CBaseEntity *pTarget = m_hTargetEnt;

	if ( !pTarget )
	{
		Stop();
		return;
	}

	SetMoveDone( &CGunTarget::Wait );
	LinearMove( pTarget->GetLocalOrigin(), m_flSpeed );
}

void CGunTarget::Wait( void )
{
	CBaseEntity *pTarget = m_hTargetEnt;

	if ( !pTarget )
	{
		Stop();
		return;
	}

	variant_t emptyVariant;
	pTarget->AcceptInput( "InPass", this, this, emptyVariant, 0 );

	m_flWait = pTarget->GetDelay();

	m_target = pTarget->m_target;
	SetMoveDone( &CGunTarget::Next );
	if (m_flWait != 0)
	{// -1 wait will wait forever!
		SetMoveDoneTime( m_flWait );
	}
	else
	{
		Next();// do it RIGHT now!
	}
}

void CGunTarget::Stop( void )
{
	SetAbsVelocity( vec3_origin );
	SetMoveDoneTime( -1 );
	m_takedamage = DAMAGE_NO;
}

int	CGunTarget::OnTakeDamage( const CTakeDamageInfo &info )
{
	if ( m_iHealth > 0 )
	{
		m_iHealth -= info.GetDamage();
		if ( m_iHealth <= 0 )
		{
			m_iHealth = 0;
			Stop();

			m_OnDeath.FireOutput( info.GetInflictor(), this );
		}
	}
	return 0;
}

//-----------------------------------------------------------------------------
// Purpose: Input handler that starts the target moving.
//-----------------------------------------------------------------------------
void CGunTarget::InputStart( inputdata_t &inputdata )
{
	Start();
}

//-----------------------------------------------------------------------------
// Purpose: Input handler that stops the target from moving.
//-----------------------------------------------------------------------------
void CGunTarget::InputStop( inputdata_t &inputdata )
{
	Stop();
}

//-----------------------------------------------------------------------------
// Purpose: Input handler that toggles the start/stop state of the target.
//-----------------------------------------------------------------------------
void CGunTarget::InputToggle( inputdata_t &inputdata )
{
	if ( m_on )
	{
		Stop();
	}
	else
	{
		Start();
	}
}


text:
[PPO](https://arxiv.org/abs/1707.06347) is a model-free on-policy RL algorithm that works well for both discrete and continuous action space environments. PPO utilizes an actor-critic framework, where there are two networks, an actor (policy network) and critic network (value function).

There are two formulations of PPO, which are both implemented in RLlib. The first formulation of PPO imitates the prior paper [TRPO](https://arxiv.org/abs/1502.05477) without the complexity of second-order optimization. In this formulation, for every iteration, an old version of an actor-network is saved and the agent seeks to optimize the RL objective while staying close to the old policy. This makes sure that the agent does not destabilize during training. In the second formulation, To mitigate destructive large policy updates, an issue discovered for vanilla policy gradient methods, PPO introduces the surrogate objective, which clips large action probability ratios between the current and old policy. Clipping has been shown in the paper to significantly improve training stability and speed.

## Distributed PPO Algorithms

PPO is a core algorithm in RLlib due to its ability to scale well with the number of nodes. In RLlib, we provide various implementation of distributed PPO, with different underlying execution plans, as shown below.

Distributed baseline PPO is a synchronous distributed RL algorithm. Data collection nodes, which represent the old policy, gather data synchronously to create a large pool of on-policy data from which the agent performs minibatch gradient descent on.

On the other hand, Asychronous PPO (APPO) opts to imitate IMPALA as its distributed execution plan. Data collection nodes gather data asynchronously, which are collected in a circular replay buffer. A target network and doubly-importance sampled surrogate objective is introduced to enforce training stability in the asynchronous data-collection setting.

Lastly, Decentralized Distributed PPO (DDPPO) removes the assumption that gradient-updates must be done on a central node.  Instead, gradients are computed remotely on each data collection node and all-reduced at each mini-batch using torch distributed. This allows each worker's GPU to be used both for sampling and for training.

## Documentation & Implementation:

1) Proximal Policy Optimization (PPO).

    **[Detailed Documentation](https://docs.ray.io/en/master/rllib-algorithms.html#ppo)**

    **[Implementation](https://github.com/ray-project/ray/blob/master/rllib/agents/ppo/ppo.py)**

2) [Asynchronous Proximal Policy Optimization (APPO)](https://arxiv.org/abs/1912.00167).

    **[Detailed Documentation](https://docs.ray.io/en/master/rllib-algorithms.html#appo)**

    **[Implementation](https://github.com/ray-project/ray/blob/master/rllib/agents/ppo/appo.py)**

3) [Decentralized Distributed Proximal Policy Optimization (DDPPO)](https://arxiv.org/abs/1911.00357)

    **[Detailed Documentation](https://docs.ray.io/en/master/rllib-algorithms.html#decentralized-distributed-proximal-policy-optimization-dd-ppo)**

    **[Implementation](https://github.com/ray-project/ray/blob/master/rllib/agents/ppo/ddppo.py)**


text:
=pod

=head1 NAME

jobs_gen_tests.pl -- output a list of invocations of the test_gen_tests.sh script, one line per each bug.

=head1 SYNOPSIS

  jobs_gen_tests.pl

=head1 DESCRIPTION

Parses all active-bugs csv files and outputs a list of invocations of the
test_gen_tests.sh script. Running this list of jobs, e.g., using GNU parallel,
runs every supported test generator on every bug.

=cut
use warnings;
use strict;

use FindBin;
use File::Basename;
use Cwd qw(abs_path);
use Getopt::Std;
use Pod::Usage;

use lib abs_path("$FindBin::Bin/../core");
use Constants;
use Project;

#
# Process arguments and issue usage message if necessary.
#

# Read all project modules
opendir(my $dir, "$CORE_DIR/Project") or die "Cannot open directory: $!";
my @files = readdir($dir);
closedir($dir);

# For each project module, instantiate project and determine its name and number
# of bugs.
my $total = 0;
my @projects = ();
for my $file (@files) {
  $file =~ "^([^.]+)\.pm\$" or next;
  my $pid=$1;
  my $project = Project::create_project($pid);
  my $name = $project->{prog_name};
  my @bug_ids = $project->get_bug_ids();
  for my $id (@bug_ids) {
    print("./test_gen_tests.sh -p $pid -b $id \n");
  }
}


text:
layout: post
microblog: true
audio:
photo:
date: 2011-09-19 07:37:58 -0600
guid: http://craigmcclellan.micro.blog/2011/09/19/t115781682719756289.html
---
"@laura_mcclellan: @carlcartee @hebcartee happy anniversary!! Thankful for your relationship and influence in our marriage." Truth.


text:
struct default_init_tag;

class poi::sl::image::ImageHeaderPICT
    : public virtual ::java::lang::Object
{

public:
    typedef ::java::lang::Object super;
    static constexpr int32_t PICT_HEADER_OFFSET { int32_t(512) };
    static constexpr double DEFAULT_RESOLUTION { 72.0 };

private:
    static ::int8_tArray* V2_HEADER_;
    ::java::awt::Rectangle* bounds {  };
    double hRes {  }, vRes {  };
protected:
    void ctor(::int8_tArray* data, int32_t off);

public:
    virtual ::java::awt::Dimension* getSize();
    virtual ::java::awt::Rectangle* getBounds();

private:
    static int32_t readUnsignedShort(::int8_tArray* data, int32_t offset);
    static double readFixedPoint(::int8_tArray* data, int32_t offset);

    // Generated

public:
    ImageHeaderPICT(::int8_tArray* data, int32_t off);
protected:
    ImageHeaderPICT(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();
    static void clinit();

private:
    static ::int8_tArray*& V2_HEADER();
    virtual ::java::lang::Class* getClass0();
};


text:
http://allouis.github.io/minivents/

# API

`on` : Listen to event. Params { type:`String`, callback:`Function` | context:`Object` }. Returns `target`.

`off` : Stop listening to event. Params { type:`String` | callback:`Function` }. Returns `target`.

`emit`: Emit event. Params { type:`String` | data:`Object` }. Returns `target`.

# Constructor Example
```javascript
var sandbox = new Events();

sandbox.on("event", function(){
    // do stuff
});

sandbox.emit("event"); //does stuff

sandbox.off("event");

sandbox.emit("event"); //does not do stuff
```
# Mixin Example
```javascript
var sandbox = {
    otherStuff: true
};

Events(sandbox);

sandbox.on("event", function(){
    // do stuff
});

sandbox.emit("event"); //does stuff

sandbox.off("event");

sandbox.emit("event"); //does not do stuff
```


text:
package org.wso2.carbon.databridge.agent.util;

import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
import org.wso2.carbon.databridge.agent.conf.DataEndpointConfiguration;
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A Util class which holds all the utility processing methods in the data publisher operation.
 */

public class DataPublisherUtil {

    /**
     * Making as private to avoid the instantiation of the class.
     */
    private DataPublisherUtil() {
    }

    /**
     * Process and extracts the receiver Groups from the string of URL set pattern passed in.
     *
     * @param urlSet receiverGroups URL set
     * @return List of Receiver groups
     * @throws DataEndpointConfigurationException
     */
    public static ArrayList<Object[]> getEndpointGroups(String urlSet)
            throws DataEndpointConfigurationException {
        ArrayList<String> urlGroups = new ArrayList<String>();
        ArrayList<Object[]> endPointGroups = new ArrayList<Object[]>();
        Pattern regex = Pattern.compile("\\{.*?\\}");
        Matcher regexMatcher = regex.matcher(urlSet);
        while (regexMatcher.find()) {
            urlGroups.add(regexMatcher.group().replace("{", "").replace("}", ""));
        }
        if (urlGroups.size() == 0) {
            urlGroups.add(urlSet.replace("{", "").replace("}", ""));
        }
        for (String aURLGroup : urlGroups) {
            endPointGroups.add(getEndpoints(aURLGroup));
        }
        return endPointGroups;
    }

    /**
     * Returns an object array which has first element as boolean
     * for specify the URLs are fail over configuration or LB configuration.
     * From the 2nd element onwards the object array will hold the separated URLs
     *
     * @param aURLGroup one receiver group's URL
     * @return First element - boolean (isFailOver), next elements are each URLs
     * @throws DataEndpointConfigurationException
     */
    private static Object[] getEndpoints(String aURLGroup)
            throws DataEndpointConfigurationException {
        boolean isLBURL = false, isFailOverURL = false;
        String[] urls;
        if (aURLGroup.contains(",")) isLBURL = true;
        if (aURLGroup.contains("|")) isFailOverURL = true;

        if (isLBURL && isFailOverURL) {
            throw new DataEndpointConfigurationException("Invalid data endpoints URL set provided : " + aURLGroup
                    + ", a URL group can be configured as failover OR load balancing endpoints.");
        } else if (isLBURL) {
            urls = aURLGroup.split(DataEndpointConstants.LB_URL_GROUP_SEPARATOR);
        } else if (isFailOverURL) {
            urls = aURLGroup.split(DataEndpointConstants.FAILOVER_URL_GROUP_SEPARATOR);
        } else {
            urls = new String[]{aURLGroup};
        }
        Object[] endpoint = new Object[urls.length + 1];
        endpoint[0] = isFailOverURL;
        for (int i = 0; i < urls.length; i++) {
            endpoint[i + 1] = urls[i].trim();
        }
        return endpoint;
    }

    /**
     * Validate whether the receiverGroup and authenticationGroups are matching with pattern.
     * Basically if the receiver groups has been configured to be in the failover pattern,
     * then the authentication URL also needs to be in the same way. Hence this method validates
     * the provided receiverGroups, and authenticationGroup.
     *
     * @param receiverGroups List of Receiver groups
     * @param authGroups     List of Authentication groups.
     * @throws DataEndpointConfigurationException
     */
    public static void validateURLs(ArrayList receiverGroups, ArrayList authGroups)
            throws DataEndpointConfigurationException {
        if (receiverGroups.size() == authGroups.size()) {
            for (int i = 0; i < receiverGroups.size(); i++) {
                Object[] receiverGroup = (Object[]) receiverGroups.get(i);
                Object[] authGroup = (Object[]) authGroups.get(i);

                if (receiverGroup.length == authGroup.length) {
                    boolean isFailOver = (Boolean) receiverGroup[0];
                    boolean isAuthFailOver = (Boolean) ((Object[]) receiverGroups.get(i))[0];
                    if (isFailOver != isAuthFailOver) {
                        throw new DataEndpointConfigurationException("Receiver and authentication URL group set " +
                                "doesn't match. Receiver URL group: " + getURLSet(receiverGroup)
                                + " is configured as failOver : " + isFailOver + ", but Authentication URL group: "
                                + getURLSet(authGroup) + " is configured as failOver :" + isAuthFailOver);
                    }
                } else {
                    throw new DataEndpointConfigurationException("Receiver and authentication URL group set doesn't match. " +
                            "Receiver URL group: " + getURLSet(receiverGroup) + ", but Authentication URL group: "
                            + getURLSet(authGroup));
                }
            }
        } else {
            throw new DataEndpointConfigurationException("Receiver and authentication URL set doesn't match. " +
                    "Receiver URL groups: " + receiverGroups.size() + ", but Authentication URL groups: "
                    + authGroups.size());
        }
    }

    /**
     * Returns the URL set string based on the URLs provided. The first element of the array is
     * a boolean which indicates whether it's failover or load balancing.
     *
     * @param urlGroup Array of url and the first element of array should specify
     *                 whether its load balancing or fail over
     * @return String representation of URL set.
     */
    private static String getURLSet(Object[] urlGroup) {
        boolean isFailOver = (Boolean) urlGroup[0];
        String urlSet = "";
        for (int i = 1; i < urlGroup.length; i++) {
            urlSet += urlGroup[i];
            if (i != urlGroup.length - 1) {
                if (isFailOver) {
                    urlSet += DataEndpointConstants.FAILOVER_URL_GROUP_SEPARATOR;
                } else {
                    urlSet += DataEndpointConstants.LB_URL_GROUP_SEPARATOR;
                }
            }
        }
        return urlSet;
    }

    /**
     * Extracts and return the protocol, host, port elements from the URL.
     *
     * @param url String of URL that needs to be processed.
     * @return Array which has elements - protocol, host, and port in the given order.
     */
    public static String[] getProtocolHostPort(String url) throws DataEndpointConfigurationException {
        String[] keyElements = url.split(DataEndpointConstants.SEPARATOR);
        String[] urlElements = keyElements[0].split(":");
        if (urlElements.length != 3) {
            throw new DataEndpointConfigurationException("Invalid URL is provided :" + url +
                    ". Receiver URL property should take the format : " + "protocol://host:port");
        }
        return new String[]{urlElements[0], urlElements[1].replace("//", ""), urlElements[2]};
    }

    /**
     * Deduce the default authentication URL based on the receiver URL passed in.
     *
     * @param receiverURL receiver URL for which it's required to get the authentication URL.
     * @return default authentication URL.
     */
    public static String getDefaultAuthUrl(String receiverURL) throws DataEndpointConfigurationException {
        String[] urlElements = getProtocolHostPort(receiverURL);
        int port = Integer.parseInt(urlElements[2]);
        String host = urlElements[1];
        return DataEndpointConfiguration.Protocol.SSL.toString() + "://" + host + ":" +
                (port + DataEndpointConstants.DEFAULT_AUTH_PORT_OFFSET);
    }

    /**
     * Deduce the default authentication URL set based on the receiver URL set passed in.
     *
     * @param receiverURLSet receiver URL set for which it's required to get the authentication URL set.
     * @return default authentication URL set.
     */
    public static String getDefaultAuthURLSet(String receiverURLSet) throws DataEndpointConfigurationException {
        ArrayList<Object[]> receiverURLGroups = DataPublisherUtil.getEndpointGroups(receiverURLSet);
        String authURLSet = "";
        for (int i = 0; i < receiverURLGroups.size(); i++) {
            Object[] receiverGroup = receiverURLGroups.get(i);
            boolean failOver = (Boolean) receiverGroup[0];
            authURLSet += "{";
            for (int j = 1; j < receiverGroup.length; j++) {
                authURLSet += DataPublisherUtil.getDefaultAuthUrl(receiverGroup[j].toString());
                if (j != receiverGroup.length - 1) {
                    if (failOver) {
                        authURLSet += DataEndpointConstants.FAILOVER_URL_GROUP_SEPARATOR;
                    } else {
                        authURLSet += DataEndpointConstants.LB_URL_GROUP_SEPARATOR;
                    }
                }
            }
            authURLSet += "}";
            if (i != receiverURLGroups.size() - 1) {
                authURLSet += ",";
            }
        }
        return authURLSet;
    }
}


text:
module Support
  module ScanMatcher
    extend RSpec::Matchers::DSL

    def scan(pattern, options = {})
      give_scan_result(:scan, pattern, options)
    end

    def check(pattern, options = {})
      give_scan_result(:check, pattern, options)
    end

    def scan_until(pattern, options = {})
      give_scan_result(:scan_until, pattern, options)
    end

    def check_until(pattern, options = {})
      give_scan_result(:check_until, pattern, options)
    end

    matcher :give_scan_result do |method_name, pattern, options = {}|
      def result_expectations
        @result_expectations ||= []
      end

      def expect_result(description, expected, &block)
        result_expectations << Proc.new do |result|
          if !block.call(result)
            "expected %p to %s %p matching %s" % [ result.scanner, method_name, pattern, description ]
          end
        end
      end

      match do |scanner|
        scanned = scanner.public_send(method_name, pattern, options)
        scanned and result_expectations.all? { |e| !e.call(scanned) }
      end

      chain(:matching_substring) do |substring|
        expected_result("the substring %p" % substring) { |r| r.to_s == substring }
      end

      chain(:matching_length) do |length|
        expected_result("%d characters" % length) { |r| r.length == length }
      end

      chain(:matching_params) do |params|
        expected_result("with params %p" % [params]) { |r| r.params == params }
      end

      failure_message do |scanner|
        if scanned = scanner.public_send(method_name, pattern, options = {})
          message  = result_expectations.inject(nil) { |m,e| m || e.call(scanned) }
        end
        message || "expected %p to %s %p" % [ scanner, method_name, pattern ]
      end

      failure_message_when_negated do |scanner|
        "expected %p not to %s %p" % [ scanner, method_name, pattern ]
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     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.
-->

<favorites xmlns:launcher="http://schemas.android.com/apk/res/com.sec.android.app.launcher">
    <home>
        <!-- Far-left screen [0] -->

        <!-- Far-left screen [1] -->
        <appwidget
        launcher:packageName="com.sec.android.widgetapp.alarmclock"
        launcher:className="com.sec.android.widgetapp.alarmclock.ClockAlarmWidgetProvider"
        launcher:screen="1"
        launcher:x="0"
        launcher:y="0"
        launcher:spanX="4"
        launcher:spanY="2" />

        <!-- Far-left screen [2] -->
        <appwidget
        launcher:packageName="com.sec.android.widgetapp.digitalclock"
        launcher:className="com.sec.android.widgetapp.digitalclock.DigitalClockWidgetProvider"
        launcher:screen="2"
        launcher:x="0"
        launcher:y="0"
        launcher:spanX="4"
        launcher:spanY="1" />

        <appwidget
        launcher:packageName="com.sec.android.widgetapp.favoriteswidget"
        launcher:className="com.sec.android.widgetapp.favoriteswidget.SeniorFavoriteWidgetProviderSmall"
        launcher:screen="2"
        launcher:x="0"
        launcher:y="2"
        launcher:spanX="4"
        launcher:spanY="2" />

        <!-- Far-left screen [3] -->
        <appwidget
        launcher:packageName="com.sec.android.favoriteappwidget"
        launcher:className="com.sec.android.favoriteappwidget.FavoriteWidgetProvider"
        launcher:screen="3"
        launcher:x="0"
        launcher:y="0"
        launcher:spanX="4"
        launcher:spanY="4" />

        <!-- Far-left screen [4] -->
        <appwidget
        launcher:packageName="com.android.settings"
        launcher:className="com.android.settings.favoritesettingswidget.FavoriteSettingsWidget"
        launcher:screen="4"
        launcher:x="0"
        launcher:y="0"
        launcher:spanX="4"
        launcher:spanY="4" />

    </home>
    <!-- Hotseat (We use the screen as the position of the item in the hotseat) -->
    <hotseat>
        <favorite
            launcher:packageName="com.android.contacts"
            launcher:className="com.android.contacts.activities.DialtactsActivity"
            launcher:screen="0" />
        <favorite
            launcher:packageName="com.android.contacts"
            launcher:className="com.android.contacts.activities.PeopleActivity"
            launcher:screen="1" />
        <favorite
            launcher:packageName="com.android.mms"
            launcher:className="com.android.mms.ui.ConversationComposer"
            launcher:screen="2" />
        <favorite
            launcher:packageName="com.android.browser"
            launcher:className="com.android.browser.BrowserActivity"
            launcher:screen="3" />
     </hotseat>
</favorites>


text:
Do you wish that you could somehow get update notifications within WordPress for _custom_ themes that you use for your site? Perhaps a custom theme that you had developed specifically for your site? Or a theme you developed for a client site?  And do you wish you could do "automatic updates" to those custom themes just like you can for _public_ themes available from WordPress.org?

This WordPress plugin lets you host a custom theme in a Github _public_ repository (private repos are not supported) and then notify sites when a new version of the theme is available.  Those sites can then perform an auto-update just as with publicly available themes.  The plugin also allows you to roll back to a previous version of the theme.

This plugin works with WordPress in both a standalone and MultiSite mode and has been tested up to WordPress 3.3.x.  It can be found in the WordPress plugin directory at:

* http://wordpress.org/extend/plugins/theme-updater/

Bugs, feature requests or other suggestions should be filed as [issues at the plugin's Github repository](https://github.com/UCF/Theme-Updater/issues)

## Screenshots

![Screenshot One](https://github.com/UCF/Theme-Updater/raw/master/screenshot-1.png)

---

![Screenshot Two](https://github.com/UCF/Theme-Updater/raw/master/screenshot-2.png)

---

![Screenshot Three](https://github.com/UCF/Theme-Updater/raw/master/screenshot-3.png)

---

## Installation

[Here](https://github.com/UCF/Theme-Updater-Demo) is a sample theme.  [Download (.zip)](https://github.com/UCF/Theme-Updater-Demo/zipball/v1.1.0)

### 1 - Publish your theme to a public GitHub Repository

### 2 - Update Your theme's `style.css`

Add `Github Theme URI` to your `style.css` header, this will be where the plugin looks for updates.  I also recommend using [semantic versioning](http://semver.org/) for the version number. (Note that the version number does _not_ need to start with "v" as shown in the examples below. You can simply use a number such as "1.2.0". You just need to be consistent with how you create version numbers.)

Example header:

    Theme Name: Example
    Theme URI: http://example.com/
    Github Theme URI: https://github.com/username/repo
    Description: My Example Theme
    Author: person
    Version: v1.0.0

Push these changes back to the project.

### 3 - Create a new tag and push the change back to the repo

    $ git tag v1.0.0
    $ git push origin v1.0.0

Note, your tag numbers and theme version numbers should match.  If you want to increment the version number, be sure to update and commit your `style.css` prior to creating the new git tag.

### 4 - Upload your modified theme to your WordPress site

Before the plugin can work, your theme with the `Github Theme URI` addition needs to be uploaded to our WordPress site.

* Create a ZIP file of your theme on your local computer.
* Inside your WordPress admin menu (standalone) or network admin menu (MultiSite) go to the Install Themes panel and click on "Upload".
* Choose your ZIP file and press "Install Now".

Your theme will now be installed inside of WordPress and can be activated for your site.  From this point forward all updates will be installed automatically once the plugin is activated.

### 5 - Download and install the plugin

Inside your WordPress admin menu (standalone) or network admin menu (MultiSite) choose "Add New" under the Plugins menu.  Search for "Theme Updater" and this will bring you to [the plugin's WordPress page](http://wordpress.org/extend/plugins/theme-updater/) where you can install the plugin directly into your WordPress installation. (Alternatively you can visit that page, download the plugin as a zip file and upload it to your WordPress install, but why go through all that work?)

With the plugin installed and activated (it must be network activated on multisite installs) on your site and the theme uploaded, the next time you push a new tag to your Github repository, it will be recognized by the plugin and an update notice will appear in your admin menu.

This is no configuration or settings panel for this plugin.

---

## Updating The Theme

The process of updating your theme and generating auto-update notifications is now simply this:

### 1 - Make your changes to the theme and commit those changes to your local git repository.

### 2 - **IMPORTANT** - Update your `style.css` file with a new version number and commit that change to your local repository.

### 3 - Push your changes to the Github repository

    $ git push origin master

### 4 - Create a new tag and push the change back to the repo

    $ git tag v1.1.0
    $ git push origin v1.1.0

Note, you should use the **identical** number for the tag that you did for a version number in `style.css` in step #2.

That's it. Now any sites with your theme installed will receive an update notification the next time their WordPress installation checks for updates.

---

## Code Comments

The flow of the plugin is:

### 1 - Get the Theme's Update URI

Code is a mashup of Wordpress source.  I'm looking at:

* [`get_themes()`](http://core.trac.wordpress.org/browser/trunk/wp-includes/theme.php?rev=17978#L249)
* [`get_theme_data()`](http://core.trac.wordpress.org/browser/trunk/wp-includes/theme.php?rev=17978#L163)

### 2 - Get the github tags

Pull the tags trough the [Repository Refs API](http://develop.github.com/p/repo.html).

### 3 - Notify Worpress of the Update

Publish the update details to the `response` array in the `update_themes` transient, similar to how [Wordpress updates themes](http://core.trac.wordpress.org/browser/trunk/wp-includes/update.php?rev=17978#L188).

## Changelog

*** v1.3.7 - July 23, 2012
* URLencode repo and user names
* Handle Github API errors appropriately

*** v1.3.6 - July 23, 2012
* Fixed [Incorrect Github Project URL Error](https://github.com/UCF/Theme-Updater/issues/22)

### v1.3.5 - July 23, 2012
* [Compabitilty with new Github API](https://github.com/UCF/Theme-Updater/issues/18)
* Updated README to address the following issues: [Installation for MultiSite should mention "Network Activate"](https://github.com/UCF/Theme-Updater/issues/13) and [Docs should mention that there is no configuration or settings panel](https://github.com/UCF/Theme-Updater/issues/15)

### v1.3.4 - February 8, 2012
* Fix to [SSL issue](https://github.com/UCF/Theme-Updater/issues/3). Code by Github user bainternet. Added by Github user danyork.