text:
[kakao](../../index.md) / [com.agoda.kakao.common.matchers](../index.md) / [AbsListViewAdapterSizeMatcher](index.md) / [describeTo](./describe-to.md)

# describeTo

`fun describeTo(description: Description): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)


text:
package lv.ctco.scm.gradle.tasks.ios;

import lv.ctco.scm.gradle.MobilePluginTask;
import lv.ctco.scm.mobile.utils.IosSimulator;
import lv.ctco.scm.mobile.utils.IosSimulatorCLP;
import lv.ctco.scm.mobile.utils.IosSimulatorState;
import lv.ctco.scm.mobile.utils.IosSimulatorUtil;

import java.io.IOException;

public class IosSimulatorOverrideKeyboardTask extends MobilePluginTask {

    public IosSimulatorOverrideKeyboardTask() {
        this.setGroup("iOS Simulator");
        this.setDescription("Overrides keyboard settings on a specific iOS simulator");
    }

    public void doTaskAction() throws Exception {
        IosSimulator iosSimulator = IosSimulatorUtil.findSimulator(
            getProject().getProperties().get(IosSimulatorCLP.UDID.getName()),
            getProject().getProperties().get(IosSimulatorCLP.TYPE.getName()),
            getProject().getProperties().get(IosSimulatorCLP.RUNTIME.getName())
        );
        getLogger().info("Checking state of {}", iosSimulator);
        if (IosSimulatorUtil.getState(iosSimulator) == IosSimulatorState.SHUTDOWN) {
            logSimulatorState(iosSimulator);
            getLogger().info("Overriding keyboard on {}", iosSimulator);
            IosSimulatorUtil.overrideKeyboard(iosSimulator);
        } else {
            stopWithError("iOS simulator must be shutdown to override keyboard");
        }
    }

    private void logSimulatorState(IosSimulator iosSimulator) throws IOException {
        getLogger().info("  state of {} is {}", iosSimulator, IosSimulatorUtil.getState(iosSimulator));
    }

}

redpajama_set_name: RedPajamaGithub


text:
<feature_model name="eShop">
<feature_tree>
:r eShop
	[:m StoreFront (store_front)
		[:o HomePage (homepage)
			<:g[1,*]
				[: StaticContent
				 : DynamicContent
					[:m ContentType
						<:g[1,*]
							[: WelcomeMessage
							 : SpecialOffers (special_offers)]>
					 :m VariationSource
						<:g[1,*]
							[: TimeDependent
							 : Personalized]>]]>
		:o Registration (registration)
			[:m RegistrationEnforcement (registration_enforcement)
				<:g[1,*]
					[: Register2browse
					 : Register2buy (register_to_buy)
					 : None]>
			:m RegistrationInformation
				[:m LoginCredentials
				 :o ShippingAddress (shipping_address)
					[:o MultipleShippingAddresses]
				 :o BillingAddress
					[:o MultipleBillingAddresses]
				 :o CreditCardInformation
					[:m Card holder name
					:m Card number
					:m Expiry date
					:o Security information]
				:o Demographics
					<:g[1,*]
						[: Age
						: Income
						: Education
						: Custom Demographic field]>
				:o Personal Information
				:o Preferences (preferences)
					<:g[1,*]
						[: Site layout
						 : List size
						 : Language]>
				:o Reminders
				:o Quick checkout profile (quick_checkout_profile)
				:o Custom fields]
			:o User behaviour tracking information (user_behaviour_tracking_info)]
		:m Catalog (catalog)
			[:m Product Information (product_information)
				[:m Product type (product_type)
					<:g[1,*]
						[: Eletronic goods (eletronic_goods)
						 : Physical goods (physical_goods)
						 : Services (services)]>
				:m Basic information (basic_information)
				:o Detailed information (detailed_information)
				:o Warranty information (warranty_information)
				:o Customer reviews (customer_reviews)
				:o Associated assets (associated_assets)
					<:g[1,*]
						[: Documents
						 : Media files
							<:g[1,*]
								[: Image
									<:g[1,*]
										[: Thumbnail
										 : image2d
										 : image3d
										 : image360
										 : Different perspectives
										 : Gallery]>
								: Video
								: Sound]>]>
				:o Product variants (product_variants)
					[:o Complex product configuration]
				:o Size (size)
				:o Weight (weight)
				:o Availability (availability)
				:o Custom fields (custom_fields)]
			:o Categories (categories)
				[:m Catalog (categories_catalog)
					[:o Categories
						[:o Multi_level
						 :o Multiple classification]]]
			:o Multiple catalogs
			:o Searching
				<:g[1,*]
					[: Basic search
					 : Advanced search]>
			:o Browsing
				[:m Product page
				 :o Category page (category_page)
				 :o Index page
					[:o Sorting filters
						<:g[1,*]
							[: Price
							 : Quality
							 : Price Quality ratio
							 : Manufacturer name
							 : Custom filter]>]]
			:o Custom views
				[:o Seasonal product views
				 :o Personalized views]]
		:o Wish list (wish_list)
			[:o Wish list save after session (wish_list_saved_after_session)
			 :o Email wish list (email_wish_list)
			 :o Multiple wish lists
			 :o Permissions (permissions)
				<:g[1,*]
					[: Public access
					 : Restricted access
					 : Private access]>]
		:m Buy paths (buy_paths)
			[:m Shopping cart
				[:m Inventory management policy
				 :m Cart content page
				 :o Cart summary page
				 :o Cart save after session]]
			:m Checkout
				[:m Checkout type
					<:g[1,*]
						[: Registered checkout (registered_checkout)
							[:o Quick checkout (quick_checkout)
								[:o Enable profile update on checkout]]
						 : Guest checkout]>
				:o Shipping options (shipping_options)
					[:o Quality of service selection
					 :o Carrier selection
					 :o Gift options
					 :o Multiple shipments
					 :m Shipping cost calculation]
				:m Taxation options
					<:g[1,*]
						[: Custom taxation
							[:m Type
								<:g[1,*]
									[: Fixed rate taxation
									 : Rule based taxation
										[:m Tax codes
										 :m Address
											[:m Shipping (shipping_2)
											 :o Billing]
										 :o Resolution
											<:g[1,*]
												[: Country
												 : Region
												 : City]>]]>
							:m Ammount specification
								<:g[1,*]
									[: Surcharge
									 : Percentage]>]
						: Tax gateways
							<:g[1,*]
								[: CertiTAX
								 : CyberSource
								 : Custom tax gateway]>]>
				:m Payment options
					[:m Payment types
						<:g[1,*]
							[: COD
							 : Credit card
							 : Debit card
							 : Eletronic cheque
							 : Fax mail order
							 : Purchase order
							 : Gift certificate
							 : Phone order
							 : Custom payment type]>
					:o Fraud detection
					:o Payment gateways
						<:g[1,*]
							[: Authorize Net
							 : CyberSource
							 : LinkPoint
							 : Paradata
							 : SkipJack
							 : Verisign Payflow Pro
							 : Custom payment gateway]>]
			:m Order confirmation
				<:g[1,*]
					[: Eletronic page
					 : Email
					 : Phone
					 : Mail]>]
		:o Customer service (customer_service)
			<:g[1,*]
				[: Question and feedback forms
					[:o Question and feedback tracking]
				 : Product returns
				 : Order status review
					[:m Filtering criteria
						<:g[1,*]
							[: Order number
							 : Order date
							 : Order status]>
					:o Request order hardcopy]
				: Shipment status tracking
					<:g[1,*]
						[: Internal tracking
						 : Partner tracking]>]>
		:o User behaviour tracking (user_behaviour_tracking)
			[:m Behaviour tracked
				<:g[1,*]
					[: Locally visited pages (locally_visited_pages)
					 : External referring pages (external_referring_pages)
					 : Previous purchases (behaviour_tracked_previous_purchases)]>]]
	:m Business management (business_management)
		[:m Order management
			[:m Fulfillment
				<:g[1,*]
					[: Physical goods fulfillment (physical_goods_fulfillment)
						[:m Warehouse management (warehouse_management)
						 :m Shipping (shipping)
							<:g[1,*]
								[: Custom shipping method
									[:m Pricing
										[:m Flat rate
										 :o Rate factors
											<:g[1,*]
												[: Quantity purchased
												 : Order total
												 : Weight
												 : Product classification]>]]
								: Shipping gateways
									<:g[1,*]
										[: FedEX
										 : UPS
										 : USPS
										 : Canada Post
										 : Custom shipping gateway]>]>]
					: Eletronic goods fulfillment (eletronic_goods_fulfillment)
						[:m File repository
						 :m License management]
					: Services fulfillment (services_fulfillment)
						[:o Appointment scheduling
						 :o Resource planning]]>]
		:o Targeting
			[:m Targeting criteria
				<:g[1,*]
					[: Customer preferences (customer_preferences)
					 : Personal information
					 : Demographics
					 : Previous purchases (targeting_criteria_previous_purchases)
					 : Shopping cart content
					 : Wish list content (wish_list_content)
					 : Previously visited pages (previously_visited_pages)
					 : Date and time
					 : Custom target criteria]>
			:m Targeting mechanisms
				<:g[1,*]
					[: Advertisements
						[:m Advertisement types
							<:g[1,*]
								[: Banner ads
								 : Popup ads]>
						:m Advertisement sources
							<:g[1,*]
								[: House advertisements
								 : Paid advertisements
									[:m Advertisement management interface]]>
						:o Advertisement response tracking
						:o Context sensitive ads]
					: Discounts (discounts)
						[:m Discount conditions
							[:m Product and quantity scope
							 :m Time scope
							 :o Purchase value scope]
						 :m Award
							<:g[1,*]
								[: Percentage discount
								 : Fixed discount
								 : Free item]>
						:m Eligibility requirements
							[:o Customer segments
							 :o Shipping address]
						:m Graduation by
							<:g[1,*]
								[: Purchase value
								 : Quantity]>
						:o Coupons
						:m Handling multiple discount]
					: Sell strategies
						<:g[1,*]
							[: Product kitting
							 : Up selling
								[:m Substitute products]
							 : Cross selling
								[:m Past customers also bought]]>]>
			:m Display and notification
				<:g[1,*]
					[: Assignment to page types for display
					 : Product flagging
					 : Emails
						[:o Personalized (personalized_emails)
						:o Response tracking]]>
			:o Campaigns]
		:o Affiliates
			[:m Affiliate registration
			 :m Commission tracking]
		:o Inventory tracking (inventory_tracking)
			[:o Allow backorders]
		:o Procurement (procurement)
			[:m Stock replenishment
				[:m Manual
				 :o Automatic (automatic)
					[:m Non repudiation service]]]
		:o Reporting and analysis (reporting_and_analysis)
			[:m Report types
			 :m Report formats
			 :m Level of detail]
		:o External systems integration
			<:g[1,*]
				[: Fulfillment system (fulfillment_system)
				 : Inventory management system
				 : Procurement system (procurement_system)
				 : External distributor system]>
		:m Administration
			[:m Content management
				[:m Product database management
				 :m Presentation options
				 :m General layout management
				 :o Content approval]
			:m Store administration
				[:m Site search
				 :m Search engine registration
				 :m Domain name setup]]]]
</feature_tree>
<constraints>
 implies(special_offers, discounts)
 implies(registered_checkout, registration_enforcement)
</constraints>
</feature_model>


text:
package com.lambstat.module.external.camera.log;

import com.lambstat.core.log.BaseLogger;

import java.util.logging.Logger;

public class CameraServiceLogger extends BaseLogger {

    private Logger logger = Logger.getLogger(getClass().getSimpleName());

    public void willHandleImageCaptureEvent(String event) {
        log("CaptureImageEvent: " + event);
    }

    public void willHandleVideoCaptureEvent(String event) {
        log("CaptureVideoEvent: " + event);
    }

    public void willHandleCameraCaptureEvent(String event) {
        log("CameraCaptureImageEvent: " + event);
    }

    public void willSendWriteToDiskEvent(String event) {
        log("will send WriteToDiskEvent: " + event);
    }

    public void simulatingWork() {
        log("simulating work");
    }

    public void workDone() {
        log("work done");
    }

    public void couldNotSleep(String errorMessage) {
        error("Could not sleep, exception: " + errorMessage);
    }
}


text:
package org.apache.curator;

import com.google.common.io.Closeables;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.KillSession;
import org.apache.curator.test.Timing;
import junit.framework.Assert;
import org.testng.annotations.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;

public class TestSessionFailRetryLoop extends BaseClassForTests
{
    @Test
    public void     testRetry() throws Exception
    {
        Timing                          timing = new Timing();
        final CuratorZookeeperClient    client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1));
        SessionFailRetryLoop            retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
        retryLoop.start();
        try
        {
            client.start();
            final AtomicBoolean     secondWasDone = new AtomicBoolean(false);
            final AtomicBoolean     firstTime = new AtomicBoolean(true);
            while ( retryLoop.shouldContinue() )
            {
                try
                {
                    RetryLoop.callWithRetry
                    (
                        client,
                        new Callable<Void>()
                        {
                            @Override
                            public Void call() throws Exception
                            {
                                if ( firstTime.compareAndSet(true, false) )
                                {
                                    Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                    KillSession.kill(client.getZooKeeper(), server.getConnectString());
                                    client.getZooKeeper();
                                    client.blockUntilConnectedOrTimedOut();
                                }

                                Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                return null;
                            }
                        }
                    );

                    RetryLoop.callWithRetry
                    (
                        client,
                        new Callable<Void>()
                        {
                            @Override
                            public Void call() throws Exception
                            {
                                Assert.assertFalse(firstTime.get());
                                Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                secondWasDone.set(true);
                                return null;
                            }
                        }
                    );
                }
                catch ( Exception e )
                {
                    retryLoop.takeException(e);
                }
            }

            Assert.assertTrue(secondWasDone.get());
        }
        finally
        {
            retryLoop.close();
            Closeables.closeQuietly(client);
        }
    }

    @Test
    public void     testRetryStatic() throws Exception
    {
        Timing                          timing = new Timing();
        final CuratorZookeeperClient    client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1));
        SessionFailRetryLoop            retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
        retryLoop.start();
        try
        {
            client.start();
            final AtomicBoolean     secondWasDone = new AtomicBoolean(false);
            final AtomicBoolean     firstTime = new AtomicBoolean(true);
            SessionFailRetryLoop.callWithRetry
            (
                client,
                SessionFailRetryLoop.Mode.RETRY,
                new Callable<Object>()
                {
                    @Override
                    public Object call() throws Exception
                    {
                        RetryLoop.callWithRetry
                        (
                            client,
                            new Callable<Void>()
                            {
                                @Override
                                public Void call() throws Exception
                                {
                                    if ( firstTime.compareAndSet(true, false) )
                                    {
                                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                        KillSession.kill(client.getZooKeeper(), server.getConnectString());
                                        client.getZooKeeper();
                                        client.blockUntilConnectedOrTimedOut();
                                    }

                                    Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                    return null;
                                }
                            }
                        );

                        RetryLoop.callWithRetry
                        (
                            client,
                            new Callable<Void>()
                            {
                                @Override
                                public Void call() throws Exception
                                {
                                    Assert.assertFalse(firstTime.get());
                                    Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                    secondWasDone.set(true);
                                    return null;
                                }
                            }
                        );
                        return null;
                    }
                }
            );

            Assert.assertTrue(secondWasDone.get());
        }
        finally
        {
            retryLoop.close();
            Closeables.closeQuietly(client);
        }
    }

    @Test
    public void     testBasic() throws Exception
    {
        Timing                          timing = new Timing();
        final CuratorZookeeperClient    client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1));
        SessionFailRetryLoop            retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
        retryLoop.start();
        try
        {
            client.start();
            try
            {
                while ( retryLoop.shouldContinue() )
                {
                    try
                    {
                        RetryLoop.callWithRetry
                        (
                            client,
                            new Callable<Void>()
                            {
                                @Override
                                public Void call() throws Exception
                                {
                                    Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                    KillSession.kill(client.getZooKeeper(), server.getConnectString());

                                    client.getZooKeeper();
                                    client.blockUntilConnectedOrTimedOut();
                                    Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                    return null;
                                }
                            }
                        );
                    }
                    catch ( Exception e )
                    {
                        retryLoop.takeException(e);
                    }
                }

                Assert.fail();
            }
            catch ( SessionFailRetryLoop.SessionFailedException dummy )
            {
                // correct
            }
        }
        finally
        {
            retryLoop.close();
            Closeables.closeQuietly(client);
        }
    }

    @Test
    public void     testBasicStatic() throws Exception
    {
        Timing                          timing = new Timing();
        final CuratorZookeeperClient    client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new RetryOneTime(1));
        SessionFailRetryLoop            retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
        retryLoop.start();
        try
        {
            client.start();
            try
            {
                SessionFailRetryLoop.callWithRetry
                (
                    client,
                    SessionFailRetryLoop.Mode.FAIL,
                    new Callable<Object>()
                    {
                        @Override
                        public Object call() throws Exception
                        {
                            RetryLoop.callWithRetry
                            (
                                client,
                                new Callable<Void>()
                                {
                                    @Override
                                    public Void call() throws Exception
                                    {
                                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                        KillSession.kill(client.getZooKeeper(), server.getConnectString());

                                        client.getZooKeeper();
                                        client.blockUntilConnectedOrTimedOut();
                                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                                        return null;
                                    }
                                }
                            );
                            return null;
                        }
                    }
                );
            }
            catch ( SessionFailRetryLoop.SessionFailedException dummy )
            {
                // correct
            }
        }
        finally
        {
            retryLoop.close();
            Closeables.closeQuietly(client);
        }
    }
}


text:
package com.chenpan.commoner.mvp.presenter;

import com.chenpan.commoner.base.pbase.BasePresenter;
import com.chenpan.commoner.mvp.view.IMusicLocalView;

/**
 * Created by Administrator on 2016/7/6.
 */
public class MusicLocalPresenter extends BasePresenter<IMusicLocalView> {
}


text:
package com.intentfilter.androidpermissions.helpers;

import static android.app.PendingIntent.FLAG_IMMUTABLE;

public class VersionOrchestrator {
    public static int getImmutablePendingIntentFlags(int... flags) {
        int combinedImmutableFlags = 0;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            combinedImmutableFlags = FLAG_IMMUTABLE;
        }

        for (int flag : flags) {
            combinedImmutableFlags = combinedImmutableFlags | flag;
        }

        return combinedImmutableFlags;
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">

Apache Cordova Documentation

                <select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.9.0rc1">2.9.0rc1</option>
<option value="2.9.0">2.9.0</option>
<option value="2.8.0">2.8.0</option>
<option value="2.7.0rc1">2.7.0rc1</option>
<option value="2.7.0">2.7.0</option>
<option value="2.6.0rc1">2.6.0rc1</option>
<option value="2.6.0">2.6.0</option>
<option selected value="2.5.0rc1">2.5.0rc1</option>
<option value="2.5.0">2.5.0</option>
<option value="2.4.0rc1">2.4.0rc1</option>
<option value="2.4.0">2.4.0</option>
<option value="2.3.0rc2">2.3.0rc2</option>
<option value="2.3.0rc1">2.3.0rc1</option>
<option value="2.3.0">2.3.0</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option value="2.2.0rc1">2.2.0rc1</option>
<option value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option value="1.5.0">1.5.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.2.0">2.2.0</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select>

Getting Started with Windows 8

            <select><option value="Getting%2520Started%2520with%2520Windows%25208">Getting Started with Windows 8</option>
<option value="Getting%20Started%20with%20Windows%208_1_requirements">      - 1. Requirements</option>
<option value="Getting%20Started%20with%20Windows%208_2_install_sdk_cordova">      - 2. Install SDK + Cordova</option>
<option value="Getting%20Started%20with%20Windows%208_3_setup_new_project">      - 3. Setup New Project</option>
<option value="Getting%20Started%20with%20Windows%208_5_test_the_project">      - 5. Test the Project</option>
<option value="Getting%20Started%20with%20Windows%208_done">      - Done!</option></select>

API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

Geolocation

Globalization

InAppBrowser

Media

Notification

Splashscreen

Storage

Guides

Getting Started Guides

Command-Line Usage

Upgrading Guides

Project Settings

Plugin Development Guide

Domain Whitelist Guide

Embedding WebView

Keyword Index

Getting Started with Windows 8

This guide describes how to set up your development environment for Cordova and run a sample application.  Note that Cordova used to be called PhoneGap, so some of the sites still use the old PhoneGap name.

During development of Windows 8 and Windows RT, Microsoft deprecated the name "Metro-style apps". On MSDN, this type of app is now called a "Windows Store" app. That's the name that we'll use in this guide. Also in this guide whenever we refer to Windows 8, you should take that to mean both Windows 8 and Windows RT.

1. Requirements

Windows 8

Visual Studio 2012 Professional or better, or Visual Studio 2012 Express for Windows 8

Follow the instructions here to submit your apps Windows Store.

2. Install SDK + Cordova

Setup your preferred variant of Visual Studio 2012. All of the paid versions of the product (Professional, etc) let you build Windows Store apps. To build Windows Store apps using the Express editions, you will need Express for Windows 8.

Download the latest copy of Cordova and extract its contents. We will be working with the subfolder lib\windows-8.

3. Setup New Project

You can already build Windows 8 apps using the "HTML/JavaScript track" available in Windows Store apps. The purpose of Cordova in Windows Store apps is to expose the same APIs used on all the other Cordova platforms.

Open Visual Studio 2012 and choose New Project.

Select Installed - Template - Other Languages - JavaScript - Windows Store from the tree, and then Blank App from the projects list. Enter whatever project name you like. We're using CordovaWin8Foo in this guide.

Microsoft continues to use default.html as the default page for use in websites, whereas most "open web" developers use index.html. (Plus it's likely that in the other platform variants of your project you are using index.html as the name of your default page.) To fix this, in Solution Explorer rename the default.html file to index.html. Then double-click the package.appxmanifest file and change the Start page value to index.html.

To include cordova.js in your project, right-click on the js folder in Solution Explorer and select Add - New Item. Locate the cordova.js file in the lib\windows-8 folder that we called out previously.

Edit the code for index.html. Add a reference to cordova.js. You can do this manually, or by dragging the file from Solution Explorer.

Adding the reference...

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- Cordova -->
    <script src="/js/cordova.js"></script>

    <!-- CordovaWin8Foo references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>

Next we want to add some code that will demonstrate that Cordova is working.

Adding a 'deviceready' handler...

<body>
    <p>Content goes here</p>

    <script type="text/javascript">

        console.log("Subscribing...");
        document.addEventListener("deviceready", function () {

            navigator.notification.alert("The device is ready!");

        });

    </script>

</body>

5. Test the Project

Run the project from Visual Studio. You'll see the message box appear.

Done!

That's it! You're now ready to build Windows Store apps with Cordova.


text:
@implementation RACSignal (POSRx)

- (id)posrx_await {
    __block id result = nil;
    __block BOOL done = NO;
    [[self take:1] subscribeNext:^(id value) {
        result = value;
        done = YES;
    } error:^(NSError *e) {
        done = YES;
    }];
    if (result) {
        return result;
    }
    NSRunLoop *runLoop = NSRunLoop.currentRunLoop;
    while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:NSDate.date] && !done) {}
    return result;
}

@end


text:
greenrobot-common
=================
greenrobot-common provides general purpose utilities for Android and Java projects. Having its root in the early days of Android development, the library is minimalistic, tiny in size (jar < 100k), and focuses on efficiency and performance.

[![Build Status](https://travis-ci.org/greenrobot/greenrobot-common.svg?branch=master)](https://travis-ci.org/greenrobot/greenrobot-common)

Features
--------
The Utility classes cover [stream-based IO](java-common/src/main/java/de/greenrobot/common/io/IoUtils.java), [files](java-common/src/main/java/de/greenrobot/common/io/FileUtils.java), [strings](java-common/src/main/java/de/greenrobot/common/StringUtils.java), and [date/time](java-common/src/main/java/de/greenrobot/common/DateUtils.java). There are also efficient [hash map](java-common/src/main/java/de/greenrobot/common/LongHashMap.java) and [hash set](java-common/src/main/java/de/greenrobot/common/LongSetMap.java) implementation for primitive long keys.

Another important part of greenrobot-common are [hash functions](hash-functions.md). Our Murmur3A&F implementations are the fastest Java implementations known to us. Murmur3 hash functions are one of today's best hash functions available with excellent properties. At 3,6 GByte/s, we measured our Murmur3F implementation to outperform Guava's by factor 10. Find more information on the [hash functions page](hash-functions.md) or jump directly to our [Java hash function benchmark PDF](web-resources/hash-functions-benchmark.pdf).

Speaking of Guava, this project is bare bones compared to a rich menu offered by Guava, or, let's say, Apache Commons. greenrobot-common is not a framework, it's rather a small set of utilities to make Java standard approaches more convenient or more efficient.

How to integrate in your project
--------------------------------
Just grab it from Maven Central (or jCenter). For Gradle, add the following dependency:

    compile 'de.greenrobot:java-common:2.0.0'

And for Maven:

    <dependency>
        <groupId>de.greenrobot</groupId>
        <artifactId>java-common</artifactId>
        <version>2.0.0</version>
    </dependency>

Code samples
============
Example code on how to use some of the utility classes:

```Java
// Get all bytes from stream and close the stream safely
byte[] bytes = IoUtils.readAllBytesAndClose(inputStream);

