text:
(function() {

module('call-remote-callbacks', {
  setup: function() {
    $('#qunit-fixture').append($('<form />', {
      action: '/echo', method: 'get', 'data-remote': 'true'
    }))
  },
  teardown: function() {
    $(document).undelegate('form[data-remote]', 'ajax:beforeSend')
    $(document).undelegate('form[data-remote]', 'ajax:before')
    $(document).undelegate('form[data-remote]', 'ajax:send')
    $(document).undelegate('form[data-remote]', 'ajax:complete')
    $(document).undelegate('form[data-remote]', 'ajax:success')
    $(document).unbind('iframe:loading')
  }
})

function submit(fn) {
  var form = $('form')

  if (fn) fn(form)
  form.triggerNative('submit')

  setTimeout(function() { start() }, 13)
}

asyncTest('modifying form fields with "ajax:before" sends modified data in request', 3, function() {
  $('form[data-remote]')
    .append($('<input type="text" name="user_name" value="john">'))
    .append($('<input type="text" name="removed_user_name" value="john">'))
    .bindNative('ajax:before', function() {
      var form = $(this)
      form
        .append($('<input />', {name: 'other_user_name', value: 'jonathan'}))
        .find('input[name="removed_user_name"]').remove()
      form
        .find('input[name="user_name"]').val('steve')
    })

  submit(function(form) {
    form.bindNative('ajax:success', function(e, data, status, xhr) {
      equal(data.params.user_name, 'steve', 'modified field value should have been submitted')
      equal(data.params.other_user_name, 'jonathan', 'added field value should have been submitted')
      equal(data.params.removed_user_name, undefined, 'removed field value should be undefined')
    })
  })
})

asyncTest('modifying data("type") with "ajax:before" requests new dataType in request', 1, function() {
  $('form[data-remote]').data('type', 'html')
    .bindNative('ajax:before', function() {
      this.setAttribute('data-type', 'xml')
    })

  submit(function(form) {
    form.bindNative('ajax:beforeSend', function(e, xhr, settings) {
      equal(settings.dataType, 'xml', 'modified dataType should have been requested')
    })
  })
})

asyncTest('setting data("with-credentials",true) with "ajax:before" uses new setting in request', 1, function() {
  $('form[data-remote]').data('with-credentials', false)
    .bindNative('ajax:before', function() {
      this.setAttribute('data-with-credentials', true)
    })

  submit(function(form) {
    form.bindNative('ajax:beforeSend', function(e, xhr, settings) {
      equal(settings.withCredentials, true, 'setting modified in ajax:before should have forced withCredentials request')
    })
  })
})

asyncTest('stopping the "ajax:beforeSend" event aborts the request', 1, function() {
  submit(function(form) {
    form.bindNative('ajax:beforeSend', function(e) {
      ok(true, 'aborting request in ajax:beforeSend')
      e.preventDefault()
    })
    form.unbind('ajax:send').bindNative('ajax:send', function() {
      ok(false, 'ajax:send should not run')
    })
    form.bindNative('ajax:error', function(e, response, status, xhr) {
      ok(false, 'ajax:error should not run')
    })
    form.bindNative('ajax:complete', function() {
      ok(false, 'ajax:complete should not run')
    })
  })
})

function skipIt() {
  // This test cannot work due to the security feature in browsers which makes the value
  // attribute of file input fields readonly, so it cannot be set with default value.
  // This is what the test would look like though if browsers let us automate this test.
  asyncTest('non-blank file form input field should abort remote request, but submit normally', 5, function() {
    var form = $('form[data-remote]')
          .append($('<input type="file" name="attachment" value="default.png">'))
          .bindNative('ajax:beforeSend', function() {
            ok(false, 'ajax:beforeSend should not run')
          })
          .bind('iframe:loading', function() {
            ok(true, 'form should get submitted')
          })
          .bindNative('ajax:aborted:file', function(e, data) {
            ok(data.length == 1, 'ajax:aborted:file event is passed all non-blank file inputs (jQuery objects)')
            ok(data.first().is('input[name="attachment"]'), 'ajax:aborted:file adds non-blank file input to data')
            ok(true, 'ajax:aborted:file event should run')
          })
          .triggerNative('submit')

    setTimeout(function() {
      form.find('input[type="file"]').val('')
      form.unbind('ajax:beforeSend')
      submit()
    }, 13)
  })

  asyncTest('file form input field should not abort remote request if file form input does not have a name attribute', 5, function() {
    var form = $('form[data-remote]')
          .append($('<input type="file" value="default.png">'))
          .bindNative('ajax:beforeSend', function() {
            ok(true, 'ajax:beforeSend should run')
          })
          .bind('iframe:loading', function() {
            ok(true, 'form should get submitted')
          })
          .bindNative('ajax:aborted:file', function(e, data) {
            ok(false, 'ajax:aborted:file should not run')
          })
          .triggerNative('submit')

    setTimeout(function() {
      form.find('input[type="file"]').val('')
      form.unbind('ajax:beforeSend')
      submit()
    }, 13)
  })

  asyncTest('blank file input field should abort request entirely if handler bound to "ajax:aborted:file" event that returns false', 1, function() {
    var form = $('form[data-remote]')
          .append($('<input type="file" name="attachment" value="default.png">'))
          .bindNative('ajax:beforeSend', function() {
            ok(false, 'ajax:beforeSend should not run')
          })
          .bind('iframe:loading', function() {
            ok(false, 'form should not get submitted')
          })
          .bindNative('ajax:aborted:file', function(e) {
            e.preventDefault()
          })
          .triggerNative('submit')

    setTimeout(function() {
      form.find('input[type="file"]').val('')
      form.unbind('ajax:beforeSend')
      submit()
    }, 13)
  })
}

asyncTest('"ajax:beforeSend" can be observed and stopped with event delegation', 1, function() {
  $(document).delegate('form[data-remote]', 'ajax:beforeSend', function(e) {
    ok(true, 'ajax:beforeSend observed with event delegation')
    e.preventDefault()
  })

  submit(function(form) {
    form.unbind('ajax:send').bindNative('ajax:send', function() {
      ok(false, 'ajax:send should not run')
    })
    form.bindNative('ajax:complete', function() {
      ok(false, 'ajax:complete should not run')
    })
  })
})

asyncTest('"ajax:beforeSend", "ajax:send", "ajax:success" and "ajax:complete" are triggered', 8, function() {
  submit(function(form) {
    form.bindNative('ajax:beforeSend', function(e, xhr, settings) {
      ok(xhr.setRequestHeader, 'first argument to "ajax:beforeSend" should be an XHR object')
      equal(settings.url, '/echo', 'second argument to "ajax:beforeSend" should be a settings object')
    })
    form.bindNative('ajax:send', function(e, xhr) {
      ok(xhr.abort, 'first argument to "ajax:send" should be an XHR object')
    })
    form.bindNative('ajax:success', function(e, data, status, xhr) {
      ok(data.REQUEST_METHOD, 'first argument to ajax:success should be a data object')
      equal(status, 'OK', 'second argument to ajax:success should be a status string')
      ok(xhr.getResponseHeader, 'third argument to "ajax:success" should be an XHR object')
    })
    form.bindNative('ajax:complete', function(e, xhr, status) {
      ok(xhr.getResponseHeader, 'first argument to "ajax:complete" should be an XHR object')
      equal(status, 'OK', 'second argument to ajax:complete should be a status string')
    })
  })
})

asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 8, function() {
  submit(function(form) {
    form.attr('action', '/error')
    form.bindNative('ajax:beforeSend', function(arg) { ok(true, 'ajax:beforeSend') })
    form.bindNative('ajax:send', function(arg) { ok(true, 'ajax:send') })
    form.bindNative('ajax:error', function(e, response, status, xhr) {
      equal(response, '', 'first argument to ajax:error should be an HTTP status response')
      equal(status, 'Forbidden', 'second argument to ajax:error should be a status string')
      ok(xhr.getResponseHeader, 'third argument to "ajax:error" should be an XHR object')
      // Opera returns "0" for HTTP code
      equal(xhr.status, window.opera ? 0 : 403, 'status code should be 403')
    })
    form.bindNative('ajax:complete', function(e, xhr, status) {
      ok(xhr.getResponseHeader, 'first argument to "ajax:complete" should be an XHR object')
      equal(status, 'Forbidden', 'second argument to ajax:complete should be a status string')
    })
  })
})

asyncTest('binding to ajax callbacks via .delegate() triggers handlers properly', 4, function() {
  $(document)
    .delegate('form[data-remote]', 'ajax:beforeSend', function() {
      ok(true, 'ajax:beforeSend handler is triggered')
    })
    .delegate('form[data-remote]', 'ajax:send', function() {
      ok(true, 'ajax:send handler is triggered')
    })
    .delegate('form[data-remote]', 'ajax:success', function() {
      ok(true, 'ajax:success handler is triggered')
    })
    .delegate('form[data-remote]', 'ajax:complete', function() {
      ok(true, 'ajax:complete handler is triggered')
    })
  $('form[data-remote]').triggerNative('submit')

  setTimeout(function() { start() }, 13)
})

})()


text:
// Copyright (c) 2018-2020 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <policy/policy.h>
#include <script/interpreter.h>

#include <test/lcg.h>
#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

#include <array>
#include <bitset>

typedef std::vector<uint8_t> valtype;
typedef std::vector<valtype> stacktype;

BOOST_FIXTURE_TEST_SUITE(checkdatasig_tests, BasicTestingSetup)

std::array<uint32_t, 3> flagset{{0, STANDARD_SCRIPT_VERIFY_FLAGS}};

const uint8_t vchPrivkey[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};

struct KeyData {
    CKey privkey, privkeyC;
    CPubKey pubkey, pubkeyC, pubkeyH;

    KeyData() {
        privkey.Set(vchPrivkey, vchPrivkey + 32, false);
        privkeyC.Set(vchPrivkey, vchPrivkey + 32, true);
        pubkey = privkey.GetPubKey();
        pubkeyH = privkey.GetPubKey();
        pubkeyC = privkeyC.GetPubKey();
        *const_cast<uint8_t *>(&pubkeyH[0]) = 0x06 | (pubkeyH[64] & 1);
    }
};

static void CheckError(uint32_t flags, const stacktype &original_stack,
                       const CScript &script, ScriptError expected) {
    BaseSignatureChecker sigchecker;
    ScriptError err = ScriptError::OK;
    stacktype stack{original_stack};
    bool r = EvalScript(stack, script, flags, sigchecker, &err);
    BOOST_CHECK(!r);
    BOOST_CHECK(err == expected);
}

static void CheckPass(uint32_t flags, const stacktype &original_stack,
                      const CScript &script, const stacktype &expected) {
    BaseSignatureChecker sigchecker;
    ScriptError err = ScriptError::OK;
    stacktype stack{original_stack};
    bool r = EvalScript(stack, script, flags, sigchecker, &err);
    BOOST_CHECK(r);
    BOOST_CHECK(err == ScriptError::OK);
    BOOST_CHECK(stack == expected);
}

/**
 * General utility functions to check for script passing/failing.
 */
