text:
package demo.drools.tests;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

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

import org.junit.Assert;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.command.Command;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;

import demo.drools.model.eshop.Customer;
import demo.drools.model.eshop.Order;

public class KieContainerClasspathTests
{

    @Test
    public void loadingRulesFromClassPath()
    {
        System.out.println("### Running loadingRulesFromClassPath() Test ###");
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.newKieClasspathContainer();

        // verify that all the resources are loaded correctly
        Results results = kContainer.verify();
        results.getMessages().stream().forEach((message) -> {
            System.out.println(">> Message ( " + message.getLevel() + " ): " + message.getText());
        });

        // If there is an Error we need to stop and correct it
        assertThat(false, is(results.hasMessages(Message.Level.ERROR)));

        kContainer.getKieBaseNames().stream().map((kieBase) -> {
            System.out.println(">> Loading KieBase: " + kieBase);
            return kieBase;
        }).forEach((kieBase) -> {
            kContainer.getKieSessionNamesInKieBase(kieBase).stream().forEach((kieSession) -> {
                System.out.println("\t >> Containing KieSession: " + kieSession);
            });
        });

        // Let's load the configurations for the kmodule.xml file
        // defined in the /src/test/resources/META-INF/ directory
        KieSession kieSession = kContainer.newKieSession("rules.cp.discount.session");

        Customer customer = new Customer();
        customer.setCategory(Customer.Category.BRONZE);

        Order order = new Order();
        order.setCustomer(customer);

        kieSession.insert(customer);
        kieSession.insert(order);

        int fired = kieSession.fireAllRules();

        assertThat(1, is(fired));
        assertThat(5.0, is(order.getDiscount().getPercentage()));

        System.out.println("### Finished loadingRulesFromLocalKieModule() Test ###");
    }

    @Test
    public void loadingRulesFromDependencyKieModule()
    {
        System.out.println("### Running loadingRulesFromDependencyKieModule() Test ###");
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.newKieClasspathContainer();

        Results results = kContainer.verify();
        results.getMessages().stream().forEach((message) -> {
            System.out.println(">> Message ( " + message.getLevel() + " ): " + message.getText());
        });
        assertThat(false, is(results.hasMessages(Message.Level.ERROR)));
        kContainer.getKieBaseNames().stream().map((kieBase) -> {
            System.out.println(">> Loading KieBase: " + kieBase);
            return kieBase;
        }).forEach((kieBase) -> {
            kContainer.getKieSessionNamesInKieBase(kieBase).stream().forEach((kieSession) -> {
                System.out.println("\t >> Containing KieSession: " + kieSession);
            });
        });

        // Let's load the configurations for the kmodule.xml file, rules.simple
        // Notice that here the rule defined in the tests is not loaded
        KieSession kieSession = kContainer.newKieSession("rules.simple.discount");

        Customer customer = new Customer();
        customer.setCategory(Customer.Category.SILVER);

        Order order = new Order();
        order.setCustomer(customer);

        kieSession.insert(customer);
        kieSession.insert(order);

        int fired = kieSession.fireAllRules();

        assertThat(1, is(fired));
        assertThat(10.0, is(order.getDiscount().getPercentage()));

        System.out.println("### Finished loadingRulesFromDependencyKieModule() Test ###");
    }

    @Test
    public void statelessSessionTest()
    {
        System.out.println("### Running statelessSessionTest() Test ###");
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.newKieClasspathContainer();

        Results results = kContainer.verify();
        results.getMessages().stream().forEach((message) -> {
            System.out.println(">> Message ( " + message.getLevel() + " ): " + message.getText());
        });
        assertThat(false, is(results.hasMessages(Message.Level.ERROR)));
        kContainer.getKieBaseNames().stream().map((kieBase) -> {
            System.out.println(">> Loading KieBase: " + kieBase);
            return kieBase;
        }).forEach((kieBase) -> {
            kContainer.getKieSessionNamesInKieBase(kieBase).stream().forEach((kieSession) -> {
                System.out.println("\t >> Containing KieSession: " + kieSession);
            });
        });

        StatelessKieSession statelessKieSession = kContainer.newStatelessKieSession("rules.simple.sl.discount");

        Assert.assertNotNull(statelessKieSession);

        Customer customer = new Customer();
        customer.setCategory(Customer.Category.SILVER);

        Order order = new Order();
        order.setCustomer(customer);

        Command newInsertOrder = ks.getCommands().newInsert(order, "orderOut");
        Command newInsertCustomer = ks.getCommands().newInsert(customer);
        Command newFireAllRules = ks.getCommands().newFireAllRules("outFired");
        List<Command> cmds = new ArrayList<Command>();
        cmds.add(newInsertOrder);
        cmds.add(newInsertCustomer);
        cmds.add(newFireAllRules);
        ExecutionResults execResults = statelessKieSession.execute(ks.getCommands().newBatchExecution(cmds));

        order = (Order) execResults.getValue("orderOut");
        int fired = (Integer) execResults.getValue("outFired");

        assertThat(1, is(fired));
        assertThat(10.0, is(order.getDiscount().getPercentage()));

        System.out.println("### Finished statelessSessionTest() Test ###");
    }

    @Test
    public void loadingRulesFromDependencyParentKieModule()
    {
        System.out.println("### Running loadingRulesFromDependencyParentKieModule() Test ###");
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.newKieClasspathContainer();

        Results results = kContainer.verify();
        results.getMessages().stream().forEach((message) -> {
            System.out.println(">> Message ( " + message.getLevel() + " ): " + message.getText());
        });
        assertThat(false, is(results.hasMessages(Message.Level.ERROR)));
        kContainer.getKieBaseNames().stream().map((kieBase) -> {
            System.out.println(">> Loading KieBase: " + kieBase);
            return kieBase;
        }).forEach((kieBase) -> {
            kContainer.getKieSessionNamesInKieBase(kieBase).stream().forEach((kieSession) -> {
                System.out.println("\t >> Containing KieSession: " + kieSession);
            });
        });

        // Let's load the configurations for the parent kmodule.xml file defined
        KieSession kieSession = kContainer.newKieSession("rules.discount.all");

        Customer customer = new Customer();
        customer.setCustomerId(1L);
        customer.setCategory(Customer.Category.SILVER);

        Order order = new Order();
        order.setCustomer(customer);

        kieSession.insert(customer);
        kieSession.insert(order);

        int fired = kieSession.fireAllRules();

        assertThat(1, is(fired));
        assertThat(10.0, is(order.getDiscount().getPercentage()));

        Customer customerGold = new Customer();
        customerGold.setCustomerId(2L);
        customerGold.setCategory(Customer.Category.GOLD);

        Order orderGold = new Order();
        orderGold.setCustomer(customerGold);

        kieSession.insert(customerGold);
        kieSession.insert(orderGold);

        fired = kieSession.fireAllRules();

        assertThat(1, is(fired));
        assertThat(20.0, is(orderGold.getDiscount().getPercentage()));

        System.out.println("### Finished loadingRulesFromDependencyParentKieModule() Test ###");
    }

}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Here's Drupal!</title>

    <meta name="description" content="The Tonight Show: A decoupled architecture, in code and in organization.">
    <meta name="author" content="Andrew Berry and David Diers">

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <link rel="stylesheet" href="css/reveal.min.css">
    <link rel="stylesheet" href="icomoon/style.css" id="icomoon">
    <link rel="stylesheet" href="css/theme/policy.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

Here's Drupal!

Tonight on the Tonight Show with Jimmy Fallon

           @deviantintegral
           of @lullabot &

@beautyhammer
            of @fourkitchens

Drupalcon Austin, June 3 2014 - Case Studies

The Stage

The Tonight Show is the longest-running television show in history, airing on NBC. It's got a long, storied history, with over 11,000 episodes since 1954.

This is The Tonight Show on NBC.com. The site is responsive, touch friendly, and is an app.

The 'net has given us the platform to share ourselves and our experiences.

TSJF's primary use case is highlighting sharable moments and making it as easy as possible to share them out. The cornerstone of our architecture

Here's Drupal! But not really. Drupal's just one component of several different systems, each built and tuned to support a specific set of functionality.

Today, David and I are going to talk about how we went from a Drupal installation screen, all the way to what you see today.

NBCUniversal is owned by Comcast, with over 136K employees.

Enterprise Software™

What do you think of when you hear the words "Enterprise software"?

Large

Complicated

Slow

18 months

But, think about just the basics that need to happen for a new or re-launched talk show.

Choosing the host (they will lead the creative direction)

Building the staff to support the show

Defining the creative direction and content of the show.

This has to happen before technical work can start.

We can't build a useful website until

A host is chosen

The creative direction is defined

This has to happen before technical work can start.

Even then, this just gets us to a website that could mirror the show.

We need to treat the web as something that isn't just bolted-on to a show. It needs to be a first-class component of the show experience.

A successful show site isn't just a list of episodes; it's got to be a channel for both repeat and unique content.

In the case of The Tonight Show, by the middle of December 2013 most of this work was complete enough to begin work on the site and apps.

Hard show launch date of February 17th, 2014, with a pre-show site needing to be launched a few weeks before.

Six Weeks

Before we get into how we approached this from the tech, let's talk about who was involved.

The Guests

NBC Entertainment Digital; they're responsible for anything and everything digital for the NBC television brand. It's their job to build and maintain whatever online tools shows need to be effective, competitive, and engaging.

NBC Operations and Tools Support; They're the team behind the Publisher 7 Drupal distribution used internally at NBC Digital.

CP+B the primary contractor for TSJF, they were responsible for designing and building both the web app and the mobile apps.

Four Kitchens and Lullabot on the Drupal team. We'd worked together on NBC.com (which at the time was in parallel development).

Both companies provided consultants, Drupal expertise, and developer resources.

The sun never set on the Tonight Show team.

Not only did we have a complex site to build, with a tight timeline, we had to with with a distributed team in both place and time.

We have all of these team members, variance in time, place, company, and background separating them. I remember thinking "if this project is going to launch on time and with a full set of features, we'll need to structure the architecture itself to be non-blocking and dependency free.."

To succeed, we need a non-blocking technical architecture.

Decompose the system

Our first task was to define the systems that needed to be built, and who owned what.

Then, we could map each system to each team's primary expertise and give them ownership over the product.

We started from the source of content (to us) and moved through each system all the way to the end user.

Our first task was to define the systems that needed to be built, and who owned what.

Then, we could map each system to each team's primary expertise and give them ownership over the product.

Content modelling needed to be a completely collaborative effort.

The API design was handled by the two Drupal architects and the lead CP+B architect.

API could be primarily on the tech teams, with NBC providing review.

P7 would be lead by 4K, Lullabot

Video is a special case; upstream video management systems, MPX.

Front end and apps handled by CP+B.

NBC became free to be our show and infrastructure experts.

In a way, it's like winning at "Lip Synch Battle"

Rules of lip synch battle - both take turns lip synching popular songs, do not know what the other player has picked, Jimmy always concedes to the other player.

