text:
/* Copyright marker.  Copyright will be inserted above.  Do not remove */
/*
** @$=@$=@$=
*/
/*
**				DICOM 93
**		     Electronic Radiology Laboratory
**		   Mallinckrodt Institute of Radiology
**		Washington University School of Medicine
**
** Module Name(s):
** Author, Date:	Stephen M. Moore, xx-May-92
** Intent:
**  This header contains private typedefs for the DICOM Upper Layer
**  (DUL) protocol package.  This is to be used to compile the DUL
**  package and is not intended to be seen by the applications programmer.
**  Files at the package level should include this file to get the
**  proper typedefs and include the public file "dulprotocol.h" to
**  get the public definitions and function prototypes.  I have omitted
**  the public definitions and prototypes on purpose so that they
**  exist in only one location.
**
** Last Update:		$Author: lpysher $, $Date: 2006/03/01 20:15:50 $
** Source File:		$RCSfile: dulpriv.h,v $
** Revision:		$Revision: 1.1 $
** Status:		$State: Exp $
*/

#ifndef DULPRIVATE_H
#define DULPRIVATE_H

#include "osconfig.h"    /* make sure OS specific configuration is included first */

#define	PRV_DEFAULTTIMEOUT	-1
#define	PRV_LISTENBACKLOG	50

#define DEBUG_DEVICE	COUT

OFCondition DUL_InitializeFSM(void);
OFCondition
PRV_StateMachine(PRIVATE_NETWORKKEY ** network,
		 PRIVATE_ASSOCIATIONKEY ** association, int event, int state,
		 void *params);

OFCondition
constructAssociatePDU(DUL_ASSOCIATESERVICEPARAMETERS * items,
		      unsigned char type, PRV_ASSOCIATEPDU * pdu);
OFCondition
constructAssociateRejectPDU(unsigned char result,
			    unsigned char source, unsigned char reason,
			    DUL_REJECTRELEASEABORTPDU * pdu);
OFCondition constructReleaseRQPDU(DUL_REJECTRELEASEABORTPDU * pdu, unsigned int mode);
OFCondition constructReleaseRPPDU(DUL_REJECTRELEASEABORTPDU * pdu);
OFCondition
constructAbortPDU(unsigned char src, unsigned char reason,
		  DUL_REJECTRELEASEABORTPDU * pdu, unsigned int mode);
OFCondition
constructDataPDU(void *buf, unsigned int length, DUL_DATAPDV type,
       DUL_PRESENTATIONCONTEXTID ctxID, OFBool last, DUL_DATAPDU * pdu);
OFCondition
streamAssociatePDU(PRV_ASSOCIATEPDU * assoc, unsigned char *b,
		   unsigned int maxLength, unsigned int *rtnLen);
OFCondition
streamRejectReleaseAbortPDU(DUL_REJECTRELEASEABORTPDU * pdu,
	  unsigned char *b, unsigned int maxLength, unsigned int *rtnLen);
OFCondition
streamDataPDUHead(DUL_DATAPDU * pdu, unsigned char *buf,
		  unsigned int maxLength, unsigned int *rtnLen);
OFCondition
parseAssociate(unsigned char *buf, unsigned int len,
	       PRV_ASSOCIATEPDU * pdu);
OFCondition
PRV_NextPDUType(PRIVATE_ASSOCIATIONKEY ** association,
		DUL_BLOCKOPTIONS block, int timeout, unsigned char *type);

void fsmDebug(OFBool flag);
void constructDebug(OFBool flag);
void parseDebug(OFBool flag);

#endif

/*
** CVS Log
** $Log: dulpriv.h,v $
** Revision 1.1  2006/03/01 20:15:50  lpysher
** Added dcmtkt ocvs not in xcode  and fixed bug with multiple monitors
**
** Revision 1.8  2005/12/08 15:48:09  meichel
** Updated Makefiles to correctly install header files
**
** Revision 1.7  2004/02/25 12:31:17  meichel
** Added global option flag for compatibility with very old DCMTK releases in the
**   DICOM upper layer and ACSE code. Default is automatic handling, which should
**   work in most cases.
**
** Revision 1.6  2001/10/12 10:18:41  meichel
** Replaced the CONDITION types, constants and functions in the dcmnet module
**   by an OFCondition based implementation which eliminates the global condition
**   stack.  This is a major change, caveat emptor!
**
** Revision 1.5  2001/09/26 12:29:04  meichel
** Implemented changes in dcmnet required by the adaptation of dcmdata
**   to class OFCondition.  Removed some unused code.
**
** Revision 1.4  2000/03/03 14:11:26  meichel
** Implemented library support for redirecting error messages into memory
**   instead of printing them to stdout/stderr for GUI applications.
**
** Revision 1.3  1997/07/21 08:47:25  andreas
** - Replace all boolean types (BOOLEAN, CTNBOOLEAN, DICOM_BOOL, BOOL)
**   with one unique boolean type OFBool.
**
** Revision 1.2  1997/01/13 15:53:13  hewett
** Added missing function prototypes (required for CodeWarrior 10).
**
** Revision 1.1.1.1  1996/03/26 18:38:46  hewett
** Initial Release.
**
**
*/


text:
package edu.hm.hafner.analysis.parser;

import java.util.regex.Matcher;

import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.Priority;
import edu.hm.hafner.analysis.RegexpLineParser;

/**
 * A parser for the Perl::Critic warnings.
 *
 * @author Mihail Menev, menev@hm.edu
 */
public class PerlCriticParser extends RegexpLineParser {
    private static final long serialVersionUID = -6481203155449490873L;

    private static final String PERLCRITIC_WARNING_PATTERN = "(?:(.*?):)?(.*)\\s+at\\s+line\\s+(\\d+),\\s+column\\s+"
            + "(\\d+)\\.\\s*(?:See page[s]?\\s+)?(.*)\\.\\s*\\(?Severity:\\s*(\\d)\\)?";

    /**
     * Creates a new instance of {@link PerlCriticParser}.
     */
    public PerlCriticParser() {
        super("perl-critic", PERLCRITIC_WARNING_PATTERN);
    }

    @Override
    protected Issue createWarning(final Matcher matcher) {
        String filename;
        if (matcher.group(1) == null) {
            filename = "-";
        }
        else {
            filename = matcher.group(1);
        }

        String message = matcher.group(2);
        int line = parseInt(matcher.group(3));
        int column = parseInt(matcher.group(4));
        String category = matcher.group(5);
        Priority priority = checkPriority(Integer.parseInt(matcher.group(6)));

        return issueBuilder().setFileName(filename).setLineStart(line).setColumnStart(column).setCategory(category)
                             .setMessage(message).setPriority(priority).build();
    }