static void CheckTestResultForAllFlags(const stacktype &original_stack,
                                       const CScript &script,
                                       const stacktype &expected) {
    for (uint32_t flags : flagset) {
        CheckPass(flags, original_stack, script, expected);
    }
}

static void CheckErrorForAllFlags(const stacktype &original_stack,
                                  const CScript &script, ScriptError expected) {
    for (uint32_t flags : flagset) {
        CheckError(flags, original_stack, script, expected);
    }
}

BOOST_AUTO_TEST_CASE(checkdatasig_test) {
    // Empty stack.
    CheckErrorForAllFlags({}, CScript() << OP_CHECKDATASIG,
                          ScriptError::INVALID_STACK_OPERATION);
    CheckErrorForAllFlags({{0x00}}, CScript() << OP_CHECKDATASIG,
                          ScriptError::INVALID_STACK_OPERATION);
    CheckErrorForAllFlags({{0x00}, {0x00}}, CScript() << OP_CHECKDATASIG,
                          ScriptError::INVALID_STACK_OPERATION);
    CheckErrorForAllFlags({}, CScript() << OP_CHECKDATASIGVERIFY,
                          ScriptError::INVALID_STACK_OPERATION);
    CheckErrorForAllFlags({{0x00}}, CScript() << OP_CHECKDATASIGVERIFY,
                          ScriptError::INVALID_STACK_OPERATION);
    CheckErrorForAllFlags({{0x00}, {0x00}}, CScript() << OP_CHECKDATASIGVERIFY,
                          ScriptError::INVALID_STACK_OPERATION);

    // Check various pubkey encoding.
    const valtype message{};
    valtype vchHash(32);
    CSHA256().Write(message.data(), message.size()).Finalize(vchHash.data());
    uint256 messageHash(vchHash);

    KeyData kd;
    valtype pubkey = ToByteVector(kd.pubkey);
    valtype pubkeyC = ToByteVector(kd.pubkeyC);
    valtype pubkeyH = ToByteVector(kd.pubkeyH);

    CheckTestResultForAllFlags({{}, message, pubkey},
                               CScript() << OP_CHECKDATASIG, {{}});
    CheckTestResultForAllFlags({{}, message, pubkeyC},
                               CScript() << OP_CHECKDATASIG, {{}});
    CheckErrorForAllFlags({{}, message, pubkey},
                          CScript() << OP_CHECKDATASIGVERIFY,
                          ScriptError::CHECKDATASIGVERIFY);
    CheckErrorForAllFlags({{}, message, pubkeyC},
                          CScript() << OP_CHECKDATASIGVERIFY,
                          ScriptError::CHECKDATASIGVERIFY);

    // Flags dependent checks.
    const CScript script = CScript() << OP_CHECKDATASIG << OP_NOT << OP_VERIFY;
    const CScript scriptverify = CScript() << OP_CHECKDATASIGVERIFY;

    // Check valid signatures (as in the signature format is valid).
    valtype validsig;
    kd.privkey.SignECDSA(messageHash, validsig);

    CheckTestResultForAllFlags({validsig, message, pubkey},
                               CScript() << OP_CHECKDATASIG, {{0x01}});
    CheckTestResultForAllFlags({validsig, message, pubkey},
                               CScript() << OP_CHECKDATASIGVERIFY, {});

    const valtype minimalsig{0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01};
    const valtype nondersig{0x30, 0x80, 0x06, 0x02, 0x01,
                            0x01, 0x02, 0x01, 0x01};
    const valtype highSSig{
        0x30, 0x45, 0x02, 0x20, 0x3e, 0x45, 0x16, 0xda, 0x72, 0x53, 0xcf, 0x06,
        0x8e, 0xff, 0xec, 0x6b, 0x95, 0xc4, 0x12, 0x21, 0xc0, 0xcf, 0x3a, 0x8e,
        0x6c, 0xcb, 0x8c, 0xbf, 0x17, 0x25, 0xb5, 0x62, 0xe9, 0xaf, 0xde, 0x2c,
        0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45,
        0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5,
        0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0};

    MMIXLinearCongruentialGenerator lcg;
    for (int i = 0; i < 4096; i++) {
        uint32_t flags = lcg.next();

        if (flags & SCRIPT_VERIFY_STRICTENC) {
            // When strict encoding is enforced, hybrid keys are invalid.
            CheckError(flags, {{}, message, pubkeyH}, script,
                       ScriptError::PUBKEYTYPE);
            CheckError(flags, {{}, message, pubkeyH}, scriptverify,
                       ScriptError::PUBKEYTYPE);
        } else {
            // Otherwise, hybrid keys are valid.
            CheckPass(flags, {{}, message, pubkeyH}, script, {});
            CheckError(flags, {{}, message, pubkeyH}, scriptverify,
                       ScriptError::CHECKDATASIGVERIFY);
        }

        // Uncompressed keys are valid.
        CheckPass(flags, {{}, message, pubkey}, script, {});
        CheckError(flags, {{}, message, pubkey}, scriptverify,
                   ScriptError::CHECKDATASIGVERIFY);

        if (flags & SCRIPT_VERIFY_NULLFAIL) {
            // Invalid signature causes checkdatasig to fail.
            CheckError(flags, {minimalsig, message, pubkeyC}, script,
                       ScriptError::SIG_NULLFAIL);
            CheckError(flags, {minimalsig, message, pubkeyC}, scriptverify,
                       ScriptError::SIG_NULLFAIL);

            // Invalid message causes checkdatasig to fail.
            CheckError(flags, {validsig, {0x01}, pubkeyC}, script,
                       ScriptError::SIG_NULLFAIL);
            CheckError(flags, {validsig, {0x01}, pubkeyC}, scriptverify,
                       ScriptError::SIG_NULLFAIL);
        } else {
            // When nullfail is not enforced, invalid signature are just false.
            CheckPass(flags, {minimalsig, message, pubkeyC}, script, {});
            CheckError(flags, {minimalsig, message, pubkeyC}, scriptverify,
                       ScriptError::CHECKDATASIGVERIFY);

            // Invalid message cause checkdatasig to fail.
            CheckPass(flags, {validsig, {0x01}, pubkeyC}, script, {});
            CheckError(flags, {validsig, {0x01}, pubkeyC}, scriptverify,
                       ScriptError::CHECKDATASIGVERIFY);
        }

        if (flags & SCRIPT_VERIFY_LOW_S) {
            // If we do enforce low S, then high S sigs are rejected.
            CheckError(flags, {highSSig, message, pubkeyC}, script,
                       ScriptError::SIG_HIGH_S);
            CheckError(flags, {highSSig, message, pubkeyC}, scriptverify,
                       ScriptError::SIG_HIGH_S);
        } else if (flags & SCRIPT_VERIFY_NULLFAIL) {
            // If we do enforce nullfail, these invalid sigs hit this.
            CheckError(flags, {highSSig, message, pubkeyC}, script,
                       ScriptError::SIG_NULLFAIL);
            CheckError(flags, {highSSig, message, pubkeyC}, scriptverify,
                       ScriptError::SIG_NULLFAIL);
        } else {
            // If we do not enforce low S, then high S sigs are accepted.
            CheckPass(flags, {highSSig, message, pubkeyC}, script, {});
            CheckError(flags, {highSSig, message, pubkeyC}, scriptverify,
                       ScriptError::CHECKDATASIGVERIFY);
        }

        if (flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S |
                     SCRIPT_VERIFY_STRICTENC)) {
            // If we get any of the dersig flags, the non canonical dersig
            // signature fails.
            CheckError(flags, {nondersig, message, pubkeyC}, script,
                       ScriptError::SIG_DER);
            CheckError(flags, {nondersig, message, pubkeyC}, scriptverify,
                       ScriptError::SIG_DER);
        } else if (flags & SCRIPT_VERIFY_NULLFAIL) {
            // If we do enforce nullfail, these invalid sigs hit this.
            CheckError(flags, {nondersig, message, pubkeyC}, script,
                       ScriptError::SIG_NULLFAIL);
            CheckError(flags, {nondersig, message, pubkeyC}, scriptverify,
                       ScriptError::SIG_NULLFAIL);
        } else {
            // If we do not check, then it is accepted.
            CheckPass(flags, {nondersig, message, pubkeyC}, script, {});
            CheckError(flags, {nondersig, message, pubkeyC}, scriptverify,
                       ScriptError::CHECKDATASIGVERIFY);
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

redpajama_set_name: RedPajamaGithub


text: NSArray<NSValue *> * beelineFitting(NSArray<NSValue *> *points);


text:
namespace blink {

inline IntRect winRectToIntRect(const RECT& rt)
{
    return IntRect(rt.left, rt.top, rt.right - rt.left, rt.bottom - rt.top);
}

inline RECT intRectToWinRect(const IntRect& rt)
{
    RECT r = { rt.x(), rt.y(), rt.maxX(), rt.maxY() };
    return r;
}

inline int intRectArea(const IntRect* r)
{
    return (r->width()) * (r->height());
}

inline IntRect intUnionRect(const IntRect& a, const IntRect& b)
{
    IntRect c = a;
    c.unite(b);
    return c;
}

inline int intUnionArea(IntRect* r1, IntRect* r2)
{
    IntRect area;
    area = intUnionRect(*r1, *r2);
    return intRectArea(&area);
}

} // namespace blink

#endif // IntRectWin_h


text:
<?php

namespace App\LoginModule\Migrators\Import;

use App\LoginModule\Migrators\Import\Mappers\UserMapper;
use App\LoginModule\Migrators\Import\Mappers\BadgeMapper;

class Data
{

    public static function queryUsers($connection, $offset, $amount) {
        return $connection->table('users')
            ->select('*')
            ->skip($offset)
            ->take($amount)
            ->get()
            ->map(function($row) {
                return UserMapper::remap($row);
            });
    }

    public static function queryBadges($connection, $user_id) {
        return $connection->table('user_badges')
            ->select('*')
            ->where('idUser', $user_id)
            ->get()
            ->map(function($row) {
                return BadgeMapper::remap($row);
            });
    }

    public static function queryAuths($connection, $user_id) {
        return $connection->table('users_auths')
            ->select('*')
            ->where('idUser', $user_id)
            ->get();
    }

}


text:
<?php

namespace AppBundle\Module;

use Clastic\CoreBundle\Module\ModuleInterface;

/**
 * Order
 */
class OrderModule implements ModuleInterface
{
    /**
     * The name of the module.
     *
     * @return string
     */
    public function getName()
    {
        return 'Order';
    }

    /**
     * The name of the module.
     *
     * @return string
     */
    public function getIdentifier()
    {
        return 'order';
    }
}


text:
<?php

namespace PHPCompatibility\Sniffs\Lists;

use PHPCompatibility\Sniffs\Lists\NewKeyedListSniff;
use PHP_CodeSniffer_File as File;

/**
 * Detect reference assignments in array destructuring using (short) list.
 *
 * PHP version 7.3
 *
 * @link https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.destruct-reference
 * @link https://wiki.php.net/rfc/list_reference_assignment
 * @link https://www.php.net/manual/en/function.list.php
 *
 * @since 9.0.0
 */
class NewListReferenceAssignmentSniff extends NewKeyedListSniff
{
    /**
     * The token(s) within the list construct which is being targeted.
     *
     * @since 9.0.0
     *
     * @var array
     */
    protected $targetsInList = array(
        \T_BITWISE_AND => \T_BITWISE_AND,
    );

    /**
     * Do a version check to determine if this sniff needs to run at all.
     *
     * @since 9.0.0
     *
     * @return bool
     */
    protected function bowOutEarly()
    {
        return ($this->supportsBelow('7.2') === false);
    }

    /**
     * Examine the contents of a list construct to determine whether an error needs to be thrown.
     *
     * @since 9.0.0
     *
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                   $opener    The position of the list open token.
     * @param int                   $closer    The position of the list close token.
     *
     * @return void
     */
    protected function examineList(File $phpcsFile, $opener, $closer)
    {
        $start = $opener;
        while (($start = $this->hasTargetInList($phpcsFile, $start, $closer)) !== false) {
            $phpcsFile->addError(
                'Reference assignments within list constructs are not supported in PHP 7.2 or earlier.',
                $start,
                'Found'
            );
        }
    }
}


text:
#ifndef _ARCH_ARM_RTC_H_
#define _ARCH_ARM_RTC_H_

/*!
 * \file arch/arm/at91_rtc.h
 * \brief AT91 real time clock.
 *
 * \verbatim
 * $Id:  $
 * \endverbatim
 */

/*!
 * \addtogroup xgNutArchArmAt91Rtc
 */
/*@{*/

#ifdef RTC_BASE

/*! \name RTC Control Register */
/*@{*/
#define RTC_CR                (RTC_BASE + 0x00)      /*!< \brief RTC controller control register address. */
#define RTC_UPDTIM            0x00000001             /*!< \brief Update Request Time Register. */
#define RTC_UPDCAL            0x00000002             /*!< \brief Peripheral reset. */
#define RTC_TIMEVSEL_MIN      0x00000008             /*!< \brief Time Event Selection - Minute change. */
#define RTC_TIMEVSEL_HR       0x00000008             /*!< \brief Time Event Selection - Hour change. */
#define RTC_TIMEVSEL_MIDN     0x00000008             /*!< \brief Time Event Selection - Every day at midnight. */
#define RTC_TIMEVSEL_NOON     0x00000008             /*!< \brief Time Event Selection - Every day at noon. */
#define RTC_CALEVSEL_WEEK     0x00000000             /*!< \brief Calendar Event Selection - Week change (every Monday at time 00:00:00. */
#define RTC_CALEVSEL_MONTH    0x00000001             /*!< \brief Calendar Event Selection - Month change (every 01 of each month at time 00:00:00. */
#define RTC_CALEVSEL_YEAR     0x00000003             /*!< \brief Calendar Event Selection - Year change (every January 1 at time 00:00:00. */
/*@}*/

/*! \name RTC Mode Register */
/*@{*/
#define RTC_MR                (RTC_BASE + 0x04)      /*!< \brief RTC controller mode register address. */
#define RTC_HRMOD_24          0x00000000             /*!< \brief 24-hour Mode. */
#define RTC_HRMOD_12          0x00000001             /*!< \brief 12-hour Mode. */
/*@}*/

/*! \name RTC Time Register */
/*@{*/
#define RTC_TIMR                (RTC_BASE + 0x08)    /*!< \brief RTC controller time register address. */
#define RTC_SEC                 0x0000007F           /*!< \brief Current second. */
#define RTC_SEC_LSB             0                    /*!< \brief Least significant bit of current second. */
#define RTC_MIN                 0x00007F00           /*!< \brief Current minute. */
#define RTC_MIN_LSB             8                    /*!< \brief Least significant bit of current minute. */
#define RTC_HOUR                0x003F0000           /*!< \brief Current hour. */
#define RTC_HOUR_LSB            16                   /*!< \brief Least significant bit of current hour. */
#define RTC_AM                  0x00000000           /*!< \brief Ante Meridiem Post Meridiem Indicator: AM. */
#define RTC_PM                  0x00400000           /*!< \brief Ante Meridiem Post Meridiem Indicator: PM. */
/*@}*/

/*! \name RTC Calendar Register */
/*@{*/
#define RTC_CALR                (RTC_BASE + 0x0C)    /*!< \brief RTC controller calendar register address. */
#define RTC_CENT                0x0000007F           /*!< \brief Current century. */
#define RTC_CENT_LSB            0                    /*!< \brief Least significant bit of current century. */
#define RTC_YEAR                0x0000FF00           /*!< \brief Current year. */
#define RTC_YEAR_LSB            8                    /*!< \brief Least significant bit of current year. */
#define RTC_MONTH               0x001F0000           /*!< \brief Current month. */
#define RTC_MONTH_LSB           16                   /*!< \brief Least significant bit of current month. */
#define RTC_DAY                 0x00E00000           /*!< \brief Current day (1-7). */
#define RTC_DAY_LSB             21                   /*!< \brief Least significant bit of current day. */
#define RTC_DATE                0x3F000000           /*!< \brief Current day in current month (1-31). */
#define RTC_DATE_LSB            24                   /*!< \brief Least significant bit of current day in current month (1-31). */
/*@}*/

/*! \name RTC Time Alarm Register */
/*@{*/
#define RTC_TIMALR              (RTC_BASE + 0x10)    /*!< \brief RTC controller time alarm register address. */
#define RTC_SECEN             0x00000080           /*!< \brief Second alarm enable. */
#define RTC_MINEN             0x00008000           /*!< \brief Minute alarm enable. */
#define RTC_HOUREN            0x00800000           /*!< \brief Hour alarm enable. */
/*@}*/

/*! \name RTC Calendar Alarm Register */
/*@{*/
#define RTC_CALALR              (RTC_BASE + 0x14)    /*!< \brief RTC controller calendar alarm register address. */
#define RTC_DATEEN              0x80000000           /*!< \brief Second alarm enable. */
#define RTC_MTHEN               0x00800000           /*!< \brief Minute alarm enable. */
/*@}*/

/*! \name RTC Status Register */
/*@{*/
#define RTC_SR                  (RTC_BASE + 0x18)    /*!< \brief RTC controller status register address. */
#define RTC_ACKUPD              0x00000001           /*!< \brief Acknowledge for Update. */
#define RTC_ALARM               0x00000002           /*!< \brief Alarm flag. */
#define RTC_SECEV               0x00000004           /*!< \brief Second event. */
#define RTC_TIMEV               0x00000008           /*!< \brief Time event. */
#define RTC_CALEV               0x00000010           /*!< \brief Calendar event. */
/*@}*/

/*! \name RTC Status Clear Command Register */
/*@{*/
#define RTC_SCCR                (RTC_BASE + 0x1C)    /*!< \brief RTC controller status clear register address. */
#define RTC_ACKCLR              0x00000001           /*!< \brief Acknowledge clear. */
#define RTC_ALRCLR              0x00000002           /*!< \brief Alarm clear. */
#define RTC_SECCLR              0x00000004           /*!< \brief Second clear. */
#define RTC_TIMCLR              0x00000008           /*!< \brief Time clear. */
#define RTC_CALCLR              0x00000010           /*!< \brief Calendar clear. */
/*@}*/

/*! \name RTC Interrupt Enable/Disable/Mask Register */
/*@{*/
#define RTC_IER                (RTC_BASE + 0x20)    /*!< \brief RTC controller interrupt enable register address. */
#define RTC_IDR                (RTC_BASE + 0x24)    /*!< \brief RTC controller interrupt disable status register address. */
#define RTC_IMR                (RTC_BASE + 0x28)    /*!< \brief RTC controller interrupt disable status register address. */
#define RTC_ACKINT             0x00000001           /*!< \brief Acknowledge update interrupt enable. */
#define RTC_ALRINT             0x00000002           /*!< \brief Alarm interrupt enable. */
#define RTC_SECINT             0x00000004           /*!< \brief Second interrupt enable. */
#define RTC_TIMINT             0x00000008           /*!< \brief Time interrupt enable. */
#define RTC_CALINT             0x00000010           /*!< \brief Calendar interrupt enable. */
/*@}*/

/*! \name RTC Valid Entry Register */
/*@{*/
#define RTC_VER                (RTC_BASE + 0x2C)    /*!< \brief RTC controller valid entry register address. */
#define RTC_NVTIM              0x00000001           /*!< \brief Non-Valid time. */
#define RTC_NVCAL              0x00000002           /*!< \brief Non-Valid calendar. */
#define RTC_NVTIMALR           0x00000004           /*!< \brief Non-Valid time alarm. */
#define RTC_NVCALALR           0x00000008           /*!< \brief Non-Valid calendar alarm. */
/*@}*/

#endif

/*@} xgNutArchArmAt91Rtc */

#endif                          /* _ARCH_ARM_RTC_H_ */


text:
function [XX, YY, ZZ] = DigitalFish(FishDim, FishLength)
% Takes in an array of heights and widths and generates a digital fish
% comprised of elipses
% Assumes first column of FishDim is heights and second is widths
% units is the distance between each measurement
figure

    [m,n] = size(FishDim);
    YY = []; ZZ = []; XX = [];
    units = linspace(0,FishLength, m);

    for i = 1:m
       % Calculate the ellipse based on height and width at each point
       [X, Y] = calculateEllipse(0, 0, FishDim(i,1), FishDim(i,2), 0, m);

       % X and Y from calculateEllipse will be the Y and Z axis of the
       % fish plot
       YY(:,i) = X; ZZ(:,i) = Y;

       % Generate an array of the i-th number in the "units" vector
       % This will be the center of the ellipse

       for j = 1:m
           XX(j,i) = units(i);
       end

       plot3(XX(:,i), YY(:,i), ZZ(:,i));
       xlabel('X'); ylabel('Y'), zlabel('Z');
       hold on

    end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
using Toggl.Core.Tests.Sync.State;
using Toggl.Shared.Extensions;
using Toggl.Shared.Models;
using Toggl.Storage;
using Toggl.Storage.Realm;

namespace Toggl.Core.Tests.Sync.Helpers
{
    public sealed class SyncStorage
    {
        public ITogglDatabase Database { get; }

        public SyncStorage()
        {
            Database = new Database(new RealmConfigurator());
        }

        public async Task<DatabaseState> LoadCurrentState()
        {
            var user = Models.User.From(await Database.User.Single());
            var clients = await Database.Clients.GetAll().Select(c => c.Select(Models.Client.From));
            var projects = await Database.Projects.GetAll().Select(p => p.Select(Models.Project.From));
            var preferences = Models.Preferences.From(await Database.Preferences.Single());
            var tags = await Database.Tags.GetAll().Select(t => t.Select(Models.Tag.From));
            var tasks = await Database.Tasks.GetAll().Select(t => t.Select(Models.Task.From));
            var timeEntries = await Database.TimeEntries.GetAll().Select(te => te.Select(Models.TimeEntry.From));
            var workspaces = await Database.Workspaces.GetAll().Select(ws => ws.Select(Models.Workspace.From));
            var sinceParameters = new Dictionary<Type, DateTimeOffset?>
            {
                [typeof(IClient)] = Database.SinceParameters.Get<IClient>(),
                [typeof(IProject)] = Database.SinceParameters.Get<IProject>(),
                [typeof(ITag)] = Database.SinceParameters.Get<ITag>(),
                [typeof(ITask)] = Database.SinceParameters.Get<ITask>(),
                [typeof(ITimeEntry)] = Database.SinceParameters.Get<ITimeEntry>(),
                [typeof(IWorkspace)] = Database.SinceParameters.Get<IWorkspace>()
            };

            return new DatabaseState(
                user, clients, projects, preferences, tags, tasks, timeEntries, workspaces, sinceParameters);
        }

        public async Task Store(DatabaseState databaseState)
        {
            if (databaseState.Workspaces.Count > 0)
                await databaseState.Workspaces.Select(Database.Workspaces.Create).Merge();

            if (databaseState.User != null)
                await Database.User.Create(databaseState.User);

            if (databaseState.Preferences != null)
                await Database.Preferences.Create(databaseState.Preferences);

            if (databaseState.Tags.Count > 0)
                await databaseState.Tags.Select(Database.Tags.Create).Merge();

            if (databaseState.Clients.Count > 0)
                await databaseState.Clients.Select(Database.Clients.Create).Merge();

            if (databaseState.Projects.Count > 0)
                await databaseState.Projects.Select(Database.Projects.Create).Merge();

            if (databaseState.Tasks.Count > 0)
                await databaseState.Tasks.Select(Database.Tasks.Create).Merge();

            if (databaseState.TimeEntries.Count > 0)
                await databaseState.TimeEntries.Select(Database.TimeEntries.Create).Merge();

            databaseState.SinceParameters?.Keys.ForEach(modelType =>
            {
                var sinceValue = databaseState.SinceParameters[modelType];
                var setMethod = typeof(ISinceParameterRepository).GetMethod(nameof(ISinceParameterRepository.Set));
                var genericSetMethod = setMethod.MakeGenericMethod(modelType);
                genericSetMethod.Invoke(
                    Database.SinceParameters, new object[] { sinceValue });
            });
        }

        public Task Clear()
            => Database.Clear().ToTask();
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "IO#readlines" do
  it "returns an Array of Strings that were separated by $/" do
    File.open(File.dirname(__FILE__) + '/fixtures/readlines.txt', 'r') do |f|
      f.readlines.should == ["Voici la ligne une.\n", "Qui \303\250 la linea due.\n",
          "Aqu\303\255 est\303\241 la l\303\255nea tres.\n", "Ist hier Linie vier.\n",
          "Est\303\241 aqui a linha cinco.\n", "Here is line six.\n"]
    end
  end
  it "returns an Array of Strings that were separated by r" do
    File.open(File.dirname(__FILE__) + '/fixtures/readlines.txt', 'r') do |f|
      f.readlines('r').should == ["Voici la ligne une.\nQui \303\250 la linea due.\nAqu\303\255 est\303\241 la l\303\255nea tr",
                                  "es.\nIst hier"," Linie vier",".\nEst\303\241 aqui a linha cinco.\nHer","e is line six.\n"]
    end
  end

  it "raises IOError on closed stream" do
    lambda { IOSpecs.closed_file.readlines }.should raise_error(IOError)
  end
end

describe "IO::readlines" do
  it "returns an Array of Strings that were separated by $/" do
    lines = IO::readlines(File.dirname(__FILE__) + '/fixtures/readlines.txt')
    lines.should == ["Voici la ligne une.\n", "Qui \303\250 la linea due.\n",
                     "Aqu\303\255 est\303\241 la l\303\255nea tres.\n", "Ist hier Linie vier.\n",
                     "Est\303\241 aqui a linha cinco.\n", "Here is line six.\n"]
  end
  it "returns an Array of Strings that were separated by r" do
    lines = IO::readlines(File.dirname(__FILE__) + '/fixtures/readlines.txt','r')
    lines.should == ["Voici la ligne une.\nQui \303\250 la linea due.\nAqu\303\255 est\303\241 la l\303\255nea tr",
                     "es.\nIst hier"," Linie vier",".\nEst\303\241 aqui a linha cinco.\nHer","e is line six.\n"]
  end
end

describe "IO.readlines" do
  it "needs to be reviewed for spec completeness" do
  end
end


text:
namespace multiverso {

namespace message {

bool to_server(MsgType type) {
  return (static_cast<int>(type)) > 0 &&
         (static_cast<int>(type)) < 32;
}

bool to_worker(MsgType type) {
  return (static_cast<int>(type)) < 0  &&
         (static_cast<int>(type)) > -32;
}

bool to_controler(MsgType type) {
  return (static_cast<int>(type)) > 32;
}

}  // namespace message

Communicator::Communicator() : Actor(actor::kCommunicator) {
  RegisterHandler(MsgType::Default, std::bind(
    &Communicator::ProcessMessage, this, std::placeholders::_1));
  net_util_ = NetInterface::Get();
}

Communicator::~Communicator() { }

void Communicator::Main() {
  is_working_ = true;

  switch (net_util_->thread_level_support()) {
  case NetThreadLevel::THREAD_MULTIPLE: {
    recv_thread_.reset(new std::thread(&Communicator::Communicate, this));
    Actor::Main();
    recv_thread_->join();
    break;
  }
  case NetThreadLevel::THREAD_SERIALIZED: {
    MessagePtr msg;
    while (mailbox_->Alive()) {
      // Try pop and Send
      if (mailbox_->TryPop(msg)) {
        ProcessMessage(msg);
      }
      // Probe and Recv
      size_t size = net_util_->Recv(&msg) > 0;
      if (size > 0) {
        LocalForward(msg);
      }
      CHECK(msg.get() == nullptr);
      net_util_->Send(msg);
    }
    break;
  }
  default:
    Log::Fatal("Unexpected thread level\n");
  }
}

void Communicator::ProcessMessage(MessagePtr& msg) {
  if (msg->dst() != net_util_->rank()) {
    net_util_->Send(msg);
    return;
  }
  LocalForward(msg);
}

void Communicator::Communicate() {
  while (is_working_) {
    MessagePtr msg(new Message());
    int size = net_util_->Recv(&msg);
    if (size == -1) {
      continue;
    }
    if (size > 0) {
      // a message received
      CHECK(msg->dst() == Zoo::Get()->rank());
      LocalForward(msg);
    }
  }
  Log::Debug("Comm recv thread exit\n");
}

void Communicator::LocalForward(MessagePtr& msg) {
  CHECK(msg->dst() == Zoo::Get()->rank());
  if (message::to_server(msg->type())) {
    SendTo(actor::kServer, msg);
  } else if (message::to_worker(msg->type())) {
    SendTo(actor::kWorker, msg);
  } else if (message::to_controler(msg->type())) {
    SendTo(actor::kController, msg);
  } else {
    // Send back to the msg queue of zoo
    Zoo::Get()->Receive(msg);
  }
}

}  // namespace multiverso


text:
#ifndef GEOS_BIGTEST_H
#define GEOS_BIGTEST_H

#include <memory>

using namespace std;
using namespace geos;

// Forward declaration
namespace geos {
	namespace geom {
		class Polygon;
		class CoordinateSequence;
		class GeometryFactory;
	}
}

class GeometryTestFactory {
public:
	static geom::Polygon* createBox(geom::GeometryFactory *fact,double minx,double miny,int nSide,double segLen);
	static geom::CoordinateSequence* createBox(double minx,double miny,int nSide,double segLen);
	static geom::CoordinateSequence* createCircle(double basex,double basey,double size,int nPts);
	static geom::Polygon* createCircle(geom::GeometryFactory *fact,double basex,double basey,double size,int nPts);
	static geom::CoordinateSequence* createSineStar(double basex,double basey,double size,double armLen,int nArms,int nPts);
	static geom::Polygon* createSineStar(geom::GeometryFactory *fact,double basex,double basey,double size,double armLen,int nArms,int nPts);
};

#endif


text:
/*
 * net/sched/sch_fifo.c	The simplest FIFO queue.
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 *
 * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
 */

#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <net/pkt_sched.h>

/* 1 band FIFO pseudo-"scheduler" */

struct fifo_sched_data
{
	u32 limit;
};

static int bfifo_enqueue(struct sk_buff *skb, struct Qdisc* sch)
{
	struct fifo_sched_data *q = qdisc_priv(sch);

	if (likely(sch->qstats.backlog + qdisc_pkt_len(skb) <= q->limit))
		return qdisc_enqueue_tail(skb, sch);

	return qdisc_reshape_fail(skb, sch);
}

static int pfifo_enqueue(struct sk_buff *skb, struct Qdisc* sch)
{
	struct fifo_sched_data *q = qdisc_priv(sch);

	if (likely(skb_queue_len(&sch->q) < q->limit))
		return qdisc_enqueue_tail(skb, sch);

	return qdisc_reshape_fail(skb, sch);
}

static int fifo_init(struct Qdisc *sch, struct nlattr *opt)
{
	struct fifo_sched_data *q = qdisc_priv(sch);

	if (opt == NULL) {
		u32 limit = qdisc_dev(sch)->tx_queue_len ? : 1;

		if (sch->ops == &bfifo_qdisc_ops)
			limit *= psched_mtu(qdisc_dev(sch));

		q->limit = limit;
	} else {
		struct tc_fifo_qopt *ctl = nla_data(opt);

		if (nla_len(opt) < sizeof(*ctl))
			return -EINVAL;

		q->limit = ctl->limit;
	}

	return 0;
}

static int fifo_dump(struct Qdisc *sch, struct sk_buff *skb)
{
	struct fifo_sched_data *q = qdisc_priv(sch);
	struct tc_fifo_qopt opt = { .limit = q->limit };

	NLA_PUT(skb, TCA_OPTIONS, sizeof(opt), &opt);
	return skb->len;

nla_put_failure:
	return -1;
}

struct Qdisc_ops pfifo_qdisc_ops __read_mostly = {
	.id		=	"pfifo",
	.priv_size	=	sizeof(struct fifo_sched_data),
	.enqueue	=	pfifo_enqueue,
	.dequeue	=	qdisc_dequeue_head,
	.peek		=	qdisc_peek_head,
	.drop		=	qdisc_queue_drop,
	.init		=	fifo_init,
	.reset		=	qdisc_reset_queue,
	.change		=	fifo_init,
	.dump		=	fifo_dump,
	.owner		=	THIS_MODULE,
};
EXPORT_SYMBOL(pfifo_qdisc_ops);

struct Qdisc_ops bfifo_qdisc_ops __read_mostly = {
	.id		=	"bfifo",
	.priv_size	=	sizeof(struct fifo_sched_data),
	.enqueue	=	bfifo_enqueue,
	.dequeue	=	qdisc_dequeue_head,
	.peek		=	qdisc_peek_head,
	.drop		=	qdisc_queue_drop,
	.init		=	fifo_init,
	.reset		=	qdisc_reset_queue,
	.change		=	fifo_init,
	.dump		=	fifo_dump,
	.owner		=	THIS_MODULE,
};
EXPORT_SYMBOL(bfifo_qdisc_ops);

/* Pass size change message down to embedded FIFO */
int fifo_set_limit(struct Qdisc *q, unsigned int limit)
{
	struct nlattr *nla;
	int ret = -ENOMEM;

	/* Hack to avoid sending change message to non-FIFO */
	if (strncmp(q->ops->id + 1, "fifo", 4) != 0)
		return 0;

	nla = kmalloc(nla_attr_size(sizeof(struct tc_fifo_qopt)), GFP_KERNEL);
	if (nla) {
		nla->nla_type = RTM_NEWQDISC;
		nla->nla_len = nla_attr_size(sizeof(struct tc_fifo_qopt));
		((struct tc_fifo_qopt *)nla_data(nla))->limit = limit;

		ret = q->ops->change(q, nla);
		kfree(nla);
	}
	return ret;
}
EXPORT_SYMBOL(fifo_set_limit);

struct Qdisc *fifo_create_dflt(struct Qdisc *sch, struct Qdisc_ops *ops,
			       unsigned int limit)
{
	struct Qdisc *q;
	int err = -ENOMEM;

	q = qdisc_create_dflt(qdisc_dev(sch), sch->dev_queue,
			      ops, TC_H_MAKE(sch->handle, 1));
	if (q) {
		err = fifo_set_limit(q, limit);
		if (err < 0) {
			qdisc_destroy(q);
			q = NULL;
		}
	}

	return q ? : ERR_PTR(err);
}
EXPORT_SYMBOL(fifo_create_dflt);


text:
'use strict';

const {createElement, createFactory, isValidElement} = require('React');

module.exports = {
  createElement,
  createFactory,
  isValidElement,
};


text:
i5ting_toc
=========

[![npm version](https://badge.fury.io/js/i5ting_toc.svg)](http://badge.fury.io/js/i5ting_toc)

i5ting_toc  a node npm wrapper of i5ting_ztree_toc https://github.com/i5ting/i5ting_ztree_toc

- [ruby版本tocmd](https://github.com/i5ting/tocmd.gem)
- [node版本i5ting_toc](https://github.com/i5ting/tocmd.npm)

## Preview

![](https://github.com/i5ting/i5ting_ztree_toc/blob/master/demo/3.png)

## Install

	npm install -g i5ting_toc

## Usage

```
➜  tocmd.npm git:(master) ✗ i5ting_toc -h

  Usage: i5ting_toc  a node npm wrapper of i5ting_ztree_toc https://github.com/i5ting/i5ting_ztree_toc

  Options:

    -h, --help             output usage information
    -V, --version          output the version number
    -f, --file [filename]  default is README.md
		-o, --open             open in browser
    -v, --verbose          打印详细日志
```

这个版本的命令比较简单,只有一个`-f`参数,如果没有填写,默认使用`README.md`,常见用法

	i5ting_toc -f sample.md -o

## Api Usages

示例说明

```
var is_open = true;
var markd_config = {
	debug: false,
  index: true
}
//函数可以返回当前正在执行的项目路径
var pwd = process.cwd()

var source_file_name = pwd + '/' + source_file
var file_name = source_file_name.split('/').pop();;
var _file_name = file_name.split('.')[0];

var dest_file_path = pwd + '/preview/' + _file_name + '.html';

console.log('pwd=' + pwd);
console.log('source_file_name=' + source_file_name);
console.log('dest_file_path=' + dest_file_path);

require('../index')(pwd, source_file_name, dest_file_path, is_open, markd_config);

```

参数说明

- pwd是存放preview的位置
- source_file 要编译的mardown文件
- dest_file_path 生成的html完整路径和文件名
- is_open 是否在编译后使用浏览器中打开html
- markd_config 编译md的选项(具体见 https://github.com/chjj/marked )

## Basic

current path

	var pwd = process.cwd()

file path

	__dirname

use shelljs judge dir is

	if (test('-d', preview_path)) {
		/* do something with dir */
		mkdir('-p', preview_path);
	};

http://documentup.com/arturadib/shelljs

- '-b', 'path': true if path is a block device
- '-c', 'path': true if path is a character device
- '-d', 'path': true if path is a directory
- '-e', 'path': true if path exists
- '-f', 'path': true if path is a regular file
- '-L', 'path': true if path is a symboilc link
- '-p', 'path': true if path is a pipe (FIFO)
- '-S', 'path': true if path is a socket

template for compile use [handlebars](http://handlebarsjs.com/)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## 推荐

- [mac-dev-setup](http://aaaaaashu.gitbooks.io/mac-dev-setup/content/index.html)
- [How To Build A CLI Tool With Node.js And PhantomJS](http://www.smashingmagazine.com/2014/02/12/build-cli-tool-nodejs-phantomjs/)

## 版本历史

- v0.1.0 初始化版本

## 欢迎fork和反馈

- write by `i5ting` shiren1118@126.com

如有建议或意见,请在issue提问或邮件

## License

this repo is released under the [MIT
License](http://www.opensource.org/licenses/MIT).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TeamFoundation.Common.Exceptions;
using TeamFoundation.Common.Factories;
using TeamFoundation.Common.Helpers;
using TeamFoundation.Common.Repositories;
using Microsoft.TeamFoundation.Common;

namespace TeamFoundation.Common
{
    public class TFSManager
    {
        private readonly RepositoryFactory m_repositoryFactory;
        private readonly TFSProxyFactory m_proxyFactory;

        public TFSManager(TFSProxyFactory proxyFactory)
        {
            m_repositoryFactory = new RepositoryFactory();
            m_proxyFactory = proxyFactory;
        }

        public TFSManager(Uri uri, ICredentials credentials)
        {
            m_repositoryFactory = new RepositoryFactory();
            m_proxyFactory = new TFSProxyFactory(uri, credentials);
        }

        public T GetRepository<T>()
        {
            var field = typeof(T).GetField("m_proxy", BindingFlags.NonPublic | BindingFlags.Instance);
            if (field == null)
                throw new ProxyNotFoundException(string.Format("No proxy found related to repository : {0}", typeof(T).Name));
            string typeName = field.FieldType.IsInterface ? field.FieldType.Name.Remove(0, 1) : field.FieldType.Name;
            // get the type related to a specifique repository
            Type proxyType = AssemblyHelper.FindType(string.Format("{0}.{1}", field.FieldType.Namespace, typeName));
            TFCommonUtil.CheckForNull(proxyType, "proxyType");
            // get the proxy
            var proxy = m_proxyFactory.GetProxy(proxyType);

            return m_repositoryFactory.GetRepository<T>(proxy);
        }

    }
}


text:
package com.cloud.network.element;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ejb.Local;
import javax.inject.Inject;

import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse;
import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
import org.apache.log4j.Logger;

import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.commands.AddExternalLoadBalancerCmd;
import com.cloud.api.commands.AddF5LoadBalancerCmd;
import com.cloud.api.commands.ConfigureF5LoadBalancerCmd;
import com.cloud.api.commands.DeleteExternalLoadBalancerCmd;
import com.cloud.api.commands.DeleteF5LoadBalancerCmd;
import com.cloud.api.commands.ListExternalLoadBalancersCmd;
import com.cloud.api.commands.ListF5LoadBalancerNetworksCmd;
import com.cloud.api.commands.ListF5LoadBalancersCmd;
import com.cloud.api.response.F5LoadBalancerResponse;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientNetworkCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalLoadBalancerDeviceManager;
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.dao.ExternalLoadBalancerDeviceDao;
import com.cloud.network.dao.ExternalLoadBalancerDeviceVO;
import com.cloud.network.dao.ExternalLoadBalancerDeviceVO.LBDeviceState;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkExternalLoadBalancerDao;
import com.cloud.network.dao.NetworkExternalLoadBalancerVO;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkVO;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.resource.F5BigIpResource;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.network.rules.LoadBalancerContainer;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.google.gson.Gson;

@Local(value = {NetworkElement.class, LoadBalancingServiceProvider.class, IpDeployer.class})
public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, IpDeployer, F5ExternalLoadBalancerElementService, ExternalLoadBalancerDeviceManager {

    private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class);

    @Inject
    NetworkModel _networkManager;
    @Inject
    ConfigurationManager _configMgr;
    @Inject
    NetworkServiceMapDao _ntwkSrvcDao;
    @Inject
    DataCenterDao _dcDao;
    @Inject
    PhysicalNetworkDao _physicalNetworkDao;
    @Inject
    HostDao _hostDao;
    @Inject
    ExternalLoadBalancerDeviceDao _lbDeviceDao;
    @Inject
    NetworkExternalLoadBalancerDao _networkLBDao;
    @Inject
    NetworkDao _networkDao;
    @Inject
    HostDetailsDao _detailsDao;
    @Inject
    ConfigurationDao _configDao;

    private boolean canHandle(Network config, List<LoadBalancingRule> rules) {
        if ((config.getGuestType() != Network.GuestType.Isolated && config.getGuestType() != Network.GuestType.Shared) || config.getTrafficType() != TrafficType.Guest) {

            s_logger.trace("Not handling network with Type  " + config.getGuestType() + " and traffic type " + config.getTrafficType());
            return false;
        }

        Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
        if (!lbCaps.isEmpty()) {
            String schemeCaps = lbCaps.get(Capability.LbSchemes);
            if (schemeCaps != null && rules != null && !rules.isEmpty()) {
                for (LoadBalancingRule rule : rules) {
                    if (!schemeCaps.contains(rule.getScheme().toString())) {
                        s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName());
                        return false;
                    }
                }
            }
        }

        return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
    }

    @Override
    public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
    InsufficientNetworkCapacityException {

        if (!canHandle(guestConfig, null)) {
            return false;
        }

        try {
            return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
        } catch (InsufficientCapacityException capacityException) {
            throw new ResourceUnavailableException("There are no F5 load balancer devices with the free capacity for implementing this network", DataCenter.class, guestConfig.getDataCenterId());
        }
    }

    @Override
    public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
    InsufficientNetworkCapacityException, ResourceUnavailableException {
        return true;
    }

    @Override
    public boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) {
        return true;
    }

    @Override
    public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException {
        if (!canHandle(guestConfig, null)) {
            return false;
        }

        try {
            return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig);
        } catch (InsufficientCapacityException capacityException) {
            // TODO: handle out of capacity exception
            return false;
        }
    }

    @Override
    public boolean destroy(Network config, ReservationContext context) {
        return true;
    }

    @Override
    public boolean validateLBRule(Network network, LoadBalancingRule rule) {
        if (canHandle(network, new ArrayList<LoadBalancingRule>(Arrays.asList(rule)))) {
            String algo = rule.getAlgorithm();
            return (algo.equals("roundrobin") || algo.equals("leastconn"));
        }
        return true;
    }

    @Override
    public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
        if (!canHandle(config, rules)) {
            return false;
        }

        return applyLoadBalancerRules(config, rules);
    }

    @Override
    public Map<Service, Map<Capability, String>> getCapabilities() {
        Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();

        // Set capabilities for LB service
        Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();

        // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
        lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");

        // specifies that F5 BIG IP network element can provide shared mode only
        lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");

        // Specifies that load balancing rules can be made for either TCP or UDP traffic
        lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");

        // Specifies that this element can measure network usage on a per public IP basis
        lbCapabilities.put(Capability.TrafficStatistics, "per public ip");

        // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
        lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");

        // Support inline mode with firewall
        lbCapabilities.put(Capability.InlineMode, "true");

        //support only for public lb
        lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString());

        LbStickinessMethod method;
        List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
        method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http");
        methodList.add(method);
        method.addParam("holdtime", false, "time period (in seconds) for which persistence is in effect.", false);

        Gson gson = new Gson();
        String stickyMethodList = gson.toJson(methodList);
        lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList);

        capabilities.put(Service.Lb, lbCapabilities);

        return capabilities;
    }

    @Override
    public Provider getProvider() {
        return Provider.F5BigIp;
    }

    @Override
    public boolean isReady(PhysicalNetworkServiceProvider provider) {
        List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.F5BigIp.getName());

        // true if at-least one F5 device is added in to physical network and is in configured (in enabled state) state
        if (lbDevices != null && !lbDevices.isEmpty()) {
            for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
                if (lbDevice.getState() == LBDeviceState.Enabled) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
    ResourceUnavailableException {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean canEnableIndividualServices() {
        return false;
    }

    @Override
    public List<Class<?>> getCommands() {
        List<Class<?>> cmdList = new ArrayList<Class<?>>();
        cmdList.add(AddExternalLoadBalancerCmd.class);
        cmdList.add(AddF5LoadBalancerCmd.class);
        cmdList.add(ConfigureF5LoadBalancerCmd.class);
        cmdList.add(DeleteExternalLoadBalancerCmd.class);
        cmdList.add(DeleteF5LoadBalancerCmd.class);
        cmdList.add(ListExternalLoadBalancersCmd.class);
        cmdList.add(ListF5LoadBalancerNetworksCmd.class);
        cmdList.add(ListF5LoadBalancersCmd.class);
        return cmdList;
    }

    @Override
    @Deprecated
    public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) {
        Long zoneId = cmd.getZoneId();
        DataCenterVO zone = null;
        PhysicalNetworkVO pNetwork = null;
        ExternalLoadBalancerDeviceVO lbDeviceVO = null;
        HostVO lbHost = null;

        zone = _dcDao.findById(zoneId);
        if (zone == null) {
            throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
        }

        List<PhysicalNetworkVO> physicalNetworks = _physicalNetworkDao.listByZone(zoneId);
        if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) {
            throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: "
                    + zoneId + " to add this device.");
        }
        pNetwork = physicalNetworks.get(0);

        String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName();
        lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(),
                deviceType, new F5BigIpResource(), false, null, null);

        if (lbDeviceVO != null) {
            lbHost = _hostDao.findById(lbDeviceVO.getHostId());
        }

        return lbHost;
    }

    @Override
    @Deprecated
    public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd) {
        return deleteExternalLoadBalancer(cmd.getId());
    }

    @Override
    @Deprecated
    public List<Host> listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) {
        Long zoneId = cmd.getZoneId();
        DataCenterVO zone = null;
        PhysicalNetworkVO pNetwork = null;

        if (zoneId != null) {
            zone = _dcDao.findById(zoneId);
            if (zone == null) {
                throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
            }

            List<PhysicalNetworkVO> physicalNetworks = _physicalNetworkDao.listByZone(zoneId);
            if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) {
                throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: "
                        + zoneId + " to add this device.");
            }
            pNetwork = physicalNetworks.get(0);
            return listExternalLoadBalancers(pNetwork.getId(), NetworkDevice.F5BigIpLoadBalancer.getName());
        } else {
            throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers");
        }
    }

    @Override
    @Deprecated
    public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLb) {
        return super.createExternalLoadBalancerResponse(externalLb);
    }

    @Override
    public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd) {
        String deviceName = cmd.getDeviceType();
        if (!deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
            throw new InvalidParameterValueException("Invalid F5 load balancer device type");
        }

        return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(),
                deviceName, new F5BigIpResource(), false, null, null);

    }

    @Override
    public boolean deleteF5LoadBalancer(DeleteF5LoadBalancerCmd cmd) {
        Long lbDeviceId = cmd.getLoadBalancerDeviceId();

        ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
        if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
            throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId);
        }

        return deleteExternalLoadBalancer(lbDeviceVo.getHostId());
    }

    @Override
    public ExternalLoadBalancerDeviceVO configureF5LoadBalancer(ConfigureF5LoadBalancerCmd cmd) {
        Long lbDeviceId = cmd.getLoadBalancerDeviceId();
        Long capacity = cmd.getLoadBalancerCapacity();

        ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
        if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
            throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId);
        }

        if (capacity != null) {
            // check if any networks are using this F5 device
            List<NetworkExternalLoadBalancerVO> networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);
            if ((networks != null) && !networks.isEmpty()) {
                if (capacity < networks.size()) {
                    throw new CloudRuntimeException("There are more number of networks already using this F5 device than configured capacity");
                }
            }
            if (capacity != null) {
                lbDeviceVo.setCapacity(capacity);
            }
        }

        lbDeviceVo.setState(LBDeviceState.Enabled);
        _lbDeviceDao.update(lbDeviceId, lbDeviceVo);
        return lbDeviceVo;
    }

    @Override
    public List<ExternalLoadBalancerDeviceVO> listF5LoadBalancers(ListF5LoadBalancersCmd cmd) {
        Long physcialNetworkId = cmd.getPhysicalNetworkId();
        Long lbDeviceId = cmd.getLoadBalancerDeviceId();
        PhysicalNetworkVO pNetwork = null;
        List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();

        if (physcialNetworkId == null && lbDeviceId == null) {
            throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
        }

        if (lbDeviceId != null) {
            ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
            if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
                throw new InvalidParameterValueException("Could not find F5 load balancer device with ID: " + lbDeviceId);
            }
            lbDevices.add(lbDeviceVo);
            return lbDevices;
        }

        if (physcialNetworkId != null) {
            pNetwork = _physicalNetworkDao.findById(physcialNetworkId);
            if (pNetwork == null) {
                throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId);
            }
            lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.F5BigIp.getName());
            return lbDevices;
        }

        return null;
    }

    @Override
    public List<? extends Network> listNetworks(ListF5LoadBalancerNetworksCmd cmd) {
        Long lbDeviceId = cmd.getLoadBalancerDeviceId();
        List<NetworkVO> networks = new ArrayList<NetworkVO>();

        ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
        if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
            throw new InvalidParameterValueException("Could not find F5 load balancer device with ID " + lbDeviceId);
        }

        List<NetworkExternalLoadBalancerVO> networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);
        if (networkLbMaps != null && !networkLbMaps.isEmpty()) {
            for (NetworkExternalLoadBalancerVO networkLbMap : networkLbMaps) {
                NetworkVO network = _networkDao.findById(networkLbMap.getNetworkId());
                networks.add(network);
            }
        }

        return networks;
    }

    @Override
    public F5LoadBalancerResponse createF5LoadBalancerResponse(ExternalLoadBalancerDeviceVO lbDeviceVO) {
        F5LoadBalancerResponse response = new F5LoadBalancerResponse();
        Host lbHost = _hostDao.findById(lbDeviceVO.getHostId());
        Map<String, String> lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId());

        response.setId(lbDeviceVO.getUuid());
        response.setIpAddress(lbHost.getPrivateIpAddress());
        PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId());
        if (pnw != null) {
            response.setPhysicalNetworkId(pnw.getUuid());
        }
        response.setPublicInterface(lbDetails.get("publicInterface"));
        response.setPrivateInterface(lbDetails.get("privateInterface"));
        response.setDeviceName(lbDeviceVO.getDeviceName());
        if (lbDeviceVO.getCapacity() == 0) {
            long defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50);
            response.setDeviceCapacity(defaultLbCapacity);
        } else {
            response.setDeviceCapacity(lbDeviceVO.getCapacity());
        }
        response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice());
        response.setProvider(lbDeviceVO.getProviderName());
        response.setDeviceState(lbDeviceVO.getState().name());
        response.setObjectName("f5loadbalancer");
        return response;
    }

    @Override
    public boolean verifyServicesCombination(Set<Service> services) {
        return true;
    }

    @Override
    public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
        // return true, as IP will be associated as part of LB rule configuration
        return true;
    }

    @Override
    public IpDeployer getIpDeployer(Network network) {
        ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network);
        if (lbDevice == null) {
            s_logger.error("Cannot find external load balanacer for network " + network.getName());
            s_logger.error("Make F5 as dummy ip deployer, since we likely met this when clean up resource after shutdown network");
            return this;
        }
        if (_networkManager.isNetworkInlineMode(network)) {
            return getIpDeployerForInlineMode(network);
        }
        return this;
    }

	@Override
	public List<LoadBalancerTO> updateHealthChecks(Network network,
			List<LoadBalancingRule> lbrules) {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Amazon.DataPipeline.Model;
    using Amazon.Runtime.Internal.Transform;

    namespace Amazon.DataPipeline.Model.Internal.MarshallTransformations
    {
      /// <summary>
      /// ReportTaskProgressResultUnmarshaller
      /// </summary>
      internal class ReportTaskProgressResultUnmarshaller : IUnmarshaller<ReportTaskProgressResult, XmlUnmarshallerContext>, IUnmarshaller<ReportTaskProgressResult, JsonUnmarshallerContext>
      {
        ReportTaskProgressResult IUnmarshaller<ReportTaskProgressResult, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
        {
          throw new NotImplementedException();
        }

        public ReportTaskProgressResult Unmarshall(JsonUnmarshallerContext context)
        {
            ReportTaskProgressResult reportTaskProgressResult = new ReportTaskProgressResult();

            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;
            while (context.Read())
            {
                if ((context.IsKey) && (context.CurrentDepth == targetDepth))
                {
                context.Read();
                context.Read();

              if (context.TestExpression("Canceled", targetDepth))
              {
                reportTaskProgressResult.Canceled = BoolUnmarshaller.GetInstance().Unmarshall(context);
                continue;
              }

                }
                else if (context.IsEndElement && context.CurrentDepth <= originalDepth)
                {
                    return reportTaskProgressResult;
                }
            }

            return reportTaskProgressResult;
        }

        private static ReportTaskProgressResultUnmarshaller instance;
        public static ReportTaskProgressResultUnmarshaller GetInstance()
        {
            if (instance == null)
                instance = new ReportTaskProgressResultUnmarshaller();
            return instance;
        }
    }
}


text:
package com.intellij.diff.tools.fragmented;

import com.intellij.diff.DiffContext;
import com.intellij.diff.comparison.DiffTooBigException;
import com.intellij.diff.tools.util.base.DiffPanelBase;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.util.ui.AsyncProcessIcon;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

import static com.intellij.diff.util.DiffUtil.createMessagePanel;

public class OnesideDiffPanel extends DiffPanelBase {
  private static final String GOOD_CONTENT = "GoodContent";
  private static final String LOADING_CONTENT = "LoadingContent";
  private static final String TOO_BIG_CONTENT = "TooBigContent";
  private static final String OPERATION_CANCELED_CONTENT = "OperationCanceledContent";
  private static final String ERROR_CONTENT = "ErrorContent";

  @NotNull private final Editor myEditor;

  @NotNull private final JPanel myEditorPanel;
  @NotNull private final AsyncProcessIcon.Big myBusyIcon;

  public OnesideDiffPanel(@Nullable Project project,
                          @NotNull OnesideContentPanel content,
                          @NotNull Editor editor,
                          @NotNull DataProvider provider,
                          @NotNull DiffContext context) {
    super(project, provider, context);
    myEditor = editor;

    myEditorPanel = content;
    myBusyIcon = new AsyncProcessIcon.Big("OnesideDiff");

    JPanel centerPanel = new JPanel(new BorderLayout());
    centerPanel.add(myNotificationsPanel, BorderLayout.NORTH);
    centerPanel.add(myEditorPanel, BorderLayout.CENTER);

    myContentPanel.add(centerPanel, GOOD_CONTENT);
    myContentPanel.add(myBusyIcon, LOADING_CONTENT);
    myContentPanel.add(createMessagePanel("Can not calculate diff. " + DiffTooBigException.MESSAGE), TOO_BIG_CONTENT);
    myContentPanel.add(createMessagePanel("Can not calculate diff. Operation canceled."), OPERATION_CANCELED_CONTENT);
    myContentPanel.add(createMessagePanel("Error"), ERROR_CONTENT);

    setCurrentCard(LOADING_CONTENT, false);
  }

  //
  // Card layout
  //

  public void setLoadingContent() {
    setCurrentCard(LOADING_CONTENT);
  }

  public void setGoodContent() {
    setCurrentCard(GOOD_CONTENT);
  }

  public void setTooBigContent() {
    setCurrentCard(TOO_BIG_CONTENT);
  }

  public void setOperationCanceledContent() {
    setCurrentCard(OPERATION_CANCELED_CONTENT);
  }

  public void setErrorContent() {
    setCurrentCard(ERROR_CONTENT);
  }

  @Override
  protected void setCurrentCard(@NotNull String card) {
    if (card == LOADING_CONTENT) {
      myBusyIcon.resume();
    }
    else {
      myBusyIcon.suspend();
    }

    super.setCurrentCard(card);
  }

  //
  // Misc
  //

  public boolean isGoodContent() {
    return myCurrentCard == GOOD_CONTENT;
  }
}


text:
<decorators defaultdir="/decorators">
    <excludes>
        <pattern>/40*.jsp</pattern>
        <pattern>/*ajax=true*</pattern>
        <pattern>/scripts/dojo/*</pattern>
        <pattern>/struts/dojo/*</pattern>
        <pattern>/resources/*</pattern>
        <pattern>/*.js</pattern>
        <pattern>/*.frag</pattern>
        <pattern>*/subpage/*</pattern>
    </excludes>
    <decorator name="default" page="default.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>


text:
<?php
use PHPUnit\Framework\TestCase;

class OneTestCase extends TestCase
{
    public function noTestCase()
    {
    }

    public function testCase($arg = '')
    {
    }
}


text:
import base64
import boto3
import json
import logging

from botocore.exceptions import ClientError

logger = logging.getLogger()
logger.setLevel(logging.INFO)

dynamo_client = boto3.resource('dynamodb')

def _make_dynamo_table():
    table = dynamo_client.create_table(
        TableName='consumers',
        KeySchema=[
            {
                'AttributeName': 'consumer',
                'KeyType': 'HASH'
            },
            {
                'AttributeName': 'shard',
                'KeyType': 'RANGE'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'consumer',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'shard',
                'AttributeType': 'S'
            }
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 1,
            'WriteCapacityUnits': 1
        }
    )
    table.meta.client.get_waiter('table_exists').wait(TableName='consumers')
    return table

def _ensure_dynamo_table():
    table = dynamo_client.Table('consumers')
    try:
        table.table_status
    except ClientError:
        _make_dynamo_table()
    return table

def _clear_consumer_lease(table, consumer, shard):
    table.delete_item(Key={'consumer': consumer, 'shard': shard})

def _get_consumer_lease(table, consumer, shard):
    row = table.get_item(Key={'consumer': consumer, 'shard': shard})
    if 'Item' not in row:
        return None
    else:
        return row['Item']['lease']

def _put_consumer_lease(table, consumer, shard, lease):
    table.put_item(
        Item={
            'consumer': consumer,
            'shard': shard,
            'lease': lease}
    )

def process(json_event):
    pass

def handler(event, context):
    """
    'If you create a Lambda function that processes events from
    stream-based services (Amazon Kinesis Streams), the number of
    shards per stream is the unit of concurrency. If your stream
    has 100 active shards, there will be 100 Lambda functions
    running concurrently. Then, each Lambda function processes
    events on a shard in the order that they arrive.'

    Therefore, for checkpointing logic, we should make the primary
    key a combination of:

    - consumer_id (hash)
    - shard_id (range)

    This will let us get a single Dynamo item, describing the
    current "consumer lease", for a consumer_id + shard_id
    combination. It will also mean that for a given consumer_id,
    we can do a range query to get all the shards owned by that
    consumer.
    """
    debug = False
    rewind = False
    dry_run = False

    table = _ensure_dynamo_table()
    consumer_id = 'test-consumer'

    if debug:
        state = table.scan()
        print "Active leases in Dynamo:", state["Count"]
        for item in state["Items"]:
            print json.dumps(item, indent=4, sort_keys=True)

    lease = None
    shard = None

    try:
        visitors = set()
        last_timestamp = None
        for i, record in enumerate(event.get('Records', [])):
            event_id, data = (record['eventID'], record['kinesis']['data'])
            shard, checkpoint = event_id.split(u':')
            if rewind:
                print "Rewinding to checkpoint 0"
                _clear_consumer_lease(table, consumer_id, shard)
                rewind = False
            if lease is None:
                lease = _get_consumer_lease(table, consumer_id, shard) \
                or {"checkpoint": "0"}

            if checkpoint <= lease["checkpoint"]:
                # replayed event, we should skip it
                print "Replayed event; skipping"
                continue
            # => decode from b64
            raw_event = base64.b64decode(data)
            # => parse from JSON
            json_event = json.loads(raw_event)
            # => extract out visitor id and timestamp if present
            visitor = json_event.get("visitor_site_id", "N/A")
            visitors.add(visitor)
            last_timestamp = json_event.get("ts_action", "N/A")
            # => do something with the data
            result = process(json_event)
            if result:
                pass
            # => checkpoint the shard
            lease["checkpoint"] = checkpoint
        logger.info("Saw {} unique visitors in batch ending with {}".format(
            len(visitors), last_timestamp))
        if not dry_run:
            _put_consumer_lease(table, consumer_id, shard, lease)
    except Exception as ex:
        # do not save consumer checkpoints because error happened
        # instead, we should probably log something about the error
        # in the consumer lease, to allow the Lambda to retry a fixed
        # number of times, before finally "giving up" and skipping
        # the records
        raise
        "^ some form of error handling required"
        if ex:
            pass


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.ericsson.otp.ic (Package com.ericsson.otp.ic version 4.4)
</TITLE>

<META NAME="date" CONTENT="2016-03-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Package
      Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.ericsson.otp.ic

Interface Summary

Holder
Holder interface class.

Class Summary

Any
The Any class is the java mapping of the any OMG-IDL type.

AnyHelper
Helper class for Any, according to OMG-IDL java mapping.

AnyHolder
Holder class for Any, according to OMG-IDL java mapping.

BooleanHolder
Holder class for Boolean, according to OMG-IDL java mapping.

ByteHolder
Holder class for Byte, according to OMG-IDL java mapping.

CharHolder
Holder class for Char, according to OMG-IDL java mapping.

DoubleHolder
Holder class for Double, according to OMG-IDL java mapping.

Environment
The Environment class handles communication
  setup and stub state.

FloatHolder
Holder class for Float, according to OMG-IDL java mapping.

IntHolder
Holder class for Int, according to OMG-IDL java mapping.

LongHolder
Holder class for Long, used by the Term class.

Pid
Pid class mapps the built-in erlang type pid, a process identity.

PidHelper
Helper class for Pid.

PidHolder
Holder class for Pid.

Port
Port class mapps the built-in erlang type port, a process port.

PortHelper
Helper class for Port.

PortHolder
Holder class for Port.

Ref
Ref class mapps the built-in erlang type Ref, a message reference.

RefHelper
Helper class for Ref.

RefHolder
Holder class for Ref.

ShortHolder
Holder class for Short, according to OMG-IDL java mapping.

StringHolder
Holder class for String, according to OMG-IDL java mapping.

TCKind
The TCKind class is the implementation of the OMG-IDL enumerant type TCKind.

Term
The Term class is intended to represent the erlang term generic type.

TermHelper
Helper class for Term.

TermHolder
Holder class for Term.

TypeCode
The TypeCode class is the implementation of the OMG-IDL TypeCode type.

      Package
      Class
      Tree
      Serialized
      Deprecated
      Index
      Help

Copyright © 1991-2007 Ericsson AB

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
#ifndef BRIDGE_VALRBN_H
#define BRIDGE_VALRBN_H

class ValProfile;

bool validateRBN(
  ValState& valState,
  ValProfile& prof);

bool validateRBX(
  ValState& valState,
  ValProfile& prof);

#endif


text:
<?php

declare(strict_types=1);

namespace Facile\SentryModule\Service;

use Psr\Container\ContainerInterface;
use Sentry\ClientInterface;
use Sentry\SentrySdk;
use Sentry\State\HubInterface;

final class HubFactory
{
    public function __invoke(ContainerInterface $container): HubInterface
    {
        $client = $container->get(ClientInterface::class);
        SentrySdk::getCurrentHub()->bindClient($client);

        return SentrySdk::getCurrentHub();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="other" />

    <Button
        android:id="@+id/save_files_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="存在files" />

    <Button
        android:id="@+id/save_caches_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="存在caches" />

    <Button
        android:id="@+id/get_files_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取files" />

    <Button
        android:id="@+id/get_caches_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取caches" />

    <Button
        android:id="@+id/same_path_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="一些路径" />
</LinearLayout>


text:
"""Replicator Distribution Strategy."""

from typing import Callable, TypeVar

from absl import logging
import contextlib
from sonnet.src import initializers
import tensorflow as tf

T = TypeVar("T")

def replica_local_creator(next_creator, **kwargs) -> tf.Variable:
  """Variable creator that by default creates replica local variables."""
  if kwargs["synchronization"] == tf.VariableSynchronization.AUTO:
    kwargs["synchronization"] = tf.VariableSynchronization.ON_READ
    if kwargs["aggregation"] == tf.VariableAggregation.NONE:
      kwargs["aggregation"] = tf.VariableAggregation.ONLY_FIRST_REPLICA
    if kwargs["trainable"] is None:
      kwargs["trainable"] = True
  return next_creator(**kwargs)

class Replicator(tf.distribute.MirroredStrategy):
  r"""Replicates input, parameters and compute over multiple accelerators.

  ``Replicator`` is a TensorFlow "Distribution Strategy" implementing the
  programming model described in the TF-Replicator paper
  :cite:`buchlovsky2019tf` and TensorFlow RFC
  :cite:`buchlovsky2019distribution`. ``Replicator`` enables data-parallel
  training across multiple accelerators on a single machine, it supports
  eager execution and :tf:`function`.

  To get started create a ``Replicator`` instance:

      >>> replicator = snt.distribute.Replicator()

  Replicator provides a scope inside which any new :tf:`Variable`\ s will be
  replicated across all local devices:

      >>> with replicator.scope():
      ...    mod = snt.Linear(32)

  Additionally replicator provides utility functions to apply a module in
  parallel on multiple devices. First we need to define some computation that
  runs on each GPU. The "replica context" object provides us a way to
  communicate between replicas (e.g. to perform an ``all_reduce``):

      >>> def forward():
      ...   # Compute a random output on each GPU.
      ...   x = tf.random.normal([8, 28 * 28])
      ...   y = mod(x)
      ...   # Synchronize the value of `y` between all GPUs.
      ...   ctx = tf.distribute.get_replica_context()
      ...   y = ctx.all_reduce("mean", y)
      ...   return y

  Finally we use the run API to apply ``forward`` in parallel on all accelerator
  devices:

      >>> per_replica_y = replicator.run(forward)
  """

  @contextlib.contextmanager
  def scope(self):
    with contextlib.ExitStack() as stack:
      stack.enter_context(super().scope())
      stack.enter_context(tf.variable_creator_scope(replica_local_creator))
      yield

# TODO(tomhennigan) Remove this once TF 2.3 is released.
try:
  TPUStrategy = tf.distribute.TPUStrategy
except AttributeError:
  TPUStrategy = tf.distribute.experimental.TPUStrategy

class TpuReplicator(TPUStrategy):
  r"""Replicates input, parameters and compute over multiple TPUs.

  ``TpuReplicator`` is a TensorFlow "Distribution Strategy" implementing the
  programming model described in the TF-Replicator paper
  :cite:`buchlovsky2019tf` and TensorFlow RFC
  :cite:`buchlovsky2019distribution`. ``TpuReplicator`` enables data-parallel
  training across multiple TPUs on one or more machines, it supports
  :tf:`function`.

  To get started create a ``TpuReplicator`` instance:

      >>> replicator = snt.distribute.TpuReplicator()

  This provides a scope inside which any new :tf:`Variable`\ s will be
  replicated across all TPU cores:

      >>> with replicator.scope():
      ...    mod = snt.Linear(32)

  Additionally replicator provides utility functions to apply a module in
  parallel on multiple devices. First we need to define some computation that
  runs on each TPU. The "replica context" object provides us a way to
  communicate between replicas:

      >>> def forward():
      ...   # Compute a random output on each GPU.
      ...   x = tf.random.normal([8, 28 * 28])
      ...   y = mod(x)
      ...   # Synchronize the value of `y` between all GPUs.
      ...   ctx = tf.distribute.get_replica_context()
      ...   y = ctx.all_reduce("mean", y)
      ...   return y

  Finally we use the run API to apply ``forward`` in parallel on all TPU
  devices. This must be run as part of a :tf:`function` since ``TpuReplicator``
  uses XLA to compile and replicate our function to run in parallel over all
  TPU cores:

      >>> @tf.function(autograph=False)
      ... def all_forward():
      ...   return replicator.run(forward)
      >>> per_replica_y = all_forward()
  """

  @contextlib.contextmanager
  def scope(self):
    with contextlib.ExitStack() as stack:
      stack.enter_context(super().scope())
      stack.enter_context(tf.variable_creator_scope(replica_local_creator))
      yield

def create_variables_eagerly(f: Callable[..., T]) -> Callable[..., T]:
  """Wraps a function and attempts to create variables using eager mode.

  Example usage:

  >>> model = snt.Sequential([snt.Linear(1) for _ in range(100)])

  >>> @tf.function
  ... @snt.distribute.create_variables_eagerly
  ... def f(x):
  ...   return model(x)

  >>> _ = f(tf.ones([1, 1]))

  On a CPU only machine ``f`` will run ~4x faster (700ms vs. 3s), the benefits
  are more pronounced in a distributed setup since eager variable creation can
  skip a number of checks that are required in graph mode (e.g. checking whether
  the variable has already been created) which end up ping-ponging RPCs.

  Args:
    f: Any function.

  Returns:
    A function running `f` in a context where variables are created eagerly.
  """
  def wrapper(*args, **kwargs):
    with contextlib.ExitStack() as stack:
      # The two hacks below enable a large speedup when initializing large
      # models on TPU pods.
      # TODO(b/141243467) Remove these workarounds.
      stack.enter_context(_eager_initial_values())
      stack.enter_context(tf.variable_creator_scope(_eager_variable_creator))
      return f(*args, **kwargs)
  return wrapper

def _eager_variable_creator(getter, initial_value, **kwargs):
  """Attempts to force variable creation to be eager."""
  eager_initial_value = None

  if isinstance(initial_value, tf.Tensor):
    eager_initial_value = tf.get_static_value(initial_value)

  if eager_initial_value is not None:
    # If we have an eager initial value we can create variables in eager mode.
    with tf.init_scope():
      return getter(initial_value=eager_initial_value, **kwargs)

  else:
    # Fall back to creating in whatever context we're in with user input.
    return getter(initial_value=initial_value, **kwargs)

@contextlib.contextmanager
def _eager_initial_values():
  """Attempts to force all initializers to create eager tensors."""
  all_initializers = {cls: cls.__call__
                      for cls in initializers.Initializer.__subclasses__()}

  def patched_call(self, shape, dtype):
    """Monkey-patched verison of `Initializer.__call__`."""
    cls = type(self)
    orig_call = all_initializers[cls]
    try:
      with tf.init_scope():
        return orig_call(self, shape, dtype)
    except:  # pylint: disable=bare-except
      if not tf.executing_eagerly():
        logging.exception(
            "Failed to create initial value eagerly for %s shape=%s dtype=%s",
            type(self).__name__, shape, dtype)
      return orig_call(self, shape, dtype)

  try:
    for cls in all_initializers:
      cls.__call__ = patched_call
    yield

  finally:
    # Restore
    for cls, orig_call in all_initializers.items():
      cls.__call__ = orig_call


text:
package ssa

import (
	"cmd/compile/internal/types"
	"testing"
)

func TestWriteBarrierStoreOrder(t *testing.T) {
	// Make sure writebarrier phase works even StoreWB ops are not in dependency order
	c := testConfig(t)
	ptrType := c.config.Types.BytePtr
	fun := c.Fun("entry",
		Bloc("entry",
			Valu("start", OpInitMem, types.TypeMem, 0, nil),
			Valu("sb", OpSB, types.TypeInvalid, 0, nil),
			Valu("sp", OpSP, types.TypeInvalid, 0, nil),
			Valu("v", OpConstNil, ptrType, 0, nil),
			Valu("addr1", OpAddr, ptrType, 0, nil, "sb"),
			Valu("wb2", OpStore, types.TypeMem, 0, ptrType, "addr1", "v", "wb1"),
			Valu("wb1", OpStore, types.TypeMem, 0, ptrType, "addr1", "v", "start"), // wb1 and wb2 are out of order
			Goto("exit")),
		Bloc("exit",
			Exit("wb2")))

	CheckFunc(fun.f)
	writebarrier(fun.f)
	CheckFunc(fun.f)
}

func TestWriteBarrierPhi(t *testing.T) {
	// Make sure writebarrier phase works for single-block loop, where
	// a Phi op takes the store in the same block as argument.
	// See issue #19067.
	c := testConfig(t)
	ptrType := c.config.Types.BytePtr
	fun := c.Fun("entry",
		Bloc("entry",
			Valu("start", OpInitMem, types.TypeMem, 0, nil),
			Valu("sb", OpSB, types.TypeInvalid, 0, nil),
			Valu("sp", OpSP, types.TypeInvalid, 0, nil),
			Goto("loop")),
		Bloc("loop",
			Valu("phi", OpPhi, types.TypeMem, 0, nil, "start", "wb"),
			Valu("v", OpConstNil, ptrType, 0, nil),
			Valu("addr", OpAddr, ptrType, 0, nil, "sb"),
			Valu("wb", OpStore, types.TypeMem, 0, ptrType, "addr", "v", "phi"), // has write barrier
			Goto("loop")))

	CheckFunc(fun.f)
	writebarrier(fun.f)
	CheckFunc(fun.f)
}


text:
package org.apache.flink.table.runtime.operators.python.scalar;

import org.apache.flink.annotation.Internal;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.python.PythonEnv;
import org.apache.flink.table.functions.python.PythonFunctionInfo;
import org.apache.flink.table.runtime.operators.python.AbstractStatelessFunctionOperator;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.Preconditions;

/**
 * Base class for all stream operators to execute Python {@link ScalarFunction}s. It executes the Python
 * {@link ScalarFunction}s in separate Python execution environment.
 *
 *
The inputs are assumed as the following format:
 * {{{
 *   +------------------+--------------+
 *   | forwarded fields | extra fields |
 *   +------------------+--------------+
 * }}}.
 *
 *
The Python UDFs may take input columns directly from the input row or the execution result of Java UDFs:
 * 1) The input columns from the input row can be referred from the 'forwarded fields';
 * 2) The Java UDFs will be computed and the execution results can be referred from the 'extra fields'.
 *
 *
The outputs will be as the following format:
 * {{{
 *   +------------------+-------------------------+
 *   | forwarded fields | scalar function results |
 *   +------------------+-------------------------+
 * }}}.
 *
 * @param <IN> Type of the input elements.
 * @param <OUT> Type of the output elements.
 * @param <UDFIN> Type of the UDF input type.
 */
@Internal
public abstract class AbstractPythonScalarFunctionOperator<IN, OUT, UDFIN>
		extends AbstractStatelessFunctionOperator<IN, OUT, UDFIN> {

	private static final long serialVersionUID = 1L;

	/**
	 * The Python {@link ScalarFunction}s to be executed.
	 */
	protected final PythonFunctionInfo[] scalarFunctions;

	/**
	 * The offset of the fields which should be forwarded.
	 */
	protected final int[] forwardedFields;

	AbstractPythonScalarFunctionOperator(
		Configuration config,
		PythonFunctionInfo[] scalarFunctions,
		RowType inputType,
		RowType outputType,
		int[] udfInputOffsets,
		int[] forwardedFields) {
		super(config, inputType, outputType, udfInputOffsets);
		this.scalarFunctions = Preconditions.checkNotNull(scalarFunctions);
		this.forwardedFields = Preconditions.checkNotNull(forwardedFields);
	}

	@Override
	public void open() throws Exception {
		userDefinedFunctionOutputType = new RowType(
			outputType.getFields().subList(forwardedFields.length, outputType.getFieldCount()));
		super.open();
	}

	@Override
	public PythonEnv getPythonEnv() {
		return scalarFunctions[0].getPythonFunction().getPythonEnv();
	}

}