// Read the contents of an file as a string (use readBytes to get byte[])
String contents = FileUtils.readUtf8(file);

// How many days until new year's eve?
long time2 = DateUtils.getTimeForDay(2015, 12, 31);
int daysToNewYear = DateUtils.getDayDifference(time, time2);
```

[Our hash functions](hash-functions.md) implement [java.util.zip.Checksum](http://docs.oracle.com/javase/8/docs/api/java/util/zip/Checksum.html), so this code might look familiar to you:

```Java
Murmur3A murmur = new Murmur3A();
murmur.update(bytes);
long hash = murmur.getValue();
```

All hashes can be calculated progressively by calling update(...) multiple times. Our Murmur3A implementation goes a step further by offering updates with primitive data in a very efficient way:
```Java
// reuse the previous instance and start over to calculate a new hash
murmur.reset();

murmur.updateLong(42L);

// Varargs and arrays are supported natively, too
murmur.updateInt(2014, 2015, 2016);

murmur.updateUtf8("And strings, of course");

// Hash for the previous update calls. No conversion to byte[] necessary.
hash = murmur.getValue();
```

We may not write a lot of documentation for this project. The utility classes are straight forward and don't have dependencies, so you should be fine to grasp them by having a look at their source code. Most of the method names should be self-explaining, and often you'll find JavaDocs where needed. Code is the best documentation, right?

Build setup
===========
Currently, Maven is used to build greenrobot-common. Inside of [build-common](build-common), there are two parent POMs defined that might be useful: parent-pom and parent-pom-with-checks. The latter integrates FindBugs and Checkstyle in your build. Use it like this:

    <parent>
        <groupId>de.greenrobot</groupId>
        <artifactId>parent-pom-with-checks</artifactId>
        <version>2.0.0</version>
        <relativePath></relativePath>
    </parent>

History
=======

You may notice that the version numbers are already above 1.0 for the initial release. That's because we were already having this project inside of greenrobot. It started as a general purpose library for Android around 2009, which was used for many Android projects since then. The Android library grew and matured over the years. In 2013, we noticed that parts of our Android library would be useful for some Java projects we do. So we moved the parts that don't depend on Android into a new project. Internally, we referred to this as java-common, which is still the artifact name. In late 2014, we decided to open source it as greenrobot-common.

More Open Source by greenrobot
==============================
[__EventBus__](https://github.com/greenrobot/EventBus) is a central publish/subscribe bus for Android with optional delivery threads, priorities, and sticky events. A great tool to decouple components (e.g. Activities, Fragments, logic components) from each other.

[__greenDAO__](https://github.com/greenrobot/greenDAO) is an ORM optimized for Android: it maps database tables to Java objects and uses code generation for optimal speed.

[Follow us on Google+](https://plus.google.com/b/114381455741141514652/+GreenrobotDe/posts) to stay up to date.

Changelog
=========
Unreleased
----------
* Added LimitedInputStream: limits bytes that can be read from an InputStream (useful if your stream contains separate sections of known lengths)

Version 2.0.0
-------------
First open source release.


text:
package com.lambdaworks.redis;

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

/**
 * Cursor providing a list of {@link com.lambdaworks.redis.ScoredValue}
 *
 * @param <V> Value type.
 * @author Mark Paluch
 * @since 3.0
 */
public class ScoredValueScanCursor<V> extends ScanCursor {

    private final List<ScoredValue<V>> values = new ArrayList<>();

    public ScoredValueScanCursor() {
    }

    public List<ScoredValue<V>> getValues() {
        return values;
    }
}


text: #{listElements}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Benarito</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Coding for fun and sharing it out.">
    <meta name="author" content="Benarito">

    <link rel="canonical" href="http://benarito.github.io//404.html">

    <link rel="stylesheet" href="/css/pixyll.css" type="text/css">

    <link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>

    <meta property="og:locale" content="en_US">
    <meta property="og:type" content="article">
    <meta property="og:title" content="Benarito">
    <meta property="og:description" content="Coding for fun and sharing it out.">
    <meta property="og:url" content="http://benarito.github.io//404.html">
    <meta property="og:site_name" content="Benarito">

    <link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
    <link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
    <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">

Benarito

        About
Contact

404

Sorry, we can’t seem to find this page.

  Home
  Contact

        © Copyright 2015   @benson254.


text:
module Main where

import Control.Arrow
import Control.Monad
import Control.Exception
import Data.List

import System.Environment
import System.Process
import System.Exit
import System.IO
import System.Directory
import System.Process

import System.FilePath
import System.FilePath.Wrapper (FileT(..))
import Development.Cake3.Utils.Find

import Text.Printf

filterCakes :: FilePath -> Bool
filterCakes x = nodots && isPrefixOf "Cake" bn &&  isSuffixOf ".hs" bn where
  bn = takeFileName x
  nodots = all (not . isPrefixOf ".") $ skipRelativeDot $ splitDirectories x
  skipRelativeDot (".":ds) = ds
  skipRelativeDot x = x

pathOrder :: FilePath -> FilePath -> Ordering
pathOrder a b =
  let
    na = normalise a
    nb = normalise b
    la = length (splitDirectories na)
    lb = length (splitDirectories nb)
    x = compare la lb
  in
    case x of
      EQ -> compare na nb
      _ -> x

nameOrder :: FilePath -> FilePath -> Ordering
nameOrder a b = takeFileName a `compare` takeFileName b

checkCakeGroupAgainstGit :: [FilePath] -> IO (Either String (String,FilePath))
checkCakeGroupAgainstGit cakes = do
  cwd <- getCurrentDirectory
  revs <- forM cakes $ \c -> do
    bracket (setCurrentDirectory (takeDirectory c)) (const (setCurrentDirectory cwd)) $ \ () -> do
      return ("ACAACACACACACACACACAACACACA", c)
  return $
    foldl' (\err (r',c') ->
      case err of
        Left x -> Left x
        Right (r,c) ->
          case r == r' of
            True -> Right (r,c)
            False -> Left (printf "Git revision for %s (%s) doesn't match the one for %s (%s)" c' r' c r)
    ) (Left "empty list") revs

main :: IO ()
main = do
  fs <- map (sortBy pathOrder) <$> groupBy (curry ((EQ==) . uncurry nameOrder)) <$> sortBy nameOrder <$> filter filterCakes <$> getDirectoryContentsRecursive' "."

  forM_ fs $ \x -> do
    putStrLn (show x)

  return ()


text:
@interface UAIAMDeleteServerCertificateResponse : UAIAMResponse

@end


text:
namespace apps {

// The BrowserContext used by the content, apps and extensions systems in
// app_shell.
class ShellBrowserContext : public content::ShellBrowserContext {
 public:
  ShellBrowserContext();
  virtual ~ShellBrowserContext();

  // HACK: Pad the virtual function table so we trip an assertion if someone
  // tries to use |this| as a Profile.
  virtual void ProfileFunctionCallOnNonProfileBrowserContext1();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext2();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext3();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext4();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext5();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext6();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext7();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext8();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext9();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext10();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext11();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext12();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext13();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext14();
  virtual void ProfileFunctionCallOnNonProfileBrowserContext15();

 private:
  DISALLOW_COPY_AND_ASSIGN(ShellBrowserContext);
};

}  // namespace apps

#endif  // APPS_SHELL_BROWSER_SHELL_BROWSER_CONTEXT_H_


text:
This tool follows [PSR-2 Coding standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
## Testing

### Development workflow

My development workflow make use of grunt watch plugin, that will run phpunit automatically after each file save. Grunt is also used to generate the test coverage.

### Unit Tests

All pull request should not break existing tests. You're more than welcome to write additional tests. There is a grunt task to run the tests :

    grunt phpunit

Without grunt, just run :

    phpunit tests

Or you can also run tests after each file edition :

	grunt watch

### Test coverage

Use the coverage grunt task to generate code coverage.

    grunt coverage

Without grunt, use :

	phpunit tests

The coverage reports is in build/coverage/index.html.


text:
var LoadingUI = (function (_super) {
    __extends(LoadingUI, _super);
    function LoadingUI() {
        _super.call(this);
        this.createView();
    }
    var __egretProto__ = LoadingUI.prototype;
    __egretProto__.createView = function () {
        this.textField = new egret.TextField();
        this.addChild(this.textField);
        this.textField.y = 300;
        this.textField.width = 480;
        this.textField.height = 100;
        this.textField.textAlign = "center";
    };
    __egretProto__.setProgress = function (current, total) {
        //显示进度
        this.textField.text = "Loading..." + current + "/" + total;
    };
    return LoadingUI;
})(egret.Sprite);
LoadingUI.prototype.__class__ = "LoadingUI";


text:
# Easy-parking project

### travis-ci

[![travis-ci](https://api.travis-ci.org/lijun003/easyparking.svg)](https://travis-ci.org/lijun003/easyparking)

### BUILD

#### Generate IntelliJ IDEA project
`./gradlew cleanIdea idea`

Open the `easyparking.ipr` using IntelliJ

#### Run clean and build tasks
`./gradlew clean build`

This will run checkstyle, unit test and code coverage check

#### start application
`./gradlew bootRun` or `java -jar build/libs/easy-parking-0.1.0.jar`

### Git提交规范:

[卡号][提交作者&Pair作者] - comment here

Note: [提交作者]和comment之间需要有 空格+minus+空格,comment内容不要出现minus。

**Example:** `[M001][lijun&jason] - add the order domain object`

### Java代码规范:

- Java代码必须删去没有引用到的包,Import语句为灰色即是可删去。
- 类文件开始处不要出现 "/* xxx create xxx */" 这样自动生成的注释。
- 还有其他规范Checkstyle也会覆盖到


text:
package test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.purchasenear.common.ice.client.ICEClientUtil;
import org.purchasenear.service.ticket.interf.Order;
import org.purchasenear.service.ticket.interf.TicketServicePrx;

public class TestICE {

	@Test
	public void testCall() {
		TicketServicePrx ticketServicePrx = (TicketServicePrx) ICEClientUtil
				.getSerivcePrx(TicketServicePrx.class);
		Order[] orders = ticketServicePrx.queryMyOrders("13916969166");
		assertEquals(true, orders.length > 1);
	}
}


text:
"""
Project level  utilities and helpers
"""

##########################################################################
## Imports
##########################################################################

import re
import base64
import bleach
import hashlib

from functools import wraps
from markdown import markdown
from datetime import datetime

##########################################################################
## Utilities
##########################################################################

## Nullable kwargs for models
nullable = { 'blank': True, 'null': True, 'default':None }

## Not nullable kwargs for models
notnullable = { 'blank': False, 'null': False }

##########################################################################
## Helper functions
##########################################################################

def normalize(text):
    """
    Normalizes the text by removing all punctuation and spaces as well as
    making the string completely lowercase.
    """
    return re.sub(r'[^a-z0-9]+', '', text.lower())

def signature(text):
    """
    This helper method normalizes text and takes the SHA1 hash of it,
    returning the base64 encoded result. The normalization method includes
    the removal of punctuation and white space as well as making the case
    completely lowercase. These signatures will help us discover textual
    similarities between questions.
    """
    text = normalize(text).encode('utf-8')
    sign = base64.b64encode(hashlib.sha256(text).digest())
    return sign.decode('utf-8')

def htmlize(text):
    """
    This helper method renders Markdown then uses Bleach to sanitize it as
    well as convert all links to actual links.
    """
    text = bleach.clean(text, strip=True)    # Clean the text by stripping bad HTML tags
    text = markdown(text)                    # Convert the markdown to HTML
    text = bleach.linkify(text)              # Add links from the text and add nofollow to existing links

    return text

def identity(arg):
    """
    Simple identity function works as a passthrough.
    """
    return arg

##########################################################################
## Decorators
##########################################################################

def memoized(fget):
    """
    Return a property attribute for new-style classes that only calls its
    getter on the first access. The result is stored and on subsequent
    accesses is returned, preventing the need to call the getter any more.
    https://github.com/estebistec/python-memoized-property
    """
    attr_name = '_{0}'.format(fget.__name__)

    @wraps(fget)
    def fget_memoized(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, fget(self))
        return getattr(self, attr_name)

    return property(fget_memoized)

def timeit(func):
    """
    Simple wall clock timer for a function that runs in seconds. Returns a
    datetime.timedelta object for use in a models.DurationField.
    """

    @wraps(func)
    def func_timed(*args, **kwargs):
        start  = datetime.now()
        result = func(*args, **kwargs)
        return result, datetime.now() - start

    return func_timed


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Module dependencies.
var net = require('net');

function NamedPipeOutputChannel() { }

NamedPipeOutputChannel.prototype.writeOutputChannel = function (name, data, callback) {
  var client = net.connect(name);

  client.on('error', function (error) {
    if(callback) {
      callback(error);
    }
  });

  client.end(data);

  if (callback) {
    callback();
  }
};

module.exports = NamedPipeOutputChannel;


text:
package org.apache.hive.hcatalog.api;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.PartitionEventType;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hive.hcatalog.api.repl.ReplicationTask;
import org.apache.hive.hcatalog.common.HCatException;
import org.apache.hive.hcatalog.data.schema.HCatFieldSchema;

/**
 * The abstract class HCatClient containing APIs for HCatalog DDL commands.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public abstract class HCatClient {

  public enum DropDBMode {RESTRICT, CASCADE}

  public static final String HCAT_CLIENT_IMPL_CLASS = "hcat.client.impl.class";

  /**
   * Creates an instance of HCatClient.
   *
   * @param conf An instance of configuration.
   * @return An instance of HCatClient.
   * @throws HCatException
   */
  public static HCatClient create(Configuration conf) throws HCatException {
    HCatClient client = null;
    String className = conf.get(HCAT_CLIENT_IMPL_CLASS,
      HCatClientHMSImpl.class.getName());
    try {
      Class<? extends HCatClient> clientClass = Class.forName(className,
        true, Utilities.getSessionSpecifiedClassLoader()).asSubclass(
          HCatClient.class);
      client = (HCatClient) clientClass.newInstance();
    } catch (ClassNotFoundException e) {
      throw new HCatException(
        "ClassNotFoundException while creating client class.", e);
    } catch (InstantiationException e) {
      throw new HCatException(
        "InstantiationException while creating client class.", e);
    } catch (IllegalAccessException e) {
      throw new HCatException(
        "IllegalAccessException while creating client class.", e);
    }
    if (client != null) {
      client.initialize(conf);
    }
    return client;
  }

  abstract void initialize(Configuration conf) throws HCatException;

  /**
   * Fetch configuration value on conf that the HCatClient is instantiated
   * against. We do not want to expose the conf itself via a getConf(), because
   * we do not want it modifiable after instantiation of the HCatClient, but
   * modules that get called from HCatClient often need to know about how
   * HCatClient is configured, so we want a read-only interface for it.
   *
   * @param key keyname to look up
   * @param defaultVal default value to furnish in case the key does not exist
   * @return value for given key, and defaultVal if key is not present in conf
   */
  public abstract String getConfVal(String key, String defaultVal);

  /**
   * Get all existing databases that match the given
   * pattern. The matching occurs as per Java regular expressions
   *
   * @param pattern  java re pattern
   * @return list of database names
   * @throws HCatException
   */
  public abstract List<String> listDatabaseNamesByPattern(String pattern)
    throws HCatException;

  /**
   * Gets the database.
   *
   * @param dbName The name of the database.
   * @return An instance of HCatDatabaseInfo.
   * @throws HCatException
   */
  public abstract HCatDatabase getDatabase(String dbName) throws HCatException;

  /**
   * Creates the database.
   *
   * @param dbInfo An instance of HCatCreateDBDesc.
   * @throws HCatException
   */
  public abstract void createDatabase(HCatCreateDBDesc dbInfo)
    throws HCatException;

  /**
   * Drops a database.
   *
   * @param dbName The name of the database to delete.
   * @param ifExists Hive returns an error if the database specified does not exist,
   *                 unless ifExists is set to true.
   * @param mode This is set to either "restrict" or "cascade". Restrict will
   *             remove the schema if all the tables are empty. Cascade removes
   *             everything including data and definitions.
   * @throws HCatException
   */
  public abstract void dropDatabase(String dbName, boolean ifExists,
                    DropDBMode mode) throws HCatException;

  /**
   * Returns all existing tables from the specified database which match the given
   * pattern. The matching occurs as per Java regular expressions.
   * @param dbName The name of the DB (to be searched)
   * @param tablePattern The regex for the table-name
   * @return list of table names
   * @throws HCatException
   */
  public abstract List<String> listTableNamesByPattern(String dbName, String tablePattern)
    throws HCatException;

  /**
   * Gets the table.
   *
   * @param dbName The name of the database.
   * @param tableName The name of the table.
   * @return An instance of HCatTableInfo.
   * @throws HCatException
   */
  public abstract HCatTable getTable(String dbName, String tableName)
    throws HCatException;

  /**
   * Creates the table.
   *
   * @param createTableDesc An instance of HCatCreateTableDesc class.
   * @throws HCatException
   */
  public abstract void createTable(HCatCreateTableDesc createTableDesc) throws HCatException;

  /**
   * Updates the Table's column schema to the specified definition.
   *
   * @param dbName The name of the database.
   * @param tableName The name of the table.
   * @param columnSchema The (new) definition of the column schema (i.e. list of fields).
   *
   */
  public abstract void updateTableSchema(String dbName, String tableName, List<HCatFieldSchema> columnSchema)
    throws HCatException;

  /**
   * Updates the Table's whole schema (including column schema, I/O Formats, SerDe definitions, etc.)
   * @param dbName The name of the database.
   * @param tableName The name of the table.
   * @param newTableDefinition The (new) definition of the table.
   * @throws HCatException
   */
  public abstract void updateTableSchema(String dbName, String tableName, HCatTable newTableDefinition)
      throws HCatException;

  /**
   * Serializer for HCatTable.
   * @param hcatTable The HCatTable to be serialized into string form
   * @return String representation of the HCatTable.
   * @throws HCatException on failure to serialize.
   */
  public abstract String serializeTable(HCatTable hcatTable) throws HCatException;

  /**
   * Deserializer for HCatTable.
   * @param hcatTableStringRep The String representation of an HCatTable, presumably retrieved from {@link #serializeTable(HCatTable)}
   * @return HCatTable reconstructed from the string
   * throws HCatException, on failure to deserialize.
   */
  public abstract HCatTable deserializeTable(String hcatTableStringRep) throws HCatException;

  /**
   * Serializer for HCatPartition.
   * @param hcatPartition The HCatPartition instance to be serialized.
   * @return String representation of the HCatPartition.
   * @throws HCatException on failure to serialize.
   */
  public abstract String serializePartition(HCatPartition hcatPartition) throws HCatException;

  /**
   * Serializer for a list of HCatPartition.
   * @param hcatPartitions The HCatPartitions to be serialized.
   * @return A list of Strings, each representing an HCatPartition.
   * @throws HCatException on failure to serialize.
   */
  public abstract List<String> serializePartitions(List<HCatPartition> hcatPartitions) throws HCatException;

  /**
   * Deserializer for an HCatPartition.
   * @param hcatPartitionStringRep The String representation of the HCatPartition, presumably retrieved from {@link #serializePartition(HCatPartition)}
   * @return HCatPartition instance reconstructed from the string.
   * @throws HCatException on failure to deserialze.
   */
  public abstract HCatPartition deserializePartition(String hcatPartitionStringRep) throws HCatException;

  /**
   * Deserializer for a list of HCatPartition strings.
   * @param hcatPartitionStringReps The list of HCatPartition strings to be deserialized.
   * @return A list of HCatPartition instances, each reconstructed from an entry in the string-list.
   * @throws HCatException on failure to deserialize.
   */
  public abstract List<HCatPartition> deserializePartitions(List<String> hcatPartitionStringReps) throws HCatException;

  /**
   * Serializer for HCatPartitionSpec.
   * @param partitionSpec HCatPartitionSpec to be serialized.
   * @return A list of Strings, representing the HCatPartitionSpec as a whole.
   * @throws HCatException On failure to serialize.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract List<String> serializePartitionSpec(HCatPartitionSpec partitionSpec) throws HCatException;

  /**
   * Deserializer for HCatPartitionSpec.
   * @param hcatPartitionSpecStrings List of strings, representing the HCatPartitionSpec as a whole.
   * @return HCatPartitionSpec, reconstructed from the list of strings.
   * @throws HCatException On failure to deserialize.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract HCatPartitionSpec deserializePartitionSpec(List<String> hcatPartitionSpecStrings) throws HCatException;

  /**
   * Creates the table like an existing table.
   *
   * @param dbName The name of the database.
   * @param existingTblName The name of the existing table.
   * @param newTableName The name of the new table.
   * @param ifNotExists If true, then error related to already table existing is skipped.
   * @param isExternal Set to "true", if table has be created at a different
   *                   location other than default.
   * @param location The location for the table.
   * @throws HCatException
   */
  public abstract void createTableLike(String dbName, String existingTblName,
                     String newTableName, boolean ifNotExists, boolean isExternal,
                     String location) throws HCatException;

  /**
   * Drop table.
   *
   * @param dbName The name of the database.
   * @param tableName The name of the table.
   * @param ifExists Hive returns an error if the database specified does not exist,
   *                 unless ifExists is set to true.
   * @throws HCatException
   */
  public abstract void dropTable(String dbName, String tableName,
                   boolean ifExists) throws HCatException;

  /**
   * Renames a table.
   *
   * @param dbName The name of the database.
   * @param oldName The name of the table to be renamed.
   * @param newName The new name of the table.
   * @throws HCatException
   */
  public abstract void renameTable(String dbName, String oldName,
                   String newName) throws HCatException;

  /**
   * Gets all the partitions.
   *
   * @param dbName The name of the database.
   * @param tblName The name of the table.
   * @return A list of partitions.
   * @throws HCatException
   */
  public abstract List<HCatPartition> getPartitions(String dbName, String tblName)
    throws HCatException;

  /**
   * Gets all the partitions that match the specified (and possibly partial) partition specification.
   * A partial partition-specification is one where not all partition-keys have associated values. For example,
   * for a table ('myDb.myTable') with 2 partition keys (dt string, region string),
   * if for each dt ('20120101', '20120102', etc.) there can exist 3 regions ('us', 'uk', 'in'), then,
   *  1. Complete partition spec: getPartitions('myDb', 'myTable', {dt='20120101', region='us'}) would return 1 partition.
   *  2. Partial  partition spec: getPartitions('myDb', 'myTable', {dt='20120101'}) would return all 3 partitions,
   *                              with dt='20120101' (i.e. region = 'us', 'uk' and 'in').
   * @param dbName The name of the database.
   * @param tblName The name of the table.
   * @param partitionSpec The partition specification. (Need not include all partition keys.)
   * @return A list of partitions.
   * @throws HCatException
   */
  public abstract List<HCatPartition> getPartitions(String dbName, String tblName, Map<String, String> partitionSpec)
    throws HCatException;

  /**
   * Gets partitions in terms of generic HCatPartitionSpec instances.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract HCatPartitionSpec getPartitionSpecs(String dbName, String tableName, int maxPartitions) throws HCatException;

  /**
   * Gets partitions in terms of generic HCatPartitionSpec instances.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract HCatPartitionSpec getPartitionSpecs(String dbName, String tableName, Map<String, String> partitionSelector, int maxPartitions)
    throws HCatException;

  /**
   * Gets the partition.
   *
   * @param dbName The database name.
   * @param tableName The table name.
   * @param partitionSpec The partition specification, {[col_name,value],[col_name2,value2]}. All partition-key-values
   *                      must be specified.
   * @return An instance of HCatPartitionInfo.
   * @throws HCatException
   */
  public abstract HCatPartition getPartition(String dbName, String tableName,
                         Map<String, String> partitionSpec) throws HCatException;

  /**
   * Adds the partition.
   *
   * @param partInfo An instance of HCatAddPartitionDesc.
   * @throws HCatException
   */
  public abstract void addPartition(HCatAddPartitionDesc partInfo)
    throws HCatException;

  /**
   * Adds a list of partitions.
   *
   * @param partInfoList A list of HCatAddPartitionDesc.
   * @return The number of partitions added.
   * @throws HCatException
   */
  public abstract int addPartitions(List<HCatAddPartitionDesc> partInfoList)
    throws HCatException;

  /**
   * Adds partitions using HCatPartitionSpec.
   * @param partitionSpec The HCatPartitionSpec representing the set of partitions added.
   * @return The number of partitions added.
   * @throws HCatException On failure to add partitions.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract int addPartitionSpec(HCatPartitionSpec partitionSpec)
    throws HCatException;

  /**
   * Drops partition(s) that match the specified (and possibly partial) partition specification.
   * A partial partition-specification is one where not all partition-keys have associated values. For example,
   * for a table ('myDb.myTable') with 2 partition keys (dt string, region string),
   * if for each dt ('20120101', '20120102', etc.) there can exist 3 regions ('us', 'uk', 'in'), then,
   *  1. Complete partition spec: dropPartitions('myDb', 'myTable', {dt='20120101', region='us'}) would drop 1 partition.
   *  2. Partial  partition spec: dropPartitions('myDb', 'myTable', {dt='20120101'}) would drop all 3 partitions,
   *                              with dt='20120101' (i.e. region = 'us', 'uk' and 'in').
   * @param dbName The database name.
   * @param tableName The table name.
   * @param partitionSpec The partition specification, {[col_name,value],[col_name2,value2]}.
   * @param ifExists Hive returns an error if the partition specified does not exist, unless ifExists is set to true.
   * @throws HCatException
   * @throws ConnectionFailureException
   */
  public abstract void dropPartitions(String dbName, String tableName,
                    Map<String, String> partitionSpec, boolean ifExists)
    throws HCatException;

  /**
   * Drops partition(s) that match the specified (and possibly partial) partition specification.
   * A partial partition-specification is one where not all partition-keys have associated values. For example,
   * for a table ('myDb.myTable') with 2 partition keys (dt string, region string),
   * if for each dt ('20120101', '20120102', etc.) there can exist 3 regions ('us', 'uk', 'in'), then,
   *  1. Complete partition spec: dropPartitions('myDb', 'myTable', {dt='20120101', region='us'}) would drop 1 partition.
   *  2. Partial  partition spec: dropPartitions('myDb', 'myTable', {dt='20120101'}) would drop all 3 partitions,
   *                              with dt='20120101' (i.e. region = 'us', 'uk' and 'in').
   * @param dbName The database name.
   * @param tableName The table name.
   * @param partitionSpec The partition specification, {[col_name,value],[col_name2,value2]}.
   * @param ifExists Hive returns an error if the partition specified does not exist, unless ifExists is set to true.
   * @param deleteData Whether to delete the underlying data.
   * @throws HCatException
   * @throws ConnectionFailureException
   */
   public abstract void dropPartitions(String dbName, String tableName,
                    Map<String, String> partitionSpec, boolean ifExists, boolean deleteData)
    throws HCatException;
  /**
   * List partitions by filter.
   *
   * @param dbName The database name.
   * @param tblName The table name.
   * @param filter The filter string,
   *    for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
   *    be done only on string partition keys.
   * @return list of partitions
   * @throws HCatException
   */
  public abstract List<HCatPartition> listPartitionsByFilter(String dbName, String tblName,
                                 String filter) throws HCatException;

  /**
   * List partitions by filter, but as HCatPartitionSpecs.
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract HCatPartitionSpec listPartitionSpecsByFilter(String dbName, String tblName,
                                                               String filter, int maxPartitions) throws HCatException;

  /**
   * Mark partition for event.
   *
   * @param dbName The database name.
   * @param tblName The table name.
   * @param partKVs the key-values associated with the partition.
   * @param eventType the event type
   * @throws HCatException
   */
  public abstract void markPartitionForEvent(String dbName, String tblName,
                         Map<String, String> partKVs, PartitionEventType eventType)
    throws HCatException;

  /**
   * Checks if a partition is marked for event.
   *
   * @param dbName the db name
   * @param tblName the table name
   * @param partKVs the key-values associated with the partition.
   * @param eventType the event type
   * @return true, if is partition marked for event
   * @throws HCatException
   */
  public abstract boolean isPartitionMarkedForEvent(String dbName, String tblName,
                            Map<String, String> partKVs, PartitionEventType eventType)
    throws HCatException;

  /**
   * Gets the delegation token.
   *
   * @param owner the owner
   * @param renewerKerberosPrincipalName the renewer kerberos principal name
   * @return the delegation token
   * @throws HCatException
   * @throws ConnectionFailureException
   */
  public abstract String getDelegationToken(String owner,
                        String renewerKerberosPrincipalName) throws HCatException;

  /**
   * Renew delegation token.
   *
   * @param tokenStrForm the token string
   * @return the new expiration time
   * @throws HCatException
   */
  public abstract long renewDelegationToken(String tokenStrForm)
    throws HCatException;

  /**
   * Cancel delegation token.
   *
   * @param tokenStrForm the token string
   * @throws HCatException
   */
  public abstract void cancelDelegationToken(String tokenStrForm)
    throws HCatException;

  /**
   * Retrieve Message-bus topic for a table.
   *
   * @param dbName The name of the DB.
   * @param tableName The name of the table.
   * @return Topic-name for the message-bus on which messages will be sent for the specified table.
   * By default, this is set to <db-name>.<table-name>. Returns null when not set.
   */
  public abstract String getMessageBusTopicName(String dbName, String tableName) throws HCatException;

  /**
   * Get an iterator that iterates over a list of replication tasks needed to replicate all the
   * events that have taken place for a given db/table.
   * @param lastEventId : The last event id that was processed for this reader. The returned
   *                    replication tasks will start from this point forward
   * @param maxEvents : Maximum number of events to consider for generating the
   *                  replication tasks. If < 1, then all available events will be considered.
   * @param dbName : The database name for which we're interested in the events for.
   * @param tableName : The table name for which we're interested in the events for - if null,
   *                  then this function will behave as if it were running at a db level.
   * @return an iterator over a list of replication events that can be processed one by one.
   * @throws HCatException
   */
  @InterfaceStability.Evolving
  public abstract Iterator<ReplicationTask> getReplicationTasks(
      long lastEventId, int maxEvents, String dbName, String tableName) throws HCatException;

  /**
   * Get a list of notifications
   * @param lastEventId The last event id that was consumed by this reader.  The returned
   *                    notifications will start at the next eventId available this eventId that
   *                    matches the filter.
   * @param maxEvents Maximum number of events to return.  If < 1, then all available events will
   *                  be returned.
   * @param filter Filter to determine if message should be accepted.  If null, then all
   *               available events up to maxEvents will be returned.
   * @return list of notifications, sorted by eventId.  It is guaranteed that the events are in
   * the order that the operations were done on the database.
   * @throws HCatException
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract List<HCatNotificationEvent> getNextNotification(long lastEventId,
                                                                  int maxEvents,
                                                                  IMetaStoreClient.NotificationFilter filter)
      throws HCatException;

  /**
   * Get the most recently used notification id.
   * @return
   * @throws HCatException
   */
  @InterfaceAudience.LimitedPrivate({"Hive"})
  @InterfaceStability.Evolving
  public abstract long getCurrentNotificationEventId() throws HCatException;

  /**
   * Close the hcatalog client.
   *
   * @throws HCatException
   */
  public abstract void close() throws HCatException;
}


text:
Contributing to Pico
====================

Pico aims to be a high quality Content Management System (CMS) but at the same time wants to give contributors freedom when submitting fixes or improvements.

As such we want to *encourage* but not obligate you, the contributor, to follow these guidelines. The only exception to this are the guidelines elucidated in the *Prevent `merge-hell`* section.

Having said that: we really appreciate it when you apply the guidelines in part or wholly as that will save us time which, in turn, we can spend on bugfixes and new features.

Issues
------

If you want to report an *issue* with Pico's core, please create a new [Issue](https://github.com/picocms/Pico/issues) on GitHub. Concerning problems with plugins or themes, please refer to the website of the developer of this plugin or theme.

Before creating a [new Issue on GitHub](https://github.com/picocms/Pico/issues/new), please make sure the problem wasn't reported yet using [GitHubs search engine](https://github.com/picocms/Pico/search?type=Issues).

Please describe your issue as clear as possible and always include the *Pico version* you're using. Provided that you're using *plugins*, include a list of them too. We need information about the *actual and expected behavior*, the *steps to reproduce* the problem, and what steps you have taken to resolve the problem by yourself (i.e. *your own troubleshooting*).

Contributing code
-----------------

Once you decide you want to contribute to *Pico's core* (which we really appreciate!) you can fork the project from https://github.com/picocms/Pico. If you're interested in developing a *plugin* or *theme* for Pico, please refer to the [development section](http://picocms.org/development/) of our website.

### Prevent `merge-hell`

Please do *not* develop your contribution on the `master` branch of your fork, but create a separate feature branch, that is based off the `master` branch, for each feature that you want to contribute.

> Not doing so means that if you decide to work on two separate features and place a pull request for one of them, that the changes of the other issue that you are working on is also submitted. Even if it is not completely finished.

To get more information about the usage of Git, please refer to the [Pro Git book](https://git-scm.com/book) written by Scott Chacon and/or [this help page of GitHub](https://help.github.com/articles/using-pull-requests).

### Pull Requests

Please keep in mind that pull requests should be small (i.e. one feature per request), stick to existing coding conventions and documentation should be updated if required. It's encouraged to make commits of logical units and check for unnecessary whitespace before committing (try `git diff --check`). Please reference issue numbers in your commit messages where appropriate.

### Coding Standards

Pico uses the [PSR-2 Coding Standard](http://www.php-fig.org/psr/psr-2/) as defined by the [PHP Framework Interoperability Group (PHP-FIG)](http://www.php-fig.org/).

For historical reasons we don't use formal namespaces. Markdown files in the `content-sample` folder (the inline documentation) must follow a hard limit of 80 characters line length.

It is recommended to check your code using [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) using Pico's `.phpcs.xml` standard. Use the following command:

    $ ./vendor/bin/phpcs --standard=.phpcs.xml [file]...

With this command you can specify a file or folder to limit which files it will check or omit that argument altogether, in which case the current working directory is checked.

### Keep documentation in sync

Pico accepts the problems of having redundant documentation on different places (concretely Pico's inline user docs, the `README.md` and the website) for the sake of a better user experience. When updating the docs, please make sure to keep them in sync.

If you update the [`README.md`](https://github.com/picocms/Pico/blob/master/README.md) or [`content-sample/index.md`](https://github.com/picocms/Pico/blob/master/content-sample/index.md), please make sure to update the corresponding files in the [`_docs`](https://github.com/picocms/Pico/tree/gh-pages/_docs/) folder of the `gh-pages` branch (i.e. [Pico's website](http://picocms.org/docs/)) and vice versa. Unfortunately this involves three (!) different markdown parsers. If you're experiencing problems, use Pico's [`erusev/parsedown-extra`](https://github.com/erusev/parsedown-extra) as a reference. You can try to make the contents compatible to [Redcarpet](https://github.com/vmg/redcarpet) by yourself, otherwise please address the issues in your pull request message and we'll take care of it.

Versioning
----------

Pico follows [Semantic Versioning 2.0](http://semver.org) and uses version numbers like `MAJOR`.`MINOR`.`PATCH`. We will increment the:

- `MAJOR` version when we make incompatible API changes,
- `MINOR` version when we add functionality in a backwards-compatible manner, and
- `PATCH` version when we make backwards-compatible bug fixes.

For more information please refer to the http://semver.org website.

Branching
---------

The `master` branch contains the current development version of Pico. It is likely *unstable* and *not ready for production use*.

However, the `master` branch always consists of a deployable (but not necessarily deployed) version of Pico. As soon as development of a new `MAJOR` or `MINOR` release starts, a separate branch (e.g. `pico-1.1`) is created and a [pull request](https://github.com/picocms/Pico/pulls) is opened to receive the desired feedback.

Pico's actual development happens in separate development branches. Development branches are prefixed by:

- `feature/` for bigger features,
- `enhancement/` for smaller improvements, and
- `bugfix/` for non-trivial bug fixes.

As soon as development reaches a point where feedback is appreciated, a pull request is opened. After some time (very soon for bug fixes, and other improvements should have a reasonable feedback phase) the pull request is merged and the development branch will be deleted. Trivial bug fixes which will be part of the next `PATCH` version will be merged directly into `master`.

Build & Release process
-----------------------

We're using [Travis CI](https://travis-ci.com) to automate the build & release process of Pico. It generates and deploys [phpDoc](http://phpdoc.org) class docs for new releases and on every commit to the `master` branch. Travis also prepares new releases by generating Pico's pre-built packages and uploading them to GitHub. Please refer to [our `.travis.yml`](https://github.com/picocms/Pico/blob/master/.travis.yml) for details.

As insinuated above, it is important that each commit to `master` is deployable. Once development of a new Pico release is finished, trigger Pico's build & release process by pushing a new Git tag. This tag should reference a (usually empty) commit on `master`, which message should adhere to the following template:

```
Version 1.0.0

