text:
<!DOCTYPE html>

    <title ng-bind="pageTitle"></title>

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@joshdmiller">
    <meta name="twitter:title" content="ngBoilerplate">
    <meta name="twitter:description" content="Non-Trivial AngularJS Made Easy: Everything you need to kickstart AngularJS projects: a best-practice directory structure, an intelligent build system, and the best web design libraries around.">
    <meta name="twitter:creator" content="@joshdmiller">
    <meta name="twitter:image:src" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846">
    <meta property="og:title" content="ngBoilerplate" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://bit.ly/ngBoilerplate" />
    <meta property="og:image" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846" />
    <meta property="og:description" content="Non-Trivial AngularJS Made Easy: Everything you need to kickstart AngularJS projects: a best-practice directory structure, an intelligent build system, and the best web design libraries around.">

    <link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

    <% styles.forEach( function ( file ) { %>
    <link rel="stylesheet" type="text/css" href="<%= file %>" /><% }); %>

    <% scripts.forEach( function ( file ) { %>
    <% }); %>

ng-boilerplate v<%= version %>

                    Home

                    What is it?

                    Read the Docs

                    Github

                    Support

            (c) 2013 Josh David Miller.
            Fork this
            to kickstart your next project.

            ng-boilerplate is based on
            AngularJS,
            Bootstrap,
            UI Bootstrap,
            and
            Font Awesome.


text:
package com.tapad.tapestry;

import java.util.List;

import static android.preference.PreferenceManager.getDefaultSharedPreferences;
import static com.tapad.tapestry.TapestryError.CLIENT_REQUEST_ERROR;
import static com.tapad.tapestry.TapestryError.OPTED_OUT;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.tapad.tapestry.deviceidentification.TypedIdentifier;
import com.tapad.tapestry.http.HttpStack;
import com.tapad.tapestry.http.HttpStackFactory;

/**
 * A client for sending requests to the Tapestry Web API and returning responses. The client should be instantiated once
 * your activity has entered {@code onCreate()}. If you use the client across many Activities, you may wish to use the
 * {@link TapestryService} wrapper instead.
 *

 * The client sends a {@link TapestryRequest} as an HTTP request to the Tapestry Web API and parses the JSON response as
 * {@link TapestryResponse}. When calling the client from the Android UI thread, it is recommended to send requests
 * asynchronously by passing in a {@link TapestryCallback} so as not to block the UI thread.
 *

 * An example of sending a request and receiving an asynchronous response:

 *
 *

 * TapestryClient client = new TapestryClient(context);
 * TapestryRequest request = new TapestryRequest();
 * // TODO build request
 * client.send(request, new TapestryCallback() {
 *     {@literal @}Override
 *     public void receive(TapestryResponse response) {
 *         // TODO handle response
 *     }
 * });
 *

 *
 *
 Note if the callback updates the UI then you should use the {@link TapestryUICallback} convenience
 * class which runs the callback on the UI thread. The client throws no exceptions unless
 * {@link Logging#setThrowExceptions(boolean)} has been set to true.
 */
public class TapestryClient {
	public static final String DEFAULT_URL = "http://tapestry.tapad.com/tapestry/1";
	public static final String PREF_TAPAD_DEVICE_ID = "_tapad_device_id";
	public static final String OPTED_OUT_DEVICE_ID = "OptedOut";
	public static final String TAPESTRY_HEADER = "X-Tapestry-Id";
	private final ConnectionStatusExecutor connectionExecutor;
	private final TapestryTracking tracking;
	private final String url;
	private final String partnerId;
	private final HttpStack stack;

	/**
	 * Creates client ready to receive requests. Client cannot be instantiated before {@code onCreate} is called.
	 * Partner id will be read from {@code tapad.PARTNER_ID} in the manifest or default if none exists. The url of the
	 * API will be read from {@code tapad.API_URL} in the manifest or default if none exists.
	 *
	 * @param context
	 *            The context of the app
	 */
	public TapestryClient(Context context) {
		this(context, getMetaData(context, "tapad.PARTNER_ID", null));
	}

	/**
	 * Creates client ready to receive requests. Client cannot be instantiated before {@code onCreate} is called. The
	 * url of the API will be read from {@code tapad.API_URL} in the manifest or default if none exists.
	 *
	 * @param context
	 *            The context of the app
	 * @param partnerId
	 *            The Tapestry partner id that has been assigned to you
	 */
	public TapestryClient(Context context, String partnerId) {
		this(context, partnerId, getMetaData(context, "tapad.API_URL", DEFAULT_URL));
	}

	/**
	 * Creates client ready to receive requests. Client cannot be instantiated before {@code onCreate} is called.
	 *
	 * @param context
	 *            The context of the app
	 * @param partnerId
	 *            The Tapestry partner id that has been assigned to you
	 * @param url
	 *            The url of the tapestry host
	 */
	public TapestryClient(Context context, String partnerId, String url) {
		this(context, partnerId, url, HttpStackFactory.getDefaultStack(context));
	}

	/**
	 * Creates client ready to receive requests. Client cannot be instantiated before {@code onCreate} is called.
	 *
	 * @param context
	 *            The context of the app
	 * @param partnerId
	 *            The Tapestry partner id that has been assigned to you
	 * @param url
	 *            The url of the tapestry host
	 * @param stack
	 *            The stack for sending and receiving http requests
	 */
	public TapestryClient(Context context, String partnerId, String url, HttpStack stack) {
		this.tracking = new TapestryTracking(context);
		this.partnerId = partnerId;
		this.url = url;
		this.stack = stack;
		this.connectionExecutor = new ConnectionStatusExecutor(context);

		if (this.partnerId == null)
			throw new RuntimeException("Partner id must be specified in the manifest or during instantiation");
	}

