text:
import React from 'react'
import toml from 'toml-js'
import Helmet from 'react-helmet'
import { config } from 'config'

module.exports = React.createClass({
  propTypes () {
    return {
      route: React.PropTypes.object,
    }
  },
  render () {
    const data = this.props.route.page.data
    return (

        <Helmet
          title={`${config.siteTitle} | ${data.title}`}
        />

{data.title}

Raw view of toml file

    )
  },
})

redpajama_set_name: RedPajamaGithub


text:
		{% if site.comment %}

Comments

		{% endif %}
		{% if site.comment.disqus %}

		Please enable JavaScript to view the comments powered by Disqus.
		{% endif %}

		{% if site.comment.youyan %}

		{% endif %}


text:
module Azure::CDN::Mgmt::V2017_04_02
  module Models
    #
    # Defines values for SkuName
    #
    module SkuName
      StandardVerizon = "Standard_Verizon"
      PremiumVerizon = "Premium_Verizon"
      CustomVerizon = "Custom_Verizon"
      StandardAkamai = "Standard_Akamai"
      StandardChinaCdn = "Standard_ChinaCdn"
    end
  end
end


text:
namespace DDZProj.Effect
{
    partial class Begin_DXJ
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Begin_DXJ));
            this.pb1 = new System.Windows.Forms.PictureBox();
            this.pb_NumSingle = new System.Windows.Forms.PictureBox();
            this.pb3 = new System.Windows.Forms.PictureBox();
            this.pb_NumTen = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pb1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb_NumSingle)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb3)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb_NumTen)).BeginInit();
            this.SuspendLayout();
            //
            // pb1
            //
            this.pb1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pb1.BackgroundImage")));
            this.pb1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pb1.Location = new System.Drawing.Point(7, 0);
            this.pb1.Name = "pb1";
            this.pb1.Size = new System.Drawing.Size(150, 200);
            this.pb1.TabIndex = 0;
            this.pb1.TabStop = false;
            //
            // pb_NumSingle
            //
            this.pb_NumSingle.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pb_NumSingle.BackgroundImage")));
            this.pb_NumSingle.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pb_NumSingle.Location = new System.Drawing.Point(221, -3);
            this.pb_NumSingle.Name = "pb_NumSingle";
            this.pb_NumSingle.Size = new System.Drawing.Size(86, 200);
            this.pb_NumSingle.TabIndex = 1;
            this.pb_NumSingle.TabStop = false;
            //
            // pb3
            //
            this.pb3.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pb3.BackgroundImage")));
            this.pb3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pb3.Location = new System.Drawing.Point(375, -3);
            this.pb3.Name = "pb3";
            this.pb3.Size = new System.Drawing.Size(153, 200);
            this.pb3.TabIndex = 2;
            this.pb3.TabStop = false;
            //
            // pb_NumTen
            //
            this.pb_NumTen.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pb_NumTen.BackgroundImage")));
            this.pb_NumTen.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pb_NumTen.Location = new System.Drawing.Point(163, -3);
            this.pb_NumTen.Name = "pb_NumTen";
            this.pb_NumTen.Size = new System.Drawing.Size(86, 200);
            this.pb_NumTen.TabIndex = 3;
            this.pb_NumTen.TabStop = false;
            this.pb_NumTen.Visible = false;
            //
            // Begin_DXJ
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Transparent;
            this.Controls.Add(this.pb_NumSingle);
            this.Controls.Add(this.pb_NumTen);
            this.Controls.Add(this.pb3);
            this.Controls.Add(this.pb1);
            this.Name = "Begin_DXJ";
            this.Size = new System.Drawing.Size(626, 200);
            ((System.ComponentModel.ISupportInitialize)(this.pb1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb_NumSingle)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb3)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pb_NumTen)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox pb1;
        private System.Windows.Forms.PictureBox pb_NumSingle;
        private System.Windows.Forms.PictureBox pb3;
        private System.Windows.Forms.PictureBox pb_NumTen;
    }
}