* [Security] ...
* [New] ...
* [Changed] ...
* [Fixed] ...
* [Removed] ...
```

Travis CI will draft the new [release on GitHub](https://github.com/picocms/Pico/releases) automatically, but will require you to manually amend the descriptions formatting. The latest Pico version is always available at https://github.com/picocms/Pico/releases/latest, so please make sure to publish this URL rather than version-specific URLs. [Packagist](http://packagist.org/packages/picocms/pico) will be updated automatically.


text:
The js or js.erb files in this top-level folder will be compiled and linked
by sprockets 4 as individually downloadble .js assets.

core.js.erb is the main js file which imports other .js files in
./components and includes js assets from external gem dependencies.

See https://github.com/rails/sprockets#link_directory

## rollupjs

We use rollupjs to compile js and css assets.

### rollup_compiled.js

This is the js output from ruinning `rollup --config rollup.config.js`
and is the compiled output from app/javascripts/renalware/application.js.

You need to have run `yarn install` before running rollup.

To keep rollup running (watching for changes), add the ` -w` switch to the rollup
command.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>Macaroon Playground</title>

Macaroon Playground

<form action="#" method="get">
  <input type="text" name="location" id="txtLocation" placeholder="location" value="http://www.example.org"/>
  <input type="text" name="identifier" id="txtIdentifier" placeholder="identifier" value="we used our secret key"/>
  <input type="text" name="secret" id="txtSecret" placeholder="secret" value="this is our super secret key; only we should know it"/>
  <button id="btnCreate" type="button">create</button>

  <textarea name="inspect" id="txtInspect" cols="50" rows="10" placeholder="macaroon details ... (press create)"></textarea>
</form>

<form action="#" method="get">
  <input type="text" name="caveat" id="txtCaveat" placeholder="add caveat" value="account = 3735928559"/>
  <button id="btnAddCaveat" type="button">add</button>
</form>

<form action="#" method="get">
  <button id="btnSerialize" type="button">serialize</button>
  <button id="btnDeSerialize" type="button">de-serialize</button>

  <textarea name="serialized" id="txtSerialized" cols="100" rows="1" placeholder="serialized ..."></textarea>
</form>

<form action="#" method="get">
  <button id="btnVerify" type="button">verify</button>
</form>


text:
package com.kimtis.graph;

import android.graphics.Color;
import android.graphics.Paint;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.kimtis.MainActivity;
import com.kimtis.MyApplication;
import com.kimtis.R;
import com.kimtis.data.CachedData;
import com.kimtis.data.EstmData;
import com.ppsoln.commons.position.NEV;

import java.util.LinkedList;
import java.util.Random;

import uiseok.skyplotview.SkyPlotViewCustom;
import uiseok.util.TypedValueCalculate;

public class GraphActivity extends AppCompatActivity {

    GraphView graphN, graphE, graphV;

    LocationManager mLM;

    TextView btn_stop, btn_start, btn_change;

    LineGraphSeries<DataPoint>
            n_series_before, n_series_modified,
            e_series_before, e_series_modified,
            v_series_before, v_series_modified;

    LinearLayout linear_nev, linear_plot;
    TextView text_r_h_err, text_r_v_err, text_r_3d_err;
    TextView text_m_h_err, text_m_v_err, text_m_3d_err;

    SkyPlotViewCustom errorView;

    int i = 0;
    double mLastRandom = 2;
    Random mRand = new Random();
    long x_zero_time = 0L;

    double avg_raw_horizontal_error = 0;
    double avg_raw_vertical_error = 0;
    double avg_raw_3d_error = 0;
    double avg_modified_horizontal_error = 0;
    double avg_modified_vertical_error = 0;
    double avg_modified_3d_error = 0;

    boolean isFirst = true;
//    private double getRandom() {
//        return mLastRandom += mRand.nextDouble() - mRand.nextDouble();
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_graph);

        linear_nev = (LinearLayout) findViewById(R.id.linear_nev);
        linear_plot = (LinearLayout) findViewById(R.id.linear_plot);
        text_r_h_err = (TextView) findViewById(R.id.text_r_hor_error);
        text_r_v_err = (TextView) findViewById(R.id.text_r_ver_error);
        text_r_3d_err = (TextView) findViewById(R.id.text_r_3d_error);
        text_m_h_err = (TextView) findViewById(R.id.text_m_hor_error);
        text_m_v_err = (TextView) findViewById(R.id.text_m_ver_error);
        text_m_3d_err = (TextView) findViewById(R.id.text_m_3d_error);

        graphN = (GraphView) findViewById(R.id.graph_n);
        graphE = (GraphView) findViewById(R.id.graph_e);
        graphV = (GraphView) findViewById(R.id.graph_v);

        // N_Graph Settings
        final Viewport n_viewport = graphN.getViewport();
        final LegendRenderer nlegendRenderer = graphN.getLegendRenderer();
        final GridLabelRenderer nlabelRenderer = graphN.getGridLabelRenderer();

        n_viewport.setScrollable(true);
        n_viewport.setScalable(true);
        n_viewport.setMinX(0);
        n_viewport.setDrawBorder(true);
        n_viewport.setBorderColor(Color.BLACK);
        graphN.setPadding(TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), 0);
        graphN.setTitle("Error with N");

        nlegendRenderer.setVisible(true);
        nlegendRenderer.setBackgroundColor(Color.WHITE);
        nlegendRenderer.setTextSize(TypedValueCalculate.dp2pixel(9, this));
        nlegendRenderer.setAlign(LegendRenderer.LegendAlign.TOP);
        graphN.setLegendRenderer(nlegendRenderer);

        nlabelRenderer.setHighlightZeroLines(true);
        nlabelRenderer.setVerticalLabelsVisible(true);
        nlabelRenderer.setVerticalAxisTitle(" ");

        n_series_before = new LineGraphSeries<DataPoint>();
        n_series_before.setAnimated(true);
        n_series_before.setDrawDataPoints(false);
        n_series_before.setTitle("Raw");

        graphN.addSeries(n_series_before);

        Paint modified_paint = new Paint();
        modified_paint.setColor(Color.RED);
        modified_paint.setStrokeWidth(TypedValueCalculate.dp2pixel(1, MyApplication.getContext()));

        n_series_modified = new LineGraphSeries<DataPoint>();
        n_series_modified.setAnimated(true);
        n_series_modified.setDrawDataPoints(false);
        n_series_modified.setCustomPaint(modified_paint);
        n_series_modified.setTitle("Modified");
        n_series_modified.setColor(Color.RED);
        graphN.addSeries(n_series_modified);

        // E_Graph Settings
        final Viewport e_viewport = graphE.getViewport();
        final LegendRenderer elegendRenderer = graphE.getLegendRenderer();
        final GridLabelRenderer elabelRenderer = graphE.getGridLabelRenderer();

        e_viewport.setScrollable(true);
        e_viewport.setScalable(true);
        e_viewport.setMinX(0);
        e_viewport.setDrawBorder(true);
        e_viewport.setBorderColor(Color.BLACK);
        graphE.setPadding(TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), 0);
        graphE.setTitle("Error with E");
        elabelRenderer.setHighlightZeroLines(true);
        elabelRenderer.setHighlightZeroLines(true);
        elabelRenderer.setVerticalLabelsVisible(true);
        elabelRenderer.setVerticalAxisTitle(" ");

        elegendRenderer.setVisible(true);
        elegendRenderer.setBackgroundColor(Color.WHITE);
        elegendRenderer.setTextSize(TypedValueCalculate.dp2pixel(9, this));
        elegendRenderer.setAlign(LegendRenderer.LegendAlign.TOP);
        graphE.setLegendRenderer(elegendRenderer);

        e_series_before = new LineGraphSeries<DataPoint>();
        e_series_before.setAnimated(true);
        e_series_before.setDrawDataPoints(false);
        e_series_before.setTitle("Raw");
        graphE.addSeries(e_series_before);

        e_series_modified = new LineGraphSeries<DataPoint>();
        e_series_modified.setAnimated(true);
        e_series_modified.setDrawDataPoints(false);
        e_series_modified.setCustomPaint(modified_paint);
        e_series_modified.setTitle("Modified");
        e_series_modified.setColor(Color.RED);
        graphE.addSeries(e_series_modified);

        // V_Graph Settings
        final Viewport v_viewport = graphV.getViewport();
        final LegendRenderer vlegendRenderer = graphV.getLegendRenderer();
        final GridLabelRenderer vlabelRenderer = graphV.getGridLabelRenderer();

        v_viewport.setScrollable(true);
        v_viewport.setScalable(true);
        v_viewport.setMinX(0);
        v_viewport.setDrawBorder(true);
        v_viewport.setBorderColor(Color.BLACK);
        graphV.setPadding(TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), TypedValueCalculate.dp2pixel(10, this), 0);
        graphV.setTitle("Error with V");
        vlabelRenderer.setHighlightZeroLines(true);
        vlabelRenderer.setHighlightZeroLines(true);
        vlabelRenderer.setVerticalLabelsVisible(true);
        vlabelRenderer.setVerticalAxisTitle(" ");

        vlegendRenderer.setVisible(true);
        vlegendRenderer.setBackgroundColor(Color.WHITE);
        vlegendRenderer.setTextSize(TypedValueCalculate.dp2pixel(9, this));
        vlegendRenderer.setAlign(LegendRenderer.LegendAlign.TOP);
        graphV.setLegendRenderer(vlegendRenderer);

        v_series_before = new LineGraphSeries<DataPoint>();
        v_series_before.setAnimated(true);
        v_series_before.setDrawDataPoints(false);
        v_series_before.setTitle("Raw");
        graphV.addSeries(v_series_before);

        v_series_modified = new LineGraphSeries<DataPoint>();
        v_series_modified.setAnimated(true);
        v_series_modified.setDrawDataPoints(false);
        v_series_modified.setCustomPaint(modified_paint);
        v_series_modified.setTitle("Modified");
        v_series_modified.setColor(Color.RED);
        graphV.addSeries(v_series_modified);

        errorView = (SkyPlotViewCustom) findViewById(R.id.error_view);

        btn_start = (TextView) findViewById(R.id.btn_start);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.registerOnSkyPlotAddedListener(nListener);
                MainActivity.registerOnNmeaCPCalculatedListener(mListener);
            }
        });
        btn_stop = (TextView) findViewById(R.id.btn_stop);
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.unregisterOnSkyPlotAddedListener(nListener);
                MainActivity.unregisterOnNmeaCPCalculatedListener(mListener);
            }
        });

        btn_change = (TextView) findViewById(R.id.btn_change);
        btn_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (linear_nev.getVisibility() == LinearLayout.VISIBLE) {
                    linear_nev.setVisibility(LinearLayout.GONE);
                    linear_plot.setVisibility(LinearLayout.VISIBLE);
                } else {
                    linear_nev.setVisibility(LinearLayout.VISIBLE);
                    linear_plot.setVisibility(LinearLayout.GONE);
                }
            }
        });

    }

    MainActivity.OnSkyPlotAddedListener nListener = new MainActivity.OnSkyPlotAddedListener() {
        @Override
        public void onSkyPlotAdded() {

        }

    };

    MainActivity.OnNmeaCPCalculatedListener mListener = new MainActivity.OnNmeaCPCalculatedListener() {
        @Override
        public void onNmeaCPCalculated() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (!((LinkedList) CachedData.getInstance().getEstmDataList()).isEmpty() && isFirst) {
                        x_zero_time = ((EstmData) ((LinkedList) CachedData.getInstance().getEstmDataList()).getFirst()).getTime().getTime() / 1000;
                        isFirst = false;
                    }

                    if (x_zero_time != 0L) {
                        EstmData current_estm = (EstmData) ((LinkedList) CachedData.getInstance().getEstmDataList()).getLast();
                        NEV before_nev = current_estm.getNEV(current_estm.getBefore_latLngAlt());
                        NEV modified_nev = current_estm.getNEV(current_estm.getModified_latLngAlt());

                        n_series_modified.appendData(new DataPoint(
                                (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                modified_nev.getN()), true, 100);

                        e_series_modified.appendData(new DataPoint(
                                (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                modified_nev.getE()), true, 100);

                        v_series_modified.appendData(new DataPoint(
                                (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                modified_nev.getV()), true, 100);

                        // TODO
                        errorView.drawErrorPoint(
                                modified_nev.getN(),
                                modified_nev.getE(),
                                modified_nev.getV(),
                                SkyPlotViewCustom.TYPE_MODIFIED
                        );
                        errorView.drawErrorPoint(-3.0,-5.0,0.0,SkyPlotViewCustom.TYPE_MODIFIED);

                        avg_modified_horizontal_error = avg_modified_horizontal_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.sqrt(Math.pow(modified_nev.getE(), 2) +
                                        Math.pow(modified_nev.getN(), 2)) * 1 / CachedData.getInstance().getEstmDataListSize();

                        avg_modified_vertical_error = avg_modified_vertical_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.abs(modified_nev.getV()) * 1 / CachedData.getInstance().getEstmDataListSize();

                        avg_modified_3d_error = avg_modified_3d_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.sqrt(Math.pow(modified_nev.getE(), 2) +
                                        Math.pow(modified_nev.getN(), 2) +
                                        Math.pow(modified_nev.getV(), 2)) * 1 / CachedData.getInstance().getEstmDataListSize();

                        text_m_h_err.setText(String.format("M Horizontal Error\n%.2f", avg_modified_horizontal_error));
                        text_m_v_err.setText(String.format("M Vertical Error\n%.2f", avg_modified_vertical_error));
                        text_m_3d_err.setText(String.format("M 3D Error\n%.2f", avg_modified_3d_error));

                        errorView.drawErrorPoint(
                                before_nev.getN(),
                                before_nev.getE(),
                                before_nev.getV(),
                                SkyPlotViewCustom.TYPE_BEFORE);
                        n_series_before.appendData(
                                new DataPoint(
                                        (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                        before_nev.getN()),
                                true,
                                100);
                        e_series_before.appendData(
                                new DataPoint(
                                        (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                        before_nev.getE()),
                                true,
                                100);

                        v_series_before.appendData(
                                new DataPoint(
                                        (double) (current_estm.getTime().getTime() / 1000 - x_zero_time),
                                        before_nev.getV()),
                                true,
                                100);
                        avg_raw_horizontal_error = avg_raw_horizontal_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.sqrt(Math.pow(before_nev.getE(), 2) +
                                        Math.pow(before_nev.getN(), 2)) * 1 / CachedData.getInstance().getEstmDataListSize();

                        avg_raw_vertical_error = avg_raw_vertical_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.abs(before_nev.getV()) * 1 / CachedData.getInstance().getEstmDataListSize();

                        avg_raw_3d_error = avg_raw_3d_error * (CachedData.getInstance().getEstmDataListSize() - 1) /
                                CachedData.getInstance().getEstmDataListSize() +
                                Math.sqrt(Math.pow(before_nev.getE(), 2) +
                                        Math.pow(before_nev.getN(), 2) +
                                        Math.pow(before_nev.getV(), 2)) * 1 / CachedData.getInstance().getEstmDataListSize();

                        text_r_h_err.setText(String.format("R Horizontal Error\n%.2f", avg_raw_horizontal_error));
                        text_r_v_err.setText(String.format("R Vertical Error\n%.2f", avg_raw_vertical_error));
                        text_r_3d_err.setText(String.format("R 3D Error\n%.2f", avg_raw_3d_error));

                    }
                }
            });

        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        MainActivity.registerOnNmeaCPCalculatedListener(mListener);
        MainActivity.registerOnSkyPlotAddedListener(nListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MainActivity.unregisterOnSkyPlotAddedListener(nListener);
        MainActivity.unregisterOnNmeaCPCalculatedListener(mListener);
    }

}