	private static String getMetaData(Context context, String key, String defaultValue) {
		try {
			String value = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.get(key).toString();
			return value == null ? defaultValue : value;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * @return Will return a list of typed device identifiers, e.g. UID, Wi-Fi MAC address
	 */
	public List<TypedIdentifier> getDeviceIDs() {
		return tracking.getIds();
	}

	public String getPartnerID() {
		return partnerId;
	}

	public String getURL() {
		return url;
	}

	/**
	 * Sends a request asynchronously using a worker thread pool.
	 *
	 * @param callback
	 *            A callback that will be called when the Tapestry server responds
	 */
	public void send(final TapestryCallback callback) {
		send(new TapestryRequest(), callback);
	}

	/**
	 * Sends a request asynchronously using a worker thread pool, without returning a response.
	 *
	 * @param request
	 *            The request
	 */
	public void send(final TapestryRequest request) {
		send(request, TapestryCallback.DO_NOTHING);
	}

	/**
	 * Sends a request asynchronously using a worker thread pool.
	 *
	 * @param request
	 *            The request
	 * @param callback
	 *            A callback that will be called when the Tapestry server responds
	 */
	public void send(final TapestryRequest request, final TapestryCallback callback) {
		final long timeOfRequest = System.currentTimeMillis();
		connectionExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					TapestryResponse response = sendSynchronously(request);
					callback.receive(response, null, System.currentTimeMillis() - timeOfRequest);
				} catch (Exception e) {
					Logging.e("Exception sending request ", e);
					TapestryResponse response = new TapestryResponse(new TapestryError(CLIENT_REQUEST_ERROR, "ClientRequestError", "Exception: " + e));
					callback.receive(response, e, System.currentTimeMillis() - timeOfRequest);
				}
			}
		});
	}

	/**
	 * Sends a request synchronously, blocking until response is received.
	 *
	 * @param request
	 *            The request
	 * @return a response from the server
	 */
	public TapestryResponse sendSynchronously(TapestryRequest request) throws Exception {
		if (tracking.getDeviceId().equals(OPTED_OUT_DEVICE_ID))
			return new TapestryResponse(new TapestryError(OPTED_OUT, "OptedOut", ""));
		String uri = url + "?" + addParameters(request).toQuery();
		String response = stack.performGet(uri, TAPESTRY_HEADER, partnerId);
		Logging.d("Received response " + response);
		return new TapestryResponse(response);
	}

	/**
	 * Opts this device into tracking. Tapestry will collect ids and send requests from this app.
	 */
	public void optIn(Context context) {
		getDefaultSharedPreferences(context).edit().remove(PREF_TAPAD_DEVICE_ID).commit();
		tracking.updateDeviceId(context);
	}

	/**
	 * Opts this device out of all tracking. Tapestry will not be able to send requests from this app. All responses
	 * will be a {@link TapestryResponse} containing an {@link TapestryError#OPTED_OUT} error.
	 */
	public void optOut(Context context) {
		getDefaultSharedPreferences(context).edit().putString(PREF_TAPAD_DEVICE_ID, OPTED_OUT_DEVICE_ID).commit();
		tracking.updateDeviceId(context);
	}

	/**
	 * Adds parameters which are required (e.g. device identifiers and partner id) to a request.
	 *
	 * @param request
	 *            A request
	 * @return the request with additional parameters
	 */
	public TapestryRequest addParameters(TapestryRequest request) {
		for (TypedIdentifier identifier : tracking.getIds())
			request.typedDid(identifier.getType(), identifier.getValue());
		if (!TextUtils.isEmpty(tracking.getPlatform()))
			request.platform(tracking.getPlatform());
		return request.partnerId(partnerId).get();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/load0" android:duration="500" />
    <item android:drawable="@drawable/load1" android:duration="500" />
    <item android:drawable="@drawable/load2" android:duration="500" />
    <item android:drawable="@drawable/load3" android:duration="500" />
</animation-list>


text:
export function exported() {}

function notExported() {}


text:
参数列表

- typ Type 传入Map的 reflect.Type 类型

返回值:

- Value 输出已被初始Map的 reflect.Value 类型

功能说明:

- 指定类型初始化一个新的Map。

代码实例:

	package main
	import (
		"fmt"
		"reflect"
	)

	func main(){
		var a map[int]string

		var value reflect.Value = reflect.ValueOf(&a)

		value = reflect.Indirect(value) //使指针指向内存地址

		value = reflect.MakeMap(value.Type())

		value.SetMapIndex(reflect.ValueOf(1), reflect.ValueOf("a"))
		value.SetMapIndex(reflect.ValueOf(2), reflect.ValueOf("b"))

		fmt.Println(value.Kind(), value.Interface())
		//>>map map[1:a 2:b]
	}


text:
<?php

namespace Google\AdsApi\Dfp\v201702;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class DeliveryRateType
{
    const EVENLY = 'EVENLY';
    const FRONTLOADED = 'FRONTLOADED';
    const AS_FAST_AS_POSSIBLE = 'AS_FAST_AS_POSSIBLE';

}


text:
package apple.homekit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.NSURL;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("HomeKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class HMAddAccessoryRequest extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected HMAddAccessoryRequest(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    /**
     * The category of the accessory to be added.
     */
    @Generated
    @Selector("accessoryCategory")
    public native HMAccessoryCategory accessoryCategory();

    /**
     * Name of the accessory to be added.
     */
    @Generated
    @Selector("accessoryName")
    public native String accessoryName();

    @Generated
    @Owned
    @Selector("alloc")
    public static native HMAddAccessoryRequest alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native HMAddAccessoryRequest allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    /**
     * Home that the accessory is to be added to.
     */
    @Generated
    @Selector("home")
    public native HMHome home();

    @Generated
    @Selector("init")
    public native HMAddAccessoryRequest init();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native HMAddAccessoryRequest new_objc();

    /**
     * Creates an accessory setup payload with ownership token
     *

     * This method may fail if this request requires a setup payload URL.
     *
     * @param ownershipToken The token proving ownership of the accessory being added to the home.
     * @return Returns an accessory setup payload object if successful or nil on error.
     */
    @Generated
    @Selector("payloadWithOwnershipToken:")
    public native HMAccessorySetupPayload payloadWithOwnershipToken(HMAccessoryOwnershipToken ownershipToken);

    /**
     * Creates an accessory setup payload with URL and ownership token
     *

     * This method may fail if the setup payload URL is not a valid payload URL.
     *
     * @param setupPayloadURL The HomeKit setup payload for the accessory being added to the home.
     * @param ownershipToken  The token proving ownership of the accessory being added to the home.
     * @return Returns an accessory setup payload object if successful or nil on error.
     */
    @Generated
    @Selector("payloadWithURL:ownershipToken:")
    public native HMAccessorySetupPayload payloadWithURLOwnershipToken(NSURL setupPayloadURL,
            HMAccessoryOwnershipToken ownershipToken);

    /**
     * Indication if the ownership token needs to be updated for this request.
     */
    @Generated
    @Selector("requiresOwnershipToken")
    public native boolean requiresOwnershipToken();

    /**
     * Indication if the setup URL needs to be updated for this request. If this is true,
     * payloadWithURL:ownershipToken: must be used to create the HMAccessorySetupPayload.
     */
    @Generated
    @Selector("requiresSetupPayloadURL")
    public native boolean requiresSetupPayloadURL();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();
}


text:
<!DOCTYPE html>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta name="keywords">
    <meta name="description">

    <title>Citizens Advice style guide- Saving content
    </title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=2.0" name="viewport">
    <meta content="48a2415d-980f-4763-a5b9-e10e000636b3" name="cab-guid">
    <meta content="EWS" name="cab-extent">
    <meta content="../../static/images/apple-touch-icon.png">
    <meta content="B53C5C20449FC2233D3862B4DBEDFA3E" name="msvalidate.01">

    <link href="../../css/guide.css" rel="stylesheet">
    <link href="../../images/favicon/32.png" rel="shortcut icon">
    <link href="../../images/favicon/228.png" rel="apple-touch-icon">

Skip to contentSkip to footer

Menu
          CymraegSign-in
          <form action="" class="main-header__search hide-offline">
            Search
            <input id="main-header__search__input" name="q" placeholder="" type="search" class="main-header__search__input">
            <button title="Search" type="submit" class="main-header__search__submit">Search</button>
          </form>

Benefits

Work

Debt and money

Consumer

Relationships

Housing

Law and rights

Discrimination

Tax

Healthcare

Education

More from us

More

HomeModulesContent toolbar

Saving content

This advice is for
            <button id="showSimpleModal" type="button" class="btn-secondary btn-small">This advice is forEngland</button>
            <button href="javascript:window.print();" data-track="Print" class="toolbar-button a-social-print">Print</button>

Making a claim for the benefit Personal Independence Payment (PIP) can take a long time time. It can often take up to 4 months from starting the application to getting your money (if you're terminally ill your claim will be processed more quickly).

If you're moving from DLA to PIP your payments won't stop while you're waiting for your PIP claim to be processed, as long as you make your claim for PIP within a month of being told by the DWP that you should.

You should make sure you're prepared and have all the relevant information to help you make your claim.

Your first payment for PIP will be backdated to the date you started your claim and cover the length of time it takes the Department for Work and Pensions (DWP) to make its decision. If you're moving from DLA to PIP your PIP payments will start the day after your DLA stops.

The claims process

There are 3 stages to your claim:

Start your claim by calling the DWP

Wait for them to send you a claim form

Go to a face-to-face assessment - most people have to do this (but you won't if you're terminally ill)

It can take up to 2 weeks for the DWP to send you a PIP claim form. While you wait, it's a good idea to think about how you'll fill in the claim form and if you need any supporting evidence.

If you're waiting a very long time for a decision on your claim, contact your local Citizens Advice in England and Wales or in Scotland. You can complain to the DWP if the delay is unreasonable and may be able to claim compensation if it's considered unlawful. However, there are no set rules on what counts as unreasonable or unlawful

Start your claim - fill in a PIP1 form

You can start your PIP claim by filling in a PIP1 form. You can do this either:

by phone - a DWP adviser will fill in the basic claim form during the call, it should only take 20 minutes

by post - filling in a paper form that the DWP can send you, and posting it back

You can't fill in the PIP1 form online.

It's best to start your claim by phone because it's quicker and your PIP payments are usually backdated to when you start your claim - either the date you phone or the date the DWP receives your PIP1 form.

You can only get the PIP claim forms from the DWP, not online or from Citizens Advice.

Basic information you need to start your claim

You'll need to have this information when you call the DWP:

your full name, address and phone number

your national insurance number

your bank or building society account details so payments can be made if PIP is awarded

contact details of your GP or other health professionals you deal with

the dates and details of any stays in hospital or residential care

your nationality or immigration status

if you've been abroad for more than 4 weeks at a time in the last 3 years (you'll need the dates and details)

You'll be asked if you have any conditions relating to your mental health, a learning difficulty or behavioural condition. These questions are asked to check if you need any additional help or support with your claim.

I want to apply by phone

PIP claim line

Telephone 0800 917 2222

Textphone 0800 917 7777

Open Monday to Friday, 8am to 6pm

Calls are free from landlines and from mobiles.

It should take about 20 minutes to complete the call. If you'd prefer someone else to call for you that's fine, but you need to be with them so that you can give permission for them to speak for you.

I want to apply by post

It's quicker to apply by phone, but If that isn't possible you can write to the DWP and ask for a PIP1 form.

You'll need to tell them why you (or someone else) can't do the PIP1 form over the phone.

Personal Independence Payment New Claims

Post Handling Site B

Wolverhampton

WV99 1AH

Information for advisers

The PIP2 form is sometimes called 'How your condition affects you' form

DWP guidance: Sample PIP1 form

DWP guidance: Sample PIP2 form

DWP guidance: Compensation for poor service

Case law: Unlawful delays in processing a PIP claim and the High Court's decision

Power of attorney: making decisions for someone who lacks mental capacity

Appointees and benefit claims

Next steps

The DWP will assess whether you meet the basic eligibility conditions.

If you do, they'll send you a PIP claim form. This form is where you tell them how your condition affects you. If you've waited more than 2 weeks, contact the PIP claims line and ask them for an update.

While you wait for the PIP2 form, you should think about how to fill in the PIP claim form and if you need to organise any supporting evidence to support your claim.

If you don't meet the basic eligibility conditions, you'll be sent a decision letter to say why you've been refused. If you think the decision is wrong, you can challenge the DWP's decision.

Share this page. Find out more about sharing.
WhatsappMessengerTwitterFacebookEmail
            <button class="a-social-copy">Copy link

Copied!

            </button>

In this section

Sick pay

Check if you're entitled to sick pay

How to get sick pay

Getting money when you're off work sick

Getting sick pay when you're pregnant

Sick pay

Contractual sick pay

Feedback

Is there anything wrong with this page? Let us know.

Get Advice

Benefits

Work

Debt and money

Consumer

Relationships

Housing

Law and rights

Discrimination

Tax

Healthcare

Education

A to Z of advice

Information

Help

Cymraeg

Terms and conditions

Privacy and cookies

Copyright © 2016 Citizens Advice, an operating name of the National Association of Citizens Advice Bureaux.
Registered charity number 279057; Registered in England 1436945; VAT number GB726020276. 3rd Floor North, 200 Aldersgate, London, EC1A 4HD


text:
DEFINITIONS

APR

An abbreviation for “Annual Percentage Rate” which is often the
rate being the basis of the interest of a loan or the finance
charge of a precomputed loan.

The exception being the “Principal Loan” where the rate is not
applied to the balance but the original principal.

See
Wikipedia
for further explanation.

EAR or EAPR

An abbreviation for Effective APR which is the APR with fees
included in the calculation.

It will be calculated for all types of loans and functions as a
rating.

See
Wikipedia
for further explanation.

Precomputed vs. Simple Interest

A finance charge is calculated from interest costs, and possibly
various other costs.

This charge is added to the principal as the owed amount.

See
DFI: Precomputed vs, Simple Interest Loans
for further explanation.

Rebate

How much of the finance charge that will be rebated (forgiven) in
the event that the loan is repaid early, prior to the agreed upon
number of payments.

See Wikipedia for
further explanation.

THE LOAN TYPES

All of the loans are paid back at fixed intervals, at fixed amounts,
at a fixed interest rate. What varies between them is how the rate is
applied, if prepayments will save interest, or if they got rebate for
repaying before maturity.

Simple Interest Loan

The rate is applied to what is left of the principal every amount
to determine the interest amount.

Prepayments will save you interest.

Rule of 78 Loan

A precomputed loan with a rebate system called the “Rule of 78”.

The finance charge is the interest of a “Simple Interest Loan” for
its full term.

See Wikipedia for
further explanation.

Precomputed Loan

A precomputed loan with no rebate.

The finance charge is the interest of a “Simple Interest Loan” for
its full term.

Principal Loan

A precomputed loan with no rebate.

The finance charge is the interest for its full term. The interest
for the full term is the sum of the periodic rate applied to the
original principal each period.

The rate may therefore seem unnaturally low.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using HFEA.BL.Contracts;
using HFEA.Core;
using HFEA.Core.Constants;

namespace HFEA.BL.Emailer
{
    public class EmailSender : IEmailSender
    {
        private const string MIME_HTML = "text/html";
        private const string MIME_TEXT = "text/plain";

        public MailMessage GetMailMessage(Email email)
        {
            if (email != null)
            {
                // pre validation and fixes to email
                if (string.IsNullOrWhiteSpace(email.ToAddress))
                {
                    //TODO: get default emailTo address from somewhere
                }

                if (string.IsNullOrWhiteSpace(email.FromAddress))
                {
                    //TODO: get default emailFrom address from somewhere
                }

                MailMessage mailMessage = new MailMessage();

                if (!string.IsNullOrWhiteSpace(email.FromAddress))
                {
                    mailMessage.From = new MailAddress(email.FromAddress.Trim());
                }

                //Add email To addresses
                if (!string.IsNullOrWhiteSpace(email.ToAddress))
                {
                    string[] toAddresses = email.ToAddress.Split(new char[] { EmailerConstants.Multiple_EmailAddresses_Seperator }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string address in toAddresses)
                    {
                        mailMessage.To.Add(address);
                    }
                }

                //Add email Cc addresses
                if (!string.IsNullOrWhiteSpace(email.CcAddress))
                {
                    string[] ccAddresses = email.CcAddress.Split(new char[] { EmailerConstants.Multiple_EmailAddresses_Seperator }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string address in ccAddresses)
                    {
                        mailMessage.CC.Add(address);
                    }
                }

                //Add Bcc addresses
                if (!string.IsNullOrWhiteSpace(email.BccAddress))
                {
                    string[] bccAddresses = email.BccAddress.Split(new char[] { EmailerConstants.Multiple_EmailAddresses_Seperator }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string address in bccAddresses)
                    {
                        mailMessage.Bcc.Add(address);
                    }
                }

                mailMessage.Subject = email.Subject;

                if (!string.IsNullOrWhiteSpace(email.BodyHTML) && !string.IsNullOrWhiteSpace(email.BodyText))
                {
                    mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(email.BodyHTML, null, MIME_HTML));
                    mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(email.BodyText, null, MIME_TEXT));
                }
                else
                {
                    bool isHtml = !string.IsNullOrWhiteSpace(email.BodyHTML) ? true : false;

                    mailMessage.Body = isHtml ? email.BodyHTML : email.BodyText;

                    mailMessage.IsBodyHtml = isHtml;
                }

                return mailMessage;
            }

            return null;
        }

        public bool Send(Email email)
        {
            bool sent = false;

            MailMessage message = this.GetMailMessage(email);

            try
            {
                using (SmtpClient client = new SmtpClient())
                {
                    client.Send(message);
                    sent = true;
                }
            }
            catch
            { }
            finally
            {
                if (message != null)
                    message.Dispose();
            }

            return sent;

        }
    }
}


