text:
package com.fada21.android.hydralist.sample;

public enum SampleContents {

    HYDRALISK("Hydralisk", R.drawable.hydralisk, R.dimen.item_default_height, R.string.hydralisk_details),
    MARINE("Marine", R.drawable.marine, R.dimen.item_default_height, R.string.marine_details),
    ZEALOT("Zealot", R.drawable.zealot, R.dimen.item_default_height, R.string.zealot_details);

    private final String name;
    private final int    iconResId;
    private final int    defHeightResId;
    private final int    textResId;

    private SampleContents(String name, int iconResId, int defHeightResId, int textResId) {
        this.name = name;
        this.iconResId = iconResId;
        this.defHeightResId = defHeightResId;
        this.textResId = textResId;
    }

    public String getName() {
        return name;
    }

    public int getIconResId() {
        return iconResId;
    }

    public int getDefHeightResId() {
        return defHeightResId;
    }

    public int getTextResId() {
        return textResId;
    }

    /**
     * Tells which should expand. Protoss protect their secrets and won't expand to easily.
     * @return true for expandable
     */
    public boolean isSampleExpandable() {
    	return this != ZEALOT;
    }

    /**
     * Tells which should be dragable. Terrans ones sieged is not to be dragged easily.
     * @return
     */
    public boolean isDragable() {
    	return this != MARINE;
    }

}

redpajama_set_name: RedPajamaGithub


text:
title: "Running Git with Github"
layout: "post"
permalink: "/2012/12/running-git.html"
uuid: "5718635464321317608"
guid: "tag:blogger.com,1999:blog-7751875784341660635.post-5718635464321317608"
date: "2012-12-21 09:44:00"
updated: "2012-12-21 09:46:06"
description:
blogger:
    siteid: "7751875784341660635"
    postid: "5718635464321317608"
    comments: "0"
categories: [RSA, Git, SSH]
author:
    name: "Yi Yang"
    url: "https://www.blogger.com/profile/13529726289633825935?rel=author"
    image: "https://img2.blogblog.com/img/b16-rounded.gif"
---

Running Git with Github on Mac seems very easy, with the help from XCode.   However running such configuration on Windows lacks of proper instruction.

The steps are list as following:

Download Git for Windows: http://git-scm.com/download/win

Generate SSH Key, PuTTYgen is a great Windows tool: link
For mac user we can just use: ssh-keygen -t rsa -C "your_email@youremail.com"

Paste your public key here: https://github.com/settings/ssh

Test connection using: ssh -T git@github.com


text:
* Cod fillets,
* Milk,
* Cheddar cheese,
* Cheese & Onion flavour crisps (US: chips),
* Maple syrup.

### Preparation:

1. Steam the fish in the oven, surrounded with milk in a ceramic/glass dish covered in tinfoil\*, until cooked to your usual taste,
2. Preheat the grill,
3. Drain the fish and place onto a tray fashion ed from tinfoil, on a baking tray,
4. Slice the cheese thinly, sufficient to cover the fish in one layer (this retains crisp crispness),
5. Crush the crisps to around 1/3 of their original average size, then cover the cheese & fish,
6. Slice more cheese to cover the crisps, cheese & fish,
7. Drizzle the syrup over it all,
8. Place under the grill and cook until the cheese melts and the syrup starts to caramelise (or brown,)
9. Slide carefully onto a plate, enjoy.

----

\* Alternative steaming methods include on a pan-lidded plate over a pan of boiling water.


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\AssetManager\UIAssetFetcher;

use Piwik\AssetManager\UIAssetFetcher;
use Piwik\Piwik;
use string;

class JScriptUIAssetFetcher extends UIAssetFetcher
{

    protected function retrieveFileLocations()
    {

        if(!empty($this->plugins)) {

            /**
             * Triggered when gathering the list of all JavaScript files needed by Piwik
             * and its plugins.
             *
             * Plugins that have their own JavaScript should use this event to make those
             * files load in the browser.
             *
             * JavaScript files should be placed within a **javascripts** subdirectory in your
             * plugin's root directory.
             *
             * _Note: While you are developing your plugin you should enable the config setting
             * `[Development] disable_merged_assets` so JavaScript files will be reloaded immediately
             * after every change._
             *
             * **Example**
             *
             *     public function getJsFiles(&$jsFiles)
             *     {
             *         $jsFiles[] = "plugins/MyPlugin/javascripts/myfile.js";
             *         $jsFiles[] = "plugins/MyPlugin/javascripts/anotherone.js";
             *     }
             *
             * @param string[] $jsFiles The JavaScript files to load.
             */
             Piwik::postEvent('AssetManager.getJavaScriptFiles', array(&$this->fileLocations), null, $this->plugins);
        }

        $this->addThemeFiles();
    }

    protected function addThemeFiles()
    {
        $theme = $this->getTheme();
        if(!$theme) {
            return;
        }
        if(in_array($theme->getThemeName(), $this->plugins)) {

            $jsInThemes = $this->getTheme()->getJavaScriptFiles();

            if(!empty($jsInThemes)) {

                foreach($jsInThemes as $jsFile) {

                    $this->fileLocations[] = $jsFile;
                }
            }
        }
    }

    protected function getPriorityOrder()
    {
        return array(
            'libs/jquery/jquery.js',
            'libs/jquery/jquery-ui.js',
            'libs/jquery/jquery.browser.js',
            'libs/',
            'plugins/CoreHome/javascripts/require.js',
            'plugins/Morpheus/javascripts/piwikHelper.js',
            'plugins/Morpheus/javascripts/jquery.icheck.min.js',
            'plugins/Morpheus/javascripts/morpheus.js',
            'plugins/Morpheus/javascripts/',
            'plugins/CoreHome/javascripts/uiControl.js',
            'plugins/CoreHome/javascripts/broadcast.js',
            'plugins/CoreHome/javascripts/', // load CoreHome JS before other plugins
            'plugins/',
            'tests/',
        );
    }
}


text:
    <form *ngIf="formResetToggle" class="form-horizontal" name="patientProfileForm" #f="ngForm" novalidate
          (ngSubmit)="f.form.valid ? save() :

          (!gender.valid && showErrorAlert('Gender is required', 'Please select a gender'));

          (!dateOfBirth.valid && showErrorAlert('Date of birth is required', 'Please select a date of birth'));">

            {{'patients.BloodGroup' | translate}}

{{bloodGroupEnum[patient.bloodGroup]}}

                <select id="bloodGroup" name="bloodGroup" bootstrapSelect class="selectpicker form-control is-required-status" title="Select a blood group" [(ngModel)]="patientEdit.bloodGroup">
                    <option [value]="bloodGroupEnum.None">None</option>
                    <option [value]="bloodGroupEnum.O_Positive">O+</option>
                    <option [value]="bloodGroupEnum.O_Negative">O-</option>
                    <option [value]="bloodGroupEnum.A_Positive">A+</option>
                    <option [value]="bloodGroupEnum.A_Negative">A-</option>
                    <option [value]="bloodGroupEnum.B_Positive">B+</option>
                    <option [value]="bloodGroupEnum.B_Negative">B-</option>
                    <option [value]="bloodGroupEnum.AB_Positive">AB+</option>
                    <option [value]="bloodGroupEnum.AB_Negative">AB-</option>
                </select>

            {{'patients.gender' | translate}}

{{genderEnum[patient.gender]}}

                <select id="gender" name="gender" #gender="ngModel" bootstrapSelect required class="selectpicker form-control is-required-status" title="Select a Gender" [(ngModel)]="patientEdit.gender">
                    <option data-icon="fa fa-male" [value]="genderEnum.Male">Male</option>
                    <option data-icon="fa fa-female" [value]="genderEnum.Female">Female</option>
                </select>

                    {{'providers.patients' | translate}}

            {{'patients.DateBirth' | translate}}

{{getPrintedDate(patient.dateOfBirth)}}

                    <input type="text" id="dateOfBirth" name="dateOfBirth" #dateOfBirth="ngModel" class="form-control" placeholder="Enter date of birth"
                           bootstrapDatepicker #datePicker="bootstrap-datepicker" [options]="datepickerOptions" [(ngModel)]="patientEdit.dateOfBirth" required />

                    {{'providers.patients' | translate}}

            {{'patients.city' | translate}}

{{patient.city}}

                <input type="text" id="city" name="city" placeholder="Enter city" class="form-control" [(ngModel)]="patientEdit.city" />

            {{'patients.Address' | translate}}

{{patient.address}}

                <textarea type="text" id="address" name="address" rows="4" placeholder="Enter address" class="form-control is-required-status" [(ngModel)]="patientEdit.address"></textarea>

                    <button *ngIf="!isEditMode && isGeneralEditor" type="button" (click)="close()" class="btn btn-default">{{'patients.Close' | translate}}</button>
                    <button *ngIf="!isEditMode && !isGeneralEditor" type="button" (click)="edit()" class="btn btn-default">{{'patients.Edit' | translate}}</button>
                    <button *ngIf="isEditMode" type="button" (click)="cancel()" class="btn btn-danger" [disabled]="isSaving">{{'patients.Cancel' | translate}}</button>
                    <button *ngIf="isEditMode" type="submit" class="btn btn-primary" [disabled]="isSaving">
                         {{isSaving ? 'Saving...' : 'Save'}}
                    </button>

    </form>


text:
bool os_is_target(const char* attribute, bool release, bool* out_is_target)
{
  assert(attribute != NULL);
  assert(out_is_target != NULL);

  if(!strcmp(attribute, OS_FREEBSD_NAME))
  {
#ifdef PLATFORM_IS_FREEBSD
    *out_is_target = true;
#else
    *out_is_target = false;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_LINUX_NAME))
  {
#ifdef PLATFORM_IS_LINUX
    *out_is_target = true;
#else
    *out_is_target = false;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_MACOSX_NAME))
  {
#ifdef PLATFORM_IS_MACOSX
    *out_is_target = true;
#else
    *out_is_target = false;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_WINDOWS_NAME))
  {
#ifdef PLATFORM_IS_WINDOWS
    *out_is_target = true;
#else
    *out_is_target = false;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_POSIX_NAME))
  {
#if defined PLATFORM_IS_POSIX_BASED
    *out_is_target = true;
#else
    *out_is_target = false;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_HAS_I128_NAME))
  {
#ifdef PLATFORM_IS_VISUAL_STUDIO
    *out_is_target = false;
#else
    *out_is_target = true;
#endif
    return true;
  }

  if(!strcmp(attribute, OS_DEBUG_NAME))
  {
    *out_is_target = !release;
    return true;
  }

  return false;
}


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

