text:
<?php

namespace common\utils;

use common\utils\phpthumb\PhpThumbFactory;
use Yii;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class FileUtils {

    const SUFFIX_TEMPLATE = '--{x}x{y}';
    const SEQUENCE_TEMPLATE = '--{sequence}';

    const ALLOW_REMOVE_FOLDER_CONTAINS_LESS = 30;

    public static $file_name_replace = [
        '#' => '-',
        '?' => '-',
        '/' => '-',
        '_' => '-',
        '–' => '-',
        ' - ' => '-',
        ' ' => '-',
    ];
    public static $allow_extensions = [
        'jpg',
        'jpeg',
        'png',
        'gif',
        'pdf',
        'doc',
        'docx',
        'xsl',
        'apk',
        'ipa',
        'xap',
        'rar',
        'zip'
    ];

    // Hàm kiểm tra file có tồn tại trên url không
    public static function checkRemoteFile($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // don't download content
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (curl_exec($ch) !== FALSE) {
            return true;
        } else {
            return false;
        }
    }

    public static function getImage($params = [
        'imageName' => '',
        'suffix' => '',
        'imagePath' => '',
        'imagesFolder' => '',
        'imagesUrl' => '',
        'defaultImage' => ''
    ])
    {
        isset($params['defaultImage']) or $params['defaultImage'] = '';
        if(isset($params['suffix'])) {
//            if (is_array($params['suffix'])) {
//                $suffix = self::getResizeSuffix($params['suffix']);
//            } else {
//                $suffix = $params['suffix'];
//            }
            $suffix = self::getResizeSuffix(self::dimArray($params['suffix']));
        } else {
            $suffix = null;
        }

        $_image = '';
        if ($suffix === null) {
            if (@is_array(getimagesize($params['imagesFolder'] . $params['imagePath'] . $params['imageName']))) {
                $_image = $params['imagesUrl'] . $params['imagePath'] . $params['imageName'];
            }
        } else {
            $name_map = explode('.', $params['imageName']);
            if (count($name_map) >= 2) {
                $extension = $name_map[count($name_map) - 1];
                $basename = substr($params['imageName'], 0, -(1 + strlen($extension)));
                if (@is_array(getimagesize($params['imagesFolder'] . $params['imagePath'] . $basename . $suffix . '.' . $extension))) {
                    $_image = $params['imagesUrl'] . $params['imagePath'] . $basename . $suffix . '.' . $extension;
                } else {
                    if (@is_array(getimagesize($params['imagesFolder'] . $params['imagePath'] . $params['imageName']))) {
                        $_image = $params['imagesUrl'] . $params['imagePath'] . $params['imageName'];
                    }
                }
            }
        }

        if ($_image != '') {
            return str_replace('%3A//', '://', str_replace('%2F', '/', rawurlencode($_image)));
        } else {
            return $params['defaultImage'];
        }
    }

    // Hàm copy ảnh và resize theo các kích thước cho trước
    // Sử dụng thư viện PhpThumbFactory:
    /**
     * PhpThumb Library Definition File
     *
     * This file contains the definitions for the PhpThumbFactory class.
     * It also includes the other required base class files.
     *
     * If you've got some auto-loading magic going on elsewhere in your code, feel free to
     * remove the include_once statements at the beginning of this file... just make sure that
     * these files get included one way or another in your code.
     *
     * PHP Version 5 with GD 2.0+
     * PhpThumb : PHP Thumb Library <http://phpthumb.gxdlabs.com>
     * Copyright (c) 2009, Ian Selby/Gen X Design
     *
     * Author(s): Ian Selby <ian@gen-x-design.com>
     *
     * Licensed under the MIT License
     * Redistributions of files must retain the above copyright notice.
     *
     * @author Ian Selby <ian@gen-x-design.com>
     * @copyright Copyright (c) 2009 Gen X Design
     * @link http://phpthumb.gxdlabs.com
     * @license http://www.opensource.org/licenses/mit-license.php The MIT License
     * @version 3.0
     * @package PhpThumb
     * @filesource
     */
    public static function copyImage(
        $params = [
            'imageName' => '',
            'fromFolder' => '',
            'toFolder' => '',
//            'removeInputImage' => false,
//            'resize' => [],
//            'resizeType' => 1,
//            'resizeQuality' => 100,
//            'resizeSuffixTemplate' => '_{x}x{y}',
//            'sequenceSuffixTemplate' => '_{sequence}',
//            'sequenceStart' => 2,
//            'imageNameReplace' => self::$file_name_replace,
        ]
    )
    {
        $params['fromFolder'] = rtrim(trim($params['fromFolder']), '/') . '/';
        $params['toFolder'] = rtrim(trim($params['toFolder']), '/') . '/';
        isset($params['removeInputImage']) or $params['removeInputImage'] = false;
        isset($params['resize']) or $params['resize'] = [];
        isset($params['resizeType']) or $params['resizeType'] = 1;
        isset($params['resizeQuality']) or $params['resizeQuality'] = 100;
        isset($params['resizeSuffixTemplate']) or $params['resizeSuffixTemplate'] = self::SUFFIX_TEMPLATE;
        isset($params['sequenceSuffixTemplate']) or $params['sequenceSuffixTemplate'] = self::SEQUENCE_TEMPLATE;
        isset($params['sequenceStart']) or $params['sequenceStart'] = 2;
        isset($params['imageNameReplace']) or $params['imageNameReplace'] = self::$file_name_replace;
        isset($params['createWatermark']) or $params['createWatermark'] = false;

        $resize_suffixes = [];
        foreach ($params['resize'] as $dim) {
            $resize_suffixes[] = self::getResizeSuffix($dim, $params['resizeSuffixTemplate']);
        }
        $img_name = trim($params['imageName']);
        while (strpos($img_name, '  ') !== false) {
            $img_name = str_replace('  ', ' ', $img_name);
        }
        $img_extension = trim(strrev(explode('.', strrev($img_name))[0]));
        $img_basename = trim(substr($img_name, 0, -1 - strlen($img_extension)));
        if (self::fileWithSuffixesExists($params['toFolder'], $img_name, $resize_suffixes)) {
            $suffix_rev_map = self::getSequenceSuffixRevMap($params['sequenceSuffixTemplate']);
            $img_basename = trim(strrev(preg_replace('/' . $suffix_rev_map[1] . '(|\s)[0-9](|\s)' . $suffix_rev_map[0] . '/', '', strrev($img_basename), 1)));
        }
        foreach ($params['imageNameReplace'] as $search => $replace) {
            $img_basename = str_replace(html_entity_decode($search), $replace, $img_basename);
        }
        if (trim($img_basename) == ''){
            $img_basename = 'Untitle';
        }
        $img_name = $img_basename . '.' . $img_extension;
        while (self::fileWithSuffixesExists($params['toFolder'], $img_name, $resize_suffixes)) {
            $img_name = $img_basename . self::getSequenceSuffix($params['sequenceStart'] ++, $params['sequenceSuffixTemplate']) . '.' . $img_extension;
        }
        $result = [
            'imageName' => $img_name,
            'success' => false,
            'removeInputImage' => false,
            'resize' => [],
        ];
        if (!file_exists($params['toFolder'])) {
            mkdir($params['toFolder'], 0777, true);
        }
        if (is_file($params['fromFolder'] . $params['imageName'])
        || self::checkRemoteFile($params['fromFolder'] . $params['imageName'])
        ) {
            $name_map = explode('.', $img_name);
            if (count($name_map) > 1) {
                $extension = $name_map[count($name_map) - 1];
                $basename = substr($img_name, 0, -1 - strlen($extension));
//                try {
//                    \Tinify\setKey('9Ahno1_2RsMdPeokXMDsXRwiQsoJz2RP');
//                    $source = \Tinify\fromFile($params['fromFolder'] . $params['imageName']);
//                    $source->toFile($params['toFolder'] . $img_name);
//                } catch (\Tinify\Exception $e) {
                    try {
                        copy($params['fromFolder'] . $params['imageName'], $params['toFolder'] . $img_name);
                    } catch (Exception $e) {
                        var_dump($e);
                        die;
                    }
//                }
//                if (copy($params['fromFolder'] . $params['imageName'], $params['toFolder'] . $img_name)) {
                    $result['success'] = true;
                    if ($params['removeInputImage']) {
                        if (is_file($params['fromFolder'] . $params['imageName'])) {
                            if (@unlink($params['fromFolder'] . $params['imageName'])) {
                                $result['removeInputImage'] = true;
                            }
                        }
                    }
                    if (filesize($params['toFolder'] . $img_name) > 0) {
                        $formatInfo = getimagesize($params['toFolder'] . $img_name);
                        if ($formatInfo !== false && (isset($formatInfo['mime']) ? in_array($formatInfo['mime'], ['image/jpeg', 'image/png', 'image/gif']) : false)) {
                            // create watermark
//                            if ($params['createWatermark']) {
//                                $thumb = PhpThumbFactory::create($params['toFolder'] . $img_name);
//                                if ($formatInfo[0] > 800 && $formatInfo[1] > 800) {
//                                    $watermark_img = 'watermark_lg.png';
//                                } else if ($formatInfo[0] > 300 && $formatInfo[1] > 300) {
//                                    $watermark_img = 'watermark_md.png';
//                                } else {
//                                    $watermark_img = 'watermark_sm.png';
//                                }
//                                if (is_file(\Yii::$app->params['images_folder'] . '/' . $watermark_img)) {
//                                    $thumb->createWatermark(\Yii::$app->params['images_folder'] . '/' . $watermark_img, 'lt', '5');
//                                    $thumb->save($params['toFolder'] . $img_name);
//                                }
//                            }
                            if (count($params['resize']) > 0) {
                                foreach ($params['resize'] as $dim) {
                                    $dim = self::dimArray($dim);
                                    $thumb = PhpThumbFactory::create($params['toFolder'] . $img_name);
                                    $thumb->setOptions(['jpegQuality' => $params['resizeQuality']]);
                                    switch ($params['resizeType']) {
                                        case 1:
                                            if ($thumb->resize($dim[0], $dim[1])) {
                                                if ($thumb->save($params['toFolder'] . $basename . self::getResizeSuffix($dim, $params['resizeSuffixTemplate']) . '.' . $extension)) {
                                                    $result['resize'][] = $basename . self::getResizeSuffix($dim, $params['resizeSuffixTemplate']) . '.' . $extension;
                                                }
                                            }
                                            break;
                                        case 2:
                                            if ($thumb->adaptiveResize($dim[0], $dim[1])) {
                                                if ($thumb->save($params['toFolder'] . $basename . self::getResizeSuffix($dim, $params['resizeSuffixTemplate']) . '.' . $extension)) {
                                                    $result['resize'][] = $basename . self::getResizeSuffix($dim, $params['resizeSuffixTemplate']) . '.' . $extension;
                                                }
                                            }
                                    }
                                }
                            }
                        }
                    }
//                }
            }
        }

//        if ($result['success']) {
//            // Move forder contains image and all resize images to other server by ftp
//            $ftpPath = str_replace(Yii::$app->params['images_folder'], 'images', $params['toFolder']);
//            Yii::$app->ftpFs->createDir($ftpPath);
//            Yii::$app->ftpFs->write($ftpPath . $result['imageName'], Yii::$app->fs->read($ftpPath . $result['imageName']));
//            foreach ($result['resize'] as $item) {
//                Yii::$app->ftpFs->write($ftpPath . $item, Yii::$app->fs->read($ftpPath . $item));
//            }
//            // End move folder by ftp
//        }
        return $result;
    }

    // Hàm copy ảnh trong nội dung text và trả về nội dung chứa đường dẫn ảnh mới
    public static function copyContentImages($params = [
        'content' => '',
//        'defaultFromFolder' => '',
        'toFolder' => '',
        'toUrl' => '',
//        'regex' => '',
//        'removeInputImage' => false,
    ])
    {
        if (empty($params['regex'])) {
            $regex = '/(http|https):\/\/+[^\"]+.(';
            foreach (self::$allow_extensions as $i => $ext) {
                $regex .= ($i > 0 ? '|' : '') . $ext . '|' . strtoupper($ext);
            }
            $regex .= ')/';
        }
        isset($params['removeInputImage']) or $params['removeInputImage'] = false;
        isset($params['createWatermark']) or $params['createWatermark'] = false;
        if (isset($params['defaultFromFolder'])) {
            $params['defaultFromFolder'] = rtrim($params['defaultFromFolder'], '/') . '/';
        }
        $params['toFolder'] = rtrim($params['toFolder'], '/') . '/';
        $toUrl = rtrim($params['toUrl'], '/') . '/';
        $content = $params['content'];
        $matches = array();
        preg_match_all($regex, $content, $matches);
        if (!empty($matches[0])) {
            foreach ($matches[0] as $img_url) {
                if (strpos($img_url, $toUrl) === false) {
                    $img_name = strrev(explode('/', strrev($img_url))[0]);
                    if (empty($params['defaultFromFolder']) || !is_file($params['defaultFromFolder'] . $img_name)) {
                        $fromFolder = substr($img_url, 0, strlen($img_url) - strlen($img_name));
                    } else {
                        $fromFolder = $params['defaultFromFolder'];
                    }
                    $copyResult = self::copyImage([
                                'imageName' => $img_name,
                                'fromFolder' => $fromFolder,
                                'toFolder' => $params['toFolder'],
                                'removeInputImage' => $params['removeInputImage'],
                                'createWatermark' => $params['createWatermark'],
                    ]);
                    if ($copyResult['success']) {
                        $content = str_replace($img_url, $toUrl . $copyResult['imageName'], $content);
                    }
                }
            }
        }
        return $content;
    }

    public static function removeFolder($dir)
    {
        if (is_dir($dir)) {
            $files = glob(rtrim($dir, '/') . '/*');
            if (count($files) < self::ALLOW_REMOVE_FOLDER_CONTAINS_LESS) {
                foreach ($files as $item) {
                    if (is_file($item)) {
                        @unlink($item);
                    }
                }
                @rmdir($dir);
            }
            // remove corresponding folder on server2 by ftp
//            $ftpPath = str_replace(Yii::$app->params['images_folder'], 'images', $dir);
//            $contents = Yii::$app->ftpFs->listContents($ftpPath);
//            if (count($contents) < self::ALLOW_REMOVE_FOLDER_CONTAINS_LESS) {
//                foreach ($contents as $item) {
//                    if ($item['type'] === 'file') {
//                        if (Yii::$app->ftpFs->has($item['path'])) {
//                            Yii::$app->ftpFs->delete($item['path']);
//                        }
//                    }
//                }
//                $contents = Yii::$app->ftpFs->listContents($ftpPath);
//                if (count($contents) == 0) {
//                    Yii::$app->ftpFs->deleteDir($ftpPath);
//                }
//            }
            // end ftp
        }
    }

    // Nếu đường dẫn thư mục ảnh không tồn tại trên local nhưng tồn tại trên ftp
    // khi xảy ra trường hợp thư mục mới (sẽ không trùng với thư mục nào trên local cho đến giới hạn xác suất nhưng)
    // bị trùng với thư mục trên ftp thì thư mục trên ftp cũng sẽ được đồng nhất với thư mục trên local
    public static function generatePath($time)
    {
//        return '/' . date('Y', $time) . '/' . date('m', $time) . '/' . date('d', $time) . '/' . self::generateRandomString(2) . '/';
        return '/' . date('Y', $time) . '/' . date('md', $time) . '/' . self::generateRandomString(2) . '/';
    }

    // private function
    private static function generateRandomString($length, $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
    {
        $str = '';
        $count = strlen($charset);
        while ($length--) {
            $str .= $charset[mt_rand(0, $count - 1)];
        }
        return $str;
    }

    private static function getSequenceSuffixRevMap($template)
    {
        $suffix_map = explode('{sequence}', $template);
        return [
            isset($suffix_map[0]) ? preg_quote(strrev($suffix_map[0])) : '',
            isset($suffix_map[1]) ? preg_quote(strrev($suffix_map[1])) : '',
        ];
    }

    public static function getSequenceSuffix($sequence, $template = '')
    {
        $template != '' or $template = self::SEQUENCE_TEMPLATE;
        if ($result = str_replace('{sequence}', $sequence, $template)) {
            return $result;
        }
        return '';
    }

    public static function getResizeSuffix($dim, $template = '')
    {
        $template != '' or $template = self::SUFFIX_TEMPLATE;
        if ($result = str_replace('{y}', $dim[1], str_replace('{x}', $dim[0], $template))) {
            return $result;
        }
        return '';
    }

    private static function fileWithSuffixesExists($container, $filename, $suffixes = [])
    {
        if (is_file($container . $filename)) {
            return true;
        }
        $name_map = explode('.', $filename);
        if (count($name_map) >= 2) {
            $extension = $name_map[count($name_map) - 1];
            $basename = substr($filename, 0, -1 - strlen($extension));
            foreach ($suffixes as $suffix) {
                if (is_file($container . $basename . $suffix . '.' . $extension)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static function dimArray($dim)
    {
        if (!is_array($dim)) {
            $dim = explode('x', $dim);
        }
        return $dim;
    }

}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Rep. Voy. Challenger, Zool. , 18 (1), 214 (as Raphidodrymus; also as Rhaphidodrymus p. 1792).

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
% DEMO OF KERNEL ANALOG FORECAST (KAF) OF THE LORENZ 63 (L63) SYSTEM
%
% This script applies KAF to predict the state vector compoents of the L63
% system under full or partial observations.
%
% Two test cases are provided, illustrating the behavior of the method when
% the covariate data is the x1 component of the state vector component alone,
% or the full state vector. In addition, we consider an example where the
% covariate data of the partially observed system is augmented using delay-
% coordinate maps, illustrating the recovery of forecast skill as expected
% from "Embedology" results.
%
% Each test case has variants utilizing 6400 or 64000 training samples, taken
% near thee L63 attractor at a sampling interval dt of 0.01 natural time
% units.  These experiments are selected using a character variable
% experiments which can take the following values:
%
% '6.4k_dt0.01_idxX1_2_3_nEL0': 6400 samples, dt=0.01, fully observed, 0 delays
% '6.4k_dt0.01_idxX1_nEL0': 6400 samples, dt=0.01, x1 only, 0 delays
% '6.4k_dt0.01_idxX1_nEL15': 6400 samples, dt=0.01, x1 only, 10 delays
%
% '64k_dt0.01_idxX1_2_3_nEL0': 64000 samples, dt=0.01, fully observed, 0 delays
% '64k_dt0.01_idxX1_nEL0': 64000 samples, dt=0.01, x1 only, 0 delays
% '64k_dt0.01_idxX1_nEL15': 64000 samples, dt=0.01, x1 only, 15 delays
%
% The kernel employed is a variable-bandwidth Gaussian kernel, normalized to a
% symmetric Markov kernel. This requires a kernel density estimation step to
% compute the bandwidth functions, followed by a normalization step to form the
% kernel matrix. See pseudocode in Appendix B of reference [2] below for
% further details. The original references for the variable-bandwith kernel
% formulation and symmetric Markov normalization are [3] and [4], respectively.
%
% In addition, for some of the test cases, we provide variants using standard
% RBF kernels as opposed to variable-bandwidth kernels for comparison. These
% experiments have the string identifiers '..._rbf'.
%
% All experiments use the same verification dataset consisting of 6400 samples
% on an independent trajectory from the training data. Using a longer
% verification dataset will improve the accuracy of forecast skill scores (at
% the expense of longer runtimes).
%
% References:
%
% [1] R. Alexander, D. Giannakis (2020), "Operator-theoretic framework for
%     forecasting nonlinear time series with kernel analog techniques",
%     Phys. D, 409, 132520, https://doi.org/10.1016/j.physd.2020.132520.
%
% [2] S. Das, D. Giannakis, J. Slawinska (2018), "Reproducing kernel Hilbert
%     space compactification of unitary evolution groups",
%     https://arxiv.org/abs/1808.01515.
%
% [3] T. Berry, J. Harlim (2016), "Variable bandwidth diffusion kernels",
%     Appl. Comput. Harmon. Anal., 40(1), 68-96,
%     https://doi.org/10.1016/j.acha.2015.01.001.
%
% [4] R. Coifman, R. Hirn (2013), "Bistochastic kernels via asymmetric
%     affinity functions", Appl. Comput. Harmon. Anal., 35(1), 177--180,
%     https://doi.org/j.acha.2013.01.001.
%
% Modified 2021/02/27

%% EXPERIMENT SPECIFICATION AND SCRIPT EXECUTION OPTIONS
%experiment = '6.4k_dt0.01_idxX1_2_3_nEL0';
%experiment = '6.4k_dt0.01_idxX1_2_3_nEL0_rbf';
%experiment = '6.4k_dt0.01_idxX1_nEL0';
%experiment = '6.4k_dt0.01_idxX1_nEL15';
experiment = '6.4k_dt0.01_idxX1_2_3_nEL15';
% experiment = '6.4k_dt0.01_idxX1_2_3_nEL15_rbf';
%experiment = '64k_dt0.01_idxX1_2_3_nEL0';
%experiment = '64k_dt0.01_idxX_nEL0';
%experiment = '64k_dt0.01_idxX_nEL15';

ifSourceData   = true; % generate source data
ifTestData     = true; % generate test (verification) data
ifNLSA         = true; % run NLSA (kernel eigenfunctions)
ifOse          = true; % do out-of-sample extension of eigenfunctions
ifReadKAFData  = true; % read training/test data for KAF
ifKAF          = true; % perform KAF
ifPlotForecast = true; % plot representative forecast trajectories
ifPlotError    = true; % plot forecast error
ifPrintFig     = true; % print figures to file

%% BATCH PROCESSING
iProc = 1; % index of batch process for this script
nProc = 1; % number of batch processes

%% GLOBAL PARAMETERS
% nL:         Number of eigenfunctions for KAF target function
% nL2:        Number of eigenfunctions used for error estimation
% nT:         Number of timesteps to predict (including 0)
% idxTPlt:    Initial conditions for which to plot forecast trajectories
% tStr:       Figure title
% figDir:     Output directory for plots

switch experiment

case '6.4k_dt0.01_idxX1_2_3_nEL0'
    nL  = 401;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, full obs.';

case '6.4k_dt0.01_idxX1_2_3_nEL0_rbf'
    nL  = 401;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, full obs., RBF';

case '6.4k_dt0.01_idxX1_2_3_nEL15'
    nL  = 401;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, full obs.';

case '6.4k_dt0.01_idxX1_2_3_nEL15_rbf'
    nL  = 401;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, full obs., RBF';

case '6.4k_dt0.01_idxX1_nEL0'
    nL  = 201;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, x1 obs.';

case '6.4k_dt0.01_idxX1_nEL15'
    nL  = 401;
    nL2 = 901;
    nT  = 501;
    idxTPlt = [ 2101 2201 2301 ];
    tStr = '6.4k, x1 obs.';

otherwise
    error( 'Invalid experiment.' )
end

% Figure/movie directory
figDir = fullfile( pwd, 'figsKAF', experiment );
if ifPrintFig && ~isdir( figDir )
    mkdir( figDir )
end

%% EXTRACT SOURCE DATA
if ifSourceData
    disp( 'Generating source data...' ); t = tic;
    demoKAF_data( experiment )
    toc( t )
end

%% EXTRACT TEST DATA
if ifTestData
    disp( 'Generating test data...' ); t = tic;
    demoKAF_test_data( experiment )
    toc( t )
end

%% BUILD NLSA MODEL, DETERMINE BASIC ARRAY SIZES
% In and Out are data structures containing the NLSA parameters for the
% training and test data, respectively.
%
% nE is the number of Takens delays applied to the covariate data.
% idxT1 is the initial time stamp in the covariante data ("origin") where
% delay embedding is performed. We remove samples 1 to idxT1 from the response
% data so that they always lie in the future of the delay embedding window.
%
% nSX is the total  number of covariate samples available after delay
% embedding.
%
% nR is the number of training realizations (ensemble members).
%
% nSXR = nSX / nR is the number of traning samples in each realization. In
% this implementation of KAF, every realization should contain the same
% number of training samples.
disp( 'Building NLSA model...' ); t = tic;
[ model, In, Out ] = demoKAF_nlsaModel( experiment );
toc( t )

nE    = getEmbeddingWindow( model.embComponent );
idxT1 = getOrigin( model.embComponent );
nR    = size( model.embComponent, 2 );
nSXR  = getNSample( model.embComponent( 1 ) );
if nR > 1 && any( getNSample( model.embComponent( 1, 2 : end ) ) ~= nSXR )
    msgStr = [ 'This implementation of KAF only supports equal sample ' ...
               'numbers in each realization.' ];
    error( msgStr )
end
nSX = nSXR * nR;

% Create parallel pool if running NLSA and the NLSA model has been set up
% with parallel workers. This part can be commented out if no parts of the
% NLSA code utilizing parallel workers are being executed.
%
% In.nParE is the number of parallel workers for delay-embedded distances
% In.nParNN is the number of parallel workers for nearest neighbor search
if ifNLSA
    if isfield( In, 'nParE' ) && In.nParE > 0
        nPar = In.nParE;
    else
        nPar = 0;
    end
    if isfield( In, 'nParNN' ) && In.nParNN > 0
        nPar = max( nPar, In.nParNN );
    end
    if nPar > 0
        poolObj = gcp( 'nocreate' );
        if isempty( poolObj )
            poolObj = parpool( nPar );
        end
    end
end

%% PERFORM NLSA
if ifNLSA

    % Execute NLSA steps. Output from each step is saved on disk.

    disp( 'Takens delay embedding...' ); t = tic;
    computeDelayEmbedding( model )
    toc( t )

    % The following steps are needed only if we are using variable-bandwidth
    % kernels.
    if isa( model, 'nlsaModel_den' )
        fprintf( 'Pairwise distances for density data, %i/%i...\n', ...
                  iProc, nProc );
        t = tic;
        computeDenPairwiseDistances( model, iProc, nProc )
        toc( t )

        disp( 'Distance normalization for kernel density steimation...' );
        t = tic;
        computeDenBandwidthNormalization( model );
        toc( t )

        disp( 'Kernel bandwidth tuning for density estimation...' ); t = tic;
        computeDenKernelDoubleSum( model );
        toc( t )

        disp( 'Kernel density estimation...' ); t = tic;
        computeDensity( model );
        toc( t )

        disp( 'Takens delay embedding for density data...' ); t = tic;
        computeDensityDelayEmbedding( model );
        toc( t )
    end

    fprintf( 'Pairwise distances (%i/%i)...\n', iProc, nProc ); t = tic;
    computePairwiseDistances( model, iProc, nProc )
    toc( t )

    disp( 'Distance symmetrization...' ); t = tic;
    symmetrizeDistances( model )
    toc( t )

    disp( 'Kernel bandwidth tuning...' ); t = tic;
    computeKernelDoubleSum( model )
    toc( t )

    disp( 'Kernel eigenfunctions...' ); t = tic;
    computeDiffusionEigenfunctions( model )
    toc( t )

end

%% DO OUT-OF-SAMPLE EXTENSIONS
if ifOse

    disp( 'Takens delay embedding for out-of-sample data...' ); t = tic;
    computeOutDelayEmbedding( model )
    toc( t )

    % The following steps are needed only if we are using variable-bandwidth
    % kernels.
    if isa( model, 'nlsaModel_den' )
        fprintf( 'OSE pairwise distances for density data... %i/%i\n', ...
                  iProc, nProc );
        t = tic;
        computeOseDenPairwiseDistances( model, iProc, nProc )
        toc( t )

        disp( 'OSE density bandwidth normalization...' ); t = tic;
        computeOseDenBandwidthNormalization( model )
        toc( t )

        disp( 'OSE kernel density estimation...' ); t = tic;
        computeOseDensity( model )
        toc( t )

        disp( 'OSE density delay embedding...' ); t = tic;
        computeOseDensityDelayEmbedding( model );
        toc( t )
    end

    fprintf( 'OSE pairwise distances... %i/%i\n', iProc, nProc ); t = tic;
    computeOsePairwiseDistances( model, iProc, nProc )
    toc( t )

    disp( 'OSE kernel normalization...' ); t = tic;
    computeOseKernelNormalization( model )

    disp( 'OSE kernel degree...' ); t = tic;
    computeOseKernelDegree( model )
    toc( t )

    disp( 'Nystrom operator...' ); t = tic;
    computeOseDiffusionOperator( model )
    toc( t )

    disp( 'OSE diffusion eigenfunctions...' ); t = tic;
    computeOseDiffusionEigenfunctions( model )
    toc( t )
end

%% READ TRAINING AND TEST DATA FOR KAF
% y is an array of size [ 3 nSY ] containing in its columns the response
% variable (3-dimensional L63 state vector) on the training states. nSY is
% the number of response samples available after delay embedding.
%
% phi is an array of size [ nSX nPhi ] whose columns contain the eigenfunctions
% from NLSA on the training states. nSX is the number of covariate samples
% available after delay embedding, and nPhi the number of eigenfunctions
% available from the nlsaModel. nSX is less than or equal to nSY.
%
% yO is an array of size [ 3 nSO ] containing in its columns the response
% variable on the test states. nSO is the number of test samples available
% after delay embedding.
%
% phiO is an array of size [ nSO nPhi ] containing the out-of-sample values
% of the NLSA eigenfunctions.
if ifReadKAFData
    tic
    disp( 'Retrieving KAF data...' ); t = tic;

    % Response variable
    y = getData( model.trgComponent );
    y = y( :, idxT1 : end );
    yStd = std( y, 0, 2 );

    % Eigenfunctions
    [ phi, mu ] = getDiffusionEigenfunctions( model );

    % Response variable (test data)
    yO = getData( model.outTrgComponent );
    yO = yO( :, idxT1 : end );

    % Eigenfunctions (test data)
    phiO = getOseDiffusionEigenfunctions( model );
    toc( t )
end

%% PERFORM KAF
% yT is an array of size [ 3 nT nSO ] such that yT( :, iT, iSO ) is the
% predicted state vector at ( iT - 1 ) timesteps in the future given the
% iSO-th initial condition in the test dataset.
%
% yTErr is an array of size [ 3 nT nSO ] such that yTErr( :, iT, iSO ) is
% a vector of estimates of the forecast error (conditional standard deviation)
% in the components of yT( :, iT, iSO ).
%
% See /nlsa/utils/forecasting/analogForecast.m for further details on the
% forecast function employed.
%
% Because this implementation of KAF employs the Nystrom out-of-sample
% extension method, the forecasts of the suare error are not guaranteed to
% be non-negative. As a result we take absolute values.
if ifKAF
    tic
    disp( 'Performing KAF...' ); t = tic;
    [ yT, ~, yTErr ] = analogForecast( y, phi, mu, phiO, nT, nL, nL2 );

    yTErr = sqrt( abs( yTErr ) );
    toc( t )

    tic
    disp( 'Computing forecast skill scores...' ); t = tic;
    [ ~, yRMSE, yPC ] = forecastError( yO, yT );
    yRMSE = yRMSE ./ yStd;
    toc( t )

    tic
    disp( 'Computing estimated RMSE...' ); t = tic;
    yRMSE_est = sqrt( mean( yTErr .^ 2, 3 ) ) ./ yStd;
    toc( t )

end

%% PLOT FORECAST TRAJECTORIES
if ifPlotForecast

    % Lead times
    t = ( 0 : nT - 1 ) * In.dt;

    % Plot limits and ticks
    yLm = [ [ -25 -25 5 ]' [ 25 25 50 ]' ];
    yTk = { -20 : 10 : 20, -20 : 10 : 20, 10 : 10 : 50 };

    % Set up figure and axes
    Fig.nTileX     = 3;
    Fig.nTileY     = numel( idxTPlt );
    Fig.units      = 'inches';
    Fig.figWidth   = 8;
    Fig.deltaX     = .6;
    Fig.deltaX2    = .15;
    Fig.deltaY     = .5;
    Fig.deltaY2    = .3;
    Fig.gapX       = .4;
    Fig.gapY       = .3;
    Fig.gapT       = 0.32;
    Fig.aspectR    = 3 / 4;
    Fig.fontName   = 'helvetica';
    Fig.fontSize   = 10;
    Fig.tickLength = [ 0.02 0 ];
    Fig.visible    = 'on';
    Fig.nextPlot   = 'add';

    [ fig, ax, axTitle ] = tileAxes( Fig );

    % Plot true and forecast signals
    for iT = 1 : Fig.nTileY;

        % Initialization time, true and forecast signal
        t0 = ( idxTPlt( iT ) - 1 ) * In.dt;
        yTrue = yO( :, idxTPlt( iT ) : idxTPlt( iT ) + nT - 1 );
        yPred = squeeze( yT( :, :, idxTPlt( iT ) ) );
        yErr = squeeze( yTErr( :, :, idxTPlt( iT ) ) );

        % Loop over the components of the response vector
        for iY = 1 : 3

            set( gcf, 'currentAxes', ax( iY, iT ) )
            [ hPred, hErr ] = boundedline( t, yPred( iY, : ), ...
                                           yErr( iY, : ), 'b-' );
            hTrue = plot( t, yTrue( iY, : ), 'k-' );

            xlim( [ t( 1 ) t( end ) ] )
            ylim( yLm( iY, : ) )
            set( gca, 'xTick', t( 1 ) : 1 : t( end ), ...
                      'yTick', yTk{ iY } )
            grid on

            if iY == 1
                ylabel( sprintf( 'Init. time t_0 = %1.1f', t0 ) )
            end
            if iT == 1
                title( sprintf( 'x_{%i}', iY ) )
            end
            if iT == Fig.nTileY
                xlabel( 'Lead time t' )
            else
                set( gca, 'xTickLabel', [] )
            end
            if iT == 1 && iY == 1
                hL = legend( [ hTrue hPred hErr ],  'true', 'forecast', ...
                               'est. error', 'location', 'northWest' );
                sL = hL.ItemTokenSize;
                sL( 1 ) = .5 * sL( 1 );
                hL.ItemTokenSize = sL;
            end
        end
    end

    % Add figure title
    titleStr = sprintf( [ '%s, Takens delays = %i, ' ...
                          'number of basis functions = %i' ], tStr, nE, nL );
    title( axTitle, titleStr )

    % Print figure
    if ifPrintFig
        figFile = sprintf( 'figForecastTrajectory_nL%i.png', nL );
        figFile = fullfile( figDir, figFile );
        print( fig, figFile, '-dpng', '-r300' )
    end

end

%% PLOT ERROR SCORES
if ifPlotError

    % Lead times
    t = ( 0 : nT - 1 ) * In.dt;

    % Set up figure and axes
    Fig.nTileX     = 3;
    Fig.nTileY     = 2;
    Fig.units      = 'inches';
    Fig.figWidth   = 8;
    Fig.deltaX     = .6;
    Fig.deltaX2    = .15;
    Fig.deltaY     = .5;
    Fig.deltaY2    = .3;
    Fig.gapX       = .3;
    Fig.gapY       = .3;
    Fig.gapT       = 0.32;
    Fig.aspectR    = 3 / 4;
    Fig.fontName   = 'helvetica';
    Fig.fontSize   = 10;
    Fig.tickLength = [ 0.02 0 ];
    Fig.visible    = 'on';
    Fig.nextPlot   = 'add';

    [ fig, ax, axTitle ] = tileAxes( Fig );

    % Plot skill scores
    for iY = 1 : 3

        % Normalized RMSE
        set( gcf, 'currentAxes', ax( iY, 1 ) )
        plot( t, yRMSE( iY, : ), 'k-' )
        plot( t, yRMSE_est( iY, : ), 'b-' )

        grid on
        ylim( [ 0 1.2 ] )
        xlim( [ t( 1 ) t( end ) ] )
        set( gca, 'xTick', t( 1 ) : 1 : t( end ), 'yTick', 0 : .2 : 1.2, ...
                  'xTickLabel', [] )
        if iY == 1
            ylabel( 'Normalized RMSE' )
            legend( 'true error', 'estimated error', 'location', 'southEast' )
        else
            set( gca, 'yTickLabel', [] )
        end
        title( sprintf( 'x_{%i}', iY ) )

        % Pattern correlation
        set( gcf, 'currentAxes', ax( iY, 2 ) )
        plot( t, yPC( iY, : ) )

        grid on
        ylim( [ -0.2 1.1 ] )
        xlim( [ t( 1 ) t( end ) ] )
        set( gca, 'xTick', t( 1 ) : 1 : t( end ), 'yTick', -0.2 : .2 : 1.2 )
        if iY == 1
            ylabel( 'Pattern correlation' )
        else
            set( gca, 'yTickLabel', [] )
        end
        xlabel( 'Lead time t' )
    end

    % Add figure title
    titleStr = sprintf( [ '%s, Takens delays = %i, ' ...
                          'number of basis functions = %i' ], tStr, nE, nL );
    title( axTitle, titleStr )

    % Print figure
    if ifPrintFig
        figFile = sprintf( 'figForecastError_nL%i.png', nL );
        figFile = fullfile( figDir, figFile );
        print( fig, figFile, '-dpng', '-r300' )
    end
end


text:
"use strict";

var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];

var _createClass = require("babel-runtime/helpers/create-class")["default"];

var _inherits = require("babel-runtime/helpers/inherits")["default"];

var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];

var _interopRequire = require("babel-runtime/helpers/interop-require")["default"];

exports.config = config;
Object.defineProperty(exports, "__esModule", {
  value: true
});

var XDR = _interopRequireWildcard(require("./types"));

var _lodash = require("lodash");

var isUndefined = _lodash.isUndefined;
var isPlainObject = _lodash.isPlainObject;
var isArray = _lodash.isArray;
var each = _lodash.each;
var map = _lodash.map;
var pick = _lodash.pick;

var sequencify = _interopRequire(require("sequencify"));

// types is the root
var types = {};

function config(fn) {
  if (fn) {
    var builder = new TypeBuilder(types);
    fn(builder);
    builder.resolve();
  }

  return types;
}

var Reference = exports.Reference = (function () {
  function Reference() {
    _classCallCheck(this, Reference);
  }

  _createClass(Reference, {
    resolve: {
      /* jshint unused: false */

      value: function resolve(context) {
        throw new Error("implement resolve in child class");
      }
    }
  });

  return Reference;
})();

var SimpleReference = (function (_Reference) {
  function SimpleReference(name) {
    _classCallCheck(this, SimpleReference);

    this.name = name;
  }

  _inherits(SimpleReference, _Reference);

  _createClass(SimpleReference, {
    resolve: {
      value: function resolve(context) {
        var defn = context.definitions[this.name];
        return defn.resolve(context);
      }
    }
  });

  return SimpleReference;
})(Reference);

var ArrayReference = (function (_Reference2) {
  function ArrayReference(childReference, length) {
    var variable = arguments[2] === undefined ? false : arguments[2];

    _classCallCheck(this, ArrayReference);

    this.childReference = childReference;
    this.length = length;
    this.variable = variable;
  }

  _inherits(ArrayReference, _Reference2);

  _createClass(ArrayReference, {
    resolve: {
      value: function resolve(context) {
        var resolvedChild = this.childReference;
        var length = this.length;

        if (resolvedChild instanceof Reference) {
          resolvedChild = resolvedChild.resolve(context);
        }

        if (length instanceof Reference) {
          length = length.resolve(context);
        }

        if (this.variable) {
          return new XDR.VarArray(resolvedChild, length);
        } else {
          return new XDR.Array(resolvedChild, length);
        }
      }
    }
  });

  return ArrayReference;
})(Reference);

var OptionReference = (function (_Reference3) {
  function OptionReference(childReference) {
    _classCallCheck(this, OptionReference);

    this.childReference = childReference;
    this.name = childReference.name;
  }

  _inherits(OptionReference, _Reference3);

  _createClass(OptionReference, {
    resolve: {
      value: function resolve(context) {
        var resolvedChild = this.childReference;

        if (resolvedChild instanceof Reference) {
          resolvedChild = resolvedChild.resolve(context);
        }

        return new XDR.Option(resolvedChild);
      }
    }
  });

  return OptionReference;
})(Reference);

var SizedReference = (function (_Reference4) {
  function SizedReference(sizedType, length) {
    _classCallCheck(this, SizedReference);

    this.sizedType = sizedType;
    this.length = length;
  }

  _inherits(SizedReference, _Reference4);

  _createClass(SizedReference, {
    resolve: {
      value: function resolve(context) {
        var length = this.length;

        if (length instanceof Reference) {
          length = length.resolve(context);
        }

        return new this.sizedType(length);
      }
    }
  });

  return SizedReference;
})(Reference);

var Definition = (function () {
  function Definition(constructor, name, config) {
    _classCallCheck(this, Definition);

    this.constructor = constructor;
    this.name = name;
    this.config = config;
  }

  _createClass(Definition, {
    resolve: {

      // resolve calls the constructor of this definition with the provided context
      // and this definitions config values.  The definitions constructor should
      // populate the final type on `context.results`, and may refer to other
      // definitions through `context.definitions`

      value: function resolve(context) {
        if (this.name in context.results) {
          return context.results[this.name];
        }

        return this.constructor(context, this.name, this.config);
      }
    }
  });

  return Definition;
})();

var TypeBuilder = (function () {
  function TypeBuilder(destination) {
    _classCallCheck(this, TypeBuilder);

    this._destination = destination;
    this._definitions = {};
  }

  _createClass(TypeBuilder, {
    "enum": {
      value: function _enum(name, members) {
        var result = new Definition(XDR.Enum.create, name, members);
        this.define(name, result);
      }
    },
    struct: {
      value: function struct(name, members) {
        var result = new Definition(XDR.Struct.create, name, members);
        this.define(name, result);
      }
    },
    union: {
      value: function union(name, config) {
        var result = new Definition(XDR.Union.create, name, config);
        this.define(name, result);
      }
    },
    typedef: {
      value: function typedef(name, config) {
        // let the reference resoltion system do it's thing
        // the "constructor" for a typedef just returns the resolved value
        var createTypedef = function (context, name, value) {
          if (value instanceof Reference) {
            value = value.resolve(context);
          }
          context.results[name] = value;
          return value;
        };

        var result = new Definition(createTypedef, name, config);
        this.define(name, result);
      }
    },
    "const": {
      value: function _const(name, config) {
        var createConst = function (context, name, value) {
          context.results[name] = value;
          return value;
        };

        var result = new Definition(createConst, name, config);
        this.define(name, result);
      }
    },
    "void": {
      value: function _void() {
        return XDR.Void;
      }
    },
    bool: {
      value: function bool() {
        return XDR.Bool;
      }
    },
    int: {
      value: function int() {
        return XDR.Int;
      }
    },
    hyper: {
      value: function hyper() {
        return XDR.Hyper;
      }
    },
    uint: {
      value: function uint() {
        return XDR.UnsignedInt;
      }
    },
    uhyper: {
      value: function uhyper() {
        return XDR.UnsignedHyper;
      }
    },
    float: {
      value: function float() {
        return XDR.Float;
      }
    },
    double: {
      value: function double() {
        return XDR.Double;
      }
    },
    quadruple: {
      value: function quadruple() {
        return XDR.Quadruple;
      }
    },
    string: {
      value: function string(length) {
        return new SizedReference(XDR.String, length);
      }
    },
    opaque: {
      value: function opaque(length) {
        return new SizedReference(XDR.Opaque, length);
      }
    },
    varOpaque: {
      value: function varOpaque(length) {
        return new SizedReference(XDR.VarOpaque, length);
      }
    },
    array: {
      value: function array(childType, length) {
        return new ArrayReference(childType, length);
      }
    },
    varArray: {
      value: function varArray(childType, maxLength) {
        return new ArrayReference(childType, maxLength, true);
      }
    },
    option: {
      value: function option(childType) {
        return new OptionReference(childType);
      }
    },
    define: {
      value: function define(name, definition) {
        if (isUndefined(this._destination[name])) {
          this._definitions[name] = definition;
        } else {
          throw new Error("XDR Error:" + name + " is already defined");
        }
      }
    },
    lookup: {
      value: function lookup(name) {
        return new SimpleReference(name);
      }
    },
    resolve: {
      value: function resolve() {
        var _this = this;

        each(this._definitions, function (defn, name) {
          defn.resolve({
            definitions: _this._definitions,
            results: _this._destination
          });
        });
      }
    }
  });

  return TypeBuilder;
})();


text:
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

M.form_dndupload = {}

M.form_dndupload.init = function(Y, options) {
    var dnduploadhelper = {
        // YUI object.
        Y: null,
        // URL for upload requests
        url: M.cfg.wwwroot + '/repository/repository_ajax.php?action=upload',
        // options may include: itemid, acceptedtypes, maxfiles, maxbytes, clientid, repositoryid, author, contextid
        options: {},
        // itemid used for repository upload
        itemid: null,
        // accepted filetypes accepted by this form passed to repository
        acceptedtypes: [],
        // maximum size of files allowed in this form
        maxbytes: 0,
        // Maximum combined size of files allowed in this form. {@link FILE_AREA_MAX_BYTES_UNLIMITED}
        areamaxbytes: -1,
        // unqiue id of this form field used for html elements
        clientid: '',
        // upload repository id, used for upload
        repositoryid: 0,
        // container which holds the node which recieves drag events
        container: null,
        // filemanager element we are working with
        filemanager: null,
        // callback  to filepicker element to refesh when uploaded
        callback: null,
        // Nasty hack to distinguish between dragenter(first entry),
        // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
        entercount: 0,
        pageentercount: 0,
        // Holds the progress bar elements for each file.
        progressbars: {},

        /**
         * Initalise the drag and drop upload interface
         * Note: one and only one of options.filemanager and options.formcallback must be defined
         *
         * @param Y the YUI object
         * @param object options {
         *            itemid: itemid used for repository upload in this form
         *            acceptdtypes: accepted filetypes by this form
         *            maxfiles: maximum number of files this form allows
         *            maxbytes: maximum size of files allowed in this form
         *            areamaxbytes: maximum combined size of files allowed in this form
         *            clientid: unqiue id of this form field used for html elements
         *            contextid: id of the current cotnext
         *            containerid: htmlid of container
         *            repositories: array of repository objects passed from filepicker
         *            filemanager: filemanager element we are working with
         *            formcallback: callback  to filepicker element to refesh when uploaded
         *          }
         */
        init: function(Y, options) {
            this.Y = Y;

            if (!this.browser_supported()) {
                Y.one('body').addClass('dndnotsupported');
                return; // Browser does not support the required functionality
            }

            // try and retrieve enabled upload repository
            this.repositoryid = this.get_upload_repositoryid(options.repositories);

            if (!this.repositoryid) {
                Y.one('body').addClass('dndnotsupported');
                return; // no upload repository is enabled to upload to
            }

            Y.one('body').addClass('dndsupported');

            this.options = options;
            this.acceptedtypes = options.acceptedtypes;
            this.clientid = options.clientid;
            this.maxbytes = options.maxbytes;
            this.areamaxbytes = options.areamaxbytes;
            this.itemid = options.itemid;
            this.author = options.author;
            this.container = this.Y.one('#'+options.containerid);

            if (options.filemanager) {
                // Needed to tell the filemanager to redraw when files uploaded
                // and to check how many files are already uploaded
                this.filemanager = options.filemanager;
            } else if (options.formcallback) {

                // Needed to tell the filepicker to update when a new
                // file is uploaded
                this.callback = options.formcallback;
            } else {
                if (M.cfg.developerdebug) {
                    alert('dndupload: Need to define either options.filemanager or options.formcallback');
                }
                return;
            }

            this.init_events();
            this.init_page_events();
        },

        /**
         * Check the browser has the required functionality
         * @return true if browser supports drag/drop upload
         */
        browser_supported: function() {

            if (typeof FileReader == 'undefined') {
                return false;
            }
            if (typeof FormData == 'undefined') {
                return false;
            }
            return true;
        },

        /**
         * Get upload repoistory from array of enabled repositories
         *
         * @param array repositories repository objects passed from filepicker
         * @param returns int id of upload repository or false if not found
         */
        get_upload_repositoryid: function(repositories) {
            for (var i in repositories) {
                if (repositories[i].type == "upload") {
                    return repositories[i].id;
                }
            }

            return false;
        },

        /**
         * Initialise drag events on node container, all events need
         * to be processed for drag and drop to work
         */
        init_events: function() {
            this.Y.on('dragenter', this.drag_enter, this.container, this);
            this.Y.on('dragleave', this.drag_leave, this.container, this);
            this.Y.on('dragover',  this.drag_over,  this.container, this);
            this.Y.on('drop',      this.drop,      this.container, this);
        },

        /**
         * Initialise whole-page events (to show / hide the 'drop files here'
         * message)
         */
        init_page_events: function() {
            this.Y.on('dragenter', this.drag_enter_page, 'body', this);
            this.Y.on('dragleave', this.drag_leave_page, 'body', this);
        },

        /**
         * Check if the filemanager / filepicker is disabled
         * @return bool - true if disabled
         */
        is_disabled: function() {
            return (this.container.ancestor('.fitem.disabled') != null);
        },

        /**
         * Show the 'drop files here' message when file(s) are dragged
         * onto the page
         */
        drag_enter_page: function(e) {
            if (this.is_disabled()) {
                return false;
            }
            if (!this.has_files(e)) {
                return false;
            }

            this.pageentercount++;
            if (this.pageentercount >= 2) {
                this.pageentercount = 2;
                return false;
            }

            this.show_drop_target();

            return false;
        },

        /**
         * Hide the 'drop files here' message when file(s) are dragged off
         * the page again
         */
        drag_leave_page: function(e) {
            this.pageentercount--;
            if (this.pageentercount == 1) {
                return false;
            }
            this.pageentercount = 0;

            this.hide_drop_target();

            return false;
        },

        /**
         * Check if the drag contents are valid and then call
         * preventdefault / stoppropagation to let the browser know
         * we will handle this drag/drop
         *
         * @param e event object
         * @return boolean true if a valid file drag event
         */
        check_drag: function(e) {
            if (this.is_disabled()) {
                return false;
            }
            if (!this.has_files(e)) {
                return false;
            }

            e.preventDefault();
            e.stopPropagation();

            return true;
        },

        /**
         * Handle a dragenter event, highlight the destination node
         * when a suitable drag event occurs
         */
        drag_enter: function(e) {
            if (!this.check_drag(e)) {
                return true;
            }

            this.entercount++;
            if (this.entercount >= 2) {
                this.entercount = 2; // Just moved over a child element - nothing to do
                return false;
            }

            // These lines are needed if the user has dragged something directly
            // from application onto the 'fileupload' box, without crossing another
            // part of the page first
            this.pageentercount = 2;
            this.show_drop_target();

            this.show_upload_ready();
            return false;
        },

        /**
         * Handle a dragleave event, Remove the highlight if dragged from
         * node
         */
        drag_leave: function(e) {
            if (!this.check_drag(e)) {
                return true;
            }

            this.entercount--;
            if (this.entercount == 1) {
                return false; // Just moved over a child element - nothing to do
            }

            this.entercount = 0;
            this.hide_upload_ready();
            return false;
        },

        /**
         * Handle a dragover event. Required to intercept to prevent the browser from
         * handling the drag and drop event as normal
         */
        drag_over: function(e) {
            if (!this.check_drag(e)) {
                return true;
            }

            return false;
        },

        /**
         * Handle a drop event.  Remove the highlight and then upload each
         * of the files (until we reach the file limit, or run out of files)
         */
        drop: function(e) {
            if (!this.check_drag(e, true)) {
                return true;
            }

            this.entercount = 0;
            this.pageentercount = 0;
            this.hide_upload_ready();
            this.hide_drop_target();

            var files = e._event.dataTransfer.files;
            if (this.filemanager) {
                var options = {
                    files: files,
                    options: this.options,
                    repositoryid: this.repositoryid,
                    currentfilecount: this.filemanager.filecount, // All files uploaded.
                    currentfiles: this.filemanager.options.list, // Only the current folder.
                    callback: Y.bind('update_filemanager', this),
                    callbackprogress: Y.bind('update_progress', this),
                    callbackcancel:Y.bind('hide_progress', this)
                };
                this.clear_progress();
                this.show_progress();
                var uploader = new dnduploader(options);
                uploader.start_upload();
            } else {
                if (files.length >= 1) {
                    options = {
                        files:[files[0]],
                        options: this.options,
                        repositoryid: this.repositoryid,
                        currentfilecount: 0,
                        currentfiles: [],
                        callback: Y.bind('update_filemanager', this),
                        callbackprogress: Y.bind('update_progress', this),
                        callbackcancel:Y.bind('hide_progress', this)
                    };
                    this.clear_progress();
                    this.show_progress();
                    uploader = new dnduploader(options);
                    uploader.start_upload();
                }
            }

            return false;
        },

        /**
         * Check to see if the drag event has any files in it
         *
         * @param e event object
         * @return boolean true if event has files
         */
        has_files: function(e) {
            // In some browsers, dataTransfer.types may be null for a
            // 'dragover' event, so ensure a valid Array is always
            // inspected.
            var types = e._event.dataTransfer.types || [];
            for (var i=0; i<types.length; i++) {
                if (types[i] == 'Files') {
                    return true;
                }
            }
            return false;
        },

        /**
         * Highlight the area where files could be dropped
         */
        show_drop_target: function() {
            this.container.addClass('dndupload-ready');
        },

        hide_drop_target: function() {
            this.container.removeClass('dndupload-ready');
        },

        /**
         * Highlight the destination node (ready to drop)
         */
        show_upload_ready: function() {
            this.container.addClass('dndupload-over');
        },

        /**
         * Remove highlight on destination node
         */
        hide_upload_ready: function() {
            this.container.removeClass('dndupload-over');
        },

        /**
         * Show the element showing the upload in progress
         */
        show_progress: function() {
            this.container.addClass('dndupload-inprogress');
        },

        /**
         * Hide the element showing upload in progress
         */
        hide_progress: function() {
            this.container.removeClass('dndupload-inprogress');
        },

        /**
         * Tell the attached filemanager element (if any) to refresh on file
         * upload
         */
        update_filemanager: function(params) {
            this.hide_progress();
            if (this.filemanager) {
                // update the filemanager that we've uploaded the files
                this.filemanager.filepicker_callback();
            } else if (this.callback) {
                this.callback(params);
            }
        },

        /**
         * Clear the current progress bars
         */
        clear_progress: function() {
            var filename;
            for (filename in this.progressbars) {
                if (this.progressbars.hasOwnProperty(filename)) {
                    this.progressbars[filename].progressouter.remove(true);
                    delete this.progressbars[filename];
                }
            }
        },

        /**
         * Show the current progress of the uploaded file
         */
        update_progress: function(filename, percent) {
            if (this.progressbars[filename] === undefined) {
                var dispfilename = filename;
                if (dispfilename.length > 50) {
                    dispfilename = dispfilename.substr(0, 49)+'…';
                }
                var progressouter = this.container.create(''+dispfilename+':
');
                var progressinner = progressouter.one('.dndupload-progress-inner');
                var progresscontainer = this.container.one('.dndupload-progressbars');
                progresscontainer.appendChild(progressouter);

                this.progressbars[filename] = {
                    progressouter: progressouter,
                    progressinner: progressinner
                };
            }

            this.progressbars[filename].progressinner.setStyle('width', percent + '%');
        }
    };

    var dnduploader = function(options) {
        dnduploader.superclass.constructor.apply(this, arguments);
    };

    Y.extend(dnduploader, Y.Base, {
        // The URL to send the upload data to.
        api: M.cfg.wwwroot+'/repository/repository_ajax.php',
        // Options passed into the filemanager/filepicker element.
        options: {},
        // The function to call when all uploads complete.
        callback: null,
        // The function to call as the upload progresses
        callbackprogress: null,
        // The function to call if the upload is cancelled
        callbackcancel: null,
        // The list of files dropped onto the element.
        files: null,
        // The ID of the 'upload' repository.
        repositoryid: 0,
        // Array of files already in the current folder (to check for name clashes).
        currentfiles: null,
        // Total number of files already uploaded (to check for exceeding limits).
        currentfilecount: 0,
        // Total size of the files present in the area.
        currentareasize: 0,
        // The list of files to upload.
        uploadqueue: [],
        // This list of files with name clashes.
        renamequeue: [],
        // Size of the current queue.
        queuesize: 0,
        // Set to true if the user has clicked on 'overwrite all'.
        overwriteall: false,
        // Set to true if the user has clicked on 'rename all'.
        renameall: false,

        /**
         * Initialise the settings for the dnduploader
         * @param object params - includes:
         *                     options (copied from the filepicker / filemanager)
         *                     repositoryid - ID of the upload repository
         *                     callback - the function to call when uploads are complete
         *                     currentfiles - the list of files already in the current folder in the filemanager
         *                     currentfilecount - the total files already in the filemanager
         *                     files - the list of files to upload
         * @return void
         */
        initializer: function(params) {
            this.options = params.options;
            this.repositoryid = params.repositoryid;
            this.callback = params.callback;
            this.callbackprogress = params.callbackprogress;
            this.callbackcancel = params.callbackcancel;
            this.currentfiles = params.currentfiles;
            this.currentfilecount = params.currentfilecount;
            this.currentareasize = 0;

            // Retrieve the current size of the area.
            for (var i = 0; i < this.currentfiles.length; i++) {
                this.currentareasize += this.currentfiles[i].size;
            };

            if (!this.initialise_queue(params.files)) {
                if (this.callbackcancel) {
                    this.callbackcancel();
                }
            }
        },

        /**
         * Entry point for starting the upload process (starts by processing any
         * renames needed)
         */
        start_upload: function() {
            this.process_renames(); // Automatically calls 'do_upload' once renames complete.
        },

        /**
         * Display a message in a popup
         * @param string msg - the message to display
         * @param string type - 'error' or 'info'
         */
        print_msg: function(msg, type) {
            var header = M.util.get_string('error', 'moodle');
            if (type != 'error') {
                type = 'info'; // one of only two types excepted
                header = M.util.get_string('info', 'moodle');
            }
            if (!this.msg_dlg) {
                this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
                this.msg_dlg_node.generateID();

                this.msg_dlg = new M.core.dialogue({
                    bodyContent: this.msg_dlg_node,
                    centered: true,
                    modal: true,
                    visible: false
                });
                this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
                this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
                    e.preventDefault();
                    this.msg_dlg.hide();
                }, this);
            }

            this.msg_dlg.set('headerContent', header);
            this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
            this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
            this.msg_dlg.show();
        },

        /**
         * Check the size of each file and add to either the uploadqueue or, if there
         * is a name clash, the renamequeue
         * @param FileList files - the files to upload
         * @return void
         */
        initialise_queue: function(files) {
            this.uploadqueue = [];
            this.renamequeue = [];
            this.queuesize = 0;

            // Loop through the files and find any name clashes with existing files.
            var i;
            for (i=0; i<files.length; i++) {
                if (this.options.maxbytes > 0 && files[i].size > this.options.maxbytes) {
                    // Check filesize before attempting to upload.
                    var maxbytesdisplay = this.display_size(this.options.maxbytes);
                    this.print_msg(M.util.get_string('maxbytesfile', 'error', {
                            file: files[i].name,
                            size: maxbytesdisplay
                        }), 'error');
                    this.uploadqueue = []; // No uploads if one file is too big.
                    return;
                }

                if (this.has_name_clash(files[i].name)) {
                    this.renamequeue.push(files[i]);
                } else {
                    if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
                        return false;
                    }
                }
                this.queuesize += files[i].size;
            }
            return true;
        },

        /**
         * Generate the display for file size
         * @param int size The size to convert to human readable form
         * @return string
         */
        display_size: function(size) {
            // This is snippet of code (with some changes) is from the display_size function in moodlelib.
            var gb = M.util.get_string('sizegb', 'moodle'),
                mb = M.util.get_string('sizemb', 'moodle'),
                kb = M.util.get_string('sizekb', 'moodle'),
                b  = M.util.get_string('sizeb', 'moodle');

            if (size >= 1073741824) {
                size = Math.round(size / 1073741824 * 10) / 10 + gb;
            } else if (size >= 1048576) {
                size = Math.round(size / 1048576 * 10) / 10 + mb;
            } else if (size >= 1024) {
                size = Math.round(size / 1024 * 10) / 10 + kb;
            } else {
                size = parseInt(size, 10) + ' ' + b;
            }

            return size;
        },

        /**
         * Add a single file to the uploadqueue, whilst checking the maxfiles limit
         * @param File file - the file to add
         * @param string filename - the name to give the file on upload
         * @param bool overwrite - true to overwrite the existing file
         * @return bool true if added successfully
         */
        add_to_upload_queue: function(file, filename, overwrite) {
            if (!overwrite) {
                this.currentfilecount++;
            }
            // The value for "unlimited files" is -1, so 0 should mean 0.
            if (this.options.maxfiles >= 0 && this.currentfilecount > this.options.maxfiles) {
                // Too many files - abort entire upload.
                this.uploadqueue = [];
                this.renamequeue = [];
                this.print_msg(M.util.get_string('maxfilesreached', 'moodle', this.options.maxfiles), 'error');
                return false;
            }
            // The new file will cause the area to reach its limit, we cancel the upload of all files.
            // -1 is the value defined by FILE_AREA_MAX_BYTES_UNLIMITED.
            if (this.options.areamaxbytes > -1) {
                var sizereached = this.currentareasize + this.queuesize + file.size;
                if (sizereached > this.options.areamaxbytes) {
                    this.uploadqueue = [];
                    this.renamequeue = [];
                    this.print_msg(M.util.get_string('maxareabytesreached', 'moodle'), 'error');
                    return false;
                }
            }
            this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
            return true;
        },

        /**
         * Take the next file from the renamequeue and ask the user what to do with
         * it. Called recursively until the queue is empty, then calls do_upload.
         * @return void
         */
        process_renames: function() {
            if (this.renamequeue.length == 0) {
                // All rename processing complete - start the actual upload.
                this.do_upload();
                return;
            }
            var multiplefiles = (this.renamequeue.length > 1);

            // Get the next file from the rename queue.
            var file = this.renamequeue.shift();
            // Generate a non-conflicting name for it.
            var newname = this.generate_unique_name(file.name);

            // If the user has clicked on overwrite/rename ALL then process
            // this file, as appropriate, then process the rest of the queue.
            if (this.overwriteall) {
                this.add_to_upload_queue(file, file.name, true);
                this.process_renames();
                return;
            }
            if (this.renameall) {
                this.add_to_upload_queue(file, newname, false);
                this.process_renames();
                return;
            }

            // Ask the user what to do with this file.
            var self = this;

            var process_dlg_node;
            if (multiplefiles) {
                process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfilemultiple);
            } else {
                process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
            }
            var node = process_dlg_node;
            node.generateID();
            var process_dlg = new M.core.dialogue({
                bodyContent: node,
                headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
                centered: true,
                modal: true,
                visible: false
            });
            process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});

            // Overwrite original.
            node.one('.fp-dlg-butoverwrite').on('click', function(e) {
                e.preventDefault();
                process_dlg.hide();
                self.add_to_upload_queue(file, file.name, true);
                self.process_renames();
            }, this);

            // Rename uploaded file.
            node.one('.fp-dlg-butrename').on('click', function(e) {
                e.preventDefault();
                process_dlg.hide();
                self.add_to_upload_queue(file, newname, false);
                self.process_renames();
            }, this);

            // Cancel all uploads.
            node.one('.fp-dlg-butcancel').on('click', function(e) {
                e.preventDefault();
                process_dlg.hide();
                if (self.callbackcancel) {
                    self.callbackcancel();
                }
            }, this);

            // When we are at the file limit, only allow 'overwrite', not rename.
            if (this.currentfilecount == this.options.maxfiles) {
                node.one('.fp-dlg-butrename').setStyle('display', 'none');
                if (multiplefiles) {
                    node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
                }
            }

            // If there are more files still to go, offer the 'overwrite/rename all' options.
            if (multiplefiles) {
                // Overwrite all original files.
                node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
                    e.preventDefault();
                    process_dlg.hide();
                    this.overwriteall = true;
                    self.add_to_upload_queue(file, file.name, true);
                    self.process_renames();
                }, this);

                // Rename all new files.
                node.one('.fp-dlg-butrenameall').on('click', function(e) {
                    e.preventDefault();
                    process_dlg.hide();
                    this.renameall = true;
                    self.add_to_upload_queue(file, newname, false);
                    self.process_renames();
                }, this);
            }
            node.one('.fp-dlg-text').setContent(M.util.get_string('fileexists', 'moodle', file.name));
            process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', newname));

            // Destroy the dialog once it has been hidden.
            process_dlg.after('visibleChange', function(e) {
                if (!process_dlg.get('visible')) {
                    process_dlg.destroy(true);
                }
            });

            process_dlg.show();
        },

        /**
         * Checks if there is already a file with the given name in the current folder
         * or in the list of already uploading files
         * @param string filename - the name to test
         * @return bool true if the name already exists
         */
        has_name_clash: function(filename) {
            // Check against the already uploaded files
            var i;
            for (i=0; i<this.currentfiles.length; i++) {
                if (filename == this.currentfiles[i].filename) {
                    return true;
                }
            }
            // Check against the uploading files that have already been processed
            for (i=0; i<this.uploadqueue.length; i++) {
                if (filename == this.uploadqueue[i].filename) {
                    return true;
                }
            }
            return false;
        },

        /**
         * Gets a unique file name
         *
         * @param string filename
         * @return string the unique filename generated
         */
        generate_unique_name: function(filename) {
            // Loop through increating numbers until a unique name is found.
            while (this.has_name_clash(filename)) {
                filename = increment_filename(filename);
            }
            return filename;
        },

        /**
         * Upload the next file from the uploadqueue - called recursively after each
         * upload is complete, then handles the callback to the filemanager/filepicker
         * @param lastresult - the last result from the server
         */
        do_upload: function(lastresult) {
            if (this.uploadqueue.length > 0) {
                var filedetails = this.uploadqueue.shift();
                this.upload_file(filedetails.file, filedetails.filename, filedetails.overwrite);
            } else {
                this.uploadfinished(lastresult);
            }
        },

        /**
         * Run the callback to the filemanager/filepicker
         */
        uploadfinished: function(lastresult) {
            this.callback(lastresult);
        },

        /**
         * Upload a single file via an AJAX call to the 'upload' repository. Automatically
         * calls do_upload as each upload completes.
         * @param File file - the file to upload
         * @param string filename - the name to give the file
         * @param bool overwrite - true if the existing file should be overwritten
         */
        upload_file: function(file, filename, overwrite) {

            // This would be an ideal place to use the Y.io function
            // however, this does not support data encoded using the
            // FormData object, which is needed to transfer data from
            // the DataTransfer object into an XMLHTTPRequest
            // This can be converted when the YUI issue has been integrated:
            // http://yuilibrary.com/projects/yui3/ticket/2531274
            var xhr = new XMLHttpRequest();
            var self = this;

            // Update the progress bar
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable && self.callbackprogress) {
                    var percentage = Math.round((e.loaded * 100) / e.total);
                    self.callbackprogress(filename, percentage);
                }
            }, false);

            xhr.onreadystatechange = function() { // Process the server response
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var result = JSON.parse(xhr.responseText);
                        if (result) {
                            if (result.error) {
                                self.print_msg(result.error, 'error'); // TODO add filename?
                                self.uploadfinished();
                            } else {
                                // Only update the filepicker if there were no errors
                                if (result.event == 'fileexists') {
                                    // Do not worry about this, as we only care about the last
                                    // file uploaded, with the filepicker
                                    result.file = result.newfile.filename;
                                    result.url = result.newfile.url;
                                }
                                result.client_id = self.options.clientid;
                                if (self.callbackprogress) {
                                    self.callbackprogress(filename, 100);
                                }
                            }
                        }
                        self.do_upload(result); // continue uploading
                    } else {
                        self.print_msg(M.util.get_string('serverconnection', 'error'), 'error');
                        self.uploadfinished();
                    }
                }
            };

            // Prepare the data to send
            var formdata = new FormData();
            formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file
            formdata.append('sesskey', M.cfg.sesskey);
            formdata.append('repo_id', this.repositoryid);
            formdata.append('itemid', this.options.itemid);
            if (this.options.author) {
                formdata.append('author', this.options.author);
            }
            if (this.options.filemanager) { // Filepickers do not have folders
                formdata.append('savepath', this.options.filemanager.currentpath);
            }
            formdata.append('title', filename);
            if (overwrite) {
                formdata.append('overwrite', 1);
            }
            if (this.options.contextid) {
                formdata.append('ctx_id', this.options.contextid);
            }

            // Accepted types can be either a string or an array, but an array is
            // expected in the processing script, so make sure we are sending an array
            if (this.options.acceptedtypes.constructor == Array) {
                for (var i=0; i<this.options.acceptedtypes.length; i++) {
                    formdata.append('accepted_types[]', this.options.acceptedtypes[i]);
                }
            } else {
                formdata.append('accepted_types[]', this.options.acceptedtypes);
            }

            // Send the file & required details.
            var uploadUrl = this.api;
            if (uploadUrl.indexOf('?') !== -1) {
                uploadUrl += '&action=upload';
            } else {
                uploadUrl += '?action=upload';
            }
            xhr.open("POST", uploadUrl, true);
            xhr.send(formdata);
            return true;
        }
    });

    dnduploadhelper.init(Y, options);
};


