text:
<?php

/**
 * Generates a new application.
 *
 * @package    symfony
 * @subpackage task
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfConfigureDatabaseTask extends sfBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('dsn', sfCommandArgument::REQUIRED, 'The database dsn'),
    ));

    $this->addOptions(array(
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_OPTIONAL, 'The environment', 'all'),
      new sfCommandOption('name', null, sfCommandOption::PARAMETER_OPTIONAL, 'The connection name', 'propel'),
      new sfCommandOption('class', null, sfCommandOption::PARAMETER_OPTIONAL, 'The database class name', 'sfPropelDatabase'),
      new sfCommandOption('app', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', null),
    ));

    $this->namespace = 'configure';
    $this->name = 'database';

    $this->briefDescription = 'Configure database DSN';

    $this->detailedDescription = <<<EOF
The [configure:database|INFO] task configures the database DSN
for a project:

  [./symfony configure:database mysql://root:mYsEcret@localhost/dbname|INFO]

By default, the task change the configuration for all environment. If you want
to change the dsn for a specific environment, use the [env|COMMENT] option:

  [./symfony configure:database --env=dev mysql://root@localhost/dbname_test|INFO]

To change the configuration for a specific application, use the [app|COMMENT] option:

  [./symfony configure:database --app=frontend mysql://root@localhost/dbname|INFO]

You can also specify the connection name and the database class name:

  [./symfony configure:database --name=main --class=sfDoctrineDatabase mysql://root@localhost/dbname|INFO]

WARNING: The [propel.ini|COMMENT] file is also updated when you use a [Propel|COMMENT] database
and configure for [all|COMMENT] environments with no [app|COMMENT].
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    // update databases.yml
    if (!is_null($options['app']))
    {
      $file = sfConfig::get('sf_apps_dir').'/'.$options['app'].'/config/databases.yml';
    }
    else
    {
      $file = sfConfig::get('sf_config_dir').'/databases.yml';
    }

    $config = file_exists($file) ? sfYaml::load($file) : array();

    $config[$options['env']][$options['name']] = array(
      'class' => $options['class'],
      'param' => array_merge(isset($config[$options['env']][$options['name']]['param']) ? $config[$options['env']][$options['name']]['param'] : array(), array('dsn' => $arguments['dsn'])),
    );

    file_put_contents($file, sfYaml::dump($config, 4));

    // update propel.ini
    if (
      is_null($options['app']) &&
      false !== strpos($options['class'], 'Propel') &&
      'all' == $options['env']
    )
    {
      $propelini = sfConfig::get('sf_config_dir').'/propel.ini';
      if (file_exists($propelini))
      {
        $content = file_get_contents($propelini);
        if (preg_match('/^(.+?):\/\//', $arguments['dsn'], $match))
        {
          $content = preg_replace('/^propel\.database(\s*)=(\s*)(.+?)$/m', 'propel.database$1=$2'.$match[1], $content);
          $content = preg_replace('/^propel\.database\.createUrl(\s*)=(\s*)(.+?)$/m', 'propel.database.createUrl$1=$2'.$arguments['dsn'], $content);
          $content = preg_replace('/^propel\.database\.url(\s*)=(\s*)(.+?)$/m', 'propel.database.url$1=$2'.$arguments['dsn'], $content);

          file_put_contents($propelini, $content);
        }
      }
    }
  }
}


text:
FROM nginx:alpine
MAINTAINER Konstantin Volodin, volodin.konstantin@gmail.com

COPY nginx.conf /etc/nginx

EXPOSE 80

ENTRYPOINT nginx -g "daemon off;"

redpajama_set_name: RedPajamaGithub


text:
redirect_to: '../../user/project/pipelines/job_artifacts.md'
---

This document was moved to [pipelines/job_artifacts.md](../../user/project/pipelines/job_artifacts.md).


text:
/* Global
--------------------------*/
body {
    background: #fff;
    margin: 0;
    padding: 0;
    color: #281f18;
}

html {
    height: 100%;
}
body {
    margin: 0;
    padding: 0;
    height: 100%;
}

body,h1,h2,h3,h4,h5,h6,p,ul,ol,dl,input,textarea {
    font-family: 'Myriad Pro', 'Myriad', helvetica, arial, sans-serif;
}

.wrapper {
    margin: 0 35px;
    min-width: 910px;
}

a:hover,a:active {
    color: #000;
}

a img {
    border: none;
}

a:active {
    outline: none;
}

/* Header
---------------------------*/
#page-header {
    background: #333;
    color: #fff;
    height: 30px;
    z-index: 99999;
    position: relative;
}

#page-header div.headermenu {
    height: 30px;
    padding-bottom: 0px;
    margin-bottom: 0px;
    padding-top: 0px;
    margin-top: 0px;
    line-height: 30px;
}

#page-header a:link,
#page-header a:visited {
    color: #fff;
    text-decoration: underline;
}

#newheader {
    height: 100px;
    position: relative;
}

#newheaderleft {
    height: 100px;
    width: 50px;
    position: absolute;
    left: -50px;
}

h1.headermain {
    margin-left: 0px;
    padding-left: 0px;
    color: #fff;
    margin-top: 35px;
    font-family: 'Myriad Pro', 'Myriad', helvetica, arial, sans-serif;
    text-shadow: 2px 3px 3px #292929;
    letter-spacing: -1px;
    -webkit-text-stroke: 1px white;
}

.headermenu .logininfo,
.headermenu .langmenu,
.headermenu .langmenu div,
.headermenu .langmenu form,
.headermenu .langmenu select,
.headermenu .langmenu label {
    display: inline !important;
}

.headermenu .logininfo {
    padding-right: 5px;
}

#region-main-box {
    background: #eee;
}

#region-post-box {
    background: #fff;
}

#page-footer {
    background: #333;
    color: #fff;
}

#page-content, #region-main-box, #region-main-wrap, #page-content-wrapper, #top, div.region-content {
    min-height: 100%;
    position: relative;
}

#region-main-box {
    -webkit-box-shadow: 6px 0px 8px #ccc;
    -moz-box-shadow: 6px 0px 8px #ccc;
    box-shadow: 6px 0px 8px #ccc;
 }

 #region-main {
    -webkit-box-shadow: 6px 0px 8px #ccc;
    -moz-box-shadow: 6px 0px 8px #ccc;
    box-shadow: 6px 0px 8px #ccc;
 }

.side-pre-only  #region-main, .content-only #region-main, .content-only #region-main-box  {
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
 }

/* Navbar
--------------------------*/
.navbar {
    margin-top: 10px;
}

.navbar .wrapper {
    margin-left: 0px !important;
    padding-left: 0px !important;
}

.breadcrumb .sep {
    color: #777;
    font-size: 0.8em;
}

.navbutton {
    margin-top: 40px;
    margin-right: 10px;
    font-size: 12px;
}

/* Blocks
---------------------------*/
.block {
    border: none;
    margin-bottom: 25px;
}

.block .header {
    border-bottom:none;
    text-transform: uppercase;
}

.block.hidden .header {
    border-top: 1px solid #dadada;
    border-bottom: 1px solid #dadada;
}
.block .title h2 {
    font-weight: normal;
    font-size: 1.1em;
    margin: 0;
}

.block .content {
    font-size: 0.95em;
}

.
/* Forums
---------------------------*/
.forumpost .subject {
    font-size: 1.2em;
}

.forumpost .author {
    font-size: 0.9em;
}

.forumpost .content {
    border-bottom:5px solid #aaa;
    padding:5px 7px 10px 7px;
}

.forumpost .topic {
    background: #eee;
    border-bottom: 1px solid #aaa;
}

/* Course
-------------------------------*/
.course-content .main {
    border: 1px solid #eee;
    background: #eee;
}

.course-content .current {
    background: #1f5480;
}

.course-content .current .left {
    background: #1f5480;
    color: #fff;
}

.course-content .main .content {
    background: #fff;
}

/* YUI Menu - custom menu
-------------------------------*/
#custommenu {
    width: 60%;
    float: left;
}

#custommenu .yui3-menu-label-active,
#custommenu .yui3-menu-label-menuvisible,
#custommenu .yui3-menu .yui3-menu .yui3-menu-label-active,
#custommenu .yui3-menu .yui3-menu .yui3-menu-label-menuvisible,
#custommenu .yui3-menuitem-active .yui3-menuitem-content,
#custommenu .yui3-menu .yui3-menu .yui3-menuitem-active .yui3-menuitem-content,
#custommenu .yui3-menu-horizontal.javascript-disabled li a:hover {
    background-color:#666;
}

#custommenu .yui3-menu-content,
#custommenu .yui3-menu .yui3-menu .yui3-menu-content {
    background-image:none;
    background-color:#333;
    border-width:0;
    padding:0;
}

#custommenu .yui3-menuitem-active .yui3-menuitem-content {
    background-image: none;
}

#custommenu .yui3-menu-label,
#custommenu .yui3-menu .yui3-menu .yui3-menu-label {
    background-image:url([[pix:theme|vertical-menu-submenu-indicator]]);
    background-position:right center;
    background-repeat:no-repeat;
}

#custommenu .yui3-menu-label.yui3-menu-label-menuvisible,
#custommenu .yui3-menu .yui3-menu .yui3-menu-label.yui3-menu-label-menuvisible {
    background-image:url([[pix:theme|horizontal-menu-submenu-indicator]]);
}

#custommenu .yui3-menu-horizontal .yui3-menu-label,
#custommenu .yui3-menu-horizontal .yui3-menuitem-content {
    border-width:0;
    text-transform: uppercase;
    text-decoration:none;
    font-size:1em;
    font-weight: 200;
    line-height:30px;
    cursor: pointer;
    padding:0 20px;
}

#custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content,
#custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content .ul {
    border-width:0;
}

#custommenu .yui3-menu-horizontal.javascript-disabled li a {
    padding: 0 20px;
    display: block;
}

/** Dock **/
#dock .firstdockitem {margin-top: 30px;}

/* Moodle forms
----------------*/
.mform .btn-cancel {
    color: #428AB5;
    text-decoration: none;
}
.mform .btn-cancel:hover, .mform .btn-cancel:focus {
    color: #428AB5;
    text-decoration: none;
}


text:
from saml2 import BINDING_SOAP
from saml2.samlp import NewID
from saml2.saml import NameID, NAMEID_FORMAT_TRANSIENT
from saml2.client import Saml2Client
from saml2.server import Server

__author__ = 'rolandh'

