text:
#include "OgreStableHeaders.h"

#include "OgreMesh2Serializer.h"
#include "OgreMesh2.h"
#include "OgreException.h"
#include "OgreLogManager.h"

namespace Ogre {
    const unsigned short HEADER_CHUNK_ID = 0x1000;
    //---------------------------------------------------------------------
    MeshSerializer::MeshSerializer( VaoManager *vaoManager )
        :mListener(0)
    {
        // Init implementations
        // String identifiers have not always been 100% unified with OGRE version

        // Note MUST be added in reverse order so latest is first in the list

        mVersionData.push_back(OGRE_NEW MeshVersionData(
            MESH_VERSION_2_1, "[MeshSerializer_v2.1 R2]",
            OGRE_NEW MeshSerializerImpl( vaoManager )));

        //These formats will be removed on release
        mVersionData.push_back(OGRE_NEW MeshVersionData(
            MESH_VERSION_LEGACY, "[MeshSerializer_v2.1 R1]",
            OGRE_NEW MeshSerializerImpl_v2_1_R1( vaoManager )));

        mVersionData.push_back(OGRE_NEW MeshVersionData(
            MESH_VERSION_LEGACY, "[MeshSerializer_v2.1]",
            OGRE_NEW MeshSerializerImpl_v2_1_R0( vaoManager )));
    }
    //---------------------------------------------------------------------
    MeshSerializer::~MeshSerializer()
    {
        // delete map
        for (MeshVersionDataList::iterator i = mVersionData.begin();
            i != mVersionData.end(); ++i)
        {
            OGRE_DELETE *i;
        }
        mVersionData.clear();
    }
    //---------------------------------------------------------------------
    void MeshSerializer::exportMesh(const Mesh* pMesh, const String& filename,
        Endian endianMode)
    {
        std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
        f->open(filename.c_str(), std::ios::binary | std::ios::out);
        DataStreamPtr stream(OGRE_NEW FileStreamDataStream(f));

        exportMesh(pMesh, stream, endianMode);

        stream->close();
    }
    //---------------------------------------------------------------------
    void MeshSerializer::exportMesh(const Mesh* pMesh, const String& filename,
                                    MeshVersion version, Endian endianMode)
    {
        if( version == MESH_VERSION_LEGACY )
        {
            OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
                         "You may not supply a legacy version number for writing meshes.",
                         "MeshSerializer::exportMesh" );
        }

        std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
        f->open(filename.c_str(), std::ios::binary | std::ios::out);
        DataStreamPtr stream(OGRE_NEW FileStreamDataStream(f));

        exportMesh(pMesh, stream, version, endianMode);

        stream->close();
    }
    //---------------------------------------------------------------------
    void MeshSerializer::exportMesh(const Mesh* pMesh, DataStreamPtr stream,
        Endian endianMode)
    {
        exportMesh(pMesh, stream, MESH_VERSION_LATEST, endianMode);
    }
    //---------------------------------------------------------------------
    void MeshSerializer::exportMesh(const Mesh* pMesh, DataStreamPtr stream,
                                    MeshVersion version, Endian endianMode)
    {
        MeshSerializerImpl* impl = 0;
        if (version == MESH_VERSION_LATEST)
            impl = mVersionData[0]->impl;
        else
        {
            for (MeshVersionDataList::iterator i = mVersionData.begin();
                 i != mVersionData.end(); ++i)
            {
                if (version == (*i)->version)
                {
                    impl = (*i)->impl;
                    break;
                }
            }
        }

        if (!impl)
        {
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot find serializer implementation for "
                        "specified version", "MeshSerializer::exportMesh");
        }

        impl->exportMesh(pMesh, stream, endianMode);
    }
    //---------------------------------------------------------------------
    void MeshSerializer::importMesh(DataStreamPtr& stream, Mesh* pDest)
    {
        determineEndianness(stream);

        // Read header and determine the version
        unsigned short headerID;

        // Read header ID
        readShorts(stream, &headerID, 1);

        if (headerID != HEADER_CHUNK_ID)
        {
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "File header not found",
                "MeshSerializer::importMesh");
        }
        // Read version
        String ver = readString(stream);
        // Jump back to start
        stream->seek(0);

        // Find the implementation to use
        MeshSerializerImpl* impl = 0;
        for (MeshVersionDataList::iterator i = mVersionData.begin();
             i != mVersionData.end(); ++i)
        {
            if ((*i)->versionString == ver)
            {
                impl = (*i)->impl;
                break;
            }
        }
        if (!impl)
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot find serializer implementation for "
                        "mesh version " + ver, "MeshSerializer::importMesh");

        // Call implementation
        impl->importMesh(stream, pDest, mListener);
        // Warn on old version of mesh
        if (ver != mVersionData[0]->versionString)
        {
            LogManager::getSingleton().logMessage("WARNING: " + pDest->getName() +
                " is an older format (" + ver + "); you should upgrade it as soon as possible" +
                " using the OgreMeshTool tool.", LML_CRITICAL);
        }

        if(mListener)
            mListener->processMeshCompleted(pDest);
    }
    //---------------------------------------------------------------------
    void MeshSerializer::setListener( MeshSerializerListener *listener )
    {
        mListener = listener;
    }
    //-------------------------------------------------------------------------
    MeshSerializerListener *MeshSerializer::getListener()
    {
        return mListener;
    }
}


text:
'use strict';

var rendered = function () {
        $('.pwdForm').bootstrapValidator(authValidationRules).on('success.form.bv', function (e) {
            e.preventDefault();
        });
    },
    events = {
        'submit .pwdForm': function (ev) {
            ev.preventDefault();
            var $form = $(ev.target),
                data = getFormObj($form);
            if ($form.data('bootstrapValidator').isValid()) {
                Accounts.changePassword(data.oldPwd, data.newPwd, function (err) {
                    if (err) {
                        console.error(err);
                    }
                });
            }
        }
    };

Template.passwordForm.rendered = rendered;
Template.passwordForm.events(events);

Template.privacyForm.rendered = rendered;
Template.privacyForm.events(events);

redpajama_set_name: RedPajamaGithub


text:
using boost::asio::ip::tcp;

class client
{
public:
  client(boost::asio::io_service& io_service,
      const std::string& server, const std::string& path)
    : resolver_(io_service),
      socket_(io_service)
  {
    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    std::ostream request_stream(&request_);
    request_stream << "GET " << path << " HTTP/1.1\r\n";
    request_stream << "Host: " << server << "\r\n";
    request_stream << "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Accept-Encoding: identity\r\n";
    request_stream << "Connection: close\r\n";
    request_stream << "Cache-Control: max-age=0\r\n\r\n";

    // Start an asynchronous resolve to translate the server and service names
    // into a list of endpoints.
    tcp::resolver::query query(server, "http");
    resolver_.async_resolve(query,
        boost::bind(&client::handle_resolve, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::iterator));
  }

private:
  void handle_resolve(const boost::system::error_code& err,
      tcp::resolver::iterator endpoint_iterator)
  {
    if (!err)
    {
      // Attempt a connection to each endpoint in the list until we
      // successfully establish a connection.
      boost::asio::async_connect(socket_, endpoint_iterator,
          boost::bind(&client::handle_connect, this,
            boost::asio::placeholders::error));
    }
    else
    {
      printf("HTTP Error1: %s\n", err.message().c_str());
    }
  }

  void handle_connect(const boost::system::error_code& err)
  {
    if (!err)
    {
      // The connection was successful. Send the request.
      boost::asio::async_write(socket_, request_,
          boost::bind(&client::handle_write_request, this,
            boost::asio::placeholders::error));
    }
    else
    {
      printf("HTTP Error2: %s\n", err.message().c_str());
    }
  }

  void handle_write_request(const boost::system::error_code& err)
  {
    if (!err)
    {
      // Read the response status line. The response_ streambuf will
      // automatically grow to accommodate the entire line. The growth may be
      // limited by passing a maximum size to the streambuf constructor.
      boost::asio::async_read_until(socket_, response_, "\r\n",
          boost::bind(&client::handle_read_status_line, this,
            boost::asio::placeholders::error));
    }
    else
    {
      printf("HTTP Error3: %s\n", err.message().c_str());
    }
  }

  void handle_read_status_line(const boost::system::error_code& err)
  {
    if (!err)
    {
      // Check that response is OK.
      std::istream response_stream(&response_);
      std::string http_version;
      response_stream >> http_version;
      unsigned int status_code;
      response_stream >> status_code;
      std::string status_message;
      std::getline(response_stream, status_message);
      if (!response_stream || http_version.substr(0, 5) != "HTTP/")
      {
        printf("HTTP Error: Invalid response\n");
        return;
      }
      if (status_code != 200)
      {
        printf("HTTP Response returned with status code: %d\n", status_code);
        return;
      }

      // Read the response headers, which are terminated by a blank line.
      boost::asio::async_read_until(socket_, response_, "\r\n\r\n",
          boost::bind(&client::handle_read_headers, this,
            boost::asio::placeholders::error));
    }
    else
    {
      printf("HTTP Error5: %s\n", err.message().c_str());
    }
  }

  void handle_read_headers(const boost::system::error_code& err)
  {
    if (!err)
    {
      // Process the response headers.
      std::istream response_stream(&response_);
      std::string header;
      while (std::getline(response_stream, header) && header != "\r")
        printf("HTTP header: %s\n", header.c_str());

      // Write whatever content we already have to output.
      if (response_.size() > 0) printf("HTTP header: response_ have content\n");
      ///  std::cout << &response_;

      // Start reading remaining data until EOF.
      boost::asio::async_read(socket_, response_,
          boost::asio::transfer_at_least(1),
          boost::bind(&client::handle_read_content, this,
            boost::asio::placeholders::error));
    }
    else
    {
      printf("HTTP Error6: %s\n", err.message().c_str());
    }
  }

  void handle_read_content(const boost::system::error_code& err)
  {
    if (!err)
    {
      // Write all of the data that has been read so far.
      //std::cout << &response_;
      std::istream response_stream(&response_);
      std::string sdata;
      while (std::getline(response_stream, sdata))
          printf("HTTP data: %s\n", sdata.c_str());

      // Continue reading remaining data until EOF.
      boost::asio::async_read(socket_, response_,
          boost::asio::transfer_at_least(1),
          boost::bind(&client::handle_read_content, this,
            boost::asio::placeholders::error));
    }
    else if (err != boost::asio::error::eof)
    {
      printf("HTTP Error7: %s\n", err.message().c_str());
    }
  }

  tcp::resolver resolver_;
  tcp::socket socket_;
  boost::asio::streambuf request_;
  boost::asio::streambuf response_;
};

const std::string HTTPClient(const std::string& pszUrl, const std::string& pszFile)
{
  try
  {
    printf("HTTP start for: %s\n", pszUrl.c_str());
    boost::asio::io_service io_service;
    //const std::string& szUrl = "lgpk.sinaapp.com";
    //const std::string& szFile="/t.php";
    //pszUrl="lgpk.sinaapp.com"; pszFile="/t.php";
    client c(io_service, pszUrl, pszFile);
    io_service.run();
  }
  catch (std::exception& e)
  {
    printf("HTTP failed: %s\n", e.what());
  }

  return pszUrl;
}


text:
import os
import faiss
import numpy as np