#ifndef BITCOIN_WALLET_TRANSACTION_H
#define BITCOIN_WALLET_TRANSACTION_H

#include <consensus/amount.h>
#include <primitives/transaction.h>
#include <serialize.h>
#include <wallet/ismine.h>
#include <threadsafety.h>
#include <tinyformat.h>
#include <util/overloaded.h>
#include <util/strencodings.h>
#include <util/string.h>

#include <list>
#include <variant>
#include <vector>

namespace wallet {
//! State of transaction confirmed in a block.
struct TxStateConfirmed {
    uint256 confirmed_block_hash;
    int confirmed_block_height;
    int position_in_block;

    explicit TxStateConfirmed(const uint256& block_hash, int height, int index) : confirmed_block_hash(block_hash), confirmed_block_height(height), position_in_block(index) {}
};

//! State of transaction added to mempool.
struct TxStateInMempool {
};

//! State of rejected transaction that conflicts with a confirmed block.
struct TxStateConflicted {
    uint256 conflicting_block_hash;
    int conflicting_block_height;

    explicit TxStateConflicted(const uint256& block_hash, int height) : conflicting_block_hash(block_hash), conflicting_block_height(height) {}
};

//! State of transaction not confirmed or conflicting with a known block and
//! not in the mempool. May conflict with the mempool, or with an unknown block,
//! or be abandoned, never broadcast, or rejected from the mempool for another
//! reason.
struct TxStateInactive {
    bool abandoned;

    explicit TxStateInactive(bool abandoned = false) : abandoned(abandoned) {}
};

//! State of transaction loaded in an unrecognized state with unexpected hash or
//! index values. Treated as inactive (with serialized hash and index values
//! preserved) by default, but may enter another state if transaction is added
//! to the mempool, or confirmed, or abandoned, or found conflicting.
struct TxStateUnrecognized {
    uint256 block_hash;
    int index;

    TxStateUnrecognized(const uint256& block_hash, int index) : block_hash(block_hash), index(index) {}
};

//! All possible CWalletTx states
using TxState = std::variant<TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized>;

//! Subset of states transaction sync logic is implemented to handle.
using SyncTxState = std::variant<TxStateConfirmed, TxStateInMempool, TxStateInactive>;

//! Try to interpret deserialized TxStateUnrecognized data as a recognized state.
static inline TxState TxStateInterpretSerialized(TxStateUnrecognized data)
{
    if (data.block_hash == uint256::ZERO) {
        if (data.index == 0) return TxStateInactive{};
    } else if (data.block_hash == uint256::ONE) {
        if (data.index == -1) return TxStateInactive{/*abandoned=*/true};
    } else if (data.index >= 0) {
        return TxStateConfirmed{data.block_hash, /*height=*/-1, data.index};
    } else if (data.index == -1) {
        return TxStateConflicted{data.block_hash, /*height=*/-1};
    }
    return data;
}

//! Get TxState serialized block hash. Inverse of TxStateInterpretSerialized.
static inline uint256 TxStateSerializedBlockHash(const TxState& state)
{
    return std::visit(util::Overloaded{
        [](const TxStateInactive& inactive) { return inactive.abandoned ? uint256::ONE : uint256::ZERO; },
        [](const TxStateInMempool& in_mempool) { return uint256::ZERO; },
        [](const TxStateConfirmed& confirmed) { return confirmed.confirmed_block_hash; },
        [](const TxStateConflicted& conflicted) { return conflicted.conflicting_block_hash; },
        [](const TxStateUnrecognized& unrecognized) { return unrecognized.block_hash; }
    }, state);
}

//! Get TxState serialized block index. Inverse of TxStateInterpretSerialized.
static inline int TxStateSerializedIndex(const TxState& state)
{
    return std::visit(util::Overloaded{
        [](const TxStateInactive& inactive) { return inactive.abandoned ? -1 : 0; },
        [](const TxStateInMempool& in_mempool) { return 0; },
        [](const TxStateConfirmed& confirmed) { return confirmed.position_in_block; },
        [](const TxStateConflicted& conflicted) { return -1; },
        [](const TxStateUnrecognized& unrecognized) { return unrecognized.index; }
    }, state);
}

typedef std::map<std::string, std::string> mapValue_t;

/** Legacy class used for deserializing vtxPrev for backwards compatibility.
 * vtxPrev was removed in commit 93a18a3650292afbb441a47d1fa1b94aeb0164e3,
 * but old wallet.dat files may still contain vtxPrev vectors of CMerkleTxs.
 * These need to get deserialized for field alignment when deserializing
 * a CWalletTx, but the deserialized values are discarded.**/
class CMerkleTx
{
public:
    template<typename Stream>
    void Unserialize(Stream& s)
    {
        CTransactionRef tx;
        uint256 hashBlock;
        std::vector<uint256> vMerkleBranch;
        int nIndex;

        s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
    }
};

/**
 * A transaction with a bunch of additional info that only the owner cares about.
 * It includes any unrecorded transactions needed to link it back to the block chain.
 */
class CWalletTx
{
public:
    /**
     * Key/value map with information about the transaction.
     *
     * The following keys can be read and written through the map and are
     * serialized in the wallet database:
     *
     *     "comment", "to"   - comment strings provided to sendtoaddress,
     *                         and sendmany wallet RPCs
     *     "replaces_txid"   - txid (as HexStr) of transaction replaced by
     *                         bumpfee on transaction created by bumpfee
     *     "replaced_by_txid" - txid (as HexStr) of transaction created by
     *                         bumpfee on transaction replaced by bumpfee
     *     "from", "message" - obsolete fields that could be set in UI prior to
     *                         2011 (removed in commit 4d9b223)
     *
     * The following keys are serialized in the wallet database, but shouldn't
     * be read or written through the map (they will be temporarily added and
     * removed from the map during serialization):
     *
     *     "fromaccount"     - serialized strFromAccount value
     *     "n"               - serialized nOrderPos value
     *     "timesmart"       - serialized nTimeSmart value
     *     "spent"           - serialized vfSpent value that existed prior to
     *                         2014 (removed in commit 93a18a3)
     */
    mapValue_t mapValue;
    std::vector<std::pair<std::string, std::string> > vOrderForm;
    unsigned int fTimeReceivedIsTxTime;
    unsigned int nTimeReceived; //!< time received by this node
    /**
     * Stable timestamp that never changes, and reflects the order a transaction
     * was added to the wallet. Timestamp is based on the block time for a
     * transaction added as part of a block, or else the time when the
     * transaction was received if it wasn't part of a block, with the timestamp
     * adjusted in both cases so timestamp order matches the order transactions
     * were added to the wallet. More details can be found in
     * CWallet::ComputeTimeSmart().
     */
    unsigned int nTimeSmart;
    /**
     * From me flag is set to 1 for transactions that were created by the wallet
     * on this bitcoin node, and set to 0 for transactions that were created
     * externally and came in through the network or sendrawtransaction RPC.
     */
    bool fFromMe;
    int64_t nOrderPos; //!< position in ordered transaction list
    std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;

    // memory only
    enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
    mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
    /**
     * This flag is true if all m_amounts caches are empty. This is particularly
     * useful in places where MarkDirty is conditionally called and the
     * condition can be expensive and thus can be skipped if the flag is true.
     * See MarkDestinationsDirty.
     */
    mutable bool m_is_cache_empty{true};
    mutable bool fChangeCached;
    mutable CAmount nChangeCached;

    CWalletTx(CTransactionRef tx, const TxState& state) : tx(std::move(tx)), m_state(state)
    {
        Init();
    }

    void Init()
    {
        mapValue.clear();
        vOrderForm.clear();
        fTimeReceivedIsTxTime = false;
        nTimeReceived = 0;
        nTimeSmart = 0;
        fFromMe = false;
        fChangeCached = false;
        nChangeCached = 0;
        nOrderPos = -1;
    }

    CTransactionRef tx;
    TxState m_state;

    template<typename Stream>
    void Serialize(Stream& s) const
    {
        mapValue_t mapValueCopy = mapValue;

        mapValueCopy["fromaccount"] = "";
        if (nOrderPos != -1) {
            mapValueCopy["n"] = ToString(nOrderPos);
        }
        if (nTimeSmart) {
            mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
        }

        std::vector<uint8_t> dummy_vector1; //!< Used to be vMerkleBranch
        std::vector<uint8_t> dummy_vector2; //!< Used to be vtxPrev
        bool dummy_bool = false; //!< Used to be fSpent
        uint256 serializedHash = TxStateSerializedBlockHash(m_state);
        int serializedIndex = TxStateSerializedIndex(m_state);
        s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
    }

    template<typename Stream>
    void Unserialize(Stream& s)
    {
        Init();

        std::vector<uint256> dummy_vector1; //!< Used to be vMerkleBranch
        std::vector<CMerkleTx> dummy_vector2; //!< Used to be vtxPrev
        bool dummy_bool; //! Used to be fSpent
        uint256 serialized_block_hash;
        int serializedIndex;
        s >> tx >> serialized_block_hash >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;

        m_state = TxStateInterpretSerialized({serialized_block_hash, serializedIndex});

        const auto it_op = mapValue.find("n");
        nOrderPos = (it_op != mapValue.end()) ? LocaleIndependentAtoi<int64_t>(it_op->second) : -1;
        const auto it_ts = mapValue.find("timesmart");
        nTimeSmart = (it_ts != mapValue.end()) ? static_cast<unsigned int>(LocaleIndependentAtoi<int64_t>(it_ts->second)) : 0;

        mapValue.erase("fromaccount");
        mapValue.erase("spent");
        mapValue.erase("n");
        mapValue.erase("timesmart");
    }

    void SetTx(CTransactionRef arg)
    {
        tx = std::move(arg);
    }

    //! make sure balances are recalculated
    void MarkDirty()
    {
        m_amounts[DEBIT].Reset();
        m_amounts[CREDIT].Reset();
        m_amounts[IMMATURE_CREDIT].Reset();
        m_amounts[AVAILABLE_CREDIT].Reset();
        fChangeCached = false;
        m_is_cache_empty = true;
    }

    /** True if only scriptSigs are different */
    bool IsEquivalentTo(const CWalletTx& tx) const;

    bool InMempool() const;

    int64_t GetTxTime() const;

    template<typename T> const T* state() const { return std::get_if<T>(&m_state); }
    template<typename T> T* state() { return std::get_if<T>(&m_state); }