text:
package mutable

import (
	"fmt"
	"math"
	"time"

	"github.com/googlecloudplatform/gcsfuse/lease"
	"github.com/jacobsa/timeutil"
	"golang.org/x/net/context"
)

// A mutable view on some content. Created with an initial read-only view,
// which then can be modified by the user and read back. Keeps track of which
// portion of the content has been dirtied.
//
// External synchronization is required.
type Content interface {
	// Panic if any internal invariants are violated.
	CheckInvariants()

	// Destroy any state used by the object, putting it into an indeterminate
	// state. The object must not be used again.
	Destroy()

	// If the content has been dirtied from its initial state, return a
	// read/write lease for the current content. Otherwise return nil.
	//
	// If this method returns a non-nil read/write lease, the Content is
	// implicitly destroyed and must not be used again.
	Release() (rwl lease.ReadWriteLease)

	// Read part of the content, with semantics equivalent to io.ReaderAt aside
	// from context support.
	ReadAt(ctx context.Context, buf []byte, offset int64) (n int, err error)

	// Return information about the current state of the content.
	Stat(ctx context.Context) (sr StatResult, err error)

	// Write into the content, with semantics equivalent to io.WriterAt aside from
	// context support.
	WriteAt(ctx context.Context, buf []byte, offset int64) (n int, err error)

	// Truncate our the content to the given number of bytes, extending if n is
	// greater than the current size.
	Truncate(ctx context.Context, n int64) (err error)
}

type StatResult struct {
	// The current size in bytes of the content.
	Size int64

	// It is guaranteed that all bytes in the range [0, DirtyThreshold) are
	// unmodified from the original content with which the mutable content object
	// was created.
	DirtyThreshold int64

	// The time at which the content was last updated, or nil if we've never
	// changed it.
	Mtime *time.Time
}

// Create a mutable content object whose initial contents are given by the
// supplied read proxy.
func NewContent(
	initialContent lease.ReadProxy,
	clock timeutil.Clock) (mc Content) {
	mc = &mutableContent{
		clock:          clock,
		initialContent: initialContent,
		dirtyThreshold: initialContent.Size(),
	}

	return
}

type mutableContent struct {
	/////////////////////////
	// Dependencies
	/////////////////////////

	clock timeutil.Clock

	/////////////////////////
	// Mutable state
	/////////////////////////

	destroyed bool

	// The initial contents with which this object was created, or nil if it has
	// been dirtied.
	//
	// INVARIANT: When non-nil, initialContent.CheckInvariants() does not panic.
	initialContent lease.ReadProxy

	// When dirty, a read/write lease containing our current contents. When
	// clean, nil.
	//
	// INVARIANT: (initialContent == nil) != (readWriteLease == nil)
	readWriteLease lease.ReadWriteLease

	// The lowest byte index that has been modified from the initial contents.
	//
	// INVARIANT: initialContent != nil => dirtyThreshold == initialContent.Size()
	dirtyThreshold int64

	// The time at which a method that modifies our contents was last called, or
	// nil if never.
	//
	// INVARIANT: If dirty(), then mtime != nil
	mtime *time.Time
}

////////////////////////////////////////////////////////////////////////
// Public interface
////////////////////////////////////////////////////////////////////////

func (mc *mutableContent) CheckInvariants() {
	if mc.destroyed {
		panic("Use of destroyed mutableContent object.")
	}

	// INVARIANT: When non-nil, initialContent.CheckInvariants() does not panic.
	if mc.initialContent != nil {
		mc.initialContent.CheckInvariants()
	}

	// INVARIANT: (initialContent == nil) != (readWriteLease == nil)
	if mc.initialContent == nil && mc.readWriteLease == nil {
		panic("Both initialContent and readWriteLease are nil")
	}

	if mc.initialContent != nil && mc.readWriteLease != nil {
		panic("Both initialContent and readWriteLease are non-nil")
	}

	// INVARIANT: If dirty(), then mtime != nil
	if mc.dirty() && mc.mtime == nil {
		panic("Expected non-nil mtime.")
	}

	// INVARIANT: initialContent != nil => dirtyThreshold == initialContent.Size()
	if mc.initialContent != nil {
		if mc.dirtyThreshold != mc.initialContent.Size() {
			panic(fmt.Sprintf(
				"Dirty threshold mismatch: %d vs. %d",
				mc.dirtyThreshold,
				mc.initialContent.Size()))
		}
	}
}

func (mc *mutableContent) Destroy() {
	mc.destroyed = true

	if mc.initialContent != nil {
		mc.initialContent.Destroy()
		mc.initialContent = nil
	}

	if mc.readWriteLease != nil {
		mc.readWriteLease.Downgrade().Revoke()
		mc.readWriteLease = nil
	}
}

func (mc *mutableContent) Release() (rwl lease.ReadWriteLease) {
	if !mc.dirty() {
		return
	}

	rwl = mc.readWriteLease
	mc.readWriteLease = nil
	mc.Destroy()

	return
}

func (mc *mutableContent) ReadAt(
	ctx context.Context,
	buf []byte,
	offset int64) (n int, err error) {
	// Serve from the appropriate place.
	if mc.dirty() {
		n, err = mc.readWriteLease.ReadAt(buf, offset)
	} else {
		n, err = mc.initialContent.ReadAt(ctx, buf, offset)
	}

	return
}

func (mc *mutableContent) Stat(
	ctx context.Context) (sr StatResult, err error) {
	sr.DirtyThreshold = mc.dirtyThreshold
	sr.Mtime = mc.mtime

	// Get the size from the appropriate place.
	if mc.dirty() {
		sr.Size, err = mc.readWriteLease.Size()
		if err != nil {
			return
		}
	} else {
		sr.Size = mc.initialContent.Size()
	}

	return
}

func (mc *mutableContent) WriteAt(
	ctx context.Context,
	buf []byte,
	offset int64) (n int, err error) {
	// Make sure we have a read/write lease.
	if err = mc.ensureReadWriteLease(ctx); err != nil {
		err = fmt.Errorf("ensureReadWriteLease: %v", err)
		return
	}

	// Update our state regarding being dirty.
	mc.dirtyThreshold = minInt64(mc.dirtyThreshold, offset)

	newMtime := mc.clock.Now()
	mc.mtime = &newMtime

	// Call through.
	n, err = mc.readWriteLease.WriteAt(buf, offset)

	return
}

func (mc *mutableContent) Truncate(
	ctx context.Context,
	n int64) (err error) {
	// Make sure we have a read/write lease.
	if err = mc.ensureReadWriteLease(ctx); err != nil {
		err = fmt.Errorf("ensureReadWriteLease: %v", err)
		return
	}

	// Convert to signed, which is what lease.ReadWriteLease wants.
	if n > math.MaxInt64 {
		err = fmt.Errorf("Illegal offset: %v", n)
		return
	}

	// Update our state regarding being dirty.
	mc.dirtyThreshold = minInt64(mc.dirtyThreshold, n)

	newMtime := mc.clock.Now()
	mc.mtime = &newMtime

	// Call through.
	err = mc.readWriteLease.Truncate(int64(n))

	return
}

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func minInt64(a int64, b int64) int64 {
	if a < b {
		return a
	}

	return b
}

func (mc *mutableContent) dirty() bool {
	return mc.readWriteLease != nil
}

// Ensure that mc.readWriteLease is non-nil with an authoritative view of mc's
// contents.
func (mc *mutableContent) ensureReadWriteLease(
	ctx context.Context) (err error) {
	// Is there anything to do?
	if mc.readWriteLease != nil {
		return
	}

	// Set up the read/write lease.
	rwl, err := mc.initialContent.Upgrade(ctx)
	if err != nil {
		err = fmt.Errorf("initialContent.Upgrade: %v", err)
		return
	}

	mc.readWriteLease = rwl
	mc.initialContent = nil

	return
}


text:
package droolsbook.bank.service.impl;

import droolsbook.bank.model.Account;
import droolsbook.bank.model.Address;
import droolsbook.bank.model.Customer;
import droolsbook.bank.service.BankingInquiryService;
import droolsbook.bank.service.Message;
import droolsbook.bank.service.ReportFactory;
import droolsbook.bank.service.ValidationReport;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseConfiguration;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.command.Command;
import org.drools.command.CommandFactory;
import org.drools.conf.SequentialOption;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatelessKnowledgeSession;
import org.joda.time.DateMidnight;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static org.junit.Assert.*;

// @extract-start 03 67
public class ValidationTest {
  static StatelessKnowledgeSession session;
  static ReportFactory reportFactory;

  @Before
  public void setUp() throws Exception {
    KnowledgeBuilder builder = KnowledgeBuilderFactory
        .newKnowledgeBuilder();
    builder.add(ResourceFactory.newClassPathResource(
        "validation.drl"), ResourceType.DRL);
    if (builder.hasErrors()) {
      throw new RuntimeException(builder.getErrors()
          .toString());
    }

    KnowledgeBaseConfiguration configuration =
      KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    configuration.setOption(SequentialOption.YES);

    KnowledgeBase knowledgeBase = KnowledgeBaseFactory
        .newKnowledgeBase(configuration);
    knowledgeBase.addKnowledgePackages(builder
        .getKnowledgePackages());

    BankingInquiryService inquiryService =
         new BankingInquiryServiceImpl();
    reportFactory = new DefaultReportFactory();

    session = knowledgeBase.newStatelessKnowledgeSession();
    session.setGlobal("reportFactory", reportFactory);
    session.setGlobal("inquiryService", inquiryService);
  }
  // @extract-end

  @Before
  public void initialize() {
  }

  // @extract-start 03 68
  void assertReportContains(Message.Type type,
      String messageKey,Customer customer,Object... context) {
    ValidationReport report =
        reportFactory.createValidationReport();
    List<Command> commands = new ArrayList<Command>();
    commands.add(CommandFactory.newSetGlobal(
        "validationReport", report));
    commands.add(CommandFactory
        .newInsertElements(getFacts(customer)));
    session.execute(CommandFactory
        .newBatchExecution(commands));

    assertTrue("Report doesn't contain message [" + messageKey
        + "]", report.contains(messageKey));
    Message message = getMessage(report, messageKey);
    assertEquals(Arrays.asList(context),
        message.getContextOrdered());
  }

  private Collection<Object> getFacts(Customer customer) {
    ArrayList<Object> facts = new ArrayList<Object>();
    facts.add(customer);
    facts.add(customer.getAddress());
    facts.addAll(customer.getAccounts());
    return facts;
  }
  // @extract-end

  Message getMessage(ValidationReport report, String key) {
    for (Message message : report.getMessages()) {
      if (message.getMessageKey().equals(key)) {
        return message;
      }
    }
    return null;
  }