def test_basic():
    sp = Saml2Client(config_file="servera_conf")
    idp = Server(config_file="idp_all_conf")

    # -------- @SP ------------
    binding, destination = sp.pick_binding("manage_name_id_service",
                                           entity_id=idp.config.entityid)

    nameid = NameID(format=NAMEID_FORMAT_TRANSIENT, text="foobar")
    newid = NewID(text="Barfoo")

    mid = sp.create_manage_name_id_request(destination, name_id=nameid,
                                           new_id=newid)

    print mid
    rargs = sp.apply_binding(binding, "%s" % mid, destination, "")

    # --------- @IDP --------------

    _req = idp.parse_manage_name_id_request(rargs["data"], binding)

    print _req.message

    assert mid.id == _req.message.id

def test_flow():
    sp = Saml2Client(config_file="servera_conf")
    idp = Server(config_file="idp_all_conf")

    binding, destination = sp.pick_binding("manage_name_id_service",
                                           entity_id=idp.config.entityid)

    nameid = NameID(format=NAMEID_FORMAT_TRANSIENT, text="foobar")
    newid = NewID(text="Barfoo")

    mid = sp.create_manage_name_id_request(destination, name_id=nameid,
                                           new_id=newid)

    print mid
    rargs = sp.apply_binding(binding, "%s" % mid, destination, "")

    # --------- @IDP --------------

    _req = idp.parse_manage_name_id_request(rargs["data"], binding)

    print _req.message

    mnir = idp.create_manage_name_id_response(_req.message, None)

    if binding != BINDING_SOAP:
        binding, destination = idp.pick_binding("manage_name_id_service",
                                                entity_id=sp.config.entityid)
    else:
        destination = ""

    respargs = idp.apply_binding(binding, "%s" % mnir, destination, "")

    print respargs

    # ---------- @SP ---------------

    _response = sp.parse_manage_name_id_request_response(respargs["data"], binding)

    print _response.response

    assert _response.response.id == mnir.id


text:
#pragma once

#include <functional>
#include <map>
#include <vector>

#include "accelerator/bvh.h"
#include "accelerator/bvh_node.h"
#include "scene/hitable.h"

namespace aten {
    /**
     * @brief Return the root of the nested tree which the specified node has.
     */
    inline bvhnode* getNestedNode(bvhnode* node)
    {
        bvhnode* ret = nullptr;

        if (node) {
            auto item = node->getItem();
            if (item) {
                auto internalObj = const_cast<hitable*>(item->getHasObject());
                if (internalObj) {
                    auto accel = internalObj->getInternalAccelerator();

                    // NOTE
                    // 本来ならこのキャストは不正だが、BVHであることは自明なので.
                    auto bvh = *reinterpret_cast<aten::bvh**>(&accel);

                    ret = bvh->getRoot();
                }
            }

            if (!ret) {
                ret = node;
            }
        }

        return ret;
    }

    /**
     * @brief Convert the tree to the linear list.
     */
    template <typename _T>
    void registerBvhNodeToLinearListRecursively(
        aten::bvhnode* root,
        aten::bvhnode* parentNode,
        aten::hitable* nestParent,
        const aten::mat4& mtxL2W,
        std::vector<_T>& listBvhNode,
        std::vector<aten::accelerator*>& listBvh,
        std::map<hitable*, aten::accelerator*>& nestedBvhMap,
        std::function<void(std::vector<_T>&, aten::bvhnode*, aten::hitable*, const aten::mat4&)> funcRegisterToList,
        std::function<void(aten::bvhnode*, int, int)> funcIfInstanceNode)
    {
        if (!root) {
            return;
        }

        auto pnode = root;

        auto original = pnode;

        // ネストしている場合にはネストさきのツリーのルートノードを取得.
        // ネストしていない場合は同じものが返ってくる.
        pnode = getNestedNode(original);

        if (pnode != original) {
            // ネストしている.
            {
                original->setParent(parentNode);
                original->setTraversalOrder((int)listBvhNode.size());
                funcRegisterToList(listBvhNode, original, nestParent, mtxL2W);
            }

            // Register nested bvh.
            aten::hitable* originalItem = original->getItem();
            AT_ASSERT(originalItem->isInstance());

            // Register relation between instance and nested bvh.
            auto internalItem = const_cast<hitable*>(originalItem->getHasObject());
            auto internalSecondItem = const_cast<hitable*>(originalItem->getHasSecondObject());

            hitable* items[] = {
                internalItem,
                internalSecondItem,
            };

            int exids[2] = { -1, -1 };

            for (int i = 0; i < AT_COUNTOF(items); i++) {
                auto item = items[i];

                if (item == nullptr) {
                    break;
                }

                // TODO
                auto obj = (AT_NAME::object*)item;

                auto nestedBvh = obj->getInternalAccelerator();

                auto found = std::find(listBvh.begin(), listBvh.end(), nestedBvh);
                if (found == listBvh.end()) {
                    listBvh.push_back(nestedBvh);

                    int exid = (int)listBvh.size() - 1;
                    AT_ASSERT(exid >= 0);

                    exids[i] = exid;
                }

                if (i == 0) {
                    if (nestedBvh) {
                        nestedBvhMap.insert(std::pair<aten::hitable*, aten::accelerator*>(originalItem, nestedBvh));
                    }
                }
            }

            if (funcIfInstanceNode) {
                funcIfInstanceNode(original, exids[0], exids[1]);
            }
        }
        else {
            pnode->setParent(parentNode);
            pnode->setTraversalOrder((int)listBvhNode.size());
            funcRegisterToList(listBvhNode, pnode, nestParent, mtxL2W);

            aten::bvhnode* pleft = pnode->getLeft();
            aten::bvhnode* pright = pnode->getRight();

            registerBvhNodeToLinearListRecursively(
                pleft, pnode, nestParent, mtxL2W, listBvhNode, listBvh, nestedBvhMap, funcRegisterToList, funcIfInstanceNode);
            registerBvhNodeToLinearListRecursively(
                pright, pnode, nestParent, mtxL2W, listBvhNode, listBvh, nestedBvhMap, funcRegisterToList, funcIfInstanceNode);
        }
    }
}


text:
package com.wingjay.jianshi.sync;

public class LocalUpdater {

  public static void updateDiary() {

  }
}


text:
// based on
// https://github.com/PurpleI2P/i2pd/blob/master/Win32/Win32NetState.cpp

#include "include/connectivity_plus/network_manager.h"

#include <iphlpapi.h>
#include <netlistmgr.h>
#include <ocidl.h>

#include <cassert>
#include <set>

class NetworkListener final : public INetworkEvents {
public:
  NetworkListener(NetworkCallback pCb) : pCallback(pCb) {}

  HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) {
    AddRef();

    HRESULT hr = S_OK;
    if (IsEqualIID(riid, IID_IUnknown)) {
      *ppvObject = (IUnknown *)this;
    } else if (IsEqualIID(riid, IID_INetworkEvents)) {
      *ppvObject = (INetworkEvents *)this;
    } else {
      hr = E_NOINTERFACE;
    }
    return hr;
  }

  ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&lRef); }

  ULONG STDMETHODCALLTYPE Release() {
    LONG lAddend = InterlockedDecrement(&lRef);
    if (lRef == 0) {
      delete this;
    }
    return lAddend;
  }

  HRESULT STDMETHODCALLTYPE NetworkAdded(GUID networkId) { return S_OK; }

  HRESULT STDMETHODCALLTYPE
  NetworkConnectivityChanged(GUID networkId, NLM_CONNECTIVITY newConnectivity) {
    Callback();
    return S_OK;
  }

  HRESULT STDMETHODCALLTYPE NetworkDeleted(GUID networkId) { return S_OK; }

  HRESULT STDMETHODCALLTYPE
  NetworkPropertyChanged(GUID networkId, NLM_NETWORK_PROPERTY_CHANGE flags) {
    if (flags & NLM_NETWORK_PROPERTY_CHANGE_CONNECTION) {
      Callback();
    }
    return S_OK;
  }

  void Callback() {
    assert(pCallback);
    pCallback();
  }

private:
  volatile LONG lRef = 1;
  NetworkCallback pCallback = nullptr;
};

NetworkManager::NetworkManager() {}

NetworkManager::~NetworkManager() {
  StopListen();
  Cleanup();
}

bool NetworkManager::Init() {
  CoInitialize(NULL);

  HRESULT hr = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
                                IID_IUnknown, (void **)&pUnknown);
  if (SUCCEEDED(hr)) {
    hr = pUnknown->QueryInterface(IID_INetworkListManager,
                                  (void **)&pNetworkListManager);
  }
  return SUCCEEDED(hr);
}

void NetworkManager::Cleanup() {
  if (pNetworkListManager) {
    pNetworkListManager->Release();
    pNetworkListManager = NULL;
  }

  if (pUnknown) {
    pUnknown->Release();
    pUnknown = NULL;
  }

  CoUninitialize();
}

std::vector<GUID> NetworkManager::GetConnectedAdapterIds() const {
  std::vector<GUID> adapterIds;

  IEnumNetworkConnections *connections = NULL;
  HRESULT hr = pNetworkListManager->GetNetworkConnections(&connections);
  if (hr == S_OK) {
    while (true) {
      INetworkConnection *connection = NULL;
      hr = connections->Next(1, &connection, NULL);
      if (hr != S_OK) {
        break;
      }

      VARIANT_BOOL isConnected = VARIANT_FALSE;
      hr = connection->get_IsConnectedToInternet(&isConnected);
      if (hr == S_OK && isConnected == VARIANT_TRUE) {
        GUID guid;
        hr = connection->GetAdapterId(&guid);
        if (hr == S_OK) {
          adapterIds.push_back(std::move(guid));
        }
      }
      connection->Release();
    }
    connections->Release();
  }

  return adapterIds;
}