    bool isAbandoned() const { return state<TxStateInactive>() && state<TxStateInactive>()->abandoned; }
    bool isConflicted() const { return state<TxStateConflicted>(); }
    bool isUnconfirmed() const { return !isAbandoned() && !isConflicted() && !isConfirmed(); }
    bool isConfirmed() const { return state<TxStateConfirmed>(); }
    const uint256& GetHash() const { return tx->GetHash(); }
    const uint256& GetWitnessHash() const { return tx->GetWitnessHash(); }
    bool IsCoinBase() const { return tx->IsCoinBase(); }

    // Disable copying of CWalletTx objects to prevent bugs where instances get
    // copied in and out of the mapWallet map, and fields are updated in the
    // wrong copy.
    CWalletTx(CWalletTx const &) = delete;
    void operator=(CWalletTx const &x) = delete;
};

struct WalletTxOrderComparator {
    bool operator()(const CWalletTx* a, const CWalletTx* b) const
    {
        return a->nOrderPos < b->nOrderPos;
    }
};
} // namespace wallet

#endif // BITCOIN_WALLET_TRANSACTION_H


text:
<?php

session_start();

	$username= $_POST['username'];
	$password= $_POST['password'];

if(empty($username) || empty($password)){

echo "Please enter values in username and password fields";

}

else{

	function pg_connection_string_from_database_url() {
  extract(parse_url($_ENV["DATABASE_URL"]));
  return "user=$user password=$pass host=$host dbname=" . substr($path, 1);
}

$pg_conn = pg_connect(pg_connection_string_from_database_url());
$pwd= md5($password);
$result = pg_query($pg_conn, "SELECT username__c, Pass__c FROM salesforce.Heroku_User__c WHERE username__c= '$username' AND Pass__c= '$pwd' Limit 1;");

$rows = pg_num_rows($result);

if($rows > 0){
$_SESSION['is_logged_in']= true;
$_SESSION['user_email']= $username;

header('location: mainPage.php');

}

else{
echo'Username or password is wrong';
}

}


text:
<?php

/**
 * Smarty Method GetTemplateVars
 *
 * Smarty::getTemplateVars() method
 *
 * @package    Smarty
 * @subpackage PluginsInternal
 * @author     Uwe Tews
 */
class Smarty_Internal_Method_GetTemplateVars
{
    /**
     * Valid for all objects
     *
     * @var int
     */
    public $objMap = 7;

    /**
     * Returns a single or all template variables
     *
     * @api  Smarty::getTemplateVars()
     * @link http://www.smarty.net/docs/en/api.get.template.vars.tpl
     *
     * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data
     * @param  string                                                 $varName       variable name or null
     * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $_ptr          optional pointer to data object
     * @param  bool                                                   $searchParents include parent templates?
     *
     * @return mixed variable value or or array of variables
     */
    public function getTemplateVars(Smarty_Internal_Data $data, $varName = null, Smarty_Internal_Data $_ptr = null,
                                    $searchParents = true)
    {
        if (isset($varName)) {
            $_var = $this->_getVariable($data, $varName, $_ptr, $searchParents, false);
            if (is_object($_var)) {
                return $_var->value;
            } else {
                return null;
            }
        } else {
            $_result = array();
            if ($_ptr === null) {
                $_ptr = $data;
            }
            while ($_ptr !== null) {
                foreach ($_ptr->tpl_vars AS $key => $var) {
                    if (!array_key_exists($key, $_result)) {
                        $_result[ $key ] = $var->value;
                    }
                }
                // not found, try at parent
                if ($searchParents) {
                    $_ptr = $_ptr->parent;
                } else {
                    $_ptr = null;
                }
            }
            if ($searchParents && isset(Smarty::$global_tpl_vars)) {
                foreach (Smarty::$global_tpl_vars AS $key => $var) {
                    if (!array_key_exists($key, $_result)) {
                        $_result[ $key ] = $var->value;
                    }
                }
            }
            return $_result;
        }
    }