  void assertNotReportContains(Message.Type type,
      String messageKey, Customer customer) {
    ValidationReport report =
      reportFactory.createValidationReport();
    session.setGlobal("validationReport", report);
    session.execute(getFacts(customer));

    assertFalse(
        "Report contains message [" + messageKey + "]",
        report.contains(messageKey));
  }

  Customer createCustomerBasic() {
    Customer customer = new Customer();
    Account account = new Account();
    customer.addAccount(account);
    account.setOwner(customer);
    return customer;
  }

  // @extract-start 03 62
  @Test
  public void addressRequired() throws Exception {
    Customer customer = createCustomerBasic();
    assertNull(customer.getAddress());
    assertReportContains(Message.Type.WARNING,
        "addressRequired", customer);

    customer.setAddress(new Address());
    assertNotReportContains(Message.Type.WARNING,
        "addressRequired", customer);
  }

  // @extract-end

  @Test
  public void accountOwnerRequired() throws Exception {
    Customer customer = createCustomerBasic();
    Account account =customer.getAccounts().iterator().next();
    assertNotNull(account.getOwner());
    assertNotReportContains(Message.Type.ERROR,
        "accountOwnerRequired", customer);
  }

  @Test
  public void phoneNumberRequired() throws Exception {
    Customer customer = createCustomerBasic();
    assertNull(customer.getPhoneNumber());
    assertReportContains(Message.Type.ERROR,
        "phoneNumberRequired", customer);

    customer.setPhoneNumber("");
    assertReportContains(Message.Type.ERROR,
        "phoneNumberRequired", customer);

    customer.setPhoneNumber("111 222 333");
    assertNotReportContains(Message.Type.ERROR,
        "phoneNumberRequired", customer);
  }

  // @extract-start 03 69
  @Test
  public void accountBalanceAtLeast() throws Exception {
    Customer customer = createCustomerBasic();
    Account account =customer.getAccounts().iterator().next();
    assertEquals(BigDecimal.ZERO, account.getBalance());
    assertReportContains(Message.Type.WARNING,
        "accountBalanceAtLeast", customer, account);

    account.setBalance(new BigDecimal("54.00"));
    assertReportContains(Message.Type.WARNING,
        "accountBalanceAtLeast", customer, account);

    account.setBalance(new BigDecimal("122.34"));
    assertNotReportContains(Message.Type.WARNING,
        "accountBalanceAtLeast", customer);
  }

  // @extract-end

  // @extract-start 03 70
  @Test
  public void studentAccountCustomerAgeLessThan()
      throws Exception {
    DateMidnight NOW = new DateMidnight();
    Customer customer = createCustomerBasic();
    Account account =customer.getAccounts().iterator().next();
    customer.setDateOfBirth(NOW.minusYears(40).toDate());
    assertEquals(Account.Type.TRANSACTIONAL,
         account.getType());
    assertNotReportContains(Message.Type.ERROR,
        "studentAccountCustomerAgeLessThan", customer);

    account.setType(Account.Type.STUDENT);
    assertReportContains(Message.Type.ERROR,
        "studentAccountCustomerAgeLessThan",customer,account);

    customer.setDateOfBirth(NOW.minusYears(20).toDate());
    assertNotReportContains(Message.Type.ERROR,
        "studentAccountCustomerAgeLessThan", customer);
  }

  // @extract-end

  // @extract-start 03 71
  @Test
  public void accountNumberUnique() throws Exception {
    Customer customer = createCustomerBasic();
    Account account = customer.getAccounts().iterator()
        .next();
    session.setGlobal("inquiryService",
        new BankingInquiryServiceImpl() {
          @Override
          public boolean isAccountNumberUnique(
              Account accout) {
            return false;
          }
        });
    assertReportContains(Message.Type.ERROR,
        "accountNumberUnique", customer, account);
  }
  // @extract-end

}


text:
« CSS « CSS Reference   « CSS Reference:Mozilla Extensions

Summary

-moz-padding-start specifies the logical start padding for an element. The computed value of the element's direction property then determines how the padding is translated to a physical padding. If the computed direction is left-to-right ("ltr") then -moz-padding-start sets the left padding; otherwise it sets the right padding.

See also
-moz-padding-end

Initial value
: 0

Applies to: all elements except table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column

Inherited
: no

Percentages: refer to
width of closest block-level ancestor

Media:
visual

Computed value
: the percentage as specified or the absolute length

Syntax

-moz-padding-start:

<length> |
<percentage> |
inherit |
auto;

Values

<length>

Specifies a fixed width.

<percentage>

A percentage with respect to the width of the containing block.

Examples

View Live Examples

  .content {
    -moz-padding-start: 5%;
  }

  .sidebox {
    -moz-padding-start: 10px;
  }

Notes

Specifications

Not yet candidate for Specifications

CSS 3 Writing Modes

Browser Compatibility

Browser	 Lowest version

Internet Explorer	 --

Firefox (Gecko)	  Firefox 3 (1.9) (-moz-padding-start)

Opera	 --

Safari | Chrome | WebKit

3 | 2 | 528.17 (-webkit-padding-start)

See also

padding,
padding-top,
padding-right,
padding-bottom,
padding-left,
-moz-padding-start,
-moz-padding-end,
border,
margin


text:
class AndroidNdk < Formula
  desc "Android native-code language toolset"
  homepage "https://developer.android.com/sdk/ndk/index.html"
  if OS.mac?
    url "https://dl.google.com/android/repository/android-ndk-r11c-darwin-x86_64.zip"
    sha256 "fe2f8986074717240df45f03e93a4436dac2040dc12fecee4853953d584424b3"
  elsif OS.linux?
    url "https://dl.google.com/android/repository/android-ndk-r11c-linux-x86_64.zip"
    sha256 "ba85dbe4d370e4de567222f73a3e034d85fc3011b3cbd90697f3e8dcace3ad94"
  end
  version "r11c"

  bottle :unneeded

  # As of r10e, only a 64-bit version is provided
  depends_on :arch => :x86_64
  depends_on "android-sdk" => :recommended

  conflicts_with "crystax-ndk",
    :because => "both install `ndk-build`, `ndk-gdb` and `ndk-stack` binaries"

  def install
    bin.mkpath

    # Now we can install both 64-bit and 32-bit targeting toolchains
    prefix.install Dir["*"]

    # Create a dummy script to launch the ndk apps
    ndk_exec = prefix+"ndk-exec.sh"
    ndk_exec.write <<-EOS.undent
      #!/bin/sh
      BASENAME=`basename $0`
      EXEC="#{prefix}/$BASENAME"
      test -f "$EXEC" && exec "$EXEC" "$@"
    EOS
    ndk_exec.chmod 0755
    %w[ndk-build ndk-depends ndk-gdb ndk-stack ndk-which].each { |app| bin.install_symlink ndk_exec => app }
  end

  def caveats; <<-EOS.undent
    We agreed to the Android NDK License Agreement for you by downloading the NDK.
    If this is unacceptable you should uninstall.

    License information at:
    https://developer.android.com/sdk/terms.html

    Software and System requirements at:
    https://developer.android.com/sdk/ndk/index.html#requirements

    For more documentation on Android NDK, please check:
      #{prefix}/docs
    EOS
  end
end


text:
package br.com.softbox.dao;

import java.util.List;

import br.com.softbox.model.Pergunta;
import br.com.softbox.model.Opcao;

public interface OpcaoDAO {

	public void salvar(Opcao opcao);

	public void excluir(Opcao opcao);

	public Pergunta carregar(long identificador);

	public List<Opcao> listar(Pergunta pergunta);

	public List<Opcao> listar();
}


text:
package io.seldon.api.resource.service;

import io.seldon.api.APIException;
import io.seldon.api.Constants;
import io.seldon.api.Util;
import io.seldon.api.caching.ActionHistoryCache;
import io.seldon.api.logging.ActionLogger;
import io.seldon.api.logging.CtrFullLogger;
import io.seldon.api.logging.CtrLogger;
import io.seldon.api.resource.ActionBean;
import io.seldon.api.resource.ActionTypeBean;
import io.seldon.api.resource.ConsumerBean;
import io.seldon.api.resource.ItemBean;
import io.seldon.api.resource.ListBean;
import io.seldon.api.resource.ResourceBean;
import io.seldon.api.resource.UserBean;
import io.seldon.api.resource.service.exception.ActionTypeNotFoundException;
import io.seldon.api.service.async.AsyncActionQueue;
import io.seldon.api.service.async.JdoAsyncActionFactory;
import io.seldon.api.state.ClientAlgorithmStore;
import io.seldon.api.state.options.DefaultOptions;
import io.seldon.api.statsd.StatsdPeer;
import io.seldon.clustering.recommender.ClientClusterTypeService;
import io.seldon.clustering.recommender.CountRecommender;
import io.seldon.clustering.recommender.RecommendationContext;
import io.seldon.clustering.recommender.jdo.JdoCountRecommenderUtils;
import io.seldon.general.Action;
import io.seldon.general.ActionType;
import io.seldon.general.Item;
import io.seldon.general.User;
import io.seldon.memcache.MemCacheKeys;
import io.seldon.memcache.MemCachePeer;
import io.seldon.recommendation.AlgorithmStrategy;
import io.seldon.recommendation.LastRecommendationBean;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author claudio
 */

@Service
public class ActionService {

	private static final String BUCKET_CLUSTER_OPTION_NAME = "io.seldon.algorithm.clusters.usebucketcluster";
	private static final String FULL_ACTION_STORE_OPTION_NAME = "io.seldon.algorithm.actions.storefullactions";
    private static Logger logger = Logger.getLogger(ActionService.class.getName());

	@Autowired
	private ClientClusterTypeService clusterTypeService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private UserService userService;

    @Autowired
    private ClientAlgorithmStore clientAlgorithmStore;

    @Autowired
    private DefaultOptions defaultOptions;

    @Autowired
    private JdoAsyncActionFactory asyncActionFactory;

    @Autowired
    JdoCountRecommenderUtils cUtils;

    @Autowired
    ActionHistoryCache actionCache;

    public ListBean getUserActions(ConsumerBean c, String userId, int limit, boolean full) throws APIException {
        ListBean bean = new ListBean();
        String clientName = c.getShort_name();
        int numActions = limit;
        long internalUserId = userService.getInternalUserId(c, userId);
        List<Long> recentActionsItemIdList = actionCache.getRecentActions(clientName, internalUserId, numActions);
        for (Long internalItemId : recentActionsItemIdList) {
            String clientItemId = itemService.getClientItemId(c, internalItemId);
            ActionBean actionBean = new ActionBean(null, userId, clientItemId, 1, null, null, 0);
            bean.addBean(actionBean);
        }
        return bean;
    }

	public ListBean getItemActions(ConsumerBean c, String itemId, int limit, boolean full) throws APIException {
		ListBean bean = (ListBean) MemCachePeer.get(MemCacheKeys.getItemActionsBeanKey(c.getShort_name(), itemId, full, false));
		bean = Util.getLimitedBean(bean, limit);
		if(bean == null) {
			bean = new ListBean();
			Collection<Action> res = Util.getActionPeer(c).getItemActions(itemService.getInternalItemId(c, itemId), limit);
			for(Action a : res) { bean.addBean(new ActionBean(a,c,full)); }
			if(Constants.CACHING) MemCachePeer.put(MemCacheKeys.getItemActionsBeanKey(c.getShort_name(), itemId, full, false),bean,Constants.CACHING_TIME);
		}
		return bean;
	}