text:
package com.lyokone.location.location.helper;

import androidx.annotation.Nullable;

public final class StringUtils {

    private StringUtils() {
        // no instance
    }

    public static boolean isEmpty(@Nullable CharSequence str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(@Nullable CharSequence str) {
        return str != null && str.length() > 0;
    }

}


text:
package extracells.models;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;

import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.EnumFacing;

import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public abstract class BlankModel implements IBakedModel {
	@Nullable
	protected ItemOverrideList overrideList;

	@Override
	public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) {
		return Collections.emptyList();
	}

	protected ItemOverrideList createOverrides() {
		return ItemOverrideList.NONE;
	}

	@Override
	public ItemOverrideList getOverrides() {
		if (overrideList == null) {
			overrideList = createOverrides();
		}
		return overrideList;
	}

	@Override
	public boolean isAmbientOcclusion() {
		return true;
	}

	@Override
	public boolean isGui3d() {
		return true;
	}

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

	@Override
	public TextureAtlasSprite getParticleTexture() {
		return Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite();
	}

	@Override
	public ItemCameraTransforms getItemCameraTransforms() {
		return ItemCameraTransforms.DEFAULT;
	}

}


text:
package de.plushnikov.builder.tobuilder;

@lombok.experimental.Accessors(prefix = "m")
class BuilderWithToBuilderOnConstructor<T> {
	private String mOne, mTwo;