    /**
     * gets the object of a Smarty variable
     *
     * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data
     * @param string                                                  $varName       the name of the Smarty variable
     * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $_ptr          optional pointer to data object
     * @param bool                                                    $searchParents search also in parent data
     * @param bool                                                    $errorEnable
     *
     * @return \Smarty_Variable
     */
    public function _getVariable(Smarty_Internal_Data $data, $varName, Smarty_Internal_Data $_ptr = null,
                                 $searchParents = true, $errorEnable = true)
    {
        if ($_ptr === null) {
            $_ptr = $data;
        }
        while ($_ptr !== null) {
            if (isset($_ptr->tpl_vars[ $varName ])) {
                // found it, return it
                return $_ptr->tpl_vars[ $varName ];
            }
            // not found, try at parent
            if ($searchParents) {
                $_ptr = $_ptr->parent;
            } else {
                $_ptr = null;
            }
        }
        if (isset(Smarty::$global_tpl_vars[ $varName ])) {
            // found it, return it
            return Smarty::$global_tpl_vars[ $varName ];
        }
        /* @var \Smarty $smarty */
        $smarty = isset($data->smarty) ? $data->smarty : $data;
        if ($smarty->error_unassigned && $errorEnable) {
            // force a notice
            $x = $$varName;
        }

        return new Smarty_Undefined_Variable;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.net-->
<!--
     Copyright (C) 2012-2014 The CyanogenMod Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="dark_theme_name">ชุดรูปแบบมืด</string>
  <string name="dark_theme_desc">ชุดรูปแบบมืดสำหรับตัวจัดการไฟล์ของ CyanogenMod</string>
</resources>


text:
A Cydia repository template. This template contains sample on how you can easily make depiction pages without replicating your html pages. The pages are styled using [Bootsrap](http://getbootstrap.com/) which is really easy to use. You can see how it looks like by visiting [this sample repo]https://github.com/Nrepo/Nrepo.github.io on your desktop or mobile phone.

Most data for this repo is stored on XML files and are loaded on the depiction page dynamically. See the guide below on how to set it up. Note that this guide doesn't cover creating .deb files but will briefly cover assiging depictions.

## How to install this template

### 1. Download
The latest release will always be [here]https://github.com/Nrepo/Nrepo.github.io/archive/master.zip.

### 2. Extract
Extract the contents into a subfolder on your website. If you're using [Github Pages](https://pages.github.com/), it should be under `username.github.io`.

#### 3. Personalize
Edit `Release` file. Modify the items pointed by `<--`

    Origin:  NsBm0d   <--
    Label:  NsBm0d    <--
    Suite: stable
    Version: 1.0
    Codename: ios
    Architectures: iphoneos-arm
    Components: main
    Description:  NsBm0d  - a cydia repo template  <--

#### 4. Your repo is ready.
At this point your repo is basically ready to be added into Cydia. You can also visit your repo's homepage by going to `https://username.github.io/repo/`. It will come with 2 sample packages, Nicon Package and NsB Package. Each of the packages have a link on this page pointing to their depictions. Next guide will show you how to assign and customize your depiction pages.

## Depiction pages for your packages

#### 1. A basic depiction page
Let's start with a simple one. First, of course, add your `.deb` files into the `debs` folder. Then, inside the `depictions` folder, duplicate the folder `com.Nrepo.Nicon`. You will see 2 xml files -- `info.xml` and `changelog.xml`. Edit the 2 files and put in the information regarding you package. The tags are pretty much self-explanatory.

`info.xml`.
```xml
<package>
	<id>com.Nrepo.Nicon</id>
	<name>Nicon</name>
	<version>1.0.4</version>
	<compatibility>
		<firmware>
      <miniOS>7.0</miniOS>
      <maxiOS>9.0+</maxiOS>
			<otherVersions>unsupported</otherVersions>
			<!--
			for otherVersions, you can put either unsupported or unconfirmed
			-->
		</firmware>
	</compatibility>
	<dependencies></dependencies>
	<descriptionlist>
		<description>This adds icons to the Sections.</description>
	</descriptionlist>
	<screenshots></screenshots>
	<changelog>
		<change>Initial release</change>
	</changelog>
	<links></links>
</package>
```
Edit `changelog.xml`.
```xml
<changelog>
	<changes>
		<version>1.0.0-1</version>
		<change>Initial release</change>
	</changes>
</changelog>
```

#### 2. Edit the depiction footer data
This data are the links that appear at the bottom of every depication. The data is stored in `repo.xml` at the root folder of your repo.

```xml
<repo>
	<footerlinks>
		<link>
			<name>I want this depiction template</name>
			<url>https://github.com/Nrepo/Nrepo.github.io</url>
			<iconclass>glyphicon glyphicon-thumbs-up</iconclass>
		</link>
	</footerlinks>
</repo>
```

#### 3. Link the depiction page to your Packages file.
Your depiction like should look like this:
```text
Depiction: https://username.github.io/repo/depictions/?p=[idhere]
```
Replace `[idhere]` with your actual package id.
```text
Depiction:
https://username.github.io/depictions/?p=com.Nrepo.Nicon
```
#### 4. Almost there
Compress your Packages file to bzip2 and there you have it! In case you haven't done yet, add your repo `https://username.github.io` to cydia.
  One final touch is to update `index.html`. Look at line 18 and 19. Change line 18 into your own **brand**, line 19 to have your own URL, and line 20 will have your YouTube video link.
YouTube Channel section Line 30 to have your YouTube Channel name, line 33 a brief description about your channel, and line 34 to have your YouTube Channel link.
Your packages section Lines 42-60 contains the list of packages you will need to edit those too. To add more packages just duplicate the previous package the add it under the last package then edit it as needed.
```html
16 <div class="container">
17 	<div class="well">
18 		<p><span class="text-primary"><b> NsBm0d </span></b> is a Cydia repository template.</p>
19 		<a class="btn btn-sm btn-default" href="cydia://url/cydia://url/https://cydia.saurik.com/api/share#?source=https://Nrepo.github.io//">Add to Cydia</a>
20    <a class="btn btn-sm btn-default" href="https://youtu.be/4goGcf1cVrQ">How to Add to Cydia</a>
21 	</div>
22 </div>

# YouTube Channel section
28 <div class="container">
29	<div class="panel panel-default">
30	  <div class="panel-heading"> NsBm0d </div>
31	  <div class="panel-body">
32		This is my YouTube Channel.
33		It also as other things that do not reference to Cydia.<br /><br />
34		<a class="btn btn-xs btn-default" href="https://www.youtube.com/user/NsBm0d">More info</a>
35	  </div>
36	</div>

# Your packages section
42 <div class="container">
43	<div class="panel panel-default">
44	  <div class="panel-heading">Nicon</div>
45	  <div class="panel-body">
46		This is a package with minimal information.
47		It also is an icon package.<br /><br />
48		<a class="btn btn-xs btn-default" href="depictions/?p=com.Nrepo.Nicon">More info</a>
49	  </div>
50	</div>
51
52	<div class="panel panel-default">
53	  <div class="panel-heading">NsB</div>
54	  <div class="panel-body">
55		This is a Theme that is used with Anemone.<br /><br />
56		<a class="btn btn-xs btn-default" href="depictions/?p=com.Nrepo.NsB">More info</a>
57	  </div>
58	</div>
59 </div>
60
```
#### 5. ALL DONE!
**And there you have it! Your first package on your repo!**

## What Next?
If you want to put more information on your depictions, see the other sample in `\depictions\com.Nrepo.NsB\`. This sample contains all the information that is supported.

Also, this guide is mostly a work in progress. I'll add up more details soon -- screenshots, more samples, repo icon, etc.


text:
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/

import java.util.*;

// line 29 "Library.ump"
// line 86 "Library.ump"
public class Author
{

  //------------------------
  // MEMBER VARIABLES
  //------------------------

  //Author Associations
  private List<EditionOrIssue> editionOrIssues;

  //------------------------
  // CONSTRUCTOR
  //------------------------

  public Author()
  {
    editionOrIssues = new ArrayList<EditionOrIssue>();
  }

  //------------------------
  // INTERFACE
  //------------------------

  public EditionOrIssue getEditionOrIssue(int index)
  {
    EditionOrIssue aEditionOrIssue = editionOrIssues.get(index);
    return aEditionOrIssue;
  }

  public List<EditionOrIssue> getEditionOrIssues()
  {
    List<EditionOrIssue> newEditionOrIssues = Collections.unmodifiableList(editionOrIssues);
    return newEditionOrIssues;
  }

  public int numberOfEditionOrIssues()
  {
    int number = editionOrIssues.size();
    return number;
  }

  public boolean hasEditionOrIssues()
  {
    boolean has = editionOrIssues.size() > 0;
    return has;
  }

  public int indexOfEditionOrIssue(EditionOrIssue aEditionOrIssue)
  {
    int index = editionOrIssues.indexOf(aEditionOrIssue);
    return index;
  }

  public static int minimumNumberOfEditionOrIssues()
  {
    return 0;
  }

  public boolean addEditionOrIssue(EditionOrIssue aEditionOrIssue)
  {
    boolean wasAdded = false;
    if (editionOrIssues.contains(aEditionOrIssue)) { return false; }
    editionOrIssues.add(aEditionOrIssue);
    if (aEditionOrIssue.indexOfAuthor(this) != -1)
    {
      wasAdded = true;
    }
    else
    {
      wasAdded = aEditionOrIssue.addAuthor(this);
      if (!wasAdded)
      {
        editionOrIssues.remove(aEditionOrIssue);
      }
    }
    return wasAdded;
  }

  public boolean removeEditionOrIssue(EditionOrIssue aEditionOrIssue)
  {
    boolean wasRemoved = false;
    if (!editionOrIssues.contains(aEditionOrIssue))
    {
      return wasRemoved;
    }

    int oldIndex = editionOrIssues.indexOf(aEditionOrIssue);
    editionOrIssues.remove(oldIndex);
    if (aEditionOrIssue.indexOfAuthor(this) == -1)
    {
      wasRemoved = true;
    }
    else
    {
      wasRemoved = aEditionOrIssue.removeAuthor(this);
      if (!wasRemoved)
      {
        editionOrIssues.add(oldIndex,aEditionOrIssue);
      }
    }
    return wasRemoved;
  }

  public boolean addEditionOrIssueAt(EditionOrIssue aEditionOrIssue, int index)
  {
    boolean wasAdded = false;
    if(addEditionOrIssue(aEditionOrIssue))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfEditionOrIssues()) { index = numberOfEditionOrIssues() - 1; }
      editionOrIssues.remove(aEditionOrIssue);
      editionOrIssues.add(index, aEditionOrIssue);
      wasAdded = true;
    }
    return wasAdded;
  }

  public boolean addOrMoveEditionOrIssueAt(EditionOrIssue aEditionOrIssue, int index)
  {
    boolean wasAdded = false;
    if(editionOrIssues.contains(aEditionOrIssue))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfEditionOrIssues()) { index = numberOfEditionOrIssues() - 1; }
      editionOrIssues.remove(aEditionOrIssue);
      editionOrIssues.add(index, aEditionOrIssue);
      wasAdded = true;
    }
    else
    {
      wasAdded = addEditionOrIssueAt(aEditionOrIssue, index);
    }
    return wasAdded;
  }

  public void delete()
  {
    ArrayList<EditionOrIssue> copyOfEditionOrIssues = new ArrayList<EditionOrIssue>(editionOrIssues);
    editionOrIssues.clear();
    for(EditionOrIssue aEditionOrIssue : copyOfEditionOrIssues)
    {
      aEditionOrIssue.removeAuthor(this);
    }
  }

}


text:
require 'gitlab'
require 'terminal-table/import'
require_relative 'cli_helpers'
require_relative 'shell'

class Gitlab::CLI
  extend Helpers

  def self.start(args)
    command = args.shift.strip rescue 'help'
    run(command, args)
  end

  def self.run(cmd, args=[])
    case cmd
    when 'help'
      puts actions_table
    when 'info'
      endpoint = Gitlab.endpoint ? Gitlab.endpoint : 'not set'
      private_token = Gitlab.private_token ? Gitlab.private_token : 'not set'
      puts "Gitlab endpoint is #{endpoint}"
      puts "Gitlab private token is #{private_token}"
      puts "Ruby Version is #{RUBY_VERSION}"
      puts "Gitlab Ruby Gem #{Gitlab::VERSION}"
    when '-v', '--version'
      puts "Gitlab Ruby Gem #{Gitlab::VERSION}"
    when 'shell'
      Gitlab::Shell.start
    else
      unless valid_command?(cmd)
        puts "Unknown command. Run `gitlab help` for a list of available commands."
        exit(1)
      end

      if args.any? && (args.last.start_with?('--only=') || args.last.start_with?('--except='))
        command_args = args[0..-2]
      else
        command_args = args
      end

      confirm_command(cmd)

      data = gitlab_helper(cmd, command_args) { exit(1) }
      output_table(cmd, args, data)
    end
  end
end


text:
#ifndef _H_CASPER_CP_SOLVER
#define _H_CASPER_CP_SOLVER

#include <casper/kernel/state/env.h>
#include <casper/kernel/goal/explorer.h>
#include <casper/cp/store.h>
// not needed by this header (just for user convenience)
#include <casper/cp/goal/bb.h>
#include <casper/cp/view/ref.h>
#include <casper/cp/filter/objective.h>

namespace Casper {
namespace CP {

struct Solver;

struct SolverStats
{
	SolverStats(Solver& solver) : solver(solver) {}
	const StateStats& getStateStats() const;
	const StoreStats& getStoreStats() const;
	const ExplorerStats& getExplorerStats() const;
protected:
	Solver& solver;
};

struct Solver : Env,Store
{
	Solver();
	~Solver() {}

	// these are necessary to solve ambiguity since both Env and Store auto convert to IHeap
	operator Util::IHeap&() { return static_cast<Env&>(*this); }
	operator const Util::IHeap&() const { return static_cast<const Env&>(*this); }

	operator State&() { return static_cast<Env&>(*this); }
	operator const State&() const { return static_cast<const Env&>(*this); }

	void setExplorer(IExplorer* e) {	pExplorer = e;	}
	IExplorer* getExplorer() {	return pExplorer;	}

	bool solve(Goal g) {	return valid() and pExplorer->explore(g);	}
#ifndef SWIG_BUILD
	template<class T>
	bool solve(const T& t) {	return valid() and pExplorer->explore(Goal(*this,t));	}
#endif
	bool next()	{	return	pExplorer->resume();	}

	const SolverStats& getStats() const
	{	return stats;	}
	SolverStats& getStats()
	{	return stats;	}

	const Util::CPUTimer& getCPUTimer() const
	{	return static_cast<const Env&>(*this).getStats().getCPUTimer(); }

	Util::IHeap& getHeap() {	return Env::getHeap(); }
	const Util::IHeap& getHeap() const {	return Env::getHeap();}

private:
	Reversible<IExplorer*>			pExplorer;
	SolverStats						stats;
};

} // CP
} // Casper

std::ostream& operator<<(std::ostream& os, const Casper::CP::SolverStats& s);

#endif


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using Microsoft.Win32;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace Microsoft.Build.UnitTests
{
    /// <summary>
    /// Helper class to simulate application configuration read
    /// </summary>
    internal class ToolsetConfigurationReaderTestHelper
    {
        private static ExeConfigurationFileMap s_configFile;
        private static string s_testFolderFullPath = null;
        private static Exception s_exceptionToThrow = null;

        internal static string WriteConfigFile(string content)
        {
            return WriteConfigFile(ObjectModelHelpers.CleanupFileContents(content), null);
        }

        internal static string WriteConfigFile(string content, Exception exception)
        {
            s_exceptionToThrow = exception;
            s_testFolderFullPath = Path.Combine(Path.GetTempPath(), "configFileTests");
            Directory.CreateDirectory(s_testFolderFullPath);
            string configFilePath = Path.Combine(s_testFolderFullPath, "test.exe.config");

            if (File.Exists(configFilePath))
            {
                File.Delete(configFilePath);
            }

            File.WriteAllText(configFilePath, content);
            s_configFile = new ExeConfigurationFileMap();
            s_configFile.ExeConfigFilename = configFilePath;
            return configFilePath;
        }

        internal static void CleanUp()
        {
            try
            {
                if (s_testFolderFullPath != null && Directory.Exists(s_testFolderFullPath))
                {
                    for (int i = 0; i < 5; i++)
                    {
                        try
                        {
                            Directory.Delete(s_testFolderFullPath, true /* recursive */);
                            break;
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1000);
                            // Eat exceptions from the delete
                        }
                    }
                }
            }
            finally
            {
                s_exceptionToThrow = null;
            }
        }

        /// <summary>
        /// Creates a config file and loads a Configuration from it
        /// </summary>
        /// <returns>configuration object</returns>
        internal static Configuration ReadApplicationConfigurationTest()
        {
            if (s_exceptionToThrow != null)
            {
                throw s_exceptionToThrow;
            }

            return ConfigurationManager.OpenMappedExeConfiguration(s_configFile, ConfigurationUserLevel.None);
        }
    }
}


text:
package playlists.providers.plugdj.api;

import java.io.Serializable;

public class PlugDjPlayList implements Serializable {
    private boolean active;
    private int count;
    private String id;
    private String name;

    public PlugDjPlayList() {
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PlugDjPlayList that = (PlugDjPlayList) o;

        if (active != that.active) return false;
        if (count != that.count) return false;
        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        return !(name != null ? !name.equals(that.name) : that.name != null);

    }

    @Override
    public int hashCode() {
        int result = (active ? 1 : 0);
        result = 31 * result + count;
        result = 31 * result + (id != null ? id.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "PlugDjPlayList{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}


text:
Nectarine Demoscene Radio XBMC Plugin
=====================================

Stream the best of demoscene music from Nectarine Demoscene Radio (www.scenemusic.net) directly from XBMC using this fan-made plugin.


text:
using System.IO;

namespace OEmbed.Net.Utilities
{
    public interface ISerializer<T>
    {
        string Serialize(T content);
        T Deserialize(string content);
        T Deserialize(Stream content);
    }
}


text:
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrustStampCore.Repository;
using TrustStampCore.Service;
using TrustStampCore.Extensions;

namespace TrustStampTests.Core.Repository
{
    [TestFixture]
    public class DBBatchTableTest : StampTest
    {
        [Test]
        public void TestAddDefault()
        {
            var partition = Batch.GetCurrentPartition();
            using (var db = TrustStampDatabase.Open())
            {
                var item = db.BatchTable.AddDefault(partition);
                Assert.IsNotNull(item);

                var count = db.BatchTable.Count();

                Assert.AreEqual(1, count);
            }
        }

        [Test]
        public void TestGetByPartition()
        {
            var partition = Batch.GetCurrentPartition();
            using (var db = TrustStampDatabase.Open())
            {
                db.BatchTable.AddDefault(partition);
                var item = db.BatchTable.GetByPartition(partition);
                Assert.AreEqual(0, ((byte[])item["root"]).Length);

                Assert.AreEqual(partition, (string)item["partition"]);
            }
        }

        [Test]
        public void TestUpdate()
        {
            var partition = Batch.GetCurrentPartition();
            using (var db = TrustStampDatabase.Open())
            {
                db.BatchTable.AddDefault(partition);
                var item = db.BatchTable.GetByPartition(partition);
                Assert.AreEqual(1, (int)item["active"]);

                item["root"] = Crypto.GetRandomHash();
                Assert.AreEqual(20, ((byte[])item["root"]).Length);

                item["active"] = 0;
                Assert.AreEqual(1, db.BatchTable.Update(item));

                var updatedItem = db.BatchTable.GetByPartition(partition);

                Assert.AreEqual(20, ((byte[])updatedItem["root"]).Length);
                Assert.AreEqual(0, (int)updatedItem["active"]);
            }
        }

        [Test]
        public void TestEnsure()
        {
            var partition = Batch.GetCurrentPartition();
            using (var db = TrustStampDatabase.Open())
            {
                var batch = db.BatchTable.Ensure(partition);
                var item = db.BatchTable.GetByPartition(partition);

                Assert.AreEqual(partition, (string)item["partition"]);
                Assert.AreEqual("", item["state"]);
                Assert.AreEqual(1, (int)item["active"]);
            }
        }

        [Test]
        public void TestGetActive()
        {

            using (var db = TrustStampDatabase.Open())
            {
                var inactiveBatch = db.BatchTable.Ensure(Batch.GetPartition(DateTime.Now));
                inactiveBatch["active"] = 0;
                db.BatchTable.Update(inactiveBatch);

                db.BatchTable.Ensure(Batch.GetPartition(DateTime.Now.AddDays(1)));
                db.BatchTable.Ensure(Batch.GetPartition(DateTime.Now.AddDays(2)));
                db.BatchTable.Ensure(Batch.GetPartition(DateTime.Now.AddDays(3)));

                var active = db.BatchTable.GetActive();

                Assert.AreEqual(3, active.Count);
                Assert.AreEqual(Batch.GetPartition(DateTime.Now.AddDays(3)), (string)active[0]["partition"]);
                Assert.AreEqual(Batch.GetPartition(DateTime.Now.AddDays(2)), (string)active[1]["partition"]);
                Assert.AreEqual(Batch.GetPartition(DateTime.Now.AddDays(1)), (string)active[2]["partition"]);
            }
        }

    }
}


text:
const path = require("path");
const utils = require("../utils");
const logger = require("../logger");
const generate = require("./generate");

module.exports = function(opt) {
  logger.log('Generating "%s" into "%s" directory.', opt.template, opt.dest);
  utils.resolveTemplateSource(opt.template, function(src) {
    opt.srcBasePath = path.resolve(src, "../");
    opt.src = src;
    generate(opt);
  });
};


text:
var Promise     = require('bluebird'),
    sequence    = require('../../../utils/sequence'),
    _           = require('lodash'),
    errors      = require('../../../errors'),
    models      = require('../../../models'),
    fixtures    = require('./permissions'),

    // private
    logInfo,
    addAllPermissions,
    addAllRolesPermissions,
    addRolesPermissionsForRole,

    // public
    populate;

logInfo = function logInfo(message) {
  errors.logInfo('Migrations', message);
};

addRolesPermissionsForRole = function (roleName) {
  var fixturesForRole = fixtures.permissions_roles[roleName],
      permissionsToAdd;

  return models.Role.forge({name: roleName}).fetch({withRelated: ['permissions']}).then(function (role) {
    return models.Permissions.forge().fetch().then(function (permissions) {
      if (_.isObject(fixturesForRole)) {
        permissionsToAdd = _.map(permissions.toJSON(), function (permission) {
          var objectPermissions = fixturesForRole[permission.object_type];
          if (objectPermissions === 'all') {
            return permission.id;
          } else if (_.isArray(objectPermissions) && _.contains(objectPermissions, permission.action_type)) {
            return permission.id;
          }
          return null;
        });
      }

      return role.permissions().attach(_.compact(permissionsToAdd));
    });
  });
};

addAllRolesPermissions = function () {
  var roleNames = _.keys(fixtures.permissions_roles),
      ops = [];

  _.each(roleNames, function (roleName) {
    ops.push(addRolesPermissionsForRole(roleName));
  });

  return Promise.all(ops);
};

addAllPermissions = function (options) {
  var ops = [];
  _.each(fixtures.permissions, function (permissions, objectType) {
    _.each(permissions, function (permission) {
      ops.push(function () {
        permission.object_type = objectType;
        return models.Permission.add(permission, options);
      });
    });
  });

  return sequence(ops);
};

// ## Populate
populate = function (options) {
  logInfo('Populating permissions');
  // ### Ensure all permissions are added
  return addAllPermissions(options).then(function () {
    // ### Ensure all roles_permissions are added
    return addAllRolesPermissions();
  });
};

module.exports = {
  populate: populate
};


text:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable name="repository"
            type="com.trollologic.pocketgithub.models.SearchItem"/>

        <variable name="handler"
            type="com.trollologic.pocketgithub.repo_details.RepoDetailsClickListeners"/>
    </data>
    <RelativeLayout
        android:id="@+id/activity_repo_details"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            tools:context="com.trollologic.pocketgithub.repo_details.RepoDetailsActivity">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/repo_avatar"
                android:layout_marginLeft="@dimen/material_8_dp"
                android:layout_marginRight="@dimen/material_8_dp"
                android:layout_width="@dimen/material_36_dp"
                android:layout_height="@dimen/material_36_dp"
                app:civ_border_width="1dp"
                app:civ_fill_color="@android:color/white"
                app:civ_border_color="@color/colorPrimary"
                tools:src="@drawable/ic_fingerprint_black_24dp"
                android:onClick="@{() -> handler.openUserProfile(repository.owner)}"
                />

            <TextView
                android:gravity="center_vertical"
                android:layout_alignBottom="@id/repo_avatar"
                android:layout_alignTop="@id/repo_avatar"
                android:layout_toRightOf="@id/repo_avatar"
                android:layout_width="match_parent"
                android:textSize="@dimen/big_text_size"
                android:lines="1"
                android:ellipsize="end"
                android:layout_height="wrap_content"
                android:text="@{repository.full_name}"/>

            <TextView
                android:id="@+id/language"
                android:layout_marginTop="@dimen/material_8_dp"
                android:gravity="center_vertical"
                android:layout_below="@id/repo_avatar"
                android:layout_width="match_parent"
                android:lines="1"
                android:ellipsize="end"
                android:layout_height="wrap_content"
                />

            <TextView
                android:id="@+id/issues"
                android:layout_marginTop="@dimen/material_8_dp"
                android:gravity="center_vertical"
                android:layout_below="@id/language"
                android:layout_width="match_parent"
                android:lines="1"
                android:ellipsize="end"
                android:layout_height="wrap_content"
                />

            <TextView
                android:id="@+id/default_branch"
                android:layout_marginTop="@dimen/material_8_dp"
                android:gravity="center_vertical"
                android:layout_below="@id/issues"
                android:layout_width="match_parent"
                android:lines="1"
                android:ellipsize="end"
                android:layout_height="wrap_content"
                />

            <TextView
                android:id="@+id/description"
                android:layout_marginTop="@dimen/material_8_dp"
                android:gravity="center_vertical"
                android:layout_below="@id/default_branch"
                android:layout_width="match_parent"
                android:lines="1"
                android:ellipsize="end"
                android:layout_height="wrap_content"
                />

            <Button
                android:layout_alignParentBottom="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/check_repository_details"
                android:onClick="@{() -> handler.openWebFragment(repository.getHtml_url())}"/>

        </RelativeLayout>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </RelativeLayout>
</layout>


text:
print "Top is Ochi"

print "Hello"

print "Change is made"
print "Dre"

print "Zach"


text:
---
layout: up
title: Writing Your First Extension
---

[PyPN](http://www.pnotepad.org/add-ons/) provides a great way to add functionality to Programmer's Notepad by writing simple Python code, but you might want to do something more advanced. For this there's the Programmer's Notepad [Extension SDK](https://github.com/simonsteele/pn/releases/download/v2.4/sdk-2.4.0.zip).

The SDK lets you extend PN using C++, allowing you to react to editor events and provide new commands in the menu. PyPN is itself implemented as an extension using this same SDK, and you can use the SDK to provide support for other scripting languages too.

## What You'll Need

You need a Windows C++ compiler and the [Boost](http://boost.org/) C++ library. Note that you don't need to compile any of boost, we use the header-only bits.

I suggest using the free [Microsoft Visual C++ Express](http://www.microsoft.com/express/vc/Default.aspx) if you don't already have Visual Studio, this should guarantee compatibility.

## Getting Started

Download the SDK and copy the template project, this is a good base for your extension. Note that the SDK also contains a demo extension showing use of various parts of the SDK. Change the name and version of your extension and you're ready to add it to Programmer's Notepad for the first time:

```cpp
void __declspec(dllexport) __stdcall pn_get_extension_info(PN::BaseString& name, PN::BaseString& version)
{
    name = "My First Plugin";
    version = "1.0";
}
```

Compile the extension and place the .dll file in your PN directory. Now run "pn --findexts" and your plugin will be discovered and loaded the next time you start PN. Go to Tools->Options->Extensions and see your extension listed.

Everything else you want to do flows from the instance of IPN that's passed to your init function. This interface gives you access to the open documents, lets you sign up to handle document events and gives you access to app-level services like script registration, find in files and options management.

## Working with Documents

Everything you want to do with an open document is done through the IDocument interface. You get a pointer to one of these from your IPN instance by calling GetCurrentDocument, NewDocument or equivalent.

```cpp
    // Make a new document
    IDocumentPtr doc = pn->NewDocument(NULL);

    // Send scintilla messages (see scintilla.org documentation)
    doc->SendEditorMessage(SCI_APPENDTEXT, 6, (LPARAM)"Hello!");

    // Save changes
    doc->Save("c:\\temp\\test.txt", true);

    // Done with the document
    doc->Close();
```

## Adding Menu Items

Menu items are added via the IPN object provided at extension load time. You add menu items by providing an implementation of IMenuItems. Here is a very simple implementation supporting a single item:

```cpp
class Menu : public extensions::IMenuItems
{
public:
    Menu()
    {
        memset(&item1, 0, sizeof(item1));
        item1.Handler = &MyExtensionFunc;
        item1.Title = L"Hello World";
        // item1.Type = extensions::miItem;
        // item1.UserData = 0;
    }

    /**
     * Get the number of MenuItem instances that can be retrieved.
     */
    virtual int GetItemCount() const
    {
        return 1;
    }

    /**
     * Get an individual MenuItem instance by index.
     */
    virtual extensions::MenuItem& GetItem(int index) const
    {
        if (index == 0)
            return const_cast<extensions::menuitem&>(item1);
    }

private:
    extensions::MenuItem item1;
};
```

This very simple implementation adds a single menu item called "Hello World". When the item is selected, the MyExtensionFunc method will be executed by PN.

It might seem like a fair bit of code to add a menu item, but in the next SDK version I'll provide a general-purpose helper to make this easy. The reason for the interface is to make it easy for you to provide sub-menus. MenuItem instances can contain child items by changing Type to miSubItem and filling in the SubItems member with another instance implementing IMenuItems.

The handler method looks like this:

```cpp
void MyExtensionFunc(extensions::cookie_t /*cookie*/)
{
    g_PN->GetGlobalOutputWindow()->AddToolOutput("Hello World!");
    g_PN->ShowOutput();
}
```

Once you have your handler and IMenuItems implementation, you just need to tell PN about your items. In your init function you need something like this:

```cpp
bool __stdcall pn_init_extension(int iface_version, extensions::IPN* pn)
{
    if(iface_version != PN_EXT_IFACE_VERSION)
        return false;

    g_PN = pn;

    Menu menu;
    pn->AddPluginMenuItems(&menu);

    return true;
}
```

Now you have Programmer's Notepad presenting your commands in the menu and can handle their selection.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>sistrak-base</artifactId>
        <groupId>br.com.kopp</groupId>
        <version>1.0</version>
    </parent>

    <artifactId>sistrak-base-ear</artifactId>
    <packaging>ear</packaging>

    <name>sistrak-base-ear</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.10.1</version>
                <configuration>
                    <version>7</version>
                    <defaultLibBundleDir>lib</defaultLibBundleDir>

                    <modules>
                        <ejbModule>
                            <groupId>br.com.kopp</groupId>
                            <artifactId>sistrak-base-ejb</artifactId>
                        </ejbModule>
                        <jarModule>
                            <groupId>br.com.kopp</groupId>
                            <artifactId>sistrak-base-api</artifactId>
                        </jarModule>
                        <webModule>
                            <groupId>br.com.kopp</groupId>
                            <artifactId>sistrak-base-rest</artifactId>
                        </webModule>
                    </modules>

                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>br.com.kopp</groupId>
            <artifactId>sistrak-base-ejb</artifactId>
            <version>${project.version}</version>
            <type>ejb</type>
        </dependency>
        <dependency>
            <groupId>br.com.kopp</groupId>
            <artifactId>sistrak-base-rest</artifactId>
            <version>${project.version}</version>
            <type>war</type>
        </dependency>
        <dependency>
            <groupId>br.com.kopp</groupId>
            <artifactId>sistrak-base-api</artifactId>
            <version>${project.version}</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>


text:
Git log => turbo mode

Today I learned that I can combine `-S 'my-search'` and `-p` in `git log` command. Here is an example:

```shell
git log -p -S 'create_or' app/models/*.rb
```

command dissecting:

- `-p` => equivalent to `git diff` for each commit found on log
- `-S 'my-seach'` => filtering by commits that **add/remove this content**

viniciusnegrisolo
June 22, 2016


text:
namespace mcpputil
{

  template <>
  thread_id_manager_t *singleton_t<thread_id_manager_t>::s_s{nullptr};
  thread_local thread_id_manager_t::id_type thread_id_manager_t::t_thread_id{
      ::std::numeric_limits<thread_id_manager_t::id_type>::max()};
  thread_id_manager_t::thread_id_manager_t() = default;
  void thread_id_manager_t::set_max_tls_pointers(ptr_index sz)
  {
    MCPPALLOC_CONCURRENCY_LOCK_GUARD(m_mutex);
    if (m_max_tls_pointers != 0) {
      throw ::std::runtime_error("thread_id_manager_t max tls pointers already set.");
    }
    if (m_max_num_threads == 0) {
      throw ::std::runtime_error("thread_id_manager_t max num threads must be set before setting max tls pointers.");
    }
    m_max_tls_pointers = sz;
    m_ptr_array.resize(::gsl::narrow<size_t>(m_max_num_threads * m_max_tls_pointers));
    for (auto &&obj : m_ptr_array) {
      obj = nullptr;
    }
  }
  void thread_id_manager_t::set_max_threads(id_type max_threads)
  {
    MCPPALLOC_CONCURRENCY_LOCK_GUARD(m_mutex);
    if (m_max_num_threads != 0) {
      throw ::std::runtime_error("thread_id_manager_t max threads already set");
    }
    m_max_num_threads = max_threads;
    m_native_handles.resize(::gsl::narrow<size_t>(m_max_num_threads));
  }
  auto thread_id_manager_t::add_current_thread() -> id_type
  {
    t_thread_id = add_thread(::std::this_thread::get_id());
    return t_thread_id;
  }
  auto thread_id_manager_t::add_thread(std_id_type sid) -> id_type
  {
    MCPPALLOC_CONCURRENCY_LOCK_GUARD(m_mutex);
    auto it = m_native_id_map.find(sid);
    if (it != m_native_id_map.end()) {
      return it->second;
    }
    auto avail_id_it = ::std::find(m_native_handles.begin(), m_native_handles.end(), ::boost::none);
    if (avail_id_it == m_native_handles.end()) {
      throw ::std::runtime_error("thread_id_manager_t out of handles.");
    }
    auto new_id = ::gsl::narrow<id_type>(avail_id_it - m_native_handles.begin());
    *avail_id_it = sid;
    m_native_id_map[sid] = new_id;
    return new_id;
  }
  void thread_id_manager_t::remove_thread(std_id_type sid)
  {
    MCPPALLOC_CONCURRENCY_LOCK_GUARD(m_mutex);
    auto it = m_native_id_map.find(sid);
    if (it == m_native_id_map.end()) {
      return;
    }
    auto id = it->second;
    m_native_handles.at(::gsl::narrow<size_t>(id)) = ::boost::none;
    m_native_id_map.erase(it);
  }
  void thread_id_manager_t::remove_current_thread()
  {
    remove_thread(::std::this_thread::get_id());
    t_thread_id = 0;
  }
} // namespace mcpputil


text:
<?php

namespace Metadata;

interface MergeableInterface
{
    /**
     * @return void
     */
    public function merge(MergeableInterface $object);
}


text:
FROM opensuse:42.1

# Install the base toolchain we need to build anything (clang, cmake, make and the like)
# this does not include libraries that we need to compile different projects, we'd like
# them in a different layer.
RUN zypper -n install binutils \
              cmake \
              which \
              gcc \
              llvm-clang \
              tar \
              ncurses-utils \
              curl \
              git \
              sudo && \
    ln -s /usr/bin/clang++ /usr/bin/clang++-3.5 && \
    zypper clean -a

# Dependencies of CoreCLR and CoreFX.

RUN zypper -n install --force-resolution \
                      libunwind \
                      libicu \
                      lttng-ust \
                      libuuid1 \
                      libopenssl1_0_0 \
                      libcurl4 \
                      krb5 && \
    zypper clean -a

# Setup User to match Host User, and give superuser permissions
ARG USER_ID=0
RUN useradd -m code_executor -u ${USER_ID} -g wheel
RUN echo 'code_executor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# With the User Change, we need to change permissions on these directories
RUN chmod -R a+rwx /usr/local
RUN chmod -R a+rwx /home
RUN chmod -R 755 /usr/lib/sudo

# Set user to the one we just created
USER ${USER_ID}

# Set working directory
WORKDIR /opt/code


text:
FROM debian:stretch

RUN groupadd --gid 1000 -r explorer && useradd --uid 1000 --create-home --system -g explorer explorer \
	&& mkdir -p /explorer

ENV PYTHONUNBUFFERED=1 \
	PYTHONDONTWRITEBYTECODE=1 \
	PYTHONPATH=/explorer

RUN apt-get update \
	&& apt-get install -y --no-install-recommends \
	   python-pip \
	   libpq-dev \
	   postgresql-client \
	   build-essential \
	   libpython2.7 \
	   python-dev \
	   wget \
	&& apt-get clean \
	&& pip install virtualenv
# Note: we're installing libpython2.7 because uWSGI needs it on runtime (crashes if it can't find it)

RUN su explorer -c "virtualenv /home/explorer/env"

COPY ./requirements /home/explorer/requirements
ARG INSTALL_REQUIREMENTS=production
RUN su explorer -c ". /home/explorer/env/bin/activate && \
	pip install --no-cache-dir -r /home/explorer/requirements/$INSTALL_REQUIREMENTS.pip && \
	rm -rf /home/explorer/.cache"

RUN apt-get purge -y python-dev build-essential libpq-dev && apt-get autoremove -y

COPY . /explorer

WORKDIR /explorer

# Always make the project virtualenv active
ENV VIRTUAL_ENV=/home/explorer/env \
	PATH=/home/explorer/env/bin:$PATH \
	FLASK_APP=app.py

EXPOSE 5000

USER explorer

HEALTHCHECK --interval=1m --timeout=3s CMD wget --content-on-error -qO- http://localhost:5000/header || exit 1

CMD ["flask", "run", "--host=0.0.0.0"]


text:
namespace QuizFactory.Mvc.Areas.Common.Controllers
{
    using System;
    using System.Collections;
    using System.Data.Entity;
    using System.Web.Mvc;
    using AutoMapper;
    using Kendo.Mvc.Extensions;
    using Kendo.Mvc.UI;
    using QuizFactory.Data;
    using QuizFactory.Data.Common;
    using QuizFactory.Mvc.Areas.Admin.ViewModels;
    using QuizFactory.Mvc.Controllers;

    public abstract class KendoGridAdministrationController : BaseController
    {
        public KendoGridAdministrationController(IQuizFactoryData data)
            : base(data)
        {
        }

        [HttpPost]
        public ActionResult Read([DataSourceRequest]
                                 DataSourceRequest request)
        {
            var ads = this.GetData().ToDataSourceResult(request);

            return this.Json(ads);
        }

        protected abstract IEnumerable GetData();

        protected abstract T GetById<T>(object id) where T : class;

        [NonAction]
        protected virtual T Create<T>(object model) where T : class
        {
            if (model != null && this.ModelState.IsValid)
            {
                var dbModel = Mapper.Map<T>(model);
                this.ChangeEntityStateAndSave(dbModel, EntityState.Added);
                return dbModel;
            }

            return null;
        }

        [NonAction]
        protected virtual void Update<TModel, TViewModel>(TViewModel model, object id)
            where TModel : AuditInfo
            where TViewModel : QuizAdminViewModel
        {
            if (model != null && this.ModelState.IsValid)
            {
                var dbModel = this.GetById<TModel>(id);
                Mapper.Map<TViewModel, TModel>(model, dbModel);

                this.ChangeEntityStateAndSave(dbModel, EntityState.Modified);
            }
        }

        protected JsonResult GridOperation<T>(T model, [DataSourceRequest] DataSourceRequest request)
        {
            return this.Json(new[] { model }.ToDataSourceResult(request, this.ModelState));
        }

        private void ChangeEntityStateAndSave(object dbModel, EntityState state)
        {
            var entry = this.Db.Context.Entry(dbModel);
            entry.State = state;
            this.Db.SaveChanges();
        }
    }
}


text:
//
// Created by chris on 23.05.15.
//

#ifndef IRCBOT_BOTCONFIG_H
#define IRCBOT_BOTCONFIG_H

#include "tools/PropertiesFile.h"

class BotConfig {
private:
    PropertiesFile props;
protected:
    /**
     * Prepares the configuration file.
     * Makes sure it exists and is at least filled with default values.
     *
     */
    void prepare();
public:

    BotConfig();
    ~BotConfig();
    /**
     * Saves the configurations
     */
    void save();

    std::string getBotNick();

    std::string getBotUserName();

    std::string getBotOwner();

    std::string getIrcServer();

    int getIrcServerPort();

    std::string getDefaultChannel();

    static BotConfig* instance();

};

#endif //IRCBOT_BOTCONFIG_H


text:
using System;
using SharpDX;
using System.Globalization;
#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Cameras
    {
        using Model;

        public abstract class CameraCore : ObservableObject, ICamera
        {
            private Vector3 position;
            public Vector3 Position
            {
                set
                {
                    Set(ref position, value);
                }
                get
                {
                    return position;
                }
            }

            private Vector3 lookDirection;
            public Vector3 LookDirection
            {
                set
                {
                    Set(ref lookDirection, value);
                }
                get
                {
                    return lookDirection;
                }
            }

            private Vector3 upDirection;
            public Vector3 UpDirection
            {
                set
                {
                    Set(ref upDirection, value);
                }
                get
                {
                    return upDirection;
                }
            }

            public Vector3 Target
            {
                get
                {
                    return position + lookDirection;
                }
            }

            private bool createLeftHandSystem = false;
            /// <summary>
            /// Gets or sets a value indicating whether to create a left hand system.
            /// </summary>
            /// <value>
            /// <c>true</c> if creating a left hand system; otherwise, <c>false</c>.
            /// </value>
            public bool CreateLeftHandSystem
            {
                set
                {
                    Set(ref createLeftHandSystem, value);
                }
                get
                {
                    return createLeftHandSystem;
                }
            }

            public abstract Matrix CreateProjectionMatrix(float aspectRatio);

            public abstract Matrix CreateProjectionMatrix(float aspectRatio, float nearPlane, float farPlane);

            public abstract Matrix CreateViewMatrix();

            public abstract FrustumCameraParams CreateCameraParams(float aspectRatio);
            public abstract FrustumCameraParams CreateCameraParams(float aspectRatio, float nearPlane, float farPlane);
            public override string ToString()
            {
                var target = Position + LookDirection;
                return string.Format(
                            CultureInfo.InvariantCulture,
                            "LookDirection:\t{0:0.000},{1:0.000},{2:0.000}",
                            LookDirection.X,
                            LookDirection.Y,
                            LookDirection.Z) + "\n"
                            + string.Format(
                            CultureInfo.InvariantCulture,
                            "UpDirection:\t{0:0.000},{1:0.000},{2:0.000}",
                            UpDirection.X,
                            UpDirection.Y,
                            UpDirection.Z) + "\n"
                            + string.Format(
                            CultureInfo.InvariantCulture,
                            "Position:\t\t{0:0.000},{1:0.000},{2:0.000}",
                            Position.X,
                            Position.Y,
                            Position.Z) + "\n"
                            + string.Format(
                            CultureInfo.InvariantCulture,
                            "Target:\t\t{0:0.000},{1:0.000},{2:0.000}",
                            target.X,
                            target.Y,
                            target.Z);
            }

            private Vector3 targetPosition;
            private Vector3 targetLookDirection;
            private Vector3 targetUpDirection;
            private Vector3 oldPosition;
            private Vector3 oldLookDir;
            private Vector3 oldUpDir;
            private float aniTime = 0;
            private float accumTime = 0;
            private long prevTicks = 0;
            /// <summary>
            /// Animates to.
            /// </summary>
            /// <param name="newPosition">The new position.</param>
            /// <param name="newDirection">The new direction.</param>
            /// <param name="newUpDirection">The new up direction.</param>
            /// <param name="animationTime">The animation time.</param>
            public void AnimateTo(
                Vector3 newPosition,
                Vector3 newDirection,
                Vector3 newUpDirection,
                float animationTime)
            {
                if (animationTime == 0)
                {
                    Position = newPosition;
                    LookDirection = newDirection;
                    UpDirection = newUpDirection;
                    aniTime = 0;
                }
                else
                {
                    targetPosition = newPosition;
                    targetLookDirection = newDirection;
                    targetUpDirection = newUpDirection;
                    oldPosition = Position;
                    oldLookDir = LookDirection;
                    oldUpDir = UpDirection;
                    aniTime = animationTime;
                    accumTime = 1;
                    prevTicks = System.Diagnostics.Stopwatch.GetTimestamp();
                    OnUpdateAnimation(0);
                }
            }
            /// <summary>
            /// Called when [time step] to update camera animation.
            /// </summary>
            /// <returns></returns>
            public virtual bool OnTimeStep()
            {
                var ticks = System.Diagnostics.Stopwatch.GetTimestamp();
                var ellapsed = (float)(ticks - prevTicks) / System.Diagnostics.Stopwatch.Frequency * 1000;
                prevTicks = ticks;
                return OnUpdateAnimation(ellapsed);
            }

            protected virtual bool OnUpdateAnimation(float ellapsed)
            {
                if (aniTime == 0)
                {
                    return false;
                }
                accumTime += ellapsed;
                if (accumTime > aniTime)
                {
                    Position = targetPosition;
                    LookDirection = targetLookDirection;
                    UpDirection = targetUpDirection;
                    aniTime = 0;
                    return false;
                }
                else
                {
                    var l = accumTime / aniTime;
                    var nextPos = Vector3.Lerp(oldPosition, targetPosition, l);
                    var nextLook = Vector3.Lerp(oldLookDir, targetLookDirection, l);
                    var nextUp = Vector3.Lerp(oldUpDir, targetUpDirection, l);
                    Position = nextPos;
                    LookDirection = nextLook;
                    UpDirection = nextUp;
                    return true;
                }
            }

            public void StopAnimation()
            {
                aniTime = 0;
            }
        }

        public abstract class ProjectionCameraCore : CameraCore
        {
            private float farPlane = 100;
            /// <summary>
            /// Gets or sets the far plane distance.
            /// </summary>
            /// <value>
            /// The far plane distance.
            /// </value>
            public float FarPlaneDistance
            {
                set
                {
                    Set(ref farPlane, value);
                }
                get
                {
                    return farPlane;
                }
            }

            private float nearPlane = 0.001f;
            /// <summary>
            /// Gets or sets the near plane distance.
            /// </summary>
            /// <value>
            /// The near plane distance.
            /// </value>
            public float NearPlaneDistance
            {
                set
                {
                    Set(ref nearPlane, value);
                }
                get
                {
                    return nearPlane;
                }
            }

            public override Matrix CreateViewMatrix()
            {
                return CreateLeftHandSystem ? Matrix.LookAtLH(this.Position, this.Position + this.LookDirection, this.UpDirection)
                    : Matrix.LookAtRH(this.Position, this.Position + this.LookDirection, this.UpDirection);
            }

            public override string ToString()
            {
                return base.ToString() + "\n" +
                    string.Format(
                            CultureInfo.InvariantCulture, "NearPlaneDist:\t{0}", NearPlaneDistance) + "\n"
                            + string.Format(CultureInfo.InvariantCulture, "FarPlaneDist:\t{0}", FarPlaneDistance);
            }
        }

        public class OrthographicCameraCore : ProjectionCameraCore
        {
            private float width = 100;
            public float Width
            {
                set
                {
                    Set(ref width, value);
                }
                get
                {
                    return width;
                }
            }

            public override FrustumCameraParams CreateCameraParams(float aspectRatio)
            {
                return CreateCameraParams(aspectRatio, NearPlaneDistance, FarPlaneDistance);
            }

            public override FrustumCameraParams CreateCameraParams(float aspectRatio, float nearPlane, float farPlane)
            {
                return new FrustumCameraParams()
                {
                    AspectRatio = aspectRatio,
                    FOV = (float)Math.PI / 2,
                    LookAtDir = LookDirection,
                    UpDir = UpDirection,
                    Position = Position,
                    ZNear = nearPlane,
                    ZFar = farPlane
                };
            }

            public override Matrix CreateProjectionMatrix(float aspectRatio)
            {
                return CreateProjectionMatrix(aspectRatio, NearPlaneDistance, FarPlaneDistance);
            }

            public override Matrix CreateProjectionMatrix(float aspectRatio, float nearPlane, float farPlane)
            {
                return this.CreateLeftHandSystem ?
                    Matrix.OrthoLH(this.Width, (float)(this.Width / aspectRatio), nearPlane, Math.Min(1e15f, farPlane))
                    : Matrix.OrthoRH(this.Width, (float)(this.Width / aspectRatio), nearPlane, Math.Min(1e15f, farPlane));
            }

            public override string ToString()
            {
                return base.ToString() + "\n" + string.Format(CultureInfo.InvariantCulture, "Width:\t{0:0.###}", Width);
            }

#if CORE
            private float oldWidth;
            private float targetWidth;
            private float accumTime;
            private float aniTime;

            public void AnimateWidth(float newWidth, float animationTime)
            {
                if (animationTime == 0)
                {
                    UpdateCameraPositionByWidth(newWidth);
                    Width = newWidth;
                }
                else
                {
                    oldWidth = Width;
                    this.targetWidth = newWidth;
                    accumTime = 1;
                    aniTime = animationTime;
                    OnUpdateAnimation(0);
                }
            }

            protected override bool OnUpdateAnimation(float ellapsed)
            {
                bool res = base.OnUpdateAnimation(ellapsed);
                if (aniTime == 0)
                {
                    return res;
                }
                accumTime += ellapsed;
                if (accumTime > aniTime)
                {
                    UpdateCameraPositionByWidth(targetWidth);
                    Width = targetWidth;
                    aniTime = 0;
                    return res;
                }
                else
                {
                    var newWidth = oldWidth + (targetWidth - oldWidth) * (accumTime / aniTime);
                    UpdateCameraPositionByWidth(newWidth);
                    Width = newWidth;
                    return true;
                }
            }

            private void UpdateCameraPositionByWidth(double newWidth)
            {
                var ratio = newWidth / Width;
                var dir = LookDirection;
                var target = Target;
                var dist = dir.Length();
                var newDist = dist * ratio;
                dir.Normalize();
                var position = (target - dir * (float)newDist);
                var lookDir = dir * (float)newDist;
                Position = position;
                LookDirection = lookDir;
            }
#endif
        }

        public class PerspectiveCameraCore : ProjectionCameraCore
        {
            public float FieldOfView
            {
                set; get;
            } = 45;

            public override Matrix CreateProjectionMatrix(float aspectRatio)
            {
                return CreateProjectionMatrix(aspectRatio, NearPlaneDistance, FarPlaneDistance);
            }

            public override Matrix CreateProjectionMatrix(float aspectRatio, float nearPlane, float farPlane)
            {
                var fov = this.FieldOfView * Math.PI / 180;
                Matrix projM;
                if (this.CreateLeftHandSystem)
                {
                    projM = Matrix.PerspectiveFovLH((float)fov, aspectRatio, nearPlane, farPlane);
                }
                else
                {
                    projM = Matrix.PerspectiveFovRH((float)fov, (float)aspectRatio, nearPlane, farPlane);
                }
                if (float.IsNaN(projM.M33) || float.IsNaN(projM.M43))
                {
                    projM.M33 = projM.M43 = -1;
                }
                return projM;
            }

            public override FrustumCameraParams CreateCameraParams(float aspectRatio)
            {
                return CreateCameraParams(aspectRatio, NearPlaneDistance, FarPlaneDistance);
            }
            public override FrustumCameraParams CreateCameraParams(float aspectRatio, float nearPlane, float farPlane)
            {
                return new FrustumCameraParams()
                {
                    AspectRatio = aspectRatio,
                    FOV = FieldOfView / 180f * (float)(Math.PI),
                    LookAtDir = LookDirection,
                    UpDir = UpDirection,
                    Position = Position,
                    ZNear = nearPlane,
                    ZFar = farPlane
                };
            }
            public override string ToString()
            {
                return base.ToString() + "\n" + string.Format(CultureInfo.InvariantCulture, "FieldOfView:\t{0:0.#}°", FieldOfView);
            }
        }
    }
}


text:
Geometriq is an extensible library for creating 2D geometrical art.

It provides a single, unified API for creating a variety of shapes
and transforms, and abstracts away the implementation details of
numerous backend systems, including:

