text:
/**
 * @author: Lefteris Karapetsas
 * @licence: BSD3 (Check repository root for details)
 */
#ifndef RF_STRING_COREX_H
#define RF_STRING_COREX_H

#include <rflib/string/xdecl.h>

#include <rflib/defs/imex.h>
#include <rflib/defs/types.h>
#include <rflib/defs/retcodes.h>

#include <string.h>
#include <stdarg.h>

#ifdef __cplusplus
extern "C"
{///opening bracket for calling from C++
#endif

//! @name RFstringx Creation
//! @{

/* --- Functions that already exist for RFstring - START --- */
#define RF_STRINGX_STATIC_INIT(s_) {            \
        {RF_STRING_STATIC_INIT(s_)},            \
        .bIndex=0,                              \
        .bSize=sizeof(s_) - 1                   \
    }
#define RF_STRINGX_SHALLOW_INIT(i_string, i_buff, i_len)                \
    do {                                                                \
        RF_STRING_SHALLOW_INIT(&(i_string)->INH_String, i_buff, i_len); \
        (i_string)->bIndex = 0;                                         \
        (i_string)->bSize = i_len;                                      \
    } while(0)

#define RF_STRINGX_SHALLOW_FROM_STR(i_string, i_from)       \
    RF_STRINGX_SHALLOW_INIT(i_string,                       \
                            rf_string_data(i_from),         \
                            rf_string_length_bytes(i_from))

i_DECLIMEX_ struct RFstringx *rf_stringx_create(const char *lit);
i_DECLIMEX_ struct RFstringx *rf_stringx_createv(const char *lit, ...);
i_DECLIMEX_ struct RFstringx *rf_stringx_createvl(const char *lit, va_list args);

i_DECLIMEX_ bool rf_stringx_init(struct RFstringx *str,const char *lit);
i_DECLIMEX_ bool rf_stringx_initv(struct RFstringx *str,const char *lit,...);
i_DECLIMEX_ bool rf_stringx_initvl(
    struct RFstringx *str,
    const char *lit,
    va_list args
);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_cp(uint32_t code);
i_DECLIMEX_ bool rf_stringx_init_cp(struct RFstringx *str, uint32_t code);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_unsafe(const char *lit);
i_DECLIMEX_ bool rf_stringx_init_unsafe(struct RFstringx *str, const char *lit);

i_DECLIMEX_ bool rf_stringx_init_unsafe_nnt(
    struct RFstringx *str,
    const char *s,
    size_t length
);
i_DECLIMEX_ bool rf_stringx_init_unsafe_bnnt(
    struct RFstringx *str,
    const char *s,
    size_t length,
    size_t buff_size
);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_int(int i);
i_DECLIMEX_ bool rf_stringx_init_int(struct RFstringx *str, int i);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_double(
    double d,
    unsigned int precision
);
i_DECLIMEX_ bool rf_stringx_init_double(
    struct RFstringx *str,
    double d,
    unsigned int precision
);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_utf16(
    const uint16_t *s,
    unsigned int len
);
i_DECLIMEX_ bool rf_stringx_init_utf16(
    struct RFstringx *str,
    const uint16_t *s,
    unsigned int len
);

i_DECLIMEX_ struct RFstringx *rf_stringx_create_utf32(
    const uint32_t *s,
    unsigned int len
);
i_DECLIMEX_ bool rf_stringx_init_utf32(
    struct RFstringx *str,
    const uint32_t *s,
    unsigned int len
);

/* --- Functions that already exist for RFstring - END --- */

/**
 * @brief Creates an RFstringx with a specified buffer size
 *
 * Allocates and returns an extended String allocating buffSize
 * bytes buffer and puts @c lit inside that buffer. If the contents
 * of the string are bigger than the buffer Size then an error is logged
 * but the String is initialized correctly.
 * @lmsFunction
 * @param buffSize               A positive value of bytes for the size of the
 *                               buffer to allocate
 * @param lit                    The string literal with which to initialize.
 *                               A check to see if it is
 *                               a valid UTF-8 sequence is performed
 * @return                       The newly initialized string
 * @see rf_stringx_init_buff()
 */
i_DECLIMEX_ struct RFstringx* rf_stringx_create_buff(uint32_t buffSize, const char *lit);

/**
 * @brief Creates an RFstringx with a specified buffer size (varargs)
 */
i_DECLIMEX_ struct RFstringx *rf_stringx_create_buffv(
    uint32_t buffSize,
    const char *lit,
    ...
);

/**
 * @brief Initializes an RFstringx with a specified buffer size
 * @lmsFunction
 * @see rf_stringx_create_buff() for details
 */
i_DECLIMEX_ bool rf_stringx_init_buff(
    struct RFstringx *str,
    uint32_t buffSize,
    const char* lit
);

/**
 * @brief Initializes an RFstringx with a specified buffer size
 * @lmsFunction
 * @see rf_stringx_init_buffv() for details
 */
i_DECLIMEX_ bool rf_stringx_init_buffv(
    struct RFstringx *str,
    uint32_t buffSize,
    const char* lit,
    ...
);

//! @}

//! @name RFstringx Copying-Assigning
//! @{

/**
 * @brief Assigns the value of the source string to the
 * destination extended string
 *
 * Both strings should already be initialized and hold a value.
 * It is an error to give null parameters.
 * @lmsFunction
 * @param dest The destination string, which should get assigned
 * @param source The source string, whose values to copy.
 * @inhtype{String,StringX} @tmpSTR
 * @return Returns @c true for success and @c false otherwise
 * @see rf_stringx_assign_char()
 */
i_DECLIMEX_ bool rf_stringx_assign(struct RFstringx *dest, const struct RFstring *source);

/**
 * @brief Assigns to a stringx with the given format (varargs)
 * Assigns to the current stringx position.
 *
 * @lmsFunction
 *
 */
i_DECLIMEX_ bool rf_stringx_assignv(struct RFstringx *str, const char *s, ...);
i_DECLIMEX_ bool rf_stringx_assignvl(
    struct RFstringx *str,
    const char *s,
    va_list args
);

/**
 * @brief Assigns the value of a unicode character to the string
 *
 * @param thisstr The string to assign to
 * @param character The unicode character codepoint to assign to the String
 * @return Returns @c true for succesfull assignment and @c false
 * if the given @c character was not a valid unicode codepoint
 * @see rf_stringx_assign()
 */
i_DECLIMEX_ bool rf_stringx_assign_char(struct RFstringx *thisstr, uint32_t character);

/**
 * @brief Assigns to a stringx from a non-null terminated char* buffer
 * and for the given bytelength
 *
 */
i_DECLIMEX_ bool rf_stringx_assign_unsafe_nnt(
    struct RFstringx *str,
    const char *s,
    size_t length
);

/**
 * @brief Nullifies a string
 * @warning Use null strings at your own risk. None of the RF_String/X
 * functions currently test for them
 * A safer and easier alternative is to assign an empty string and
 * check for it with @ref rf_string_is_empty()
 */
#define rf_stringx_null(i_STRING) do{           \
        rf_string_length_bytes(i_STRING) = 0;   \
        rf_string_data(i_STRING) = NULL;        \
        (i_STRING)->bIndex = 0;                 \
        (i_STRING)->bSize = 0;                  \
    }while(0)

/**
 * @brief Checks that a string is null
 */
#define rf_stringx_is_null(i_STRING)              \
    ((rf_string_length_bytes(i_STRING) == 0) &&    \
     (rf_string_data(i_STRING) == NULL))

/**
 * @brief Creates an RFstringx from an RF_string
 *
 * Returns an RFstringx version of the parameter RFstring
 * @param s The RFstring from which to create the RFstringx
 * @return The RFstringx version of the parameter string
 * @see rf_stringx_from_string_in()
 * @see rf_stringx_copy_out()
 * @see rf_stringx_copy_chars()
 */
i_DECLIMEX_ struct RFstringx *rf_stringx_from_string_out(const struct RFstring *s);

/**
 * @brief Initializes an RFstringx from an RF_string
 *
 * @param dst The RFstringx that will get initialize
 * @param src The RFstring to copy from
 * @return Returns @c true for success and @c false otherwise
 * @see rf_stringx_from_string_out()
 * @see rf_stringx_copy_in()
 * @see rf_stringx_copy_chars()
 */
i_DECLIMEX_ bool rf_stringx_from_string_in(
    struct RFstringx *dst,
    const struct RFstring *src
);

/**
 * @brief Shallow copy of 2 RFstringx
 */
#define RF_STRINGX_SHALLOW_COPY(i_dst, i_src)                           \
    do {                                                                \
        rf_string_data(i_dst) = rf_string_data(i_src);                  \
        rf_string_length_bytes(i_dst) = rf_string_length_bytes(i_src);  \
        (i_dst)->bSize = (i_src)->bSize;                                \
        (i_dst)->bIndex = (i_src)->bIndex;                              \
    }while(0)

/**
 * @brief Creates a copy of an extended String and returns it
 *
 * Also note that the source RFstringx is not @c const unlike the
 * RFstring copying functions.
 * The reason for this is because we actually have to copy all of it,
 * even if its internal pointer has been moved, in which case
 * its contents are indeed tampered with in the function so as to allow
 * reading the whole string. But despite that after the function finishes
 * the contents of the source string are guaranteed to be the same.
 * @param  s The  string to copy
 * @return A copy of the string
 * @see rf_stringx_from_string_out()
 * @see rf_stringx_copy_in()
 * @see rf_stringx_copy_chars()
 */
i_DECLIMEX_ struct RFstringx *rf_stringx_copy_out(struct RFstringx *s);