ConnectivityType NetworkManager::GetConnectivityType() const {
  ULONG bufferSize = 15 * 1024;
  ULONG flags = GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST |
                GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER |
                GAA_FLAG_SKIP_FRIENDLY_NAME;
  std::vector<unsigned char> buffer(bufferSize);
  PIP_ADAPTER_ADDRESSES addresses =
      reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer.front());
  DWORD rc = GetAdaptersAddresses(AF_UNSPEC, flags, 0, addresses, &bufferSize);
  if (rc == ERROR_BUFFER_OVERFLOW) {
    buffer.resize(bufferSize);
    addresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer.front());
    rc = GetAdaptersAddresses(AF_UNSPEC, flags, 0, addresses, &bufferSize);
  }

  if (rc != NO_ERROR) {
    return ConnectivityType::None;
  }

  std::vector<GUID> adapterIds = GetConnectedAdapterIds();
  if (adapterIds.empty()) {
    return ConnectivityType::None;
  }

  std::set<ConnectivityType> connectivities;
  for (; addresses != NULL; addresses = addresses->Next) {
    NET_LUID luid;
    rc = ConvertInterfaceIndexToLuid(addresses->IfIndex, &luid);
    if (rc != NO_ERROR) {
      continue;
    }

    GUID guid;
    rc = ConvertInterfaceLuidToGuid(&luid, &guid);
    if (rc != NO_ERROR) {
      continue;
    }

    if (std::find(adapterIds.begin(), adapterIds.end(), guid) !=
        adapterIds.end()) {
      switch (addresses->IfType) {
      case IF_TYPE_ETHERNET_CSMACD:
        connectivities.insert(ConnectivityType::Ethernet);
        break;
      default:
        connectivities.insert(ConnectivityType::WiFi);
        break;
      }
    }
  }

  if (connectivities.find(ConnectivityType::WiFi) != connectivities.end()) {
    return ConnectivityType::WiFi;
  }

  if (connectivities.find(ConnectivityType::Ethernet) != connectivities.end()) {
    return ConnectivityType::Ethernet;
  }

  return ConnectivityType::None;
}

bool NetworkManager::StartListen(NetworkCallback pCallback) {
  if (!pCallback || pListener) {
    return false;
  }

  HRESULT hr = pNetworkListManager->QueryInterface(
      IID_IConnectionPointContainer, (void **)&pCPContainer);
  if (SUCCEEDED(hr)) {
    hr = pCPContainer->FindConnectionPoint(IID_INetworkEvents, &pConnectPoint);
    if (SUCCEEDED(hr)) {
      pListener = new NetworkListener(pCallback);
      hr = pConnectPoint->Advise((IUnknown *)pListener, &dwCookie);
      if (SUCCEEDED(hr)) {
        return true;
      }
    }
  }
  return false;
}

void NetworkManager::StopListen() {
  if (pConnectPoint) {
    pConnectPoint->Unadvise(dwCookie);
    pConnectPoint->Release();
    pConnectPoint = NULL;
    dwCookie = 0;
  }

  if (pCPContainer) {
    pCPContainer->Release();
    pCPContainer = NULL;
  }

  if (pListener) {
    pListener->Release();
    pListener = NULL;
  }
}

bool NetworkManager::HasError() const { return GetLastError() != 0; }

int NetworkManager::GetError() const { return GetLastError(); }


text:
namespace Yeast.Modules
{
    public static class ModuleLoaderExtensions
    {
        /// <summary>
        /// Tests if a module was loaded
        /// </summary>
        /// <param name="moduleName">Module name to test</param>
        /// <returns>True if module was loaded, otherwise False</returns>
        public static bool IsLoaded(this IModuleLoader moduleLoader, string moduleName)
        {
            return moduleLoader.GetLoadedModuleByName(moduleName) != null;
        }

    }
}


text:
**RegNetX** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear parameterisation of block widths (the design space only contains models with this linear structure):

$$ u\_{j} = w\_{0} + w\_{a}\cdot{j} $$

For **RegNetX** we have additional restrictions: we set $b = 1$ (the bottleneck ratio), $12 \leq d \leq 28$, and $w\_{m} \geq 2$ (the width multiplier).

{% include 'code_snippets.md' %}

## How do I train this model?

You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.

## Citation

```BibTeX
@misc{radosavovic2020designing,
      title={Designing Network Design Spaces},
      author={Ilija Radosavovic and Raj Prateek Kosaraju and Ross Girshick and Kaiming He and Piotr Dollár},
      year={2020},
      eprint={2003.13678},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}
```

<!--
Type: model-index
Collections:
- Name: RegNetX
  Paper:
    Title: Designing Network Design Spaces
    URL: https://paperswithcode.com/paper/designing-network-design-spaces
Models:
- Name: regnetx_002
  In Collection: RegNetX
  Metadata:
    FLOPs: 255276032
    Parameters: 2680000
    File Size: 10862199
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_002
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 1024
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L337
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_002-e7e85e5c.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 68.75%
      Top 5 Accuracy: 88.56%
- Name: regnetx_004
  In Collection: RegNetX
  Metadata:
    FLOPs: 510619136
    Parameters: 5160000
    File Size: 20841309
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_004
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 1024
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L343
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_004-7d0e9424.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 72.39%
      Top 5 Accuracy: 90.82%
- Name: regnetx_006
  In Collection: RegNetX
  Metadata:
    FLOPs: 771659136
    Parameters: 6200000
    File Size: 24965172
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_006
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 1024
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L349
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_006-85ec1baa.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 73.84%
      Top 5 Accuracy: 91.68%
- Name: regnetx_008
  In Collection: RegNetX
  Metadata:
    FLOPs: 1027038208
    Parameters: 7260000
    File Size: 29235944
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_008
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 1024
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L355
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_008-d8b470eb.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 75.05%
      Top 5 Accuracy: 92.34%
- Name: regnetx_016
  In Collection: RegNetX
  Metadata:
    FLOPs: 2059337856
    Parameters: 9190000
    File Size: 36988158
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_016
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 1024
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L361
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_016-65ca972a.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 76.95%
      Top 5 Accuracy: 93.43%
- Name: regnetx_032
  In Collection: RegNetX
  Metadata:
    FLOPs: 4082555904
    Parameters: 15300000
    File Size: 61509573
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_032
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L367
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_032-ed0c7f7e.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 78.15%
      Top 5 Accuracy: 94.09%
- Name: regnetx_040
  In Collection: RegNetX
  Metadata:
    FLOPs: 5095167744
    Parameters: 22120000
    File Size: 88844824
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_040
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L373
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_040-73c2a654.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 78.48%
      Top 5 Accuracy: 94.25%
- Name: regnetx_064
  In Collection: RegNetX
  Metadata:
    FLOPs: 8303405824
    Parameters: 26210000
    File Size: 105184854
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_064
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L379
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_064-29278baa.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 79.06%
      Top 5 Accuracy: 94.47%
- Name: regnetx_080
  In Collection: RegNetX
  Metadata:
    FLOPs: 10276726784
    Parameters: 39570000
    File Size: 158720042
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_080
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L385
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_080-7c7fcab1.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 79.21%
      Top 5 Accuracy: 94.55%
- Name: regnetx_120
  In Collection: RegNetX
  Metadata:
    FLOPs: 15536378368
    Parameters: 46110000
    File Size: 184866342
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_120
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L391
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_120-65d5521e.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 79.61%
      Top 5 Accuracy: 94.73%
- Name: regnetx_160
  In Collection: RegNetX
  Metadata:
    FLOPs: 20491740672
    Parameters: 54280000
    File Size: 217623862
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_160
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 512
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L397
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_160-c98c4112.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 79.84%
      Top 5 Accuracy: 94.82%
- Name: regnetx_320
  In Collection: RegNetX
  Metadata:
    FLOPs: 40798958592
    Parameters: 107810000
    File Size: 431962133
    Architecture:
    - 1x1 Convolution
    - Batch Normalization
    - Convolution
    - Dense Connections
    - Global Average Pooling
    - Grouped Convolution
    - ReLU
    Tasks:
    - Image Classification
    Training Techniques:
    - SGD with Momentum
    - Weight Decay
    Training Data:
    - ImageNet
    Training Resources: 8x NVIDIA V100 GPUs
    ID: regnetx_320
    Epochs: 100
    Crop Pct: '0.875'
    Momentum: 0.9
    Batch Size: 256
    Image Size: '224'
    Weight Decay: 5.0e-05
    Interpolation: bicubic
  Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/regnet.py#L403
  Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-regnet/regnetx_320-8ea38b93.pth
  Results:
  - Task: Image Classification
    Dataset: ImageNet
    Metrics:
      Top 1 Accuracy: 80.25%
      Top 5 Accuracy: 95.03%
-->


text:
import os
from collections import defaultdict
import logging

from peyutil import StringIO

from taxalotl.ott_schema import (read_taxonomy_to_get_single_taxon,
                                 )
from taxalotl.cmds.partitions import (fill_empty_anc_of_mapping,
                                      MISC_DIRNAME,
                                      PREORDER_PART_LIST,
                                      NAME_TO_PARTS_SUBSETS)
from taxalotl.resource_wrapper import ResourceWrapper, TaxonomyWrapper
from taxalotl.tax_partition import (get_roots_for_subset, )
from taxalotl.util import get_true_false_repsonse

_LOG = logging.getLogger(__name__)

OTT_PARTMAP = {
    'Archaea': frozenset([996421]),
    'Bacteria': frozenset([844192]),
    'Eukaryota': frozenset([304358]),
    'SAR': frozenset([5246039]),
    'Haptophyta': frozenset([151014]),
    'Rhodophyta': frozenset([878953]),
    'Archaeplastida': frozenset([5268475]),
    'Glaucophyta': frozenset([664970]),
    'Chloroplastida': frozenset([361838]),
    'Fungi': frozenset([352914]),
    'Metazoa': frozenset([691846]),
    'Annelida': frozenset([941620]),
    'Arthropoda': frozenset([632179]),
    'Malacostraca': frozenset([212701]),
    'Arachnida': frozenset([511967]),
    'Insecta': frozenset([1062253]),
    'Diptera': frozenset([661378]),
    'Coleoptera': frozenset([865243]),
    'Lepidoptera': frozenset([965954]),
    'Hymenoptera': frozenset([753726]),
    'Bryozoa': frozenset([442934]),
    'Chordata': frozenset([125642]),
    'Cnidaria': frozenset([641033]),
    'Ctenophora': frozenset([641212]),
    'Mollusca': frozenset([802117]),
    'Nematoda': frozenset([395057]),
    'Platyhelminthes': frozenset([555379]),
    'Porifera': frozenset([67819]),
    'Viruses': frozenset([4807313]),
}

# Unused separation taxa: cellular organisms	93302

OTT_3_SEPARATION_TAXA = OTT_PARTMAP

def ott_fetch_root_taxon_for_partition(res, parts_key, root_id):
    tax_dir = res.get_taxdir_for_root_of_part(parts_key)
    if not tax_dir:
        _LOG.info('No taxon file found for {}'.format(parts_key))
        return None
    # _LOG.info('{} root should be in {}'.format(parts_key, tax_dir))
    taxon_obj = read_taxonomy_to_get_single_taxon(tax_dir, root_id)
    if not tax_dir:
        _LOG.info(
            'Root taxon for {} with ID {} not found in {}'.format(parts_key, root_id, tax_dir))
        return None
    return taxon_obj