	public ListBean getActions(ConsumerBean c, String userId, String itemId, int limit, boolean full) throws APIException {
		ListBean bean = (ListBean)MemCachePeer.get(MemCacheKeys.getUserItemActionBeanKey(c.getShort_name(), userId, itemId, full, false));
		bean = Util.getLimitedBean(bean, limit);
		if(bean == null) {
			bean = new ListBean();
			Collection<Action> res = Util.getActionPeer(c).getUserItemActions(itemService.getInternalItemId(c, itemId), userService.getInternalUserId(c, userId), limit);
			for(Action a : res) { bean.addBean(new ActionBean(a,c,full)); }
			if(Constants.CACHING) MemCachePeer.put(MemCacheKeys.getUserItemActionBeanKey(c.getShort_name(), userId, itemId, full, false),bean,Constants.CACHING_TIME);
		}
		return bean;
	}

	public static ListBean getActions(ConsumerBean c, long userId, long itemId, int limit, boolean full) throws APIException {
		ListBean bean = (ListBean)MemCachePeer.get(MemCacheKeys.getInternalUserItemActionBeanKey(c.getShort_name(), userId, itemId, full, false));
		bean = Util.getLimitedBean(bean, limit);
		if(bean == null) {
			bean = new ListBean();
			Collection<Action> res = Util.getActionPeer(c).getUserItemActions(itemId, userId, limit);
			for(Action a : res) { bean.addBean(new ActionBean(a,c,full)); }
			if(Constants.CACHING) MemCachePeer.put(MemCacheKeys.getInternalUserItemActionBeanKey(c.getShort_name(), userId, itemId, full, false),bean,Constants.CACHING_TIME);
		}
		return bean;
	}

// TODO: setup another memcache key for a specific action type?
//	public static ListBean getActions(ConsumerBean c, String userId, String itemId, int type, int limit, boolean full) throws APIException {
//		ListBean bean = (ListBean)MemCachePeer.get(MemCacheKeys.getUserItemActionBeanKey(c.getShort_name(), userId, itemId, full));
//		bean = Util.getLimitedBean(bean, limit);
//		if(bean == null) {
//			bean = new ListBean();
//			Collection<Action> res = Util.getActionPeer(c).getUserItemActions(ItemService.getInternalItemId(c, itemId), UserService.getInternalUserId(c, userId), limit);
//			for(Action a : res) { bean.addBean(new ActionBean(a,c,full)); }
//			if(Constants.CACHING) MemCachePeer.put(MemCacheKeys.getUserItemActionBeanKey(c.getShort_name(), userId, itemId, full),bean,Constants.CACHING_TIME);
//		}
//		return bean;
//	}

	public static ActionBean getAction(ConsumerBean c,long actionId,boolean full) throws APIException  {
		ActionBean bean =  (ActionBean)MemCachePeer.get(MemCacheKeys.getActionBeanKey(c.getShort_name(), actionId, full, false));
		if(bean==null) {
			Action a = Util.getActionPeer(c).getAction(actionId);
			bean = new ActionBean(a,c,full);
			if(Constants.CACHING) MemCachePeer.put(MemCacheKeys.getActionBeanKey(c.getShort_name(), actionId, full, false),bean,Constants.CACHING_TIME);
		}
		return bean;
	}

	public static ResourceBean getRecentActions(ConsumerBean c,int limit,boolean full) throws APIException {
			ListBean bean = new ListBean();
			Collection<Action> res = Util.getActionPeer(c).getRecentActions(limit);
			for(Action a : res) { bean.addBean(new ActionBean(a,c,full)); }
		return bean;
	}

	public void addAction(ConsumerBean c,ActionBean bean) {

		AsyncActionQueue q = null;
		if (asyncActionFactory != null)
			q = asyncActionFactory.get(c.getShort_name());
		boolean doAsyncAction = q != null;

		//check if user and item exist
		//if not it adds them to the db
		Long userId = null;
		Long itemId = null;

		try
		{
			itemId = itemService.getInternalItemId(c, bean.getItem());
		}
		catch(APIException e)
		{
			if (!doAsyncAction || !JdoAsyncActionFactory.isAsyncItemWrites())
			{
				if(e.getError_id()==APIException.ITEM_NOT_FOUND)
				{
					//TODO - addItem can throw an exception if item is now already created - change?
					try
					{
						Item item = itemService.addItem(c, new ItemBean(bean.getItem()));
						itemId = item.getItemId();
					}
					catch (APIException e2)
					{
						if(e2.getError_id()==APIException.ITEM_DUPLICATED)
							itemId = itemService.getInternalItemId(c, bean.getItem());
						else
							throw e2;
					}
				}
				else
					throw e;
			}
			else
				itemId=0L;
		};

		try
		{
			userId = userService.getInternalUserId(c, bean.getUser());
		}
		catch(APIException e)
		{
			if (!doAsyncAction || !JdoAsyncActionFactory.isAsyncUserWrites())
			{
				if(e.getError_id()==APIException.USER_NOT_FOUND)
				{
					//TODO - addUser can throw an exception if user is now already created - change?
					try
					{
						User user = userService.addUser(c, new UserBean(bean.getUser()));
						userId = user.getUserId();
					}
					catch(APIException e2)
					{
						if(e2.getError_id()==APIException.USER_DUPLICATED)
							userId = userService.getInternalUserId(c, bean.getUser());
						else
							throw e2;
					}
				}
				else
					throw e;
			}
			else
				userId=0L;

		};

		if (userId != null && itemId != null)
		{
			Action a = bean.createAction(c,userId,itemId);
			if (logger.isDebugEnabled())
				logger.debug("Action created with Async "+doAsyncAction+" for client "+c.getShort_name()+" userId:"+userId+" itemId:"+itemId+" clientUserId:"+a.getClientUserId()+" clientItemId:"+a.getClientItemId());

			ActionLogger.log(c.getShort_name(), userId, itemId, a.getType(), a.getValue(), a.getClientUserId(), a.getClientItemId(), bean.getRecTag());

			if(doAsyncAction)
			{
				q.put(a);
			}
			else
			{
				Util.getActionPeer(c).addAction(a);
			}

			//Add to count recommender if applicable to client and action cache
			if (userId > 0 && itemId > 0)
			{

                boolean useBucketCluster = false;
                boolean storeFullActions = false;
				CountRecommender cRec = cUtils.getCountRecommender(c.getShort_name());
                for (AlgorithmStrategy strat : clientAlgorithmStore.retrieveStrategy(c.getShort_name()).getAlgorithms(a.getClientUserId(), bean.getRecTag())){
                    RecommendationContext.OptionsHolder holder = new RecommendationContext.OptionsHolder(defaultOptions, strat.config);
                    if (holder.getBooleanOption(BUCKET_CLUSTER_OPTION_NAME)) {
                        useBucketCluster = true;
                    }
                    if (holder.getBooleanOption(FULL_ACTION_STORE_OPTION_NAME)) {
                        storeFullActions = true;
                    }
                }

				if (cRec != null)
				{
					boolean addCount = true;
					if (a.getType() != null)
						addCount = clusterTypeService.okToClusterCount(c.getShort_name(), a.getType());
					if (addCount)
					{
						Map<Integer,Double> actionWeights = clientAlgorithmStore.retrieveStrategy(c.getShort_name()).getActionsWeights(a.getClientUserId(), bean.getRecTag());
						Double actionWeight = actionWeights.get(a.getType());
						if (bean.getReferrer() != null)
							cRec.setReferrer(bean.getReferrer());
						if (a.getDate() != null)
							cRec.addCount(userId, itemId,a.getDate().getTime()/1000, useBucketCluster,actionWeight);
						else
							cRec.addCount(userId, itemId, useBucketCluster,actionWeight);
					}
				}

				actionCache.addAction(c.getShort_name(),userId, itemId);
				if (storeFullActions)
					actionCache.addFullAction(c.getShort_name(), a);

			}
		}
		else {
//			logger.error("UserId or ItemId is null when adding action "+bean);
            final String message = "UserId or ItemId is null when adding action " + bean;
            logger.error(message, new Exception(message));
        }
	}

	public static ActionType getActionType(ConsumerBean c, String name) throws ActionTypeNotFoundException {
        String actionTypeKey = MemCacheKeys.getActionTypeByName(c.getShort_name(), name);
        ActionType at = (ActionType) MemCachePeer.get(actionTypeKey);
		if(at==null) {
			at = Util.getActionPeer(c).getActionType(name);
            if ( at == null ) {
                throw new ActionTypeNotFoundException(c.getShort_name(), name);
            }
			MemCachePeer.put(actionTypeKey, at,Constants.CACHING_TIME);
		}
		return at;
	}

	public static ActionType getActionType(ConsumerBean c, int typeId) {
		ActionType at = (ActionType) MemCachePeer.get(MemCacheKeys.getActionTypeById(c.getShort_name(), typeId));
		if(at==null) {
			at = Util.getActionPeer(c).getActionType(typeId);
			MemCachePeer.put(MemCacheKeys.getActionTypeById(c.getShort_name(), typeId), at, Constants.CACHING_TIME);
		}
		return at;
	}

	public static ResourceBean getActionTypes(ConsumerBean c) {
		ListBean bean = (ListBean)MemCachePeer.get(MemCacheKeys.getActionTypes(c.getShort_name()));
		if(bean == null) {
			bean = new ListBean();
			Collection<ActionType> types = Util.getActionPeer(c).getActionTypes();
			for(ActionType t : types) { bean.addBean(new ActionTypeBean(t)); }
			MemCachePeer.put(MemCacheKeys.getActionTypes(c.getShort_name()), bean,Constants.CACHING_TIME);
		}
			return bean;
	}

    public void logAction(ConsumerBean consumerBean, ActionBean actionBean, LastRecommendationBean lastRecs, int clickIndex,
                          String recTag, String recsCounter) {
        StatsdPeer.logClick(consumerBean.getShort_name(), recTag);
        String stratName = clientAlgorithmStore.retrieveStrategy(consumerBean.getShort_name()).getName(actionBean.getUser(), recTag);
        CtrFullLogger.log(true, consumerBean.getShort_name(), actionBean.getUser(),
                actionBean.getItem(), recTag);
        String algorithmsString = lastRecs==null? "UNKNOWN": lastRecs.getAlgorithm();
        CtrLogger.log(true, consumerBean.getShort_name(), algorithmsString,
                clickIndex, actionBean.getUser(), recsCounter,
                itemService.getInternalItemId(consumerBean,actionBean.getItem()), 0, "", stratName, recTag);

    }
}


text:
"""A simple example of connecting to Earth Engine using App Engine."""

# Works in the local development environment and when deployed.
# If successful, shows a single web page with the SRTM DEM
# displayed in a Google Map.  See accompanying README file for
# instructions on how to set up authentication.

import os

import config
import ee
import jinja2
import webapp2

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainPage(webapp2.RequestHandler):

  def get(self):                             # pylint: disable=g-bad-name
    """Request an image from Earth Engine and render it to a web page."""
    ee.Initialize(config.EE_CREDENTIALS)
    mapid = ee.Image('srtm90_v4').getMapId({'min': 0, 'max': 1000})

    # These could be put directly into template.render, but it
    # helps make the script more readable to pull them out here, especially
    # if this is expanded to include more variables.
    template_values = {
        'mapid': mapid['mapid'],
        'token': mapid['token']
    }
    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)


text:
Document 'WithoutInstanceName' {
    $InstanceName;
    $TargetObject.Object.Name;
    $TargetObject.Hashtable.Name;
}

# Synopsis: Document for unit testing
Document 'WithInstanceName' {
    $InstanceName;
}