class CombinedIndex:
    """
    combines a set of inverted lists into a hstack
    masks part of those lists
    adds these inverted lists to an empty index that contains
    the info on how to perform searches
    """

    def __init__(self, invlist_fnames, empty_index_fname,
                 masked_index_fname=None):

        self.indexes = indexes = []
        ilv = faiss.InvertedListsPtrVector()

        for fname in invlist_fnames:
            if os.path.exists(fname):
                print('reading', fname, end='\r', flush=True)
                index = faiss.read_index(fname)
                indexes.append(index)
                il = faiss.extract_index_ivf(index).invlists
            else:
                raise AssertionError
            ilv.push_back(il)
        print()

        self.big_il = faiss.VStackInvertedLists(ilv.size(), ilv.data())
        if masked_index_fname:
            self.big_il_base = self.big_il
            print('loading', masked_index_fname)
            self.masked_index = faiss.read_index(
                masked_index_fname,
                faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY)
            self.big_il = faiss.MaskedInvertedLists(
                faiss.extract_index_ivf(self.masked_index).invlists,
                self.big_il_base)

        print('loading empty index', empty_index_fname)
        self.index = faiss.read_index(empty_index_fname)
        ntotal = self.big_il.compute_ntotal()

        print('replace invlists')
        index_ivf = faiss.extract_index_ivf(self.index)
        index_ivf.replace_invlists(self.big_il, False)
        index_ivf.ntotal = self.index.ntotal = ntotal
        index_ivf.parallel_mode = 1   # seems reasonable to do this all the time

        quantizer = faiss.downcast_index(index_ivf.quantizer)
        quantizer.hnsw.efSearch = 1024

    ############################################################
    # Expose fields and functions of the index as methods so that they
    # can be called by RPC

    def search(self, x, k):
        return self.index.search(x, k)

    def range_search(self, x, radius):
        return self.index.range_search(x, radius)

    def transform_and_assign(self, xq):
        index = self.index

        if isinstance(index, faiss.IndexPreTransform):
            assert index.chain.size() == 1
            vt = index.chain.at(0)
            xq = vt.apply_py(xq)

        # perform quantization
        index_ivf = faiss.extract_index_ivf(index)
        quantizer = index_ivf.quantizer
        coarse_dis, list_nos = quantizer.search(xq, index_ivf.nprobe)
        return xq, list_nos, coarse_dis

    def ivf_search_preassigned(self, xq, list_nos, coarse_dis, k):
        index_ivf = faiss.extract_index_ivf(self.index)
        n, d = xq.shape
        assert d == index_ivf.d
        n2, d2 = list_nos.shape
        assert list_nos.shape == coarse_dis.shape
        assert n2 == n
        assert d2 == index_ivf.nprobe
        D = np.empty((n, k), dtype='float32')
        I = np.empty((n, k), dtype='int64')
        index_ivf.search_preassigned(
            n, faiss.swig_ptr(xq), k,
            faiss.swig_ptr(list_nos), faiss.swig_ptr(coarse_dis),
            faiss.swig_ptr(D), faiss.swig_ptr(I), False)
        return D, I

    def ivf_range_search_preassigned(self, xq, list_nos, coarse_dis, radius):
        index_ivf = faiss.extract_index_ivf(self.index)
        n, d = xq.shape
        assert d == index_ivf.d
        n2, d2 = list_nos.shape
        assert list_nos.shape == coarse_dis.shape
        assert n2 == n
        assert d2 == index_ivf.nprobe
        res = faiss.RangeSearchResult(n)

        index_ivf.range_search_preassigned(
            n, faiss.swig_ptr(xq), radius,
            faiss.swig_ptr(list_nos), faiss.swig_ptr(coarse_dis),
            res)

        lims = faiss.rev_swig_ptr(res.lims, n + 1).copy()
        nd = int(lims[-1])
        D = faiss.rev_swig_ptr(res.distances, nd).copy()
        I = faiss.rev_swig_ptr(res.labels, nd).copy()
        return lims, D, I

    def set_nprobe(self, nprobe):
        index_ivf = faiss.extract_index_ivf(self.index)
        index_ivf.nprobe = nprobe

    def set_parallel_mode(self, pm):
        index_ivf = faiss.extract_index_ivf(self.index)
        index_ivf.parallel_mode = pm

    def get_ntotal(self):
        return self.index.ntotal

    def set_prefetch_nthread(self, nt):
        for idx in self.indexes:
            il = faiss.downcast_InvertedLists(
                faiss.extract_index_ivf(idx).invlists)
            il.prefetch_nthread
            il.prefetch_nthread = nt

    def set_omp_num_threads(self, nt):
        faiss.omp_set_num_threads(nt)

class CombinedIndexDeep1B(CombinedIndex):
    """ loads a CombinedIndex with the data from the big photodna index """

    def __init__(self):
        # set some paths
        workdir = "/checkpoint/matthijs/ondisk_distributed/"

        # empty index with the proper quantizer
        indexfname = workdir + 'trained.faissindex'

        # index that has some invlists that override the big one
        masked_index_fname = None
        invlist_fnames = [
            '%s/hslices/slice%d.faissindex' % (workdir, i)
            for i in range(50)
        ]
        CombinedIndex.__init__(self, invlist_fnames, indexfname, masked_index_fname)

def ivecs_read(fname):
    a = np.fromfile(fname, dtype='int32')
    d = a[0]
    return a.reshape(-1, d + 1)[:, 1:].copy()

def fvecs_read(fname):
    return ivecs_read(fname).view('float32')

if __name__ == '__main__':
    import time
    ci = CombinedIndexDeep1B()
    print('loaded index of size ', ci.index.ntotal)

    deep1bdir = "/datasets01_101/simsearch/041218/deep1b/"

    xq = fvecs_read(deep1bdir + "deep1B_queries.fvecs")
    gt_fname = deep1bdir + "deep1B_groundtruth.ivecs"
    gt = ivecs_read(gt_fname)

    for nprobe in 1, 10, 100, 1000:
        ci.set_nprobe(nprobe)
        t0 = time.time()
        D, I = ci.search(xq, 100)
        t1 = time.time()
        print('nprobe=%d 1-recall@1=%.4f t=%.2fs' % (
            nprobe, (I[:, 0] == gt[:, 0]).sum() / len(xq),
            t1 - t0
        ))