def ott_build_paritition_maps(res):
    # srcs = {i[0]:i[1] for i in res.inputs if i[0] and is_str_type(i[1])}
    src_pre_to_map = {}
    all_part_keys = set()
    for part_key in PREORDER_PART_LIST:
        if part_key != 'Life':
            all_part_keys.add(part_key)
        all_part_keys.update(NAME_TO_PARTS_SUBSETS[part_key])
    for pk in all_part_keys:
        if pk == MISC_DIRNAME:
            continue
        tax_dir = res.get_taxdir_for_part(pk)
        roots = get_roots_for_subset(tax_dir, res.get_misc_taxon_dir_for_part(pk))
        _LOG.info("{} -> {} roots = {}".format(pk, tax_dir, roots))
        if not roots:
            continue
        assert len(roots) == 1
        root_id, taxon = roots.popitem()
        _LOG.info('root for {} has sources: {}'.format(pk, taxon.src_dict))
        for src_pre, src_ids in taxon.src_dict.items():
            src_pre_to_map.setdefault(src_pre, {})[pk] = src_ids
    import copy
    filled = {}
    for src_pre, mapping in src_pre_to_map.items():
        pm = copy.deepcopy(mapping)
        fill_empty_anc_of_mapping(mapping)
        filled[src_pre] = {k: list(v) for k, v in mapping.items()}
        for k, v in mapping.items():
            pv = pm.get(k)
            if pv is None:
                _LOG.info("{}: {} -> (None -> {})".format(src_pre, k, v))
            else:
                assert v == pv
    # @TODO: hard copying the fact that OTT was built with SILVA-115
    if 'silva' in filled:
        filled['silva_115'] = filled['silva']
        del filled['silva']
    # @TODO: make this automatic not generic
    gbif = filled['gbif']
    assert "Chloroplastida" not in gbif
    gbif["Chloroplastida"] = [13, 9, 7707728, 7819616, 36, 35]

    return filled

UNSTABLE_SRC_PREFIXES = frozenset(['h2007', 'study713', 'https', 'http'])

class NewSeparator(object):
    def __init__(self, ott_taxon_obj):
        self.taxon = ott_taxon_obj
        self.sub_separators = {}

    def __str__(self):
        out = StringIO()
        self.write_str(out)
        return out.getvalue()

    def write_str(self, out, pref=''):
        t = self.taxon
        if pref:
            pref = pref + '/'
        out.write('{}{} ott{} sources={}\n'.format(pref,
                                                   t.name_that_is_unique,
                                                   t.id,
                                                   t.src_dict))
        for name, sep in self.sub_separators.items():
            if pref:
                ns = pref + name
            else:
                ns = name
            sep.write_str(out, ns)

    def as_dict(self):
        d = {"name": self.taxon.name, "uniqname": self.taxon.name_that_is_unique}
        sd = {}
        for k, v in self.taxon.src_dict.items():
            vl = list(v)
            vl.sort()
            sd[k] = vl
        d["src_dict"] = sd
        s = {}
        for v in self.sub_separators.values():
            s[v.taxon.id] = v.as_dict()
        if s:
            d["sub"] = s
        return d

    def num_sub_separators(self):
        n = 0
        for el in self.sub_separators.values():
            n += 1 + el.num_sub_separators()
        return n

class NestedNewSeparator(object):
    def __init__(self):
        self.separators = {}

    def __bool__(self):
        return bool(self.separators)

    def add_separtors_for_tree(self, tree, sep_ids):
        self._add_separtors_for_descendants(tree.root, sep_ids, self.separators)

    def _add_separtors_for_descendants(self, nd, sep_ids, par_dict):
        child_refs = nd.children_refs
        if not child_refs:
            return
        for child in child_refs:
            if child.id in sep_ids:
                if nd.id in sep_ids and len(child_refs) == 1:
                    # suppress monotypic separators children as separators
                    self._add_separtors_for_descendants(child, sep_ids, par_dict)
                else:
                    ns = NewSeparator(child)
                    par_dict[child.id] = ns
                    self._add_separtors_for_descendants(child, sep_ids, ns.sub_separators)
            else:
                self._add_separtors_for_descendants(child, sep_ids, par_dict)

    def __str__(self):
        out = StringIO()
        for name, sep in self.separators.items():
            out.write('top-level name={}\n'.format(name))
            sep.write_str(out)
        return out.getvalue()

    def as_dict(self):
        d = {}
        for el in self.separators.values():
            d[el.taxon.id] = el.as_dict()
        return d

    def num_separators(self):
        n = 0
        for el in self.separators.values():
            n += 1 + el.num_sub_separators()
        return n

def _add_nst_subtree_el_to_dict(rd, nst_el, par_to_child):
    sep_taxon, children = nst_el
    if sep_taxon is not None:
        nst = NewSeparator(sep_taxon)
        nd = nst.sub_separators
        rd[sep_taxon.name_that_is_unique] = nst
    else:
        nd = rd
    for c in children:
        next_el = par_to_child[c]
        _add_nst_subtree_el_to_dict(nd, next_el, par_to_child)

NON_SEP_RANKS = frozenset(['forma', 'no rank - terminal', 'species',
                           'species group', 'species subgroup', 'varietas', 'variety', ])
MIN_SEP_SIZE = 20

def get_stable_source_keys(taxon):
    all_src_keys = taxon.src_dict.keys()
    filtered = [i for i in all_src_keys if not i.startswith('additions')]
    r = [i for i in filtered if i not in UNSTABLE_SRC_PREFIXES]
    r.sort()
    return r

def _diagnose_relevant_sources(tree):
    source_to_count = defaultdict(int)
    leaf_set = set()
    src_prefix_set = set()
    for v in tree.id_to_taxon.values():
        if v.children_refs is None:
            leaf_set.add(v.id)
        filtered = get_stable_source_keys(v)
        src_prefix_set.update(filtered)
        for src in filtered:
            source_to_count[src] += 1
    # We'll define a "minor" source as one that is found in 5000 fold fewer taxa as
    #   the most common source for a slice. This is arbitrary.
    FOLD_DIFF = 5000
    max_seen = max(source_to_count.values())
    min_cutoff = 0 if max_seen < FOLD_DIFF else max_seen // FOLD_DIFF
    ac_src = [k for k, v in source_to_count.items() if v >= min_cutoff]
    ac_src.sort()
    _LOG.info("Relevant sources appear to be: {}".format(ac_src))
    return frozenset(ac_src)

DEFAULT_REL_SRC_SET = frozenset(['gbif', 'irmng', 'ncbi', 'worms'])
NO_WORMS_REL_SRC_SET = frozenset(['gbif', 'irmng', 'ncbi'])
SILVA_NOT_WORMS_REL_SRC_SET = frozenset(['gbif', 'irmng', 'ncbi', 'silva'])
PART_KEY_TO_REL_SRC_SET = {'Insecta': NO_WORMS_REL_SRC_SET,
                           'Hymenoptera': NO_WORMS_REL_SRC_SET,
                           'Diptera': NO_WORMS_REL_SRC_SET,
                           'Coleoptera': NO_WORMS_REL_SRC_SET,
                           'Lepidoptera': NO_WORMS_REL_SRC_SET,
                           'Chordata': NO_WORMS_REL_SRC_SET,
                           'Fungi': NO_WORMS_REL_SRC_SET,
                           'Bacteria': SILVA_NOT_WORMS_REL_SRC_SET,
                           'Archaea': SILVA_NOT_WORMS_REL_SRC_SET,
                           }

def add_confirmed_sep(nns, tree, list_num_id_taxon, sep_name):
    if list_num_id_taxon:
        r = tree.root
        m = 'The current partition subtree "{}" has {} tips below it.'
        _LOG.info(m.format(r.name_that_is_unique, r.num_tips_below))
    top_sep_set = set()
    for nt, i, obj in list_num_id_taxon:
        if top_sep_set:
            already_sep = False
            for anc_obj in tree.to_root_gen(obj):
                if anc_obj.id in top_sep_set:
                    already_sep = True
                    break
            if already_sep:
                continue
        if sep_name is None:
            m = '"{}" has {} tips below it.'.format(obj.name_that_is_unique, nt)
            p = '{} Enter (y) to treat is a separator: '.format(m)
            if get_true_false_repsonse(p, def_value=True):
                top_sep_set.add(i)
        else:
            top_sep_set.add(i)
    if top_sep_set:
        nns.add_separtors_for_tree(tree, top_sep_set)

_skip_semanticizing_set = frozenset(['not_otu', 'was_container', 'barren'])

# noinspection PyAbstractClass
class OTTaxonomyWrapper(TaxonomyWrapper):
    resource_type = 'open tree taxonomy'
    schema = {'ott'}

    def __init__(self, obj, parent=None, refs=None):
        TaxonomyWrapper.__init__(self, obj, parent=parent, refs=refs)

    def node_should_be_semanticized(self, node):
        if node.flags and _skip_semanticizing_set.intersection(node.flags):
            return False
        return super(OTTaxonomyWrapper, self).node_should_be_semanticized(node)

    def get_source_for_sep_or_part(self, current_partition_key):
        try:
            return PART_KEY_TO_REL_SRC_SET.get(current_partition_key, DEFAULT_REL_SRC_SET)
        except:
            dn = self.config.get_fragment_from_part_name(current_partition_key)
            higher = os.path.split(os.path.split(dn)[0])[-1]
            if higher.lower() == 'life':
                raise ValueError('partition/separator name "{}" not found'.format(current_partition_key))
            return self.get_source_for_sep_or_part(higher)

    def diagnose_new_separators(self, current_partition_key, sep_name):
        tax_forest = self.get_taxon_forest_for_partition(current_partition_key)
        nns = NestedNewSeparator()
        if sep_name is None:
            lsn, lsep = 0, None
        else:
            lsn, lsep = len(sep_name), sep_name.lower()
        if tax_forest:
            try:
                ac_src = self.get_source_for_sep_or_part(current_partition_key)
            except:
                m = 'Might try calling _diagnose_relevant_sources for "{}", but in Jan 2019 moved to ' \
                    'making this hard coded in PART_KEY_TO_REL_SRC_SET.'
                raise NotImplementedError(m.format(current_partition_key))
            _LOG.info("Relevant sources for {} are recorded as to be: {}. size = {}".format(current_partition_key,
                                                                                ac_src, len(ac_src)))
            for tree in tax_forest.trees:
                tree.add_num_tips_below()
                assert ac_src
                nst = []
                for i, obj in tree.id_to_taxon.items():
                    if obj is tree.root:
                        continue  # no point in partitioning at the root taxon
                    if not obj.children_refs:
                        continue  # no point in partitioning leaves...
                    if sep_name is not None:
                        obn, obun = obj.name, obj.uniqname
                        if (obn and (len(obn) == lsn and obn.lower() == lsep)) \
                                or (obun and (len(obun) == lsn and obun.lower() == lsep)):
                            nst.append((obj.num_tips_below, i, obj))
                            break
                    else:
                        sk_for_obj = set(get_stable_source_keys(obj))
                        if sk_for_obj.issuperset(ac_src):
                            if obj.num_tips_below >= MIN_SEP_SIZE:
                                if not obj.rank or (obj.rank not in NON_SEP_RANKS):
                                    nst.append((obj.num_tips_below, i, obj))
                nst.sort(reverse=True)
                add_confirmed_sep(nns, tree, nst, sep_name)
        if len(nns.separators) == 0:
            _LOG.info('No new separators found for "{}"'.format(current_partition_key))
            return None
        rel_dir_for_part = self.config.get_fragment_from_part_name(current_partition_key)
        return {rel_dir_for_part: nns}

    def build_paritition_maps(self):
        return ott_build_paritition_maps(self)

    def get_primary_partition_map(self):
        return OTT_PARTMAP

    def input_dict(self):
        d = {}
        for k, v in self.inputs:
            d[k] = v
        return d