# Synopsis: Document for unit testing
document 'WithMultiInstanceName' {
    $InstanceName;
}

# Synopsis: Document for unit testing
document 'WithEncoding' {
    $InstanceName;
}

# Synopsis: Document for unit testing
document 'WithPassThru' {
    $InstanceName;
}

# Synopsis: Document for unit testing
document 'WithMetadata' {
    Metadata @{
        key1 = 'value1'
    }
    Section 'Test' -Force {
    }
}


text:
var reader  = require('./reader');
var program = require('commander');
var util    = require('util');

program
  .version('0.0.1')
  .usage('[options] <file ...>')
  .parse(process.argv);

program.on('--help', function(){
  console.log('  Examples:');
  console.log('');
  console.log('    $ reader index.html');
  console.log('');
});

program.parse(process.argv);

for (var fileIndex = 0; fileIndex < program.args.length; fileIndex++) {
  console.log(util.inspect(reader.readFile(program.args[fileIndex]), {
    showHidden: false,
    depth: null
  }));
}


text: IRenderPass::~IRenderPass() {}


text:
import * as THREE from 'three';
import 'whatwg-fetch';

import Config from '../../data/config';
import Helpers from '../../utils/helpers';

export default class SoundObject {
  constructor(main) {
    this.type = 'SoundObject';
    this.posX = 0;
    this.posY = 0;
    this.posZ = 0;
    this.radius = Config.soundObject.defaultRadius;
    this.cones = [];
    this.audio = main.audio;
    this.gui = main.gui;

    this.trajectory = null;
    this.trajectoryClock = Config.soundObject.defaultTrajectoryClock;
    this.movementSpeed = Config.soundObject.defaultMovementSpeed;
    this.movementDirection = Config.soundObject.defaultMovementDirection;
    this.movementIncrement = null;

    this.containerObject = new THREE.Object3D();

    const sphereGeometry = new THREE.SphereBufferGeometry(this.radius, 100, 100);
    const sphereMaterial = new THREE.MeshBasicMaterial({
      color: 0xFFFFFF,
      opacity: 0.8,
      transparent: true,
      premultipliedAlpha: true
    });
    this.omniSphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
    this.omniSphere.name = 'omniSphere';
    this.omniSphere.castShadow = true;

    const raycastSphereGeometry = new THREE.SphereBufferGeometry(150, 100, 100);
    const raycastSphereMaterial = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, visible: false });
    this.raycastSphere = new THREE.Mesh(raycastSphereGeometry, raycastSphereMaterial);
    this.raycastSphere.name = 'sphere';
    this.raycastSphere.position.copy(main.mouse);
    main.scene.add(this.raycastSphere);

    this.axisHelper = new THREE.AxisHelper(100);
    this.axisHelper.position.copy(main.mouse);
    main.scene.add(this.axisHelper);

    const lineMaterial = new THREE.LineDashedMaterial({
      color: 0x888888,
      dashSize: 30,
      gapSize: 30,
    });
    const lineGeometry = new THREE.Geometry();

    lineGeometry.vertices.push(
      new THREE.Vector3(0, 0, -300),
      new THREE.Vector3(0, 0, 300),
    );

    lineGeometry.computeLineDistances();
    this.altitudeHelper = new THREE.Line(lineGeometry, lineMaterial);
    this.altitudeHelper.rotation.x = Math.PI / 2;
    main.scene.add(this.altitudeHelper);
    this.altitudeHelper.position.copy(main.mouse);

    this.containerObject.add(this.omniSphere);
    this.containerObject.position.copy(main.mouse);
    main.scene.add(this.containerObject);
  }

  createCone(sound, color = null) {
    sound.volume.gain.value = 1;
    sound.spread = 0.5;

    const coneWidth = sound.spread * 90;
    const coneHeight = sound.volume.gain.value * 50 + 50;

    const coneGeo = new THREE.CylinderGeometry(coneWidth, 0, coneHeight, 100, 1, true);
    const randGreen = color !== null ? color : Math.random();
    const randBlue = color !== null ? color : Math.random();
    //const coneColor = new THREE.Color(0.5, randGreen, randBlue);
    const coneColor = new THREE.Color();
    coneColor.setHSL(randGreen, randBlue, 0.8);
    const coneMaterial = new THREE.MeshBasicMaterial({
      color: coneColor,
      opacity: 0.8,
      transparent:true
    });

    coneGeo.translate(0, coneHeight / 2, 0);
    coneGeo.rotateX(Math.PI / 2);
    coneMaterial.side = THREE.DoubleSide;

    const cone = new THREE.Mesh(coneGeo, coneMaterial);

    cone.randGreen = randGreen;
    cone.sound = sound;
    cone.sound.panner.coneInnerAngle = Math.atan(coneWidth / coneHeight) * (180 / Math.PI);
    cone.sound.panner.coneOuterAngle = cone.sound.panner.coneInnerAngle * 3;
    cone.sound.panner.coneOuterGain = 0.05;
    // cone.sound.volume.gain.value = Helpers.mapRange(coneHeight, 100, 150, 0.5, 2);

    cone.name = 'cone';
    cone.baseColor = coneColor;
    cone.hoverColor = function() {
      let c = this.baseColor.clone();
      c.offsetHSL(0,-0.05,0.1);
      return c;
    }

    sound.scriptNode.onaudioprocess = function() {
      let array =  new Uint8Array(sound.analyser.frequencyBinCount);
      sound.analyser.getByteFrequencyData(array);
      let values = 0;
      let length = array.length;
      for (let i = 0; i < length; i++) values += array[i];
      let average = values / length;
      cone.material.opacity = Helpers.mapRange(average, 50, 100, 0.65, 0.95);
    }

    cone.long = cone.lat = 0;

    this.cones.push(cone);
    this.containerObject.add(cone);
    this.setAudioPosition(cone);
    return cone;
  }

  setAudioPosition(object) {
    const o = new THREE.Vector3();
    object.updateMatrixWorld();
    o.setFromMatrixPosition(object.matrixWorld);
    object.sound.panner.setPosition(o.x, o.y, o.z);

    if (object.name == 'cone') {
      const p = new THREE.Vector3();
      const q = new THREE.Vector3();
      const m = object.matrixWorld;

      const mx = m.elements[12];
      const my = m.elements[13];
      const mz = m.elements[14];

      const vec = new THREE.Vector3(0, 0, 1);

      m.elements[12] = m.elements[13] = m.elements[14] = 0;

      vec.applyMatrix4(m);
      vec.normalize();
      object.sound.panner.setOrientation(vec.x, vec.y, vec.z);

      m.elements[12] = mx;
      m.elements[13] = my;
      m.elements[14] = mz;
    }
  }

  loadSound(file, audio, mute, object) {
    const context = audio.context;
    const mainMixer = context.createGain();
    let reader = new FileReader();
    var sound = {};

    if (object) { // cones can be null at this point
      object.filename = file.name;
      object.file = file;
    }

    let promise = new Promise(function(resolve, reject) {
      reader.onload = (ev) => {
        context.decodeAudioData(ev.target.result, function(decodedData) {
          if (object && object.type === 'SoundObject') {
            /* attach omnidirectional sound */
            object = object.omniSphere;
          }

          if (object && object.sound) {
            object.sound.source.stop();
            object.sound.source.disconnect(object.sound.scriptNode);
            object.sound.scriptNode.disconnect(context.destination);
          }

          sound.mainMixer = mainMixer;

          sound.analyser = context.createAnalyser();
          sound.analyser.smoothingTimeConstant = 0.5;
          sound.analyser.fftSize = 1024;

          sound.scriptNode = context.createScriptProcessor(2048, 1, 1);
          sound.scriptNode.connect(context.destination);

          sound.source = context.createBufferSource();
          sound.source.loop = true;
          sound.source.connect(sound.scriptNode);

          sound.panner = context.createPanner();
          sound.panner.panningModel = 'HRTF';
          sound.panner.distanceModel = 'inverse';
          sound.panner.refDistance = 100;

          // sound.panner.rolloffFactor = 5;

          sound.volume = context.createGain();
          sound.source.connect(sound.volume);
          sound.volume.connect(sound.analyser);
          sound.volume.connect(sound.panner);
          sound.panner.connect(mainMixer);
          mainMixer.connect(audio.destination);
          mainMixer.gain.value = mute ? 0 : 1;

          sound.source.buffer = decodedData;
          sound.source.start(context.currentTime + 0.020);

          if (object && object.name === 'omniSphere') {
            sound.scriptNode.onaudioprocess = () => {
              const array = new Uint8Array(sound.analyser.frequencyBinCount);
              sound.analyser.getByteFrequencyData(array);
              let values = 0;
              const length = array.length;
              for (let i = 0; i < length; i++) values += array[i];
              const average = values / length;
              object.material.opacity = Helpers.mapRange(average, 50, 100, 0.65, 0.95);
            };
          }

          resolve(sound);
        });
      };

      reader.readAsArrayBuffer(file);
    });

    return promise;
  }

  isUnderMouse(ray) {
    return ray.intersectObject(this.containerObject, true).length > 0;
  }

  select(main) {
    this.nonScaledMouseOffsetY = main.nonScaledMouse.y;
  }

  move(main) {
    let pointer;

    if (main.perspectiveView) {
      const posY = Helpers.mapRange(
        main.nonScaledMouse.y - this.nonScaledMouseOffsetY,
        -0.5,
        0.5,
        -200,
        200,
      );

      pointer = this.containerObject.position;
      if (pointer.y > -200 || pointer.y < 200) pointer.y += posY;

      // clamp
      pointer.y = Math.max(Math.min(pointer.y, 300), -300);

      this.nonScaledMouseOffsetY = main.nonScaledMouse.y;
    } else {
      pointer = main.mouse;
      pointer.y = this.containerObject.position.y;
    }

    if (this.trajectory) this.trajectory.move(pointer, main.nonScaledMouse, main.perspectiveView);

    this.setPosition(pointer);
  }

  setPosition(position) {
    this.containerObject.position.copy(position);
    this.axisHelper.position.copy(position);
    this.altitudeHelper.position.copy(position);
    this.altitudeHelper.position.y = 0;
    this.raycastSphere.position.copy(position);

    if (this.cones[0]) {
      for (const i in this.cones) {
        this.setAudioPosition(this.cones[i]);
      }
    }

    if (this.omniSphere.sound){
      this.setAudioPosition(this.omniSphere);
    }
  }

  addToScene(scene) {
    scene.add(this.containerObject);
  }

  setActive(main) {
    if (this.trajectory) {
      this.trajectory.setActive();
      this.trajectory.setMouseOffset(main.nonScaledMouse, main.mouse);
    }
  }

  setInactive() {
    if (this.trajectory) {
      this.trajectory.setInactive();
    }
  }

  changeRadius() {
    if (this.omniSphere.sound && this.omniSphere.sound.volume) {
      const r = 0.5 + 0.5*this.omniSphere.sound.volume.gain.value;
      this.omniSphere.scale.x = this.omniSphere.scale.y = this.omniSphere.scale.z = r;
    }
    else {
      this.omniSphere.scale.x = this.omniSphere.scale.y = this.omniSphere.scale.z = 1;
    }
  }

  changeLength(cone) {
    const r = cone.sound.spread * 90;
    const l = cone.sound.volume.gain.value * 50 + 50;
    cone.sound.panner.coneInnerAngle = Math.atan( r / l) * (180 / Math.PI);
    cone.sound.panner.coneOuterAngle = cone.sound.panner.coneInnerAngle * 1.5;

    cone.geometry.dynamic = true;

    let circVertices = cone.geometry.vertices.slice(0,-1);
    let origin = cone.geometry.vertices[cone.geometry.vertices.length-1];

    circVertices.forEach(vertex => {
      let v = new THREE.Vector3().subVectors(vertex, origin).normalize();
      vertex.copy(origin.clone().addScaledVector(v, l));
    })

    cone.geometry.verticesNeedUpdate = true;
  }

  changeWidth(cone) {
    const r = cone.sound.spread * 90;
    const l = cone.sound.volume.gain.value * 50 + 50;
    cone.sound.panner.coneInnerAngle = Math.atan( r / l) * (180 / Math.PI);
    cone.sound.panner.coneOuterAngle = cone.sound.panner.coneInnerAngle * 3;

    cone.geometry.dynamic = true;

    let circVertices = cone.geometry.vertices.slice(0,-1);
    let center = new THREE.Vector3();
    center.lerpVectors(circVertices[0], circVertices[Math.round(circVertices.length/2)], 0.5);

    circVertices.forEach(vertex => {
      let v = new THREE.Vector3().subVectors(vertex, center).normalize();
      vertex.copy(center.clone().addScaledVector(v, r));
    })

    cone.geometry.verticesNeedUpdate = true;
  }

  pointCone(cone, point) {
    const coneRotation = new THREE.Vector3();
    coneRotation.subVectors(point, this.containerObject.position);
    cone.lookAt(coneRotation);
    this.setAudioPosition(cone);

    const longlat = (function( vector3 ) {
        // taken from https://gist.github.com/nicoptere/2f2571db4b454bb18cd9
        vector3.normalize();

        //longitude = angle of the vector around the Y axis
        //-( ) : negate to flip the longitude (3d space specific )
        //- PI / 2 to face the Z axis
        var lng = -( Math.atan2( -vector3.z, -vector3.x ) ) - Math.PI / 2;

        //to bind between -PI / PI
        if( lng < - Math.PI )lng += Math.PI*2;

        //latitude : angle between the vector & the vector projected on the XZ plane on a unit sphere

        //project on the XZ plane
        var p = new THREE.Vector3( vector3.x, 0, vector3.z );
        //project on the unit sphere
        p.normalize();

        //compute the angle ( both vectors are normalized, no division by the sum of lengths )
        var lat = Math.acos( p.dot( vector3 ) );

        //invert if Y is negative to ensure the latitude is between -PI/2 & PI / 2
        if( vector3.y < 0 ) lat *= -1;

        return [ lng,lat ];

      })( coneRotation );
    cone.long = longlat[0];
    cone.lat = longlat[1];
  }

  // Needs to be refactored - also lives in guiwindow
  pointConeMagic(cone, lat, long) {
    // adapted from https://gist.github.com/nicoptere/2f2571db4b454bb18cd9
    const v = (function lonLatToVector3( lng, lat )
      {
      //flips the Y axis
      lat = Math.PI / 2 - lat;

      //distribute to sphere
      return new THREE.Vector3(
        Math.sin( lat ) * Math.sin( lng ),
        Math.cos( lat ),
        Math.sin( lat ) * Math.cos( lng )
      );

      })( long, lat );
    if (v.x === 0) { v.x = 0.0001; }
    const point = this.containerObject.position.clone().add(v);
    this.pointCone(cone, point);

  }

  applySoundToCone(cone, sound) {

    sound.scriptNode.onaudioprocess = function() {
      let array =  new Uint8Array(sound.analyser.frequencyBinCount);
      sound.analyser.getByteFrequencyData(array);
      let values = 0;
      let length = array.length;
      for (let i = 0; i < length; i++) values += array[i];
      let average = values / length;
      cone.material.opacity = Helpers.mapRange(average, 50, 100, 0.65, 0.95);
    }

    sound.spread = cone.sound.spread;
    sound.panner.refDistance = cone.sound.panner.refDistance;
    sound.panner.distanceModel = cone.sound.panner.distanceModel;
    sound.panner.coneInnerAngle = cone.sound.panner.coneInnerAngle;
    sound.panner.coneOuterAngle = cone.sound.panner.coneOuterAngle;
    sound.panner.coneOuterGain = cone.sound.panner.coneOuterGain;
    sound.volume.gain.value = cone.sound.volume.gain.value;
    cone.sound = sound;
  }

  removeCone(cone) {
    cone.sound.source.stop();
    cone.sound.source.disconnect(cone.sound.scriptNode);
    cone.sound.scriptNode.disconnect(this.audio.context.destination);
    cone.sound = null;
    const i = this.cones.indexOf(cone);
    this.cones.splice(i, 1);
    this.containerObject.remove(cone);
  }

  removeFromScene(scene) {
    scene.remove(this.containerObject, true);
    scene.remove(this.altitudeHelper, true);
    scene.remove(this.axisHelper, true);
    scene.remove(this.trajectory, true);

    for (const i in this.cones) {
      this.cones[i].sound.source.stop();
    }

    if (this.omniSphere.sound && this.omniSphere.sound.source) {
      this.omniSphere.sound.source.stop();
    }
  }

  pause() {
    this.isPaused = true;
  }
  unpause() {
    this.isPaused = false;
  }

  mute(main) {
    this.isMuted = true;
    this.checkMuteState(main);
  }
  unmute(main) {
    this.isMuted = false;
    this.checkMuteState(main);
  }

  turnVisible() {
    this.containerObject.visible = true;
    this.axisHelper.visible = true;
    this.altitudeHelper.visible = true;
  }

  turnInvisible() {
    this.containerObject.visible = false;
    this.axisHelper.visible = false;
    this.altitudeHelper.visible = false;
  }

  checkMuteState(main) {
    if (main.isMuted || this.isMuted) {
      this.cones.forEach(cone => cone.sound.mainMixer.gain.value = 0);
      if (this.omniSphere.sound && this.omniSphere.sound.mainMixer) {
        this.omniSphere.sound.mainMixer.gain.value = 0;
      }
    }
    else {
      this.cones.forEach(cone => cone.sound.mainMixer.gain.value = 1);
      if (this.omniSphere.sound && this.omniSphere.sound.mainMixer) {
        this.omniSphere.sound.mainMixer.gain.value = 1;
      }
    }
  }

  followTrajectory(mute) {
    if (this.trajectory && !this.isPaused && !this.isMuted && !mute) {
      this.trajectoryClock -= this.movementDirection * this.movementIncrement;

      if (this.trajectoryClock >= 1) {
        if (this.trajectory.spline.closed) {
          this.trajectoryClock = 0;
        } else {
          this.movementDirection = -this.movementDirection;
          this.trajectoryClock = 1;
        }
      }

      if (this.trajectoryClock < 0) {
        if (this.trajectory.spline.closed) {
          this.trajectoryClock = 1;
        } else {
          this.movementDirection = -this.movementDirection;
          this.trajectoryClock = 0;
        }
      }

      let pointOnTrajectory = this.trajectory.spline.getPointAt(this.trajectoryClock);
      this.containerObject.position.copy(pointOnTrajectory);
      this.raycastSphere.position.copy(pointOnTrajectory);
      this.altitudeHelper.position.copy(pointOnTrajectory);
      this.axisHelper.position.copy(pointOnTrajectory);
      this.altitudeHelper.position.y = 0;

      if (this.cones[0]) {
        for (const i in this.cones) {
          this.setAudioPosition(this.cones[i]);
        }
      }
      if (this.omniSphere.sound) {
        this.setAudioPosition(this.omniSphere);
      }
    }
  }

  calculateMovementSpeed() {
    if (this.trajectory) {
      this.movementIncrement = this.movementSpeed / this.trajectory.spline.getLength(10);
    }
  }

  toJSON() {
    return JSON.stringify({
      filename: (this.omniSphere.sound && this.omniSphere.sound && this.omniSphere.sound.name) || null,
      volume: (this.omniSphere && this.omniSphere.sound && this.omniSphere.sound.volume.gain.value) || null,
      position: this.containerObject.position,
      movementSpeed: this.movementSpeed,
      trajectory: (this.trajectory && this.trajectory.points) || null,
      cones: this.cones.map((c) => {
        return {
          file: c.file,
          filename: c.filename,
          position: {
            lat: c.lat,
            long: c.long,
          },
          volume: c.sound.volume.gain.value,
          spread: c.sound.spread,
          color: c.randGreen,
        };
      }),
    });
  }

  fromJSON(json, importedData) {
    const object = JSON.parse(json);
    this.containerObject.position.copy(object.position);
    this.altitudeHelper.position.copy(object.position);
    this.raycastSphere.position.copy(object.position);
    this.axisHelper.position.copy(object.position);

    if (object.filename && object.volume) {
      const file = importedData[object.filename];
      if (file) {
        this.loadSound(file, this.audio, false, this).then((sound) => {
          this.omniSphere.sound = sound;
          this.omniSphere.sound.name = object.filename;
          this.omniSphere.sound.volume.gain.value = object.volume;
          this.setAudioPosition(this.omniSphere);
        });
      }
    }

    object.cones.forEach((c) => {
      let cone;
      const file = importedData[c.filename];
      if (file) {
        this.loadSound(file, this.audio, false).then((sound) => {
          cone = this.createCone(sound, c.color);
          cone.file = file;
          cone.filename = c.filename;
          cone.sound.volume.gain.value = c.volume;
          cone.sound.spread = c.spread;
          this.changeLength(cone);
          this.changeWidth(cone);
          this.gui.addCone(cone);
          this.pointConeMagic(cone, c.position.lat, c.position.long);
        });
      }
    });

    this.movementSpeed = object.movementSpeed;
  }
}