text:
module.exports = {
    url : 'localhost:27017/turinglab'
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>shop_onlineStore</title>

shop_onlineStore

	store
	http://test-ui-interconnect-demo-1487186885376.mybluemix.net/
	MyURL

	open
	${MyURL}

	clickAndWait
	link=Catalog Load Tester


text:
layout: post
title: "Master's Calculator International"
description: "Formula Update"
tags: [Apps]
---

Will update soon with exact FINA points formula.
It will use the cubic function:

`P = 1000 * (Bt / T)^3`

Where `P` are the points, `Bt` is the base time and `T` is the time performed.


text:
namespace Kvasir {
//System Mode Controller
    namespace SmcPmprot{    ///<Power Mode Protection register
        using Addr = Register::Address<0x4007e000,0xffffff5d,0x00000000,unsigned char>;
        ///Allow Very-Low-Leakage Stop Mode
        enum class AvllsVal {
            v0=0x00000000,     ///<Any VLLSx mode is not allowed
            v1=0x00000001,     ///<Any VLLSx mode is allowed
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,AvllsVal> avlls{};
        namespace AvllsValC{
            constexpr Register::FieldValue<decltype(avlls)::Type,AvllsVal::v0> v0{};
            constexpr Register::FieldValue<decltype(avlls)::Type,AvllsVal::v1> v1{};
        }
        ///Allow Very-Low-Power Modes
        enum class AvlpVal {
            v0=0x00000000,     ///<VLPR, VLPW, and VLPS are not allowed.
            v1=0x00000001,     ///<VLPR, VLPW, and VLPS are allowed.
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,AvlpVal> avlp{};
        namespace AvlpValC{
            constexpr Register::FieldValue<decltype(avlp)::Type,AvlpVal::v0> v0{};
            constexpr Register::FieldValue<decltype(avlp)::Type,AvlpVal::v1> v1{};
        }
        ///Allow High Speed Run mode
        enum class AhsrunVal {
            v0=0x00000000,     ///<HSRUN is not allowed
            v1=0x00000001,     ///<HSRUN is allowed
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,AhsrunVal> ahsrun{};
        namespace AhsrunValC{
            constexpr Register::FieldValue<decltype(ahsrun)::Type,AhsrunVal::v0> v0{};
            constexpr Register::FieldValue<decltype(ahsrun)::Type,AhsrunVal::v1> v1{};
        }
    }
    namespace SmcPmctrl{    ///<Power Mode Control register
        using Addr = Register::Address<0x4007e001,0xffffff90,0x00000000,unsigned char>;
        ///Stop Mode Control
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> stopm{};
        ///Stop Aborted
        enum class StopaVal {
            v0=0x00000000,     ///<The previous stop mode entry was successsful.
            v1=0x00000001,     ///<The previous stop mode entry was aborted.
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,StopaVal> stopa{};
        namespace StopaValC{
            constexpr Register::FieldValue<decltype(stopa)::Type,StopaVal::v0> v0{};
            constexpr Register::FieldValue<decltype(stopa)::Type,StopaVal::v1> v1{};
        }
        ///Run Mode Control
        enum class RunmVal {
            v00=0x00000000,     ///<Normal Run mode (RUN)
            v10=0x00000002,     ///<Very-Low-Power Run mode (VLPR)
            v11=0x00000003,     ///<High Speed Run mode (HSRUN)
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,5),Register::ReadWriteAccess,RunmVal> runm{};
        namespace RunmValC{
            constexpr Register::FieldValue<decltype(runm)::Type,RunmVal::v00> v00{};
            constexpr Register::FieldValue<decltype(runm)::Type,RunmVal::v10> v10{};
            constexpr Register::FieldValue<decltype(runm)::Type,RunmVal::v11> v11{};
        }
    }
    namespace SmcStopctrl{    ///<Stop Control Register
        using Addr = Register::Address<0x4007e002,0xffffff00,0x00000000,unsigned char>;
        ///VLLS Mode Control
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> vllsm{};
        ///LPO Power Option
        enum class LpopoVal {
            v0=0x00000000,     ///<LPO clock is enabled in LLS/VLLSx
            v1=0x00000001,     ///<LPO clock is disabled in LLS/VLLSx
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,LpopoVal> lpopo{};
        namespace LpopoValC{
            constexpr Register::FieldValue<decltype(lpopo)::Type,LpopoVal::v0> v0{};
            constexpr Register::FieldValue<decltype(lpopo)::Type,LpopoVal::v1> v1{};
        }
        ///RAM2 Power Option
        enum class Ram2poVal {
            v0=0x00000000,     ///<RAM2 not powered in VLLS2
            v1=0x00000001,     ///<RAM2 powered in VLLS2
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,Ram2poVal> ram2po{};
        namespace Ram2poValC{
            constexpr Register::FieldValue<decltype(ram2po)::Type,Ram2poVal::v0> v0{};
            constexpr Register::FieldValue<decltype(ram2po)::Type,Ram2poVal::v1> v1{};
        }
        ///POR Power Option
        enum class PorpoVal {
            v0=0x00000000,     ///<POR detect circuit is enabled in VLLS0
            v1=0x00000001,     ///<POR detect circuit is disabled in VLLS0
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,PorpoVal> porpo{};
        namespace PorpoValC{
            constexpr Register::FieldValue<decltype(porpo)::Type,PorpoVal::v0> v0{};
            constexpr Register::FieldValue<decltype(porpo)::Type,PorpoVal::v1> v1{};
        }
        ///Partial Stop Option
        enum class PstopoVal {
            v00=0x00000000,     ///<STOP - Normal Stop mode
            v01=0x00000001,     ///<PSTOP1 - Partial Stop with both system and bus clocks disabled
            v10=0x00000002,     ///<PSTOP2 - Partial Stop with system clock disabled and bus clock enabled
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,PstopoVal> pstopo{};
        namespace PstopoValC{
            constexpr Register::FieldValue<decltype(pstopo)::Type,PstopoVal::v00> v00{};
            constexpr Register::FieldValue<decltype(pstopo)::Type,PstopoVal::v01> v01{};
            constexpr Register::FieldValue<decltype(pstopo)::Type,PstopoVal::v10> v10{};
        }
    }
    namespace SmcPmstat{    ///<Power Mode Status register
        using Addr = Register::Address<0x4007e003,0xffffff00,0x00000000,unsigned char>;
        ///Power Mode Status
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pmstat{};
    }
}


text:
<?xml version="1.0"?>

<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
    <widget id="new_products" class="Magento\Catalog\Block\Product\Widget\NewWidget" module="Magento_Catalog" is_email_compatible="true"
            placeholder_image="Magento_Catalog::images/product_widget_new.png" translate="label description">
        Catalog New Products List
        <description>List of Products that are set as New</description>
        <parameter name="display_type" type="select" required="true" visible="true" translate="label description">
            Display Type
            <description>All products - recently added products, New products - products marked as new</description>
            <option name="default" value="all_products" selected="true" translate="label">
                All products
            </option>
            <option name="item" value="new_products" translate="label">
                New products
            </option>
        </parameter>
        <parameter name="show_pager" type="select" visible="true" source_model="Magento\Config\Model\Config\Source\Yesno"
                   translate="label" >
            Display Page Control
        </parameter>
        <parameter name="products_per_page" type="text" required="true" visible="true" translate="label">
            Number of Products per Page
            <value>5</value>
            <depends>
                <parameter name="show_pager" value="1"/>
            </depends>
        </parameter>
        <parameter name="products_count" type="text" required="true" visible="true" translate="label">
            Number of Products to Display
            <value>10</value>
        </parameter>
        <parameter name="template" type="select" required="true" visible="true" translate="label">
            Template
            <option name="default" value="product/widget/new/content/new_grid.phtml" selected="true" translate="label">
                New Products Grid Template
            </option>
            <option name="list" value="product/widget/new/content/new_list.phtml" translate="label">
                New Products List Template
            </option>
            <option name="list_default" value="product/widget/new/column/new_default_list.phtml" translate="label">
                New Products Images and Names Template
            </option>
            <option name="list_names" value="product/widget/new/column/new_names_list.phtml" translate="label">
                New Products Names Only Template
            </option>
            <option name="list_images" value="product/widget/new/column/new_images_list.phtml" translate="label">
                New Products Images Only Template
            </option>
        </parameter>
        <parameter name="cache_lifetime" type="text" visible="true" translate="label description">
            Cache Lifetime (Seconds)
            <description>86400 by default, if not set. To refresh instantly, clear the Blocks HTML Output cache.</description>
        </parameter>

        <container name="left">
            <template name="default" value="list_default"/>
            <template name="names_only" value="list_names"/>
            <template name="images_only" value="list_images"/>
        </container>
        <container name="content">
            <template name="grid" value="default"/>
            <template name="list" value="list"/>
        </container>
        <container name="right">
            <template name="default" value="list_default"/>
            <template name="names_only" value="list_names"/>
            <template name="images_only" value="list_images"/>
        </container>
    </widget>

    <widget id="catalog_product_link" class="Magento\Catalog\Block\Product\Widget\Link" module="Magento_Catalog" is_email_compatible="true"
            placeholder_image="Magento_Catalog::images/product_widget_link.png" translate="label description">
        Catalog Product Link
        <description>Link to a Specified Product</description>
        <parameter name="id_path" type="block" visible="true" required="true" sort_order="10" translate="label">
            Product
            <block class="Magento\Backend\Block\Catalog\Product\Widget\Chooser">
                <data>
                    <item name="button" type="array">
                        <item name="open" type="string">Select Product...</item>
                    </item>
                </data>
            </block>
        </parameter>
        <parameter name="anchor_text" type="text" visible="true" translate="label description">
            Anchor Custom Text
            <description>If empty, we'll use the product name here.</description>
        </parameter>
        <parameter name="title" type="text" visible="true" translate="label">
            Anchor Custom Title
        </parameter>
        <parameter name="template" type="select" visible="true" translate="label" >
            Template
            <option name="default" value="product/widget/link/link_block.phtml" selected="true" translate="label">
                Product Link Block Template
            </option>
            <option name="link_inline" value="product/widget/link/link_inline.phtml" translate="label">
                Product Link Inline Template
            </option>
        </parameter>
    </widget>

    <widget id="catalog_category_link" class="Magento\Catalog\Block\Category\Widget\Link" module="Magento_Catalog" is_email_compatible="true"
            placeholder_image="Magento_Catalog::images/category_widget_link.png" translate="label description">
        Catalog Category Link
        <description>Link to a Specified Category</description>
        <parameter name="id_path" type="block" visible="true" required="true" sort_order="10" translate="label">
            Category
            <block class="Magento\Backend\Block\Catalog\Category\Widget\Chooser">
                <data>
                    <item name="button" type="array">
                        <item name="open" type="string">Select Category...</item>
                    </item>
                </data>
            </block>
        </parameter>
        <parameter name="anchor_text" type="text" visible="true" translate="label description">
            Anchor Custom Text
            <description>If empty, we'll use the category name here.</description>
        </parameter>
        <parameter name="title" type="text" visible="true" translate="label">
            Anchor Custom Title
        </parameter>
        <parameter name="template" type="select" visible="true" translate="label">
            Template
            <option name="default" value="category/widget/link/link_block.phtml" selected="true" translate="label">
                Category Link Block Template
            </option>
            <option name="link_inline" value="category/widget/link/link_inline.phtml" translate="label">
                Category Link Inline Template
            </option>
        </parameter>
    </widget>
</widgets>


text:
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';

import SparklineChart from '../SparklineChart';
import { sparklineChartPrivateDriverFactory } from './SparklineChart.private.uni.driver';

const data = [
  { label: new Date('Thu Sep 4 2020'), value: 3 },
  { label: new Date('Thu Sep 5 2020'), value: 17 },
  { label: new Date('Thu Sep 6 2020'), value: 18 },
];

describe(SparklineChart.displayName, () => {
  const render = createRendererWithUniDriver(
    sparklineChartPrivateDriverFactory,
  );

  afterEach(cleanup);

  it('should render', async () => {
    const { driver } = render(<SparklineChart data={data} />);

    expect(await driver.exists()).toBe(true);
  });
});


text:
package org.deeplearning4j.nn.conf.layers;

/**
 * Pooling type:

 * MAX: Max pooling - output is the maximum value of the input values

 * AVG: Average pooling - output is the average value of the input values

 * SUM: Sum pooling - output is the sum of the input values

 * PNORM: P-norm pooling

 */
public enum PoolingType {
    MAX, AVG, SUM, PNORM
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />

    <title>krTheme Sphinx Style — monty 2022.9.9 documentation</title>
    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/flasky.css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

  <link media="only screen and (max-device-width: 480px)" href="../_static/small_flask.css" type= "text/css" rel="stylesheet" />
  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Navigation

          index

          modules |

monty 2022.9.9 documentation »

krTheme Sphinx Style

krTheme Sphinx Style¶

This repository contains sphinx styles Kenneth Reitz uses in most of
his projects. It is a drivative of Mitsuhiko's themes for Flask and Flask related
projects.  To use this style in your Sphinx documentation, follow
this guide:

put this folder as _themes into your docs folder.  Alternatively
you can also use git submodules to check out the contents there.

add this to your conf.py:

sys.path.append(os.path.abspath('_themes'))
html_theme_path = ['_themes']
html_theme = 'kr'

The following themes exist:

kr

the standard flask documentation theme for large projects

kr_small

small one-page theme.  Intended to be used by very small addon libraries.

Related Topics

Documentation overview

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

      © Copyright 2014, Shyue Ping Ong.


text:
require_relative 'geometry/unit'
require_relative 'geometry/centimeter'
require_relative 'geometry/metre'
require_relative 'geometry/length'
require_relative 'geometry/rectangle'


text:
set -e

# read user.cfg if it exists and is readable

_CFG_FILE=$(dirname "$0")"/user.cfg"
if [ -f "$_CFG_FILE" ]
then
    [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable"
    . "$_CFG_FILE"
fi

# paths

if [ -z "${ANDROID_SDK_ROOT+aaa}" ]; then
# ... if ANDROID_SDK_ROOT is not set, use "$HOME/bin/android-sdk"
    ANDROID_SDK_ROOT="$HOME/bin/android-sdk"
fi

if [ -z "${ANDROID_NDK_ROOT+aaa}" ]; then
# ... if ANDROID_NDK_ROOT is not set, use "$HOME/bin/android-ndk"
    ANDROID_NDK_ROOT="$HOME/bin/android-ndk"
fi

# find current dir
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# find working dir
WORKINGDIR="$(pwd)"

# paths with defaults hardcoded to relative paths

if [ -z "${COCOS2DX_ROOT+aaa}" ]; then
    COCOS2DX_ROOT="$WORKINGDIR"
fi

if [ ! -f "$COCOS2DX_ROOT/tools/android-buildsetup.sh" ]
then
    echo "Run..."
    echo "> ./tools/android-buildsetup.sh"
    echo "... from the top level of the cocos2d-x source tree"
    echo "OR"
    echo "Run..."
    echo "> COCOS2DX_ROOT=<path/to/cocos2d-x> <path/to/cocos2d-x>/build/setupandroid.sh"
    exit -1
fi

echo "Paths :"
echo "    ANDROID_SDK_ROOT: $ANDROID_SDK_ROOT"
echo "    ANDROID_NDK_ROOT: $ANDROID_NDK_ROOT"
echo "    COCOS2DX_ROOT   : $COCOS2DX_ROOT"
echo "    WORKINGDIR      : $WORKINGDIR"
echo "    SCRIPTDIR       : $SCRIPTDIR"

_CONTENTS=""
_CONTENTS+="sdk.dir=$ANDROID_SDK_ROOT"'\n'
_CONTENTS+="NDK_ROOT=$ANDROID_NDK_ROOT"'\n'
echo
echo "--- local.properties"
echo "---"
echo -e "$_CONTENTS"
echo "---"

_ANDROIDMANIFESTS=(`find "$COCOS2DX_ROOT/cocos2dx" -type f -name "AndroidManifest.xml"`)
_ANDROIDMANIFESTS+=(`find "$COCOS2DX_ROOT/samples" -type f -name "AndroidManifest.xml"`)

for a in "${_ANDROIDMANIFESTS[@]}"; do
    _LOCAL_PROPERTIES_FILE=${a/AndroidManifest\.xml/local\.properties}

# write local.properties if it doesn't already exist
    if [ -f "$_LOCAL_PROPERTIES_FILE" ]
    then
        echo "$_LOCAL_PROPERTIES_FILE exists. skipping overwrite"
    else
        echo "writing $_LOCAL_PROPERTIES_FILE"
        echo -e "$_CONTENTS" > "$_LOCAL_PROPERTIES_FILE"
    fi
done


text:
package org.web3j.abi.datatypes.generated;

import java.math.BigInteger;

import org.web3j.abi.datatypes.Ufixed;

/**
 *
Auto generated code.

 * Do not modifiy!

 * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.

 */
public class Ufixed32x112 extends Ufixed {
    public static final Ufixed32x112 DEFAULT = new Ufixed32x112(BigInteger.ZERO);

    public Ufixed32x112(BigInteger value) {
        super(32, 112, value);
    }

    public Ufixed32x112(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
        super(32, 112, m, n);
    }
}


text:
<!-- toc -->
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
  - [Non-Goals](#non-goals)
- [Proposal](#proposal)
  - [User Stories](#user-stories)
    - [Multiple containers with different scaling thresholds](#multiple-containers-with-different-scaling-thresholds)
    - [Multiple containers but only scaling for one.](#multiple-containers-but-only-scaling-for-one)
    - [Add container metrics to existing pod resource metric.](#add-container-metrics-to-existing-pod-resource-metric)
  - [Risks and Mitigations](#risks-and-mitigations)
- [Design Details](#design-details)
  - [Test Plan](#test-plan)
  - [Graduation Criteria](#graduation-criteria)
  - [Upgrade/Downgrade Strategy](#upgradedowngrade-strategy)
- [Implementation History](#implementation-history)
<!-- /toc -->

## Summary

The Horizontal Pod Autoscaler supports scaling of targets based on the resource usage
of the pods in the target. The resource usage of pods is calculated as the sum
of the individual container usage values of the pod. This is unsuitable for workloads where
the usage of the containers are not strongly correlated or do not change in lockstep. This KEP
suggests that when scaling based on resource usage the HPA also provide an option
to consider the usages of individual containers to make scaling decisions.

## Motivation

An HPA is used to ensure that a scaling target is scaled up or down in such a way that the
specificed current metric values are always maintained at a certain level. Resource based
autoscaling is the most basic approach to autoscaling and has been present in the HPA spec since `v1`.
In this mode the HPA controller fetches the current resource metrics for all the pods of a scaling
target and then computes how many pods should be added or removed based on the current usage to
achieve the target average usage.

For performance critical applications where the resource usage of individual containers needs to
be configured individually the default behavior of the HPA controller may be unsuitable. When
there are multiple containers in the pod their individual resource usages may not have a direct
correlation or may grow at different rates as the load changes. There are several reasons for this:

  - A sidecar container is only providing an auxiliary service such as log shipping. If the
    application does not log very frequently or does not produce logs in its hotpath then the usage of
    the log shipper will not grow.
  - A sidecar container which provides authentication. Due to heavy caching the usage will only
    increase slightly when the load on the main container increases. In the current blended usage
    calculation approach this usually results in the the HPA not scaling up the deployment because
    the blended usage is still low.
  - A sidecar may be injected without resources set which prevents scaling based on utilization. In
    the current logic the HPA controller can only scale on absolute resource usage of the pod when
    the resource requests are not set.

The optimum usage of the containers may also be at different levels. Hence the HPA should offer
a way to specify the target usage in a more fine grained manner.

### Goals

- Make HPA scale based on individual container resources usage

### Non-Goals
- Configurable aggregation for containers resources in pods.
- Optimization of the calls to the `metrics-server`

## Proposal

Currently the HPA accepts multiple metric sources to calculate the number of replicas in the target,
one of which is called `Resource`. The `Resource` type represents the resource usage of the
pods in the scaling target. The resource metric source has the following structure:

```go
type ResourceMetricSource struct {
	Name v1.ResourceName
	Target MetricTarget
}
```

Here the `Name` is the name of the resource. Currently only `cpu` and `memory` are supported
for this field. The other field is used to specify the target at which the HPA should maintain
the resource usage by adding or removing pods. For instance if the target is _60%_ CPU utilization,
and the current average of the CPU resources across all the pods of the target is _70%_ then
the HPA will add pods to reduce the CPU utilization. If it's less than _60%_ then the HPA will
remove pods to increase utilization.

It should be noted here that when a pod has multiple containers the HPA gets the resource
usage of all the containers and sums them to get the total usage. This is then divided
by the total requested resources to get the average utilizations. For instance if there is
a pods with 2 containers: `application` and `log-shipper` requesting `250m` and `250m` of
CPU resources then the total requested resources of the pod as calculated by the HPA is `500m`.
If then the first container is currently using `200m` and the second only `50m` then
the usage of the pod is `250m` which in utilization is _50%_. Although individually
the utilization of the containers are _80%_ and _20%_. In such a situation the performance
of the `application` container might be affected significantly. There is no way to specify
in the HPA to keep the utilization of the first container below a certain threshold. This also
affects `memory` resource based autocaling scaling.

We propose that the a new metric source called `ContainerResourceMetricSource` be introduced
with the following structure:

```go
type ContainerResourceMetricSource struct {
	Container string
	Name v1.ResourceName
	Target MetricTarget
}
```

The only new field is `Container` which is the name of the container for which the resource
usage should be tracked.

### User Stories

#### Multiple containers with different scaling thresholds

Assume the user has a deployment with multiple pods, each of which have multiple containers. A main
container called `application` and 2 others called `log-shipping` and `authnz-proxy`. Two
of the containers are critical to provide the application functionality, `application` and
`authnz-proxy`. The user would like to prevent _OOMKill_ of these containers and also keep
their CPU utilization low to ensure the highest performance. The other container
`log-shipping` is less critical and can tolerate failures and restarts. In this case the
user would create an HPA with the following configuration:

```yaml
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: mission-critical
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: mission-critical
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: ContainerResource
    resource:
      name: cpu
      container: application
      target:
        type: Utilization
        averageUtilization: 30
  - type: ContainerResource
    resource:
      name: memory
      container: application
      target:
        type: Utilization
        averageUtilization: 80
  - type: ContainerResource
    resource:
      name: cpu
      container: authnz-proxy
      target:
        type: Utilization
        averageUtilization: 30
  - type: ContainerResource
    resource:
      name: memory
      container: authnz-proxy
      target:
        type: Utilization
        averageUtilization: 80
  - type: ContainerResource
    resource:
      name: cpu
      container: log-shipping
      target:
        type: Utilization
        averageUtilization: 80
```

The HPA specifies that the HPA controller should maintain the CPU utilization of the containers
`application` and `authnz-proxy` at _30%_ and the memory utilization at _80%_. The `log-shipping`
container is scaled to keep the cpu utilization at _80%_ and is not scaled on memory.

#### Multiple containers but only scaling for one.
Assume the user has a deployment where the pod spec has multiple containers but scaling should
be performed based only on the utilization of one of the containers. There could be several reasons
for such a strategy: Disruptions due to scaling of sidecars may be expensive and should be avoided
or the resource usage of the sidecars could be erratic because it has a different work characteristics
to the main container.

In such a case the user creates an HPA as follows:

```yaml
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: mission-critical
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: mission-critical
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: ContainerResource
    resource:
      name: cpu
      container: application
      target:
        type: Utilization
        averageUtilization: 30
```

The HPA controller will then completely ignore the resource usage in other containers.

#### Add container metrics to existing pod resource metric.
A user who is already using an HPA to scale their application can add the container metric source to the HPA
in addition to the existing pod metric source. If there is a single container in the pod then the behavior
will be exactly the same as before. If there are multiple containers in the application pods then the deployment
might scale out more than before. This happens when the resource usage of the specified container is more
than the blended usage as calculated by the pod metric source. If however in the unlikely case, the usage of
all the containers in the pod change in tandem by the same amount then the behavior will remain as before.

For example consider the HPA object which targets a _Deployment_ with pods that have two containers `application`
and `log-shipper`:

```yaml

apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: mission-critical
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: mission-critical
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: ContainerResource
    resource:
      name: cpu
      container: application
      target:
        type: Utilization
        averageUtilization: 50
  - type: PodResource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
```

If the resource usage of the `application` container increases then the target would be scaled out even if
the usage of the `log-shipper` container does not increase much. If the resource usage of `log-shipper` container
increases then the deployment would only be scaled out if the combined resource usage of both containers increases
above the target.

### Risks and Mitigations

Since the new field `container` in the container resource metric source is not validated against the target it is
possible that the user could specify an invalid value, i.e. a container name which is not part of the pod. The HPA
controller would treat this as invalid configuration and prevent scale down. However scale up would still be possible
based on recommendations from other metric sources.

A similar problem is possible when renaming container names in the HPA. To mitigate this the recommended procedure
is to have both the old and new container names during the deployment. The old container name can be removed from
the HPA when the migration is complete.

## Design Details

### Test Plan
Most of the tests will follow the same pattern as the tests for the pod resource metric source. The following
unit tests will be added:

- **Replica Calculator:** Verify that the number of replicas calculated is based on the metrics of individual
  containers when a container metric source is specified.
- **REST Metrics Client:** Verify that the resources returned from the REST metric client is the metrics for only
  the containers specified in the metric source.
- **API server validation:** Verify that only valid container metric sources are accepted.
- **kubectl:** Verify that the new metric sources are displayed correctly.

### Graduation Criteria

Since the feature is being added to the HPA version `v2beta2` there is no further graduation
criteria required because it will graduate when the original API graduates to `stable`

### Upgrade/Downgrade Strategy

For cluster upgrades the HPAs from the previous version will continue working as before. There
is no change in behavior or flags which have to be enabled or disabled.

A new feature gate `HPAContainerMetrics` is added in version 1.20 which is turned off by default.
The new feature can only be used when this feature gate is enabled.

## Implementation History
* 2020-04-03 Initial KEP merged
* 2020-10-23 Implementation merged


text:
package pivotal.au.se.gemfirexdweb.dao.members;

import java.util.List;

import pivotal.au.se.gemfirexdweb.main.SqlFireException;

public interface MemberDAO
{
	public List<Member> retrieveMembers (String userKey) throws SqlFireException;

    public String getMemberProperties (String memberId, String type, String userKey) throws SqlFireException;

	public javax.servlet.jsp.jstl.sql.Result getMemberInfo (String memberId, String userKey) throws SqlFireException;
}


text:
package org.vocobox.events;

import java.util.Arrays;
import java.util.Collection;

import org.jzy3d.maths.Statistics;

public class SoundEventStatistics {
    public static float[] LEVELS = { 0.00f, 0.25f, 0, 50f, 0.75f, 1.00f };

    public float[] values;
    public float[] levels;
    public float[] quantiles;
    public float min;
    public float q25;
    public float q50;
    public float q75;
    public float max;

    public SoundEventStatistics(Collection<SoundEvent> events) {
        compute(events);
    }

    public void compute(Collection<SoundEvent> events) {
        values = SoundEvent.toArray(events);
        levels = LEVELS;
        quantiles = quantile(values, levels);
        min = Statistics.min(values);// quantiles[0];
        q25 = quantiles[1];
        q50 = quantiles[2];
        q75 = quantiles[3];
        max = Statistics.max(values);// quantiles[4];
    }

    public static float[] quantile(float[] values, float[] levels, boolean interpolated) {
        if (values.length == 0)
            return new float[0];

        float[] quantiles = new float[levels.length];
        float[] sorted = new float[values.length];
        System.arraycopy(values, 0, sorted, 0, values.length);
        Arrays.sort(sorted);

        float quantileIdx;
        float quantileIdxCeil;
        float quantileIdxFloor;

        for (int i = 0; i < levels.length; i++) {
            if (levels[i] > 100 || levels[i] < 0)
                throw new IllegalArgumentException("input level " + levels[i] + " is out of bounds [0;100].");

            quantileIdx = (sorted.length - 1) * levels[i] / 100;

            if (quantileIdx == (int) quantileIdx) // exactly find the quantile
                quantiles[i] = sorted[(int) quantileIdx];
            else {
                quantileIdxCeil = (float) Math.ceil(quantileIdx);
                quantileIdxFloor = (float) Math.floor(quantileIdx);

                if (interpolated) { // generate an interpolated quantile
                    quantiles[i] = sorted[(int) quantileIdxFloor] * (quantileIdxCeil - quantileIdx) + sorted[(int) quantileIdxCeil] * (quantileIdx - quantileIdxFloor);
                } else { // return the quantile corresponding to the closest
                         // value
                    if (quantileIdx - quantileIdxFloor < quantileIdxCeil - quantileIdx)
                        quantiles[i] = sorted[(int) quantileIdxFloor];
                    else
                        quantiles[i] = sorted[(int) quantileIdxCeil];
                }
            }
        }
        return quantiles;
    }

    public static float[] quantile(float[] values, float[] levels) {
        return quantile(values, levels, true);
    }

}


text:
package dotty.runtime

/**
 * Classes used as holders for local lazy vals
 */
class LazyInt {
  var value: Int = _
  @volatile var initialized: Boolean = false
}

class LazyLong {
  var value: Long = _
  @volatile var initialized: Boolean = false
}

class LazyBoolean {
  var value: Boolean = _
  @volatile var initialized: Boolean = false
}

class LazyDouble {
  var value: Double = _
  @volatile var initialized: Boolean = false
}

class LazyByte {
  var value: Byte = _
  @volatile var initialized: Boolean = false
}

class LazyRef {
  var value: AnyRef = _
  @volatile var initialized: Boolean = false
}

class LazyShort {
  var value: Short = _
  @volatile var initialized: Boolean = false
}

class LazyChar {
  var value: Char = _
  @volatile var initialized: Boolean = false
}


text:
#pragma once
#include <aws/servicecatalog/ServiceCatalog_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/servicecatalog/model/FailedServiceActionAssociation.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ServiceCatalog
{
namespace Model
{
  class AWS_SERVICECATALOG_API BatchAssociateServiceActionWithProvisioningArtifactResult
  {
  public:
    BatchAssociateServiceActionWithProvisioningArtifactResult();
    BatchAssociateServiceActionWithProvisioningArtifactResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    BatchAssociateServiceActionWithProvisioningArtifactResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline const Aws::Vector<FailedServiceActionAssociation>& GetFailedServiceActionAssociations() const{ return m_failedServiceActionAssociations; }

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline void SetFailedServiceActionAssociations(const Aws::Vector<FailedServiceActionAssociation>& value) { m_failedServiceActionAssociations = value; }

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline void SetFailedServiceActionAssociations(Aws::Vector<FailedServiceActionAssociation>&& value) { m_failedServiceActionAssociations = std::move(value); }

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline BatchAssociateServiceActionWithProvisioningArtifactResult& WithFailedServiceActionAssociations(const Aws::Vector<FailedServiceActionAssociation>& value) { SetFailedServiceActionAssociations(value); return *this;}

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline BatchAssociateServiceActionWithProvisioningArtifactResult& WithFailedServiceActionAssociations(Aws::Vector<FailedServiceActionAssociation>&& value) { SetFailedServiceActionAssociations(std::move(value)); return *this;}

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline BatchAssociateServiceActionWithProvisioningArtifactResult& AddFailedServiceActionAssociations(const FailedServiceActionAssociation& value) { m_failedServiceActionAssociations.push_back(value); return *this; }

    /**
     *
An object that contains a list of errors, along with information to help you
     * identify the self-service action.

     */
    inline BatchAssociateServiceActionWithProvisioningArtifactResult& AddFailedServiceActionAssociations(FailedServiceActionAssociation&& value) { m_failedServiceActionAssociations.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<FailedServiceActionAssociation> m_failedServiceActionAssociations;
  };

} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws


text:
class CreateChildResources < ActiveRecord::Migration
  def change
    create_table :child_resources do |t|
      t.integer :parent_resource_id

      t.boolean :r_boolean
      t.date :r_date
      t.datetime :r_datetime
      t.decimal :r_decimal
      t.float :r_float
      t.integer :r_integer
      t.string :r_string
      t.text :r_text
      t.time :r_time

      t.timestamps
    end
  end
end


text:
package com.cin.linyuehlii.nobile;

import java.io.Serializable;

/**
 * Created by 大芳鎖定你 on 2016/7/20.
 */
public class BMission implements Serializable {
    String MissionAppName;
    long MissionAppTime;

    public BMission(String MissionAppName, long MissionAppTime) {
        this.MissionAppName = MissionAppName;
        this.MissionAppTime = MissionAppTime;
    }

    public String getMissionAppName() {
        return MissionAppName;
    }

    public void setMissionAppName(String missionAppName) {
        MissionAppName = missionAppName;
    }

    public long getMissionAppTime() {
        return MissionAppTime;
    }

    public void setMissionAppTime(long missionAppTime) {
        MissionAppTime = missionAppTime;
    }

    public String getMissionAppTimeFormatted() {
        String Minute = String.valueOf(MissionAppTime % 60000);
        String Hour = String.valueOf(MissionAppTime / 3600000);
        return Hour +" hr " + Minute + " min ";
    }
}


text:
using log4net;
using Umbraco.Core;
using Umbraco.Core.Persistence;

namespace uFluent.Migrate.Persistence
{
    public static class TableFactory
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (TableFactory));

        public static void CreateTables()
        {
            var databaseContext = ApplicationContext.Current.DatabaseContext;

            if (!databaseContext.IsDatabaseConfigured)
            {
                Log.Debug("Database is not configured, skipping uFluent.Migrate table creation");
                return;
            }

            var database = databaseContext.Database;

            try
            {
                database.OpenSharedConnection();

                if (database.TableExist("MigrationHistory"))
                {
                    Log.Debug("MigrationHistory table already exists.");
                    return;
                }

                using (var transaction = database.GetTransaction())
                {
                    database.CreateTable<MigrationHistory>();
                    transaction.Complete();
                    Log.Info("Created MigrationHistory table.");
                }
            }
            finally
            {
                database.CloseSharedConnection();
            }
        }
    }
}


text:
package org.jabref.logic.integrity;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;

import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.strings.StringUtil;

public class HowPublishedChecker implements ValueChecker {

    private static final Predicate<String> FIRST_LETTER_CAPITALIZED = Pattern.compile("^[^a-z]").asPredicate();

    private final BibDatabaseContext databaseContext;

    public HowPublishedChecker(BibDatabaseContext databaseContext) {
        this.databaseContext = Objects.requireNonNull(databaseContext);
    }

    /**
     * Official BibTeX specification:
     *  HowPublished: How something strange has been published. The first word should be capitalized.
     * biblatex package documentation (Section 4.9.1):
     *  The biblatex package will automatically capitalize the first word when required at the beginning of a sentence.
     */
    @Override
    public Optional<String> checkValue(String value) {
        if (StringUtil.isBlank(value)) {
            return Optional.empty();
        }

        //BibTeX
        if (!databaseContext.isBiblatexMode() && !FIRST_LETTER_CAPITALIZED.test(value.trim())) {
            return Optional.of(Localization.lang("should have the first letter capitalized"));
        }

        return Optional.empty();
    }
}


text:
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file rsa_decrypt_key.c
  RSA PKCS #1 Decryption, Tom St Denis and Andreas Lange
*/

#ifdef LTC_MRSA

/**
   PKCS #1 decrypt then v1.5 or OAEP depad
   @param in          The ciphertext
   @param inlen       The length of the ciphertext (octets)
   @param out         [out] The plaintext
   @param outlen      [in/out] The max size and resulting size of the plaintext (octets)
   @param lparam      The system "lparam" value
   @param lparamlen   The length of the lparam value (octets)
   @param hash_idx    The index of the hash desired
   @param padding     Type of padding (LTC_PKCS_1_OAEP or LTC_PKCS_1_V1_5)
   @param stat        [out] Result of the decryption, 1==valid, 0==invalid
   @param key         The corresponding private RSA key
   @return CRYPT_OK if succcessul (even if invalid)
*/
int rsa_decrypt_key_ex(const unsigned char *in,       unsigned long  inlen,
                             unsigned char *out,      unsigned long *outlen,
                       const unsigned char *lparam,   unsigned long  lparamlen,
                             int            hash_idx, int            padding,
                             int           *stat,     rsa_key       *key)
{
  unsigned long modulus_bitlen, modulus_bytelen, x;
  int           err;
  unsigned char *tmp;

  LTC_ARGCHK(out    != NULL);
  LTC_ARGCHK(outlen != NULL);
  LTC_ARGCHK(key    != NULL);
  LTC_ARGCHK(stat   != NULL);

  /* default to invalid */
  *stat = 0;

  /* valid padding? */

  if ((padding != LTC_PKCS_1_V1_5) &&
      (padding != LTC_PKCS_1_OAEP)) {
    return CRYPT_PK_INVALID_PADDING;
  }

  if (padding == LTC_PKCS_1_OAEP) {
    /* valid hash ? */
    if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
       return err;
    }
  }

  /* get modulus len in bits */
  modulus_bitlen = mp_count_bits( (key->N));

  /* outlen must be at least the size of the modulus */
  modulus_bytelen = mp_unsigned_bin_size( (key->N));
  if (modulus_bytelen != inlen) {
     return CRYPT_INVALID_PACKET;
  }

  /* allocate ram */
  tmp = XMALLOC(inlen);
  if (tmp == NULL) {
     return CRYPT_MEM;
  }

  /* rsa decode the packet */
  x = inlen;
  if ((err = ltc_mp.rsa_me(in, inlen, tmp, &x, PK_PRIVATE, key)) != CRYPT_OK) {
     XFREE(tmp);
     return err;
  }

  if (padding == LTC_PKCS_1_OAEP) {
    /* now OAEP decode the packet */
    err = pkcs_1_oaep_decode(tmp, x, lparam, lparamlen, modulus_bitlen, hash_idx,
                             out, outlen, stat);
  } else {
    /* now PKCS #1 v1.5 depad the packet */
    err = pkcs_1_v1_5_decode(tmp, x, LTC_PKCS_1_EME, modulus_bitlen, out, outlen, stat);
  }

  XFREE(tmp);
  return err;
}

#endif /* LTC_MRSA */

/* $Source: /cvs/libtom/libtomcrypt/src/pk/rsa/rsa_decrypt_key.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:32:35 $ */


text:
package org.apache.accumulo.server.tabletserver.log;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.master.thrift.RecoveryStatus;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.SimpleThreadPool;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.logger.LogFileKey;
import org.apache.accumulo.server.logger.LogFileValue;
import org.apache.accumulo.server.zookeeper.DistributedWorkQueue;
import org.apache.accumulo.server.zookeeper.DistributedWorkQueue.Processor;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;

/**
 *
 */
public class LogSorter {

  private static final Logger log = Logger.getLogger(LogSorter.class);
  FileSystem fs;
  AccumuloConfiguration conf;

  private final Map<String,LogProcessor> currentWork = Collections.synchronizedMap(new HashMap<String,LogProcessor>());

  class LogProcessor implements Processor {

    private FSDataInputStream input;
    private DataInputStream decryptingInput;
    private long bytesCopied = -1;
    private long sortStart = 0;
    private long sortStop = -1;

    @Override
    public Processor newProcessor() {
      return new LogProcessor();
    }

    @Override
    public void process(String child, byte[] data) {
      String dest = Constants.getRecoveryDir(conf) + "/" + child;
      String src = new String(data);
      String name = new Path(src).getName();

      synchronized (currentWork) {
        if (currentWork.containsKey(name))
          return;
        currentWork.put(name, this);
      }

      try {
        log.info("Copying " + src + " to " + dest);
        sort(name, new Path(src), dest);
      } finally {
        currentWork.remove(name);
      }

    }

    public void sort(String name, Path srcPath, String destPath) {

      synchronized (this) {
        sortStart = System.currentTimeMillis();
      }

      String formerThreadName = Thread.currentThread().getName();
      int part = 0;
      try {

        // the following call does not throw an exception if the file/dir does not exist
        fs.delete(new Path(destPath), true);

        FSDataInputStream tmpInput = fs.open(srcPath);
        DataInputStream tmpDecryptingInput = tmpInput;

        Map<String,String> cryptoOpts = new HashMap<String,String>();
        tmpInput = DfsLogger.readHeader(fs, srcPath, cryptoOpts);

        if (!cryptoOpts.containsKey(Property.CRYPTO_MODULE_CLASS.getKey())) {

          log.debug("Log file " + name + " not encrypted");

          synchronized (this) {
            this.input = tmpInput;
            this.decryptingInput = tmpInput;
          }

        } else {

          String cryptoModuleName = cryptoOpts.get(Property.CRYPTO_MODULE_CLASS.getKey());
          if (cryptoModuleName == null) {
            // If for whatever reason we didn't get a configured crypto module (old log file version, for instance)
            // default to using the default configuration entry (usually NullCipher).
            cryptoModuleName = AccumuloConfiguration.getDefaultConfiguration().get(Property.CRYPTO_MODULE_CLASS);
          }

          synchronized (this) {
            this.input = tmpInput;
          }

          @SuppressWarnings("deprecation")
          org.apache.accumulo.core.security.crypto.CryptoModule cryptoOps = org.apache.accumulo.core.security.crypto.CryptoModuleFactory
              .getCryptoModule(cryptoModuleName);
          @SuppressWarnings("deprecation")
          InputStream decryptingInputStream = cryptoOps.getDecryptingInputStream(input, cryptoOpts);

          tmpDecryptingInput = new DataInputStream(decryptingInputStream);

          synchronized (this) {
            this.decryptingInput = tmpDecryptingInput;
          }
        }

        final long bufferSize = conf.getMemoryInBytes(Property.TSERV_SORT_BUFFER_SIZE);
        Thread.currentThread().setName("Sorting " + name + " for recovery");
        while (true) {
          final ArrayList<Pair<LogFileKey,LogFileValue>> buffer = new ArrayList<Pair<LogFileKey,LogFileValue>>();
          try {
            long start = input.getPos();
            while (input.getPos() - start < bufferSize) {
              LogFileKey key = new LogFileKey();
              LogFileValue value = new LogFileValue();
              key.readFields(decryptingInput);
              value.readFields(decryptingInput);
              buffer.add(new Pair<LogFileKey,LogFileValue>(key, value));
            }
            writeBuffer(destPath, buffer, part++);
            buffer.clear();
          } catch (EOFException ex) {
            writeBuffer(destPath, buffer, part++);
            break;
          }
        }
        fs.create(new Path(destPath, "finished")).close();
        log.info("Finished log sort " + name + " " + getBytesCopied() + " bytes " + part + " parts in " + getSortTime() + "ms");
      } catch (Throwable t) {
        try {
          // parent dir may not exist
          fs.mkdirs(new Path(destPath));
          fs.create(new Path(destPath, "failed")).close();
        } catch (IOException e) {
          log.error("Error creating failed flag file " + name, e);
        }
        log.error(t, t);
      } finally {
        Thread.currentThread().setName(formerThreadName);
        try {
          close();
        } catch (Exception e) {
          log.error("Error during cleanup sort/copy " + name, e);
        }
        synchronized (this) {
          sortStop = System.currentTimeMillis();
        }
      }
    }

    private void writeBuffer(String destPath, ArrayList<Pair<LogFileKey,LogFileValue>> buffer, int part) throws IOException {
      String path = destPath + String.format("/part-r-%05d", part++);
      MapFile.Writer output = new MapFile.Writer(fs.getConf(), fs, path, LogFileKey.class, LogFileValue.class);
      try {
        Collections.sort(buffer, new Comparator<Pair<LogFileKey,LogFileValue>>() {
          @Override
          public int compare(Pair<LogFileKey,LogFileValue> o1, Pair<LogFileKey,LogFileValue> o2) {
            return o1.getFirst().compareTo(o2.getFirst());
          }
        });
        for (Pair<LogFileKey,LogFileValue> entry : buffer) {
          output.append(entry.getFirst(), entry.getSecond());
        }
      } finally {
        output.close();
      }
    }

    synchronized void close() throws IOException {
      bytesCopied = input.getPos();
      input.close();
      decryptingInput.close();
      input = null;
    }

    public synchronized long getSortTime() {
      if (sortStart > 0) {
        if (sortStop > 0)
          return sortStop - sortStart;
        return System.currentTimeMillis() - sortStart;
      }
      return 0;
    }

    synchronized long getBytesCopied() throws IOException {
      return input == null ? bytesCopied : input.getPos();
    }
  }

  ThreadPoolExecutor threadPool;
  private final Instance instance;

  public LogSorter(Instance instance, FileSystem fs, AccumuloConfiguration conf) {
    this.instance = instance;
    this.fs = fs;
    this.conf = conf;
    int threadPoolSize = conf.getCount(Property.TSERV_RECOVERY_MAX_CONCURRENT);
    this.threadPool = new SimpleThreadPool(threadPoolSize, this.getClass().getName());
  }

  public void startWatchingForRecoveryLogs(ThreadPoolExecutor distWorkQThreadPool) throws KeeperException, InterruptedException {
    this.threadPool = distWorkQThreadPool;
    new DistributedWorkQueue(ZooUtil.getRoot(instance) + Constants.ZRECOVERY).startProcessing(new LogProcessor(), this.threadPool);
  }

  public List<RecoveryStatus> getLogSorts() {
    List<RecoveryStatus> result = new ArrayList<RecoveryStatus>();
    synchronized (currentWork) {
      for (Entry<String,LogProcessor> entries : currentWork.entrySet()) {
        RecoveryStatus status = new RecoveryStatus();
        status.name = entries.getKey();
        try {
          status.progress = entries.getValue().getBytesCopied() / (0.0 + conf.getMemoryInBytes(Property.TSERV_WALOG_MAX_SIZE));
        } catch (IOException ex) {
          log.warn("Error getting bytes read");
        }
        status.runtime = (int) entries.getValue().getSortTime();
        result.add(status);
      }
      return result;
    }
  }
}


text:
print(__doc__)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn import svm

xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500))

# Generate train data
X = 0.3 * np.random.randn(100, 2)
X_train = np.r_[X+2, X-2]

# Generate some regular novel observations
X = 0.3 * np.random.randn(20, 2)
X_test = np.r_[X+2, X-2]

# Generate some abnormal observations
X_outliers = np.random.uniform(low=-4, high=4, size=(20,2))

# fit the model
clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

n_error_train = y_pred_train[y_pred_train == -1].size
n_error_test = y_pred_test[y_pred_test == -1].size
n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size

# plot the line, the points, and the nearest vectors to the plane
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]
Z = Z.reshape(xx.shape)

plt.title("Novelty Detection")
plt.contourf(xx, yy, z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu)


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.twilio;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class TwilioEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    private static final Map<String, Object> ALL_OPTIONS;
    static {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("apiName", org.apache.camel.component.twilio.internal.TwilioApiName.class);
        map.put("methodName", java.lang.String.class);
        map.put("inBody", java.lang.String.class);
        map.put("bridgeErrorHandler", boolean.class);
        map.put("sendEmptyMessageWhenIdle", boolean.class);
        map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class);
        map.put("exchangePattern", org.apache.camel.ExchangePattern.class);
        map.put("pollStrategy", org.apache.camel.spi.PollingConsumerPollStrategy.class);
        map.put("lazyStartProducer", boolean.class);
        map.put("basicPropertyBinding", boolean.class);
        map.put("synchronous", boolean.class);
        map.put("backoffErrorThreshold", int.class);
        map.put("backoffIdleThreshold", int.class);
        map.put("backoffMultiplier", int.class);
        map.put("delay", long.class);
        map.put("greedy", boolean.class);
        map.put("initialDelay", long.class);
        map.put("repeatCount", long.class);
        map.put("runLoggingLevel", org.apache.camel.LoggingLevel.class);
        map.put("scheduledExecutorService", java.util.concurrent.ScheduledExecutorService.class);
        map.put("scheduler", java.lang.Object.class);
        map.put("schedulerProperties", java.util.Map.class);
        map.put("startScheduler", boolean.class);
        map.put("timeUnit", java.util.concurrent.TimeUnit.class);
        map.put("useFixedDelay", boolean.class);
        map.put("applicationSid", java.lang.String.class);
        map.put("areaCode", java.lang.String.class);
        map.put("body", java.lang.String.class);
        map.put("callbackUrl", java.net.URI.class);
        map.put("city", java.lang.String.class);
        map.put("credentialListSid", java.lang.String.class);
        map.put("customerName", java.lang.String.class);
        map.put("domainName", java.lang.String.class);
        map.put("endDate", org.joda.time.LocalDate.class);
        map.put("friendlyName", java.lang.String.class);
        map.put("from", com.twilio.type.Endpoint.class);
        map.put("ipAccessControlListSid", java.lang.String.class);
        map.put("ipAddress", java.lang.String.class);
        map.put("isoCountry", java.lang.String.class);
        map.put("mediaUrl", java.util.List.class);
        map.put("messagingServiceSid", java.lang.String.class);
        map.put("password", java.lang.String.class);
        map.put("pathAccountSid", java.lang.String.class);
        map.put("pathAddOnResultSid", java.lang.String.class);
        map.put("pathAddressSid", java.lang.String.class);
        map.put("pathCallSid", java.lang.String.class);
        map.put("pathConferenceSid", java.lang.String.class);
        map.put("pathCountryCode", java.lang.String.class);
        map.put("pathCredentialListSid", java.lang.String.class);
        map.put("pathDomainSid", java.lang.String.class);
        map.put("pathIpAccessControlListSid", java.lang.String.class);
        map.put("pathMessageSid", java.lang.String.class);
        map.put("pathQueueSid", java.lang.String.class);
        map.put("pathRecordingSid", java.lang.String.class);
        map.put("pathReferenceSid", java.lang.String.class);
        map.put("pathSid", java.lang.String.class);
        map.put("phoneNumber", com.twilio.type.PhoneNumber.class);
        map.put("postalCode", java.lang.String.class);
        map.put("qualityScore", java.lang.Integer.class);
        map.put("region", java.lang.String.class);
        map.put("startDate", org.joda.time.LocalDate.class);
        map.put("status", com.twilio.rest.api.v2010.account.call.Recording.Status.class);
        map.put("street", java.lang.String.class);
        map.put("to", com.twilio.type.Endpoint.class);
        map.put("triggerValue", java.lang.String.class);
        map.put("twiml", com.twilio.type.Twiml.class);
        map.put("url", java.net.URI.class);
        map.put("usageCategory", com.twilio.rest.api.v2010.account.usage.Trigger.UsageCategory.class);
        map.put("username", java.lang.String.class);
        ALL_OPTIONS = map;
    }

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        TwilioEndpoint target = (TwilioEndpoint) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "backofferrorthreshold":
        case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
        case "backoffidlethreshold":
        case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
        case "backoffmultiplier":
        case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
        case "basicpropertybinding":
        case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
        case "delay": target.setDelay(property(camelContext, long.class, value)); return true;
        case "exceptionhandler":
        case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
        case "exchangepattern":
        case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
        case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
        case "inbody":
        case "inBody": target.setInBody(property(camelContext, java.lang.String.class, value)); return true;
        case "initialdelay":
        case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
        case "lazystartproducer":
        case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
        case "pollstrategy":
        case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
        case "repeatcount":
        case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
        case "runlogginglevel":
        case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
        case "scheduledexecutorservice":
        case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
        case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true;
        case "schedulerproperties":
        case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
        case "sendemptymessagewhenidle":
        case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
        case "startscheduler":
        case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
        case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
        case "timeunit":
        case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
        case "usefixeddelay":
        case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Map<String, Object> getAllOptions(Object target) {
        return ALL_OPTIONS;
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        TwilioEndpoint target = (TwilioEndpoint) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "backofferrorthreshold":
        case "backoffErrorThreshold": return target.getBackoffErrorThreshold();
        case "backoffidlethreshold":
        case "backoffIdleThreshold": return target.getBackoffIdleThreshold();
        case "backoffmultiplier":
        case "backoffMultiplier": return target.getBackoffMultiplier();
        case "basicpropertybinding":
        case "basicPropertyBinding": return target.isBasicPropertyBinding();
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": return target.isBridgeErrorHandler();
        case "delay": return target.getDelay();
        case "exceptionhandler":
        case "exceptionHandler": return target.getExceptionHandler();
        case "exchangepattern":
        case "exchangePattern": return target.getExchangePattern();
        case "greedy": return target.isGreedy();
        case "inbody":
        case "inBody": return target.getInBody();
        case "initialdelay":
        case "initialDelay": return target.getInitialDelay();
        case "lazystartproducer":
        case "lazyStartProducer": return target.isLazyStartProducer();
        case "pollstrategy":
        case "pollStrategy": return target.getPollStrategy();
        case "repeatcount":
        case "repeatCount": return target.getRepeatCount();
        case "runlogginglevel":
        case "runLoggingLevel": return target.getRunLoggingLevel();
        case "scheduledexecutorservice":
        case "scheduledExecutorService": return target.getScheduledExecutorService();
        case "scheduler": return target.getScheduler();
        case "schedulerproperties":
        case "schedulerProperties": return target.getSchedulerProperties();
        case "sendemptymessagewhenidle":
        case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle();
        case "startscheduler":
        case "startScheduler": return target.isStartScheduler();
        case "synchronous": return target.isSynchronous();
        case "timeunit":
        case "timeUnit": return target.getTimeUnit();
        case "usefixeddelay":
        case "useFixedDelay": return target.isUseFixedDelay();
        default: return null;
        }
    }
}


text:
namespace Chimera {
class IRenderer3d {
  public:
    virtual void begin(class Camera* camera, class ViewProjection* vpo) = 0;
    virtual bool submit(const class RenderCommand& command, class IRenderable3d* renderable) = 0;
    virtual void end() = 0;
    virtual void flush() = 0;
    virtual MapUniform& uboQueue() = 0;
    virtual std::vector<class Texture*>& texQueue() = 0;
    virtual class TransformationStack& getStack() = 0;
    virtual class Camera* getCamera() const = 0;
    virtual class ViewProjection* getEyeView() const = 0;
};
} // namespace Chimera


text:
package ticwear.design.app;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import ticwear.design.R;
import ticwear.design.widget.TimePicker;

class TimePickerViewHolder {

    private static final String HOUR = "hour";
    private static final String MINUTE = "minute";
    private static final String IS_24_HOUR = "is24hour";

    private TimePicker mTimePicker;

    private int mInitialHourOfDay;
    private int mInitialMinute;
    private boolean mIs24HourView;

    private final Context mContext;

    public TimePickerViewHolder(Context context) {
        this.mContext = context;
    }

    public TimePicker init(ViewGroup parent, int hourOfDay, int minute, boolean is24HourView,
                           TimePicker.OnTimeChangedListener listener,
                           TimePicker.ValidationCallback callback) {

        mInitialHourOfDay = hourOfDay;
        mInitialMinute = minute;
        mIs24HourView = is24HourView;

        final LayoutInflater inflater = LayoutInflater.from(mContext);

        mTimePicker = (TimePicker) inflater.inflate(R.layout.dialog_time_picker, parent, false);
        mTimePicker.setIs24HourView(mIs24HourView);
        mTimePicker.setCurrentHour(mInitialHourOfDay);
        mTimePicker.setCurrentMinute(mInitialMinute);
        mTimePicker.setOnTimeChangedListener(listener);
        mTimePicker.setValidationCallback(callback);

        return mTimePicker;
    }

    /**
     * Gets the {@link TimePicker} contained in this dialog.
     *
     * @return The TimePicker view.
     */
    public TimePicker getTimePicker() {
        return mTimePicker;
    }

    /**
     * Sets the current time.
     *
     * @param hourOfDay The current hour within the day.
     * @param minuteOfHour The current minute within the hour.
     */
    public void updateTime(int hourOfDay, int minuteOfHour) {
        mTimePicker.setCurrentHour(hourOfDay);
        mTimePicker.setCurrentMinute(minuteOfHour);
    }

    public void onSaveInstanceState(Bundle state) {
        state.putInt(HOUR, mTimePicker.getCurrentHour());
        state.putInt(MINUTE, mTimePicker.getCurrentMinute());
        state.putBoolean(IS_24_HOUR, mTimePicker.is24HourView());
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        final int hour = savedInstanceState.getInt(HOUR);
        final int minute = savedInstanceState.getInt(MINUTE);
        mTimePicker.setIs24HourView(savedInstanceState.getBoolean(IS_24_HOUR));
        mTimePicker.setCurrentHour(hour);
        mTimePicker.setCurrentMinute(minute);
    }

}


text:
<?php

namespace ClearSale;

use ClearSale\Environment\AbstractEnvironment;
use ClearSale\XmlEntity\SendOrder\Order;
use ClearSale\XmlEntity\Response\OrderReturn;
use ClearSale\XmlEntity\Response\PackageStatus;
use InvalidArgumentException;

class ClearSaleAnalysis
{
    const APROVADO             = 'Aprovado';
    const AGUARDANDO_APROVACAO = 'Aguardando aprovação';
    const REPROVADO            = 'Reprovado';
    const ERRO                 = 'Erro';

    private static $paymentStatus = array(
        self::APROVADO,
        self::REPROVADO,
    );

    private $environment;
    private $clearSaleService;
    private $clearSalePaymentIntegration;
    private $packageStatusResponse;

    /**
     * Construtor para gerar a integração com a ClearSale
     *
     * @param AbstractEnvironment $environment
     * @param bool $isDebug
     * @throws InvalidArgumentException
     */
    public function __construct(AbstractEnvironment $environment)
    {
        $this->environment                 = $environment;
        $this->clearSaleService            = new ClearSaleService($environment);
        $this->clearSalePaymentIntegration = new ClearSalePaymentIntegration($environment);
    }

    /**
     * Método para envio de pedidos e retorno do status
     *
     * @param Order $order
     * @return string
     */
    public function analysis(Order $order)
    {
        $this->sendOrder($order);

        return $this->getOrderStatus($order->getId());
    }

    /**
     * Retorna o status de aprovação de um pedido
     *
     * @param string $orderId
     * @return string
     */
    public function getOrderStatus($orderId)
    {
        $this->packageStatusResponse = $this->clearSaleService->getOrderStatus($orderId);

        // TODO: Implement log -> $this->packageStatusResponse->getOrder()->getStatus()
        // TODO: Implement log -> $this->packageStatusResponse->getOrder()->getScore()

        if ($this->approved($this->packageStatusResponse)) {
            return self::APROVADO;
        } elseif ($this->notApproved($this->packageStatusResponse)) {
            return self::REPROVADO;
        } elseif ($this->waitingForApproval($this->packageStatusResponse)) {
            return self::AGUARDANDO_APROVACAO;
        } else {
            return self::ERRO;
        }
    }

    /**
     * Retorna os detalhes do pedido após o pedido de análise
     *
     * @return PackageStatus
     */
    public function getPackageStatus()
    {
        return $this->packageStatusResponse;
    }

    /**
     * Método para atualizar o pedido com o status do pagamento
     *
     * @param string $orderId
     * @param string $paymentStatus
     * @return OrderReturn
     */
    public function updateOrderStatusId($orderId, $paymentStatus)
    {
        if (!in_array($paymentStatus, self::$paymentStatus)) {
            throw new InvalidArgumentException(sprintf('Invalid payment status (%s)', $paymentStatus));
        }

        return $this->clearSalePaymentIntegration->updateOrderStatusId($orderId, $paymentStatus);
    }

    private function sendOrder(Order $order)
    {
        $packageStatus = $this->clearSaleService->sendOrders($order);

        if ($this->environment->isDebug()) {
            var_dump($packageStatus);
        }

        if ($packageStatus->getStatusCode() != PackageStatus::STATUS_CODE_TRANSACAO_CONCLUIDA) {
            throw new \Exception(sprintf('Transaction Failed! (statusCode: %s)', $packageStatus->getStatusCode()));
        }
    }

    private function approved(PackageStatus $packageStatus)
    {
        switch ($packageStatus->getOrder()->getStatus()) {
            case OrderReturn::STATUS_SAIDA_APROVACAO_AUTOMATICA:
            case OrderReturn::STATUS_SAIDA_APROVACAO_MANUAL:
                return true;
            default:
                return false;
        }
    }

    private function notApproved(PackageStatus $packageStatus)
    {
        switch ($packageStatus->getOrder()->getStatus()) {
            case OrderReturn::STATUS_SAIDA_REPROVADA_SEM_SUSPEITA:
            case OrderReturn::STATUS_SAIDA_CANCELADO_PELO_CLIENTE:
            case OrderReturn::STATUS_SAIDA_FRAUDE_CONFIRMADA:
            case OrderReturn::STATUS_SAIDA_REPROVACAO_AUTOMATICA:
            case OrderReturn::STATUS_SAIDA_REPROVACAO_POR_POLITICA:
                return true;
            default:
                return false;
        }
    }

    private function waitingForApproval(PackageStatus $packageStatus)
    {
        switch ($packageStatus->getOrder()->getStatus()) {
            case OrderReturn::STATUS_SAIDA_ANALISE_MANUAL:
            case OrderReturn::STATUS_SAIDA_NOVO:
            case OrderReturn::STATUS_SAIDA_SUSPENSAO_MANUAL:
                return true;
            default:
                return false;
        }
    }
}


text:
USE TelerikAcademy

SELECT FirstName, LastName
FROM Employees
WHERE LEN(LastName) = 5;


text:
<?xml version='1.0.1' encoding='utf-8'?>
<widget id="me.shapaozi.mobile" version="1.1.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>ShaPaoZi</name>
    <description>
        The Andoird App of ShaPaoZi.me
    </description>
    <author email="whtsky@gmail.com" href="https://github.com/whtsky">
        Wu Haotian
    </author>
    <content src="index.html"/>
    <preference name="DisallowOverscroll" value="true" />
    <preference name="orientation" value="portrait" />
    <preference name="webviewbounce" value="false" />
    <preference name="BackgroundColor" value="0xffeeeeee" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="android-installLocation" value="auto" />
    <icon src="icon.png" />
    <plugin name="cordova-plugin-whitelist" version="1" />
    <plugin name="cordova.plugins.clipboard" />
    <allow-intent href="magnet:*" />
    <access origin="*" />
    <engine name="android" spec="~4.1.1" />
    <preference name="xwalkVersion" value="20+" />
    <preference name="xwalkCommandLine" value="--disable-pull-to-refresh-effect" />
    <preference name="xwalkMode" value="embedded" />
    <preference name="xwalkMultipleApk" value="false" />
</widget>


text:
#ifndef __itkConvolutionImageFilter_h
#define __itkConvolutionImageFilter_h

#include "itkImageToImageFilter.h"

namespace itk
{
/** \class ConvolutionImageFilter
 * \brief Convolve a given image with an arbitrary image kernel
 *
 * This code was contributed in the Insight Journal paper:
 *
 * "Image Kernel Convolution"
 * by Tustison N., Gee J.
 * http://hdl.handle.net/1926/1323
 * http://www.insight-journal.org/browse/publication/208
 *
 * \author Nicholas J. Tustison
 * \author James C. Gee
 * \ingroup ITK-Review
 *
 * \wiki
 * \wikiexample{ImageProcessing/ConvolutionImageFilter,Convolve an image with a kernel}
 * \endwiki
 */
template< class TInputImage, class TOutputImage = TInputImage >
class ITK_EXPORT ConvolutionImageFilter:
  public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  typedef ConvolutionImageFilter                          Self;
  typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;
  typedef SmartPointer< Self >                            Pointer;
  typedef SmartPointer< const Self >                      ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information ( and related methods ) */
  itkTypeMacro(ConvolutionImageFilter, ImageToImageFilter);

  /** Dimensionality of input and output data is assumed to be the same. */
  itkStaticConstMacro(ImageDimension, unsigned int,
                      TInputImage::ImageDimension);

  typedef TInputImage                          InputImageType;
  typedef TOutputImage                         OutputImageType;
  typedef typename InputImageType::PixelType   InputPixelType;
  typedef typename OutputImageType::PixelType  OutputPixelType;
  typedef typename OutputImageType::RegionType OutputRegionType;

  itkSetInputMacro(ImageKernel, InputImageType, 1);
  itkGetInputMacro(ImageKernel, InputImageType, 1);

  /**
   * Normalize the output image by the sum of the kernel components
   */
  itkSetMacro(Normalize, bool);
  itkGetConstMacro(Normalize, bool);
  itkBooleanMacro(Normalize);

  /** ConvolutionImageFilter needs a smaller 2nd input (the image kernel)
   * requested region than output requested region.  As such, this filter
   * needs to provide an implementation for GenerateInputRequestedRegion() in
   * order to inform the pipeline execution model.
   * \sa ProcessObject::GenerateInputRequestedRegion()  */
  virtual void GenerateInputRequestedRegion();

protected:
  /** de/constructor */
  ConvolutionImageFilter();
  ~ConvolutionImageFilter();

  void PrintSelf(std::ostream & os, Indent indent) const;

  void ThreadedGenerateData(const OutputRegionType & outputRegionForThread, ThreadIdType threadId);

private:
  ConvolutionImageFilter(const Self &); //purposely not implemented
  void operator=(const Self &);         //purposely not implemented

private:
  bool m_Normalize;
};
}

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkConvolutionImageFilter.txx"
#endif

#endif


text:
package com.gemstone.gemfire.distributed.internal.tcpserver;

import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.internal.Version;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Get GemFire version of the member running TcpServer.
 * @author shobhit
 * @since 7.1
 */
public class VersionResponse implements DataSerializable {

  private static final long serialVersionUID = 8320323031808601748L;
  private short versionOrdinal = Version.TOKEN.ordinal();

  @Override
  public void toData(DataOutput out) throws IOException {
    out.writeShort(versionOrdinal);
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    versionOrdinal = in.readShort();
  }

  public short getVersionOrdinal() {
    return versionOrdinal;
  }

  public void setVersionOrdinal(short versionOrdinal) {
    this.versionOrdinal = versionOrdinal;
  }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSObject (SWCameraAuthorization)

+ (void)requestCameraAuthorizationWithCompletion:(void(^ _Nullable)(BOOL isAuthorized))completedBlock alertViewController:(UIViewController *_Nullable)alertViewController;
+ (NSNumber *)sw_isHaveCameraAuthorizationWithAlertViewController:(UIViewController *_Nullable)alertViewController;

@end

NS_ASSUME_NONNULL_END


text:
import { store } from '../store/index';

/**
 * Fuse can only search arrays that are one level deep.
 * This loader will create a flat array from all the articles previously loaded by manifest-loader.
 * This loader is wrapped in a function to pass parameters to the underlying promise.
 *
 * @param rootArticles = store.state.core.articles
 */
function searchLoader(rootArticles = store.state.core.articles) {
    return new Promise(resolve => {
        Object.values(rootArticles).forEach(topLevel => {
            /**
             * If we have objects (aka sub categories within this level) we recursively load them until
             * we end up with an array. An array is the sign that we have POTENTIALLY reached the deepest
             * level of sub categories.
             *
             */
            if (!Array.isArray(topLevel)) {
                searchLoader(topLevel);
            } else {
                /**
                 * If we get an array, we MIGHT be at the deepest level of sub categories. This is not a certainty
                 * since we can have an infinite number of sub categories.
                 *
                 */
                Object.values(topLevel).forEach(article => {
                    /**
                     * IMPORTANT:
                     * "title" is a reserved keyword. It is how we know if we have further nested categories.
                     *
                     */
                    if (!article.title) {
                        searchLoader(article);
                    } else {
                        store.commit({
                            type: 'search/setFlatArticle',
                            article: article
                        });
                    }
                });
            }
        });

        // Resolve the loader.
        resolve();
    });
}

export default searchLoader;


text:
layout: post
title:  "Java Lambda Expressions"
date:   2017-09-17 23:49:20
category: java
published: true
author: RoyChan
tags:
- java
- lambda expressions
---

# change of interface
在java8中,interface可加入一个由default关键字修饰的method,这个method类似于abstract method,有具体的实现方式,但却不需要subclass继承

````java
interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};

formula.calculate(100);     // 100.0
formula.sqrt(16);           // 4.0
````

# why we need lambda expressions
lambda expressions的出现最主要的目的就是为了简化anonymous class的书写
,上述代码可做如下改写
````java>
Formula formula1 = a -> sqrt(a * 100);
````
however,如果真的在compiler上做这样的改写,你会发现这会出现compile error:stuck_out_tongue_winking_eye:,实际上这里涉及到一个lambda的scope问题,这在后面会有详细地讲解

# FunctionalInterface annotation
@FunctionalInterface这个注解是解决interface中type inference问题。当interface中含有generic type时,需要加入此注解来让compiler识别出确定的type,如以下代码。

````java
@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}

Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted);    // 123
````

# lambda in constructor and method
constructor和method的lambda expressions是使用运算符::。这本质上就是用constructor或method来替换对应在interface中declare的method。因为是替换,所以parameter type和return type都必须一致。而对于method来说,需要使用static来修饰,否则需要相关的object。
````java
//constructor相关
class Person {
    String firstName;
    String lastName;

    Person() {}

    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

interface PersonFactory<P extends Person> {
    P create(String firstName, String lastName);
}

PersonFactory<Person> personFactory = Person::new;//这里使用的是第二个constructor
Person person = personFactory.create("Peter", "Parker");
````
````java
//method相关
class Something {
    String startsWith(String s) {
        return String.valueOf(s.charAt(0));
    }
}

Something something = new Something();
Converter<String, String> converter = something::startsWith;//没用static修饰
String converted = converter.convert("Java");
System.out.println(converted);    // "J"
````

# lambda scopes
这里借[官方文档](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.2)的一段话:

> Unlike code appearing in anonymous class declarations, the meaning of **names** and the **this** and **super** keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

大意就是关键字names、this和super,以及the accessibility of referenced declarations都与周围的上下文一样,也就是所有variable和method的reference都是与周围上下文一样的,新的variable和method需要做重新的declare。下面一段摘抄自StackOverflow中的code,可以很好地表达这其中的含义。

````java
class Main {

    public static void main(String[] args) {
        new Main().foo();
    }

    void foo() {
        System.out.println(this);
        Runnable r = () -> {
            System.out.println(this);
        };
        r.run();
    }
}
````
输出的结果:

````java
Main@f6f4d33
Main@f6f4d33
````

对于local variables,可以不使用final来做修饰,但必须是implicitly final,否则会有compile error。而对于field和static variables,都是和anonymous class一致,这里就不再赘述了

# references:
- [http://winterbe.com/posts/2014/03/16/java-8-tutorial/][R1]
- [https://stackoverflow.com/questions/33108540/why-can-we-not-use-default-methods-in-lambda-expressions][R2]
- [http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.2][R3]

[R1]: http://winterbe.com/posts/2014/03/16/java-8-tutorial/
[R2]: https://stackoverflow.com/questions/33108540/why-can-we-not-use-default-methods-in-lambda-expressions
[R3]: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.2


text:
package org.apereo.cas.adaptors.radius;

import net.jradius.packet.attribute.RadiusAttribute;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.login.FailedLoginException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * This is {@link RadiusUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public final class RadiusUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(RadiusUtils.class);

    private RadiusUtils() {
    }

    /**
     * Authenticate pair.
     *
     * @param username                        the username
     * @param password                        the password
     * @param servers                         the servers
     * @param failoverOnAuthenticationFailure the failover on authentication failure
     * @param failoverOnException             the failover on exception
     * @return the pair
     * @throws Exception the exception
     */
    public static Pair<Boolean, Optional<Map<String, Object>>> authenticate(final String username, final String password,
                                                                            final List<RadiusServer> servers,
                                                                            final boolean failoverOnAuthenticationFailure,
                                                                            final boolean failoverOnException) throws Exception {
        for (final RadiusServer radiusServer : servers) {
            LOGGER.debug("Attempting to authenticate [{}] at [{}]", username, radiusServer);
            try {
                final RadiusResponse response = radiusServer.authenticate(username, password);
                if (response != null) {
                    final Map<String, Object> attributes = new HashMap<>();
                    for (final RadiusAttribute attribute : response.getAttributes()) {
                        attributes.put(attribute.getAttributeName(), attribute.getValue().toString());
                    }
                    return Pair.of(Boolean.TRUE, Optional.of(attributes));
                }

                if (!failoverOnAuthenticationFailure) {
                    throw new FailedLoginException("Radius authentication failed for user " + username);
                }
                LOGGER.debug("failoverOnAuthenticationFailure enabled -- trying next server");
            } catch (final Exception e) {
                if (!failoverOnException) {
                    throw e;
                }
                LOGGER.warn("failoverOnException enabled -- trying next server.", e);
            }
        }
        return Pair.of(Boolean.TRUE, Optional.empty());
    }
}