# noinspection PyAbstractClass
class OTTaxonomyIdListWrapper(ResourceWrapper):
    resource_type = 'open tree taxonomy idlist'
    schema = {resource_type, 'ott id csv'}
    _norm_filename = 'by_qid.csv'

    def __init__(self, obj, parent=None, refs=None):
        ResourceWrapper.__init__(self, obj, parent=parent, refs=refs)


text:
package com.asksunny.validator;

public class InvalidObjectTypeException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public InvalidObjectTypeException(String types) {
		super(String.format("Only the following types are supported[%s]", types));
	}

}


text:
<?php

use utilities\Metadata_json as Metadata_json;
use utilities\Metadata_sqlite as Metadata_sqlite;

interface MetadataInterface {
	public static function hasMetadataFile($path, $filename);
}

abstract class Metadata
{
	const TYPE_SQLITE = 'sqlite';
	const TYPE_JSON = 'json';

	public $path;
	public $filename;

	function __construct($fullpath)
	{
		$this->path = dirname($fullpath);
		$this->filename = basename($fullpath);
		is_dir($this->path) || die("Unable to find directory for " . $this->path);
	}

	public static function forDirectory($fullpath, $type = Metadata::TYPE_JSON)
	{
		return Metadata::forDirectoryAndFile( $fullpath, null, $type );
	}

	public static function forDirectoryAndFile($path, $filename = null, $type = Metadata::TYPE_JSON)
	{
		$j_file = (is_null($filename) ? Metadata_json::DefaultFilename : $filename);
		$s_file = (is_null($filename) ? Metadata_sqlite::DefaultFilename : $filename);

		// always use existing metadata
		if ( Metadata_json::hasMetadataFile( $path, $j_file) == true ) {
			return new Metadata_json( appendPath($path, $j_file));
		}
		else if (Metadata_sqlite::hasMetadataFile( $path, $s_file ) == true ) {
			return new Metadata_sqlite( appendPath($path, $s_file));
		}

		if ( $type === Metadata::TYPE_JSON ) {
			return new Metadata_json( appendPath($path, $j_file));
		}

		return new Metadata_sqlite( appendPath($path, $s_file));
	}

	public function fullpath() {
		return appendPath($this->path, $this->filename);
	}

	public function deleteMetadataFile() {
		return safe_unlink(appendPath($this->path, $this->filename));
	}

	public function isMeta($key)
	{
		$test = $this->getMeta($key);
		return (is_null($test) == false);
	}

	/**
	 * Counts the number of entries for 'key' or if null the total top level keys
	 * @param mixed $key
	 */
	public abstract function metaCount($key = null);

	/**
	 * sets a specific value to a specific key of the session
	 * @param mixed $key
	 * @param mixed $value
	 */
	public abstract function setMeta($key, $value);

	/**
	 * gets/returns the value of a specific key of the metadata
	 * @param mixed $key Usually a string, path may be separated using '/', so 'source/subkey/itemkey'
	 * @return mixed
	 */
	public abstract function getMeta($key, $default = null);
}

?>


text:
layout: page
title: About Me
permalink: /me/
---

I help craft and bootstrap ideas with pragmatic user experience, technology feasibility and business model viability toward larger societal impacts.

Bring agility, integrative thinking and collaborative mindset to intuit trends, latent needs, and anticipate future.

Proficient in design thinking, data visualisation and rapid prototyping.

## Recognitions
As member of R&D organisations, we put relentless pursuit of innovation. Following are notable initiatives that demonstrate our contributions toward Business and Social Value Creation Principles.

**Awards**

<time datetime="">2019</time>

NEC APAC Innovation Award for Project Ally

NEC APAC Innovation Award for Asian Transportation Society Best Paper & Presentation

<time datetime="">2018</time>

NEC Corporation Certificate of Achievements Award on Creation of Advanced Centre for Experimentation (ACE)

<time datetime="">2017</time>

NEC APAC Innovation Award for Ministry of Home Affairs Multi-Analytics Integrated System Project

{% comment %}{% endcomment %}

**Patent Submission**

<time datetime="">2018 </time>

An apparatus and a method for adaptively managing event-related data in a control room  [Filed]

## Inspirational workshops

These are list of courses and workshops that I found helpful for both professional and personal development.

{% include about-events-list.html %}

You can also [search](/search) the site or view chronological [external references](/ref) about projects that I was involved in.


text:
import { Component, OnInit } from '@angular/core';
import { RedditService } from './reddit.service';
import { Wallpaper } from './wallpaper.model';
import { WallpaperListing } from './wallpaper-listing.model';

@Component({
    selector: 'main',
    template: require('./main.component.html'),
    styles: [require('./main.component.less')],
})
export class MainComponent implements OnInit {

    private wallpaperListing: WallpaperListing;
    private error: boolean;

    constructor(private service: RedditService) { }

    ngOnInit() {
        this.wallpaperListing = new WallpaperListing();

        this.service
            .getWallpapers(null)
            .subscribe(
                result => this.wallpaperListing = result,
                error =>  this.error = true);
    }

    open(url:string) {
        window.open(url,'_blank');
    }

    loadMore() {
        console.log(this.wallpaperListing.after);

        this.service
            .getWallpapers(this.wallpaperListing.after)
            .subscribe(result => {
                    this.wallpaperListing.after = result.after;
                    this.wallpaperListing.wallpapers = this.wallpaperListing.wallpapers.concat(result.wallpapers);
                }, error => this.error = true
            );
    }
}


text:
#include <aws/ec2/model/PurchaseReservedInstancesOfferingResponse.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::EC2::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

PurchaseReservedInstancesOfferingResponse::PurchaseReservedInstancesOfferingResponse()
{
}

PurchaseReservedInstancesOfferingResponse::PurchaseReservedInstancesOfferingResponse(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

PurchaseReservedInstancesOfferingResponse& PurchaseReservedInstancesOfferingResponse::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (!rootNode.IsNull() && (rootNode.GetName() != "PurchaseReservedInstancesOfferingResponse"))
  {
    resultNode = rootNode.FirstChild("PurchaseReservedInstancesOfferingResponse");
  }

  if(!resultNode.IsNull())
  {
    XmlNode reservedInstancesIdNode = resultNode.FirstChild("reservedInstancesId");
    if(!reservedInstancesIdNode.IsNull())
    {
      m_reservedInstancesId = StringUtils::Trim(reservedInstancesIdNode.GetText().c_str());
    }
  }

  if (!rootNode.IsNull()) {
    XmlNode requestIdNode = rootNode.FirstChild("requestId");
    if (!requestIdNode.IsNull())
    {
      m_responseMetadata.SetRequestId(StringUtils::Trim(requestIdNode.GetText().c_str()));
    }
    AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::PurchaseReservedInstancesOfferingResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
  }
  return *this;
}


text:
//*****************************************************************************
// FILE: ossimEcefVector.h
//
// License:  See top level LICENSE.txt file.
//
// DESCRIPTION:
//   Contains declaration of a 3D vector object in the Earth-centered, earth
//   fixed (ECEF) coordinate system.
//
//   NOTE: There is no associated ossimEcefVector.cc file. All methods are
//         inlined here
//
// SOFTWARE HISTORY:
//>
//   08Aug2001  Oscar Kramer
//              Initial coding.
//<
//*****************************************************************************
//  $Id: ossimEcefVector.h 20043 2011-09-06 15:00:55Z oscarkramer $

#ifndef ossimEcefVector_HEADER
#define ossimEcefVector_HEADER

#include <cmath>
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimColumnVector3d.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimString.h>
#include <ossim/matrix/newmat.h>

class ossimGpt;

//*****************************************************************************
//  CLASS: ossimEcefVector
//
//*****************************************************************************
class OSSIMDLLEXPORT ossimEcefVector
{
public:
   /*!
    * CONSTRUCTORS:
    */
   ossimEcefVector()
      : theData(0,0,0) {}

   ossimEcefVector(const ossimEcefVector& copy_this)
      : theData (copy_this.theData) {}

   ossimEcefVector(const NEWMAT::ColumnVector& assign_this)
      : theData (assign_this) {}

   ossimEcefVector(const ossimEcefPoint& from,
                   const ossimEcefPoint& to)
      : theData (to.data() - from.data()) {}

   ossimEcefVector(const ossimGpt& from,
                   const ossimGpt& to)
      : theData ((ossimEcefPoint(to) - ossimEcefPoint(from)).data()) {}

   ossimEcefVector(const double& x,
                   const double& y,
                   const double& z)
      : theData(x, y, z) {}

   ossimEcefVector(const ossimColumnVector3d& assign_this)
      : theData(assign_this) {}

   void makeNan()
   {
      theData[0] = ossim::nan();
      theData[1] = ossim::nan();
      theData[2] = ossim::nan();
   }

   bool hasNans()const
   {
      return ( ossim::isnan(theData[0]) ||
               ossim::isnan(theData[1]) ||
               ossim::isnan(theData[2]) );
   }

   bool isNan()const
   {
      return ( ossim::isnan(theData[0]) &&
               ossim::isnan(theData[1]) &&
               ossim::isnan(theData[2]) );
   }