text:
{-# LANGUAGE InstanceSigs #-}

module Koan.State where

enrolled :: Bool
enrolled = False

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
  fmap :: (a -> b) -> State s a -> State s b
  fmap = error "TODO: Implement fmap in Functor (State s) instance"

instance Applicative (State s) where
    pure :: a -> State s a
    pure = error "TODO: Implement pure in Applicative (State s) instance"

    (<*>) :: State s (a -> b) -> State s a -> State s b
    (<*>) = error "TODO: Implement (<*>) in Applicative (State s) instance"

instance Monad (State s) where
    (>>=) :: State s a -> (a -> State s b) -> State s b
    (>>=) = error "TODO: Implement (>>=) in Monad (State s) instance"

get :: State s s
get = error "TODO: Implement get"

put :: s -> State s ()
put = error "TODO: Implement put"

modify :: (s -> s) -> State s ()
modify = error "TODO: Implement modify"


text:
import os.path
import pandas as pd
import sys

from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn import linear_model, neighbors, tree
from sklearn.neural_network import MLPClassifier

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from github_analysis_tool.analyzer.analysis_utilities import AnalysisUtilities
from github_analysis_tool.analyzer.classification import Classification
from github_analysis_tool.analyzer.network_analysis import NetworkAnalysis
from github_analysis_tool import OssConstants

class Classify:
    def __init__(self):
        self.network_analysis = NetworkAnalysis()
        self.analysis_utilities = AnalysisUtilities()
        self.classification = Classification()

        # Create list of desired labellings
        self.label_funcs = self.__create_label_funcs()  # {func:<labelling_function(df)>, name:<String>}
        # Create data frames
        self.data_sets = self.__create_data_sets()  # {df:<DataFrame>, name:<String>}
        # Create classifiers
        self.classifiers = self.__create_classifiers()  # {func:<Classifying method>, name:<String}
        # construct configurations
        self.configurations = self.__create_configurations()

    def __create_label_funcs(self):
        label_funcs = list()
        label_funcs.append({"func": self.classification.set_language_labels,
                            "name": "languageLabels"})
        label_funcs.append({"func": self.classification.set_two_class_language_labels,
                            "name": "twoClassLanguageLabels"})
        return label_funcs

    def __create_data_sets(self):
        data_sets = list()
        # File metrics data frame
        file_df = pd.read_csv(OssConstants.FILE_METRICS_PATH, sep=';', index_col=0)
        data_sets.append({"df": file_df,
                          "name": "fileMetric"})
        # Commit metrics data frame
        commit_df = pd.read_csv(OssConstants.COMMIT_METRICS_PATH, sep=';', index_col=0)
        data_sets.append({"df": commit_df,
                          "name": "commitMetric"})
        # Repo stats data frame
        repo_df = self.analysis_utilities.get_repo_stats_df()
        # File + commit metrics data frame
        file_commit_df = self.analysis_utilities.merge_dfs_on_indexes(file_df, commit_df, "_file", "_commit")
        data_sets.append({"df": file_commit_df,
                          "name": "fileMetric,CommitMetric"})
        # file + repo stats data frame
        file_repo_df = self.analysis_utilities.merge_dfs_on_indexes(file_df, repo_df, "", "")
        data_sets.append({"df": file_repo_df,
                          "name": "fileMetric,repoStat"})
        # commit + repo stats data frame
        commit_repo_df = self.analysis_utilities.merge_dfs_on_indexes(commit_df, repo_df, "", "")
        data_sets.append({"df": commit_repo_df,
                          "name": "commitMetric,repoStat"})
        # all
        file_commit_repo_df = self.analysis_utilities.merge_dfs_on_indexes(file_commit_df, repo_df)
        data_sets.append({"df": file_commit_repo_df,
                          "name": "fileMetric,commitMetric,repoStat"})

        return data_sets

    def __create_classifiers(self):
        classifiers = list()
        classifiers.append({"func": linear_model.SGDClassifier(loss="log"),
                            "name": "sgd"})
        classifiers.append({"func": neighbors.KNeighborsClassifier(1, weights='distance'),
                            "name": "knn1"})
        classifiers.append({"func": neighbors.KNeighborsClassifier(3, weights='distance'),
                            "name": "knn3"})
        classifiers.append({"func": neighbors.KNeighborsClassifier(5, weights='distance'),
                            "name": "knn5"})
        classifiers.append({"func": GaussianNB(),
                            "name": "naive_bayes"})

        # classifiers.append({"func": tree.DecisionTreeClassifier(), "name": "decision_tree"})
        # classifiers.append({"func": MLPClassifier(max_iter=10000), "name": "mlp"})
        # classifiers.append({"func": RandomForestClassifier(), "name": "random_forest"})
        return classifiers

    def __create_configurations(self):
        configurations = list()
        configurations.append({"sampling": False, "normalize": False})
        configurations.append({"sampling": False, "normalize": True})
        configurations.append({"sampling": True, "normalize": False})
        configurations.append({"sampling": True, "normalize": True})
        return configurations

    def start_classifying(self):
        print("--> Classification started")

        for label_func in self.label_funcs:
            for data_set in self.data_sets:
                for conf in self.configurations:
                    self.network_analysis.do_classification(classifiers=self.classifiers,
                                                       df=data_set["df"], df_name=data_set["name"],
                                                       labelling_func=label_func["func"],
                                                       labelling_name=label_func["name"],
                                                       sampling=conf["sampling"], normalize=conf["normalize"])

        print("--> Classification finished calculation finished")

if __name__ == "__main__":
    classify = Classify()
    classify.start_classifying()


text:
"""Utility functions for tabular MDPs and CMDPs."""
from typing import Tuple

from absl import logging
import cvxopt
import jax
import jax.config
import numpy as np
import scipy
import scipy.optimize

cvxopt.solvers.options['show_progress'] = False
jax.config.update('jax_enable_x64', True)

class MDP:
  """MDP class."""

  def __init__(self,
               num_states: int,
               num_actions: int,
               transition: np.ndarray,
               reward: np.ndarray,
               gamma: float):
    """MDP Constructor.

    Args:
      num_states: the number of states.
      num_actions: the number of actions.
      transition: transition matrix. [num_states, num_actions, num_states].
      reward: reward function. [num_states, num_actions]
      gamma: discount factor (0 ~ 1).
    """
    self.num_states = num_states
    self.num_actions = num_actions
    self.transition = np.array(transition)
    self.reward = np.array(reward)
    self.gamma = gamma
    self.initial_state = 0
    self.absorbing_state = num_states - 1
    assert self.transition.shape == (num_states, num_actions, num_states)
    assert self.reward.shape == (num_states, num_actions)

  def __copy__(self):
    mdp = MDP(
        num_states=self.num_states,
        num_actions=self.num_actions,
        transition=np.array(self.transition),
        reward=np.array(self.reward),
        gamma=self.gamma)
    return mdp

class CMDP(MDP):
  """Constrained MDP class."""

  def __init__(self,
               num_states: int,
               num_actions: int,
               num_costs: int,
               transition: np.ndarray,
               reward: np.ndarray,
               costs: np.ndarray,
               cost_thresholds: np.ndarray,
               gamma: float):
    """Constrained MDP Constructor.

    Args:
      num_states: the number of states.
      num_actions: the number of actions.
      num_costs: the number of cost types.
      transition: transition matrix. [num_states, num_actions, num_states].
      reward: reward function. [num_states, num_actions]
      costs: cost function. [num_costs, num_states, num_actions]
      cost_thresholds: cost thresholds. [num_costs]
      gamma: discount factor (0 ~ 1).
    """
    assert len(cost_thresholds) == num_costs
    super(CMDP, self).__init__(num_states, num_actions, transition, reward,
                               gamma)
    self.num_costs = num_costs
    self.costs = np.array(costs)
    self.cost_thresholds = np.array(cost_thresholds)
    assert self.costs.shape == (num_costs, num_states, num_actions)

  def __copy__(self):
    cmdp = CMDP(
        num_states=self.num_states,
        num_actions=self.num_actions,
        num_costs=self.num_costs,
        transition=np.array(self.transition),
        reward=np.array(self.reward),
        costs=np.array(self.costs),
        cost_thresholds=np.array(self.cost_thresholds),
        gamma=self.gamma)
    return cmdp

def generate_random_cmdp(num_states: int, num_actions: int, num_costs: int,
                         cost_thresholds: np.ndarray, gamma: float):
  """Create a random CMDP.

  Args:
    num_states: the number of states.
    num_actions: the number of actions.
    num_costs: the number of cost types.
    cost_thresholds: cost thresholds. [num_costs]
    gamma: discount factor (0 ~ 1).

  Returns:
    a CMDP instance.
  """
  assert len(cost_thresholds) == num_costs
  if num_costs != 1:
    raise NotImplementedError('Only support when num_costs=1')
  initial_state = 0
  absorbing_state = num_states - 1  # the absorbing state index.

  # Define a random transition.
  transition = np.zeros((num_states, num_actions, num_states))
  for s in range(num_states):
    if s == absorbing_state:
      transition[s, :, s] = 1  # absorbing state: self-transition
    else:
      for a in range(num_actions):
        # Transition to next states is defined sparsely.
        # For each (s,a), the connectivity to the next states is 4.
        p = np.r_[np.random.dirichlet([1, 1, 1, 1]), [0] * (num_states - 4 - 1)]
        np.random.shuffle(p)
        transition[s, a, :] = np.r_[p, [0]]

  # Define a reward function. Roughly speaking, a non-zero reward is given
  # to the state which is most difficult to reach from the initial state.
  min_value_state, min_value = -1, 1e10
  for s in range(num_states - 1):
    reward = np.zeros((num_states, num_actions))
    reward[s, :] = 1 / (1 - gamma)
    transition_tmp = np.array(transition[s, :, :])
    transition[s, :, :] = 0
    transition[s, :, absorbing_state] = 1  # from goal_state to absorbing state
    mdp = MDP(num_states, num_actions, transition, reward, gamma)
    _, v, _ = solve_mdp(mdp)
    if v[initial_state] < min_value:
      min_value = v[initial_state]
      min_value_state = s
    transition[s, :, :] = transition_tmp
  # min_value_state will be the goal state that yields a non-zero reward.
  goal_state = min_value_state
  reward = np.zeros((num_states, num_actions))
  reward[goal_state, :] = 1 / (1 - gamma)
  transition[goal_state, :, :] = 0
  transition[goal_state, :, absorbing_state] = 1  # to absorbing one

  # Define a cost function.
  while True:
    costs = np.random.beta(0.2, 0.2, (num_costs, num_states, num_actions))
    # For each state, there exists a no-cost action.
    for s in range(num_states):
      a_no_cost = np.random.randint(0, num_actions)
      costs[:, s, a_no_cost] = 0
    costs[:, absorbing_state, :] = 0
    cmdp = CMDP(num_states, num_actions, num_costs, transition, reward, costs,
                cost_thresholds, gamma)
    pi_copt = solve_cmdp(cmdp)
    v_c_opt = policy_evaluation(cmdp, pi_copt)[2][0, 0]
    if v_c_opt >= cost_thresholds[0] - 1e-4:
      # We want that optimal policy tightly matches the cost constraint.
      break

  cmdp = CMDP(num_states, num_actions, num_costs, transition, reward, costs,
              cost_thresholds, gamma)
  return cmdp

def policy_evaluation_mdp(mdp: MDP,
                          pi: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  """Policy evaluation (normalized value) for pi in the given MDP.

  Args:
    mdp: MDP instance.
    pi: a stochastic policy. [num_states, num_actions]

  Returns:
    (V_R, Q_R)
  """
  reward = mdp.reward * (1 - mdp.gamma)  # normalized value
  r = np.sum(mdp.reward * pi, axis=-1)
  p = np.sum(pi[:, :, None] * mdp.transition, axis=1)
  v = np.linalg.inv(np.eye(mdp.num_states) - mdp.gamma * p).dot(r)
  q = reward + mdp.gamma * mdp.transition.dot(v)
  return v, q

def policy_evaluation(
    cmdp: CMDP,
    pi: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
  """Policy evaluation (normalized value) for pi in the given CMDP.

  Args:
    cmdp: CMDP instance.
    pi: a stochastic policy. [num_states, num_actions]

  Returns:
    (V_R, Q_R, V_C, Q_C)
  """
  def compute(transition, reward, pi):
    reward = reward * (1 - cmdp.gamma)  # normalized value
    r = np.sum(reward * pi, axis=-1)
    p = np.sum(pi[:, :, None] * transition, axis=1)
    v = np.linalg.inv(np.eye(cmdp.num_states) - cmdp.gamma * p).dot(r)
    q = reward + cmdp.gamma * cmdp.transition.dot(v)
    return v, q

  v_r, q_r = compute(cmdp.transition, cmdp.reward, pi)
  v_cs = np.zeros((cmdp.num_costs, cmdp.num_states))
  q_cs = np.zeros((cmdp.num_costs, cmdp.num_states, cmdp.num_actions))
  for k in range(cmdp.num_costs):
    v_c, q_c = compute(cmdp.transition, cmdp.costs[k], pi)
    v_cs[k] = v_c
    q_cs[k] = q_c
  return v_r, q_r, v_cs, q_cs

def solve_mdp(mdp: MDP):
  """Solve MDP via policy iteration.

  Args:
    mdp: an MDP instance.

  Returns:
    (pi, V_R, Q_R).
  """
  pi = np.ones((mdp.num_states, mdp.num_actions)) / mdp.num_actions
  v_old = np.zeros(mdp.num_states)

  for _ in range(1_000_000):
    v, q = policy_evaluation_mdp(mdp, pi)
    pi_new = np.zeros((mdp.num_states, mdp.num_actions))
    pi_new[np.arange(mdp.num_states), np.argmax(q, axis=1)] = 1.

    if np.all(pi == pi_new) or np.max(np.abs(v - v_old)) < 1e-8:
      break
    v_old = v
    pi = pi_new

  if not np.all(pi == pi_new):
    logging.info('Warning: policy iteration process did not converge.')
  return pi, v, q

def generate_trajectory(seed: int,
                        cmdp: CMDP,
                        pi: np.ndarray,
                        num_episodes: int = 10,
                        max_timesteps: int = 50):
  """Generate trajectories using the policy in the CMDP.

  Args:
    seed: random seed.
    cmdp: CMDP instance.
    pi: a stochastic policy. [num_states, num_actions]
    num_episodes: the number of episodes to generate.
    max_timesteps: the maximum timestep within an episode.

  Returns:
    trajectory: list of list of (episode_idx, t, s_t, a_t, r_t, c_t, s_t').
  """
  if seed is not None:
    np.random.seed(seed + 1)

  def random_choice_prob_vectorized(p):
    """Batch random_choice.

    e.g. p = np.array([
        [0.1, 0.5, 0.4],
        [0.8, 0.1, 0.1]])

    Args:
      p: batch of probability vector.

    Returns:
      Sampled indices
    """
    r = np.expand_dims(np.random.rand(p.shape[0]), axis=1)
    return (p.cumsum(axis=1) > r).argmax(axis=1)

  trajectory = [[] for i in range(num_episodes)]
  done = np.zeros(num_episodes, dtype=np.bool)
  state = np.array([cmdp.initial_state] * num_episodes)
  for t in range(max_timesteps):
    action = random_choice_prob_vectorized(p=pi[state, :])
    reward = cmdp.reward[state, action]
    costs = cmdp.costs[:, state, action]
    state1 = random_choice_prob_vectorized(p=cmdp.transition[state, action, :])
    for i in range(num_episodes):
      if not done[i]:
        trajectory[i].append(
            (i, t, state[i], action[i], reward[i], costs[:, i], state1[i]))
    done = done | (state == cmdp.absorbing_state)

    state = state1

  return trajectory

def compute_mle_cmdp(num_states: int,
                     num_actions: int,
                     num_costs: int,
                     reward: np.ndarray,
                     costs: np.ndarray,
                     cost_thresholds: np.ndarray,
                     gamma: float,
                     trajectory,
                     absorb_unseen: bool = True) -> Tuple[CMDP, np.ndarray]:
  """Construct a maximum-likelihood estimation CMDP from the trajectories.

  Args:
    num_states: the number of states.
    num_actions: the number of actions.
    num_costs: the number of costs.
    reward: reward function.
    costs: cost function.
    cost_thresholds: cost thresholds.
    gamma: discount factor (0~1).
    trajectory: trajectories collected by a behavior policy.
      list of list of (episode_idx, t, s_t, a_t, r_t, c_t, s_t').
    absorb_unseen: for unvisited s, whether to use transition to absorbing
      state. If False, uniform transition is used.

  Returns:
    (MLE CMDP, visitation count matrix)
  """
  absorbing_state = num_states - 1
  n = np.zeros((num_states, num_actions, num_states))
  for trajectory_one in trajectory:
    # episode, t, s, a, r, c, s1
    for _, _, s, a, _, _, s1 in trajectory_one:
      n[s, a, s1] += 1

  transition = np.zeros((num_states, num_actions, num_states))
  for s in range(num_states):
    for a in range(num_actions):
      if n[s, a, :].sum() == 0:
        if absorb_unseen:
          transition[s, a, absorbing_state] = 1  # absorbing state
        else:
          transition[s, a, :] = 1. / num_states
      else:
        transition[s, a, :] = n[s, a, :] / n[s, a, :].sum()

  mle_cmdp = CMDP(num_states, num_actions, num_costs, transition, reward, costs,
                  cost_thresholds, gamma)

  return mle_cmdp, n

def solve_cmdp(cmdp: CMDP):
  """Solve CMDP via linear programming.

  Args:
    cmdp: a CMDP instance.

  Returns:
    optimal policy.
  """
  c = -cmdp.reward.reshape(cmdp.num_states * cmdp.num_actions)
  p0 = np.zeros(cmdp.num_states)
  p0[cmdp.initial_state] = 1
  p = cmdp.transition.reshape(cmdp.num_states * cmdp.num_actions,
                              cmdp.num_states)  # |S||A| x |S|
  p = p / np.sum(p, axis=1, keepdims=True)
  b = np.repeat(
      np.eye(cmdp.num_states), cmdp.num_actions, axis=0)  # |S||A| x |S|

  a_eq = (b - cmdp.gamma * p).T
  b_eq = (1 - cmdp.gamma) * p0
  a_ub = cmdp.costs.reshape(cmdp.num_costs, cmdp.num_states * cmdp.num_actions)
  b_ub = cmdp.cost_thresholds

  #  Minimize::
  #     c @ x
  # Subject to::
  #     A_ub @ x <= b_ub
  #     A_eq @ x == b_eq
  #      lb <= x <= ub
  # where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
  res = scipy.optimize.linprog(
      c,
      A_ub=a_ub,
      b_ub=b_ub,
      A_eq=a_eq,
      b_eq=b_eq,
      bounds=(0, np.inf),
      options={
          'maxiter': 10000,
          'tol': 1e-8
      })
  assert np.all(res.x >= -1e-4)

  d = np.clip(res.x.reshape(cmdp.num_states, cmdp.num_actions), 1e-10, np.inf)
  pi = d / np.sum(d, axis=1, keepdims=True)
  return pi


text:
import React from 'react';
import { render } from '@testing-library/react';
import AddRole from '../../../components/role/AddRole';
import API from "../../../api";

describe('AddRole', () => {
    it('should render', () => {
        let domain = 'domain';

        const { getByTestId } = render(
            <AddRole
                api={API()}
                domain={domain}
                justificationRequired={true}
            />
        );
        const addRoleForm = getByTestId('add-role');
        expect(addRoleForm).toMatchSnapshot();
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/PPLUtils.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/PPLUtils</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>PPLUtils.h</DeclaredIn>

			<NodeRef refid="7"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/PPLUtils/sharedInstance</TokenIdentifier>
			<Abstract type="html">Method to get singleton instance for PPUtils class</Abstract>
			<DeclaredIn>PPLUtils.h</DeclaredIn>

			<Declaration>+ (PPLUtils *)sharedInstance</Declaration>

			<ReturnValue><Abstract type="html">a new created instance or an existing one</Abstract></ReturnValue>
			<Anchor>//api/name/sharedInstance</Anchor>
            <NodeRef refid="7"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/PPLUtils/getUniqueId</TokenIdentifier>
			<Abstract type="html">Function to get unique ID for this device, this is used for submitting
feedback to the server</Abstract>
			<DeclaredIn>PPLUtils.h</DeclaredIn>

			<Declaration>- (NSString *)getUniqueId</Declaration>

			<ReturnValue><Abstract type="html">unique ID for this device</Abstract></ReturnValue>
			<Anchor>//api/name/getUniqueId</Anchor>
            <NodeRef refid="7"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/PPLUtils/showLaunch:</TokenIdentifier>
			<Abstract type="html">This function shows the launch screen which has instructions</Abstract>
			<DeclaredIn>PPLUtils.h</DeclaredIn>

			<Declaration>- (void)showLaunch:(UIViewController *)sender</Declaration>
			<Parameters>
				<Parameter>
					<Name>sender</Name>
					<Abstract type="html">Initiator for this function</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/showLaunch:</Anchor>
            <NodeRef refid="7"/>
		</Token>

	</File>
</Tokens>


text:
    <button type="submit" class="btn btn-primary" (click)="tournament()">Správa turnajů</button>
    <button type="submit" class="btn btn-secondary" (click)="team()">Správa oddílů</button>
    <button type="submit" class="btn btn-warning" (click)="user()">Správa uživatelů</button>
    <button type="submit" class="btn btn-light" (click)="nationality()">Správa národností</button>
    <button type="submit" class="btn btn-secondary" (click)="export()">Export dle filtrů</button>

        <button class="close" (click)="modal.hide()" aria-label="Close">
          ×
        </button>

Úprava uživatele

Vytvořit nového uživatele

Úprava oddílu

Vytvořit nový oddíl

Úprava turnaje

Vytvořit nový turnaj

Úprava narodnosti

Vytvořit novou narodnost

        <form *ngIf='type=="team"' [formGroup]="teamForm" novalidate (submit)="team(true)">
          <input type='hidden' formControlName='id' />

            Název
            <input type="text" class="form-control" formControlName='name' id="name" placeholder="Název oddílu">

            Založeno
            <input type="date" class="form-control" formControlName='founded_at' id="founded_at">

            Město
            <input type="text" class="form-control" formControlName='city' id="city" placeholder="Sídlí ve městě">

            Web
            <input type="text" class="form-control" formControlName='www' id="www" placeholder="http://">

        </form>
        <form *ngIf='type=="user"' [formGroup]="userForm" novalidate (submit)="user(true)" autocomplete="off">
          <input type='hidden' formControlName='id' />

            E-mail
            <input type="text" class="form-control" formControlName='email' id="email">

            Heslo
            <input type="text" class="form-control" formControlName='password' id="password">

            Přihlašovací jméno
            <input type="text" class="form-control" formControlName='login' id="login" placeholder="agentXY">

            Oddíly (ctrl+click pro více oddílů)
            <select multiple class="form-control" formControlName='privileges' id="privileges">
              <option *ngFor='let team of teamsOptions|order:["title"]' value='{{team.value}}'>{{team.title}}</option>
            </select>

        </form>
        <form *ngIf='type=="nationality"' [formGroup]="nationalityForm" novalidate (submit)="nationality(true)" autocomplete="off">
          <input type='hidden' formControlName='id' />

            Název
            <input type="text" class="form-control" formControlName='name'>

            Stát
            <input type="text" class="form-control" formControlName='country_name'>

        </form>
        <form [formGroup]="tournamentForm" novalidate (submit)="tournament(true)" *ngIf='type=="tournament"'>
          <input type='hidden' formControlName='id' />

                Název
                <input type="text" class="form-control" formControlName='name' id="name" placeholder="Název turnaje">

                Lokace
                <input type="text" class="form-control" formControlName='location' id="location" placeholder="Lokace turnaje">

                Datum
                <input type="date" class="form-control" formControlName='date' id="date">

                Trvání (dny)
                <input type="number" class="form-control" formControlName='duration' id="duration">

                Sezóna
                <select class="form-control" formControlName='season_id' id="season_id">
                  <option *ngFor='let season of seasons|order:["name"]' value='{{season.id}}'>{{season.name}}</option>
                </select>

                Divize
                <select multiple="true" class="form-control" formControlName='division_ids' id="division_ids">
                  <option *ngFor='let division of server.divisions|order:["name"]' value='{{division.id}}'>{{division.name}}</option>
                </select>

                Liga
                <select multiple="true" class="form-control" formControlName='league_ids' id="league_ids">
                  <option *ngFor='let league of server.leagues|order:["name"]' value='{{league.id}}'>{{league.name}}</option>
                </select>

        </form>

        <button *ngIf='type=="nationality"' [hidden]='sending' [disabled]='nationalityForm.invalid' class="btn btn-primary confirm-btn" (click)="saveNationality()">Uložit</button>
        <button *ngIf='type=="user"' [hidden]='sending' [disabled]='userForm.invalid' class="btn btn-primary confirm-btn" (click)="saveUser()">Uložit</button>
        <button *ngIf='type=="team"' [hidden]='sending' [disabled]='teamForm.invalid' class="btn btn-primary confirm-btn" (click)="saveTeam()">Uložit</button>
        <button *ngIf='type=="tournament"' [hidden]='sending' [disabled]='tournamentForm.invalid' class="btn btn-primary confirm-btn" (click)="saveTournament()">Uložit</button>

    <ba-card title="Seznam uživatelů" baCardClass="with-scroll" *ngIf='type=="user"'>
      <ng2-smart-table [settings]="settings.user" (create)="openUserForm($event,true)" (edit)="openUserForm($event)" [source]="source.user"></ng2-smart-table>
    </ba-card>
    <ba-card title="Seznam oddílů" baCardClass="with-scroll" *ngIf='type=="team"'>
      <ng2-smart-table [settings]="settings.team" (create)="openTeamForm($event,true)" (edit)="openTeamForm($event)" [source]="source.team"></ng2-smart-table>
    </ba-card>
    <ba-card title="Seznam národností" baCardClass="with-scroll" *ngIf='type=="nationality"'>
      <ng2-smart-table [settings]="settings.nationality" (delete)="deleteNationality($event)" (create)="openNationalityForm($event)" (edit)="openNationalityForm($event)" [source]="source.nationality"></ng2-smart-table>
    </ba-card>
    <ba-card title="Seznam turnajů" baCardClass="with-scroll" *ngIf='type=="tournament"'>
      <ng2-smart-table [settings]="settings.tournament" (delete)="deleteTournament($event)" (create)="openTournamentForm($event,true)" (edit)="openTournamentForm($event)" [source]="source.tournament"></ng2-smart-table>
    </ba-card>
    <ba-card title="Export do CSV" baCardClass="with-scroll" *ngIf='type=="export"'>

              Pohlaví
              <select formControlName='sex' id='sex'>
                <option value='' selected='selected'>-- nemá vliv --</option>
                <option value='male'>Muž</option>
                <option value='female'>Žena</option>
              </select>

              Rok narození
              <select formControlName='birth_date_comparator' id='birth_date_comparator'>
                <option value='=='>==</option>
                <option value='<'><</option>
                <option value='<='><=</option>
                <option value='>'>></option>
                <option value='>='>>=</option>
              </select>
              <input type='text' class="form-control"  formControlName='birth_date' size='4' placeholder='1987' />

              Aktivní v sezonách
              <input type='checkbox' formControlName='active_in_seasons_allowed'/>
              <select multiple class="form-control" formControlName='active_in_seasons' id="active_in_seasons">
                <option *ngFor='let season of seasons|order:["-name"]' value='{{season.id}}'>{{season.name}}</option>
              </select>

      <button *ngIf='type=="export"' [hidden]='sending' [disabled]='exportForm.invalid' class="btn btn-primary confirm-btn" (click)="exportByFilter()">Exportovat dle filtru</button>

    </ba-card>


text:
(function() {
  var Flow, FlowStep, flow,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __slice = [].slice;

  FlowStep = (function() {

    function FlowStep(func, lastReturn, state, callback) {
      this.callback = callback;
      this.next = __bind(this.next, this);

      this._next = __bind(this._next, this);

      this.spawn = __bind(this.spawn, this);

      this.raise = __bind(this.raise, this);

      if (!(state.catchExceptions != null)) {
        state.catchExceptions = true;
      }
      this.state = state;
      state.next = this.next;
      state.spawn = this.spawn;
      state.raise = this.raise;
      this.threads = [];
      this._unjoinedThreadCount = 1;
      if (this.state.catchExceptions) {
        try {
          lastReturn.unshift(state);
          func.apply(null, lastReturn);
        } catch (ex) {
          if (this.state.catchExceptions) {
            this.callback([ex]);
          } else {
            throw ex;
          }
        }
      } else {
        lastReturn.unshift(state);
        func.apply(null, lastReturn);
      }
    }

    FlowStep.prototype.raise = function(ex) {
      this.state.catchExceptions = false;
      if (typeof ex === "undefined" || ex === null) {
        throw "Can not raise null or undefined exception. Call to step.raise() has failed!";
      }
      throw ex;
    };

    FlowStep.prototype.spawn = function() {
      var threadId,
        _this = this;
      this._unjoinedThreadCount++;
      threadId = this.threads.length;
      this.threads.push([null]);
      return function() {
        var args;
        args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
        args.unshift(null);
        _this.threads[threadId] = args;
        _this._unjoinedThreadCount--;
        return _this._next();
      };
    };

    FlowStep.prototype._next = function() {
      if (this._unjoinedThreadCount === 0) {
        if (this.threads.length === 1) {
          this.threads = this.threads[0];
        }
        return this.callback(this.threads);
      }
    };

    FlowStep.prototype.next = function() {
      if (arguments.length > 0) {
        this.spawn().apply(null, arguments);
      }
      this._unjoinedThreadCount--;
      this._next();
    };

    return FlowStep;

  })();

  Flow = (function() {

    function Flow(steps, state, callback) {
      this.steps = steps;
      if (state == null) {
        state = null;
      }
      if (callback == null) {
        callback = null;
      }
      this.run = __bind(this.run, this);

      if (!(callback != null)) {
        callback = state;
        state = null;
      }
      if (!(callback != null)) {
        callback = function() {};
      }
      if (!(state != null)) {
        state = {};
      }
      this.steps.push(callback);
      this.state = state;
    }

    Flow.prototype.run = function() {
      var i, _run,
        _this = this;
      i = -1;
      _run = function(lastReturn) {
        var step;
        i++;
        if (i < _this.steps.length) {
          return step = new FlowStep(_this.steps[i], lastReturn, _this.state, _run);
        }
      };
      _run([null]);
    };

    return Flow;

  })();

  flow = function(steps, state, callback) {
    (new Flow(steps, state, callback)).run();
  };

  if (typeof module !== 'undefined') {
    module.exports = flow;
  } else {
    window.funcflow = flow;
  }

}).call(this);


text:
#import "NSTextView.h"

@interface NSTextView (PBXIndentation)
- (void)processOpenBrace:(id)arg1;
@end


text:
title: Triptyque de Jean le Baptiste et de Jean l'Évangéliste de Hans Memling
slug: "page:20"
created: 24-09-2018, 20:28
date: 24-09-2018, 20:28
modified: 06-10-2018, 11:58
visible: false
routable: false
taxonomy:
    category: [saint-jean, fr]
shortcode-core:
    active: true
---
### Vision du trône du dieu et de la cour céleste: le vivant sur le trône et l'Agneau {.orange #apocalypse}

[1]: /bruges/hopital-saint-jean/saint-jean/page:2#renvoi-aristodeme "https://francois-vidit.com/docs/fr/saint-jean/page:2#renvoi-aristodeme"


text:
FOUNDATION_EXPORT double RouterVersionNumber;

//! Project version string for Router.
FOUNDATION_EXPORT const unsigned char RouterVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Router/PublicHeader.h>


text:
using namespace swift;

void PrettyStackTraceSILFunctionTransform::print(llvm::raw_ostream &out) const {
  out << "While running SILFunctionTransform \"" << SFT->getName()
      << "\" on SILFunction ";
  if (!SFT->getFunction()) {
    out << " <<null>>";
    return;
  }
  out << "\"";
  SFT->getFunction()->printName(out);
  out << "\".\n";
}

void PrettyStackTraceSILModuleTransform::print(llvm::raw_ostream &out) const {
  out << "While running SILModuleTransform \"" << SMT->getName() << "\".\n";
}


text:
"""
Created on Thu Feb 22 17:50:01 2018

@author: Dimitrije Markovic
"""

from torch import ones, zeros, arange
from torch.distributions import Categorical

from .agent import Discrete

__all__ = [
        'Random'
]

class Random(Discrete):
    """Agent with discrete number of actions.
    """
    def __init__(self, pars, runs=1, blocks=1, trials=10):

        na = pars['na']  # number of choices

        super(Random, self).__init__(runs, blocks, trials, na, 1, 1)

    def set_parameters(self, *args, **kwargs):
        """Set free model parameters.
        """
        pass

    def update_beliefs(self, *args):
        """Update beliefs about hidden states given some sensory stimuli and action outcomes.
        """
        pass

    def planning(self, *args, **kwargs):
        """Compute choice probabilities in current block and trial.
        """
        pass

    def sample_responses(self, *args):
        """Generate responses given response probability.
        """
        cat = Categorical(probs=ones(self.runs, self.na))

        return cat.sample()


text:
package im.actor.runtime.crypto.primitives.curve25519;

// Disabling Bounds checks for speeding up calculations

/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/

public class crypto_verify_32 {

    public static int crypto_verify_32(byte[] x, byte[] y) {
        int differentbits = 0;
        for (int count = 0; count < 32; count++) {
            differentbits |= (x[count] ^ y[count]);
        }
        return differentbits;
    }
}


text:
package org.kaazing.k3po.lang.internal.ast;

public class AstUnbindNode extends AstCommandNode {

    @Override
    public <R, P> R accept(Visitor<R, P> visitor, P parameter) {
        return visitor.visit(this, parameter);
    }
    @Override
    protected int hashTo() {
        return getClass().hashCode();
    }

    @Override
    protected boolean equalTo(AstRegion that) {
        return that instanceof AstUnbindNode;
    }

    @Override
    protected void describe(StringBuilder buf) {
        super.describe(buf);
        buf.append("unbind\n");
    }
}


text:
package com.qiibeta.bitmapviewsample.support;

import android.graphics.Bitmap;

public class Constants {
    public static final Bitmap.Config PREFERRED_CONFIG = Bitmap.Config.ARGB_8888;

    public static final int COLUMN_COUNT = 3;
}


text:
package example

import doobie._
import doobie.implicits._
import org.postgresql.geometric._
import doobie.postgres.implicits._

// Some queries to test using the AnalysisTestSpec in src/test
object AnalysisTest {

  final case class Country(name: String, indepYear: Int)

  def speakerQuery(lang: String, pct: Double): Query0[Country] =
    sql"""
      SELECT C.NAME, C.INDEPYEAR, C.CODE FROM COUNTRYLANGUAGE CL
      JOIN COUNTRY C ON CL.COUNTRYCODE = C.CODE
      WHERE LANGUAGE = $lang AND PERCENTAGE > $pct
    """.query[Country]

  val speakerQuery2 =
    sql"""
      SELECT C.NAME, C.INDEPYEAR, C.CODE FROM COUNTRYLANGUAGE CL
      JOIN COUNTRY C ON CL.COUNTRYCODE = C.CODE
    """.query[(String, Option[Short], String)]

  val arrayTest =
    sql"""
      SELECT ARRAY[1, 2, NULL] test
    """.query[Option[List[String]]]

  val arrayTest2 =
    sql"""
      SELECT ARRAY[1, 2, NULL] test
    """.query[String]

  val pointTest =
    sql"""
      SELECT '(1, 2)'::point test
    """.query[PGpoint]

  val pointTest2 = {
    Meta[PostgresPoint.Point] // why not? ... irritating that it must be instantiated. what to do?
    sql"""
      SELECT '(1, 2)'::point test
    """.query[PGcircle]
  }

  def update(code: String, name: Int): Update0 =
    sql"""
      UPDATE COUNTRY SET NAME = $name WHERE CODE = $code
    """.update

  val update2 =
    sql"""
      UPDATE COUNTRY SET NAME = 'foo' WHERE CODE = 'bkah'
    """.update

}


text:
<?php
$translations = array(
	'Login' => 'Entrar',
	'Logout successful.' => 'Sessão terminada com sucesso.',
	'Invalid credentials.' => 'Identificação inválida.',
	'Server' => 'Servidor',
	'Username' => 'Nome de utilizador',
	'Password' => 'Senha',
	'Select database' => 'Selecionar Base de dados',
	'Invalid database.' => 'Base de dados inválida.',
	'Table has been dropped.' => 'Tabela eliminada.',
	'Table has been altered.' => 'Tabela modificada.',
	'Table has been created.' => 'Tabela criada.',
	'Alter table' => 'Modificar estrutura',
	'Create table' => 'Criar tabela',
	'Table name' => 'Nome da tabela',
	'engine' => 'motor',
	'collation' => 'collation',
	'Column name' => 'Nome da coluna',
	'Type' => 'Tipo',
	'Length' => 'Tamanho',
	'Auto Increment' => 'Incremento Automático',
	'Options' => 'Opções',
	'Save' => 'Guardar',
	'Drop' => 'Remover',
	'Database has been dropped.' => 'Base de dados eliminada.',
	'Database has been created.' => 'Base de dados criada.',
	'Database has been renamed.' => 'Base de dados renomeada.',
	'Database has been altered.' => 'Base de dados modificada.',
	'Alter database' => 'Modificar Base de dados',
	'Create database' => 'Criar Base de dados',
	'SQL command' => 'Comando SQL',
	'Logout' => 'Terminar sessão',
	'database' => 'base de dados',
	'Use' => 'Usar',
	'No tables.' => 'Não existem tabelas.',
	'select' => 'registos',
	'Item has been deleted.' => 'Registo eliminado.',
	'Item has been updated.' => 'Registo modificado.',
	'Item%s has been inserted.' => 'Registo%s inserido.',
	'Edit' => 'Modificar',
	'Insert' => 'Inserir',
	'Save and insert next' => 'Guardar e inserir outro',
	'Delete' => 'Eliminar',
	'Database' => 'Base de dados',
	'Routines' => 'Procedimentos',
	'Indexes have been altered.' => 'Índices modificados.',
	'Indexes' => 'Índices',
	'Alter indexes' => 'Modificar índices',
	'Add next' => 'Adicionar próximo',
	'Language' => 'Idioma',
	'Select' => 'Selecionar',
	'New item' => 'Novo Registo',
	'Search' => 'Procurar',
	'Sort' => 'Ordenar',
	'descending' => 'decrescente',
	'Limit' => 'Limite',
	'No rows.' => 'Não existem registos.',
	'Action' => 'Ação',
	'edit' => 'modificar',
	'Page' => 'Página',
	'Query executed OK, %d row(s) affected.' => array('Consulta executada, %d registo afetado.', 'Consulta executada, %d registos afetados.'),
	'Error in query' => 'Erro na consulta',
	'Execute' => 'Executar',
	'Table' => 'Tabela',
	'Foreign keys' => 'Chaves estrangeiras',
	'Triggers' => 'Triggers',
	'View' => 'Visualizar',
	'Unable to select the table' => 'Não é possivel selecionar a Tabela',
	'Invalid CSRF token. Send the form again.' => 'Token CSRF inválido. Enviar o formulario novamente.',
	'Comment' => 'Comentário',
	'Default values' => 'Valores predeterminados',
	'%d byte(s)' => array('%d byte', '%d bytes'),
	'No commands to execute.' => 'Nenhum comando para executar.',
	'Unable to upload a file.' => 'Não é possível enviar o ficheiro.',
	'File upload' => 'Importar ficheiro',
	'File uploads are disabled.' => 'Importação de ficheiros desativada.',
	'Routine has been called, %d row(s) affected.' => array('Consulta executada, %d registo afetado.', 'Consulta executada, %d registos afetados.'),
	'Call' => 'Chamar',
	'No extension' => 'Não há extensão',
	'None of the supported PHP extensions (%s) are available.' => 'Nenhuma das extensões PHP suportadas (%s) está disponivel.',
	'Session support must be enabled.' => 'As sessões devem estar ativas.',
	'Session expired, please login again.' => 'Sessão expirada, por favor entre de novo.',
	'Text length' => 'Tamanho do texto',
	'Foreign key has been dropped.' => 'Chave estrangeira eliminada.',
	'Foreign key has been altered.' => 'Chave estrangeira modificada.',
	'Foreign key has been created.' => 'Chave estrangeira criada.',
	'Foreign key' => 'Chave estrangeira',
	'Target table' => 'Tabela de destino',
	'Change' => 'Modificar',
	'Source' => 'Origem',
	'Target' => 'Destino',
	'Add column' => 'Adicionar coluna',
	'Alter' => 'Modificar',
	'Add foreign key' => 'Adicionar Chave estrangeira',
	'ON DELETE' => 'ON DELETE',
	'ON UPDATE' => 'ON UPDATE',
	'Index Type' => 'Tipo de índice',
	'Column (length)' => 'coluna (tamanho)',
	'View has been dropped.' => 'Vista eliminada.',
	'View has been altered.' => 'Vista modificada.',
	'View has been created.' => 'Vista criada.',
	'Alter view' => 'Modificar vista',
	'Create view' => 'Criar vista',
	'Name' => 'Nome',
	'Process list' => 'Lista de processos',
	'%d process(es) have been killed.' => array('%d processo terminado.', '%d processos terminados.'),
	'Kill' => 'Parar',
	'Parameter name' => 'Nome de Parâmetro',
	'Database schema' => 'Esquema de Base de dados',
	'Create procedure' => 'Criar procedimento',
	'Create function' => 'Criar função',
	'Routine has been dropped.' => 'Procedimento eliminado.',
	'Routine has been altered.' => 'Procedimento modificado.',
	'Routine has been created.' => 'Procedimento criado.',
	'Alter function' => 'Modificar Função',
	'Alter procedure' => 'Modificar procedimento',
	'Return type' => 'Tipo de valor de regresso',
	'Add trigger' => 'Adicionar trigger',
	'Trigger has been dropped.' => 'Trigger eliminado.',
	'Trigger has been altered.' => 'Trigger modificado.',
	'Trigger has been created.' => 'Trigger criado.',
	'Alter trigger' => 'Modificar Trigger',
	'Create trigger' => 'Adicionar Trigger',
	'Time' => 'Tempo',
	'Event' => 'Evento',
	'%s version: %s through PHP extension %s' => 'Versão %s: %s através da extensão PHP %s',
	'%d row(s)' => array('%d registo', '%d registos'),
	'Remove' => 'Remover',
	'Are you sure?' => 'Tem a certeza?',
	'Privileges' => 'Privilégios',
	'Create user' => 'Criar utilizador',
	'User has been dropped.' => 'Utilizador eliminado.',
	'User has been altered.' => 'Utilizador modificado.',
	'User has been created.' => 'Utilizador criado.',
	'Hashed' => 'Hash',
	'Column' => 'Coluna',
	'Routine' => 'Rotina',
	'Grant' => 'Conceder',
	'Revoke' => 'Impedir',
	'Too big POST data. Reduce the data or increase the %s configuration directive.' => 'POST data demasiado grande. Reduza o tamanho ou aumente a diretiva de configuração %s.',
	'Logged as: %s' => 'Ligado como: %s',
	'Move up' => 'Mover para cima',
	'Move down' => 'Mover para baixo',
	'Functions' => 'Funções',
	'Aggregation' => 'Adições',
	'Export' => 'Exportar',
	'Output' => 'Saída',
	'open' => 'abrir',
	'save' => 'guardar',
	'Format' => 'Formato',
	'Tables' => 'Tabelas',
	'Data' => 'Dados',
	'Event has been dropped.' => 'Evento eliminado.',
	'Event has been altered.' => 'Evento modificado.',
	'Event has been created.' => 'Evento criado.',
	'Alter event' => 'Modificar Evento',
	'Create event' => 'Criar Evento',
	'At given time' => 'À hora determinada',
	'Every' => 'Cada',
	'Events' => 'Eventos',
	'Schedule' => 'Agenda',
	'Start' => 'Início',
	'End' => 'Fim',
	'Status' => 'Estado',
	'On completion preserve' => 'Preservar ao completar',
	'Tables and views' => 'Tabelas e vistas',
	'Data Length' => 'Tamanho de dados',
	'Index Length' => 'Tamanho de índice',
	'Data Free' => 'Espaço Livre',
	'Collation' => 'Colação',
	'Analyze' => 'Analizar',
	'Optimize' => 'Otimizar',
	'Check' => 'Verificar',
	'Repair' => 'Reparar',
	'Truncate' => 'Truncar',
	'Tables have been truncated.' => 'Tabelas truncadas (truncate).',
	'Rows' => 'Registos',
	',' => ' ',
	'0123456789' => '0123456789',
	'Tables have been moved.' => 'As Tabelas foram movidas.',
	'Move to other database' => 'Mover outra Base de dados',
	'Move' => 'Mover',
	'Engine' => 'Motor',
	'Save and continue edit' => 'Guardar e continuar a edição',
	'original' => 'original',
	'Tables have been dropped.' => 'As tabelas foram eliminadas.',
	'%d item(s) have been affected.' => array('%d item afetado.', '%d itens afetados.'),
	'whole result' => 'resultado completo',
	'Clone' => 'Clonar',
	'Maximum number of allowed fields exceeded. Please increase %s.' => 'Quantidade máxima de campos permitidos excedidos. Por favor aumente %s.',
	'Partition by' => 'Particionar por',
	'Partitions' => 'Partições',
	'Partition name' => 'Nome da Partição',
	'Values' => 'Valores',
	'%d row(s) have been imported.' => array('%d registo importado.', '%d registos importados.'),
	'anywhere' => 'qualquer local',
	'Import' => 'Importar',
	'Stop on error' => 'Parar em caso de erro',
	'%.3f s' => '%.3f s',
	'$1-$3-$5' => '$5/$3/$1',
	'[yyyy]-mm-dd' => 'dd/mm/[aaaa]',
	'History' => 'Histórico',
	'Variables' => 'Variáveis',
	'Source and target columns must have the same data type, there must be an index on the target columns and referenced data must exist.' => 'As colunas de origen e destino devem ser do mesmo tipo, deve existir um índice entre as colunas de destino e o registo referenciado deve existir.',
	'Relations' => 'Relações',
	'Run file' => 'Executar ficheiro',
	'Clear' => 'Limpar',
	'Maximum allowed file size is %sB.' => 'Tamanho máximo do ficheiro é %sB.',
	'Numbers' => 'Números',
	'Date and time' => 'Data e hora',
	'Strings' => 'Cadeia',
	'Binary' => 'Binário',
	'Lists' => 'Listas',
	'Editor' => 'Editor',
	'E-mail' => 'E-mail',
	'From' => 'De',
	'Subject' => 'Assunto',
	'Send' => 'Enviar',
	'%d e-mail(s) have been sent.' => array('%d email enviado.', '%d emails enviados.'),
	'Webserver file %s' => 'Ficheiro do servidor web %s',
	'File does not exist.' => 'Ficheiro não existe.',
	'%d in total' => '%d no total',
	'Permanent login' => 'Memorizar a senha',
	'Databases have been dropped.' => 'Bases de dados eliminadas.',
	'Search data in tables' => 'Pesquisar dados nas Tabelas',
	'Schema' => 'Esquema',
	'Alter schema' => 'Modificar esquema',
	'Create schema' => 'Criar esquema',
	'Schema has been dropped.' => 'Esquema eliminado.',
	'Schema has been created.' => 'Esquema criado.',
	'Schema has been altered.' => 'Esquema modificado.',
	'Sequences' => 'Sequências',
	'Create sequence' => 'Criar sequências',
	'Alter sequence' => 'Modificar sequência',
	'Sequence has been dropped.' => 'Sequência eliminada.',
	'Sequence has been created.' => 'Sequência criada.',
	'Sequence has been altered.' => 'Sequência modificada.',
	'User types' => 'Tipos definidos pelo utilizador',
	'Create type' => 'Criar tipo',
	'Alter type' => 'Modificar tipo',
	'Type has been dropped.' => 'Tipo eliminado.',
	'Type has been created.' => 'Tipo criado.',
	'Ctrl+click on a value to modify it.' => 'Ctrl+clique vezes sobre o valor para edita-lo.',
	'Use edit link to modify this value.' => 'Utilize o link modificar para alterar.',
	'last' => 'último',
	'From server' => 'Do servidor',
	'System' => 'Motor de Base de dados',
	'Select data' => 'Selecionar dados',
	'Show structure' => 'Mostrar estrutura',
	'empty' => 'vazio',
	'Network' => 'Rede',
	'Geometry' => 'Geometria',
	'File exists.' => 'Ficheiro já existe.',
	'Attachments' => 'Anexos',
	'%d query(s) executed OK.' => array('%d consulta sql executada corretamente.', '%d consultas sql executadas corretamente.'),
	'Show only errors' => 'Mostrar somente erros',
	'Refresh' => 'Atualizar',
	'Invalid schema.' => 'Esquema inválido.',
	'Please use one of the extensions %s.' => 'Por favor use uma das extensões %s.',
	'now' => 'agora',
	'ltr' => 'ltr',
);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- General -->

    <string name="app_name">Freezer</string>
    <string name="app_name_full">Freezer Manager</string>

    <!-- MainActivity -->

    <string name="main_action_sort">Sort</string>
    <string name="main_action_filter">Filter</string>
    <string name="main_action_settings">Settings</string>
    <string name="main_pick_sort">Sort by</string>
    <string name="main_no_items">Once you add food,\n you\'ll see it listed here</string>
    <string name="main_snackbar_defrost">\u0020defrosted</string>
    <string name="main_snackbar_defrost_undo">Undo</string>

    <string-array name="sort_options">
        <item>Name</item>
        <item>Size</item>
        <item>Freeze date</item>
        <item>Expiration date</item>
    </string-array>

    <!-- Item edit -->

    <string name="item_edit_title">Edit food</string>
    <string name="item_edit_title_create">Freeze food</string>
    <string name="item_edit_name">Name</string>
    <string name="item_edit_change_photo">Change</string>
    <string name="item_edit_freeze_date">Freeze date</string>
    <string name="item_edit_exp_date">Expiration date</string>
    <string name="item_edit_section_label">Section %1$d</string>
    <string name="item_edit_category">Category</string>
    <string name="item_edit_insert_name">Please insert a name</string>
    <string name="item_edit_done">Done</string>

    <!-- Item detail -->

    <string name="item_detail_size">%1$s:</string>
    <string name="item_detail_freeze_date">Freeze date:</string>
    <string name="item_detail_exp_date">Expiration date:</string>
    <string name="item_detail_section">Section:</string>
    <string name="item_detail_category">Category:</string>
    <string name="item_detail_edit">Edit</string>

    <!-- Settings -->

    <string name="title_activity_settings">Settings</string>

    <string name="pref_header_layout">Freezer layout</string>
    <string name="pref_title_sections">Number of sections</string>

    <string name="pref_header_notifications">Notifications</string>
    <string name="pref_title_notification_expiration">Notify before expiration</string>
    <string-array name="pref_before_exp_titles">
        <item>@string/three_days</item>
        <item>@string/one_week</item>
        <item>@string/two_weeks</item>
        <item>@string/three_weeks</item>
        <item>@string/four_weeks</item>
        <item>@string/never</item>
    </string-array>
    <string-array name="pref_before_exp_values" translatable="false">
        <item>3</item>
        <item>7</item>
        <item>14</item>
        <item>21</item>
        <item>28</item>
        <item>-1</item>
    </string-array>
    <string name="three_days">3 days</string>
    <string name="one_week">1 week</string>
    <string name="two_weeks">2 weeks</string>
    <string name="three_weeks">3 weeks</string>
    <string name="four_weeks">4 weeks</string>
    <string name="never">Never</string>
    <string name="pref_title_ringtone">Notification sound</string>
    <string name="pref_ringtone_silent">Silent</string>
    <string name="pref_title_vibrate">Vibrate</string>
    <string name="pref_notification_before">upfront</string>

    <!-- Units -->

    <string name="mass">oz</string>
    <string name="volume">fl oz</string>
    <string name="pieces">pc.</string>
    <string name="mass_label">Weight</string>
    <string name="volume_label">Volume</string>
    <string name="pieces_label">Quantity</string>

    <!-- Categories -->

    <string name="meat">Meat</string>
    <string name="fruits">Fruits</string>
    <string name="vegetables">Vegetables</string>
    <string name="fish">Fish</string>
    <string name="pastry">Pastry</string>
    <string name="roll">Roll</string>
    <string name="fast_food">Fast food</string>
    <string name="ice_cream">Ice cream</string>
    <string name="other">Other</string>

    <!-- Notifications -->

    <string name="notification_channel">Expiration</string>
    <string name="notification_expires_today">%1$s expires today.</string>
    <string name="notification_has_expired_today">%1$s expired today.</string>
    <plurals name="notification_expires">
        <item quantity="one">%1$s expires tomorrow.</item>
        <item quantity="other">%1$s expires in %2$d days.</item>
    </plurals>
    <plurals name="notification_has_expired">
        <item quantity="one">%1$s expired yesterday.</item>
        <item quantity="other">%1$s expired %2$d days ago.</item>
    </plurals>

</resources>


text:
<!DOCTYPE html>
<html lang="en">
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/d3-sankey@0.7.1"></script>
<style>

.node rect {
  cursor: move;
  fill-opacity: .9;
  shape-rendering: crispEdges;
}

.node text {
  pointer-events: none;
  text-shadow: 0 1px 0 #fff;
}

.link {
  fill: none;
  stroke: #000;
  stroke-opacity: .2;
}

.link:hover {
  stroke-opacity: .5;
}

</style>
<script>

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var formatNumber = d3.format(",.0f"),
    format = function(d) { return formatNumber(d); },
    color = d3.scaleOrdinal(d3.schemeCategory10);

var sankey = d3.sankey()
    .nodeWidth(15)
    .nodePadding(10)
    .extent([[1, 1], [width - 1, height - 6]]);

var link = svg.append("g")
    .attr("class", "links")
    .attr("fill", "none")
    .attr("stroke", "#000")
    .attr("stroke-opacity", 0.2)
  .selectAll("path");

var node = svg.append("g")
    .attr("class", "nodes")
    .attr("font-family", "sans-serif")
    .attr("font-size", 10)
  .selectAll("g");

d3.json("/api/atlas/v2/debug/lineage/", function(error, lineage) {
  if (error) throw error;

  sankey(lineage);

  link = link
    .data(lineage.links)
    .enter().append("path")
      .attr("class", "link")
      .attr("d", d3.sankeyLinkHorizontal())
      .attr("stroke-width", function(d) { return Math.max(1, d.width); });

  link.append("title")
      .text(function(d) { return d.source.name + "->" + d.target.name + "\n" + format(d.value); });

  node = node
    .data(lineage.nodes)
    .enter().append("g")
      .attr("class", "node");

  node.append("rect")
      .attr("x", function(d) { return d.x0; })
      .attr("y", function(d) { return d.y0; })
      .attr("height", function(d) { return d.y1 - d.y0; })
      .attr("width", function(d) { return d.x1 - d.x0; })
      .attr("fill", function(d) { return color(d.name.replace(/ .*/, "")); })
      .attr("stroke", "#000");

  node.append("text")
      .attr("x", function(d) { return d.x0 - 6; })
      .attr("y", function(d) { return (d.y1 + d.y0) / 2; })
      .attr("dy", "0.35em")
      .attr("text-anchor", "end")
      .text(function(d) { return d.name; })
    .filter(function(d) { return d.x0 < width / 2; })
      .attr("x", function(d) { return d.x1 + 6; })
      .attr("text-anchor", "start");

  node.append("title")
      .text(function(d) { return d.type + "\n" + d.name + "\n" + d.qualifiedName; });
});

</script>
</html>


text:
/*global YSLOW*/
/*jslint browser: true, sloppy: true*/

/**
 * Parse details (HTTP headers, content, etc) from a
 * given source and set component properties.
 * @param o The object containing component details.
 */
YSLOW.Component.prototype.setComponentDetails = function (o) {
    var comp = this,

        parse = function (request, response) {
            var xhr;

            // copy from the response object
            comp.status = response.status;
            comp.headers = {};
            comp.raw_headers = '';
            response.headers.forEach(function (header) {
                comp.headers[header.name.toLowerCase()] = header.value;
                comp.raw_headers += header.name + ': ' + header.value + '\n';
            });
            comp.req_headers = {};
            request.headers.forEach(function (header) {
                comp.req_headers[header.name.toLowerCase()] = header.value;
            });
            comp.method = request.method;
            if (response.contentText) {
                comp.body = response.contentText;
            } else {
                // try to fetch component again using sync xhr while
                // content is not available through phantomjs.
                // see: http://code.google.com/p/phantomjs/issues/detail?id=158
                // and http://code.google.com/p/phantomjs/issues/detail?id=156
                try {
                    xhr = new XMLHttpRequest();
                    xhr.open('GET', comp.url, false);
                    xhr.send();
                    comp.body = xhr.responseText;
                } catch (err) {
                    comp.body = {
                        toString: function () {
                            return '';
                        },
                        length: response.bodySize || 0
                    };
                }
            }
            // for security checking
            comp.response_type = comp.type;
            comp.cookie = (comp.headers['set-cookie'] || '') +
                (comp.req_headers.cookie || '');
            comp.nsize = parseInt(comp.headers['content-length'], 10) ||
                response.bodySize;
            comp.respTime = response.time;
            comp.after_onload = (new Date(request.time)
                .getTime()) > comp.parent.onloadTimestamp;

            // populate properties ignoring redirect
            // resolution and image request
            comp.populateProperties(false, true);

            comp.get_info_state = 'DONE';

            // notify parent ComponentSet that this component has gotten net response.
            comp.parent.onComponentGetInfoStateChange({
                'comp': comp,
                'state': 'DONE'
            });
        };

    if (o.request && o.response) {
        parse(o.request, o.response);
    }
};


text:
/**
 * Created by msav on 2/16/2017.
 */
var app = angular.module("dmsApp");

app.factory("userService", function ($http, configService, $q) {
    return {
        loadUsers: function (vat) {
            return $http.get(configService.getConfig().host+"/user/loadusers/" + vat);
        },
        updateUser: function (user) {
            return $http.post(configService.getConfig().host+"/user/update", user);
        },
        deleteUser: function (user) {
            return $http.post(configService.getConfig().host+"/user/delete", user);
        },
        addEmployee: function (employee) {
            return $http.post(configService.getConfig().host+"/user/addEmployee", employee);
        },
        changeUserPassword: function (user) {
            return $http.post(configService.getConfig().host+"/user/changePassword", user);
        }
    }
});


text:
  Crotelles est
       un village
       localisé dans le département de l'Indre-et-Loire en Centre. On dénombrait 585 habitants en 2008.

Si vous envisagez de emmenager à Crotelles, vous pourrez facilement trouver une maison à acheter.

À coté de Crotelles sont localisées les villes de
Château-Renault située à 7 km, 5 245 habitants,
Montreuil-en-Touraine localisée à 10 km, 682 habitants,
Saint-Laurent-en-Gâtines située à 6 km, 886 habitants,
Monnaie située à 6 km, 3 768 habitants,
Chançay à 10 km, 1 000 habitants,
Auzouer-en-Touraine située à 6 km, 1 853 habitants,
 entre autres. De plus, Crotelles est située à seulement 20 km de Tours.

Le parc d'habitations, à Crotelles, était réparti en 2011 en sept appartements et 247 maisons soit
 un marché plutôt équilibré.

À Crotelles, la valeur moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 798 € du m². À la location le prix moyen se situe à 7,21 € du m² mensuel.

La commune offre quelques  aménagements, elle propose entre autres un terrain de sport et une boucle de randonnée.


text:
package cucumber.runtime.java;

import cucumber.runtime.snippets.SnippetGenerator;
import gherkin.pickles.Argument;
import gherkin.pickles.PickleLocation;
import gherkin.pickles.PickleStep;
import org.junit.Test;

import java.util.Collections;

import static org.junit.Assert.assertEquals;

public class Java8SnippetTest {
    private static final String GIVEN_KEYWORD = "Given";

    @Test
    public void generatesPlainSnippet() {
        String expected = "" +
                "Given(\"^I have (\\\\d+) cukes in my \\\"([^\\\"]*)\\\" belly$\", (Integer arg1, String arg2) -> {\n" +
                "    // Write code here that turns the phrase above into concrete actions\n" +
                "    throw new PendingException();\n" +
                "});\n";
        System.out.println(expected);
        assertEquals(expected, snippetFor("I have 4 cukes in my \"big\" belly"));
    }

    private String snippetFor(String name) {
        PickleStep step = new PickleStep(name, Collections.<Argument>emptyList(), Collections.<PickleLocation>emptyList());
        return new SnippetGenerator(new Java8Snippet()).getSnippet(step, GIVEN_KEYWORD, null);
    }
}


text:
"""<iframe> template"""

from ..environment import env

iframe = env.from_string("""\
<iframe {% if src -%} src="{{ src }}" {% endif -%}
        {% if width -%} width="{{ width }}" {% endif -%}
        {% if height -%} height="{{ height }}" {% endif -%}
        {% if align -%} align="{{ align }}" {% endif -%}
        {% if frameborder -%} frameborder="{{ frameborder }}" {% endif -%}
        {% if longdesc -%} longdesc="{{ longdesc }}" {% endif -%}
        {% if marginheight -%} marginheight="{{ marginheight }}" {% endif -%}
        {% if marginwidth -%} marginwidth="{{ marginwidth }}" {% endif -%}
        {% if name -%} name="{{ name }}" {% endif -%}
        {% if sandbox -%} sandbox="{{ sandbox }}" {% endif -%}
        {% if scrolling -%} scrolling="{{ scrolling }}" {% endif -%}
        {% if srcdoc -%} srcdoc="{{ srcdoc }}" {% endif -%}></iframe>
""")


text:
/**
 * Provides the ManagedClient class used by the guacClientManager service.
 */
angular.module('client').factory('ManagedClientState', [function defineManagedClientState() {

    /**
     * Object which represents the state of a Guacamole client and its tunnel,
     * including any error conditions.
     *
     * @constructor
     * @param {ManagedClientState|Object} [template={}]
     *     The object whose properties should be copied within the new
     *     ManagedClientState.
     */
    var ManagedClientState = function ManagedClientState(template) {

        // Use empty object by default
        template = template || {};

        /**
         * The current connection state. Valid values are described by
         * ManagedClientState.ConnectionState.
         *
         * @type String
         * @default ManagedClientState.ConnectionState.IDLE
         */
        this.connectionState = template.connectionState || ManagedClientState.ConnectionState.IDLE;

        /**
         * The status code of the current error condition, if connectionState
         * is CLIENT_ERROR or TUNNEL_ERROR. For all other connectionState
         * values, this will be @link{Guacamole.Status.Code.SUCCESS}.
         *
         * @type Number
         * @default Guacamole.Status.Code.SUCCESS
         */
        this.statusCode = template.statusCode || Guacamole.Status.Code.SUCCESS;

    };

    /**
     * Valid connection state strings. Each state string is associated with a
     * specific state of a Guacamole connection.
     */
    ManagedClientState.ConnectionState = {

        /**
         * The Guacamole connection has not yet been attempted.
         *
         * @type String
         */
        IDLE : "IDLE",

        /**
         * The Guacamole connection is being established.
         *
         * @type String
         */
        CONNECTING : "CONNECTING",

        /**
         * The Guacamole connection has been successfully established, and the
         * client is now waiting for receipt of initial graphical data.
         *
         * @type String
         */
        WAITING : "WAITING",

        /**
         * The Guacamole connection has been successfully established, and
         * initial graphical data has been received.
         *
         * @type String
         */
        CONNECTED : "CONNECTED",

        /**
         * The Guacamole connection has terminated successfully. No errors are
         * indicated.
         *
         * @type String
         */
        DISCONNECTED : "DISCONNECTED",

        /**
         * The Guacamole connection has terminated due to an error reported by
         * the client. The associated error code is stored in statusCode.
         *
         * @type String
         */
        CLIENT_ERROR : "CLIENT_ERROR",

        /**
         * The Guacamole connection has terminated due to an error reported by
         * the tunnel. The associated error code is stored in statusCode.
         *
         * @type String
         */
        TUNNEL_ERROR : "TUNNEL_ERROR"

    };

    /**
     * Sets the current client state and, if given, the associated status code.
     * If an error is already represented, this function has no effect.
     *
     * @param {ManagedClientState} clientState
     *     The ManagedClientState to update.
     *
     * @param {String} connectionState
     *     The connection state to assign to the given ManagedClientState, as
     *     listed within ManagedClientState.ConnectionState.
     *
     * @param {Number} [statusCode]
     *     The status code to assign to the given ManagedClientState, if any,
     *     as listed within Guacamole.Status.Code. If no status code is
     *     specified, the status code of the ManagedClientState is not touched.
     */
    ManagedClientState.setConnectionState = function(clientState, connectionState, statusCode) {

        // Do not set state after an error is registered
        if (clientState.connectionState === ManagedClientState.ConnectionState.TUNNEL_ERROR
         || clientState.connectionState === ManagedClientState.ConnectionState.CLIENT_ERROR)
            return;

        // Update connection state
        clientState.connectionState = connectionState;

        // Set status code, if given
        if (statusCode)
            clientState.statusCode = statusCode;

    };

    return ManagedClientState;

}]);


text:
    <button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open me!</button>
    <button type="button" class="btn btn-default" ng-click="$ctrl.open('lg')">Large modal</button>
    <button type="button" class="btn btn-default" ng-click="$ctrl.open('sm')">Small modal</button>
    <button type="button"
        class="btn btn-default"
        ng-click="$ctrl.open('sm', '.modal-parent')">
            Modal appended to a custom parent
    </button>
    <button type="button" class="btn btn-default" ng-click="$ctrl.toggleAnimation()">Toggle Animation ({{ $ctrl.animationsEnabled }})</button>
    <button type="button" class="btn btn-default" ng-click="$ctrl.openComponentModal()">Open a component modal!</button>
    <button type="button" class="btn btn-default" ng-click="$ctrl.openMultipleModals()">
        Open multiple modals at once
    </button>

Selection from a modal: {{ $ctrl.selected }}


text:
from rustypy.pywrapper import rust_bind

@rust_bind
def first_module() -> None:
    print('... called from first module')

if __name__ == "__main__":
    first_module()


text:
import os

import numpy as np

import openmc
from openmc.examples import slab_mg

from tests.testing_harness import PyAPITestHarness

def create_library():
    # Instantiate the energy group data and file object
    groups = openmc.mgxs.EnergyGroups(group_edges=[0.0, 0.625, 20.0e6])
    n_dg = 2

    mg_cross_sections_file = openmc.MGXSLibrary(groups)
    mg_cross_sections_file.num_delayed_groups = n_dg

    beta = np.array([0.003, 0.003])
    one_m_beta = 1. - np.sum(beta)
    nu = [2.50, 2.50]
    fiss = np.array([0.002817, 0.097])
    capture = [0.008708, 0.02518]
    absorption = np.add(capture, fiss)
    scatter = np.array(
        [[[0.31980, 0.06694], [0.004555, -0.0003972]],
         [[0.00000, 0.00000], [0.424100, 0.05439000]]])
    total = [0.33588, 0.54628]
    chi = [1., 0.]

    # Make the base data that uses chi & nu-fission vectors with a beta
    mat_1 = openmc.XSdata('mat_1', groups)
    mat_1.order = 1
    mat_1.num_delayed_groups = 2
    mat_1.set_beta(beta)
    mat_1.set_nu_fission(np.multiply(nu, fiss))
    mat_1.set_absorption(absorption)
    mat_1.set_scatter_matrix(scatter)
    mat_1.set_total(total)
    mat_1.set_chi(chi)
    mg_cross_sections_file.add_xsdata(mat_1)

    # Make a version that uses prompt and delayed version of nufiss and chi
    mat_2 = openmc.XSdata('mat_2', groups)
    mat_2.order = 1
    mat_2.num_delayed_groups = 2
    mat_2.set_prompt_nu_fission(one_m_beta * np.multiply(nu, fiss))
    delay_nu_fiss = np.zeros((n_dg, groups.num_groups))
    for dg in range(n_dg):
        for g in range(groups.num_groups):
            delay_nu_fiss[dg, g] = beta[dg] * nu[g] * fiss[g]
    mat_2.set_delayed_nu_fission(delay_nu_fiss)
    mat_2.set_absorption(absorption)
    mat_2.set_scatter_matrix(scatter)
    mat_2.set_total(total)
    mat_2.set_chi_prompt(chi)
    mat_2.set_chi_delayed(np.stack([chi] * n_dg))
    mg_cross_sections_file.add_xsdata(mat_2)

    # Make a version that uses a nu-fission matrix with a beta
    mat_3 = openmc.XSdata('mat_3', groups)
    mat_3.order = 1
    mat_3.num_delayed_groups = 2
    mat_3.set_beta(beta)
    mat_3.set_nu_fission(np.outer(np.multiply(nu, fiss), chi))
    mat_3.set_absorption(absorption)
    mat_3.set_scatter_matrix(scatter)
    mat_3.set_total(total)
    mg_cross_sections_file.add_xsdata(mat_3)

    # Make a version that uses prompt and delayed version of the nufiss matrix
    mat_4 = openmc.XSdata('mat_4', groups)
    mat_4.order = 1
    mat_4.num_delayed_groups = 2
    mat_4.set_prompt_nu_fission(one_m_beta *
                                np.outer(np.multiply(nu, fiss), chi))
    delay_nu_fiss = np.zeros((n_dg, groups.num_groups, groups.num_groups))
    for dg in range(n_dg):
        for g in range(groups.num_groups):
            for go in range(groups.num_groups):
                delay_nu_fiss[dg, g, go] = beta[dg] * nu[g] * fiss[g] * chi[go]
    mat_4.set_delayed_nu_fission(delay_nu_fiss)
    mat_4.set_absorption(absorption)
    mat_4.set_scatter_matrix(scatter)
    mat_4.set_total(total)
    mg_cross_sections_file.add_xsdata(mat_4)

    # Make the base data that uses chi & nu-fiss vectors with a group-wise beta
    mat_5 = openmc.XSdata('mat_5', groups)
    mat_5.order = 1
    mat_5.num_delayed_groups = 2
    mat_5.set_beta(np.stack([beta] * groups.num_groups))
    mat_5.set_nu_fission(np.multiply(nu, fiss))
    mat_5.set_absorption(absorption)
    mat_5.set_scatter_matrix(scatter)
    mat_5.set_total(total)
    mat_5.set_chi(chi)
    mg_cross_sections_file.add_xsdata(mat_5)

    # Make a version that uses a nu-fission matrix with a group-wise beta
    mat_6 = openmc.XSdata('mat_6', groups)
    mat_6.order = 1
    mat_6.num_delayed_groups = 2
    mat_6.set_beta(np.stack([beta] * groups.num_groups))
    mat_6.set_nu_fission(np.outer(np.multiply(nu, fiss), chi))
    mat_6.set_absorption(absorption)
    mat_6.set_scatter_matrix(scatter)
    mat_6.set_total(total)
    mg_cross_sections_file.add_xsdata(mat_6)

    # Write the file
    mg_cross_sections_file.export_to_hdf5('2g.h5')

class MGXSTestHarness(PyAPITestHarness):
    def _cleanup(self):
        super()._cleanup()
        f = '2g.h5'
        if os.path.exists(f):
            os.remove(f)

def test_mg_basic_delayed():
    create_library()
    model = slab_mg(num_regions=6, mat_names=['vec beta', 'vec no beta',
                                              'matrix beta', 'matrix no beta',
                                              'vec group beta',
                                              'matrix group beta'])

    harness = PyAPITestHarness('statepoint.10.h5', model)
    harness.main()


text:
layout: post
date: 2016-02-05 19:52
---
(aim for some friends, HipChat for work, Gitter for side projects, IRC for meetups, SMS/iMessage for everything else)