/**
 * @brief Copies the given source RFstringx into the destination RFstringx
 * @return Returns @c true for success and @c false otherwise
 * @see rf_stringx_from_string_in()
 * @see rf_stringx_copy_out()
 * @see rf_stringx_copy_chars()
 */
i_DECLIMEX_ bool rf_stringx_copy_in(struct RFstringx *dst, struct RFstringx *src);

/**
 * @brief Copies a certain number of characters from an RFstringx
 *
 * Copies @c n characters from @c src StringX into
 * the destination @c dst StringX.
 *
 * @param  dst The String to copy in.
 * @param  src The String to copy from
 * @param n  The number of characters to copy from the @c src string.
 * If the value is bigger than the maximum number of characters then
 * still all characters are copied.
 * @return Returns @c true for success and @c false otherwise
 * @see rf_stringx_copy_out()
 * @see rf_stringx_copy_in()
 */
i_DECLIMEX_ bool rf_stringx_copy_chars(
    struct RFstringx *dst,
    struct RFstringx *src,
    uint32_t n
);

//! @}

//! @name Getting rid of an RFstringx
//! @{

/**
 * @brief Destroys an extended String and releases its memory.
 *
 * Use it for strings made with _Create
 * @param s The exended String to destroy
 * @see rf_stringx_deinit()
 */
i_DECLIMEX_ void rf_stringx_destroy(struct RFstringx *s);
/**
 * @brief Destroys only the contents of the Extended string
 * without freeing the pointer itself.
 *
 * Use it for strings made with _Init
 * @param s The exended String to destroy
 * @see rf_stringx_destroy()
 */
i_DECLIMEX_ void rf_stringx_deinit(struct RFstringx *s);

//! @}

#ifdef __cplusplus
}///closing bracket for calling from C++
#endif

#endif//include guards end


text:
package blended.mgmt.service.jmx

import java.lang.management.ManagementFactory

import blended.mgmt.service.jmx.internal.{ServiceJmxAnalyser, ServiceJmxConfig}
import com.typesafe.config.ConfigFactory
import org.scalatest.{FreeSpec, Matchers}