   /*!
    * OPERATORS: (all inlined below)
    */
   inline ossimEcefVector        operator- () const;
   inline ossimEcefVector        operator+ (const ossimEcefVector&) const;
   inline ossimEcefVector        operator- (const ossimEcefVector&) const;
   inline ossimEcefPoint         operator+ (const ossimEcefPoint&)  const;
   inline ossimEcefVector        operator* (const double&)          const;
   inline ossimEcefVector        operator/ (const double&)          const;
   inline bool                   operator==(const ossimEcefVector&) const;
   inline bool                   operator!=(const ossimEcefVector&) const;
   inline const ossimEcefVector& operator= (const ossimEcefVector&);

   /*!
    * Vector-related functions:  (all inlined below)
    */
   inline double          dot    (const ossimEcefVector&) const;
   inline double          angleTo(const ossimEcefVector&) const; // degrees
   inline ossimEcefVector cross  (const ossimEcefVector&) const;
   inline ossimEcefVector unitVector()                    const;
   inline double          magnitude()                     const; // meters
   inline double          norm2()                         const; // squared meters
   inline double length() const;
   inline double          normalize();

   /*!
    * COMPONENT ACCESS METHODS:
    */
   double    x() const { return theData[0]; }
   double&   x()       { return theData[0]; }
   double    y() const { return theData[1]; }
   double&   y()       { return theData[1]; }
   double    z() const { return theData[2]; }
   double&   z()       { return theData[2]; }
   double& operator [](int idx){return theData[idx];}
   const double& operator [](int idx)const{return theData[idx];}

   const ossimColumnVector3d& data() const { return theData; }
   ossimColumnVector3d&       data()       { return theData; }

   /**
    * @brief To string method.
    *
    * @param precision Output floating point precision.
    *
    * @return ossimString representing point.
    *
    * Output format:
    * ( 0.0000000,  0.0000000,  0.00000000 )
    *   -----x----  -----y----  ------z----
    */
   ossimString toString(ossim_uint32 precision=15) const;

   /**
    * @brief Initializes this point from string.
    *
    * Expected format:
    *
    * ( 0.0000000,  0.0000000,  0.00000000 )
    *   -----x----  -----y----  ------z----
    *
    * @param s String to initialize from.
    */
   void toPoint(const std::string& s);

   //! Converts this point to a 3D column vector.
   NEWMAT::ColumnVector toVector() const
   {
      NEWMAT::ColumnVector v (3);
      v(0) = theData[0];
      v(1) = theData[1];
      v(2) = theData[2];
      return v;
   }

   /*!
    * Debug Dump:
    */
   void print(std::ostream& os = ossimNotify(ossimNotifyLevel_INFO)) const
      {	 os << "(ossimEcefVector) " << theData; }

   friend std::ostream& operator<< (std::ostream& os , const ossimEcefVector& instance)
      { instance.print(os); return os; }

protected:
   ossimColumnVector3d theData;
};