	private T foo;

	@lombok.Singular
	private java.util.List<T> bars;

	@lombok.Builder(toBuilder = true)
	public BuilderWithToBuilderOnConstructor(String mOne, @lombok.Builder.ObtainVia(field = "foo") T bar) {
	}

	public static void main(String[] args) {
		BuilderWithToBuilderOnConstructor<String> bean = new BuilderWithToBuilderOnConstructor<String>("mOneParam", "barParam");
		bean.mOne = "mOne";
		bean.mTwo = "mTwo";
		bean.foo = "foo";

		BuilderWithToBuilderOnConstructor.BuilderWithToBuilderOnConstructorBuilder x = bean.toBuilder();
		System.out.println(x);

		x.mOne("builderOne");
		x.bar("builderBar");
		System.out.println(x);
	}
}


text:
package com.streamsets.pipeline.stage.origin.jdbc.cdc.postgres;

import com.streamsets.pipeline.api.Config;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.StageUpgrader;
import com.streamsets.pipeline.api.impl.Utils;
import java.util.List;

public class PostgresCDCSourceUpgrader implements StageUpgrader {
  @Override
  public List<Config> upgrade(String library, String stageName, String stageInstance, int fromVersion, int toVersion, List<Config> configs) throws StageException {
    switch (fromVersion) {
      case 1:
        configs.add(new Config("postgresCDCConfigBean.maxBatchWaitTime", 15000));
        if (toVersion == 2) {
          break;
        }
      case 2:
        configs.add(new Config("postgresCDCConfigBean.generatorQueueMaxSize", getMaxBatchSize(configs) * 5));
        configs.add(new Config("postgresCDCConfigBean.statusInterval", 30));
        if (toVersion == 3) {
          break;
        }

      default:
        throw new IllegalStateException(Utils.format("Unexpected fromVersion {}", fromVersion));
    }

    return configs;
  }