class ServiceJMXAnalyserSpec extends FreeSpec
  with Matchers {

  val server = ManagementFactory.getPlatformMBeanServer()
  val config = ServiceJmxConfig(ConfigFactory.load("javalang.conf"))

  val analyser = new ServiceJmxAnalyser(server, config)

  "The Service Analyser" - {

    "should find a specified MBean" in {

      val list = analyser.analyse()
      list should have size (2)

      val info = list.filter(_.name.contains("OperatingSystem")).head

      info.name should be ("java.lang:type=OperatingSystem")
      info.serviceType should be ("Runtime")
      info.lifetimeMsec should be (3000)

      info.props should have size(1)
      info.props should contain key("Name")

      val memory = list.filter(_.name.contains("Memory")).head
      memory.serviceType should be ("Runtime")
      memory.lifetimeMsec should be (3000)

      memory.props should have size(4)
      memory.props should contain key("HeapMemoryUsage.used")
      memory.props should contain key("HeapMemoryUsage.max")
      memory.props should contain key("HeapMemoryUsage.committed")
      memory.props should contain key("HeapMemoryUsage.init")

    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  File: 20150401091122_add_guest_session

    — Documentation by YARD 0.9.5

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

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

    Index »
    File: 20150401091122_add_guest_session

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

class AddGuestSession < ActiveRecord::Migration
  def change
    add_column :sessions, :guest, :boolean, default: false
  end
end

  Generated on Sat Oct 22 02:15:17 2016 by
  yard
  0.9.5 (ruby-2.3.1).


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.omeletlab.sa.moviester" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name=".util.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.HomeActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.MovieDetailsActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/title_activity_movie_details"
            android:theme="@style/AppTheme.NoActionBar" >
        </activity>

        <meta-data
            android:name="DATABASE"
            android:value="moviester_database.db" />
        <meta-data
            android:name="VERSION"
            android:value="1" />
        <meta-data
            android:name="QUERY_LOG"
            android:value="true" />
        <meta-data
            android:name="DOMAIN_PACKAGE_NAME"
            android:value="com.omeletlab.sa.moviester" />

    </application>

</manifest>


text:
/* jshint mocha: true */

/**
 * Module dependencies.
 */

var ejs = require('..')
  , fs = require('fs')
  , read = fs.readFileSync
  , assert = require('assert')
  , path = require('path');

try {
  fs.mkdirSync(__dirname + '/tmp');
} catch (ex) {
  if (ex.code !== 'EEXIST') {
    throw ex;
  }
}

// From https://gist.github.com/pguillory/729616
function hook_stdout(callback) {
  var old_write = process.stdout.write;

  process.stdout.write = (function() {
    return function(string, encoding, fd) {
      callback(string, encoding, fd);
    };
  })(process.stdout.write);

  return function() {
    process.stdout.write = old_write;
  };
}

/**
 * Load fixture `name`.
 */

function fixture(name) {
  return read('test/fixtures/' + name, 'utf8').replace(/\r/g, '').trim();
}

/**
 * User fixtures.
 */

var users = [];
users.push({name: 'geddy'});
users.push({name: 'neil'});
users.push({name: 'alex'});

suite('ejs.compile(str, options)', function () {
  test('compile to a function', function () {
    var fn = ejs.compile('
yay
');
    assert.equal(fn(), '
yay
');
  });

  test('empty input works', function () {
    var fn = ejs.compile('');
    assert.equal(fn(), '');
  });

  test('throw if there are syntax errors', function () {
    try {
      ejs.compile(fixture('fail.ejs'));
    }
    catch (err) {
      assert.ok(err.message.indexOf('compiling ejs') > -1);

      try {
        ejs.compile(fixture('fail.ejs'), {filename: 'fail.ejs'});
      }
      catch (err) {
        assert.ok(err.message.indexOf('fail.ejs') > -1);
        return;
      }
    }
    throw new Error('no error reported when there should be');
  });

  test('allow customizing delimiter local var', function () {
    var fn;
    fn = ejs.compile('
<?= name ?>
', {delimiter: '?'});
    assert.equal(fn({name: 'geddy'}), '
geddy
');

    fn = ejs.compile('
<:= name :>
', {delimiter: ':'});
    assert.equal(fn({name: 'geddy'}), '
geddy
');

    fn = ejs.compile('
<$= name $>
', {delimiter: '$'});
    assert.equal(fn({name: 'geddy'}), '
geddy
');
  });

  test('default to using ejs.delimiter', function () {
    var fn;
    ejs.delimiter = '&';
    fn = ejs.compile('
<&= name &>
');
    assert.equal(fn({name: 'geddy'}), '
geddy
');

    fn = ejs.compile('
<|= name |>
', {delimiter: '|'});
    assert.equal(fn({name: 'geddy'}), '
geddy
');
    delete ejs.delimiter;
  });

  test('have a working client option', function () {
    var fn
      , str
      , preFn;
    fn = ejs.compile('
<%= foo %>
', {client: true});
    str = fn.toString();
    if (!process.env.running_under_istanbul) {
      eval('var preFn = ' + str);
      assert.equal(preFn({foo: 'bar'}), '
bar
');
    }
  });

  test('support client mode without locals', function () {
    var fn
      , str
      , preFn;
    fn = ejs.compile('
<%= "foo" %>
', {client: true});
    str = fn.toString();
    if (!process.env.running_under_istanbul) {
      eval('var preFn = ' + str);
      assert.equal(preFn(), '
foo
');
    }
  });
});

suite('ejs.render(str, data)', function () {
  test('render the template', function () {
    assert.equal(ejs.render('
yay
'), '
yay
');
  });

  test('empty input works', function () {
    assert.equal(ejs.render(''), '');
  });

  test('undefined renders nothing escaped', function () {
    assert.equal(ejs.render('<%= undefined %>'), '');
  });

  test('undefined renders nothing raw', function () {
    assert.equal(ejs.render('<%- undefined %>'), '');
  });

  test('null renders nothing escaped', function () {
    assert.equal(ejs.render('<%= null %>'), '');
  });

  test('null renders nothing raw', function () {
    assert.equal(ejs.render('<%- null %>'), '');
  });

  test('zero-value data item renders something escaped', function () {
    assert.equal(ejs.render('<%= 0 %>'), '0');
  });

  test('zero-value data object renders something raw', function () {
    assert.equal(ejs.render('<%- 0 %>'), '0');
  });

  test('accept locals', function () {
    assert.equal(ejs.render('
<%= name %>
', {name: 'geddy'}),
        '
geddy
');
  });

  test('accept locals without using with() {}', function () {
    assert.equal(ejs.render('
<%= locals.name %>
', {name: 'geddy'},
                            {_with: false}),
        '
geddy
');
    assert.throws(function() {
      ejs.render('
<%= name %>
', {name: 'geddy'},
                 {_with: false});
    }, /name is not defined/);
  });

  test('support caching (pass 1)', function () {
    var file = __dirname + '/tmp/render.ejs'
      , options = {cache: true, filename: file}
      , out = ejs.render('
Old
', {}, options)
      , expected = '
Old
';
    assert.equal(out, expected);
  });

  test('support caching (pass 2)', function () {
    var file = __dirname + '/tmp/render.ejs'
      , options = {cache: true, filename: file}
      , out = ejs.render('
New
', {}, options)
      , expected = '
Old
';
    assert.equal(out, expected);
  });
});

suite('ejs.renderFile(path, [data], [options], fn)', function () {
  test('render a file', function(done) {
    ejs.renderFile('test/fixtures/para.ejs', function(err, html) {
      if (err) {
        return done(err);
      }
      assert.equal(html, '
hey
');
      done();
    });
  });

  test('accept locals', function(done) {
    var data =  {name: 'fonebone'}
      , options = {delimiter: '$'};
    ejs.renderFile('test/fixtures/user.ejs', data, options, function(err, html) {
      if (err) {
        return done(err);
      }
      assert.equal(html, '
fonebone
');
      done();
    });
  });

  test('deprecation warning for data-in-opts', function(done) {
    var data =  {name: 'fonebone', delimiter: '$'}
      , options = {delimiter: '$'}
      , warn = console.warn
      , incr = 0;

    console.warn = function (msg) {
      assert.ok(msg.indexOf('options found in locals object') > -1);
      incr++;
    }

    ejs.renderFile('test/fixtures/user.ejs', data, function(err, html) {
      if (err) {
        return done(err);
      }
      assert.equal(html, '
fonebone
');
      assert.equal(incr, 1);
      console.warn = warn;

      done();
    });
  });

  test('no deprecation warning for data-in-opts via Express', function(done) {
    var data =  {name: 'fonebone', delimiter: '$'}
      , options = {delimiter: '$'}
      , warn = console.warn
      , incr = 0;

    console.warn = function (msg) {
      incr++;
    }

    ejs.__express('test/fixtures/user.ejs', data, function(err, html) {
      if (err) {
        return done(err);
      }
      assert.equal(html, '
fonebone
');
      assert.equal(incr, 0);
      console.warn = warn;

      done();
    });
  });

  test('accept locals without using with() {}', function(done) {
    var data =  {name: 'fonebone'}
      , options = {delimiter: '$', _with: false}
      , doneCount = 0;
    ejs.renderFile('test/fixtures/user-no-with.ejs', data, options,
                   function(err, html) {
      if (err) {
        if (doneCount === 2) {
          return;
        }
        doneCount = 2;
        return done(err);
      }
      assert.equal(html, '
fonebone
');
      doneCount++;
      if (doneCount === 2) {
        done();
      }
    });
    ejs.renderFile('test/fixtures/user.ejs', data, options, function(err) {
      if (!err) {
        if (doneCount === 2) {
          return;
        }
        doneCount = 2;
        return done(new Error('error not thrown'));
      }
      doneCount++;
      if (doneCount === 2) {
        done();
      }
    });
  });

  test('not catch err thrown by callback', function(done) {
    var data =  {name: 'fonebone'}
      , options = {delimiter: '$'}
      , counter = 0;

    var d = require('domain').create();
    d.on('error', function (err) {
      assert.equal(counter, 1);
      assert.equal(err.message, 'Exception in callback');
      done();
    });
    d.run(function () {
      // process.nextTick() needed to work around mochajs/mocha#513
      //
      // tl;dr: mocha doesn't support synchronous exception throwing in
      // domains. Have to make it async. Ticket closed because: "domains are
      // deprecated :D"
      process.nextTick(function () {
        ejs.renderFile('test/fixtures/user.ejs', data, options,
                       function(err) {
          counter++;
          if (err) {
            assert.notEqual(err.message, 'Exception in callback');
            return done(err);
          }
          throw new Error('Exception in callback');
        });
      });
    });
  });

  test('support caching (pass 1)', function (done) {
    var expected = '
Old
'
      , file = __dirname + '/tmp/renderFile.ejs'
      , options = {cache: true}
    fs.writeFileSync(file, '
Old
');

    var out = ejs.renderFile(file, {}, options, function (err, out) {
      if (err) {
        done(err);
      }
      assert.equal(out, expected);
      done();
    });
  });

  test('support caching (pass 2)', function (done) {
    var expected = '
Old
'
      , file = __dirname + '/tmp/renderFile.ejs'
      , options = {cache: true}
    fs.writeFileSync(file, '
New
');

    var out = ejs.renderFile(file, {}, options, function (err, out) {
      if (err) {
        done(err);
      }
      assert.equal(out, expected);
      done();
    });
  });
});

suite('ejs.clearCache()', function () {
  test('work properly', function () {
    var expected = '
Old
'
      , file = __dirname + '/tmp/clearCache.ejs'
      , options = {cache: true, filename: file}
      , out = ejs.render('
Old
', {}, options);
    assert.equal(out, expected);

    ejs.clearCache();

    expected = '
New
';
    out = ejs.render('
New
', {}, options);
    assert.equal(out, expected);
  });
});

suite('<%=', function () {
  test('escape &


text:
package org.bouncycastle.asn1.crmf;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.GeneralName;

/**
 * <pre>
 * SinglePubInfo ::= SEQUENCE {
 *        pubMethod    INTEGER {
 *           dontCare    (0),
 *           x500        (1),
 *           web         (2),
 *           ldap        (3) },
 *       pubLocation  GeneralName OPTIONAL }
 * </pre>
 */
public class SinglePubInfo
    extends ASN1Object
{
    public static final ASN1Integer dontCare = new ASN1Integer(0);
    public static final ASN1Integer x500 = new ASN1Integer(1);
    public static final ASN1Integer web = new ASN1Integer(2);
    public static final ASN1Integer ldap = new ASN1Integer(3);

    private ASN1Integer pubMethod;
    private GeneralName pubLocation;

    private SinglePubInfo(ASN1Sequence seq)
    {
        pubMethod = ASN1Integer.getInstance(seq.getObjectAt(0));

        if (seq.size() == 2)
        {
            pubLocation = GeneralName.getInstance(seq.getObjectAt(1));
        }
    }

    public static SinglePubInfo getInstance(Object o)
    {
        if (o instanceof SinglePubInfo)
        {
            return (SinglePubInfo)o;
        }

        if (o != null)
        {
            return new SinglePubInfo(ASN1Sequence.getInstance(o));
        }

        return null;
    }

    public SinglePubInfo(ASN1Integer pubMethod, GeneralName pubLocation)
    {
        this.pubMethod = pubMethod;
        this.pubLocation = pubLocation;
    }

    public ASN1Integer getPubMethod()
    {
        return pubMethod;
    }

    public GeneralName getPubLocation()
    {
        return pubLocation;
    }

    /**
     * Return the primitive representation of SinglePubInfo.
     *
     * @return a basic ASN.1 object representation.
     */
    public ASN1Primitive toASN1Primitive()
    {
        ASN1EncodableVector v = new ASN1EncodableVector(2);

        v.add(pubMethod);

        if (pubLocation != null)
        {
            v.add(pubLocation);
        }

        return new DERSequence(v);
    }
}


text: <meta http-equiv="refresh" content="0; url=http://chess.jordanbray.com/chess/">


text:
package com.badlogic.gdx.controllers;

import com.badlogic.gdx.math.Vector3;

/** A base implementation for {@link ControllerListener}. Subclass this if you are only interested in a few specific events.
 * @author mzechner */
public class ControllerAdapter implements ControllerListener {
	@Override
	public boolean buttonDown (Controller controller, int buttonIndex) {
		return false;
	}

	@Override
	public boolean buttonUp (Controller controller, int buttonIndex) {
		return false;
	}

	@Override
	public boolean axisMoved (Controller controller, int axisIndex, float value) {
		return false;
	}

	@Override
	public boolean povMoved (Controller controller, int povIndex, PovDirection value) {
		return false;
	}

	@Override
	public boolean xSliderMoved (Controller controller, int sliderIndex, boolean value) {
		return false;
	}

	@Override
	public boolean ySliderMoved (Controller controller, int sliderIndex, boolean value) {
		return false;
	}

	@Override
	public boolean accelerometerMoved (Controller controller, int accelerometerIndex, Vector3 value) {
		return false;
	}

	@Override
	public void connected (Controller controller) {
	}

	@Override
	public void disconnected (Controller controller) {
	}
}


text:
<?php

namespace Bunny\Framework\Http;

use Bunny\Http\Request;
use Bunny\Http\Response;

use Bunny\Framework\Aware\FactoryAware;
use Bunny\Framework\Aware\LoggerAware;

/**
 * 控制器基础类
 */
class Controller{

    use LoggerAware;
    use FactoryAware;

    /**
     * @var Bunny\Http\Request HTTP请求
     */
    protected $request;

    /**
     * @var Bunny\Http\Response HTTP响应
     */
    protected $response;

    public function __construct(Request $request, Response $response) {
        $this->request = $request;
        $this->response = $response;
    }

    /**
     * 业务前置方法
     */
    public function before(){}

    /**
     * 业务后置方法
     */
    public function after(){}
}


text:
import { create as timeSpanCreate } from "./TimeSpan"
import { compare as utilCompare } from "./Util"
import * as Long from "./Long"

export const enum DateKind {
  Unspecified = 0,
  UTC = 1,
  Local = 2
}

export function minValue() {
  return parse(-8640000000000000, 1);
}

export function maxValue() {
  return parse(8640000000000000, 1);
}

export function parse(v?: any, kind?: DateKind): any {
  if (kind == null) {
    kind = typeof v == "string" && v.slice(-1) == "Z" ? DateKind.UTC : DateKind.Local;
  }
  let date = (v == null) ? new Date() : new Date(v);
  if (kind === DateKind.Local) {
    (date as any).kind = kind;
  }
  if (isNaN(date.getTime())) {
    throw new Error("The string is not a valid Date.");
  }
  return date;
}

export function tryParse(v: any): [boolean, Date] {
  try {
    return [true, parse(v)];
  }
  catch (_err) {
    return [false, minValue()];
  }
}

export function create(year: number, month: number, day: number, h: number = 0, m: number = 0, s: number = 0, ms: number = 0, kind: DateKind = DateKind.Local) {
  let date: Date;
  if (kind === DateKind.Local) {
    date = new Date(year, month - 1, day, h, m, s, ms);
    (date as any).kind = kind;
  }
  else {
    date = new Date(Date.UTC(year, month - 1, day, h, m, s, ms));
  }
  if (isNaN(date.getTime())) {
    throw new Error("The parameters describe an unrepresentable Date.");
  }
  return date;
}

export function now() {
  return parse();
}

export function utcNow() {
  return parse(null, 1);
}

export function today() {
  return date(now());
}

export function isLeapYear(year: number) {
  return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}

export function daysInMonth(year: number, month: number) {
  return month == 2
    ? isLeapYear(year) ? 29 : 28
    : month >= 8 ? month % 2 == 0 ? 31 : 30 : month % 2 == 0 ? 30 : 31;
}

export function toUniversalTime(d: Date) {
  return (d as any).kind === DateKind.Local ? new Date(d.getTime()) : d;
}

export function toLocalTime(d: Date) {
  if ((d as any).kind === DateKind.Local) {
    return d;
  }
  else {
    let d2 = new Date(d.getTime());
    (d2 as any).kind = DateKind.Local;
    return d2;
  }
}

export function timeOfDay(d: Date) {
  return timeSpanCreate(0, hour(d), minute(d), second(d), millisecond(d));
}

export function date(d: Date) {
  return create(year(d), month(d), day(d), 0, 0, 0, 0, (d as any).kind || DateKind.UTC);
}

export function kind(d: Date) {
  return (d as any).kind || DateKind.UTC;
}

export function day(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getDate() : d.getUTCDate();
}

export function hour(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getHours() : d.getUTCHours();
}

export function millisecond(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getMilliseconds() : d.getUTCMilliseconds();
}

export function minute(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getMinutes() : d.getUTCMinutes();
}

export function month(d: Date) {
  return ((d as any).kind === DateKind.Local ? d.getMonth() : d.getUTCMonth()) + 1;
}

export function second(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getSeconds() : d.getUTCSeconds();
}

export function year(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getFullYear() : d.getUTCFullYear();
}

export function dayOfWeek(d: Date) {
  return (d as any).kind === DateKind.Local ? d.getDay() : d.getUTCDay();
}

export function ticks(d: Date) {
  return Long.fromNumber(d.getTime())
             .add(62135596800000) // UnixEpochMilliseconds
             .sub((d as any).kind == DateKind.Local ? d.getTimezoneOffset()*60*1000 : 0)
             .mul(10000);
}

export function toBinary(d: Date) {
  return ticks(d);
}

export function dayOfYear(d: Date) {
  const _year = year(d);
  const _month = month(d);
  let _day = day(d);
  for (let i = 1; i < _month; i++)
    _day += daysInMonth(_year, i);
  return _day;
}

export function add(d: Date, ts: number) {
  return parse(d.getTime() + <number>ts, (d as any).kind || DateKind.UTC);
}

export function addDays(d: Date, v: number) {
  return parse(d.getTime() + v * 86400000, (d as any).kind || DateKind.UTC);
}

export function addHours(d: Date, v: number) {
  return parse(d.getTime() + v * 3600000, (d as any).kind || DateKind.UTC);
}

export function addMinutes(d: Date, v: number) {
  return parse(d.getTime() + v * 60000, (d as any).kind || DateKind.UTC);
}

export function addSeconds(d: Date, v: number) {
  return parse(d.getTime() + v * 1000, (d as any).kind || DateKind.UTC);
}

export function addMilliseconds(d: Date, v: number) {
  return parse(d.getTime() + v, (d as any).kind || DateKind.UTC);
}

export function addTicks(d: Date, t: Long.Long) {
  return parse(Long.fromNumber(d.getTime()).add(t.div(10000)).toNumber(), (d as any).kind || DateKind.UTC);
}

export function addYears(d: Date, v: number) {
  const newMonth = month(d);
  const newYear = year(d) + v;
  const _daysInMonth = daysInMonth(newYear, newMonth);
  const newDay = Math.min(_daysInMonth, day(d));
  return create(newYear, newMonth, newDay, hour(d), minute(d), second(d), millisecond(d), (d as any).kind || DateKind.UTC);
}

export function addMonths(d: Date, v: number) {
  let newMonth = month(d) + v;
  let newMonth_ = 0;
  let yearOffset = 0;
  if (newMonth > 12) {
    newMonth_ = newMonth % 12;
    yearOffset = Math.floor(newMonth / 12);
    newMonth = newMonth_;
  } else if (newMonth < 1) {
    newMonth_ = 12 + newMonth % 12;
    yearOffset = Math.floor(newMonth / 12) + (newMonth_ == 12 ? -1 : 0);
    newMonth = newMonth_;
  }
  const newYear = year(d) + yearOffset;
  const _daysInMonth = daysInMonth(newYear, newMonth);
  const newDay = Math.min(_daysInMonth, day(d));
  return create(newYear, newMonth, newDay, hour(d), minute(d), second(d), millisecond(d), (d as any).kind || DateKind.UTC);
}

export function subtract(d: Date, that: Date | number) {
  return typeof that == "number"
    ? parse(d.getTime() - <number>that, (d as any).kind || DateKind.UTC)
    : d.getTime() - (<Date>that).getTime();
}

export function toLongDateString(d: Date) {
  return d.toDateString();
}

export function toShortDateString(d: Date) {
  return d.toLocaleDateString();
}

export function toLongTimeString(d: Date) {
  return d.toLocaleTimeString();
}

export function toShortTimeString(d: Date) {
  return d.toLocaleTimeString().replace(/:\d\d(?!:)/, "");
}

export function equals(d1: Date, d2: Date) {
  return d1.getTime() == d2.getTime();
}

export function compare(x: Date, y: Date) {
  return utilCompare(x, y)
}

export function compareTo(x: Date, y: Date) {
  return utilCompare(x, y)
}

export function op_Addition(x: Date, y: number) {
  return add(x, y);
}

export function op_Subtraction(x: Date, y: number | Date) {
  return subtract(x, y);
}


text:
Distribution representing the quantization `Y = ceiling(X)`.

#### Definition in terms of sampling.

```
1. Draw X
2. Set Y <-- ceiling(X)
3. If Y < lower_cutoff, reset Y <-- lower_cutoff
4. If Y > upper_cutoff, reset Y <-- upper_cutoff
5. Return Y
```

#### Definition in terms of the probability mass function.

Given scalar random variable `X`, we define a discrete random variable `Y`
supported on the integers as follows:

```
P[Y = j] := P[X <= lower_cutoff],  if j == lower_cutoff,
         := P[X > upper_cutoff - 1],  j == upper_cutoff,
         := 0, if j < lower_cutoff or j > upper_cutoff,
         := P[j - 1 < X <= j],  all other j.
```

Conceptually, without cutoffs, the quantization process partitions the real
line `R` into half open intervals, and identifies an integer `j` with the
right endpoints:

```
R = ... (-2, -1](-1, 0](0, 1](1, 2](2, 3](3, 4] ...
j = ...      -1      0     1     2     3     4  ...
```

`P[Y = j]` is the mass of `X` within the `jth` interval.
If `lower_cutoff = 0`, and `upper_cutoff = 2`, then the intervals are redrawn
and `j` is re-assigned:

```
R = (-infty, 0](0, 1](1, infty)
j =          0     1     2
```

`P[Y = j]` is still the mass of `X` within the `jth` interval.

#### Caveats

Since evaluation of each `P[Y = j]` involves a cdf evaluation (rather than
a closed form function such as for a Poisson), computations such as mean and
entropy are better done with samples or approximations, and are not
implemented by this class.
- - -

#### `tf.contrib.distributions.QuantizedDistribution.__init__(base_dist_cls, lower_cutoff=None, upper_cutoff=None, name='QuantizedDistribution', **base_dist_args)` {#QuantizedDistribution.__init__}

Construct a Quantized Distribution.

Some properties are inherited from the distribution defining `X`.
In particular, `validate_args` and `allow_nan_stats` are determined for this
`QuantizedDistribution` by reading the additional kwargs passed as
`base_dist_args`.

##### Args:

*  <b>`base_dist_cls`</b>: the base distribution class to transform. Must be a
      subclass of `Distribution` implementing `cdf`.
*  <b>`lower_cutoff`</b>: `Tensor` with same `dtype` as this distribution and shape
    able to be added to samples.  Should be a whole number.  Default `None`.
    If provided, base distribution's pdf/pmf should be defined at
    `lower_cutoff`.
*  <b>`upper_cutoff`</b>: `Tensor` with same `dtype` as this distribution and shape
    able to be added to samples.  Should be a whole number.  Default `None`.
    If provided, base distribution's pdf/pmf should be defined at
    `upper_cutoff - 1`.
    `upper_cutoff` must be strictly greater than `lower_cutoff`.
*  <b>`name`</b>: The name for the distribution.
*  <b>`**base_dist_args`</b>: kwargs to pass on to dist_cls on construction.
    These determine the shape and dtype of this distribution.

##### Raises:

*  <b>`TypeError`</b>: If `base_dist_cls` is not a subclass of
      `Distribution` or continuous.
*  <b>`AttributeError`</b>: If the base distribution does not implement `cdf`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.allow_nan_stats` {#QuantizedDistribution.allow_nan_stats}

Python boolean describing behavior when a stat is undefined.

Stats return +/- infinity when it makes sense.  E.g., the variance
of a Cauchy distribution is infinity.  However, sometimes the
statistic is undefined, e.g., if a distribution's pdf does not achieve a
maximum within the support of the distribution, the mode is undefined.
If the mean is undefined, then by definition the variance is undefined.
E.g. the mean for Student's T for df = 1 is undefined (no clear way to say
it is either + or - infinity), so the variance = E[(X - mean)^2] is also
undefined.

##### Returns:

*  <b>`allow_nan_stats`</b>: Python boolean.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.base_distribution` {#QuantizedDistribution.base_distribution}

Base distribution, p(x).

- - -

#### `tf.contrib.distributions.QuantizedDistribution.batch_shape(name='batch_shape')` {#QuantizedDistribution.batch_shape}

Shape of a single sample from a single event index as a 1-D `Tensor`.

The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.

##### Args:

*  <b>`name`</b>: name to give to the op

##### Returns:

*  <b>`batch_shape`</b>: `Tensor`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.cdf(value, name='cdf')` {#QuantizedDistribution.cdf}

Cumulative distribution function.

Given random variable `X`, the cumulative distribution function `cdf` is:

```
cdf(x) := P[X <= x]
```

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`cdf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.dtype` {#QuantizedDistribution.dtype}

The `DType` of `Tensor`s handled by this `Distribution`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.entropy(name='entropy')` {#QuantizedDistribution.entropy}

Shanon entropy in nats.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.event_shape(name='event_shape')` {#QuantizedDistribution.event_shape}

Shape of a single sample from a single batch as a 1-D int32 `Tensor`.

##### Args:

*  <b>`name`</b>: name to give to the op

##### Returns:

*  <b>`event_shape`</b>: `Tensor`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.get_batch_shape()` {#QuantizedDistribution.get_batch_shape}

Shape of a single sample from a single event index as a `TensorShape`.

Same meaning as `batch_shape`. May be only partially defined.

##### Returns:

*  <b>`batch_shape`</b>: `TensorShape`, possibly unknown.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.get_event_shape()` {#QuantizedDistribution.get_event_shape}

Shape of a single sample from a single batch as a `TensorShape`.

Same meaning as `event_shape`. May be only partially defined.

##### Returns:

*  <b>`event_shape`</b>: `TensorShape`, possibly unknown.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.is_continuous` {#QuantizedDistribution.is_continuous}

- - -

#### `tf.contrib.distributions.QuantizedDistribution.is_reparameterized` {#QuantizedDistribution.is_reparameterized}

- - -

#### `tf.contrib.distributions.QuantizedDistribution.log_cdf(value, name='log_cdf')` {#QuantizedDistribution.log_cdf}

Log cumulative distribution function.

Given random variable `X`, the cumulative distribution function `cdf` is:

```
log_cdf(x) := Log[ P[X <= x] ]
```

Often, a numerical approximation can be used for `log_cdf(x)` that yields
a more accurate answer than simply taking the logarithm of the `cdf` when
`x << -1`.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`logcdf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.log_pdf(value, name='log_pdf')` {#QuantizedDistribution.log_pdf}

Log probability density function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`log_prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`AttributeError`</b>: if not `is_continuous`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.log_pmf(value, name='log_pmf')` {#QuantizedDistribution.log_pmf}

Log probability mass function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`log_pmf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`AttributeError`</b>: if `is_continuous`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.log_prob(value, name='log_prob')` {#QuantizedDistribution.log_prob}

Log probability density/mass function (depending on `is_continuous`).

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`log_prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.log_survival_function(value, name='log_survival_function')` {#QuantizedDistribution.log_survival_function}

Log survival function.

Given random variable `X`, the survival function is defined:

```
log_survival_function(x) = Log[ P[X > x] ]
                         = Log[ 1 - P[X <= x] ]
                         = Log[ 1 - cdf(x) ]
```

Typically, different numerical approximations can be used for the log
survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

  `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type
    `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.mean(name='mean')` {#QuantizedDistribution.mean}

Mean.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.mode(name='mode')` {#QuantizedDistribution.mode}

Mode.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.name` {#QuantizedDistribution.name}

Name prepended to all ops created by this `Distribution`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.param_shapes(cls, sample_shape, name='DistributionParamShapes')` {#QuantizedDistribution.param_shapes}

Shapes of parameters given the desired shape of a call to `sample()`.

Subclasses should override static method `_param_shapes`.

##### Args:

*  <b>`sample_shape`</b>: `Tensor` or python list/tuple. Desired shape of a call to
    `sample()`.
*  <b>`name`</b>: name to prepend ops with.

##### Returns:

  `dict` of parameter name to `Tensor` shapes.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.param_static_shapes(cls, sample_shape)` {#QuantizedDistribution.param_static_shapes}

param_shapes with static (i.e. TensorShape) shapes.

##### Args:

*  <b>`sample_shape`</b>: `TensorShape` or python list/tuple. Desired shape of a call
    to `sample()`.

##### Returns:

  `dict` of parameter name to `TensorShape`.

##### Raises:

*  <b>`ValueError`</b>: if `sample_shape` is a `TensorShape` and is not fully defined.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.parameters` {#QuantizedDistribution.parameters}

Dictionary of parameters used by this `Distribution`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.pdf(value, name='pdf')` {#QuantizedDistribution.pdf}

Probability density function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`AttributeError`</b>: if not `is_continuous`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.pmf(value, name='pmf')` {#QuantizedDistribution.pmf}

Probability mass function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`pmf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`AttributeError`</b>: if `is_continuous`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.prob(value, name='prob')` {#QuantizedDistribution.prob}

Probability density/mass function (depending on `is_continuous`).

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.sample(sample_shape=(), seed=None, name='sample')` {#QuantizedDistribution.sample}

Generate samples of the specified shape.

Note that a call to `sample()` without arguments will generate a single
sample.

##### Args:

*  <b>`sample_shape`</b>: 0D or 1D `int32` `Tensor`. Shape of the generated samples.
*  <b>`seed`</b>: Python integer seed for RNG
*  <b>`name`</b>: name to give to the op.

##### Returns:

*  <b>`samples`</b>: a `Tensor` with prepended dimensions `sample_shape`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.sample_n(n, seed=None, name='sample_n')` {#QuantizedDistribution.sample_n}

Generate `n` samples.

##### Args:

*  <b>`n`</b>: `Scalar` `Tensor` of type `int32` or `int64`, the number of
    observations to sample.
*  <b>`seed`</b>: Python integer seed for RNG
*  <b>`name`</b>: name to give to the op.

##### Returns:

*  <b>`samples`</b>: a `Tensor` with a prepended dimension (n,).

##### Raises:

*  <b>`TypeError`</b>: if `n` is not an integer type.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.std(name='std')` {#QuantizedDistribution.std}

Standard deviation.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.survival_function(value, name='survival_function')` {#QuantizedDistribution.survival_function}

Survival function.

Given random variable `X`, the survival function is defined:

```
survival_function(x) = P[X > x]
                     = 1 - P[X <= x]
                     = 1 - cdf(x).
```

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.

##### Returns:

  Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type
    `self.dtype`.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.validate_args` {#QuantizedDistribution.validate_args}

Python boolean indicated possibly expensive checks are enabled.

- - -

#### `tf.contrib.distributions.QuantizedDistribution.variance(name='variance')` {#QuantizedDistribution.variance}

Variance.


text:
import React from 'react';
import { CloudProviderRegistry } from '../CloudProviderRegistry';
import { Modal } from 'react-bootstrap';
import { IModalComponentProps, ReactModal } from 'core/presentation';
import { ModalClose } from 'core/modal';

export interface IProviderSelectionModalProps extends IModalComponentProps {
  providerOptions: string[];
}

export interface IProviderSelectionModalState {
  selectedProvider?: string;
}

export class ProviderSelectionModal extends React.Component<
  IProviderSelectionModalProps,
  IProviderSelectionModalState
> {
  constructor(props: IProviderSelectionModalProps) {
    super(props);
    this.state = {};
  }

  public static show(props: IProviderSelectionModalProps): Promise<string> {
    const modalProps = {};
    return ReactModal.show(ProviderSelectionModal, props, modalProps);
  }

  private setProvider(selectedProvider: string) {
    this.setState({ selectedProvider });
  }

  private cancel = () => {
    this.props.dismissModal();
  };

  private selectProvider = () => {
    this.props.closeModal(this.state.selectedProvider);
  };

  public render() {
    const { selectedProvider } = this.state;
    const { providerOptions } = this.props;

    return (
      <>
        <ModalClose dismiss={this.cancel} />
        <Modal.Header>
          <Modal.Title>Select Your Provider</Modal.Title>
        </Modal.Header>
        <Modal.Body>

            {providerOptions.map((provider) => (
              <div
                className={`card vertical center middle ${selectedProvider === provider && 'active'}`}
                key={provider}
                onClick={() => this.setProvider(provider)}
              >
                {CloudProviderRegistry.hasValue(provider, 'logo.path') && (

                )}
                {!CloudProviderRegistry.hasValue(provider, 'logo.path') &&
{provider}
}

            ))}

        </Modal.Body>
        <Modal.Footer>
          <button className="btn btn-default" onClick={this.cancel}>
            Cancel
          </button>
          <button className="btn btn-primary" onClick={this.selectProvider} disabled={!selectedProvider}>
            Next
          </button>
        </Modal.Footer>
      </>
    );
  }
}


text:
module MediaLibrary
  class Variation < ActiveRecord::Base
    attr_accessible :file, :remote_file_url, :size, :active

    belongs_to :document

    mount_uploader :file, MediaLibrary::DocumentUploader

    validates_presence_of :document_id, :file

    default_scope Proc.new { where(active: true) }
  end
end


text:
package ru.job4j.testtask;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * BomberMan Game class.
 */
public class Game {
    /**
     * game board.
     */
    private final ReentrantLock[][] board;
    /**
     * pool of threads to execute.
     */
    private ExecutorService poll;
    /**
     * number of Monster thread.
     */
    private static int iM = 0;
    /**
     * number of Wall thread.
     */
    private static int iW = 0;
    /**
     * array of theoretical steps.
     */
    private final int[][] dirArr = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    /**
     * Constructor.
     * @param monstersNum - number of Monsters.
     * @param wallsNum - number of Walls.
     * @param boardSize - size of square game board.
     */
    private Game(int monstersNum, int wallsNum, int boardSize) {
        poll = Executors.newFixedThreadPool(monstersNum + wallsNum + 1);
        board = new ReentrantLock[boardSize][boardSize];
        for (int i = 0; i < boardSize; i++) {
            for (int j = 0; j < boardSize; j++) {
                board[i][j] = new ReentrantLock();
            }
        }
        final Player player = new Player(6, 6);
        poll.execute(player);
        final Monster[] monstersArr = new Monster[monstersNum];
        for (int i = 0; i < monstersNum; i++) {
            monstersArr[i] = new Monster(i * 2 + 3, i * 2 + 3);
            System.out.println("Monster " + (i + 1) + "-й stand on position " + (i * 2 + 3) + " " + (i * 2 + 3) + "  " + board[i][i * 2 + 3]);
            poll.execute(monstersArr[i]);
        }
        final Wall[] wallsArr = new Wall[wallsNum];
        for (int i = 0; i < wallsNum; i++) {
            wallsArr[i] = new Wall(i, i + 2);
            System.out.println("Wall " + (i + 1) + "-й stand on position " + i + " " + (i + 2) + "  " + board[i][i + 2]);
            poll.execute(wallsArr[i]);
        }

        for (int i = 0; i < boardSize; i++) {
            for (int j = 0; j < boardSize; j++) {
                System.out.println(i + "  " + j + "  " + board[i][j]);
            }
        }
    }

    /**
     * Player.
     */
    class Player extends Term {
        /**
         * Constructor.
         * @param x - x position.
         * @param y - y position.
         */
        Player(int x, int y) {
            super(x, y);
        }

        /**
         * array of theoretical steps in string representation (for user manual input).
         */
        private String[] arrMove = {"left", "up", "right", "down"};

        /**
         * method for step in decided direction.
         * @param dir - direction.
         * @param curX - current x position.
         * @param curY - current y position.
         * @return - new position.
         */
        int[] move(String dir, int curX, int curY) {
            int[] newPos = {curX, curY};
            switch (dir) {
                case "left":
                    newPos[0] = curX - 1;
                    newPos[1] = curY;
                    System.out.println("////////// иду влево: " + Thread.currentThread().getName());
                    break;
                case "up":
                    newPos[0] = curX;
                    newPos[1] = curY + 1;
                    System.out.println("//////// иду вверх: " + Thread.currentThread().getName());
                    break;
                case "right":
                    newPos[0] = curX + 1;
                    newPos[1] = curY;
                    System.out.println("///////// иду вправо: " + Thread.currentThread().getName());
                    break;
                case "down":
                    newPos[0] = curX;
                    newPos[1] = curY - 1;
                    System.out.println("////////// иду вниз: " + Thread.currentThread().getName());
                    break;
                default:
                    System.out.println("Неправильный ввод. Попробуйте еще раз.");
            }
            return newPos;
        }

        /**
         * overrided run().
         */
        @Override
        public void run() {
            Thread.currentThread().setName("Player");
            int[] playerNewPos;
            board[super.getX()][super.getY()].lock();
            int newX = super.getX();
            int newY = super.getY();
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    if (newX > board.length - 1) {
                        playerNewPos = this.move("left", newX, newY);
                    } else if (newX < 1) {
                        playerNewPos = this.move("right", newX, newY);
                    } else if (newY > board.length - 1) {
                        playerNewPos = this.move("up", newX, newY);
                    } else if (newY < 1) {
                        playerNewPos = this.move("down", newX, newY);
                    } else {
                        playerNewPos = this.move(arrMove[(int) (Math.random() * 4)], newX, newY);
                    }
                    if (board[newX][newY].isHeldByCurrentThread()) {
                        board[newX][newY].unlock();
                    }
                    newX = playerNewPos[0];
                    newY = playerNewPos[1];

                    if (board[newX][newY].tryLock(500, TimeUnit.MILLISECONDS)) {
                        System.out.println("//////////// " + Thread.currentThread().getName() + " думает куда пойти");
                        System.out.println(board[newX][newY] + ": newX " + newX + ", newY " + newY);
                        Thread.sleep(3000);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                board[newX][newY].unlock();
            }
        }
    }

    /**
     * Monster.
     */
    class Monster extends Term {
        /**
         * Constructor.
         * @param x - x position.
         * @param y - y position.
         */
        Monster(int x, int y) {
            super(x, y);
        }
        /**
         * overrided run().
         */
        @Override
        public void run() {
            int[] r;
            Thread.currentThread().setName("Monster" + iM);
            iM++;
            board[super.getX()][super.getY()].lock();
            int newX = super.getX();
            int newY = super.getY();
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    if (board[newX][newY].isHeldByCurrentThread()) {
                        board[newX][newY].unlock();
                    }
                    r = dirArr[(int) (Math.random() * 4)];
                    newX = Math.abs(Math.min(newX + r[0], 9));
                    newY = Math.abs(Math.min(newY + r[1], 9));
                    if (board[newX][newY].tryLock(500, TimeUnit.MILLISECONDS)) {
                        Thread.sleep(2000);
                        System.out.println("************ " + Thread.currentThread().getName() + " думает куда пойти");
                        System.out.println(board[newX][newY] + ": newX " + newX + ", newY " + newY);
                    }
                }
            } catch (InterruptedException e) {
                System.out.println("++++++++++++++++++Монстр вышел из-за закрытия ThreadPool  " + Thread.currentThread().getName());
                e.printStackTrace();
            } finally {
                board[newX][newY].unlock();
            }
        }
    }

    /**
     * Wall.
     */
    class Wall extends Term {
        /**
         * Constructor.
         * @param x - x position.
         * @param y - y position.
         */
        Wall(int x, int y) {
            super(x, y);
        }
        /**
         * overrided run().
         */
        @Override
        public void run() {
            Thread.currentThread().setName("Wall" + iW);
            iW++;
            board[super.getX()][super.getY()].lock();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    board[super.getX()][super.getY()].unlock();
                }
            }
        }
    }

    /**
     * current states of threads (locked/unlocked).
     */
    private void stateOf() {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                System.out.println(i + "  " + j + "  " + board[i][j]);
            }
        }
    }

    /**
     * main().
     * @param args - args.
     */
    public static void main(String[] args) {
        Game game = new Game(3, 2, 10);
        try {
            Thread.sleep(20000);
            System.out.println(Thread.currentThread());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        game.poll.shutdownNow();
        try {
            Thread.sleep(2000);
            System.out.println(Thread.currentThread());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Новое состояние: ");
        game.stateOf();
        System.out.println(game.poll.isTerminated());
    }
}


text:
package org.fseek.simon.swing.filetable.i18n;

import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 *
 * @author Simon Wimmesberger
 */
public class I18nData {
    private static final String[] INIT_BUNDLES = {"org/fseek/simon/swing/filetable/i18n/filetable"};

    private static List<ResourceBundle> bundles;

    static{
        loadBundles();
    }

    public static String get(String name){
        if(bundles == null)throw new IllegalStateException("Bundles not initialized !");
        String value = null;
        for(ResourceBundle rb : bundles){
            try{
                value = rb.getString(name);
                break;
            }catch(MissingResourceException ex){

            }
        }
        return value;
    }

    private static void loadBundles(){
        if(bundles == null){
            bundles = new ArrayList<>();
        }else{
            bundles.clear();
        }
        for(String s : INIT_BUNDLES){
            bundles.add(ResourceBundle.getBundle(s));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Media.Models;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.Media
{
    public partial class MediaJobData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (Optional.IsDefined(Input))
            {
                writer.WritePropertyName("input");
                writer.WriteObjectValue(Input);
            }
            if (Optional.IsCollectionDefined(Outputs))
            {
                writer.WritePropertyName("outputs");
                writer.WriteStartArray();
                foreach (var item in Outputs)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(Priority))
            {
                writer.WritePropertyName("priority");
                writer.WriteStringValue(Priority.Value.ToString());
            }
            if (Optional.IsCollectionDefined(CorrelationData))
            {
                writer.WritePropertyName("correlationData");
                writer.WriteStartObject();
                foreach (var item in CorrelationData)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static MediaJobData DeserializeMediaJobData(JsonElement element)
        {
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            Optional<DateTimeOffset> created = default;
            Optional<MediaJobState> state = default;
            Optional<string> description = default;
            Optional<MediaJobInputBasicProperties> input = default;
            Optional<DateTimeOffset> lastModified = default;
            Optional<IList<MediaJobOutput>> outputs = default;
            Optional<MediaJobPriority> priority = default;
            Optional<IDictionary<string, string>> correlationData = default;
            Optional<DateTimeOffset?> startTime = default;
            Optional<DateTimeOffset?> endTime = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("created"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            created = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("state"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            state = new MediaJobState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("description"))
                        {
                            description = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("input"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            input = MediaJobInputBasicProperties.DeserializeMediaJobInputBasicProperties(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("lastModified"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            lastModified = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("outputs"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<MediaJobOutput> array = new List<MediaJobOutput>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(MediaJobOutput.DeserializeMediaJobOutput(item));
                            }
                            outputs = array;
                            continue;
                        }
                        if (property0.NameEquals("priority"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            priority = new MediaJobPriority(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("correlationData"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, property1.Value.GetString());
                            }
                            correlationData = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("startTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                startTime = null;
                                continue;
                            }
                            startTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("endTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                endTime = null;
                                continue;
                            }
                            endTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new MediaJobData(id, name, type, systemData.Value, Optional.ToNullable(created), Optional.ToNullable(state), description.Value, input.Value, Optional.ToNullable(lastModified), Optional.ToList(outputs), Optional.ToNullable(priority), Optional.ToDictionary(correlationData), Optional.ToNullable(startTime), Optional.ToNullable(endTime));
        }
    }
}


text:
//
//  BannerView.m
//  KBLove
//
//  Created by 吴铭博 on 14-10-11.
//  Copyright (c) 2014年 block. All rights reserved.
//

#import "BannerView.h"
//#import "UIImageView+AFNetworking.h"

@implementation BannerView

/**
 *  从storyboard创建时调用
 */
- (void)awakeFromNib{
    // 添加ScrollView
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;

    // 添加PageControl
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.center = CGPointMake(self.width * 0.5, self.height - 10);
    pageControl.bounds = CGRectMake(0, 0, 320, 20);

    // 设置非选中页的圆点颜色
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    // 设置选中页的圆点颜色
    pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    // 禁止默认的点击功能
    pageControl.enabled = NO;
    [self addSubview:pageControl];
    _pageControl = pageControl;
    // 将scrollView添加到视图
    [self insertSubview:_scrollView atIndex:0];
}

/**
 *  当被布局到某个view或者调用setNeedsDisplay时调用
 */
- (void)layoutSubviews {

    _scrollView.frame = CGRectMake(0, 0, self.width, self.height);

    _pageControl.center = CGPointMake(self.width * 0.5, self.height - 10);
    _pageControl.bounds = CGRectMake(0, 0, 320, 20);

}

//给banner赋值
- (void)setImageWithArray:(NSArray *)imageArray andIsAutoScroll:(BOOL)isAutoScroll{
    CGFloat w = self.size.width;
    CGFloat h = self.size.height;

    _imageArray = imageArray;

    // 添加内容图片视图imageView
    for (int i = 0; i<[_imageArray count]; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * w, 0, w, h)];
        imageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:i]];
        [_scrollView addSubview:imageView];

    }
    // 在后面多加一页 实现循环滚动
    UIImageView *fristImageView = [[UIImageView alloc] initWithFrame:CGRectMake([_imageArray count] * w, 0, w, h)];

#warning 滚动视图图片优化
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:_imageArray.firstObject ofType:nil];
    fristImageView.image = [UIImage imageWithContentsOfFile:imagePath];

//    fristImageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:0]];

    [_scrollView addSubview:fristImageView];
    // 设置ScrollView属性 contentSize 加上最后多加的那一页
    _scrollView.contentSize = CGSizeMake(([_imageArray count] +1 ) * w, h);

    // 一共显示多少个圆点(多少页)
    _pageControl.numberOfPages = [_imageArray count];

    //是否自动滚动
    if (isAutoScroll) {
        [self addTimer];
    }

}

/** 添加计时器*/
- (void)addTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(autoScroll:) userInfo:_scrollView repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

// 定时器响应方法,实现自动滚动
-(void)autoScroll:(NSTimer *)timer {
    CGPoint offset = _scrollView.contentOffset;
    CGFloat width = _scrollView.frame.size.width;
    // 设置偏移量到下一页
    offset.x += width;
    [_scrollView setContentOffset:offset animated:YES];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer invalidate];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat width = _scrollView.frame.size.width;
    // 循环滚动
    if (_scrollView.contentOffset.x / width == [_imageArray count]) {
        // 当翻转到'假'的第一页,设置偏移量到真实的第一页 不开启动画
        [_scrollView setContentOffset:CGPointZero animated:NO];
    }
    if (_scrollView.contentOffset.x / width <0) {
        // 当翻转到'假'的第一页,设置偏移量到真实的第一页 不开启动画
        [_scrollView setContentOffset:CGPointMake(320 * 5 + 300, 0) animated:NO];
    }
    // 根据偏移量计算页码
    int page = (scrollView.contentOffset.x + self.bounds.size.width * 0.5) / scrollView.frame.size.width;
    _pageControl.currentPage = page%[_imageArray count];
    if (page >= 6) {
        page = 0;
    }

}

@end


text:
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}

module Leankit.Types.User where

import Data.Aeson.TH

import Leankit.Types.TH
import Leankit.Types.Common

data User = User {
		_id             :: UserID,
		_userName       :: String,
		_fullName       :: Maybe String,
		_emailAddress   :: Maybe String,

		_gravatarFeed   :: Maybe String,
		_gravatarLink   :: Maybe String,

		_role           :: Maybe Int,
		_roleName       :: Maybe String,

		_enabled        :: Maybe Bool,
		_isAccountOwner :: Maybe Bool,
		_isDeleted      :: Maybe Bool,

		_dateFormat     :: Maybe String,
		_wip            :: Maybe Int
} deriving (Eq, Show)

$(deriveFromJSON parseOptions ''User)


text:
require 'taxjar/base'

module Taxjar
  class Address < Taxjar::Base
    extend ModelAttribute

    attribute :country, :string
    attribute :state,   :string
    attribute :zip,     :string
    attribute :city,    :string
    attribute :street,  :string
  end
end


text:
module Trello
  module Reports
    class Checklist
      def initialize(task, card, environment)
        @task = task
        @card = card
        @environment = environment
      end

      def call
        environment_checklists
      end

      private

      attr_reader :task, :card, :environment

      def checklist
        @checklist ||= begin
          found_checklist = card.checklists.keep_if  do |item|
            item.name == environment.checklist_name
          end.first

          return if found_checklist.nil?

          Trello::Checklist.find(found_checklist.id)
        end
      end

      def complete_item(item)
        checklist.add_item(item.name, true)
        checklist.delete_checklist_item(item.id)
      end

      def environment_checklists
        return if checklist.nil?

        checklist.items.map do |item|
          begin
            complete_item(item)
            task.checklists.create!(description: item.name)
          rescue ActiveRecord::RecordInvalid => invalid
            p "ERRORS: ", invalid.record.errors
            next
          end
        end
      end
    end
  end
end


text:
namespace doppia {

class SoftCascadeOverIntegralChannelsModel;
typedef doppia::objects_detection::gpu_detections_t gpu_detections_t;
typedef gpu_detections_t::Type gpu_detection_t;

/// This is the GPU variant of IntegralChannelsDetector
/// @see IntegralChannelsDetector
class GpuIntegralChannelsDetector: public virtual BaseIntegralChannelsDetector
{

public:

    typedef SoftCascadeOverIntegralChannelsModel::fast_stage_t fast_stage_t;
    typedef SoftCascadeOverIntegralChannelsModel::stump_stage_t stump_stage_t;

    typedef SoftCascadeOverIntegralChannelsModel::two_stumps_stage_t two_stumps_stage_t;
    typedef SoftCascadeOverIntegralChannelsModel::three_stumps_stage_t three_stumps_stage_t;
    typedef SoftCascadeOverIntegralChannelsModel::four_stumps_stage_t four_stumps_stage_t;

    // using Pitched allocation for a custom type makes us run into troubles,
    // we used linear allocation, even is slightly less efficient GPU access (to be fixed...)
    //typedef Cuda::DeviceMemoryPitched2D<cascade_stage_t> gpu_detection_cascade_per_scale_t;
    typedef Cuda::DeviceMemoryLinear2D<fast_stage_t> gpu_detection_cascade_per_scale_t;
    typedef Cuda::DeviceMemoryLinear2D<stump_stage_t> gpu_detection_stump_cascade_per_scale_t;

    typedef Cuda::DeviceMemoryLinear2D<two_stumps_stage_t> gpu_detection_two_stumps_cascade_per_scale_t;
    typedef Cuda::DeviceMemoryLinear2D<three_stumps_stage_t> gpu_detection_three_stumps_cascade_per_scale_t;
    typedef Cuda::DeviceMemoryLinear2D<four_stumps_stage_t> gpu_detection_four_stumps_cascade_per_scale_t;

    typedef SoftCascadeOverIntegralChannelsModel::fast_fractional_stage_t fractional_cascade_stage_t;
    typedef Cuda::DeviceMemoryLinear2D<fractional_cascade_stage_t> gpu_fractional_detection_cascade_per_scale_t;

    // list of all possible stages types
    typedef
    boost::variant<
    gpu_detection_cascade_per_scale_t, // classic one
    gpu_detection_stump_cascade_per_scale_t, // bad idea 1
    gpu_fractional_detection_cascade_per_scale_t, // bad idea 2
    gpu_detection_two_stumps_cascade_per_scale_t, // stump sets (2,3,4)
    gpu_detection_three_stumps_cascade_per_scale_t,
    gpu_detection_four_stumps_cascade_per_scale_t
    >  gpu_detection_variant_cascade_per_scale_t;

public:

    static boost::program_options::options_description get_args_options();

    GpuIntegralChannelsDetector(
            const boost::program_options::variables_map &options,
            boost::shared_ptr<SoftCascadeOverIntegralChannelsModel> cascade_model_p,
            boost::shared_ptr<AbstractNonMaximalSuppression> non_maximal_suppression_p,
            const float score_threshold, const int additional_border);
    ~GpuIntegralChannelsDetector();

    void set_image(const boost::gil::rgb8c_view_t &input_image,
                   const std::string &image_file_path = std::string());
    void compute();

protected:

    const bool frugal_memory_usage;

    boost::shared_ptr<AbstractGpuIntegralChannelsComputer> integral_channels_computer_p;

    cv::gpu::CudaMem input_rgb8_gpu_mem; // allows for faster data upload
    cv::Mat input_rgb8_gpu_mem_mat; // allows for faster data upload
    cv::gpu::GpuMat input_rgb8_gpu_mat, input_gpu_mat;

    /// helper vector avoid unecessary GPU re-allocations
    std::vector<cv::gpu::GpuMat> resized_input_gpu_matrices;
    size_t previous_resized_input_gpu_matrix_index;

    gpu_detection_variant_cascade_per_scale_t gpu_detection_variant_cascade_per_scale;

    virtual void set_gpu_scale_detection_cascades();

    gpu_detections_t gpu_detections;
    size_t num_gpu_detections;

    size_t get_input_width() const;
    size_t get_input_height() const;

    /// shared section of code between
    /// compute_detections_at_specific_scale_v0 and compute_detections_at_specific_scale_v1
    doppia::objects_detection::gpu_integral_channels_t &
    resize_input_and_compute_integral_channels(const size_t search_range_index,
                                               const bool first_call = false);

    /// computes the score image on GPU, transfer to CPU and find the detections
    void compute_detections_at_specific_scale_v0(const size_t search_range_index,
                                                 const bool save_score_image = false,
                                                 const bool first_call = false);

    /// computes the detections directly on GPU, avoiding the score image transfer
    virtual void compute_detections_at_specific_scale_v1(const size_t search_range_index,
                                                         const bool first_call);

    void collect_the_gpu_detections();

#if defined(BOOTSTRAPPING_LIB)
    friend class bootstrapping::FalsePositivesDataCollector;
    float current_image_scale;

    /// we keep the detections on the rescaled image coordinates,
    /// instead of mapping them back to the original image scale
    detections_t non_rescaled_detections;
#endif

};

} // end of namespace doppia

#endif // GPUINTEGRALCHANNELSDETECTOR_HPP


text:
namespace AutoMapper.UnitTests.Bug
{
    namespace SetterOnlyBug
    {
        using Shouldly;
        using Xunit;

        public class MappingTests : AutoMapperSpecBase
        {
            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
            {
                cfg
                    .CreateMap<Source, Desitination>()
                    .ForMember("Property", o => o.Ignore());
            });

            [Fact]
            public void TestMapping()
            {
                var source = new Source
                {
                    Property = "Something"
                };
                var destination = Mapper.Map<Source, Desitination>(source);

                destination.GetProperty().ShouldBeNull();
            }
        }

        public class Source
        {
            public string Property { get; set; }
        }

        public class Desitination
        {
            string _property;

            public string Property
            {
                set { _property = value; }
            }

            public string GetProperty()
            {
                return _property;
            }
        }
    }
}


text:
SleepInStudyRoom
================


text:
My Personal Website.

Visit it from http://www.atakanermis.tk


text:
<?xml version="1.0" encoding="UTF-8"?>
<sql:table name="Binary" xmlns:sql="http://xsd.nore.fr/sql/2.0">
	<sql:column name="basic">
		<sql:comment>Binary column</sql:comment>
		<sql:datatype>
			<sql:binary />
		</sql:datatype>
	</sql:column>
	<sql:column name="string">
		<sql:comment>Binary column with a string default value "abcd" / 0x61626364</sql:comment>
		<sql:datatype>
			<sql:binary />
		</sql:datatype>
		<sql:default>
			<!-- 0x61626364 -->
			<sql:string>abcd</sql:string>
		</sql:default>
	</sql:column>
	<sql:column name="integer">
		<sql:comment>Binary column with a integer default value 2048 / 0x0800</sql:comment>
		<sql:datatype>
			<sql:binary />
		</sql:datatype>
		<sql:default>
			<!-- 0x0800 -->
			<sql:integer>2048</sql:integer>
		</sql:default>
	</sql:column>
	<sql:column name="hexadecimal">
		<sql:comment>Binary column with a hexadecimal default value 0x61626364 / "abcd"</sql:comment>
		<sql:datatype>
			<sql:binary />
		</sql:datatype>
		<sql:default>
			<!-- abcd -->
			<sql:hexBinary>61626364</sql:hexBinary>
		</sql:default>
	</sql:column>
	<sql:column name="base64">
		<sql:comment>Binary column with a Base64-encoded default value YWJjZA== / 0x61626364 / "abcd"</sql:comment>
		<sql:datatype>
			<sql:binary />
		</sql:datatype>
		<sql:default>
			<sql:base64Binary>YWJjZA==</sql:base64Binary>
		</sql:default>
	</sql:column>
</sql:table>


text:
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.

Classes which implement tasks which builder has to be capable of doing.
Logic above these classes has to set the workflow itself.
"""
import json

import logging
from atomic_reactor.core import DockerTasker, LastLogger
from atomic_reactor.util import ImageName, print_version_of_tools, df_parser
from atomic_reactor.constants import DOCKERFILE_FILENAME

logger = logging.getLogger(__name__)

class ImageAlreadyBuilt(Exception):
    """ This method expects image not to be built but it already is """

class ImageNotBuilt(Exception):
    """ This method expects image to be already built but it is not """

class BuilderStateMachine(object):
    def __init__(self):
        self.is_built = False
        self.image = None

    def ensure_is_built(self):
        """
        ensure that image is already built

        :return: None
        """
        if not self.is_built:
            logger.error("image '%s' is not built yet!", self.image)
            raise ImageNotBuilt()

    def ensure_not_built(self):
        """
        verify that image wasn't built with 'build' method yet

        :return: None
        """
        if self.is_built:
            logger.error("image '%s' is already built!", self.image)
            raise ImageAlreadyBuilt()

class BuildResult(object):

    REMOTE_IMAGE = object()

    def __init__(self, logs=None, fail_reason=None, image_id=None,
                 annotations=None, labels=None):
        """
        :param logs: iterable of log lines (without newlines)
        :param fail_reason: str, description of failure or None if successful
        :param image_id: str, ID of built container image
        :param annotations: dict, data captured during build step which
                            should be annotated to OpenShift build
        :param labels: dict, data captured during build step which
                       should be set as labels on OpenShift build
        """
        assert fail_reason is None or bool(fail_reason), \
            "If fail_reason provided, can't be falsy"
        # must provide one, not both
        assert bool(fail_reason) != bool(image_id), \
            "Either fail_reason or image_id should be provided, not both"
        self._logs = logs or []
        self._fail_reason = fail_reason
        self._image_id = image_id
        self._annotations = annotations
        self._labels = labels

    @staticmethod
    def make_remote_image_result(annotations=None, labels=None):
        """Instantiate BuildResult for image not built locally."""
        return BuildResult(image_id=BuildResult.REMOTE_IMAGE,
                           annotations=annotations, labels=labels)

    @property
    def logs(self):
        return self._logs

    @property
    def fail_reason(self):
        return self._fail_reason

    def is_failed(self):
        return self._fail_reason is not None

    @property
    def image_id(self):
        return self._image_id

    @property
    def annotations(self):
        return self._annotations

    @property
    def labels(self):
        return self._labels

    def is_image_available(self):
        return self._image_id and self._image_id is not self.REMOTE_IMAGE

class InsideBuilder(LastLogger, BuilderStateMachine):
    """
    This is expected to run within container
    """

    def __init__(self, source, image, **kwargs):
        """
        """
        LastLogger.__init__(self)
        BuilderStateMachine.__init__(self)

        print_version_of_tools()

        self.tasker = DockerTasker()

        info, version = self.tasker.get_info(), self.tasker.get_version()
        logger.debug(json.dumps(info, indent=2))
        logger.info(json.dumps(version, indent=2))

        # arguments for build
        self.source = source
        self.base_image = None
        self.image_id = None
        self.built_image_info = None
        self.image = ImageName.parse(image)

        # get info about base image from dockerfile
        build_file_path, build_file_dir = self.source.get_build_file_path()

        self.df_dir = build_file_dir
        self._df_path = None

        # If the build file isn't a Dockerfile, but say, a flatpak.json then a
        # plugin needs to create the Dockerfile and set the base image
        if build_file_path.endswith(DOCKERFILE_FILENAME):
            self.set_df_path(build_file_path)

    @property
    def df_path(self):
        if self._df_path is None:
            raise AttributeError("Dockerfile has not yet been generated")

        return self._df_path

    def set_df_path(self, path):
        self._df_path = path
        self.set_base_image(df_parser(path).baseimage)
        logger.debug("base image specified in dockerfile = '%s'", self.base_image)
        if not self.base_image.tag:
            self.base_image.tag = 'latest'

    def set_base_image(self, base_image):
        self.base_image = ImageName.parse(base_image)

    def inspect_base_image(self):
        """
        inspect base image

        :return: dict
        """
        logger.info("inspecting base image '%s'", self.base_image)
        inspect_data = self.tasker.inspect_image(self.base_image)
        return inspect_data

    def inspect_built_image(self):
        """
        inspect built image

        :return: dict
        """
        logger.info("inspecting built image '%s'", self.image_id)
        self.ensure_is_built()
        # dict with lots of data, see man docker-inspect
        inspect_data = self.tasker.inspect_image(self.image_id)
        return inspect_data

    def get_base_image_info(self):
        """
        query docker about base image

        :return dict
        """
        logger.info("getting information about base image '%s'", self.base_image)
        image_info = self.tasker.get_image_info_by_image_name(self.base_image)
        items_count = len(image_info)
        if items_count == 1:
            return image_info[0]
        elif items_count <= 0:
            logger.error("image '%s' not found", self.base_image)
            raise RuntimeError("image '%s' not found", self.base_image)
        else:
            logger.error("multiple (%d) images found for image '%s'", items_count,
                         self.base_image)
            raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
                                                                              self.base_image))

    def get_built_image_info(self):
        """
        query docker about built image

        :return dict
        """
        logger.info("getting information about built image '%s'", self.image)
        image_info = self.tasker.get_image_info_by_image_name(self.image)
        items_count = len(image_info)
        if items_count == 1:
            return image_info[0]
        elif items_count <= 0:
            logger.error("image '%s' not found", self.image)
            raise RuntimeError("image '%s' not found" % self.image)
        else:
            logger.error("multiple (%d) images found for image '%s'", items_count, self.image)
            raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
                                                                              self.image))