//================== BEGIN DEFINITIONS FOR INLINE METHODS =====================

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator-()
//  Reverses direction of vector.
//*****************************************************************************
inline ossimEcefVector ossimEcefVector::operator-() const
{
   return ossimEcefVector(-theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator+(const ossimEcefVector&)
//*****************************************************************************
inline ossimEcefVector
ossimEcefVector::operator+(const ossimEcefVector& v) const
{
   return ossimEcefVector(theData + v.theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator-(const ossimEcefVector&)
//*****************************************************************************
inline ossimEcefVector
ossimEcefVector::operator-(const ossimEcefVector& v) const
{
   return ossimEcefVector(theData - v.theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator+(const ossimEcefPoint&)
//*****************************************************************************
inline  ossimEcefPoint
ossimEcefVector::operator+(const ossimEcefPoint& p) const
{
   return ossimEcefPoint(theData + p.data());
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator*(const double&)
//*****************************************************************************
inline ossimEcefVector ossimEcefVector::operator*(const double& scalar) const
{
   return ossimEcefVector(theData*scalar);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator/(const double&)
//*****************************************************************************
inline ossimEcefVector ossimEcefVector::operator/(const double& scalar) const
{
   return ossimEcefVector(theData/scalar);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator==(const ossimEcefVector&)
//*****************************************************************************
inline bool ossimEcefVector::operator==(const ossimEcefVector& v) const
{
   return (theData == v.theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator!=(const ossimEcefVector&)
//*****************************************************************************
inline bool ossimEcefVector::operator!=(const ossimEcefVector& v) const
{
   return (theData != v.theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::operator=
//*****************************************************************************
inline const ossimEcefVector&
ossimEcefVector::operator=(const ossimEcefVector& v)
{
   theData = v.theData;
   return *this;
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::dot()
//  Computes the scalar product.
//*****************************************************************************
inline double ossimEcefVector::dot(const ossimEcefVector& v) const
{
   return theData.dot(v.theData);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::angleTo()
//  Returns the angle subtended (in DEGREES) between this and arg vector
//*****************************************************************************
inline double ossimEcefVector::angleTo(const ossimEcefVector& v) const
{
   double mag_product = theData.magnitude() * v.theData.magnitude();
   return ossim::acosd(theData.dot(v.theData)/mag_product);
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::cross()
//  Computes the cross product.
//*****************************************************************************
inline ossimEcefVector ossimEcefVector::cross(const ossimEcefVector& v) const
{
   return ossimEcefVector(theData.cross(v.theData));
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::unitVector()
//  Returns a unit vector parallel to this.
//*****************************************************************************
inline ossimEcefVector ossimEcefVector::unitVector() const
{
   return ossimEcefVector(theData/theData.magnitude());
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::magnitude()
//*****************************************************************************
inline double ossimEcefVector::magnitude() const
{
   return theData.magnitude();
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::norm2()
//*****************************************************************************
inline double ossimEcefVector::norm2() const
{
   return theData.norm2();
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::length()
//*****************************************************************************
inline double ossimEcefVector::length() const
{
   return theData.magnitude();
}

//*****************************************************************************
//  INLINE METHOD: ossimEcefVector::normalize()
//  Normalizes this vector.
//*****************************************************************************
inline double ossimEcefVector::normalize()
{
   double result = theData.magnitude();
   if(result > 1e-15)
   {
      theData /= result;
   }

   return result;
}
#endif


text:
namespace boost {
    namespace io {

        // gcc-2.95 char traits (non-conformantly named string_char_traits)
        // lack several functions so we extend them in a replacement class.
        template<class Tr>
        class CompatTraits;

        // std::allocator<Ch> in gcc-2.95 is ok, but basic_string only works
        // with plain 'std::alloc' still, alt_stringbuf requires a functionnal
        // alloc template argument, so we need a replacement allocator
        template<class Alloc>
        class CompatAlloc;
    } // N.S. io
}// N.S. boost

#include <boost/format/detail/config_macros.hpp>
   // sets-up macros and load compiler-specific workarounds headers.

#if !defined(BOOST_FORMAT_STREAMBUF_DEFINED)
// workarounds-gcc-2.95 might have defined own streambuf
#include <streambuf>
#endif

#if !defined(BOOST_FORMAT_OSTREAM_DEFINED)
// workarounds-gcc-2.95 might already have included <iostream>
#include <ostream>
#endif

namespace boost {
    namespace io {

        // **** CompatTraits general definitions : ----------------------------
        template<class Tr>
        class CompatTraits
        {        // general case : be transparent
        public:
            typedef Tr  compatible_type;
        };

        // **** CompatAlloc general definitions : -----------------------------
        template<class Alloc>
        class CompatAlloc
        {        // general case : be transparent
        public:
            typedef Alloc  compatible_type;
        };

    } //N.S. io
} // N.S. boost
#endif // include guard


text:
require "dm-core"
require "dm-transactions"

#Datamapper 1.0 requires you to require dm-migrations to automigrate
require "dm-migrations"

# only to please activerecord API used in database_cleaner/examples/features/step_definitions
# yes, i know that's lazy ...

require "dm-validations"
require "dm-aggregates"

DataMapper.setup(:default, "sqlite3:#{DB_DIR}/datamapper_default.db")
DataMapper.setup(:one, "sqlite3:#{DB_DIR}/datamapper_one.db")
DataMapper.setup(:two, "sqlite3:#{DB_DIR}/datamapper_two.db")

class DataMapperWidget
  include DataMapper::Resource

  property :id,   Serial
  property :name, String
end

class DataMapperWidgetUsingDatabaseOne
  include DataMapper::Resource

  def self.default_repository_name
    :one
  end

  property :id,   Serial
  property :name, String

end

class DataMapperWidgetUsingDatabaseTwo
  include DataMapper::Resource

  def self.default_repository_name
    :two
  end

  property :id,   Serial
  property :name, String

end

DataMapperWidget.auto_migrate!
DataMapperWidgetUsingDatabaseOne.auto_migrate!
DataMapperWidgetUsingDatabaseTwo.auto_migrate!


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<movie>
<title>external</title>
<title>internal</title>
</movie>


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

namespace PHPUnit\TestFixture;

use PHPUnit\Framework\TestCase;
use Throwable;

class TemplateMethodsTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        print __METHOD__ . "\n";
    }

    public static function tearDownAfterClass(): void
    {
        print __METHOD__ . "\n";
    }

    protected function setUp(): void
    {
        print __METHOD__ . "\n";
    }

    protected function tearDown(): void
    {
        print __METHOD__ . "\n";
    }

    public function testOne(): void
    {
        print __METHOD__ . "\n";
        $this->assertTrue(true);
    }

    public function testTwo(): void
    {
        print __METHOD__ . "\n";
        $this->assertTrue(false);
    }

    protected function assertPreConditions(): void
    {
        print __METHOD__ . "\n";
    }

    protected function assertPostConditions(): void
    {
        print __METHOD__ . "\n";
    }

    protected function onNotSuccessfulTest(Throwable $t): void
    {
        print __METHOD__ . "\n";

        throw $t;
    }
}


text:
namespace gfx {
class Size;
}

namespace net {
class X509Certificate;
}

class SkBitmap;

namespace xwalk {

// A class that handles the Java<->Native communication for the
// XWalkContentsClient. XWalkContentsClientBridge is created and owned by
// native XWalkViewContents class and it only has a weak reference to the
// its Java peer. Since the Java XWalkContentsClientBridge can have
// indirect refs from the Application (via callbacks) and so can outlive
// XWalkView, this class notifies it before being destroyed and to nullify
// any references.
class XWalkContentsClientBridge : public XWalkContentsClientBridgeBase {
 public:
  XWalkContentsClientBridge(JNIEnv* env, jobject obj);
  virtual ~XWalkContentsClientBridge();

  // XWalkContentsClientBridgeBase implementation
  virtual void AllowCertificateError(int cert_error,
                                     net::X509Certificate* cert,
                                     const GURL& request_url,
                                     const base::Callback<void(bool)>& callback,
                                     bool* cancel_request) OVERRIDE;

  virtual void RunJavaScriptDialog(
      content::JavaScriptMessageType message_type,
      const GURL& origin_url,
      const base::string16& message_text,
      const base::string16& default_prompt_text,
      const content::JavaScriptDialogManager::DialogClosedCallback& callback)
      OVERRIDE;
  virtual void RunBeforeUnloadDialog(
      const GURL& origin_url,
      const base::string16& message_text,
      const content::JavaScriptDialogManager::DialogClosedCallback& callback)
      OVERRIDE;
  virtual void ShowNotification(
      const content::ShowDesktopNotificationHostMsgParams& params,
      bool worker,
      int process_id,
      int route_id)
      OVERRIDE;
  virtual void UpdateNotificationIcon(
      int notification_id,
      const SkBitmap& icon)
      OVERRIDE;
  virtual void CancelNotification(
      int notification_id,
      int process_id,
      int route_id)
      OVERRIDE;

  bool OnReceivedHttpAuthRequest(const base::android::JavaRef<jobject>& handler,
                                 const std::string& host,
                                 const std::string& realm);

  void OnNotificationIconDownloaded(
      int id,
      int http_status_code,
      const GURL& image_url,
      const std::vector<SkBitmap>& bitmaps,
      const std::vector<gfx::Size>& original_bitmap_sizes);

  // Methods called from Java.
  void ProceedSslError(JNIEnv* env, jobject obj, jboolean proceed, jint id);
  void ConfirmJsResult(JNIEnv*, jobject, int id, jstring prompt);
  void CancelJsResult(JNIEnv*, jobject, int id);
  void ExitFullscreen(JNIEnv*, jobject, jint web_contents);
  void NotificationDisplayed(
      JNIEnv*, jobject, int id, int process_id, int route_id);
  void NotificationError(
      JNIEnv*, jobject, int id, jstring error, int process_id, int route_id);
  void NotificationClicked(
      JNIEnv*, jobject, int id, int process_id, int route_id);
  void NotificationClosed(
      JNIEnv*, jobject, int id, bool by_user, int process_id, int route_id);

 private:
  JavaObjectWeakGlobalRef java_ref_;

  typedef const base::Callback<void(bool)> CertErrorCallback;
  IDMap<CertErrorCallback, IDMapOwnPointer> pending_cert_error_callbacks_;
  IDMap<content::JavaScriptDialogManager::DialogClosedCallback, IDMapOwnPointer>
      pending_js_dialog_callbacks_;

  typedef std::map<int, std::vector<int> > NotificationDownloadRequestIdMap;
  NotificationDownloadRequestIdMap downloading_icon_notifications_;
};

bool RegisterXWalkContentsClientBridge(JNIEnv* env);

}  // namespace xwalk

#endif  // XWALK_RUNTIME_BROWSER_ANDROID_XWALK_CONTENTS_CLIENT_BRIDGE_H_


text:
const rucksack = require('rucksack-css')
const path = require('path')
const webpack = require('webpack')
const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin')
const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'))

const CleanPlugin = require('clean-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const webpackModule = require('./config/module.prod')
const projectRootPath = path.resolve(__dirname, '..')
const assetsPath = path.resolve(projectRootPath, 'static/dist')

const outputPath = path.resolve(__dirname, '../static/dist')
const entry = require('./config/entry')

const config = {
  devtool: 'source-map',
  entry,
  output: {
    path: outputPath,
    filename: '[name]-[hash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: '/dist/'
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new CleanPlugin([assetsPath], { root: projectRootPath }),
    new ExtractTextPlugin('[name]-[chunkhash].css', { allChunks: true }),
    new webpack.DefinePlugin({
      'process.env': {
        // Useful to reduce the size of client-side libraries, e.g. react
        NODE_ENV: JSON.stringify('production')
      }
    }),
    // optimizations
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    webpackIsomorphicToolsPlugin
  ],
  module: webpackModule,
  resolve: {
    modulesDirectories: ['src', 'node_modules'],
    extensions: ['', '.js', '.jsx', '.css', '.scss']
  },
  postcss: [
    rucksack({
      autoprefixer: true
    })
  ],
  toolbox: { theme: './src/theme/theme.scss' }
}

module.exports = config


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Welcome to Composite Plate's documentation! — Composite Plate 0.1.1 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Composite Plate 0.1.1 documentation" href="#" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Welcome to Composite Plate’s documentation!¶

Contents:

Indices and tables¶

Index

Module Index

Search Page

How to Use Composite Plate¶

The goal of this module is to provide you with a way to determine how a
composite plate will respond to either stresses or strains.  In order to
do this, you must define the composite plate in the following way.

Define a ply material using composite_plate.Ply

Use the ply and a given orientation to define a laminae using composite_plate.Laminae

One or more of the laminae in a list to define a laminate using composite_plate.Laminate

Example:

>>> E1      = 133.44;   # Modulus in fiber direction        [GPa]
>>> E2      = 8.78;     # Modulus in transverse direction   [GPa]
>>> G12     = 3.254;    # Shear Modulus                     [GPa]
>>> nu12    = 0.26;     # Poissons Ratio (principal)        [   ]
>>> h       = 6;        # Ply thickness                     [mm]

>>> ply = composite_plate.Ply(E1=E1,E2=E2,G12=G12,nu12=nu12,h=h)

>>> theta_deg = 45;     # Orientation (+ from X)            [deg]
>>> theta_rad = theta_deg*np.pi/180.0;    #                 [rad]

>>> laminae1 = composite_plate.Laminae(ply, theta_rad);
>>> laminae2 = composite_plate.Laminae(ply,-theta_rad);

>>> laminate = composite_plate.Laminate([laminae1, laminae2])

After the laminate is created, you can then apply strains and see the
resulting stress using composite_plate.Laminate.applied_strain().

Example:

>>> Epsilon = numpy.matrix([]);
>>> Kappa = numpy.matrix([]);
>>> force_and_moment_dict = laminate.applied_strain(Epsilon, Kappa)
>>> N = force_and_moment_dict('N')
>>> print("The forces are Nxx = {0}, Nyy = {1}, Nxy = {2}".format(N[1],N[2],N[3]))

>>> M = force_and_moment_dict('M')
>>> print("The moments are Mxx = {0}, Myy = {1}, Mxy = {2}".format(M[1],M[2],M[3]))

Modules¶

exception composite_plate.CompPlateError[source]¶

Base class for exceptions in this module.

__weakref__¶

list of weak references to the object (if defined)

exception composite_plate.InputError(expr, msg)[source]¶

Exception raised for errors in the input.

expr -- input expression in which the error occurred

msg  -- explanation of the error

class composite_plate.Laminae(ply, theta_rad)[source]¶

Composite Laminae defined for each layer in a composite.

A laminae is an individual layer in a composite laminate.  It
consists of a ply rotated some angle in the composite.  The angle is
defined as the angle between the plys primary (1) axis and the
composites x axis.

Example

To instantiate a laminae, you must start with a ply, and then use
the ply instance and a specified angle to get a single laminae.:

>>> E1      = 133.44;   # Modulus in fiber direction        [GPa]
>>> E2      = 8.78;     # Modulus in transverse direction   [GPa]
>>> G12     = 3.254;    # Shear Modulus                     [GPa]
>>> nu12    = 0.26;     # Poissons Ratio (principal)        [   ]
>>> h       = 6;        # Ply thickness                     [mm]
>>> ply = Ply(E1=E1,E2=E2,G12=G12,nu12=nu12,h=h)
>>> theta_deg = 45;     # Orientation (+ from X)            [deg]
>>> theta_rad = theta_deg*np.pi/180.0;    #                 [rad]
>>> laminae1 = Laminae(ply, theta_rad);

__init__(ply, theta_rad)[source]¶

Initialize the composite Laminae

Defines an individual laminae based on the ply and orientation
of the laminae x-axis to the ply 1 axis (theta_rad)

<col class="field-name" />
<col class="field-body" />

Parameters:

ply (composite_plate.Ply) – A ply object

theta_rad (float) – The orientation of the plys primary (1) axis to the composites x axis [radians]

__weakref__¶

list of weak references to the object (if defined)

class composite_plate.Laminate(laminae_list)[source]¶

A class defining a composite Laminate.  Input is as the composites
laminae, the laminae thickness and stacking order.

<col class="field-name" />
<col class="field-body" />

Parameters:	laminae_list (list of composite_plate.Laminae) – A list of laminae which compose the laminate, in order from bottom to top

A,B,D

numpy.matrix

Compliance matrices will become class
variables after __init__.

laminae_midplane_z¶

list[float]

A list of heights from the
midplane of the laminate to the midplane of each laminae.

Epsilon¶

numpy.matrix

If defined contains a vector [3x1] of the
midplane laminate strains.

Kappa¶

numpy.matrix

If defined contains a vector [3x1] of the
laminate curvatures.

Example

To instantiate a laminate, you must start with one or more laminae,
and then use the laminae instance(s) in a list to create the
laminate.:

>>> E1      = 133.44;   # Modulus in fiber direction        [GPa]
>>> E2      = 8.78;     # Modulus in transverse direction   [GPa]
>>> G12     = 3.254;    # Shear Modulus                     [GPa]
>>> nu12    = 0.26;     # Poissons Ratio (principal)        [   ]
>>> h       = 6;        # Ply thickness                     [mm]
>>> ply = Ply(E1=E1,E2=E2,G12=G12,nu12=nu12,h=h)
>>> theta_deg = 45;     # Orientation (+ from X)            [deg]
>>> theta_rad = theta_deg*np.pi/180.0;    #                 [rad]
>>> laminae1 = Laminae(ply, theta_rad);
>>> laminae2 = Laminae(ply,-theta_rad);
>>> laminate = Laminate([laminae1, laminae2])

\[\begin{split}[N](3x1) &= [A](3x3)*[\epsilon](3x1) +[B](3x3)*[\kappa](3x1) \\
[M](3x1) &= [B](3x3)*[\epsilon](3x1) +[D](3x3)*[\kappa](3x1)\end{split}\]

Normal Force/ unit lenght [F/l] in x,y and xy directions:

\[\begin{split}[N] &= [N_{xx} N_{yy} N_{xy}]^T \\
[M] &= [M_{xx} M_{yy} M_{xy}]^T\end{split}\]

-> Moment / unit length [F*l/l]

\[\begin{split}[\epsilon] &= [\epsilon^0_{xx} \epsilon^0_{yy} \gamma^0_{xy}]^T \\
[\kappa] &= [\kappa_{xx} \kappa_{yy} \kappa_{xy}]^T\end{split}\]

Midplane strains indicated by \(\epsilon^0\)

\[\begin{split}[A]_{mn} = \sum_{j=1}^N(\bar{Q}_{mn})_j(h_j -h_{j-1})\\
[B]_{mn} = \frac{1}{2}\sum_{j=1}^N(\bar{Q}_{mn})_j(h_j^2 -h_{j-1}^2)\\
[D]_{mn} = \frac{1}{3}\sum_{j=1}^N(\bar{Q}_{mn})_j(h_j^3 -h_{j-1}^3)\\\end{split}\]

Laminae stiffness matrix \(\bar{Q}\)

\[\begin{split}[\epsilon] &= [A_1]*[N] + [B_1]*[M] \\
[\kappa] &= [C_1]*[N] + [D_1]*[M] \\
\\
[A_1] &= [A^{-1}]+[A^{-1}][B][D^{*-1}][B][A^{-1}] \\
[B_1] &= -[A^{-1}][B][D^{*-1}] \\
[C_1] &= -[D^{*-1}][B][A^{-1}] = [B_1]^T \\
[D^*] &= [D] -[B][A^{-1}][B] \\
[D_1] &= [D^{*-1}]\end{split}\]

__init__(laminae_list)[source]¶

Initialize class Laminate

<col class="field-name" />
<col class="field-body" />

Parameters:

self – This object instance.

laminae_list – A list containing objects of type Laminae,
defined in Laminae.py

Example

ply1 = CompositePlate.Ply(...)
laminae1 = CompositePlate.Laminae
laminate = CompositePlate.Laminate([laminae1, laminae2, laminae1]

__weakref__¶

list of weak references to the object (if defined)

applied_strain(Epsilon, Kappa)[source]¶

Method for applying midplane strains to the laminate instance and determine the resulting midplane stresses

<col class="field-name" />
<col class="field-body" />

Parameters:

Epsilon (numpy.matrix) – A [3x1] vector of midplane strains.
\([\epsilon]_1 = \epsilon_{xx}^0\), \([\epsilon]_2 = \epsilon_{yy}^0\), \([\epsilon]_3 = \gamma_{xy}^0\)

Kappa (numpy.matrix) – A [3x1] vector of curvatures.
\([\kappa]_1 = \kappa_{xx}\), \([\kappa]_2 = \kappa_{yy}\), \([\kappa]_3 = \kappa_{xy}\)

Returns:

A dictionary containing the Normal stresses (N) and Moments (M)

N (numpy.matrix): A [3x1] vector containing the normal stresses

M (numpy.matrix): A [3x1] vector containing the resulting moments

Return type:
numpy.matrix

applied_stress(N, M)[source]¶

Method for applying forces normalized by the section width to the laminate at the midplane.

<col class="field-name" />
<col class="field-body" />

Parameters:

N (numpy.matrix) – A [3x1] vector of normal stresses normalized by the section width
\([N]_1=N_{xx}\), \([N]_2=N_{yy}\), \([N]_3=N_{xy}\)

M (numpy.matrix) – A [3x1] vector of moments normalized by the section width
\([M]_1=M_{xx}\), \([M]_2=M_{yy}\), \([M]_3=M_{xy}\)

Returns:

A dictionary containing the normal strains (Epsilon) and curvatures (Kappa)

Epsilon (numpy.matrix): A [3x1] vector of laminate midplane strains.

Kappa (numpy.matrix): A [3x1] vector of laminate curvatures.

Return type:
numpy.matrix

midplane_strain(Epsilon=None, Kappa=None)[source]¶

Method for determining the laminae midplane strains in
response to laminate nidplane strains and curvatures.

If no laminate strain (Epsilon) or curvature (Kappa) is specified,
the method will attempt to use the laminate’s current strain
and curvaure.  If they haven’t been set, the method will throw
an InputError exception.

<col class="field-name" />
<col class="field-body" />

Parameters:

Epsilon (numpy.matrix) – A [3x1] vector of laminate midplane
strains.  If a value is specified, this will be assigned
to the laminate as the current state of strain.

Kappa (numpy.matrix) – A [3x1] vector of laminate curvatures.
If a value is specified, this will be assigned to the
laminate as the current state of curvature.

Returns:

A list of Epsilon values corresponding to the
midplane strain in each laminae of the laminate.

Epsilon (numpy.matrix): A [3x1] vector of laminate midplane strains.

Return type:
numpy.matrix

class composite_plate.Ply(E1, E2, G12, nu12, h)[source]¶

Defines a ply for a composite.

A ply is the material which goes into a composite.  Typically a ply
will have a different modulus in the primary (E1) direction and the
traverse (E2) direction.  The ply will have a shear modulus (G12)
and poissons ratio (nu12), as well as a thickness (h)

Example

To instantiate a ply, you must specify the plys parameter values:

>>> E1      = 133.44;   # Modulus in fiber direction        [GPa]
>>> E2      = 8.78;     # Modulus in transverse direction   [GPa]
>>> G12     = 3.254;    # Shear Modulus                     [GPa]
>>> nu12    = 0.26;     # Poissons Ratio (principal)        [   ]
>>> h       = 6;        # Ply thickness                     [mm]
>>> ply = Ply(E1=E1,E2=E2,G12=G12,nu12=nu12,h=h)

__init__(E1, E2, G12, nu12, h)[source]¶

Initializes the properties of the anisotropic ply.

Anisotropic ply.  Need to define 4 of [E1,E2,nu12,nu21,G12] (4
of 5 independent variables).
Dependent constraint: nu21/E2 = nu12/E1

Units can be any set of self consistent units desired.

<col class="field-name" />
<col class="field-body" />

Parameters:

E1 (float) – Modulus in the primary direction

E2 (float) – Modulus perpendicular to the primary direction

G12 (float) – Shear Modulus

nu12 (float) – Poissons Ratio

h (float) – Ply thickness

Exceptions:

InputError:     If any input value is not > 0

__weakref__¶

list of weak references to the object (if defined)

degree_of_isotropy()[source]¶

Returns the degree of Isotropy of the Ply (E1/E2)

E1/E2 is a metric used to compare how isotropic plys are

class composite_plate.PlyFromFiber[source]¶

Estimate ply properties from Fiber and Matrix properties

Will provide estimates of various elastic and thermal ply properties
based on the Fiber and matrix properties

__init__()[source]¶

Initialize the PlyFromFiber object, all member variables to
NaN

This initializes all possible member variables to NaN, since
different estimated properties require different variables to be
defined.  When using, define the required fiber and matrix values
for your property of interest, and then calculate the property.

Member Variables:

E_f:    Elastic modulus of the fiber
v_f:    Volume fraction of the ply that is fiber
nu_f:   Poissons ratio of the fiber
G_f:    Shear modulus of the fiber

E_m:    Elastic modulus of the matrix
v_m:    Volume fraction of the ply that is matrix
nu_m:   Poissons ratio of the matrix
G_m:    Shear modulus of the matrix

__weakref__¶

list of weak references to the object (if defined)

elastic_props()[source]¶

Calculates the elastic properties of the ply from the fiber
and matrix properties.

Table Of Contents

Welcome to Composite Plate’s documentation!

Indices and tables

How to Use Composite Plate

Modules

Related Topics

Documentation overview

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      ©2015, John Robinson.

      |
      Powered by Sphinx 1.3.1
      & Alabaster 0.7.6

      |
      Page source


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ajatus Software</title>
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="canonical" href="http://countableset.ch/blog/blog/2012/01/29/twitter-bootstrap-login-page">
  	<link href="img/favicon.png" rel="icon">
  	<link href="/blog/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">

 	 <link href="/blog/atom.xml" rel="alternate" title="countableSet" type="application/atom+xml">

	<link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
	<link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">

<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>

   	<link href="docs/assets/css/bootstrap.css" rel="stylesheet">

    <link href="docs/assets/css/bootstrap-responsive.css" rel="stylesheet">

	<link rel="shortcut icon" href="docs/assets/ico/favicon.ico">
	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="docs/assets/ico/apple-touch-icon-144-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="docs/assets/ico/apple-touch-icon-114-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="docs/assets/ico/apple-touch-icon-72-precomposed.png">
	<link rel="apple-touch-icon-precomposed" href="docs/assets/ico/apple-touch-icon-57-precomposed.png">
	<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/cupertino/jquery-ui.css" type="text/css" />

Login

                  <form action="">
                      <fieldset>

                              <input type="text" placeholder="Username">

                              <input type="password" placeholder="Password">

                          <button class="btn btn-primary" type="submit">Sign in</button>
                      </fieldset>
                  </form>


text:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;

namespace OneCog.Io.Spark
{
    public interface IRestClient
    {
        Task<Stream> Get(Uri uri);

        Task<Stream> Post(Uri uri, HttpContent content);
    }

    public class RestClient : IRestClient
    {
        private readonly HttpClient _client;
        private readonly IScheduler _requestScheduler;
        private readonly IScheduler _responseScheduler;

        public RestClient(string accessToken, IScheduler requestScheduler, IScheduler responseScheduler)
        {
            _client = new HttpClient();
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            _requestScheduler = requestScheduler ?? new EventLoopScheduler();
            _responseScheduler = responseScheduler ?? TaskPoolScheduler.Default;
        }

        public Task<Stream> Get(Uri uri)
        {
            return Observable
                .StartAsync(() => _client.GetStreamAsync(uri))
                .SubscribeOn(_requestScheduler)
                .ObserveOn(_responseScheduler)
                .ToTask();
        }

        public Task<Stream> Post(Uri uri, HttpContent content)
        {
            return Observable
                .StartAsync(
                    async () =>
                    {
                        HttpResponseMessage response = await _client.PostAsync(uri, content);

                        response.EnsureSuccessStatusCode();

                        return await response.Content.ReadAsStreamAsync();
                    }
                )
                .SubscribeOn(_requestScheduler)
                .ObserveOn(_responseScheduler)
                .ToTask();
        }
    }
}


text:
module Nupack
  class Calculator
    FLAT_MARKUP = 0.05

    def initialize
      @products = []
    end

    def add_product(product)
      @products << product
    end

    def total_cost
      @products.inject(0) do |total, product|
        product_cost = product.price + (product.price * product.markup)
        product_cost = product_cost + (product_cost * FLAT_MARKUP)

        total += product_cost.round(2)
      end
    end
  end
end