    /**
     * Checks the severity level, parsed from the warning and return the priority level.
     *
     * @param priority the severity level of the warning.
     * @return the priority level.
     */
    private Priority checkPriority(final int priority) {
        if (priority < 2) {
            return Priority.LOW;
        }
        else if (priority < 4) {
            return Priority.NORMAL;
        }
        else {
            return Priority.HIGH;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<oors-ui>

	<splash>
		<image></image>
		<width>0</width>
		<height>0</height>
		<message>
			<x>0</x>
			<y>0</y>

			<color></color>
			<max-length>0</max-length>
		</message>
	</splash>

	<startup>

	</startup>

	<icons default="images/error.png">
		<icon>
			<name>cut</name>
			<filename>images/Cut.png</filename>
		</icon>
		<icon>
			<name>copy</name>
			<filename>images/Copy.png</filename>
		</icon>
		<icon>
			<name>paste</name>
			<filename>images/Paste.png</filename>
		</icon>
		<icon>
			<name>folder</name>
			<filename>images/folder.png</filename>
		</icon>
		<icon>
			<name>folderProperties</name>
			<filename>images/folder_wrench.png</filename>
		</icon>
		<icon>
			<name>newDocument</name>
			<filename>images/page_white_add.png</filename>
		</icon>
		<icon>
			<name>newFolder</name>
			<filename>images/folder_add.png</filename>
		</icon>
		<icon>
			<name>documentProperties</name>
			<filename>images/page_white_gear.png</filename>
		</icon>
		<icon>
			<name>newObject</name>
			<filename>images/add.png</filename>
		</icon>
		<icon>
			<name>open</name>
			<filename>images/lightning.png</filename>
		</icon>
		<icon>
			<name>objectProperties</name>
			<filename>images/wrench.png</filename>
		</icon>
		<icon>
			<name>projectProperties</name>
			<filename>images/database_gear.png</filename>
		</icon>
		<icon>
			<name>branchProperties</name>
			<filename>images/arrow_divide.png</filename>
		</icon>
	</icons>

	<actions>
		<action>
			<name>new folder</name>

		</action>
		<action>
			<name>new document</name>

		</action>
		<action>
			<name>folder properties</name>

		</action>
		<action>
			<name>branch properties</name>

		</action>
		<action>
			<name>project properties</name>

		</action>
		<action>
			<name>insert after</name>

		</action>
		<action>
			<name>insert before</name>

		</action>
		<action>
			<name>new obj</name>

		</action>
		<action>
			<name>add column</name>

		</action>
		<action>
			<name>remove column</name>

		</action>
		<action>
			<name>sort</name>

		</action>
		<action>
			<name>filter</name>

		</action>
		<action>
			<name>start link</name>

		</action>
		<action>
			<name>create link</name>

		</action>
	</actions>

	<menus>

		<menu>
			<ui-element>JTableHeader</ui-element>
			<selection></selection>
			<action>add column</action>
			<action>remove column</action>
			<action>sort</action>
			<action>filter</action>
		</menu>

		<menu>
			<ui-element>ProjectBranchTree</ui-element>
			<selection>ProjectBranch</selection>
			<action>new document</action>
			<action>new folder</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>ProjectBranchTree</ui-element>
			<selection>Folder</selection>
			<action>new document</action>
			<action>new folder</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>FolderTable</ui-element>
			<selection>ProjectBranch</selection>
			<action>new document</action>
			<action>new folder</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>FolderTable</ui-element>
			<selection>Folder</selection>
			<action>new document</action>
			<action>new folder</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>FolderTable</ui-element>
			<selection>Document</selection>
			<action>start link</action>
			<action>create link</action>
		</menu>

		<menu>
			<ui-element>DocumentTree</ui-element>
			<selection>Document</selection>
			<action>new obj</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>DocumentTree</ui-element>
			<selection>Obj</selection>
			<action>new obj</action>
			<action>insert after</action>
			<action>insert before</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>DocumentTable</ui-element>
			<selection>Obj</selection>
			<action>new obj</action>
			<action>insert after</action>
			<action>insert before</action>
			<action>start link</action>
			<action>create link</action>
		</menu>
		<menu>
			<ui-element>DocumentTable</ui-element>
			<selection>Document</selection>
			<action>new obj</action>
			<action>start link</action>
			<action>create link</action>
		</menu>

	</menus>

	<help>help/index.html</help>
</oors-ui>


text:
package com.peterpotts.sample

import org.scalatest.{Matchers, WordSpec}

import scala.collection.immutable.Seq

class SampleShuffleTest extends WordSpec with Matchers {
  "A sample shuffle instance" should {
    "shuffle sample values" in {
      val animals = Seq("wolf", "bear")
      val samples = animals.map(SampleLift[String])
      val animal = SampleShuffle(samples: _*).next()
      animals.contains(animal) shouldEqual true
    }
  }
}


text:
module Yesod.Helpers.Widget where

-- {{{1 imports
import ClassyPrelude.Yesod

import Yesod.Helpers.Message
import Yesod.Helpers.Form2
import Yesod.Helpers.Handler
-- }}}1

-- | construct page title by merging pieces of texts, separated by MsgPageTitleSep
mergePageTitles :: ( RenderMessage (HandlerSite m) message
                    , RenderMessage (HandlerSite m) YHCommonMessage
                    , MonadWidget m
                    )
                => [message]
                -> m ()
-- {{{1
mergePageTitles parts = do
    mr <- getMessageRender
    mr2 <- getMessageRender
    setTitleI $ mconcat $ intersperse (mr MsgPageTitleSep) $ map mr2 parts
-- }}}1

-- | A simple widget to show a html POST form
simpleFormPageWidgetEither :: ( MonadIO m, MonadThrow m
                              , MonadBaseControl IO m
                              , RenderMessage master a
                              , RenderMessage master YHCommonMessage
                              )
                           => GenFormData master
                           -> Either (Route master) Text  -- ^ action url
                           -> Maybe a       -- ^ any global error message
                           -> FieldErrors master  -- ^ error messages for form fields
                           -> WidgetT master m ()
-- {{{1
simpleFormPageWidgetEither = simpleFormPageWidgetEither' "POST"
-- }}}1

-- | A simple widget to show a html form
simpleFormPageWidgetEither' :: ( MonadIO m, MonadThrow m
                              , MonadBaseControl IO m
                              , RenderMessage master a
                              , RenderMessage master YHCommonMessage
                              )
                            => ByteString   -- ^ method
                            -> GenFormData master
                            -> Either (Route master) Text  -- ^ action url
                            -> Maybe a       -- ^ any global error message
                            -> FieldErrors master  -- ^ error messages for form fields
                            -> WidgetT master m ()
-- {{{1
simpleFormPageWidgetEither' method (formWidget, formEnctype) action' m_err_msg form_errs = do
  action <- case action' of
                  Right x -> return x
                  Left r -> do
                    url_render <- getUrlRender
                    return $ url_render r
  [whamlet|
$maybe err_msg <- m_err_msg
   <div .form-group>
     <span .err_msg>_{err_msg}
<ul>
  $forall ((_name, fs), errs) <- fieldErrorsToList form_errs
    <li>_{fsLabel fs}: #{intercalate ";" errs}
<form method=#{decodeUtf8 method} action="#{action}" enctype=#{formEnctype} .form-horizontal>
  ^{formWidget}
  <div .form-group>
    <div .submit-btn-container .col-xs-offset-3 .col-xs-9>
      <input .btn .btn-primary type=submit value=_{MsgSubmitForm}>
  |]
-- }}}1

simpleFormPageWidget :: (MonadIO m, MonadThrow m
                        , MonadBaseControl IO m
                        , RenderMessage master a
                        , RenderMessage master YHCommonMessage
                        )
                     => GenFormData master
                     -> Route master  -- ^ action url
                     -> Maybe a       -- ^ any global error message
                     -> FieldErrors master  -- ^ error messages for form fields
                     -> WidgetT master m ()
simpleFormPageWidget (formWidget, formEnctype) action m_err_msg form_errs =
  simpleFormPageWidgetEither (formWidget, formEnctype) (Left action) m_err_msg form_errs

-- vim: set foldmethod=marker:


text:
"""
Benchmarks on the power iterations phase in randomized SVD.

We test on various synthetic and real datasets the effect of increasing
the number of power iterations in terms of quality of approximation
and running time. A number greater than 0 should help with noisy matrices,
which are characterized by a slow spectral decay.

We test several policy for normalizing the power iterations. Normalization
is crucial to avoid numerical issues.

The quality of the approximation is measured by the spectral norm discrepancy
between the original input matrix and the reconstructed one (by multiplying
the randomized_svd's outputs). The spectral norm is always equivalent to the
largest singular value of a matrix. (3) justifies this choice. However, one can
notice in these experiments that Frobenius and spectral norms behave
very similarly in a qualitative sense. Therefore, we suggest to run these
benchmarks with `enable_spectral_norm = False`, as Frobenius' is MUCH faster to
compute.

The benchmarks follow.

(a) plot: time vs norm, varying number of power iterations
    data: many datasets
    goal: compare normalization policies and study how the number of power
    iterations affect time and norm

(b) plot: n_iter vs norm, varying rank of data and number of components for
    randomized_SVD
    data: low-rank matrices on which we control the rank
    goal: study whether the rank of the matrix and the number of components
    extracted by randomized SVD affect "the optimal" number of power iterations

(c) plot: time vs norm, varing datasets
    data: many datasets
    goal: compare default configurations

We compare the following algorithms:
-   randomized_svd(..., power_iteration_normalizer='none')
-   randomized_svd(..., power_iteration_normalizer='LU')
-   randomized_svd(..., power_iteration_normalizer='QR')
-   randomized_svd(..., power_iteration_normalizer='auto')
-   fbpca.pca() from https://github.com/facebook/fbpca (if installed)

Conclusion
----------
- n_iter=2 appears to be a good default value
- power_iteration_normalizer='none' is OK if n_iter is small, otherwise LU
  gives similar errors to QR but is cheaper. That's what 'auto' implements.

References
----------
(1) Finding structure with randomness: Stochastic algorithms for constructing
    approximate matrix decompositions
    Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061

(2) A randomized algorithm for the decomposition of matrices
    Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert

(3) An implementation of a randomized algorithm for principal component
    analysis
    A. Szlam et al. 2014
"""

# Author: Giorgio Patrini

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

import gc
import pickle
from time import time
from collections import defaultdict
import os.path

from sklearn.utils import gen_batches
from sklearn.utils.validation import check_random_state
from sklearn.utils.extmath import randomized_svd
from sklearn.datasets.samples_generator import (make_low_rank_matrix,
                                                make_sparse_uncorrelated)
from sklearn.datasets import (fetch_lfw_people,
                              fetch_mldata,
                              fetch_20newsgroups_vectorized,
                              fetch_olivetti_faces,
                              fetch_rcv1)

try:
    import fbpca
    fbpca_available = True
except ImportError:
    fbpca_available = False

# If this is enabled, tests are much slower and will crash with the large data
enable_spectral_norm = False

# TODO: compute approximate spectral norms with the power method as in
# Estimating the largest eigenvalues by the power and Lanczos methods with
# a random start, Jacek Kuczynski and Henryk Wozniakowski, SIAM Journal on
# Matrix Analysis and Applications, 13 (4): 1094-1122, 1992.
# This approximation is a very fast estimate of the spectral norm, but depends
# on starting random vectors.

# Determine when to switch to batch computation for matrix norms,
# in case the reconstructed (dense) matrix is too large
MAX_MEMORY = np.int(2e9)

# The following datasets can be dowloaded manually from:
# CIFAR 10: http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
# SVHN: http://ufldl.stanford.edu/housenumbers/train_32x32.mat
CIFAR_FOLDER = "./cifar-10-batches-py/"
SVHN_FOLDER = "./SVHN/"

datasets = ['low rank matrix', 'lfw_people', 'olivetti_faces', '20newsgroups',
            'MNIST original', 'CIFAR', 'a1a', 'SVHN', 'uncorrelated matrix']

big_sparse_datasets = ['big sparse matrix', 'rcv1']

def unpickle(file_name):
    with open(file_name, 'rb') as fo:
        return pickle.load(fo, encoding='latin1')["data"]

def handle_missing_dataset(file_folder):
    if not os.path.isdir(file_folder):
        print("%s file folder not found. Test skipped." % file_folder)
        return 0

def get_data(dataset_name):
    print("Getting dataset: %s" % dataset_name)

    if dataset_name == 'lfw_people':
        X = fetch_lfw_people().data
    elif dataset_name == '20newsgroups':
        X = fetch_20newsgroups_vectorized().data[:, :100000]
    elif dataset_name == 'olivetti_faces':
        X = fetch_olivetti_faces().data
    elif dataset_name == 'rcv1':
        X = fetch_rcv1().data
    elif dataset_name == 'CIFAR':
        if handle_missing_dataset(CIFAR_FOLDER) == "skip":
            return
        X1 = [unpickle("%sdata_batch_%d" % (CIFAR_FOLDER, i + 1))
              for i in range(5)]
        X = np.vstack(X1)
        del X1
    elif dataset_name == 'SVHN':
        if handle_missing_dataset(SVHN_FOLDER) == 0:
            return
        X1 = sp.io.loadmat("%strain_32x32.mat" % SVHN_FOLDER)['X']
        X2 = [X1[:, :, :, i].reshape(32 * 32 * 3) for i in range(X1.shape[3])]
        X = np.vstack(X2)
        del X1
        del X2
    elif dataset_name == 'low rank matrix':
        X = make_low_rank_matrix(n_samples=500, n_features=np.int(1e4),
                                 effective_rank=100, tail_strength=.5,
                                 random_state=random_state)
    elif dataset_name == 'uncorrelated matrix':
        X, _ = make_sparse_uncorrelated(n_samples=500, n_features=10000,
                                        random_state=random_state)
    elif dataset_name == 'big sparse matrix':
        sparsity = np.int(1e6)
        size = np.int(1e6)
        small_size = np.int(1e4)
        data = np.random.normal(0, 1, np.int(sparsity/10))
        data = np.repeat(data, 10)
        row = np.random.uniform(0, small_size, sparsity)
        col = np.random.uniform(0, small_size, sparsity)
        X = sp.sparse.csr_matrix((data, (row, col)), shape=(size, small_size))
        del data
        del row
        del col
    else:
        X = fetch_mldata(dataset_name).data
    return X

def plot_time_vs_s(time, norm, point_labels, title):
    plt.figure()
    colors = ['g', 'b', 'y']
    for i, l in enumerate(sorted(norm.keys())):
        if l != "fbpca":
            plt.plot(time[l], norm[l], label=l, marker='o', c=colors.pop())
        else:
            plt.plot(time[l], norm[l], label=l, marker='^', c='red')

        for label, x, y in zip(point_labels, list(time[l]), list(norm[l])):
            plt.annotate(label, xy=(x, y), xytext=(0, -20),
                         textcoords='offset points', ha='right', va='bottom')
    plt.legend(loc="upper right")
    plt.suptitle(title)
    plt.ylabel("norm discrepancy")
    plt.xlabel("running time [s]")

def scatter_time_vs_s(time, norm, point_labels, title):
    plt.figure()
    size = 100
    for i, l in enumerate(sorted(norm.keys())):
        if l != "fbpca":
            plt.scatter(time[l], norm[l], label=l, marker='o', c='b', s=size)
            for label, x, y in zip(point_labels, list(time[l]), list(norm[l])):
                plt.annotate(label, xy=(x, y), xytext=(0, -80),
                             textcoords='offset points', ha='right',
                             arrowprops=dict(arrowstyle="->",
                                             connectionstyle="arc3"),
                             va='bottom', size=11, rotation=90)
        else:
            plt.scatter(time[l], norm[l], label=l, marker='^', c='red', s=size)
            for label, x, y in zip(point_labels, list(time[l]), list(norm[l])):
                plt.annotate(label, xy=(x, y), xytext=(0, 30),
                             textcoords='offset points', ha='right',
                             arrowprops=dict(arrowstyle="->",
                                             connectionstyle="arc3"),
                             va='bottom', size=11, rotation=90)

    plt.legend(loc="best")
    plt.suptitle(title)
    plt.ylabel("norm discrepancy")
    plt.xlabel("running time [s]")

def plot_power_iter_vs_s(power_iter, s, title):
    plt.figure()
    for l in sorted(s.keys()):
        plt.plot(power_iter, s[l], label=l, marker='o')
    plt.legend(loc="lower right", prop={'size': 10})
    plt.suptitle(title)
    plt.ylabel("norm discrepancy")
    plt.xlabel("n_iter")

def svd_timing(X, n_comps, n_iter, n_oversamples,
               power_iteration_normalizer='auto', method=None):
    """
    Measure time for decomposition
    """
    print("... running SVD ...")
    if method is not 'fbpca':
        gc.collect()
        t0 = time()
        U, mu, V = randomized_svd(X, n_comps, n_oversamples, n_iter,
                                  power_iteration_normalizer,
                                  random_state=random_state, transpose=False)
        call_time = time() - t0
    else:
        gc.collect()
        t0 = time()
        # There is a different convention for l here
        U, mu, V = fbpca.pca(X, n_comps, raw=True, n_iter=n_iter,
                             l=n_oversamples+n_comps)
        call_time = time() - t0

    return U, mu, V, call_time

def norm_diff(A, norm=2, msg=True):
    """
    Compute the norm diff with the original matrix, when randomized
    SVD is called with *params.

    norm: 2 => spectral; 'fro' => Frobenius
    """

    if msg:
        print("... computing %s norm ..." % norm)
    if norm == 2:
        # s = sp.linalg.norm(A, ord=2)  # slow
        value = sp.sparse.linalg.svds(A, k=1, return_singular_vectors=False)
    else:
        if sp.sparse.issparse(A):
            value = sp.sparse.linalg.norm(A, ord=norm)
        else:
            value = sp.linalg.norm(A, ord=norm)
    return value

def scalable_frobenius_norm_discrepancy(X, U, s, V):
    # if the input is not too big, just call scipy
    if X.shape[0] * X.shape[1] < MAX_MEMORY:
        A = X - U.dot(np.diag(s).dot(V))
        return norm_diff(A, norm='fro')

    print("... computing fro norm by batches...")
    batch_size = 1000
    Vhat = np.diag(s).dot(V)
    cum_norm = .0
    for batch in gen_batches(X.shape[0], batch_size):
        M = X[batch, :] - U[batch, :].dot(Vhat)
        cum_norm += norm_diff(M, norm='fro', msg=False)
    return np.sqrt(cum_norm)

def bench_a(X, dataset_name, power_iter, n_oversamples, n_comps):

    all_time = defaultdict(list)
    if enable_spectral_norm:
        all_spectral = defaultdict(list)
        X_spectral_norm = norm_diff(X, norm=2, msg=False)
    all_frobenius = defaultdict(list)
    X_fro_norm = norm_diff(X, norm='fro', msg=False)

    for pi in power_iter:
        for pm in ['none', 'LU', 'QR']:
            print("n_iter = %d on sklearn - %s" % (pi, pm))
            U, s, V, time = svd_timing(X, n_comps, n_iter=pi,
                                       power_iteration_normalizer=pm,
                                       n_oversamples=n_oversamples)
            label = "sklearn - %s" % pm
            all_time[label].append(time)
            if enable_spectral_norm:
                A = U.dot(np.diag(s).dot(V))
                all_spectral[label].append(norm_diff(X - A, norm=2) /
                                           X_spectral_norm)
            f = scalable_frobenius_norm_discrepancy(X, U, s, V)
            all_frobenius[label].append(f / X_fro_norm)

        if fbpca_available:
            print("n_iter = %d on fbca" % (pi))
            U, s, V, time = svd_timing(X, n_comps, n_iter=pi,
                                       power_iteration_normalizer=pm,
                                       n_oversamples=n_oversamples,
                                       method='fbpca')
            label = "fbpca"
            all_time[label].append(time)
            if enable_spectral_norm:
                A = U.dot(np.diag(s).dot(V))
                all_spectral[label].append(norm_diff(X - A, norm=2) /
                                           X_spectral_norm)
            f = scalable_frobenius_norm_discrepancy(X, U, s, V)
            all_frobenius[label].append(f / X_fro_norm)

    if enable_spectral_norm:
        title = "%s: spectral norm diff vs running time" % (dataset_name)
        plot_time_vs_s(all_time, all_spectral, power_iter, title)
    title = "%s: Frobenius norm diff vs running time" % (dataset_name)
    plot_time_vs_s(all_time, all_frobenius, power_iter, title)

def bench_b(power_list):

    n_samples, n_features = 1000, 10000
    data_params = {'n_samples': n_samples, 'n_features': n_features,
                   'tail_strength': .7, 'random_state': random_state}
    dataset_name = "low rank matrix %d x %d" % (n_samples, n_features)
    ranks = [10, 50, 100]

    if enable_spectral_norm:
        all_spectral = defaultdict(list)
    all_frobenius = defaultdict(list)
    for rank in ranks:
        X = make_low_rank_matrix(effective_rank=rank, **data_params)
        if enable_spectral_norm:
            X_spectral_norm = norm_diff(X, norm=2, msg=False)
        X_fro_norm = norm_diff(X, norm='fro', msg=False)

        for n_comp in [np.int(rank/2), rank, rank*2]:
            label = "rank=%d, n_comp=%d" % (rank, n_comp)
            print(label)
            for pi in power_list:
                U, s, V, _ = svd_timing(X, n_comp, n_iter=pi, n_oversamples=2,
                                        power_iteration_normalizer='LU')
                if enable_spectral_norm:
                    A = U.dot(np.diag(s).dot(V))
                    all_spectral[label].append(norm_diff(X - A, norm=2) /
                                               X_spectral_norm)
                f = scalable_frobenius_norm_discrepancy(X, U, s, V)
                all_frobenius[label].append(f / X_fro_norm)

    if enable_spectral_norm:
        title = "%s: spectral norm diff vs n power iteration" % (dataset_name)
        plot_power_iter_vs_s(power_iter, all_spectral, title)
    title = "%s: Frobenius norm diff vs n power iteration" % (dataset_name)
    plot_power_iter_vs_s(power_iter, all_frobenius, title)

def bench_c(datasets, n_comps):
    all_time = defaultdict(list)
    if enable_spectral_norm:
        all_spectral = defaultdict(list)
    all_frobenius = defaultdict(list)

    for dataset_name in datasets:
        X = get_data(dataset_name)
        if X is None:
            continue

        if enable_spectral_norm:
            X_spectral_norm = norm_diff(X, norm=2, msg=False)
        X_fro_norm = norm_diff(X, norm='fro', msg=False)
        n_comps = np.minimum(n_comps, np.min(X.shape))

        label = "sklearn"
        print("%s %d x %d - %s" %
              (dataset_name, X.shape[0], X.shape[1], label))
        U, s, V, time = svd_timing(X, n_comps, n_iter=2, n_oversamples=10,
                                   method=label)

        all_time[label].append(time)
        if enable_spectral_norm:
            A = U.dot(np.diag(s).dot(V))
            all_spectral[label].append(norm_diff(X - A, norm=2) /
                                       X_spectral_norm)
        f = scalable_frobenius_norm_discrepancy(X, U, s, V)
        all_frobenius[label].append(f / X_fro_norm)

        if fbpca_available:
            label = "fbpca"
            print("%s %d x %d - %s" %
                  (dataset_name, X.shape[0], X.shape[1], label))
            U, s, V, time = svd_timing(X, n_comps, n_iter=2, n_oversamples=2,
                                       method=label)
            all_time[label].append(time)
            if enable_spectral_norm:
                A = U.dot(np.diag(s).dot(V))
                all_spectral[label].append(norm_diff(X - A, norm=2) /
                                           X_spectral_norm)
            f = scalable_frobenius_norm_discrepancy(X, U, s, V)
            all_frobenius[label].append(f / X_fro_norm)

    if len(all_time) == 0:
        raise ValueError("No tests ran. Aborting.")

    if enable_spectral_norm:
        title = "normalized spectral norm diff vs running time"
        scatter_time_vs_s(all_time, all_spectral, datasets, title)
    title = "normalized Frobenius norm diff vs running time"
    scatter_time_vs_s(all_time, all_frobenius, datasets, title)

if __name__ == '__main__':
    random_state = check_random_state(1234)

    power_iter = np.linspace(0, 6, 7, dtype=int)
    n_comps = 50

    for dataset_name in datasets:
        X = get_data(dataset_name)
        if X is None:
            continue
        print(" >>>>>> Benching sklearn and fbpca on %s %d x %d" %
              (dataset_name, X.shape[0], X.shape[1]))
        bench_a(X, dataset_name, power_iter, n_oversamples=2,
                n_comps=np.minimum(n_comps, np.min(X.shape)))

    print(" >>>>>> Benching on simulated low rank matrix with variable rank")
    bench_b(power_iter)

    print(" >>>>>> Benching sklearn and fbpca default configurations")
    bench_c(datasets + big_sparse_datasets, n_comps)

    plt.show()


text:
<?php

namespace mageekguy\atoum\asserters;

use
	mageekguy\atoum\asserters
;

class hash extends asserters\string
{
	public function isSha1($failMessage = null)
	{
		return $this->isHash(40, $failMessage);
	}

	public function isSha256($failMessage = null)
	{
		return $this->isHash(64, $failMessage);
	}

	public function isSha512($failMessage = null)
	{
		return $this->isHash(128, $failMessage);
	}

	public function isMd5($failMessage = null)
	{
		return $this->isHash(32, $failMessage);
	}

	protected function isHash($length, $failMessage = null)
	{
		if (strlen($this->valueIsSet()->value) === $length)
		{
			 $this->match('/^[a-fA-F0-9]+$/', $failMessage ?: $this->_('%s does not match given pattern', $this));
		}
		else
		{
			$this->fail($failMessage ?: $this->_('%s should be a string of %d characters', $this, $length));
		}

		return $this;
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Lamin Sanneh
 * Date: 5/19/14
 * Time: 10:35 AM
 */

namespace LaminSanneh\FlexiContact\Models;

use Model;
class Settings extends Model{

    public $implement = [
        'System.Behaviors.SettingsModel'
    ];

    public $settingsCode = 'laminsanneh_flexicontact_settings';

    public $settingsFields = 'fields.yaml';
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
	<class name="Zh.DAL.Define.Entities.AdTemplate, Zh.DAL.Define" table="AdTemplate">
		<id name="ID" type="Guid" unsaved-value="00000000-0000-0000-0000-000000000000">
			<column name="ID" length="16" sql-type="uniqueidentifier" not-null="true" unique="true"/>
            <generator class="assigned" />
		</id>
        <!--  -->
		<property name="AdBannerID" type="Guid"  >
			<column name="AdBannerID" length="16" sql-type="uniqueidentifier" not-null="true"/>
		</property>
        <!--  -->
		<property name="TemplateName" type="String"  >
			<column name="TemplateName" length="50" sql-type="nvarchar" not-null="true"/>
		</property>
        <!--  -->
		<property name="Layout" type="Int32"  >
			<column name="Layout" length="4" sql-type="int" not-null="true"/>
		</property>
        <!--  -->
		<property name="Order" type="Int32"  >
			<column name="`Order`" length="4" sql-type="int" not-null="true"/>
		</property>

         <!--  -->
        <many-to-one update="false" insert="false" name="AdBanner" class="Zh.DAL.Define.Entities.AdBanner, Zh.DAL.Define">
			<column name="AdBannerID" length="16" sql-type="uniqueidentifier" not-null="true"/>
		</many-to-one>

		<bag name="Ad_single" inverse="true" lazy="true" cascade="all">
			<key column="TemplateID"/>
			<one-to-many class="Zh.DAL.Define.Entities.Ad_single, Zh.DAL.Define"/>
		</bag>

	</class>
</hibernate-mapping>


text: {:plugs('uploadImg')}


text:
"""
    REST API Documentation for the NRS TFRS Credit Trading Application

    The Transportation Fuels Reporting System is being designed to streamline compliance reporting for transportation fuel suppliers in accordance with the Renewable & Low Carbon Fuel Requirements Regulation.

    OpenAPI spec version: v1

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import datetime

from django.db import models
from django.utils import timezone
from .PermissionViewModel import PermissionViewModel

class UserDetailsViewModel(models.Model):
    givenName = models.CharField(max_length=255)
    surname = models.CharField(max_length=255)
    initials = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    active = models.BooleanField()
    permissions = models.ManyToManyField('PermissionViewModel',related_name='UserDetailsViewModelpermissions')


text:
static int local_EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
  int i,b;
  int n;

  *outl=0;
  b=ctx->cipher->block_size;
  if (ctx->flags & EVP_CIPH_NO_PADDING)
    {
      if(ctx->buf_len)
	{
	  EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
	  return 0;
	}
      *outl = 0;
      return 1;
    }
  if (b > 1)
    {
      if (ctx->buf_len || !ctx->final_used)
	{
	  EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_WRONG_FINAL_BLOCK_LENGTH);
	  return(0);
	}
      OPENSSL_assert(b <= sizeof ctx->final);
      n=ctx->final[b-1];
      if (n > b)
	{
	  EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_BAD_DECRYPT);
	  return(0);
	}
      for (i=0; i<n; i++)
	{
	  if (ctx->final[--b] != n)
	    {
	      EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_BAD_DECRYPT);
	      return(0);
	    }
	}
      n=ctx->cipher->block_size-n;
      for (i=0; i<n; i++)
	out[i]=ctx->final[i];
      *outl=n;
    }
  else
    *outl=0;
  return(1);
}

// LengthWithoutIncompleteUtf8 from V8 d8-posix.cc
// see http://v8.googlecode.com/svn/trunk/src/d8-posix.cc
static int LengthWithoutIncompleteUtf8(char* buffer, int len) {
  int answer = len;
  // 1-byte encoding.
  static const int kUtf8SingleByteMask = 0x80;
  static const int kUtf8SingleByteValue = 0x00;
  // 2-byte encoding.
  static const int kUtf8TwoByteMask = 0xe0;
  static const int kUtf8TwoByteValue = 0xc0;
  // 3-byte encoding.
  static const int kUtf8ThreeByteMask = 0xf0;
  static const int kUtf8ThreeByteValue = 0xe0;
  // 4-byte encoding.
  static const int kUtf8FourByteMask = 0xf8;
  static const int kUtf8FourByteValue = 0xf0;
  // Subsequent bytes of a multi-byte encoding.
  static const int kMultiByteMask = 0xc0;
  static const int kMultiByteValue = 0x80;
  int multi_byte_bytes_seen = 0;
  while (answer > 0) {
    int c = buffer[answer - 1];
    // Ends in valid single-byte sequence?
    if ((c & kUtf8SingleByteMask) == kUtf8SingleByteValue) return answer;
    // Ends in one or more subsequent bytes of a multi-byte value?
    if ((c & kMultiByteMask) == kMultiByteValue) {
      multi_byte_bytes_seen++;
      answer--;
    } else {
      if ((c & kUtf8TwoByteMask) == kUtf8TwoByteValue) {
        if (multi_byte_bytes_seen >= 1) {
          return answer + 2;
        }
        return answer - 1;
      } else if ((c & kUtf8ThreeByteMask) == kUtf8ThreeByteValue) {
        if (multi_byte_bytes_seen >= 2) {
          return answer + 3;
        }
        return answer - 1;
      } else if ((c & kUtf8FourByteMask) == kUtf8FourByteValue) {
        if (multi_byte_bytes_seen >= 3) {
          return answer + 4;
        }
        return answer - 1;
      } else {
        return answer;  // Malformed UTF-8.
      }
    }
  }
  return 0;
}

void
Decipher::Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(t, "init", DecipherInit);
    NODE_SET_PROTOTYPE_METHOD(t, "initiv", DecipherInitIv);
    NODE_SET_PROTOTYPE_METHOD(t, "update", DecipherUpdate);
    NODE_SET_PROTOTYPE_METHOD(t, "final", DecipherFinal);
    NODE_SET_PROTOTYPE_METHOD(t, "finaltol", DecipherFinalTolerate);

    target->Set(String::NewSymbol("Decipher"), t->GetFunction());
  }

bool Decipher::DecipherInit(char* cipherType, char* key_buf, int key_buf_len)
  {
    cipher = EVP_get_cipherbyname(cipherType);
    if(!cipher) {
      fprintf(stderr, "node-crypto : Unknown cipher %s\n", cipherType);
      return false;
    }

    unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH];
    int key_len = EVP_BytesToKey(cipher, EVP_md5(), NULL, (unsigned char*) key_buf, key_buf_len, 1, key, iv);

    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit(&ctx,cipher,(unsigned char *)key,(unsigned char *)iv, false);
    if (!EVP_CIPHER_CTX_set_key_length(&ctx,key_len)) {
    	fprintf(stderr, "node-crypto : Invalid key length %d\n", key_len);
    	EVP_CIPHER_CTX_cleanup(&ctx);
    	return false;
    }
    initialised = true;
    return true;
  }

bool Decipher::DecipherInitIv(char* cipherType, char* key, int key_len, char *iv, int iv_len)
  {
    cipher = EVP_get_cipherbyname(cipherType);
    if(!cipher) {
      fprintf(stderr, "node-crypto : Unknown cipher %s\n", cipherType);
      return false;
    }
    if (EVP_CIPHER_iv_length(cipher)!=iv_len) {
    	fprintf(stderr, "node-crypto : Invalid IV length %d\n", iv_len);
      return false;
    }
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit(&ctx,cipher,(unsigned char *)key,(unsigned char *)iv, false);
    if (!EVP_CIPHER_CTX_set_key_length(&ctx,key_len)) {
    	fprintf(stderr, "node-crypto : Invalid key length %d\n", key_len);
    	EVP_CIPHER_CTX_cleanup(&ctx);
    	return false;
    }
    initialised = true;
    return true;
  }

int Decipher::DecipherUpdate(char* data, int len, unsigned char** out, int* out_len) {
    if (!initialised)
      return 0;
    *out_len=len+EVP_CIPHER_CTX_block_size(&ctx);
    *out=(unsigned char*)malloc(*out_len);

    EVP_CipherUpdate(&ctx, *out, out_len, (unsigned char*)data, len);
    return 1;
  }

int Decipher::DecipherFinal(unsigned char** out, int *out_len, bool tolerate_padding) {
    if (!initialised)
      return 0;
    *out = (unsigned char*) malloc(EVP_CIPHER_CTX_block_size(&ctx));
    if (tolerate_padding) {
      local_EVP_DecryptFinal_ex(&ctx,*out,out_len);
    } else {
      EVP_CipherFinal(&ctx,*out,out_len);
    }
    EVP_CIPHER_CTX_cleanup(&ctx);
    initialised = false;
    return 1;
  }

Handle<Value>
Decipher::New (const Arguments& args)
  {
    HandleScope scope;

    Decipher *cipher = new Decipher();
    cipher->Wrap(args.This());
    return args.This();
  }

Handle<Value>
Decipher::DecipherInit(const Arguments& args) {
    Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

    HandleScope scope;

    cipher->incomplete_utf8=NULL;
    cipher->incomplete_hex_flag=false;

    if (args.Length() <= 1 || !args[0]->IsString() || !args[1]->IsString()) {
      return ThrowException(String::New("Must give cipher-type, key as argument"));
    }

    ssize_t key_len = DecodeBytes(args[1], BINARY);

    if (key_len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }

    char* key_buf = new char[key_len];
    ssize_t key_written = DecodeWrite(key_buf, key_len, args[1], BINARY);
    assert(key_written == key_len);

    String::Utf8Value cipherType(args[0]->ToString());

    bool r = cipher->DecipherInit(*cipherType, key_buf,key_len);

    return args.This();
  }

Handle<Value>
Decipher::DecipherInitIv(const Arguments& args) {
    Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

    HandleScope scope;

    cipher->incomplete_utf8=NULL;
    cipher->incomplete_hex_flag=false;

    if (args.Length() <= 2 || !args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString()) {
      return ThrowException(String::New("Must give cipher-type, key, and iv as argument"));
    }

    ssize_t key_len = DecodeBytes(args[1], BINARY);

    if (key_len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }

    ssize_t iv_len = DecodeBytes(args[2], BINARY);

    if (iv_len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }

    char* key_buf = new char[key_len];
    ssize_t key_written = DecodeWrite(key_buf, key_len, args[1], BINARY);
    assert(key_written == key_len);

    char* iv_buf = new char[iv_len];
    ssize_t iv_written = DecodeWrite(iv_buf, iv_len, args[2], BINARY);
    assert(iv_written == iv_len);

    String::Utf8Value cipherType(args[0]->ToString());

    bool r = cipher->DecipherInitIv(*cipherType, key_buf,key_len,iv_buf,iv_len);

    return args.This();
  }

Handle<Value>
Decipher::DecipherUpdate(const Arguments& args) {
    Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

    HandleScope scope;

    ssize_t len = DecodeBytes(args[0], BINARY);
    char* buf = new char[len];
    ssize_t written = DecodeWrite(buf, len, args[0], BINARY);
    char* ciphertext;
    int ciphertext_len;

    if (args.Length() <= 1 || !args[1]->IsString()) {
      // Binary - do nothing
    } else {
      String::Utf8Value encoding(args[1]->ToString());
      if (strcasecmp(*encoding, "hex") == 0) {
	// Hex encoding
	// Do we have a previous hex carry over?
	if (cipher->incomplete_hex_flag) {
	  char* complete_hex = (char*)malloc(len+2);
	  memcpy(complete_hex, &cipher->incomplete_hex, 1);
	  memcpy(complete_hex+1, buf, len);
	  free(buf);
	  buf = complete_hex;
	  len += 1;
	}
	// Do we have an incomplete hex stream?
	if ((len>0) && (len % 2 !=0)) {
	  len--;
	  cipher->incomplete_hex=buf[len];
	  cipher->incomplete_hex_flag=true;
	  buf[len]=0;
	}
        hex_decode((unsigned char*)buf, len, (char **)&ciphertext, &ciphertext_len);

        free(buf);
	buf = ciphertext;
	len = ciphertext_len;
      } else if (strcasecmp(*encoding, "base64") == 0) {
        unbase64((unsigned char*)buf, len, (char **)&ciphertext, &ciphertext_len);
        free(buf);
	buf = ciphertext;
	len = ciphertext_len;
      } else if (strcasecmp(*encoding, "binary") == 0) {
        // Binary - do nothing
      } else {
	fprintf(stderr, "node-crypto : Decipher .update encoding "
		"can be binary, hex or base64\n");
      }

    }

    unsigned char *out=0;
    int out_len=0;
    int r = cipher->DecipherUpdate(buf, len,&out,&out_len);

    Local<Value> outString;
    if (out_len==0) {
      outString=String::New("");
    } else if (args.Length() <= 2 || !args[2]->IsString()) {
      outString = Encode(out, out_len, BINARY);
    } else {
      enum encoding enc = ParseEncoding(args[2]);
      if (enc == UTF8) {
	// See if we have any overhang from last utf8 partial ending
	if (cipher->incomplete_utf8!=NULL) {
	  char* complete_out = (char *)malloc(cipher->incomplete_utf8_len + out_len);
	  memcpy(complete_out, cipher->incomplete_utf8, cipher->incomplete_utf8_len);
	  memcpy((char *)complete_out+cipher->incomplete_utf8_len, out, out_len);
	  free(out);
	  free(cipher->incomplete_utf8);
	  cipher->incomplete_utf8=NULL;
	  out = (unsigned char*)complete_out;
	  out_len += cipher->incomplete_utf8_len;
	}
	// Check to see if we have a complete utf8 stream
	int utf8_len = LengthWithoutIncompleteUtf8((char *)out, out_len);
	if (utf8_len<out_len) { // We have an incomplete ut8 ending
	  cipher->incomplete_utf8_len = out_len-utf8_len;
          cipher->incomplete_utf8 = (unsigned char *)malloc(cipher->incomplete_utf8_len+1);
          memcpy(cipher->incomplete_utf8, &out[utf8_len], cipher->incomplete_utf8_len);
	}
        outString = Encode(out, utf8_len, enc);
      } else {
        outString = Encode(out, out_len, enc);
      }
    }

    if (out) free(out);
    free(buf);
    return scope.Close(outString);

  }

Handle<Value>
Decipher::DecipherFinal(const Arguments& args) {
    Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

    HandleScope scope;

    unsigned char* out_value;
    int out_len;
    char* out_hexdigest;
    int out_hex_len;
    Local<Value> outString ;

    int r = cipher->DecipherFinal(&out_value, &out_len, false);

    if (out_len == 0 || r == 0) {
      return scope.Close(String::New(""));
    }

    if (args.Length() == 0 || !args[0]->IsString()) {
      outString = Encode(out_value, out_len, BINARY);
    } else {
      enum encoding enc = ParseEncoding(args[0]);
      if (enc == UTF8) {
	// See if we have any overhang from last utf8 partial ending
	if (cipher->incomplete_utf8!=NULL) {
	  char* complete_out = (char *)malloc(cipher->incomplete_utf8_len + out_len);
	  memcpy(complete_out, cipher->incomplete_utf8, cipher->incomplete_utf8_len);
	  memcpy((char *)complete_out+cipher->incomplete_utf8_len, out_value, out_len);
	  free(cipher->incomplete_utf8);
	  cipher->incomplete_utf8=NULL;
	  outString = Encode(complete_out, cipher->incomplete_utf8_len+out_len, enc);
	  free(complete_out);
	} else {
	  outString = Encode(out_value, out_len, enc);
	}
      } else {
	outString = Encode(out_value, out_len, enc);
      }
    }
    free(out_value);
    return scope.Close(outString);

  }

Handle<Value>
Decipher::DecipherFinalTolerate(const Arguments& args) {
    Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

    HandleScope scope;

    unsigned char* out_value;
    int out_len;
    char* out_hexdigest;
    int out_hex_len;
    Local<Value> outString ;

    int r = cipher->DecipherFinal(&out_value, &out_len, true);

    if (out_len == 0 || r == 0) {
      return scope.Close(String::New(""));
    }

    if (args.Length() == 0 || !args[0]->IsString()) {
      outString = Encode(out_value, out_len, BINARY);
    } else {
      enum encoding enc = ParseEncoding(args[0]);
      if (enc == UTF8) {
	// See if we have any overhang from last utf8 partial ending
	if (cipher->incomplete_utf8!=NULL) {
	  char* complete_out = (char *)malloc(cipher->incomplete_utf8_len + out_len);
	  memcpy(complete_out, cipher->incomplete_utf8, cipher->incomplete_utf8_len);
	  memcpy((char *)complete_out+cipher->incomplete_utf8_len, out_value, out_len);
	  free(cipher->incomplete_utf8);
	  cipher->incomplete_utf8=NULL;
	  outString = Encode(complete_out, cipher->incomplete_utf8_len+out_len, enc);
	  free(complete_out);
	} else {
	  outString = Encode(out_value, out_len, enc);
	}
      } else {
	outString = Encode(out_value, out_len, enc);
      }
    }
    free(out_value);
    return scope.Close(outString);

  }

Decipher::Decipher () : ObjectWrap ()
  {
    initialised = false;
  }

Decipher::~Decipher ()
  {
  }


text:
package org.hoteia.qalingo.core.web.mvc.viewbean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hoteia.qalingo.core.util.CoreUtil;

public class ProductAssociationLinkViewBean extends AbstractViewBean {

	/**
	 * Generated UID
	 */
	private static final long serialVersionUID = 7398066505291279593L;

	protected int orderItem;
	protected String name;
	protected String description;
	protected String type;

    protected String i18nName;
    protected String i18nDescription;
    protected String i18nShortDescription;

    protected List<AssetViewBean> assets = new ArrayList<AssetViewBean>();

	protected String productDetailsUrl;

	public int getOrderItem() {
		return orderItem;
	}

	public void setOrderItem(int orderItem) {
		this.orderItem = orderItem;
	}

	public String getName() {
		return name;
	}

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

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getI18nName() {
        if(StringUtils.isNotEmpty(i18nName)){
            return i18nName;
        }
        return name;
    }

    public void setI18nName(String i18nName) {
        this.i18nName = i18nName;
    }

    public String getI18nDescription() {
        if(StringUtils.isNotEmpty(i18nDescription)){
            return i18nDescription;
        }
        return description;
    }

    public void setI18nDescription(String i18nDescription) {
        this.i18nDescription = i18nDescription;
    }

    public String getI18nShortDescription() {
        return i18nShortDescription;
    }

    public void setI18nShortDescription(String i18nShortDescription) {
        this.i18nShortDescription = i18nShortDescription;
    }

    public String getI18nTruncatedDescription() {
        if(StringUtils.isNotEmpty(getI18nShortDescription())){
            if(getI18nShortDescription().length() >= 150){
                return CoreUtil.handleTruncatedDescription(getI18nShortDescription());
            } else {
                return getI18nShortDescription();
            }
        } else if (StringUtils.isNotEmpty(getI18nDescription())){
            if(getI18nDescription().length() >= 150){
                return CoreUtil.handleTruncatedDescription(getI18nDescription());
            } else {
                return getI18nDescription();
            }
        }
        return "";
    }

    public List<AssetViewBean> getAssets() {
        return assets;
    }

    public String getAssetPath(String type) {
        for (Iterator<AssetViewBean> iterator = assets.iterator(); iterator.hasNext();) {
            AssetViewBean assetViewBean = (AssetViewBean) iterator.next();
            if(assetViewBean.getType().equals(type)){
                return assetViewBean.getPath();
            }
        }
        return null;
    }

    public String getAssetAbsoluteWebPath(String type) {
        for (Iterator<AssetViewBean> iterator = assets.iterator(); iterator.hasNext();) {
            AssetViewBean assetViewBean = (AssetViewBean) iterator.next();
            if(assetViewBean.getType().equals(type)){
                return assetViewBean.getAbsoluteWebPath();
            }
        }
        return null;
    }

    public String getAssetRelativeWebPath(String type) {
        for (Iterator<AssetViewBean> iterator = assets.iterator(); iterator.hasNext();) {
            AssetViewBean assetViewBean = (AssetViewBean) iterator.next();
            if(assetViewBean.getType().equals(type)){
                return assetViewBean.getRelativeWebPath();
            }
        }
        return null;
    }

    public void setAssets(List<AssetViewBean> assets) {
        this.assets = assets;
    }

	public String getProductDetailsUrl() {
		return productDetailsUrl;
	}

	public void setProductDetailsUrl(String productDetailsUrl) {
		this.productDetailsUrl = productDetailsUrl;
	}

}


text:
__author__ = 'sergey'

from dedupsqlfs.db.mysql.table import Table

class TableTree( Table ):

    _table_name = "tree"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS `%s` (" % self._table_name+
                "`id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, "+
                "`parent_id` BIGINT UNSIGNED, "+
                "`name_id` BIGINT UNSIGNED NOT NULL, "+
                "`inode_id` BIGINT UNSIGNED NOT NULL"+
            ")"+
            self._getCreationAppendString()
        )

        self.createIndexIfNotExists("pn", ('parent_id', 'name_id',), unique=True)
        self.createIndexIfNotExists("inode", ('inode_id',))
        self.createIndexIfNotExists("parent_id", ('parent_id', 'id'))

        return

    def getRowSize(self):
        return 4 * 8

    def insert( self, parent_id, name_id, inode_id ):
        """
        :param parent_id: int|None
        :param name_id: int
        :param inode_id: int
        :return: int
        """
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "INSERT INTO `%s` " % self.getName()+
            " (`parent_id`, `name_id`, `inode_id`) "+
            "VALUES (%(parent)s, %(name)s, %(inode)s)",
            {
                "parent": parent_id,
                "name": name_id,
                "inode": inode_id
            }
        )
        item = cur.lastrowid
        self.stopTimer('insert')
        return item

    def rename_inode( self, node_id, new_parent_id, new_name_id):
        """
        :param parent_id: int|None
        :param name_id: int
        :param inode_id: int
        :return: int
        """
        self.startTimer()
        cur = self.getCursor()
        cur.execute("UPDATE `%s` " % self.getName()+
                    "SET parent_id=%(parent)s, name_id=%(name)s WHERE id=%(id)s",
                    {
                        "parent": new_parent_id,
                        "name": new_name_id,
                        "id": node_id
                     })
        item = cur.lastrowid
        self.stopTimer('rename_inode')
        return item

    def delete(self, node_id):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "DELETE FROM `%s` " % self.getName()+
            " WHERE `id`=%(id)s",
            {
                "id": node_id
            }
        )
        item = cur.rowcount
        self.stopTimer('delete')
        return item

    def find_by_parent_name(self, parent_id, name_id):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "SELECT `id`, `inode_id`, `name_id` FROM `%s` " % self.getName()+
            " WHERE `parent_id`=%(parent)s AND `name_id`=%(name)s",
            {
                "parent": parent_id,
                "name": name_id
            }
        )
        item = cur.fetchone()
        self.stopTimer('find_by_parent_name')
        return item

    def find_by_inode(self, inode_id):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM `%s` " % self.getName()+
            " WHERE `inode_id`=%(inode)s",
            {
                "inode": inode_id
            }
        )
        item = cur.fetchone()
        self.stopTimer('find_by_inode')
        return item

    def get(self, node_id):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM `%s` " % self.getName()+
            " WHERE `id`=%(node)s",
            {
                "node": node_id
            }
        )
        item = cur.fetchone()
        cur.close()
        self.stopTimer('get')
        return item

    def get_children_inodes(self, parent_id):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "SELECT `inode_id` FROM `%s` " % self.getName()+
            " WHERE `parent_id`=%(parent)s ORDER BY `id` ASC",
            {
                "parent": parent_id
            }
        )
        _items = cur.fetchall()
        items = ("%i" % _i["inode_id"] for _i in _items)
        self.stopTimer('get_children_inodes')
        return items

    def get_children(self, parent_id, offset=0):
        self.startTimer()
        cur = self.getCursor()
        cur.execute(
            "SELECT `id`,`name_id`,`inode_id` FROM `%s` " % self.getName()+
            " WHERE `parent_id`=%(parent)s AND `id`>%(offset)s ORDER BY `id` ASC",
            {
                "parent": parent_id,
                "offset": offset
            }
        )
        items = (item for item in cur)
        self.stopTimer('get_children')
        return items

    def get_inodes_by_inodes(self, inode_ids):
        self.startTimer()

        iids = ()
        id_str = ",".join(inode_ids)
        if id_str:
            cur = self.getCursor()
            cur.execute("SELECT `inode_id` FROM `%s` " % self.getName()+
                            " WHERE `inode_id` IN (%s)" % (id_str,))
            iids = set(str(item["inode_id"]) for item in cur)

        self.stopTimer('get_inodes_by_inodes')
        return iids

    def get_inodes_by_inodes_intgen(self, id_str):
        self.startTimer()

        iids = ()
        if id_str:
            cur = self.getCursor()
            cur.execute("SELECT `inode_id` FROM `%s` " % self.getName()+
                            " WHERE `inode_id` IN (%s)" % (id_str,))
            iids = (item["inode_id"] for item in cur)

        self.stopTimer('get_inodes_by_inodes_intgen')
        return iids

    def get_all_inodes_set(self):
        self.startTimer()

        cur = self.getCursor()
        cur.execute("SELECT `inode_id` FROM `%s` " % self.getName())
        iids = set(item["inode_id"] for item in cur)

        self.stopTimer('get_all_inodes_set')
        return iids

    pass


text:
package com.evalonlabs.booking.http;

/**
 * Created by Evangelos
 */
public interface ContextSystem {
}


text:
#include <skiboot.h>
#include <device.h>
#include <lpc.h>
#include <console.h>
#include <opal.h>
#include <interrupts.h>
#include <libflash/libflash.h>
#include <libflash/libffs.h>
#include <libflash/blocklevel.h>
#include <sfc-ctrl.h>
#include "ec/config.h"
#include "ec/gpio.h"

/*
 * EC GPIO mapping
 */
#define RHESUS_RST_UCD90160_N	EC_GPIO_PORT_J, 3
#define RHESUS_FM_PWR_CYCLE_N	EC_GPIO_PORT_K, 2
#define RHESUS_EN_PWR_ON_SEQ	EC_GPIO_PORT_R, 1
#define RHESUS_BOARD_REVISION0	EC_GPIO_PORT_F, 3
#define RHESUS_BOARD_REVISION1	EC_GPIO_PORT_F, 2
#define RHESUS_BOARD_REVISION2	EC_GPIO_PORT_E, 5
#define RHESUS_BOARD_REVISION3	EC_GPIO_PORT_E, 4
#define RHESUS_BOARD_REVISION4	EC_GPIO_PORT_E, 1

/*
 * IO accessors for the EC driver
 */
void ec_outb(uint16_t addr, uint8_t data)
{
	lpc_outb(data, addr);
}

uint8_t ec_inb(uint16_t addr)
{
	return lpc_inb(addr);
}

static int rhesus_board_revision(void)
{
    int revision = 0, ret = 0, i = 0;

    static const struct {
        EcGpioPort port;
        uint8_t pin;
    } revision_gpios[] = {
        { RHESUS_BOARD_REVISION0 },
        { RHESUS_BOARD_REVISION1 },
        { RHESUS_BOARD_REVISION2 },
        { RHESUS_BOARD_REVISION3 },
        { RHESUS_BOARD_REVISION4 },
    };
    for (i = 0; i < sizeof(revision_gpios) / sizeof(revision_gpios[0]); ++i)
    {
        ret = ec_gpio_read(revision_gpios[i].port, revision_gpios[i].pin);
        if (ret < 0)
            return ret;
        revision <<= 1; revision |= ret;
    }

    return revision;
}

static int64_t rhesus_reboot(void)
{
    // TODO(rlippert): This should use EC_SYS_RST_N, but there is nothing to
    // deassert that at the moment.
    int ret = 0;
    ret = ec_gpio_set(RHESUS_FM_PWR_CYCLE_N, 0);
    if (ret < 0) {
        return ret;
    }

    ret = ec_gpio_setup(RHESUS_FM_PWR_CYCLE_N,
                        EC_GPIO_OUTPUT,
                        EC_GPIO_PULLUP_DISABLE);
    if (ret < 0) {
        return ret;
    }

    return 0;
}

static int64_t rhesus_power_down(uint64_t request __unused)
{
    int ret = 0;
    ret = ec_gpio_set(RHESUS_EN_PWR_ON_SEQ, 0);
    if (ret < 0) {
        return ret;
    }

    ret = ec_gpio_setup(RHESUS_EN_PWR_ON_SEQ,
                        EC_GPIO_OUTPUT,
                        EC_GPIO_PULLUP_DISABLE);
    if (ret < 0) {
        return ret;
    }

    return 0;
}

static int rhesus_pnor_init(void)
{
	struct spi_flash_ctrl *pnor_ctrl;
	struct blocklevel_device *bl = NULL;
	int rc;

	/* Open controller, flash and ffs */
	rc = sfc_open(&pnor_ctrl);
	if (rc) {
		prerror("PLAT: Failed to open PNOR flash controller\n");
		goto fail;
	}
	rc = flash_init(pnor_ctrl, &bl, NULL);
	if (rc) {
		prerror("PLAT: Failed to open init PNOR driver\n");
		goto fail;
	}

	rc = flash_register(bl);
	if (!rc)
		return 0;

 fail:
	if (bl)
		flash_exit(bl);
	if (pnor_ctrl)
		sfc_close(pnor_ctrl);

	return rc;
}

static void rhesus_init(void)
{
	/* Initialize PNOR/NVRAM */
	rhesus_pnor_init();

	/* Setup UART for direct use by Linux */
	uart_set_console_policy(UART_CONSOLE_OS);
}

static void rhesus_dt_fixup_uart(struct dt_node *lpc, bool has_irq)
{
	/*
	 * The official OF ISA/LPC binding is a bit odd, it prefixes
	 * the unit address for IO with "i". It uses 2 cells, the first
	 * one indicating IO vs. Memory space (along with bits to
	 * represent aliasing).
	 *
	 * We pickup that binding and add to it "2" as a indication
	 * of FW space.
	 *
	 * TODO: Probe the UART instead if the LPC bus allows for it
	 */
	struct dt_node *uart;
	char namebuf[32];
#define UART_IO_BASE	0x3f8
#define UART_IO_COUNT	8

	snprintf(namebuf, sizeof(namebuf), "serial@i%x", UART_IO_BASE);
	uart = dt_new(lpc, namebuf);

	dt_add_property_cells(uart, "reg",
			      1, /* IO space */
			      UART_IO_BASE, UART_IO_COUNT);
	dt_add_property_strings(uart, "compatible",
				"ns16550",
				"pnpPNP,501");
	dt_add_property_cells(uart, "clock-frequency", 1843200);
	dt_add_property_cells(uart, "current-speed", 115200);

	/*
	 * This is needed by Linux for some obscure reasons,
	 * we'll eventually need to sanitize it but in the meantime
	 * let's make sure it's there
	 */
	dt_add_property_strings(uart, "device_type", "serial");

	/* Expose the external interrupt if supported
	 */
	if (has_irq) {
		uint32_t chip_id = dt_get_chip_id(lpc);
		uint32_t irq = get_psi_interrupt(chip_id) + P8_IRQ_PSI_EXTERNAL;
		dt_add_property_cells(uart, "interrupts", irq, 1);
		dt_add_property_cells(uart, "interrupt-parent",
				      get_ics_phandle());
	}
}

/*
 * This adds the legacy RTC device to the device-tree
 * for Linux to use
 */
static void rhesus_dt_fixup_rtc(struct dt_node *lpc)
{
	struct dt_node *rtc;

	/*
	 * Follows the structure expected by the kernel file
	 * arch/powerpc/sysdev/rtc_cmos_setup.c
	 */
	rtc = dt_new_addr(lpc, "rtc", EC_RTC_PORT_BASE);
	assert(rtc);
	dt_add_property_string(rtc, "compatible", "pnpPNP,b00");
	dt_add_property_cells(rtc, "reg",
			      1, /* IO space */
			      EC_RTC_PORT_BASE,
			      /* 1 index/data pair per 128 bytes */
			      (EC_RTC_BLOCK_SIZE / 128) * 2);
}

static void rhesus_dt_fixup(bool has_uart_irq)
{
	struct dt_node *n, *primary_lpc = NULL;

	/* Find the primary LPC bus */
	dt_for_each_compatible(dt_root, n, "ibm,power8-lpc") {
		if (!primary_lpc || dt_has_node_property(n, "primary", NULL))
			primary_lpc = n;
		if (dt_has_node_property(n, "#address-cells", NULL))
			break;
	}

	if (!primary_lpc)
		return;

	rhesus_dt_fixup_rtc(primary_lpc);
	rhesus_dt_fixup_uart(primary_lpc, has_uart_irq);
}

static bool rhesus_probe(void)
{
	const char *model;
	int rev;
	bool has_uart_irq = false;

	if (!dt_node_is_compatible(dt_root, "ibm,powernv"))
		return false;

	model = dt_prop_get_def(dt_root, "model", NULL);
	if (!model || !(strstr(model, "rhesus") || strstr(model, "RHESUS")))
		return false;

	/* Grab board version from EC */
	rev = rhesus_board_revision();
	if (rev >= 0) {
		printf("Rhesus board rev %d\n", rev);
		dt_add_property_cells(dt_root, "revision-id", rev);
	} else
		prerror("Rhesus board revision not found !\n");

	/* Add missing bits of device-tree such as the UART */
	rhesus_dt_fixup(has_uart_irq);

	/* Setup UART and use it as console */
	uart_init();

	return true;
}

DECLARE_PLATFORM(rhesus) = {
	.name		= "Rhesus",
	.probe		= rhesus_probe,
	.init		= rhesus_init,
	.cec_power_down	= rhesus_power_down,
	.cec_reboot	= rhesus_reboot,
};


text:
v2.0.1 February 21, 2015
    - Escaping things for regexps

v2.0.0 February 10, 2015
	- Initial working version


text:
"""Fixes implementation which overwrites the variable."""
#
# (C) Pywikibot team, 2015-2018
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals

# Just kill the old value suffices
fixes = {}


text:
import { WebGLHardwareTexture } from "../../Engines/WebGL/webGLHardwareTexture";
import { InternalTexture, InternalTextureSource } from "../../Materials/Textures/internalTexture";
import { Observable } from "../../Misc/observable";
import { Tools } from "../../Misc/tools";
import type { Nullable } from "../../types";
import { WebXRFeatureName, WebXRFeaturesManager } from "../webXRFeaturesManager";
import type { WebXRSessionManager } from "../webXRSessionManager";
import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
import { Constants } from "../../Engines/constants";
import { Color3 } from "../../Maths/math.color";
import { Vector3 } from "../../Maths/math.vector";
import { DirectionalLight } from "../../Lights/directionalLight";
import { BaseTexture } from "../../Materials/Textures/baseTexture";
import { SphericalHarmonics, SphericalPolynomial } from "../../Maths/sphericalPolynomial";
import { LightConstants } from "../../Lights/lightConstants";

/**
 * Options for Light Estimation feature
 */
export interface IWebXRLightEstimationOptions {
    /**
     * Disable the cube map reflection feature. In this case only light direction and color will be updated
     */
    disableCubeMapReflection?: boolean;
    /**
     * Should the scene's env texture be set to the cube map reflection texture
     * Note that this doesn't work is disableCubeMapReflection if set to false
     */
    setSceneEnvironmentTexture?: boolean;
    /**
     * How often should the cubemap update in ms.
     * If not set the cubemap will be updated every time the underlying system updates the environment texture.
     */
    cubeMapPollInterval?: number;
    /**
     * How often should the light estimation properties update in ms.
     * If not set the light estimation properties will be updated on every frame (depending on the underlying system)
     */
    lightEstimationPollInterval?: number;
    /**
     * Should a directional light source be created.
     * If created, this light source will be updated whenever the light estimation values change
     */
    createDirectionalLightSource?: boolean;
    /**
     * Define the format to be used for the light estimation texture.
     */
    reflectionFormat?: XRReflectionFormat;
    /**
     * Should the light estimation's needed vectors be constructed on each frame.
     * Use this when you use those vectors and don't want their values to change outside of the light estimation feature
     */
    disableVectorReuse?: boolean;

    /**
     * disable applying the spherical polynomial to the cube map texture
     */
    disableSphericalPolynomial?: boolean;
}

/**
 * An interface describing the result of a light estimation
 */
export interface IWebXRLightEstimation {
    /**
     * The intensity of the light source
     */
    lightIntensity: number;
    /**
     * Color of light source
     */
    lightColor: Color3;
    /**
     * The direction from the light source
     */
    lightDirection: Vector3;
    /**
     * Spherical harmonics coefficients of the light source
     */
    sphericalHarmonics: SphericalHarmonics;
}

/**
 * Light Estimation Feature
 *
 * @since 5.0.0
 */
export class WebXRLightEstimation extends WebXRAbstractFeature {
    private _canvasContext: Nullable<WebGLRenderingContext | WebGL2RenderingContext> = null;
    private _reflectionCubeMap: Nullable<BaseTexture> = null;
    private _xrLightEstimate: Nullable<XRLightEstimate> = null;
    private _xrLightProbe: Nullable<XRLightProbe> = null;
    private _xrWebGLBinding: Nullable<XRWebGLBinding> = null;
    private _lightDirection: Vector3 = Vector3.Up().negateInPlace();
    private _lightColor: Color3 = Color3.White();
    private _intensity: number = 1;
    private _sphericalHarmonics: SphericalHarmonics = new SphericalHarmonics();
    private _cubeMapPollTime = Date.now();
    private _lightEstimationPollTime = Date.now();

    /**
     * The module's name
     */
    public static readonly Name = WebXRFeatureName.LIGHT_ESTIMATION;
    /**
     * The (Babylon) version of this module.
     * This is an integer representing the implementation version.
     * This number does not correspond to the WebXR specs version
     */
    public static readonly Version = 1;

    /**
     * ARCore's reflection cube map size is 16x16.
     * Once other systems support this feature we will need to change this to be dynamic.
     * see https://github.com/immersive-web/lighting-estimation/blob/main/lighting-estimation-explainer.md#cube-map-open-questions
     */
    private _reflectionCubeMapTextureSize: number = 16;

    /**
     * If createDirectionalLightSource is set to true this light source will be created automatically.
     * Otherwise this can be set with an external directional light source.
     * This light will be updated whenever the light estimation values change.
     */
    public directionalLight: Nullable<DirectionalLight> = null;

    /**
     * This observable will notify when the reflection cube map is updated.
     */
    public onReflectionCubeMapUpdatedObservable: Observable<BaseTexture> = new Observable();

    /**
     * Creates a new instance of the light estimation feature
     * @param _xrSessionManager an instance of WebXRSessionManager
     * @param options options to use when constructing this feature
     */
    constructor(
        _xrSessionManager: WebXRSessionManager,
        /**
         * options to use when constructing this feature
         */
        public readonly options: IWebXRLightEstimationOptions
    ) {
        super(_xrSessionManager);
        this.xrNativeFeatureName = "light-estimation";

        if (this.options.createDirectionalLightSource) {
            this.directionalLight = new DirectionalLight("light estimation directional", this._lightDirection, this._xrSessionManager.scene);
            this.directionalLight.position = new Vector3(0, 8, 0);
            // intensity will be set later
            this.directionalLight.intensity = 0;
            this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF;
        }

        // https://immersive-web.github.io/lighting-estimation/
        Tools.Warn("light-estimation is an experimental and unstable feature.");
    }

    /**
     * While the estimated cube map is expected to update over time to better reflect the user's environment as they move around those changes are unlikely to happen with every XRFrame.
     * Since creating and processing the cube map is potentially expensive, especially if mip maps are needed, you can listen to the onReflectionCubeMapUpdatedObservable to determine
     * when it has been updated.
     */
    public get reflectionCubeMapTexture(): Nullable<BaseTexture> {
        return this._reflectionCubeMap;
    }

    /**
     * The most recent light estimate.  Available starting on the first frame where the device provides a light probe.
     */
    public get xrLightingEstimate(): Nullable<IWebXRLightEstimation> {
        if (this._xrLightEstimate) {
            return {
                lightColor: this._lightColor,
                lightDirection: this._lightDirection,
                lightIntensity: this._intensity,
                sphericalHarmonics: this._sphericalHarmonics,
            };
        }
        return this._xrLightEstimate;
    }

    private _getCanvasContext(): WebGLRenderingContext | WebGL2RenderingContext {
        if (this._canvasContext === null) {
            this._canvasContext = this._xrSessionManager.scene.getEngine()._gl;
        }
        return this._canvasContext;
    }

    private _getXRGLBinding(): XRWebGLBinding {
        if (this._xrWebGLBinding === null) {
            const context = this._getCanvasContext();
            this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context);
        }
        return this._xrWebGLBinding;
    }

    /**
     * Event Listener for "reflectionchange" events.
     */
    private _updateReflectionCubeMap = (): void => {
        if (!this._xrLightProbe) {
            return;
        }
        // check poll time, do not update if it has not been long enough
        if (this.options.cubeMapPollInterval) {
            const now = Date.now();
            if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) {
                return;
            }
            this._cubeMapPollTime = now;
        }
        const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);
        if (lp && this._reflectionCubeMap) {
            if (!this._reflectionCubeMap._texture) {
                const internalTexture = new InternalTexture(this._xrSessionManager.scene.getEngine(), InternalTextureSource.Unknown);
                internalTexture.isCube = true;
                internalTexture.invertY = false;
                internalTexture._useSRGBBuffer = this.options.reflectionFormat === "srgba8";
                internalTexture.format = Constants.TEXTUREFORMAT_RGBA;
                internalTexture.generateMipMaps = true;
                internalTexture.type = this.options.reflectionFormat !== "srgba8" ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE;
                internalTexture.samplingMode = Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
                internalTexture.width = this._reflectionCubeMapTextureSize;
                internalTexture.height = this._reflectionCubeMapTextureSize;
                internalTexture._cachedWrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
                internalTexture._cachedWrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
                internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext() as WebGLRenderingContext);
                this._reflectionCubeMap._texture = internalTexture;
            } else {
                this._reflectionCubeMap._texture._hardwareTexture?.set(lp);
                this._reflectionCubeMap._texture.getEngine().resetTextureCache();
            }
            this._reflectionCubeMap._texture.isReady = true;
            this._xrSessionManager.scene.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);

            this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap);
        }
    };

    /**
     * attach this feature
     * Will usually be called by the features manager
     *
     * @returns true if successful.
     */
    public attach(): boolean {
        if (!super.attach()) {
            return false;
        }

        const reflectionFormat = this.options.reflectionFormat ?? (this._xrSessionManager.session.preferredReflectionFormat || "srgba8");
        this.options.reflectionFormat = reflectionFormat;
        this._xrSessionManager.session
            .requestLightProbe({
                reflectionFormat,
            })
            .then((xrLightProbe: XRLightProbe) => {
                this._xrLightProbe = xrLightProbe;
                if (!this.options.disableCubeMapReflection) {
                    if (!this._reflectionCubeMap) {
                        this._reflectionCubeMap = new BaseTexture(this._xrSessionManager.scene);
                        this._reflectionCubeMap._isCube = true;
                        this._reflectionCubeMap.coordinatesMode = Constants.TEXTURE_CUBIC_MODE;
                        if (this.options.setSceneEnvironmentTexture) {
                            this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap;
                        }
                    }
                    this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap);
                }
            });

        return true;
    }

    /**
     * detach this feature.
     * Will usually be called by the features manager
     *
     * @returns true if successful.
     */
    public detach(): boolean {
        const detached = super.detach();

        if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) {
            this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap);
            this._xrLightProbe = null;
        }

        this._canvasContext = null;
        this._xrLightEstimate = null;
        // When the session ends (on detach) we must clear our XRWebGLBinging instance, which references the ended session.
        this._xrWebGLBinding = null;

        return detached;
    }

    /**
     * Dispose this feature and all of the resources attached
     */
    public dispose(): void {
        super.dispose();

        this.onReflectionCubeMapUpdatedObservable.clear();

        if (this.directionalLight) {
            this.directionalLight.dispose();
            this.directionalLight = null;
        }

        if (this._reflectionCubeMap !== null) {
            if (this._reflectionCubeMap._texture) {
                this._reflectionCubeMap._texture.dispose();
            }
            this._reflectionCubeMap.dispose();
            this._reflectionCubeMap = null;
        }
    }

    protected _onXRFrame(_xrFrame: XRFrame): void {
        if (this._xrLightProbe !== null) {
            if (this.options.lightEstimationPollInterval) {
                const now = Date.now();
                if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) {
                    return;
                }
                this._lightEstimationPollTime = now;
            }
            this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe);
            if (this._xrLightEstimate) {
                this._intensity = Math.max(
                    1.0,
                    this._xrLightEstimate.primaryLightIntensity.x,
                    this._xrLightEstimate.primaryLightIntensity.y,
                    this._xrLightEstimate.primaryLightIntensity.z
                );

                const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0;

                // recreate the vector caches, so that the last one provided to the user will persist
                if (this.options.disableVectorReuse) {
                    this._lightDirection = new Vector3();
                    this._lightColor = new Color3();
                    if (this.directionalLight) {
                        this.directionalLight.direction = this._lightDirection;
                        this.directionalLight.diffuse = this._lightColor;
                    }
                }

                this._lightDirection.copyFromFloats(
                    this._xrLightEstimate.primaryLightDirection.x,
                    this._xrLightEstimate.primaryLightDirection.y,
                    this._xrLightEstimate.primaryLightDirection.z * rhsFactor
                );
                this._lightColor.copyFromFloats(
                    this._xrLightEstimate.primaryLightIntensity.x / this._intensity,
                    this._xrLightEstimate.primaryLightIntensity.y / this._intensity,
                    this._xrLightEstimate.primaryLightIntensity.z / this._intensity
                );
                this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients);
                if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) {
                    this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial();
                    this._reflectionCubeMap.sphericalPolynomial?.updateFromHarmonics(this._sphericalHarmonics);
                }

                // direction from instead of direction to
                this._lightDirection.negateInPlace();
                // set the values after calculating them
                if (this.directionalLight) {
                    this.directionalLight.direction.copyFrom(this._lightDirection);
                    this.directionalLight.intensity = Math.min(this._intensity, 1.0);
                    this.directionalLight.diffuse.copyFrom(this._lightColor);
                }
            }
        }
    }
}

// register the plugin
WebXRFeaturesManager.AddWebXRFeature(
    WebXRLightEstimation.Name,
    (xrSessionManager, options) => {
        return () => new WebXRLightEstimation(xrSessionManager, options);
    },
    WebXRLightEstimation.Version,
    false
);


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2012 The Android Open Source Project

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

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- digital clock & date, together -->
<com.android.deskclock.DigitalClock xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/clock_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:gravity="top"
    >

    <com.android.deskclock.ZeroTopPaddingTextView
        android:id="@+id/timeDisplayHours"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingRight="@dimen/time_margin_right"
        android:singleLine="true"
        android:ellipsize="none"
        style="@style/medium_bold"
        android:textColor="@color/clock_white"/>
    <com.android.deskclock.ZeroTopPaddingTextView
        android:id="@+id/timeDisplayMinutes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/medium_light"
        android:singleLine="true"
        android:ellipsize="none"
        android:textColor="@color/clock_white" />
    <com.android.deskclock.ZeroTopPaddingTextView
        android:id="@+id/am_pm"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        style="@style/label"
        android:singleLine="true"
        android:ellipsize="none"
        android:gravity="top"
        android:textColor="@color/clock_white"
        />
</com.android.deskclock.DigitalClock>


text: export * from './network.component';