text:
var confirm, alert, normalizeNewlines, limitStrLen;

(function() {
	"use strict";

	// Extend the keyCode constants with values only needed in this app
	$.extend(keyCode, {
		N: 78,
		O: 79,
		S: 83,
		T: 84,
		W: 87,
		Y: 89,
		Z: 90,
		1: 49,
		2: 50,
		3: 51,
		4: 52,
		5: 53,
		6: 54,
		7: 55,
		8: 56,
		9: 57,
		F4: 115,
		PGUP: 33,
		PGDOWN: 34,
		ARROWLEFT: 37,
		ARROWRIGHT: 39
	});

	confirm = function(text, buttons) {
		return new Promise(function(resolvePromise, rejectPromise) {
			rejectPromise = rejectPromise.bind(null, confirm.REJECTION_MSG);

			if (typeof buttons == "undefined") buttons = [new confirm.Button(confirm.Button.CANCEL_BUTTON), new confirm.Button(confirm.Button.OK_BUTTON)];

			var modal = new Modal({
				content: text,
				buttons: buttons.join(""),

				onInit: function() {
					var modal = this;

					modal.el.on("close.modal", function() { rejectPromise() });

					modal.buttonsEls.filter("[data-action=\"cancel\"]").on("click", function(e) {
						e.preventDefault();
						rejectPromise();
						modal.close();
					});

					modal.buttonsEls.filter("[data-action=\"confirm\"]").on("click", function(e) {
						e.preventDefault();
						resolvePromise($(e.target).data("value"));
						modal.close();
					});
				}
			});

			modal.show();
		});
	};

	confirm.REJECTION_MSG = "User closed confirm modal.";

	confirm.Button = (function() {
		// Yes, I'm using a constructor to return a string (well, a String obj). "new Button()" looks cool, and it's abstracted enough that we don't care what's underneath.
		var Button = function(options) {
				return new String(""+ options.text +"");
			},

			ButtonConfig = function(options) {
				$.extend(this, options);
			};

		ButtonConfig.prototype.extend = function(options) {
			return $.extend({}, this, options);
		};

		// Sets of options
		Button.CANCEL_BUTTON = new ButtonConfig({
			class: "button",
			dataAction: "cancel",
			text: "Cancel"
		});
		Button.OK_BUTTON = new ButtonConfig({
			class: "button button-primary",
			dataAction: "confirm",
			text: "Ok"
		});

		return Button;
	})();

	alert = function(text) {
		var modal = new Modal({
			content: text,
			buttons: new confirm.Button(confirm.Button.OK_BUTTON),

			onInit: function() {
				var modal = this;

				modal.buttonsEls.on("click", function(e) {
					e.preventDefault();
					modal.close();
				});
			}
		});

		modal.show();
	};

	// The editor regularly compares files' contents to detect changes, and different line break format will mess with the result.
	// Chrome (and all browsers) already normalize line breaks as LF characters inside a form element's API value (which is
	// W3C lingo for "an element's `value` IDL attribute") (see http://www.w3.org/TR/html5/forms.html#attr-textarea-wrap). Hence,
	// normalizing line breaks in text that doesn't get through that native normalization (text that doesn't get in and out
	// the editor's textarea) seems like the sanest way to go.
	normalizeNewlines = function(str) {
		return String(str).replace(/\r/g, "");
	};

	// Limit the length of a string by, if it's longer than intended, remove text from the middle and inserting an ellipsis
	limitStrLen = function(str, length) {
		if (str.length > length) length = length / 2 - 1, str = str.substr(0, length) +"…"+ str.substr(-length);

		return str;
	};
})();