  private int getMaxBatchSize(List<Config> configs) {
    for (Config config : configs) {
      if(config.getName().equals("postgresCDCConfigBean.baseConfigBean.maxBatchSize")) {
        return (int)config.getValue();
      }
    }

    return 1000;
  }

}


text:
package com.intellij.openapi.command.impl;

import com.intellij.openapi.command.undo.DocumentReference;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

class DocumentReferenceByNonlocalVirtualFile implements DocumentReference {
  private final VirtualFile myFile;

  DocumentReferenceByNonlocalVirtualFile(@NotNull VirtualFile file) {
    myFile = file;
  }

  @Override
  @Nullable
  public Document getDocument() {
    return FileDocumentManager.getInstance().getDocument(myFile);
  }

  @Override
  @NotNull
  public VirtualFile getFile() {
    return myFile;
  }

  @Override
  public String toString() {
    return myFile.toString();
  }
}


text:
/*
 * @page index home
 *
JavaScriptMVC - develop with direction!

 *
JavaScriptMVC is an open-source framework
 * containing the best ideas in enterprise JavaScript development.
 * It guides you to successfully completed projects by promoting best practices,
 * maintainability, and convention over configuration.

 *
 Download JavaScriptMVC
 2.0 Production (6.2 MB)

     Watch
     2.0 Video

 *
What's Inside?

 * We've made everything you should be doing as easy as possible.
 *

 *
Maintainability via the [jQuery.Model Model]-[jQuery.View View]-[jQuery.Controller Controller] architecture pattern.

 *
Application Concatination and Compression via [include].

 *
Testing via [jQuery.Test Test].

 *
Documentation via [include.Doc].

 *
Error Reporting via [http://damnit.jupiterit.com DamnIT].

 *
Updates and Dependancy Management via update.

 *
Ajax and DOM functionality via [http://jquery.com jQuery].

 *

 *
The Plan.

 *

 *
[download |Download] JavaScriptMVC

 *
[getstarted |Read] the Getting Started Guide

 *
[learn Learn] the technology

 *
[api Explore] the api

 *

 *
Showcase.

 * Checkout some of the companies using JavaScriptMVC:
 *

 *
[http://www.zend.com Zend]

 *
[http://www.shoretel.com ShoreTel]

 *
[http://www.wegener.com/ Wegner]

 *
[http://www.musicglue.com/ MusicGlue]

 *
[http://jupiterit.com Jupiter IT]

 *
[http://socialcollider.net/ SocialCollider]

 *

 */