  * [CoreGraphics][coregraphics_link] (macOS and iOS)
  * Pythonista's [canvas module][canvas_link] (partial, for iOS)
  * [Pillow][pillow_link] (partial)
  * [PyX][pyx_link] (rudimentary)

As well as planned:

  * [Cairo][cairo_link] (on Linux, macOS, and Windows)

[coregraphics_link]: https://developer.apple.com/documentation/coregraphics?changes=_7 "CoreGraphics"
[canvas_link]: http://omz-software.com/pythonista/docs/ios/canvas.html "canvas module"
[pillow_link]: https://pillow.readthedocs.io/en/5.1.x/ "Pillow"
[pyx_link]: http://pyx.sourceforge.net/documentation.html "PyX"
[cairo_link]: https://www.cairographics.org/manual/ "Cairo"


text:
layout: post
title: Udacity Deep Learning Course By Google
tags: [MOOC, Machine-Learning]
---

![deep-learning-google]({{ site.baseurl }}/images/2016020700.png "deep-learning-google")

### Deep Learning By Google @ udacity
FYI, the course link is [https://www.udacity.com/course/deep-learning--ud730](https://www.udacity.com/course/deep-learning--ud730). This course takes
Approximately 3 months with assumption 6hrs/wk (work at your own pace).

### Knowledge Needed
- Python (using jupyter notebook)

### Assumption On Achievement
- Good at using Tensorflow: which should be the main reason google had built this course, to promote their open source machine learning framework. IMHO, Tensorflow really lack of documentation/example due to its age.
- More deep learning knowledge: Andrew Ng Machine Learning course only slightly covered neural network, I do hope can learn something new about deep learning here

### Syllabus
This course consist of four Lessons:

- Lesson 1: From Machine Learning to Deep Learning
- Lesson 2: Deep Neural Networks
- Lesson 3: Convolutional Neural Networks
- Lesson 4: Deep Models for Text and Sequences

### So far on Lessons 1
Nothings new if you had attended other machine learning course. Basicly:

- Prepare your Docker environment which consist of Course Materials with Jupyter Notebook for the future Lesson
- Walkthrough on basic machine learning rules such as learning rate, overfitting, etc.

### Comment
This is really a course that machine learning guys shouldn't miss. Deep learning is the state of the art machine learning technique which has been used to solve many real world problem.

You probably know that AlphaGo - which is mainly written in deep learning - has beaten the three-time European Go champion Fan Hui 5–0.


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Tests\Integration\Routes\V2;

use Twilio\Exceptions\DeserializeException;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\Response;
use Twilio\Tests\HolodeckTestCase;
use Twilio\Tests\Request;

class PhoneNumberTest extends HolodeckTestCase {
    public function testUpdateRequest(): void {
        $this->holodeck->mock(new Response(500, ''));

        try {
            $this->twilio->routes->v2->phoneNumbers("phone_number")->update();
        } catch (DeserializeException $e) {}
          catch (TwilioException $e) {}

        $this->assertRequest(new Request(
            'post',
            'https://routes.twilio.com/v2/PhoneNumbers/phone_number'
        ));
    }

    public function testUpdateResponse(): void {
        $this->holodeck->mock(new Response(
            200,
            '
            {
                "phone_number": "+18001234567",
                "url": "https://routes.twilio.com/v2/PhoneNumbers/+18001234567",
                "sid": "QQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "friendly_name": "friendly_name",
                "voice_region": "au1",
                "date_created": "2015-07-30T20:00:00Z",
                "date_updated": "2015-07-30T20:00:00Z"
            }
            '
        ));

        $actual = $this->twilio->routes->v2->phoneNumbers("phone_number")->update();

        $this->assertNotNull($actual);
    }

    public function testFetchRequest(): void {
        $this->holodeck->mock(new Response(500, ''));

        try {
            $this->twilio->routes->v2->phoneNumbers("phone_number")->fetch();
        } catch (DeserializeException $e) {}
          catch (TwilioException $e) {}

        $this->assertRequest(new Request(
            'get',
            'https://routes.twilio.com/v2/PhoneNumbers/phone_number'
        ));
    }

    public function testFetchResponse(): void {
        $this->holodeck->mock(new Response(
            200,
            '
            {
                "phone_number": "+18001234567",
                "url": "https://routes.twilio.com/v2/PhoneNumbers/+18001234567",
                "sid": "QQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "friendly_name": "friendly_name",
                "voice_region": "au1",
                "date_created": "2015-07-30T20:00:00Z",
                "date_updated": "2015-07-30T20:00:00Z"
            }
            '
        ));

        $actual = $this->twilio->routes->v2->phoneNumbers("phone_number")->fetch();

        $this->assertNotNull($actual);
    }
}


text:
const data = {
    stage: null,
    background: 0xffffff,
    width: 32,
    height: 32,
    framerate: 24,
    totalFrames: 1,
    assets: {
        "alpha": "images/alpha.shapes.json"
    },
    lib: {},
    shapes: {},
    textures: {},
    spritesheets: [],
    getTexture: function(id) {
        if (data.textures[id]) {
            return data.textures[id];
        }
        const atlas = data.spritesheets.find(atlas => !!atlas.textures[id]);
        return atlas ? atlas.textures[id] : null;
    },
    setup: function (animate) {
        const MovieClip = animate.MovieClip;
        const Container = animate.Container;
        const Graphics = animate.Graphics;

        data.lib.Graphic1 = class extends Container {
            constructor() {
                super();
                const instance1 = new Graphics()
                    .drawCommands(data.shapes.alpha[0]);
                this.addChild(instance1);
            }
        };

        data.lib.alpha = class extends MovieClip {
            constructor() {
                super({
                    duration: 1,
                    framerate: 24
                });
                const instance1 = new data.lib.Graphic1()
                    .setTransform(16, 16)
                    .setAlpha(0.3);
                this.addChild(instance1);
            }
        };

        data.stage = data.lib.alpha;
    }
};

module.exports = data;