Ok, it's actually nothing like winning at Lip Synch Battle.

But it is a little like playing

You don't know your opponents song - Low visibility to the intent of other teams - Allow independent iteration on all layers of the site

You can only control how well you do - Play to our strengths and have your team go for it - reduce and simplify developer dependencies

Lightly competitive structure --conducive to enable the best from your "opponents" that simply dissolves at the end for the benefit of all.

Our Non-Blocking Approach

The two biggest components are:

A COPE decoupled technology stack

Semantic content model

A decoupled app & web front end with a services based Drupal API layer.

And an abstracted semantic content model that supported great iteration.

This is a "standard" Drupal site. Content goes in, views go out.

And because this is a site with a ton of traffic, we've got multiple caching layers on top of it.

And because this is a site with a ton of traffic, we've got multiple caching layers on top of it.

And this is where everything changes!

Everything before... everything that makes what we'd consider to be a complete site... is simply an API living in the cloud.

So...Semantic what now?

I'll explain our Semantic content model in a moment but let's start with how we got there.

We started working on the API thought we could unblock for asynchronous work

BUT we quickly observed we were headed down a prescriptive and unsustainable path. - it's a bit like Jeopardy - start with the answers and form the questions (the development) later - the problem was that the answers we could create with the content model we had only allowed us to ask very specific questions.

Endpoints tended to be requests for very specific resources and the front end was dictating the content model.

The initial design was display centric with some concessions for REST

So...Semantic what now?

We thought we could unblock through the API

BUT

This got tightly coupled quickly

This was a display centric API with some concessions for REST

...

This was pretty close to a blocking workflow and clearly not going to help us suceed.

Front end and back ends are very coupled - reduces our reusability.

Content model did not have the flexibility production staff need longterm

This type of coupled content model is one that is composed of elements that drive specific displays. When changes come along to the displays or in fact to the business itself this requires a lot of work because the basis of the model was never the business itself only a set of displays at inception.

Based on this approach we realized that the biggest unblocker would be a quality content model

The Dawn of the Semantic Content Model

It can be easy in Drupal to have a page centric content model, you start your model from the pages or sections you want available and that then drives the fields, content and their relations

But that puts something very dangerous in the driver's seat?

The Dawn of the Semantic Content Model

Your site is driving your content in this page centric model.

It has the problems we discussed in our display centric content model - tightly coupled and neither flexible or sustainable.

TSJF doesnt exist because it has a website, so why let the website drive the modeling of the business? Ulitmately it's more meaningful if we let the show drive our site and our content model.

Semantic Content Modeling would have you create structures that resemble the real-life elements of your business

Since Drupal wasn't responsible for pages at all but content we had some very clear freedom from that pattern, and with a renewed mindfulness around display centric modeling we set about creating agnostic and dependency free endpoints.

The Dawn of the Semantic Content Model

Content structures resemble real-life

For the Tonight Show that meant content types would look like elements of the show

Semantic BUT Abstract

One other point about proceeding with semantic content modeling

Set the correct resolution on your model. Once the abstraction level (10,000 feet or 100 feet) is codified - it connects the dots between performance and production for the long-term

Direct modeling would be ungainly as Jimmy has tremendous variety in his recurring segments

Semantic BUT Abstract

Setting the correct resolution for semantics is important.

Addresses volatility in trends and interests - gives you flexibility

The Science of Semantics

The joke: smallest atomic unit of funny.

Eddie Lee from NBC Digital had this great insight to really push for the idea that the smallest meaningful component of the late show, is the joke, and that we could build from there.

It coincided perfectly with the mission of the site, the apps, and the property, to provide shareable moments that viewers, fans and their networks can experience the best moments time and again.

Thinking Semantically

Show elements:

Joke

Bit

Segment

Guests

Supporting elements:

Challenges

Games

In Practice

We ended up with a Semantic content model...MOSTLY

What we found is that it made sense to have a multi-layered content approach

The theory of it can be taken to far - it's like database optimization - too much becomes too unwieldy

The end result was a content model that would drive a restful site with a few sacrifices for display - rather than the other way around

Get the benefits of semantic content modeling plus the benefits of a familiar editorial workflow.

In Practice

Building Blocks

Video

image

carousel items

Semantic

Bits

Segments

Challenges

Games

Guests

Display-centric

Carousels

Blog Posts

Queues

Image Galleries

We created entities that weren't semantic but were building blocks to be used by the semantic content types

We then created semantic show based content types which tied these elements together through references that we could utilize as endpoints.

Finally we had several content types whose primary function was site/app display centric that could weave semantic elements and building blocks together freely.

Semantic Content Modeling Benefits

Gave all teams - developers, q/a, editorial a shared meaningful language that was native both to the show and the web stack.

Make sense editorially for the long term

Provided a familiar Drupal editorial process with a non-page based content paradigm

AND... now you've placed content in the driver's seat, your content is driving your properties not the other way around

Semantic Content Modeling Benefits

Shared Language for all teams

Sustainable

Looked like any other editorial process at NBC Digital

The business is final driving

The Second Part of our Non-blocking approach: The API

Establish Outs - Multi-platform, multi-team development needed to happen independently

Develop with agility, respond to volatility, free front-end up for frequent updates.

Hopefully save time by adopting some existing API work.

Provide continuity for editorial and support teams at NBC Digital.

The Second Part of our Non-blocking approach: The API

Establish Outputs

Decoupled - faster itterations and deployment

Leverage a pre-existing API framework

Consistent editorial experience

More than meets the API

At its core: An OOP API built on Drupal services.

BUT...it was more than that

At first glance the product of our API work would presumably be the API itself.

But it's more than that - it's also the API design.

The System is the Architect

The design of the API was the product it was a codex and approach that allowed us to work multi-threaded.  It was like a commitment of behavior.

This allowed our System to be the architect, Decoupled development needs a connecting tissue - that could be a person, a spec, or a system - since we couldn't be available all the time our design manifested in the API could and was.

Legally binding your web APIs came out of much of the TSJF API design work #self-promotion

A versionless, backwards compatible, hyrdra styled development approach - itterative and dependency free. The API was often feature forward of the app and site releases.

EXAMPLES: - A brand new resource needs to be created we have that stubbed. We even went so far as to detail how inner endpoint resources would look - so teams could build their features ahead of actual drupal implementation.

The System is the Architect

IF decoupled development needs a lynch pin - Why not make it your API?

The API as a commitment of behavior

Versionless, backwards compatible, and dependency free.

API Concerns

YES

Provide Semantic content

Provide display content

Be performant

Respect permissions, state

Deliver agnostic and predicatable resource managment

NO

Routing

Display tailored results

Authenticated audience interaction

Here are the basic concerns of our API

Provided a highly customizable way to select indvidual and groups of semantic and display-centric content for endpoints

Deliver endpoints quickly and accurately - Content caching and permissions, and responsive ready inner resource patterns in a familiar way to the enterprise (in use on one other property)

Routing, specific tailored results, and authenticated interaction were all handled elsewhere

That's no API, it's a PHPOOPAPI

Even within a services based API solution - there are options - why not site build for speed? - It may be fast to get out there but it is not fast to itterate on asynchronously.

OOP code was more sensible than features or views code - easy to see what had been changed while teams worked around the clock and easy to extend cleanly and consistently

Using a heavliy PHP OOP solution let us leverage the available expertise and resources in a sustainable way - still deliver a familiar editorial and backend solution.

Solve for the obtuse in one place - keep drupalisms low to the ground

That's no API, it's a PHPOOPAPI

Let us utilize available strong PHP OOP resources

OOP inheritence let us shift complexity down and simplify implementing classes

Simpler implementations gave us cleaner asynchronous workflows.

The API In practice.

The API was structured similarly so that calls could be placed in reliable ways.

An API call to a display centric resource looks something like this:

episodes?id=15

The API In practice.

You might get something back like this:

{
    "episodes": [
        {
            "type": "episode",
            "episodeNumber": "15",
            "name": "Jimmy and Justin",
            "season": "1",
            "airDate": "2014-03-05T00:00:00-05:00",
            "guests": [ {"id": "123"},{"id": "124"} ],
            "merlinId": "",
            "images":[
                {
                    "id":"642",
                    "description":"Scenes from the Tonight Show with Jimmy Fallon.",
                    "orientation":"portrait",
                    "emphasized":false,
                    "isGif":false,
                    "url":"http://tonightshowpath.com/files/images/2014/02/05/img_20130309_140147_1.jpg",
                    "bitImageStacked":"http://tonightshowpath.com/files/styles/bit_stacked_resized/public/images/2014/02/05/img_20130309_140147_1.jpg?itok=NUKlRWNu",
                    "detailImageSmall":"http://tonightshowpath.com/files/styles/detail_image_small_portrait/public/images/2014/02/05/img_20130309_140147_1.jpg?itok=ApiJp4Od",
                    "detailImageMedium":"http://tonightshowpath.com/files/styles/detail_image_medium_portrait/public/images/2014/02/05/img_20130309_140147_1.jpg?itok=WakkI2CC",
                    "detailImageLarge":"http://tonightshowpath.com/files/styles/detail_image_large_portrait/public/images/2014/02/05/img_20130309_140147_1.jpg?itok=3s6NWs-A"
                }
            ]
        },

From a display centric endpoint you are given several paths into the semantic content endpoints

The actual resources (images and videos) are going to be served out via the CDN

The API In practice.

An API call to a semantic resource looks something like this:

guests/124

The API In practice.

{
    "id": "127",
    "name": "Britney Spears",
    "headshotImage": [{
        "id": "123",
        "title": "Slim Shady image",
        "description": "Jimmy and Justin do Eminem image",
        "orientation": "landscape",
        "emphasized": false,
        "isGif": false,
        "bitStacked": "http://path.image.com/app2/img/144x81xS/scet/episode/6/9/3/6/9/rok_504_sm.jpg",
        "androidLdpi": "http://path.image.com/image2.png",
        "androidMdpi": "http://path.image.com/image2.png",
        "androidHdpi": "http://path.image.com/image2.png",
        "androidXhdpi": "http://path.image.com/image2.png",
        "androidXxhdpi": "http://path.image.com/image2.png",
        "iphone": "http://path.image.com/image2.png",
        "iphoneRetina": "http://path.image.com/image2.png",
        "ipad": "http://path.image.com/image2.png",
        "ipadRetina": "http://path.image.com/image2.png"

We'd get something back like this.

Notice how there is a lot of consistency to the internal elements of the resources

This consistency was key to keeping platform teams asynchronous and unblocked.

Drupal as content provider - challenges

It's not a site - so you lose things you get for free like unpublished previewing and routing

CDN becomes interesting - all performance elements become interesting

Can be difficult for editorial production teams to see the connections initially

Authoring is abstracted - wysiwyg work and media integration especially.

Drupal as content provider - challenges

Known unknowns - understand where you are drawing your boundaries

Specialized resource delivery needs

Be prepared for questions and training

The more you know...

Don't forget the site preview experience

Eschew soup-to-nuts solutions - you don't need the complexity

Even less concessions for display

The Finale

On the next episode of nova... (twinkletwinklehollystarr)

The timeline, the approach hid something surprising, something unusual...

Approach =>

Decoupled

Synergy:

Strong Asynchronous Workflow

<= Deadline

Fast and Looming

That synergy came in two stripes

The deadline pushed us to decoupling, decoupling gave us a strongly asynchronous workflow, the asynchronous workflow let us complete the site more quickly.

A decoupled approach allows a deeply-semantic content model which happens to pair well with REST and non-blocking workflows.

Consider the system as an architect

If designed consistently and well it is the most available member of your team

Decoupling

Building a decoupled stack has been a hot topic in the industry for several years.

But, it took either extraordinary content requirements or multiple channels to build.

We thought decoupled solutions were a solution for content longevity.

Decoupled architectures are  better way to work.

Constraints Inspire Innovation

We actually underestimated our ability to get work done in parallel. Now, I look at projects as "why not decoupled" instead of "why".

Not only did we decouple our technology and our teams, but we also decoupled project stress.

Some of our backend team members didn't even realize the site had launched to the public; our times of stress were spread out much more evenly throughout the whole project.

Evaluate this Session

Please, and thank-you! We'd love to hear what you think.

austin2014.drupal.org/schedule

Questions?

We're done! Questions?

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NumberValuesUtils (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jasperreports.data.cache

Class NumberValuesUtils

java.lang.Object

net.sf.jasperreports.data.cache.NumberValuesUtils

public class NumberValuesUtils
extends java.lang.Object

Version:

$Id: NumberValuesUtils.java 5878 2013-01-07 20:23:13Z teodord $

Author:

Lucian Chirita (lucianc@users.sourceforge.net)

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
NumberValuesUtils()

Method Summary

Methods

Modifier and Type
Method and Description

static NumberValuesUtils
instance()

protected ColumnValues
toByteValues(int count,
            long[] values,
            long linearFactor,
            long linearOffset)

protected ColumnValues
toIntValues(int count,
           long[] values,
           long linearFactor,
           long linearOffset)

protected ColumnValues
toLongValues(int count,
            long[] values,
            long linearFactor,
            long linearOffset)

protected ColumnValues
toShortValues(int count,
             long[] values,
             long linearFactor,
             long linearOffset)

ColumnValues
toValues(int count,
        long[] values,
        ValueLength valueLength,
        long linearFactor,
        long linearOffset)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NumberValuesUtils

protected NumberValuesUtils()

Method Detail

instance

public static NumberValuesUtils instance()

toValues

public ColumnValues toValues(int count,
                    long[] values,
                    ValueLength valueLength,
                    long linearFactor,
                    long linearOffset)

toByteValues

protected ColumnValues toByteValues(int count,
                        long[] values,
                        long linearFactor,
                        long linearOffset)

toShortValues

protected ColumnValues toShortValues(int count,
                         long[] values,
                         long linearFactor,
                         long linearOffset)

toIntValues

protected ColumnValues toIntValues(int count,
                       long[] values,
                       long linearFactor,
                       long linearOffset)

toLongValues

protected ColumnValues toLongValues(int count,
                        long[] values,
                        long linearFactor,
                        long linearOffset)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
layout: main
---

{{ page.title }}

  {% if page.subtitle %}

{{ page.subtitle }}

  {% endif %}

  {% if page.image %}

    {% if page.caption %}

{{ page.caption | markdownify }}

    {% endif %}

  {% endif %}

  {{ content }}


text:
BOOL	RegKey::Create( HKEY hParentKey, LPCTSTR lpszSubKey ) {
	assert( hParentKey != NULL && lpszSubKey != NULL );
	Close();

	DWORD	dwDisposition;
	if ( ::RegCreateKeyEx(
			hParentKey, lpszSubKey,
			0, REG_NONE,
			REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
			NULL, &m_hKey, &dwDisposition ) !=  ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::Open( HKEY hParentKey, LPCTSTR lpszSubKey ) {
	assert( hParentKey != NULL && lpszSubKey != NULL );
	Close();

	if ( ::RegOpenKeyEx(
			hParentKey, lpszSubKey,
			0, KEY_ALL_ACCESS, &m_hKey ) !=  ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::DeleteSubKey( LPCTSTR lpszSubKey ) {
	assert( lpszSubKey != NULL );
	assert( isOpened() );

	if ( ::RegDeleteKey( m_hKey, lpszSubKey ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

void	RegKey::Close() {
	if ( isOpened() ) {
		::RegCloseKey( m_hKey );
		m_hKey = NULL;
	}
}

void	RegKey::Flush() {
	if ( isOpened() ) {
		::RegFlushKey( m_hKey );
	}
}

BOOL	RegKey::SetValue( LPCTSTR lpValueName, DWORD dwValue ) {
	assert( lpValueName != NULL );
	if ( ::RegSetValueEx( m_hKey, lpValueName, 0,
		REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD) ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::SetValue( LPCTSTR lpValueName, LPCTSTR lpValue ) {
	assert( lpValueName != NULL && lpValue != NULL );
	if ( ::RegSetValueEx( m_hKey, lpValueName, 0,
		REG_SZ, (LPBYTE)lpValue, ::lstrlen(lpValue)+1 ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::SetValue( LPCTSTR lpValueName, LPCVOID lpBuffer, DWORD dwSize ) {
	assert( lpValueName != NULL && lpBuffer != NULL && dwSize > 0 );
	if ( ::RegSetValueEx( m_hKey, lpValueName, 0,
		REG_BINARY, (LPBYTE)lpBuffer, dwSize ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::GetValue( LPCTSTR lpValueName, LPDWORD pdwBuffer ) {
	assert( lpValueName != NULL && pdwBuffer != NULL );
	DWORD	dwSize = sizeof(DWORD);
	if ( ::RegQueryValueEx( m_hKey, lpValueName, 0,
		NULL, (LPBYTE)pdwBuffer, &dwSize ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::GetValue( LPCTSTR lpValueName, LPTSTR lpBuffer, DWORD dwBufSize ) {
	assert( lpValueName != NULL && lpBuffer != NULL );
	if ( ::RegQueryValueEx( m_hKey, lpValueName, 0,
		NULL, (LPBYTE)lpBuffer, &dwBufSize ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::GetValueSize( LPCTSTR lpValueName, LPDWORD pdwSize ) {
	assert( lpValueName != NULL && pdwSize != NULL );

	if ( ::RegQueryValueEx( m_hKey, lpValueName,
			NULL, NULL, NULL, pdwSize ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

BOOL	RegKey::GetValue( LPCTSTR lpValueName, LPVOID lpBuffer, DWORD dwSize ) {
	assert( lpValueName != NULL && lpBuffer != NULL );

	if ( ::RegQueryValueEx( m_hKey, lpValueName, NULL, NULL,
			(LPBYTE)lpBuffer, &dwSize ) != ERROR_SUCCESS )
		return	FALSE;
	return	TRUE;
}

template<class T>
BOOL	RegKey::SetValueT( LPCTSTR iName, const T* iT ) {
	assert(iName != NULL);
	assert(iT != NULL);
	return SetValue(iName, iT, sizeof(T) );
}

template<class T>
BOOL	RegKey::GetValueT( LPCTSTR iName, T* oT ) {
	assert(iName != NULL);
	assert(oT != NULL);
	return GetValue(iName, oT, sizeof(T) );
}

BOOL	RegKey::DeleteValue( LPCTSTR lpValueName ) {
	assert( lpValueName != NULL );
	return	( ::RegDeleteValue( m_hKey, lpValueName ) == ERROR_SUCCESS );
}


text:
package org.apache.ignite.internal.processors.query.h2;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.processors.cache.mvcc.MvccQueryTracker;

/**
 * Special field set iterator based on database result set.
 */
public class H2FieldsIterator extends H2ResultSetIterator<List<?>> {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    private transient MvccQueryTracker mvccTracker;

    /**
     * @param data Data.
     * @param mvccTracker Mvcc tracker.
     * @param forUpdate {@code SELECT FOR UPDATE} flag.
     * @throws IgniteCheckedException If failed.
     */
    public H2FieldsIterator(ResultSet data, MvccQueryTracker mvccTracker, boolean forUpdate)
        throws IgniteCheckedException {
        super(data, forUpdate);

        this.mvccTracker = mvccTracker;
    }

    /** {@inheritDoc} */
    @Override protected List<?> createRow() {
        List<Object> res = new ArrayList<>(row.length);

        Collections.addAll(res, row);

        return res;
    }

    /** {@inheritDoc} */
    @Override public void onClose() throws IgniteCheckedException {
        try {
            super.onClose();
        }
        finally {
            if (mvccTracker != null)
                mvccTracker.onDone();
        }
    }
}


text:
class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.string :name, null: false

      t.timestamps null: false
    end
  end
end


text:
namespace Capl.Services.Configuration
{
    using System.Configuration;

    public abstract class ExtensionContainerElement<TExtension> : ConfigurationElement
    {
        public abstract TExtension GetExtension();
    }
}


text:
<?php
/**
 * @license MIT
 * Full license text in LICENSE file
 */

namespace Welgam\Core\Usecase\Racer\Edit;

interface Repository
{
    /**
     * @return bool
     */
    public function does_racer_exist($racer_id, $racer_password);

    /**
     * @return void
     */
    public function update_racer($racer_id, $racer_email, $racer_goal_weight);
}


text:
package com.mvidalgarcia.pinmap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.ByteArrayOutputStream;

@SuppressLint("NewApi")
public class PhotoActivity extends Activity {
	ProgressDialog prgDialog;
	String encodedString;
	RequestParams params = new RequestParams();
	String imgPath, fileName;
	Bitmap bitmap;
	private static int RESULT_LOAD_IMG = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		prgDialog = new ProgressDialog(this);
		// Set Cancelable as False
		prgDialog.setCancelable(false);
        Intent intent = getIntent();
        fileName = intent.getStringExtra(PinFormFragment.EPOCH);
	}

	public void loadImagefromGallery(View view) {
		// Create intent to Open Image applications like Gallery, Google Photos
		Intent galleryIntent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		// Start the Intent
		startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
	}

	// When Image is selected from Gallery
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			// When an Image is picked
			if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
					&& null != data) {
				// Get the Image from data

				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				// Get the cursor
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				// Move to first row
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				imgPath = cursor.getString(columnIndex);
				cursor.close();
				ImageView imgView = (ImageView) findViewById(R.id.imgView);
				// Set the Image in ImageView
				imgView.setImageBitmap(BitmapFactory
						.decodeFile(imgPath));
				// Add image extension
				fileName += ".jpg";
				// Put file name in Async Http Post Param which will used in Php web app
				params.put("filename", fileName);

			} else {
				Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
					.show();
		}

	}

	// When Upload button is clicked
	public void uploadImage(View v) {
		// When Image is selected from Gallery
		if (imgPath != null && !imgPath.isEmpty()) {
			prgDialog.setMessage("Converting Image to Binary Data");
			prgDialog.show();
			// Convert image to String using Base64
			encodeImagetoString();
		// When Image is not selected from Gallery
		} else {
			Toast.makeText(
                    getApplicationContext(),
                    "You must select image from gallery before you try to upload",
                    Toast.LENGTH_LONG).show();
		}
	}

	// AsyncTask - To convert Image to String
	public void encodeImagetoString() {
		new AsyncTask<Void, Void, String>() {

			protected void onPreExecute() {

			};

			@Override
			protected String doInBackground(Void... params) {
				BitmapFactory.Options options = null;
				options = new BitmapFactory.Options();
				options.inSampleSize = 3;
				bitmap = BitmapFactory.decodeFile(imgPath,
                        options);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				// Must compress the Image to reduce image size to make upload easy
				bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
				byte[] byte_arr = stream.toByteArray();
				// Encode Image to String
				encodedString = Base64.encodeToString(byte_arr, 0);
				return "";
			}

			@Override
			protected void onPostExecute(String msg) {
				prgDialog.setMessage("Uploading...");
				// Put converted Image string into Async Http Post param
				params.put("image", encodedString);
				// Trigger Image upload
				triggerImageUpload();
			}
		}.execute(null, null, null);
	}

	public void triggerImageUpload() {
		makeHTTPCall();
	}

	// Make Http call to upload Image to Php server
	public void makeHTTPCall() {
		prgDialog.setMessage("Uploading photo...");
		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://156.35.95.75:9090/upload_image.php",
				params, new AsyncHttpResponseHandler() {
					// When the response returned by REST has Http
					// response code '200'
					@Override
					public void onSuccess(String response) {
						// Hide Progress Dialog
						prgDialog.hide();
						Toast.makeText(getApplicationContext(), response,
                                Toast.LENGTH_LONG).show();
                        finish();
					}

					// When the response returned by REST has Http
					// response code other than '200' such as '404',
					// '500' or '403' etc
					@Override
					public void onFailure(int statusCode, Throwable error,
							String content) {
						// Hide Progress Dialog
						prgDialog.hide();
						// When Http response code is '404'
						if (statusCode == 404) {
							Toast.makeText(getApplicationContext(),
                                    "Requested resource not found",
                                    Toast.LENGTH_LONG).show();
						}
						// When Http response code is '500'
						else if (statusCode == 500) {
							Toast.makeText(getApplicationContext(),
                                    "Something went wrong at server end",
                                    Toast.LENGTH_LONG).show();
						}
						// When Http response code other than 404, 500
						else {
							Toast.makeText(
                                    getApplicationContext(),
                                    "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                            + statusCode, Toast.LENGTH_LONG)
									.show();
						}
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Dismiss the progress bar when application is closed
		if (prgDialog != null) {
			prgDialog.dismiss();
		}
	}
}


text:
package com.defano.wyldcard.awt.keyboard;

import com.defano.jmonet.canvas.JMonetCanvas;
import com.defano.wyldcard.WyldCard;
import com.defano.wyldcard.part.stack.StackModel;
import com.defano.wyldcard.runtime.ExecutionContext;
import com.google.inject.Singleton;

import javax.swing.FocusManager;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.Set;

/**
 * Provides an AWT-level view of keyboard events; see {@link WyldCardRoboticTypist} for a utility to produce keystroke events
 * from a String.
 */
@Singleton
public class WyldCardKeyboardManager implements KeyboardManager {

    private final Set<KeyListener> observers = new HashSet<>();

    private boolean isShiftDown;
    private boolean isAltOptionDown;          // Either 'alt' or 'option' (Mac)
    private boolean isCtrlCommandDown;        // Either 'ctrl' or 'command' (Mac)
    private Long breakTime;

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(e -> {

            isShiftDown = e.isShiftDown();
            isAltOptionDown = e.isAltDown();
            isCtrlCommandDown = e.isMetaDown() || e.isControlDown();

            if (e.getKeyCode() == KeyEvent.VK_PERIOD && isCtrlCommandDown) {
                breakTime = System.currentTimeMillis();
            }

            fireGlobalKeyListeners(e);

            // When no UI element has keyboard focus, send key press events to the displayed card
            if (FocusManager.getCurrentManager().getFocusOwner() == null || FocusManager.getCurrentManager().getFocusOwner() instanceof JMonetCanvas) {
                delegateKeyEventToFocusedCard(e);
            }

            return false;
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addGlobalKeyListener(KeyListener observer) {
        observers.add(observer);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean removeGlobalKeyListener(KeyListener observer) {
        return observers.remove(observer);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Long getBreakTime() {
        return breakTime;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isShiftDown() {
        return isShiftDown;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAltOptionDown() {
        return isAltOptionDown;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isCtrlCommandDown() {
        return isCtrlCommandDown;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isPeeking(ExecutionContext context) {
        return isAltOptionDown() && isCtrlCommandDown() &&
                !WyldCard.getInstance().getStackManager().getFocusedStack()
                        .getStackModel()
                        .get(context, StackModel.PROP_CANTPEEK)
                        .booleanValue();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void resetKeyStates() {
        isShiftDown = false;
        isAltOptionDown = false;
        isCtrlCommandDown = false;
    }

    private void fireGlobalKeyListeners(KeyEvent e) {
        Set<KeyListener> listeners = new HashSet<>(observers);

        for (KeyListener thisListener : listeners) {
            switch (e.getID()) {
                case KeyEvent.KEY_PRESSED:
                    thisListener.keyPressed(e);
                    break;
                case KeyEvent.KEY_RELEASED:
                    thisListener.keyReleased(e);
                    break;
                case KeyEvent.KEY_TYPED:
                    thisListener.keyTyped(e);
                    break;
            }
        }
    }

    private void delegateKeyEventToFocusedCard(KeyEvent e) {
        switch (e.getID()) {
            case KeyEvent.KEY_PRESSED:
                WyldCard.getInstance().getStackManager().getFocusedStack().getDisplayedCard().keyPressed(e);
                break;

            case KeyEvent.KEY_TYPED:
                WyldCard.getInstance().getStackManager().getFocusedStack().getDisplayedCard().keyTyped(e);
                break;

            case KeyEvent.KEY_RELEASED:
                WyldCard.getInstance().getStackManager().getFocusedStack().getDisplayedCard().keyReleased(e);
                break;
        }
    }

}


text:
'use strict';

var INSTANTIATING = {};
var PROVIDER_SUFFIX = 'Provider';

/**
 * Return array of named arguments to a function
 * @param func
 * @returns {Array}
 */
var annotate = function(func){
  var result = [];
  var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  var FN_ARG_SPLIT = /,/;
  var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

  // validate argument
  if (typeof func !== 'function') {
    throw new Error('Argument must be a function');
  }

  // if has $inject property, just return that
  if (func.hasOwnProperty('$inject') && Array.isArray(func['$inject'])) {
    result = func['$inject'];
  }
  else {
    // extract the arguments section of the function with regex
    var fnText = func.toString().replace(STRIP_COMMENTS, '');
    var argDecl = fnText.match(FN_ARGS);

    // push each argument name into result array
    argDecl[1].split(FN_ARG_SPLIT).forEach(function(arg){
      arg.replace(FN_ARG, function(all, underscore, name) {
        result.push(name);
      });
    });

    func['$inject'] = result;
  }

  return result;
};

/**
 * Invoke a function with injected dependencies
 * @param fn - function
 * @param self - object on which to invoke function
 * @param factory - function that takes named dependency and returns instance
 * @returns {*} result from invoking the function
 */
var invoke = function(fn, self, factory){
  var args = [];

  // get list of argument names
  var $inject = annotate(fn);

  // loop through named arguments and get an appropriate instance
  for (var i = 0; i < $inject.length; i++) {
    // get an instance of this name from our factory
    var argInst = factory($inject[i]);

    // push to args list
    args.push(argInst);
  }

  return fn.apply(self, args);
};

/**
 * Instantiate a new object given a function (ctor) with injected dependencies
 * @param fn
 * @param factory
 * @returns {*}
 */
var instantiate = function(fn, factory) {
  var DefaultConstructor = function(){};
  var inst = new DefaultConstructor();

  var result = invoke(fn, inst, factory);

  return (typeof result !== 'undefined' && result !== null) ? result : inst;
};

/**
 * Injector/Container for Providers
 */
var $providerInjector = function(){

  var self = this;

  /**
   * Map of providers and instances
   * @type {Object}
   *
   * Associative arary of provider entries by name.
   */
  var container = {};

  /**
   * factory function to instantiate a dependency of this provider
   * @param dependency
   * @returns {*}
   */
  var loadProviderDependency = function(dependency){
    var dependencyInst = self.get(dependency);

    // if this provider does not allow injection, throw an error as if it's not a real provider
    if (dependencyInst.hasOwnProperty('$injectable') && dependencyInst['$injectable'] === false) {
      throw new Error('Not allowed to inject provider \'' + dependency + '\'');
    }

    return dependencyInst;
  };

  /**
   * Create an instance of the specified provider (entry)
   * @param providerEntry
   */
  var instantiateProvider = function(providerEntry){
    // if the provider definition is a function
    if (typeof providerEntry.provider === 'function') {

      // mark this provider as being instantiated
      providerEntry.inst = INSTANTIATING;

      // invoke the provider function with dependency injection
      var newInst = instantiate(providerEntry.provider, loadProviderDependency);

      // validate returned provider instance
      if (newInst === null || newInst === undefined) {
        throw new Error('Invalid provider instance specified for ' + name);
      }

      // save this instance
      providerEntry.inst = newInst;
    }
    else {
      throw new Error('Unable to instantiate provider of type ' + (typeof providerEntry.provider));
    }
  };

  /**
   * Invoke a function with dependency injection
   * @param fn
   * @param self_
   * @returns {*}
   */
  this.invoke = function(fn, self_) {
    return invoke(fn, self_, loadProviderDependency);
  };

  /**
   * Register a provider with the container
   * @param name
   * @param provider - provider definition. This argument may be
   * an object or a function. If it is an object, it must have a $get
   * function. If it is a function, it is treated as a CTOR which much
   * itself return an object that has a $get function.
   * @param asInstance  - treat the provider argument as a raw instance value.
   * This is used for value providers and 3rd-party modules which may actually
   * be functions.
   */
  this.register = function(name, provider, asInstance){
    // validate arguments
    if (typeof name !== 'string') {
      throw new Error('Provider name must be a string');
    }

    if (provider === null) {
      throw new Error('Invalid provider: ' + provider);
    }

    // create map entry
    var newEntry = {
      provider: provider,
      inst: null
    };

    // if the provider definition is a object or constant value, then just instantiate it now.
    if (typeof provider !== 'function' || asInstance === true) {
      newEntry.inst = provider;
    }

    // create / replace provider definition
    container[name] = newEntry;

  };

  /**
   * Check if a provider has been successfully instantiated
   * @param name - provider name
   * @returns {boolean}
   */
  this.has = function(name){
    var entry = container[name];
    var result = false;

    if (container.hasOwnProperty(name) && entry !== null) {
      result = entry.inst !== null && entry.inst !== INSTANTIATING;
    }

    return result;
  };

  /**
   * Return an instance of a provider
   * @param name - name of provider
   * @returns {*}
   */
  this.get = function(name){
    var entry = container[name];

    // if no definition found
    if (!container.hasOwnProperty(name) || entry === null) {
      throw new Error('Unknown provider: \'' + name + '\'');
    }

    // if there is a circular dependency
    if (entry.inst === INSTANTIATING) {
      throw new Error('Circular dependency in provider: \'' + name + '\'');
    }
    // or if we havent created an instance yet
    else if (entry.inst === null) {
      instantiateProvider(entry);
    }

    return entry.inst;
  };

  /**
   * Instantiate all providers
   */
  this.instantiateAll = function(){

    // iterate all registered providers
    for (var name in container) {
      if (container.hasOwnProperty(name)) {
        // if this provider is not already instantiated
        var entry = container[name];

        // if failed a provider somewhere
        if (entry.inst === INSTANTIATING) {
          throw new Error('Error instantiating providers');
        }
        // try to create this one
        else if (entry.inst === null) {
          instantiateProvider(entry);
        }
      }
    }//endfor
  };
};

/**
 * Injector/Container for service instances
 */
var $injector = function(providerInjector){

  var self = this;

  /**
   * Associative array of service names to instances
   * @type {Object}
   */
  var container = {
    '$injector' : self // this is a hard-coded service that is always available.
  };

  /**
   * Return an instance of a service
   * @param name
   * @returns {*}
   */
  this.get = function(name){
    var inst = container[name];
    var providerInst = null;

    // if we already have an entry
    if (container.hasOwnProperty(name) && inst !== null) {
      // if this service is already being instantiated
      if (inst === INSTANTIATING) {
        throw new Error('Circular dependency in service \'' + name + '\'');
      }
    }
    // else we need to load the service
    else {

      // look for a suitable provider instance. First try with the provider suffix.
      if (providerInjector.has(name + PROVIDER_SUFFIX)) {
        providerInst = providerInjector.get(name + PROVIDER_SUFFIX);
      }
      // then try without (for things like plain values)
      else if (providerInjector.has(name)) {
        providerInst = providerInjector.get(name);

        // if trying to get a non-constant provider, don't allow
        if (providerInst.hasOwnProperty('$injectable') && providerInst['$injectable'] === false) {
          // just mask it out. pretend the hidden providers aren't there.
          providerInst = null;
        }
      }

      // if no provider instance
      if (providerInst === null) {
        throw new Error('No suitable provider for \'' + name + '\'');
      }

      // if the provider instance DOES NOT have a $get property
      if (typeof providerInst !== 'object' || !providerInst.hasOwnProperty('$get')) {
        // then just use that as the service instance, too.
        // this is useful for constant values
        inst = providerInst;
      }
      // otherwise the provider instance is an object with a $get property
      else {
        // if the provider's $get property is NOT a function, straight return that
        if (typeof providerInst['$get'] !== 'function') {
          inst = providerInst['$get'];
        }
        // else if $get is a CTOR function
        else {
          // mark this service as being instantiated
          container[name] = INSTANTIATING;

          // invoke the ctor with dependency injection
          inst = invoke(providerInst['$get'], providerInst, function loadDependency(dependency){
            return self.get(dependency);
          });
        }

        // if inst is invalid
        if (inst === null) {
          throw new Error('Service instance resolved to null: \'' + name + '\'');
        }
      }

      container[name] = inst;
    }

    // return our loaded instance
    return inst;
  };

  /**
   * Invoke a function with dependency injection
   * @param fn
   * @param self_
   * @returns {*}
   */
  this.invoke = function(fn, self_) {
    return invoke(fn, self_, function loadDependency(dependency){
      return self.get(dependency);
    });
  };

  /**
   * Instantiate an object from constructor with dependency injection
   * @param fn
   * @returns {*}
   */
  this.instantiate = function(fn) {
    return instantiate(fn, function loadDependency(dependency){
      return self.get(dependency);
    });
  }

};

exports.providerInjector = new $providerInjector();
exports.instanceInjector = new $injector(exports.providerInjector);
exports.annotate = annotate;
exports.PROVIDER_SUFFIX = PROVIDER_SUFFIX;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rep. Tottori Mycol. Inst. 10: 177 (1973)

#### Original name
Puccinia viatica J.F. Hennen & Cummins

### Remarks
null


text:
package com.tgx.zq.z.rook.sdk.client.aio.db.bean;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.je.DatabaseEntry;
import com.tgx.zq.z.queen.base.inf.IDisposable;
import com.tgx.zq.z.queen.db.bdb.inf.IDbStorageProtocol;

/**
 * @author William.d.zk
 */
public class DeviceMessageEntry
        implements
        IDisposable,
        IDbStorageProtocol
{
    @Override
    public int dataLength() {
        return 0;
    }

    @Override
    public long getPrimaryKey() {
        return 0;
    }

    public final static class DeviceMessageEntryBinding
            implements
            EntryBinding<DeviceMessageEntry>
    {
        @Override
        public DeviceMessageEntry entryToObject(DatabaseEntry entry) {
            DeviceMessageEntry dme = new DeviceMessageEntry();
            dme.decode(entry.getData());
            return dme;
        }

        @Override
        public void objectToEntry(DeviceMessageEntry object, DatabaseEntry entry) {
            byte[] data = object.encode();
            object.dispose();
            entry.setData(data);
        }
    }
}


text:
import LocalStorageEvent = require('../event/LocalStorageEvent');
import EventDispatcher = require('../event/EventDispatcher');
import BaseModel = require('../model/BaseModel');

/**
 * The LocalStorageController...
 *
 * @class LocalStorageController
 * @extends EventDispatcher
 * @module StructureJS
 * @submodule controller
 * @requires Extend
 * @requires EventDispatcher
 * @requires LocalStorageEvent
 * @requires BaseModel
 * @constructor
 * @author Robert S. (www.codeBelt.com)
 */
class LocalStorageController extends EventDispatcher
{
    /**
     * Current user namespace. The namespace is optional.
     *
     * @property _namespace
     * @type {string}
     * @default defaultNamespace
     * @optional
     * @protected
     */
    protected _namespace:string = 'defaultNamespace';

    /**
     * A reference to window.localStorage for faster access.
     *
     * @property _localStorage
     * @type {Storage}
     * @protected
     */
    protected _localStorage:Storage = null;

    constructor()
    {
        super();

        this._localStorage = window.localStorage;

        window.addEventListener('storage', this.onLocalStorageEvent.bind(this));
    }

    /**
     * Set storage namespace
     *
     * @method setNamespace
     * @param namespace
     * @returns {string}
     */
    public setNamespace(namespace:string):void
    {
        this._namespace = namespace;
    }

    /**
     * Get storage namespace
     *
     * @method getNamespace
     * @returns {string}
     */
    public getNamespace():string
    {
        return this._namespace;
    }

    /**
     * Add a key/value pair to localStorage.
     *
     * @method addItem
     * @param key {string}
     * @param data {Object}
     * @param useNamespace {boolean}
     * @return {boolean}
     */
    public addItem(key:string, data:any, useNamespace:boolean = false):boolean
    {
        if (useNamespace)
        {
            key = this.getNamespace() + key;
        }

        if (data instanceof BaseModel)
        {
            data = <BaseModel>data.toJSON();
        }

        data = JSON.stringify(data);

        try
        {
            this._localStorage.setItem(key, data);
            return true;
        }
        catch (error)
        {
            return false;
        }
    }

    /**
     * Retrieves the current value associated with the Local Storage key.
     *
     * @method getItem
     * @param key {string}
     * @param [useNamespace=false] {string}
     * @returns {any}
     */
    public getItem(key:string, useNamespace:boolean = false):any
    {
        if (useNamespace)
        {
            key = this.getNamespace() + key;
        }

        var value = this._localStorage.getItem(key);
        if (value)
        {
            try
            {
                value = JSON.parse(value);
            }
            catch (error)
            {
                // We are assuming the error is because value being parsed is a plain string with spaces.
                value = value;
            }
        }

        return value;
    }

    /**
     * Returns all items in local storage as an Object with key and value properties that has a certain namespace.
     *
     * @method getItemsWithNamespace
     * @param namespace {string} The namespace that is used to items. If a namespace is not passed in then the current set namespace will be used.
     * @return {Array}
     */
    public getItemsWithNamespace(namespace:string = this._namespace):Array<any>
    {
        var list:Array<any> = [];
        var length:number = this.getLength();
        for (var i:number = 0; i < length; i++)
        {
            var key:string = this._localStorage.key(i);
            if (key.indexOf(namespace) > -1)
            {
                var value:any = this.getItem(key);
                var obj:any = {
                    key: key,
                    value: value
                }

                list.push(obj);
            }
        }
        return list;
    }

    /**
     * Returns all items in local storage as an Object with key and value properties.
     *
     * @method getAllItems
     * @return {Array}
     */
    public getAllItems():Array<any>
    {
        var list:Array<any> = [];
        var length:number = this.getLength();
        for (var i:number = 0; i < length; i++)
        {
            var key:string = this._localStorage.key(i);
            var value:any = this.getItem(key);
            var obj:any = {
                key: key,
                value: value
            };

            list.push(obj);
        }
        return list;
    }

    /**
     * Deletes a key/value pair from the Local Storage collection.
     *
     * @method removeItem
     * @param key {string}
     * @param [useNamespace=false] {string}
     * @return {boolean}
     */
    public removeItem(key:string, useNamespace:boolean = false):boolean
    {
        if (useNamespace)
        {
            key = this.getNamespace() + key;
        }

        try
        {
            this._localStorage.removeItem(key);
            return true;
        }
        catch (error)
        {
            return false;
        }
    }

    /**
     * Returns the number of items storage in local storage.
     *
     * @method getLength
     * @returns {number}
     */
    public getLength():number
    {
        return this._localStorage.length;
    }

    /**
     * Returns the size of the Local Storage.
     *
     * @method getSize
     * @returns {number}
     */
    public getSize():number
    {
        return encodeURIComponent(JSON.stringify(this._localStorage)).length;
    }

    /**
     * Removes all key/value pairs from the Local Storage area.
     *
     * @method clear
     */
    public clear():void
    {
        this._localStorage.clear();
    }

    /**
     * @overridden EventDispatcher.destroy
     */
    public destroy():void
    {
        super.destroy();
    }

    /**
     *
     *
     * @method onLocalStorageEvent
     * @param event {StorageEvent} The native browser event for Web Storage.
     * @protected
     */
    protected onLocalStorageEvent(event:StorageEvent)
    {
        this.dispatchEvent(new LocalStorageEvent(LocalStorageEvent.STORAGE, false, false, event));
    }
}

export = LocalStorageController;


text:
var Geometry = require('../c2d/Geometry');

/**
 * Mutable storage for sets of 3d points
 *
 * Can be used for calculation of bounds
 * Doesn't have anything related to particular DisplayObject
 * Renderers can use it to upload data to vertex buffer or to copy data to other buffers
 *
 * @class
 * @extends PIXI.Geometry
 * @memberof PIXI
 */
function Geometry3d() {
    Geometry.call(this);
    this.stride = 3;
    this.is3d = true;
}

Geometry3d.prototype = Object.create(Geometry.prototype);
Geometry3d.prototype.constructor = Geometry3d;
module.exports = Geometry3d;

Geometry3d.fromBuffers = function (vertices, indices) {
    var geometry = new Geometry3d();
    geometry.vertices = vertices || null;
    geometry.indices = indices || null;
    return geometry;
};


text:
set -o errexit
set -o nounset
set -o pipefail

# sync_repo() cherry picks the latest changes in k8s.io/kubernetes/${filter} to the
# local copy of the repository to be published.
#
# prerequisites
# 1. we are in the root of the repository to be published
# 2. we are on the branch to be published (let's call it "target-branch")
# overall flow
# 1. fetch the current level of k8s.io/kubernetes
# 2. check out the $src_branch of k8s.io/kubernetes as branch kube-sync
# 3. rewrite the history of branch kube-sync to *only* include code in $subdirectory
# 4. locate all commits between the last time we sync'ed and now
# 5. switch back to the "target-branch"
# 6. for each commit, cherry-pick it (which will keep authorship) into "target-branch"
# 7. update metadata files indicating which commits we've sync'ed to
sync_repo() {
    # subdirectory in k8s.io/kubernetes, e.g., staging/src/k8s.io/apimachinery
    local subdirectory="${1}"
    local src_branch="${2}"
    local kubernetes_remote="${3:-https://github.com/kubernetes/kubernetes.git}"
    readonly filter src_branch

    local currBranch=$(git rev-parse --abbrev-ref HEAD)
    local previousKubeSHA=$(cat kubernetes-sha)
    local new_repo="false"
    if [[ "${previousKubeSHA}" == "" ]]; then
        new_repo="true"
        echo "sync_repo() is processing a repo that doesn't have kubernetes-sha, treat it as a new repo"
    fi

    git remote add upstream-kube "${kubernetes_remote}" || true
    git fetch upstream-kube
    git branch -D kube-sync || true
    git checkout upstream-kube/"${src_branch}" -b kube-sync
    git reset --hard upstream-kube/"${src_branch}"

    # this command rewrites git history to *only* include $subdirectory
    git filter-branch -f --msg-filter 'awk 1 && echo && echo "Kubernetes-commit: ${GIT_COMMIT}"' \
        --subdirectory-filter "${subdirectory}" HEAD

    local newKubeSHA=$(git log kube-sync -1 | tail -n 1 | sed "s/Kubernetes-commit: //g")

    local previousBranchSHA=$(git log --grep "Kubernetes-commit: ${previousKubeSHA}" --format='%H')
    local commits=$(git log --no-merges --format='%H' --reverse ${previousBranchSHA}..HEAD)
    if [ "${new_repo}" = "true" ]; then
        commits=$(git log --no-merges --format='%H' --reverse HEAD)
    fi

    # check if any commit of commits change Godeps/Godeps.json
    local commits_change_godeps=$(git log --format='%H' --follow Godeps/Godeps.json)
    local cherrypicks_change_godeps="false"
    while read commit; do
        if [[ -z "${commit}" ]]; then
            continue
        fi
        if echo ${commits_change_godeps} | grep -q ${commit} > /dev/null; then
            echo "branch commit ${commit} changes Godeps.json"
            cherrypicks_change_godeps="true"
            break
        fi
    done <<< "${commits}"

    git checkout ${currBranch}

    # we must reset Godeps.json to what it looked like in the kube-sync branch
    # before the first commit that's to be cherry-picked so that any new
    # Godep.json changes from k8s.io/kubernetes will apply cleanly. Note that
    # entries for k8s.io/* will be updated later in the process.
    if [ "${cherrypicks_change_godeps}" = "true" ] && [ "${new_repo}" = "false" ]; then
       local cleanGodepJsonCommit=${previousBranchSHA}
       git checkout ${cleanGodepJsonCommit} Godeps/Godeps.json
       if git diff --cached --exit-code &>/dev/null; then
           echo "no need to reset Godeps.json!"
       else
           git -c user.name="Kubernetes Publisher" -c user.email="k8s-publish-robot@users.noreply.github.com" commit -m "sync: reset Godeps.json" -- Godeps/Godeps.json
       fi
    fi

    echo "commits to be cherry-picked:"
    echo "${commits}"
    echo ""

    while read commitSHA; do
        if [[ -z "${commitSHA}" ]]; then
            continue
        fi
        echo "working ${commitSHA}"
        git -c user.name="Kubernetes Publisher" -c user.email="k8s-publish-robot@users.noreply.github.com" cherry-pick --keep-redundant-commits ${commitSHA}
    done <<< "${commits}"

    # track the k8s.io/kubernetes commit SHA so we can always determine which level of kube this repo matches
    # track the filtered branch commit SHA so that we can determine which commits need to be picked
    echo ${newKubeSHA} > kubernetes-sha
    if git diff --exit-code &>/dev/null; then
        echo "SHAs haven't changed!"
        return
    fi
    git -c user.name="Kubernetes Publisher" -c user.email="k8s-publish-robot@users.noreply.github.com" commit -m "sync(k8s.io/kubernetes) ${newKubeSHA}" -- kubernetes-sha
}

# This function updates the vendor/ folder, and removes k8s.io/* and glog from
# the vendor/ if the repo being published is a library. This is to avoid issues
# like https://github.com/kubernetes/client-go/issues/83 and
# https://github.com/kubernetes/client-go/issues/19.
#
# "deps" lists the dependent k8s.io/* repos and branches. For example, if the
# function is handling the release-1.6 branch of k8s.io/apiserver, deps is
# expected to be "apimachinery:release-1.6,client-go:release-3.0". Dependencies
# are expected to be separated by ",", and the name of the dependent repo and
# the branch name are expected to be separated by ":".
#
# "is_library" indicates if the repo being published is a library.
#
# This function should be run after the Godeps.json are updated with the latest
# revisions of k8s.io/* dependencies.
#
# To avoid repeated godep restore, repositories should share the GOPATH.
#
# This function assumes to be called at the root of the repository that's going to be published.
# This function assumes the branch that need update is checked out.
# This function assumes it's the last step in the publishing process that's going to generate commits.
restore_vendor() {
    local deps="${1:-""}"
    IFS=',' read -a deps <<< "${DEPS}"
    dep_count=${#deps[@]}
    # The Godeps.json of apiserver, kube-aggregator, sample-apiserver in staging
    # don't contain entries for k8s.io/* repos, so we need to explicitly check
    # out a revision of deps.
    for (( i=0; i<${dep_count}; i++ )); do
        pushd ../"${deps[i]%%:*}"
            git checkout "${deps[i]##*:}"
        popd
    done

    local is_library="${2}"
    # At this step, currently only client-go's Godeps.json contains entries for
    # k8s.io repos, with commit hash of the first commit in the master branch.
    godep restore
    # need to remove the Godeps folder, otherwise godep won't save source code to vendor/
    rm -rf ./Godeps
    # otherwise `godep save` might fail, see https://github.com/kubernetes/test-infra/issues/2684
    rm -rf ./vendor
    godep save ./...
    if [ "${is_library}" = "true" ]; then
        echo "remove k8s.io/*, gofuzz, and glog from vendor/"
        # glog uses global variables, it panics when multiple copies are compiled.
        rm -rf ./vendor/github.com/golang/glog
        # this ensures users who get the repository via `go get` won't end up with
        # multiple copies of k8s.io/ repos. The only copy will be the one in the
        # GOPATH.
        # Godeps.json has a complete, up-to-date list of dependencies, so
        # Godeps.json will be the ground truth for users using godep/glide/dep.
        rm -rf ./vendor/k8s.io
        # see https://github.com/kubernetes/kubernetes/issues/45693
        rm -rf ./vendor/github.com/google/gofuzz
    fi
    git add --all
    # check if there are new contents
    if git diff --cached --exit-code &>/dev/null; then
        echo "vendor hasn't changed!"
        return
    fi
    git -c user.name="Kubernetes Publisher" -c user.email="k8s-publish-robot@users.noreply.github.com" commit -m "sync: resync vendor folder"
}

# set up github token in ~/.netrc
set_github_token() {
    mv ~/.netrc ~/.netrc.bak || true
    echo "machine github.com login ${1}" > ~/.netrc
}

cleanup_github_token() {
    rm -rf ~/.netrc
    mv ~/.netrc.bak ~/.netrc || true
}

# Godeps.json copied from the staging area might contain invalid commit hashes
# in entries for k8s.io/*. This function updates entry for k8s.io/${1} to track
# the latest commit created by the publishing robot.
# Currently this function is only useful for client-go. Entries for k8s.io/* are
# removed from the Godeps.json in the staging area of other repos.
update_godeps_json() {
    local repo=${1%%:*}
    local branch=${1##*:}
    local godeps_json="./Godeps/Godeps.json"
    local old_revs=""
    # TODO: pass in the new_rev if we want to depend on a specific revision.
    local new_rev=$(cd ../${repo}; git rev-parse ${branch})

    # TODO: simplify the following lines
    while read path rev; do
        if [[ "${path}" == "k8s.io/${repo}"* ]]; then
            old_revs+="${rev}"$'\n'
        fi
    done < <(jq '.Deps|.[]|.ImportPath + " " + .Rev' -r < "${godeps_json}")
    old_revs=$(echo "${old_revs%%$'\n'}" | sort | uniq)
    while read old_rev; do
        if [[ -z "${old_rev}" ]]; then
            continue
        fi
        sed -i "s|${old_rev}|${new_rev}|g" "${godeps_json}"
    done <<< "${old_revs}"
}


text:
/**
 */
function Tool() {
}
Tool.prototype = {
	collapse : function(selector) {
		$(selector || ".editor:visible").hide();
	},
	expand : function(selector) {
		tool.collapse();
		$(selector).show();
	},
	changeTo : function(selector) {
		$("#editTopic").children(".check").attr("class", "uncheck");
		$(selector).attr("class", "check");
	},
	changeTo2 : function(selector) {
		$(".setContent4").children(".check").attr("class", "uncheck");
		$(selector).attr("class", "check");
	},
	changeTo3 : function(selector) {
		$(".setContent5").children(".check").attr("class", "uncheck");
		$(selector).attr("class", "check");
	},
	transfer : function(img, theme, callback) {
		var $img = $(img).clone();
		var pos = $(img).position();
		$img.css({
			position : 'absolute',
			opacity : "0.6"
		}).css(pos).appendTo(img.parentNode);
		var d = 40;
		$img.animate({
			left : pos.left - d / 2 - 2,
			top : pos.top - d / 2 - 2,
			width : img.offsetWidth + d,
			height : img.offsetHeight + d
		}, 300, function() {
			var pos2 = tool.useimg.position();
			$img.animate({
				left : pos2.left + 1,
				top : pos2.top + 1,
				width : img.offsetWidth,
				height : img.offsetHeight
			}, function() {
				tool.useimg.attr("src", $img.attr("src"));
				$img.remove();
				$.extend(pageTheme, theme);
				tool.clearStyle();
				onLoad.refresh();
				mytheme.style = {};
				$("#theme").attr(
						"href",
						function(i, v) {
							return v.replace(/theme\/.+\/theme/, "theme/"
									+ theme.folder + "/theme");
						});
				if (typeof callback == "function")
					callback();
			})
		})
	},
	setTheme : function() {
		var sheet, rules = {};
		(function() {
			$.each(arguments, function(i, id) {
				$("link,style").each(function(i) {
					if (this.id == id) {
						sheet = document.styleSheets[i];
						return false;
					}
				});
				$.each(sheet.rules || sheet.cssRules, function(i, rule) {
					if (rule.type && rule.type != 1)
						return;
					var r = rules[rule.selectorText]
							|| (rules[rule.selectorText] = {});
					for ( var key in rule.style) {
						var k = key.replace(/([A-Z])/g, "-$1").toLowerCase();
						if (rule.style[key])
							r[k] = rule.style[key]
					}
				});
			})
		})("baseTheme", "theme");
		tool.theme = rules;
	},
	setStyle : function(style) {
		if ($.browser.msie) {
			for ( var key in style)
				for ( var k in style[key])
					tool.style.addRule(key, k + ":" + style[key][k])
		} else {
			tool.style.html(this.toJSON(style));
		}
	},
	clearStyle : function() {
		if ($.browser.msie) {
			while (tool.style.rules.length)
				tool.style.removeRule();
		} else {
			tool.style.html("");
		}
		mytheme.style = {};
	},
	normalPic : function(param) {
		if (typeof param == "string")
			return param.replace(/\.min\.(gif|jpg)/gi, ".$1");
		if (typeof param == "object") {
			for ( var key in param)
				param[key] = param[key].replace(/\.min\.(gif|jpg)/gi, ".$1");
			return param;
		}
	},
	toJSON : function(style) {
		var array = [];
		for ( var key in style) {
			var arr = [];
			for ( var k in style[key]) {
				arr.push(k + ":" + style[key][k])
			}
			array.push(key + "{" + arr.join(";") + "}");
		}
		return array.join("");
	},
	flashLink : function() {
		document.getElementById('flashLink').onclick = function() {
			var url = contextRoot + "/rest/site/" + username
					+ "/flash?preview=1";
			for ( var k in jsonSign.flash)
				url += "&" + k + "=" + encodeURIComponent(jsonSign.flash[k]);
			open(url);
		}
	},
	deleteLog : function() {
		if (confirm("确定删除LOGO?")) {
			$("#log").empty();
			$("#logEdit").empty();
			$("#uploadLogoFile").val("");
			delete jsonSign.log;
		}
	},
	fn : {
		privateSetup : function($node, selector) {
			$(selector + " .check2").removeClass("check2").addClass("uncheck2");
			$node.removeClass("uncheck2").addClass("check2");
			$node.metadata().value = "url(" + $node.attr("src") + ")";
			mytheme.setup($node[0]);
		},
		setupTopic : function() {
			tool.fn.privateSetup($(this), "#topicImgList")
		},
		setupNavBg : function() {
			tool.fn.privateSetup($(this), "#navBgList")
		},
		setupTitleBg : function() {
			tool.fn.privateSetup($(this), "#titleBgList")
		},
		setupInBg : function() {
			tool.fn.privateSetup($(this), "#bgSetContIn")
		},
		setupOutBg : function() {
			tool.fn.privateSetup($(this), "#bgSetContOut")
		}
	},
	theme : null,
	style : null,
	useimg : null,
	href : msie6 ? "#" : "javascript:",
	msie6 : function() {
		$(function() {
			$("a[href=#]").click(function() {
				return false;
			});
		})
	}
}
var tool = new Tool();
tool.msie6();


text:
package com.msi.tough.engine.aws.elasticache;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.codehaus.jackson.annotate.JsonProperty;

import com.msi.tough.core.JsonUtil;

public class CacheClusterResource {

	private String type;
	private LinkedHashMap<String, Object> properties = null;
	private ArrayList<String> dependsOn = null;

	public CacheClusterResource() {
		dependsOn = new ArrayList<String>();
		properties = new LinkedHashMap<String, Object>();
		type = "AWS::ElastiCache::CacheCluster";
	}

	public void addProperty(final String key, final Object value) {
		properties.put(key, value);
	}

	public void addRefParameter(final LinkedHashMap<String, Object> properties,
			final String parameter) {
		properties.put(parameter, JsonUtil.toSingleHash("Ref", parameter));
	}

	@JsonProperty("DependsOn")
	public ArrayList<String> getDependsOn() {
		return dependsOn;
	}

	@JsonProperty("Properties")
	public LinkedHashMap<String, Object> getProperties() {
		return properties;
	}

	@JsonProperty("Type")
	public String getType() {
		return type;
	}

	public void setDefaultProperties() {

		// Should move Elasticache Constants so they can be used here
		addRefParameter(properties, "AutoMinorVersionUpgrade");
		addRefParameter(properties, "CacheNodeType");
		addRefParameter(properties, "CacheParameterGroupName");
		addRefParameter(properties, "Engine");
		addRefParameter(properties, "EngineVersion");
		addRefParameter(properties, "NotificationTopicArn");
		addRefParameter(properties, "NumCacheNodes");
		addRefParameter(properties, "Port");
		addRefParameter(properties, "PreferredAvailabilityZone");
		// addRefParameter( properties, "CacheSecurityGroupNames");
	}

	public void setDependsOn(final ArrayList<String> dependsOn) {
		this.dependsOn = dependsOn;
	}

	public void setProperties(final LinkedHashMap<String, Object> properties) {
		this.properties = properties;
	}

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


text:
This will install prober on your Mac.

--------------------------------------------------

This is a basic welcome message that is generated for every Omnibus project. You should customize this message by editing the file at files/mac_pkg/welcome.html.

If you are not the developer of prober, the presence of this message is likely a bug and should be reported to the creator.

Thank you for choosing Omnibus! Have a fantastic day!


text:
/* tslint:disable:no-unused-variable */
import * as React from 'react'
/* tslint:enable:no-unused-variable */
import {ShallowWrapper, shallow} from 'enzyme'
import Empty from '.'

type TestContext = {
  wrapper: ShallowWrapper<any, {}>
}

describe('Empty', function () {
  beforeEach(function (this: TestContext) {
    this.wrapper = shallow(
      <Empty />
    )
  })

  it('renders with its class', function (this: TestContext) {
    expect(this.wrapper.is('.yam-empty')).toBe(true)
  })
})


text:
package io.github.theangrydev.businessflows;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class HappyCaseSadPathTest {

    class Happy {

    }

    private final Happy happy = new Happy();
    private final HappyCaseSadPath<Happy, Object> happyCaseSadPath = new HappyCaseSadPath<>(happy);

    @Test
    public void toOptionalIsEmpty() {
        assertThat(happyCaseSadPath.toOptional()).isEmpty();
    }

    @Test
    public void ifTechnicalFailureIsHappyCase() {
        assertThat(happyCaseSadPath.ifTechnicalFailure()).isInstanceOf(HappyCaseTechnicalFailure.class);
        assertThat(happyCaseSadPath.ifTechnicalFailure().ifHappy().get()).isSameAs(happy);
    }

    @Test
    public void ifHappyIsHappyCase() {
        assertThat(happyCaseSadPath.ifHappy()).isInstanceOf(HappyCaseHappyPath.class);
        assertThat(happyCaseSadPath.ifHappy().get()).isSameAs(happy);
    }

    @Test
    public void ifSadReturnsThis() {
        assertThat(happyCaseSadPath.ifSad()).isSameAs(happyCaseSadPath);
    }

    @Test
    public void thenReturnsThis() {
        assertThat(happyCaseSadPath.then(null)).isSameAs(happyCaseSadPath);
    }

    @Test
    public void mapReturnsThis() {
        assertThat(happyCaseSadPath.map(null)).isSameAs(happyCaseSadPath);
    }

    @Test
    public void recoverUsingAttemptReturnsHappyCase() {
        assertThat(happyCaseSadPath.recover((Attempt<Happy>) null)).isInstanceOf(HappyCaseHappyPath.class);
        assertThat(happyCaseSadPath.recover((Attempt<Happy>) null).get()).isSameAs(happy);
    }

    @Test
    public void recoverUsingMappingAttemptReturnsHappyCase() {
        assertThat(happyCaseSadPath.recover((Mapping<Object, Happy>) null)).isInstanceOf(HappyCaseHappyPath.class);
        assertThat(happyCaseSadPath.recover((Mapping<Object, Happy>) null).get()).isSameAs(happy);
    }

    @Test
    public void peekReturnsThis() {
        assertThat(happyCaseSadPath.peek(null)).isSameAs(happyCaseSadPath);
    }
}


text:
var esprima = require('esprima');
var esgraph = require('esgraph');
var analyses = require('analyses');
var codegen = require("escodegen");
var Shade = require("..");
var walk = require('estraverse');
var Syntax = walk.Syntax;
var fs = require('fs');
var should = require('should');
var Compiler = require("../src/generate/glmatrix/compiler.js").GLMatrixCompiler;

var SnippetList = require("../src/generate/snippets/snippet-list").SnippetList;
var SnippetEntry = require("../src/generate/snippets/snippet-list").SnippetEntry;
var SnippetConnector = require("../src/generate/snippets/snippet-connector");

function createSnippetList(connection, snippetFunctions){
    var list = new SnippetList();
    for(var i = 0; i < connection.length; ++i){
        var entry = connection[i];
        var code = snippetFunctions[entry.code];
        var snippetEntry = new SnippetEntry(Shade.getSnippetAst(code));
        addEntryInput(snippetEntry, entry);
        addEntryOutput(snippetEntry, entry);
        list.addEntry(snippetEntry);
    }
    return list;
}

function addEntryInput(dest, src){
    for(var i = 0; i < src.input.length; ++i){
        var entry = src.input[i];
        if(entry.directInputIndex !== undefined){
            if(entry.iterate)
                dest.addVertexInput(entry.type, entry.directInputIndex);
            else if(entry.arraySize)
                dest.addUniformArray(entry.type, entry.directInputIndex, entry.arraySize);
            else
                dest.addUniformInput(entry.type, entry.directInputIndex);
        }
        else{
            dest.addTransferInput(entry.type, entry.transferOperator, entry.transferOutput);
        }
    }
}

function addEntryOutput(dest, src){
    for(var i = 0; i < src.output.length; ++i){
        var entry = src.output[i];
        if(entry.finalOutputIndex !== undefined){
            dest.addFinalOutput(entry.type, entry.name, entry.finalOutputIndex);
        }
        else{
            dest.addLostOutput(entry.type, entry.name);
        }
    }
}

function extractSnippetFunctions(ast){
    var result = {};
    var properties = ast.expression.right.properties;
    var i = properties.length;
    while(i--){
        var key = properties[i].key.name;
        var method = properties[i].value;
        result[key] = method;
    }
    return result;
}

function createTest(dir, file) {
    if(fs.lstatSync(dir + file).isDirectory())
        return;
    var contents = fs.readFileSync(dir + file, 'utf8');
    var ast = esprima.parse(contents, {comment: true, range: true});
    var comments = ast.comments;
    delete ast.comments;
    var description = comments[0].value.trim() + ' (' + file + ')';
    var connection = JSON.parse(comments[1].value);
    var jsInfo = JSON.parse(comments[2].value);
    var glslInfo = JSON.parse(comments[3].value);
    var snippetsFunctions = extractSnippetFunctions(ast.body[0]);
    it(description, function () {
        var outputJs = {
                type: Syntax.Program,
                body: ast.body[1].body
            };
        outputJs.body[0].id.name = "main";
        var outputGLSL = {
                type: Syntax.Program,
                body: ast.body[2].body
            };
        outputGLSL.body[0].id.name = "main";

        var snippetList = createSnippetList(connection, snippetsFunctions);
        var resultJs = SnippetConnector.connectSnippets(snippetList, {mode: SnippetConnector.MODE.JS_ITERATE});
        var compiledCode = codegen.generate(resultJs.ast);
        var expectedCode = codegen.generate(outputJs);
        compiledCode.should.eql(expectedCode);
        resultJs.argTypes.should.eql(jsInfo.argTypes);

        snippetList = createSnippetList(connection, snippetsFunctions);
        var resultGLSL = SnippetConnector.connectSnippets(snippetList, {mode: SnippetConnector.MODE.GLSL_VS});
        compiledCode = codegen.generate(resultGLSL.ast);
        expectedCode = codegen.generate(outputGLSL);
        compiledCode.should.eql(expectedCode);
        resultGLSL.argTypes.should.eql(glslInfo.argTypes);
        resultGLSL.inputIndices.should.eql(glslInfo.inputIndices);
    });
}

describe('Snippet Connection:', function () {

    var dir = __dirname + '/data/snippet/';

//    createTest(dir, "swizzles.js");

    var files = fs.readdirSync(dir);
    files.forEach(function (file) {
        createTest(dir, file);
    });

});


text:
package eap.util.validator;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 *
 Title: 必须

 *
 Description:

 * @作者 chiknin@gmail.com
 * @创建时间
 * @版本 1.00
 * @修改记录
 *

 * 版本       修改人         修改时间         修改内容描述
 * ----------------------------------------
 *
 * ----------------------------------------
 *

 */
@Documented
@Constraint(validatedBy = {RequiredValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Required {

	String message() default "{validator.constraints.Required.message}";

//	String script() default "";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };

	@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
	@Retention(RUNTIME)
	@Documented
	public @interface List {
		Required[] value();
	}
}


text:
#include "SimTKcommon/basics.h"
#include "SimTKcommon/internal/Random.h"
#include "SimTKcommon/internal/AtomicInteger.h"
#include "SFMT.h"

#include <cassert>
#include <cmath>

using namespace SimTK_SFMT;

namespace SimTK {

/**
 * This is the private implementation class for Random.  It has a subclass corresponding to each subclass of Random.
 */

class Random::RandomImpl {
private:
    mutable SimTK_SFMT::SFMTData* sfmt;
    static const int bufferSize = 1024;
    mutable uint64_t buffer[bufferSize];
    mutable int nextIndex;
    static AtomicInteger nextSeed;
public:
    class UniformImpl;
    class GaussianImpl;

    RandomImpl() {
        sfmt = createSFMTData();
        nextIndex = bufferSize;
        init_gen_rand(++nextSeed, *sfmt);
    }

    virtual ~RandomImpl() {
        deleteSFMTData(sfmt);
    }

    virtual void setSeed(int seed) {
        nextIndex = bufferSize;
        init_gen_rand(seed, *sfmt);
    }

    virtual Real getValue() const = 0;

    Real getNextRandom() const {
        if (nextIndex >= bufferSize) {
            // There are no remaining values in the buffer, so we need to refill it.

            fill_array64(buffer, bufferSize, *sfmt);
            nextIndex = 0;
        }
        return Real(to_res53(buffer[nextIndex++]));
    }

    int getInt(int max) {
        return (int) floor(getValue()*max);
    }

    void fillArray(Real array[], int length) const {
        for (int i = 0; i < length; ++i)
            array[i] = getValue();
    }
};

AtomicInteger Random::RandomImpl::nextSeed = 0;

/**
 * This is the private implementation class for uniform random numbers.
 */

class Random::Uniform::UniformImpl : public Random::RandomImpl {
private:
    Real min, max, range;
public:
    UniformImpl(Real min, Real max) : min(min), max(max), range(max-min) {
    }

    Real getValue() const override {
        return min+getNextRandom()*range;
    }

    Real getMin() const {
        return min;
    }

    void setMin(Real value) {
        min = value;
        range = max-min;
    }

    Real getMax() const {
        return max;
    }

    void setMax(Real value) {
        max = value;
        range = max-min;
    }
};

/**
 * This is the private implementation class for Gaussian random numbers.
 */

class Random::Gaussian::GaussianImpl : public Random::RandomImpl {
private:
    Real mean, stddev;
    mutable Real nextGaussian;
    mutable bool nextGaussianIsValid;
public:
    GaussianImpl(Real mean, Real stddev) : mean(mean), stddev(stddev) {
        nextGaussianIsValid = false;
    }

    Real getValue() const override {
        if (nextGaussianIsValid) {
            nextGaussianIsValid = false;
            return mean+stddev*nextGaussian;
        }

        // Use the polar form of the Box-Muller transformation to generate two Gaussian random numbers.

        Real x, y, r2;
        do {
            x = 2*getNextRandom()-1;
            y = 2*getNextRandom()-1;
            r2 = x*x + y*y;
        } while (r2 >= 1.0 || r2 == 0.0);
        Real multiplier = std::sqrt((-2*std::log(r2))/r2);
        nextGaussian = y*multiplier;
        nextGaussianIsValid = true;
        return mean+stddev*x*multiplier;
    }

    void setSeed(int seed) override {
        RandomImpl::setSeed(seed);
        nextGaussianIsValid = false;
    }

    Real getMean() const {
        return mean;
    }

    void setMean(Real value) {
        mean = value;
    }

    Real getStdDev() const {
        return stddev;
    }

    void setStdDev(Real value) {
        stddev = value;
    }
};

Random::Random() : impl(0) {
}

Random::~Random() {
    delete impl;
}

Random::RandomImpl& Random::getImpl() {
    assert(impl);
    return *impl;
}

const Random::RandomImpl& Random::getConstImpl() const {
    assert(impl);
    return *impl;
}

void Random::setSeed(int seed) {
    getImpl().setSeed(seed);
}

Real Random::getValue() const {
    return getConstImpl().getValue();
}

void Random::fillArray(Real array[], int length) const {
    getConstImpl().fillArray(array, length);
}

Random::Uniform::Uniform() {
    impl = new Random::Uniform::UniformImpl(0.0, 1.0);
}

Random::Uniform::Uniform(Real min, Real max) {
    impl = new Random::Uniform::UniformImpl(min, max);
}

Random::Uniform::UniformImpl& Random::Uniform::getImpl() {
    assert(impl);
    return SimTK_DYNAMIC_CAST_DEBUG<Random::Uniform::UniformImpl&>(*impl);
}

const Random::Uniform::UniformImpl& Random::Uniform::getConstImpl() const {
    assert(impl);
    return SimTK_DYNAMIC_CAST_DEBUG<Random::Uniform::UniformImpl&>(*impl);
}

int Random::Uniform::getIntValue() {
    return (int) std::floor(getImpl().getValue());
}

Real Random::Uniform::getMin() const {
    return getConstImpl().getMin();
}

void Random::Uniform::setMin(Real min) {
    getImpl().setMin(min);
}

Real Random::Uniform::getMax() const {
    return getConstImpl().getMax();
}

void Random::Uniform::setMax(Real max) {
    getImpl().setMax(max);
}

Random::Gaussian::Gaussian() {
    impl = new Random::Gaussian::GaussianImpl(0.0, 1.0);
}

Random::Gaussian::Gaussian(Real mean, Real stddev) {
    impl = new Random::Gaussian::GaussianImpl(mean, stddev);
}

Random::Gaussian::GaussianImpl& Random::Gaussian::getImpl() {
    assert(impl);
    return SimTK_DYNAMIC_CAST_DEBUG<Random::Gaussian::GaussianImpl&>(*impl);
}

const Random::Gaussian::GaussianImpl& Random::Gaussian::getConstImpl() const {
    assert(impl);
    return SimTK_DYNAMIC_CAST_DEBUG<Random::Gaussian::GaussianImpl&>(*impl);
}

Real Random::Gaussian::getMean() const {
    return getConstImpl().getMean();
}

void Random::Gaussian::setMean(Real mean) {
    getImpl().setMean(mean);
}

Real Random::Gaussian::getStdDev() const {
    return getConstImpl().getStdDev();
}

void Random::Gaussian::setStdDev(Real stddev) {
    getImpl().setStdDev(stddev);
}

} // namespace SimTK


text:
package org.keycloak.services.clientregistration;

import org.keycloak.provider.ProviderFactory;

/**
 * @author Stian Thorgersen
 */
public interface ClientRegistrationProviderFactory extends ProviderFactory<ClientRegistrationProvider> {
}


text:
package org.hibernate.ejb.test.ejb3configuration.id;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.ejb.cfg.spi.IdentifierGeneratorStrategyProvider;

/**
 * @author Emmanuel Bernard <emmanuel@hibernate.org>
 */
public class FunkyIdentifierGeneratorProvider implements IdentifierGeneratorStrategyProvider {
	public Map<String, Class<?>> getStrategies() {
		final HashMap<String, Class<?>> result = new HashMap<String, Class<?>>( 1 );
		result.put( "funky", FunkyIdGenerator.class );
		return result;
	}
}


text:
Cordova Evan Plugin Background
==============================

Prevents Cordova apps running in Android devices from going to sleep while in background.

Based on [Cordova Background Plug-in](https://github.com/katzer/cordova-plugin-background-mode)

Install
-------

```sh
cordova plugin add https://github.com/tassoevan/cordova-plugin-evan-background.git
```

Usage
-----

```js
// Configure notification on background
cordova.Evan.Background.configure({
    title: "My App",
    ticker: "My App is still running",
    text: "Doing heavy tasks"
});

// Enable background mode
cordova.Evan.Background.enable();

// Disable background mode
cordova.Evan.Background.disable();
```