text:
package org.apache.commons.imaging.formats.jpeg.exif;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImagingTest;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.formats.jpeg.JpegImageParser;

public abstract class ExifBaseTest extends ImagingTest {

    protected static boolean hasExifData(final File file) {
        if (!file.getName().toLowerCase().endsWith(".jpg")) {
            return false;
        }

        try {
            final ByteSource byteSource = new ByteSourceFile(file);
            return new JpegImageParser().hasExifSegment(byteSource);
        } catch (final Exception e) {
            return false;
        }
    }

    private static final ImageFilter HAS_EXIF_IMAGE_FILTER = new ImageFilter() {
        public boolean accept(final File file) throws IOException, ImageReadException {
            return hasExifData(file);
        }
    };

    private static final ImageFilter JPEG_IMAGE_FILTER = new ImageFilter() {
        public boolean accept(final File file) throws IOException, ImageReadException {
            return file.getName().toLowerCase().endsWith(".jpg");
        }
    };

    protected File getImageWithExifData() throws IOException,
            ImageReadException {
        return getTestImage(HAS_EXIF_IMAGE_FILTER);
    }

    protected static List<File> getImagesWithExifData() throws IOException,
            ImageReadException {
        return getTestImages(HAS_EXIF_IMAGE_FILTER);
    }

    protected static List<File> getJpegImages() throws IOException, ImageReadException {
        return getTestImages(JPEG_IMAGE_FILTER);
    }

}


text:
package pt.trycatch.jfungue;

public abstract class EasyAnticipatorListener extends ParserListenerAdapter
{
    private Voice activeVoice;
    private Instrument activeInstrument;

    public EasyAnticipatorListener()
    {
        activeVoice = new Voice((byte)0);
        activeInstrument = new Instrument((byte)0);
    }

    private int tempo;

    public void tempoEvent(Tempo tempo)
    {
        this.tempo = tempo.getTempo();
        System.out.println("tempo = "+tempo.getTempo());
    }

    public void voiceEvent(Voice voice)
    {
        this.activeVoice = voice;
    }

    public void instrumentEvent(Instrument instrument)
    {
        this.activeInstrument = instrument;
    }

    public void noteEvent(Note note)
    {
        extendedNoteEvent(activeVoice, activeInstrument, note);
    }

    public void parallelNoteEvent(Note note)
    {
        extendedNoteEvent(activeVoice, activeInstrument, note);
    }

    public void sequentialNoteEvent(Note note)
    {
        extendedNoteEvent(activeVoice, activeInstrument, note);
//        sleep(note.getDuration());
    }

    /** Duration is in PPQ, need to translate that into msec */
    // TODO: Is duration ALWAYS in PPQ, or does it depend on sequenceTiming?
    private void sleep(long durationInPPQ)
    {
        try {
            long msec = ((durationInPPQ / 4 ) );
            Thread.sleep(msec);
        } catch (InterruptedException e)
        {
            throw new JFugueException(JFugueException.ERROR_SLEEP);
        }
    }

    public abstract void extendedNoteEvent(Voice voice, Instrument instrument, Note note);
}


text:
package de.undercouch.citeproc.tool.shell;

import de.undercouch.citeproc.CSLTool;
import de.undercouch.underline.Command;
import de.undercouch.underline.Option;
import de.undercouch.underline.OptionGroup;
import de.undercouch.underline.OptionIntrospector;
import de.undercouch.underline.OptionIntrospector.ID;
import org.jline.reader.Candidate;
import org.jline.reader.impl.DefaultParser;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Tests {@link ShellCommandCompleter}
 * @author Michel Kraemer
 */
public class ShellCommandCompleterTest {
    private void complete(String line, ArrayList<CharSequence> r) {
        complete(line, r, Collections.emptyList());
    }

    private void complete(String line, ArrayList<CharSequence> r,
            List<Class<? extends Command>> excludedCommands) {
        ShellCommandCompleter cc = new ShellCommandCompleter(excludedCommands);
        List<Candidate> cs = new ArrayList<>();
        cc.complete(null, new DefaultParser().new ArgumentList(line,
                Arrays.asList(line.split("\\s+")), 0, 0, 0, null, 0, 0), cs);
        for (Candidate c : cs) {
            r.add(c.value());
        }
    }

    /**
     * Tests if top-level commands can be completed
     * @throws Exception if something goes wrong
     */
    @Test
    public void topLevel() throws Exception {
        ArrayList<CharSequence> r = new ArrayList<>();
        complete("", r);

        OptionGroup<ID> options = OptionIntrospector.introspect(CSLTool.class);
        OptionGroup<ID> optionsAdditional = OptionIntrospector.introspect(
                AdditionalShellCommands.class);
        // get number of commands, subtract 1 because there's a HelpCommand
        // and a ShellHelpCommand
        int numCommands = options.getCommands().size() +
                optionsAdditional.getCommands().size() - 1;
        assertEquals(numCommands, r.size());
        for (Option<ID> o : options.getCommands()) {
            assertTrue(r.contains(o.getLongName()));
        }
        for (Option<ID> o : optionsAdditional.getCommands()) {
            assertTrue(r.contains(o.getLongName()));
        }

        r = new ArrayList<>();
        complete(" ", r);
        assertEquals(numCommands, r.size());

        r = new ArrayList<>();
        complete("     ", r);
        assertEquals(numCommands, r.size());

        r = new ArrayList<>();
        complete("bibl", r);
        assertEquals(1, r.size());
        assertEquals("bibliography", r.get(0));

        r = new ArrayList<>();
        complete("   bibl", r);
        assertEquals(1, r.size());
        assertEquals("bibliography", r.get(0));

        r = new ArrayList<>();
        complete("ge", r);
        assertEquals(1, r.size());
        assertEquals("get", r.get(0));

        r = new ArrayList<>();
        complete("bla", r);
        assertEquals(0, r.size());
    }

    /**
     * Tests if subcommands can be completed
     * @throws Exception if something goes wrong
     */
    @Test
    public void subcommand() throws Exception {
        ArrayList<CharSequence> r = new ArrayList<>();
        complete("get", r);

        OptionGroup<ID> options = OptionIntrospector.introspect(
                ShellGetCommand.class);
        assertEquals(options.getCommands().size(), r.size());
        for (Option<ID> o : options.getCommands()) {
            assertTrue(r.contains(o.getLongName()));
        }

        r = new ArrayList<>();
        complete("get ", r);
        assertEquals(options.getCommands().size(), r.size());

        r = new ArrayList<>();
        complete("get st", r);
        assertEquals(1, r.size());
        assertEquals("style", r.get(0));

        r = new ArrayList<>();
        complete("get   st", r);
        assertEquals(1, r.size());
        assertEquals("style", r.get(0));

        r = new ArrayList<>();
        complete("get style", r);
        assertEquals(0, r.size());

        r = new ArrayList<>();
        complete("get bla", r);
        assertEquals(0, r.size());
    }

    /**
     * Tests if unknown attributes are ignored
     */
    @Test
    public void unknownAttributes() {
        ArrayList<CharSequence> r = new ArrayList<>();
        complete("get style test", r);
        assertEquals(0, r.size());

        r = new ArrayList<>();
        complete("get style test test2", r);
        assertEquals(0, r.size());
    }

    /**
     * Tests if commands can be excluded
     * @throws Exception if something goes wrong
     */
    @Test
    public void excludedCommands() throws Exception {
        List<Class<? extends Command>> cmds = new ArrayList<>();
        cmds.add(ShellGetCommand.class);

        OptionGroup<ID> options = OptionIntrospector.introspect(CSLTool.class);
        OptionGroup<ID> optionsAdditional = OptionIntrospector.introspect(
                AdditionalShellCommands.class);
        // get number of commands, subtract 1 because there's a HelpCommand
        // and a ShellHelpCommand
        int numCommands = options.getCommands().size() +
                optionsAdditional.getCommands().size() - 1;
        // subtract 1 again because we excluded one command
        --numCommands;

        ArrayList<CharSequence> r = new ArrayList<>();
        complete("", r, cmds);
        assertEquals(numCommands, r.size());
    }

    /**
     * Tests if completions for the help command are computed correctly
     * @throws Exception if something goes wrong
     */
    @Test
    public void help() throws Exception {
        ArrayList<CharSequence> r = new ArrayList<>();
        complete("hel", r);
        assertEquals(1, r.size());
        assertEquals("help", r.get(0));

        r = new ArrayList<>();
        complete("help ge", r);
        assertEquals(1, r.size());
        assertEquals("get", r.get(0));

        r = new ArrayList<>();
        complete("help get st", r);
        assertEquals(1, r.size());
        assertEquals("style", r.get(0));

        r = new ArrayList<>();
        complete("help get", r);
        OptionGroup<ID> options = OptionIntrospector.introspect(ShellGetCommand.class);
        assertEquals(options.getCommands().size(), r.size());
        for (Option<ID> cmd : options.getCommands()) {
            assertTrue(r.contains(cmd.getLongName()));
        }

        r = new ArrayList<>();
        complete("help", r);
        options = OptionIntrospector.introspect(CSLTool.class);
        OptionGroup<ID> optionsAdditional = OptionIntrospector.introspect(
                AdditionalShellCommands.class);
        // get number of commands, subtract 1 because there's a HelpCommand
        // and a ShellHelpCommand
        int numCommands = options.getCommands().size() +
                optionsAdditional.getCommands().size() - 1;
        assertEquals(numCommands, r.size());
    }

    /**
     * Checks if completions for output formats are calculated correctly
     */
    @Test
    public void completeFormats() {
        ArrayList<CharSequence> r = new ArrayList<>();
        complete("set format h", r);
        assertEquals(1, r.size());
        assertEquals("html", r.get(0));

        r = new ArrayList<>();
        complete("set format", r);
        assertEquals(4, r.size());
    }
}