include('getstarted','api','download','learn','why','selenium','follow','contribute','help','generators')


text:
cd libmo_unpack

if [[ $(uname) == Darwin ]]
then
   # Just build for this version for now.
   unset MACOSX_DEPLOYMENT_TARGET
   gcc -c -fPIC -O3 -mfpmath=sse -msse -I include -D_LARGEFILE_SOURCE -D_DARWIN_SOURCE *.c

   ld -dylib -undefined dynamic_lookup -arch x86_64 -o lib/libmo_unpack.dylib *.o
else
   gcc -c -fPIC -O4 -mfpmath=sse -msse -I include -D_LARGEFILE_SOURCE *.c

   gcc -shared -Wl,-soname,libmo_unpack.so -o lib/libmo_unpack.so *.o
fi

# Actually install the built product.
mkdir $PREFIX/lib $PREFIX/include
cp lib/* $PREFIX/lib
cp include/* $PREFIX/include


text:
layout: post
title: Android - AsyncTask Kullanımı
date: 2014-02-12 15:17
comments: true
categories:
---

`AsyncTask`, ana thread ile arka plan işlemlerini birleştirmemize sağlıyan güzide
bir Android sınıfı. Bilindiği üzere bazı sebeblerden (mesela `performans`) dolayı
Android'i geliştiren abilerimiz ana thread bazı işlemleri yapmamızı
yasaklamışlar(`Network` işlemleri gibi). Kullanmamız için bize `Thread` sınıfını
özelleştirip `AsyncTask` sınıfını sunmuşlar. `Thread`lerden farklı olarak
arka plan işlemi hakkında aşama aşama bilgi sahibi olabiliyoruz. <!-- more -->

### Nasıl Kullanılır ?

        private class ArkaplanIslemi extends AsyncTask<var1, var2, var3>

Önce yukardaki gibi sınıfızı AsyncTask sınıfından extends ediyoruz. Burada
bilmeniz gereken var1, var2 ve var3 un ne olduğu.

- var1 = Ana threadten AsyncTask verilecek değişken( örneğin dosya indirme
  işlemi yapılacaksa URL)
- var2 = Arka plan işlemi sürerken aşamalar arasında bilgi alışverişi için
  kullanılacak değişken( 100 dosya inecek sizde her 25 dosya indiğinde kullanıcı
  bildirmek istiyorsanız int verebilirsiniz.)
- var3 = Arka plan işlemi bittiğinde ana threade dönülecek değişken tipi

Bunları söyledikten sonra artık AsyncTask'ın aşamlarına geçebiliriz.

#### onPreExecute()

Bu aşamada daha arkaplan işlemi başlamamıştır. Ana thread üzerinde değişiklik
yapabilirsiniz. Örneğin; bir TextView'in içeriğini "indirme işlemi başlıyor"
olarak değiştirebilirisiniz.

#### doInBackground(var1...)

Bu aşamada artık arkaplan işlemi başlamış durumda. Ana thread'ten alınan veriler
burda işleniyor.

#### onProgressUpdate(var2...)

Bu aşamada ise arkaplan işlemi devam ederken, ana thread'e (yani kullanıcıya)
bilgi verme işlemi yapılır. Örneğin; "50 dosya indi." gibi.

#### onPostExecute(var3...)

Artık arka plan işlemi bitmiştir. Sonucun ana thread'e döndürüldüğü aşamadır.

Sınıfı çağırma işlemide:

        ArkaplanIslemi.execute(argumanlar...)


text:
<!--
  kissy 构建文件,开启每个组件的构建
  @author yiminghe@gmail.com
-->
<project name="config">

    <!-- kissy 主目录 -->
    <property name="kissy.dir" location="${ant.file.config}/../../"/>
    <!-- kissy 工具目录 -->
    <property name="tools.dir" location="${kissy.dir}/tools/"/>
    <property name="module-compiler"
              location="${tools.dir}/module-compiler/module-compiler.jar"/>
    <property name="closure-compiler"
              location="${tools.dir}/closure-compiler/closure-compiler.jar"/>
    <property name="yui-compressor"
              location="${tools.dir}/yui-compressor/yui-compressor.jar"/>
    <property name="kissy.build.dir" location="${kissy.dir}/build/"/>
    <property name="kissy.src.dir" location="${kissy.dir}/src/"/>

    <property name="version" value="1.40dev"/>
    <property name="charset" value="utf-8"/>
    <property name="js-css.files" value="**/*.js,**/*.css"/>
    <property name="js-css.min.files" value="**/*-min.js,**/*-min.css"/>

    <property name="git.origin" value="origin"/>
    <property name="git.remote" value="remote"/>
    <property name="git.gh-pages" value="gh-pages"/>
    <property name="git.master" value="master"/>
    <property name="git.dev" value="dev"/>
    <property name="bom" value=""/>

</project>


text:
namespace GitVersion;

public interface IRemote : IEquatable<IRemote?>, IComparable<IRemote>
{
    string Name { get; }
    string Url { get; }

    IEnumerable<IRefSpec> RefSpecs { get; }
    IEnumerable<IRefSpec> FetchRefSpecs { get; }
    IEnumerable<IRefSpec> PushRefSpecs { get; }
}


text:
package com.aspose.ocr.examples.OcrFeatures;

import com.aspose.ocr.AsposeOCR;
import com.aspose.ocr.Language;
import com.aspose.ocr.License;
import com.aspose.ocr.RecognitionResult;
import com.aspose.ocr.RecognitionSettings;
import com.aspose.ocr.examples.License.SetLicense;
import com.aspose.ocr.examples.Utils;

import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;

public class OCROperationWithLanguageSelection {

	public static void main(String[] args) {
		// ExStart:1
		// The path to the documents directory.
		String dataDir = Utils.getSharedDataDir(OCROperationWithLanguageSelection.class);

		// The image path
		String file = dataDir + "p3.png";

		//Create api instance
		AsposeOCR api = new AsposeOCR();

		// set recognition options
		RecognitionSettings settings = new RecognitionSettings();
		settings.setAutoSkew(false);
		ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
		rectangles.add(new Rectangle(90,186,775,95));
		settings.setRecognitionAreas(rectangles);
		settings.setSkew(0.5);
		settings.setLanguage(Language.Eng);

		// get result object
		RecognitionResult result = null;
		try {
			result = api.RecognizePage(file, settings);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// print result
		System.out.println("Result: \n" + result.recognitionText+"\n\n");
		for(String n: result.recognitionAreasText) {
			System.out.println ( n );
		}
		for(Rectangle n: result.recognitionAreasRectangles) {
			System.out.println(n.height+":"+n.width+":"+n.x+":"+n.y);
		}
		System.out.println("\nJSON:" + result.GetJson());
		System.out.println("angle:" + result.skew);
		for(String n: result.warnings) {
			System.out.println ( n );
		}
		// ExEnd:1

		System.out.println("OCROperationWithLanguageSelection: execution complete");
	}
}


text:
'use strict';

var utils = require('../../lib/utils');
var fs = require('fs');
var path = require('path');
var os = require('os');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

describe('file utils', function () {
  var tmpDir = path.join(os.tmpdir(), 'mocha-file-lookup');
  var existsSync = fs.existsSync;
  var tmpFile = path.join.bind(path, tmpDir);
  var symlinkSupported = false;

  beforeEach(function () {
    this.timeout(2000);
  });

  (function testSymlinkSupport () {
    makeTempDir();

    fs.writeFileSync(tmpFile('mocha-utils.js'), 'yippy skippy ying yang yow');
    try {
      fs.symlinkSync(tmpFile('mocha-utils.js'), tmpFile('mocha-utils-link.js'));
      symlinkSupported = true;
    } catch (ignored) {
      // ignored
    } finally {
      removeTempDir();
    }
  }());

  beforeEach(function () {
    makeTempDir();

    fs.writeFileSync(tmpFile('mocha-utils.js'), 'yippy skippy ying yang yow');
    if (symlinkSupported) {
      fs.symlinkSync(tmpFile('mocha-utils.js'), tmpFile('mocha-utils-link.js'));
    }
  });

  describe('.lookupFiles', function () {
    (symlinkSupported ? it : it.skip)('should not return broken symlink file path', function () {
      expect(utils.lookupFiles(tmpDir, ['js'], false))
        .to
        .contain(tmpFile('mocha-utils-link.js'))
        .and
        .contain(tmpFile('mocha-utils.js'))
        .and
        .have
        .length(2);
      expect(existsSync(tmpFile('mocha-utils-link.js')))
        .to
        .be(true);
      fs.renameSync(tmpFile('mocha-utils.js'), tmpFile('bob'));
      expect(existsSync(tmpFile('mocha-utils-link.js')))
        .to
        .be(false);
      expect(utils.lookupFiles(tmpDir, ['js'], false))
        .to
        .eql([]);
    });

    it('should accept a glob "path" value', function () {
      var res = utils.lookupFiles(tmpFile('mocha-utils*'), ['js'], false)
        .map(path.normalize.bind(path));

      var expectedLength = 0;
      var ex = expect(res)
        .to
        .contain(tmpFile('mocha-utils.js'));
      expectedLength++;

      if (symlinkSupported) {
        ex = ex.and
          .contain(tmpFile('mocha-utils-link.js'));
        expectedLength++;
      }

      ex.and
        .have
        .length(expectedLength);
    });
  });

  describe('.files', function () {
    (symlinkSupported ? it : it.skip)('should return broken symlink file path', function () {
      expect(utils.files(tmpDir, ['js']))
        .to.contain(tmpFile('mocha-utils-link.js'))
        .and.contain(tmpFile('mocha-utils.js'))
        .and.have.length(2);

      expect(existsSync(tmpFile('mocha-utils-link.js')))
        .to.be(true);

      fs.renameSync(tmpFile('mocha-utils.js'), tmpFile('bob'));

      expect(existsSync(tmpFile('mocha-utils-link.js')))
        .to.be(false);

      expect(utils.files(tmpDir, ['js']))
        .to.eql([tmpFile('mocha-utils-link.js')]);
    });
  });

  afterEach(removeTempDir);

  function makeTempDir () {
    mkdirp.sync(tmpDir);
  }

  function removeTempDir () {
    rimraf.sync(tmpDir);
  }
});


text:
body { padding: 70px 0px 0px 65px; font-family: 'Rale', sans-serif;
font-weight: 100; font-size: 22px;
background: #420d20 url(../stylesheets/images/background/images8.jpg)
no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover; }

h1 {font-size:35px }

p {
  display: inline-block;
  font-size: 15px;
  font-family: 'Rale';
  color: black;
}

footer {font-size: 15px;
  font-family: 'Times New Roman';
  color: black;
}

form {font-size: 15px;
  width:}

  .topleft{postion: absolute;
    font-size: 20px;
    top: 8px;
    left:10px;}
    section {
      font-size: 20px;
    }


text:
pythonutils
===========

This contains python utils