text:
Full continuous deployment pipeline using tools running all in docker containers.

Each tool runs in a separeted docker container and to manages the orchestration and deployment of the docker images
and containers we use Docker Compose.

Docker Compose is a tool for defining and running multi-container applications with Docker. With Compose,
you define a multi-container application in a single file, then spin your application up in a single command which does
everything that needs to be done to get it running.

Within the continuous deployment environment we use the following tools:

- Gitlab - Similar to GitHub but open source
- Jenkins
- Docker
- Docker-compose
- Docker-registry - Similar to docker hub but open source
- Docker-registry-ui
- Mesos
- Mesosphere Marathon
- Zookeeper for internal use of Mesos and Marathon

##Pipeline Description

The continuous deployment pipeline should be configured as follows, the developers work on their local environments and running their build, test and other processes within Docker containers. Once their code is ready and tested they will commit it to the central Git repo (Gitlab) and the new piece of code will continue its journey towards deployment.

After this, the jenkins detect a new modifications on the git repo and build the application and run all configured tests and having success in it all then push to the docker-registry the new docker images related to the application deployed, finally deploy the application on the marathon, that is an Apache Mesos framework for long-running applications. It ensures that an app stays up even when machines or entire racks fail.

With your application deployed on Marathon you can do acceptance test and scale the app with just using the Marathon interface.

##Prerequisites:

Install the following tools:
- Git Client
- Docker [link](https://docs.docker.com/installation/)
- Docker-compose [link](https://docs.docker.com/compose/install/)

Advice: The docker-compose and docker should be installed under same user account. Can be necessary allow to running the docker without root account, to do this execute the following commands:

> $ sudo groupadd docker

> $ sudo gpasswd -a $ {USER} docker

> $ sudo service docker restart

> $ exit

##Download the solution

Download the solution and go to the directory, just executing the following commands:

> $ git clone https://github.com/dgmachado/devops-tools.git

> $ cd devops-tools

Just if you are using a CentOS you also need execute the following commands:

> $ cd volumes

> $ chcon -Rt svirt_sandbox_file_t *

Obs: Directories that you are mounting into the container need to have svirt_sandbox_file_t as their label.

##Quick Start

To lauch the full continuous deployment pipeline environment, just execute the following command:

> $ docker-compose up -d

This command will download the required images launching containers and will start these with this configuration in the docker-compose.yml file. You will see the following output:

> Creating devopstools_zookeeper_1...

> Creating devopstools_postgresql_1...

> Creating devopstools_redis_1...

> Creating devopstools_gitlab_1...

> Creating devopstools_mesosMaster_1...

> Creating devopstools_marathon_1...

> Creating devopstools_chronos_1...

> Creating devopstools_jenkins_1...

> Creating devopstools_mesosSlave1_1...

> Creating devopstools_mesosSlave2_1...

> Creating devopstools_mesosSlave3_1...

> Creating devopstools_registry_1...

> Creating devopstools_registryui_1...

You should algo verify the state of the services executing the following command:

> $ docker-compose ps

If any service haven't the up state you can verify the problem analyzing the logs just executing the following command:

> $ docker-compose logs

##Access

See the following tools that can be accessed:

- Jenkins -> http://IP_ADDRESS:8081
- GitLab -> http://IP_ADDRESS:10080
- Registry-UI -> http://IP_ADDRESS:9090
- Marathon -> http://IP_ADDRESS:8080
- Mesos -> http://IP_ADDRESS:5050
- Chronos -> http://IP_ADDRESS:4400

If the services are deployed locally, it is possible to replace IP_ADDRESS by localhost

An account already exists in GitLab, change the password as requested after the first connection:

>username: root

>password: 5iveL!fe

Beware with the tools configurations. Some of these tools are accessible without login and for production use they should be protected. It is advisable not to use existing accounts but rather create additional and secure accounts for production use.

##Configuration an new app on CD pipeline

For this example, we'll create a new project on the interface GitLab and place our code with Git client. The code we'll use is the one present in the deposit. It is a small Node application with a Hello World web page.

###Publishing the source code on Gitlab repository

To publishing the source code on Gitlab repositor following the next steps:

1. Create a new project on GitLab with the name "SampleApp"
2. Be placed in the folder sampleapp
3. Initialize the local repository
> $ git init

4. Connect the local repository and the remote
> $ git remote add origin http://localhost:10080/root/SampleApp.git

5. Add all files to be commited
> $ git add .

6. Commit the content
> $ git commit -m "Initial Commit"

7. Pushing the code on the remote repository
> $ git push origin master

8. Access the gitlab url (http://localhost:10080) to verify your pushed source code

###Configurating the Jenkins

To configurating the jenkins build and deploy following the next steps:

1. Access the Jenkins and create a new job "SampleApp" Freestyle project type
2. Configure the project with Git and the URL http://gitlab/root/SampleApp.git and enter the credentials with user and the password that we created earlier
3. In the Build Triggers section, check the periodic construction and specify the following settings:
> H/2 \* \* \* \*
>
> This will run a building for every two minutes

4. Add the following build steps of type 'Execute shell' to the build:

   - First Command - Script to build the app container
   > ./continuous_deployment_scripts/build_appcontainer.sh ${BUILD_ID}

   - Second Command - Script to push the app container
   > ./continuous_deployment_scripts/push_appcontainer.sh ${BUILD_ID}

   - Third Command - Script to deploy the app container
   > ./continuous_deployment_scripts/deploy_appcontainer.sh ${BUILD_ID}

5. Save the configuration
6. Build manually the "SampleApp" project
7. After the build if all successfully finished we can see the application running on Marathon web page:
> localhost:8080

8. We can see our app on http://localhost:31000

###Using the CD envirement

To using the CD envirement following the next steps:

1. Edit the file sampleapp/nodejs_app/app.js and replace the text "Hello World\n" by the text "Hello World - New version\n";
2. Publish the new code

  > $ git add .

  > $ git commit -m "Nodejs app modified"

  > $ git push origin master

3. Wait for 2 minutes and access the page http://localhost:31000 and see the new modification
4. See the app running on the Marathon (http://localhost:8080)

##Final Words

My recommendation is that you use at least two distinct pipeline environments, one specific for development and acceptance tests and another to production, and you could too do even more and also separate the development and acceptance tests environment and would be great.

The deploy of the development environment pipeline could push the new code on the git repo of the acceptance test and in the same way the acceptance test pipeline could push code to git repo of production pipeline finally could deploy the app in same cloud vendor. There are endless ways to customize these settings in order to achieve powerful environments and it depends only of you.

There are two main direction to improve this devops-tools system: adding more functionality and deepening the quality of the setup. The list of possible extensions is very long. Here are some examples:

- Manage code quality (SonarQube)
- Auto-scaling system (Jmeter)
- Package manager (NPM, NugetServer, Maven, ...)
- Project management platform (Taiga)
- Adding centralised logging

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "jq ftw II"
date:   2017-07-14 20:54:16
categories: tools
excerpt: "exploring more cool tricks with jq"
tags:
  - bash
---

Well, my affinity for shell scripting shows no sign of slowing down.  Today I found out some more cool stuff that is possible with the `jq` utility.

In addition to the easy handling of raw JSON, `jq` also provides classic functional operators like `map`, `reduce` and `filter` which can be chained together.

To facilitate, there's a fantastic website called [jqplay](https://jqplay.org/) which I highly recommend!

Here's a quick example of how to curl some API data and transform it into a format that can be easily bash'ed with.

Sample of input data from [https://jsonplaceholder.typicode.com/](https://jsonplaceholder.typicode.com/):

(api returns 10 at a time, this is just one sample)
{% highlight json %}
[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }
]
{% endhighlight %}

The command:
{% highlight bash %}
curl -s "https://jsonplaceholder.typicode.com/users" \
  | jq 'map([.website, .id|tostring] | join(" => ")) | join("\n")'
{% endhighlight %}

Notes:
* The `curl` request returns an array of objects
* Each object is yielded to `map`
* `map` returns an array for each object, composed of `website` and `id|tostring` (nice pipe function to turn int into string)
* each array is flattened into a new string with `=>` symbol in between
* then the whole array is flattened into a string of elements separated by new line characters

Output:
{% highlight bash %}
hildegard.org => 1
anastasia.net => 2
ramiro.info => 3
kale.biz => 4
demarco.info => 5
ola.org => 6
elvis.io => 7
jacynthe.com => 8
conrad.com => 9
ambrose.net => 10
{% endhighlight %}

We can use the `read/while` loop [described yesterday](/tools/2017/07/13/jq-ftw.html) to loop over this data and do whatever we want with it.  For example, we can use the original call to gather the elements needed to compose URLs, then we can build the URLs dynamically in the loop and fetch the data.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" href="/img/favicon.ico">

    <title>SISE-CWEB</title>

    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/jumbotron-narrow.css" rel="stylesheet">

Home

Get help

SISE-CWEB

Hello friend

This is just a placeholder for the UI of your project. Good luck!

Do eet!


text:
<?php

// /var/www/symfony2.0/alf/src/Alf/ShopBundle/Resources/views/Shop/test.html.twig
return array (
);


text:
    $navpath

Generated on $datetime for phpMv-UI
 by doxygen $doxygenversion

<address class="footer">Generated on $datetime for phpMv-UI
 by doxygen $doxygenversion
</address>


text:
package org.apache.commons.betwixt.derived;

/**
EmployeeBean a sample derived bean.

 *
 * @author James Strachan
 * @version $Revision$
 */
public class EmployeeBean extends PersonBean {

   public EmployeeBean() {
   }
}


text:
package org.kaazing.k3po.driver.internal.netty.bootstrap.bbosh;

import org.jboss.netty.channel.ChannelConfig;

public interface BBoshChannelConfig extends ChannelConfig {

}


text:
<?php

declare(strict_types=1);

namespace Broadway\EventHandling;

use Broadway\Domain\DomainEventStream;

/**
 * Simple synchronous publishing of events.
 */
final class SimpleEventBus implements EventBus
{
    private $eventListeners = [];
    private $queue = [];
    private $isPublishing = false;

    /**
     * {@inheritdoc}
     */
    public function subscribe(EventListener $eventListener): void
    {
        $this->eventListeners[] = $eventListener;
    }

    /**
     * {@inheritdoc}
     */
    public function publish(DomainEventStream $domainMessages): void
    {
        foreach ($domainMessages as $domainMessage) {
            $this->queue[] = $domainMessage;
        }

        if (!$this->isPublishing) {
            $this->isPublishing = true;

            try {
                while ($domainMessage = array_shift($this->queue)) {
                    foreach ($this->eventListeners as $eventListener) {
                        $eventListener->handle($domainMessage);
                    }
                }
            } finally {
                $this->isPublishing = false;
            }
        }
    }
}


text:
package com.babel.order;

/**
 * @author liviu.cretu
 * @version 1.0
 * @created 06-Oct-2014 7:34:55 PM
 */
@javax.ejb.Stateless
@javax.ejb.Remote(value=CreateOrder.class)
@javax.ejb.Local(value=CreateOrder.class) //JBoss 4.2 still supports same interface as Remote. Otherwise, extend remote interfce with anither interface
@javax.ejb.TransactionManagement(javax.ejb.TransactionManagementType.CONTAINER)
public class CreateOrderEJB implements CreateOrder {

	private CreateOrder delegate;
	@javax.persistence.PersistenceContext(unitName="myJPAUnit")
	private javax.persistence.EntityManager em;

	public CreateOrderEJB(){

	}

	public void finalize() throws Throwable {

	}
	/**
	 *
	 * @param p
	 */
	public Order createOrder(Order p){
		return this.delegate.createOrder(p);
	}

	@javax.annotation.PostConstruct
	public void init(){
		this.delegate=new CreateOrderImpl();
		 (( CreateOrderImpl)this.delegate).setEm(em);
	}
}//end CreateOrderEJB


text:
function print_environment()
{
    echo "Date: $(date)"
    echo "Directory: $(pwd)"
    echo "Kernel: $(uname -a)"
    echo "Memory: $(head -n1 /proc/meminfo)"
    echo "Processor: $(grep 'model name' /proc/cpuinfo | head -n1)"

    echo ""
}

function run_test_suite()
{
    local entry_point
    local bucket_name
    local log_file
    local s3_path
    local result
    local elapsed_time

    entry_point=$1
    bucket_name=$2
    test_name=$3

    #echo "DEBUG $(pwd)"

    log_file=$entry_point.txt

    #time (echo "This is a test" &> $log_file) &> $log_file.time
    time (./$entry_point &> $log_file) &> $log_file.time

    elapsed_time=$(grep real $log_file.time|awk '{print $2}')
    result=$(tail -n1 $log_file)

    s3_path="s3://$bucket_name/tests/$test_name"

    aws s3 cp $log_file $s3_path/$log_file &> $log_file.s3

    address="https://$bucket_name.s3.amazonaws.com/tests/$test_name/$log_file"

    echo "TestSuite: $entry_point Result: $result Time: $elapsed_time Log: $address"
}

function test_endpoint()
{
    local topic
    local bucket_name
    local test_name
    local test_suite
    local log_file
    local address
    local endpoint
    local subject
    local message
    local repository
    local branch
    local directory

    repository="https://github.com/kbase/assembly.git"

    endpoint=$1
    branch=$2
    directory=$3

    # go in the common test directory
    cd $directory

    export ARAST_URL=$endpoint
    test_name=$(date +%Y-%m-%d-%H:%M:%S)
    bucket_name="kbase-assembly-service"

    # create current test directory and go inside it
    mkdir -p $test_name
    cd $test_name

    log_file="main.txt"

    (
    print_environment

    echo "TestName: $test_name"
    echo "Directory: $(pwd)"
    echo "Repository: $repository"
    echo "Branch: $branch"
    echo "Service endpoint: $endpoint"

    echo ""

    # Clone repository and deploy
    (
    echo "Clone"
    git clone $repository
    cd assembly
    git checkout $branch

    make -f Makefile.standalone deploy DEPLOY_RUNTIME=/software/python/2.7.3-1/
    ) &> clone.txt

    cd assembly
    cd test

    echo "Git Commit: $(git log | head -n1|awk '{print $2}')"

    # set up the path
    export PATH=$directory/$test_name/assembly/deployment/bin:$PATH

    # run tests
    run_test_suite arast.t.sh $bucket_name $test_name

    #run_test_suite . mock.sh $bucket_name $
    # run_test_suite $test_name integration_test_1.sh $bucket_name
    # run_test_suite $test_name test_SRS213780.sh $bucket_name

    ) | tee $log_file

    s3_path="s3://$bucket_name/tests/$test_name"

    aws s3 cp $log_file $s3_path/$log_file

    address="https://$bucket_name.s3.amazonaws.com/tests/$test_name/$log_file"

    topic="arn:aws:sns:us-east-1:584851907886:kbase-assembly-service"
    subject="[KBase] Assembly Service quality assurance results ($endpoint)"

    message="$(cat $log_file)

Quality assurance result is available at $address."

    aws sns publish --topic-arn $topic --subject "$subject" \
    --message "$message"
}

function main()
{
    local argc=$#
    local prod_url="http://kbase.us/services/assembly"
    local dev_url="140.221.84.203"

    local production_branch="master"
    local development_branch="dev"

    local directory="/home/boisvert/stuff/assembly-service-tests"

    # default : dev && prod
    # dev     : "140.221.84.203"
    # prod    : "http://kbase.us/services/assembly"
    # string  : use string as endpoint

    if test $argc -eq 0
    then
        main "default"
        return
    fi

    local operand=$1

    if test $operand = "prod"
    then
        test_endpoint $prod_url $production_branch $directory

    elif test $operand = "dev"
    then
        test_endpoint $dev_url $development_branch $directory

    elif test $operand = "default"
    then
        test_endpoint $prod_url $production_branch $directory
        test_endpoint $dev_url $development_branch $directory

    else
        test_endpoint $operand $production_branch $directory
    fi
}

main $@


text:
/**
 * 后端文章预览页面
 * Created by y27chen on 2016/10/29.
 */
import AdminBasePage from "../../joshua-admin-base-page";
import Editor from "../../component/editor";

class AdminArticleReaderPage extends AdminBasePage {
    constructor() {
        super();
        this.editor = new Editor();
    }
}

$(document).ready(()=> {
    var page = new AdminArticleReaderPage();
    page.editor.loadAsReader();
    page.editor.loadContent($("#article-id").val(), page.editor.initContent);
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.chan.englishboby"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name="com.chan.englishbaby.base.BaseApplication"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.chan.englishbaby.views.impls.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity android:name="com.chan.englishbaby.MainActivity" android:exported="false"/>
        <activity android:name="com.chan.englishbaby.views.impls.InitActivity" android:exported="false"/>
        <activity android:name="com.chan.englishbaby.views.impls.LessonActivity" android:exported="false"/>
    </application>

</manifest>


text: module.exports = { axe: require('./rule') };


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Mitt. Staatssamml. München 13:506. 1977

#### Original name
null

### Remarks
null


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Senecio hansenii G.Kunkel

### Remarks
null


text:
Lightweight web framework on top of Cowboy: a dynamite powered Cowboy

This is a responsive and lightweight web framework written in Elixir that run on top of the [Cowboy web server](http://ninenines.eu/docs/en/cowboy/HEAD/guide/introduction/)

The scope of this project is to offer a dynamic environment with a simple but powerful up-to-date tools where several sites could be hosted at the same time, sharing resources when needed but with a safe and clear separation of scopes.

It is known to work well with:
* Elixir > 1.1.0
* Cowboy > 1.0.0

## Disclaimer:

The current implementation is to be taken as a proof of concept. The author is using it as a vehicle for learning Elixir. For any serious job, please consider more mature frameworks such as Phoenix.

However, given that is so simple yet well featured, flexible and performant, it could be useful for some use cases. The author have several instances running smoothly on production environments 24/7 in both Linux and Windows.

## Instructions:

With Erlang/Elixir installed, clone the repo and run within the cloned directory:

 ```
    mix deps.get
    mix deps.compile
    cp config/config.sample config/config.exs
    iex -S mix
 ```

Then, open a browser to localhost:8080. There is a sample site configured to serve static and dynamic content, including broadcasting through websockets.

Several sites could be configured to work at the same time, listening to different ports and serving content comming from  different locations. There is a default site listening to port 9999 that permit to configure Dynamite and manage the options for the sites dynamically without ever stopping the server.

It is very easy to setup a working site on Dynamite. Each site is composed by:

* Routes: one or more Cowboy routing as EEx dynamic files
* Views: dynamic HTML with EEx parsing
* Static: browser side functionality and static resources

The routes and views are parsed at runtime and served dynamically, so they could be modified at any time, thus facilitating the development of web applications.

In order to have a performant web application, the programmer should find a good balance between server side and browser side functionality. For example, one method to optimize the flow of data is to use a front end datastore with sync capabilities to the back end database. The browser should handle all the user interaction, formatting, data sanitization and layout (bells and whistles) while the server should handle the data retrieval and storage.

There is a sample site included in the repository that used [Pouchdb](https://pouchdb.com/api.html) as a front end for [Couchdb](http://couchdb.apache.org/) for all the data handling. The sample site includes several javascript libraries for enhancing the browser functionality:

* [Momentjs](http://momentjs.com/docs)
* [Chartjs](http://nnnick.github.io/Chart.js/docs-v2/)
* [Dynamize](http://j-pel.github.io/dynamize)

## Mode of employ

For real life scenarios, a site should bind to port 80 (or 443). It is strongly suggested to run the server without root priviledges (avoid using `sudo` to launch the server). It is possible to use authbind and then launch Dynamite as follows:
 ```
# sudo apt-get install authbind
# sudo touch /etc/authbind/byport/80
# sudo chown user /etc/authbind/byport/80
# sudo chmod 755 /etc/authbind/byport/80
# cd /home/user/path/to/dynamite
# authbind --deep mix run --name web@example.com --no-halt > test/service.log 2>&1 < /dev/null &
```
The last command launches an instance of a beam virtual machine, redirecting stdout to a log file.

To start Dynamite on an `iex` console, binding to port 80 without root priviledges use:
```
# authbind --deep iex -S mix
```

## License:

This code is released under the MIT license.  See LICENSE.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:padding="@dimen/spacing_medium">

    <TextView
        android:id="@+id/textViewLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:lineSpacingExtra="3dp"
        android:text="Label" />

    <TextView
        android:id="@+id/textViewValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="Value" />
</RelativeLayout>


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>::marker supports 'overflow-wrap'</title>
<link rel="author" title="Oriol Brufau" href="mailto:obrufau@igalia.com" />
<link rel="help" href="https://drafts.csswg.org/css-pseudo-4/#marker-pseudo">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#overflow-wrap-property">
<link rel="match" href="marker-line-break-ref.html">
<meta name="assert" content="Checks that ::marker supports 'overflow-wrap', both explicitly set or inherited from an ancestor">


text:
namespace Fonet.Fo.Pagination
{
    using Fonet.Fo.Properties;

    internal class ConditionalPageMasterReference : FObj
    {
        new internal class Maker : FObj.Maker
        {
            public override FObj Make(FObj parent, PropertyList propertyList)
            {
                return new ConditionalPageMasterReference(parent, propertyList);
            }
        }

        new public static FObj.Maker GetMaker()
        {
            return new Maker();
        }

        private RepeatablePageMasterAlternatives repeatablePageMasterAlternatives;

        private string masterName;

        private int pagePosition;
        private int oddOrEven;
        private int blankOrNotBlank;

        public ConditionalPageMasterReference(FObj parent, PropertyList propertyList)
            : base(parent, propertyList)
        {
            this.name = GetElementName();
            if (GetProperty("master-reference") != null)
            {
                SetMasterName(GetProperty("master-reference").GetString());
            }

            validateParent(parent);

            setPagePosition(this.properties.GetProperty("page-position").GetEnum());
            setOddOrEven(this.properties.GetProperty("odd-or-even").GetEnum());
            setBlankOrNotBlank(this.properties.GetProperty("blank-or-not-blank").GetEnum());
        }

        protected internal void SetMasterName(string masterName)
        {
            this.masterName = masterName;
        }

        public string GetMasterName()
        {
            return masterName;
        }

        protected internal bool isValid(int currentPageNumber, bool thisIsFirstPage,
                                        bool isEmptyPage)
        {
            bool okOnPagePosition = true;
            switch (getPagePosition())
            {
                case PagePosition.FIRST:
                    if (!thisIsFirstPage)
                    {
                        okOnPagePosition = false;
                    }
                    break;
                case PagePosition.LAST:
                    FonetDriver.ActiveDriver.FireFonetInfo("Last page position not known");
                    okOnPagePosition = true;
                    break;
                case PagePosition.REST:
                    if (thisIsFirstPage)
                    {
                        okOnPagePosition = false;
                    }
                    break;
                case PagePosition.ANY:
                    okOnPagePosition = true;
                    break;
            }

            bool okOnOddOrEven = true;
            int ooe = getOddOrEven();
            bool isOddPage = ((currentPageNumber % 2) == 1) ? true : false;
            if ((OddOrEven.ODD == ooe) && !isOddPage)
            {
                okOnOddOrEven = false;
            }
            if ((OddOrEven.EVEN == ooe) && isOddPage)
            {
                okOnOddOrEven = false;
            }

            bool okOnBlankOrNotBlank = true;

            int bnb = getBlankOrNotBlank();

            if ((BlankOrNotBlank.BLANK == bnb) && !isEmptyPage)
            {
                okOnBlankOrNotBlank = false;
            }
            else if ((BlankOrNotBlank.NOT_BLANK == bnb) && isEmptyPage)
            {
                okOnBlankOrNotBlank = false;
            }

            return (okOnOddOrEven && okOnPagePosition && okOnBlankOrNotBlank);

        }

        protected internal void setPagePosition(int pagePosition)
        {
            this.pagePosition = pagePosition;
        }

        protected internal int getPagePosition()
        {
            return this.pagePosition;
        }

        protected internal void setOddOrEven(int oddOrEven)
        {
            this.oddOrEven = oddOrEven;
        }

        protected internal int getOddOrEven()
        {
            return this.oddOrEven;
        }

        protected internal void setBlankOrNotBlank(int blankOrNotBlank)
        {
            this.blankOrNotBlank = blankOrNotBlank;
        }

        protected internal int getBlankOrNotBlank()
        {
            return this.blankOrNotBlank;
        }

        protected internal string GetElementName()
        {
            return "fo:conditional-page-master-reference";
        }

        protected internal void validateParent(FObj parent)
        {
            if (parent.GetName().Equals("fo:repeatable-page-master-alternatives"))
            {
                this.repeatablePageMasterAlternatives =
                    (RepeatablePageMasterAlternatives)parent;

                if (GetMasterName() == null)
                {
                    FonetDriver.ActiveDriver.FireFonetWarning(
                        "single-page-master-reference"
                            + "does not have a master-reference and so is being ignored");
                }
                else
                {
                    this.repeatablePageMasterAlternatives.addConditionalPageMasterReference(this);
                }
            }
            else
            {
                throw new FonetException("fo:conditional-page-master-reference must be child "
                    + "of fo:repeatable-page-master-alternatives, not "
                    + parent.GetName());
            }
        }
    }
}


text:
package org.elixirian.jsonstatham.core.convertible;

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

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.junit.Test;

/**
 * <pre>
 *     ___  _____                                _____
 *    /   \/    /_________  ___ ____ __ ______  /    /   ______  ______
 *   /        / /  ___ \  \/  //___// //     / /    /   /  ___ \/  ___ \
 *  /        \ /  _____/\    //   //   __   / /    /___/  _____/  _____/
 * /____/\____\\_____/   \__//___//___/ /__/ /________/\_____/ \_____/
 * </pre>
 *
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-02-03)
 */
public class OrderedJsonObjectCreatorTest
{
  @Test
  public void testNewJSONObject() throws SecurityException, NoSuchFieldException, IllegalArgumentException,
      IllegalAccessException
  {
    final JsonObjectCreator jsonObjectCreator = new OrderedJsonObjectCreator();
    final JsonObject jsonObject = jsonObjectCreator.newJsonObjectConvertible();

    final Field mapField = jsonObject.getClass()
        .getSuperclass()
        .getDeclaredField("jsonFieldMap");
    mapField.setAccessible(true);
    final Object mapObject = mapField.get(jsonObject);
    assertThat(mapObject).isNotNull();
    assertThat(mapObject).isInstanceOf(LinkedHashMap.class);
    assertThat(mapObject.getClass()).isSameAs(LinkedHashMap.class);
    assertThat(mapObject.getClass()).isNotSameAs(HashMap.class);
  }
}


text:
import React, { Component, PropTypes, View, Image } from 'react-native';

export default class Header extends Component {

    static propTypes = {
        image: PropTypes.shape({ type: PropTypes.oneOf([Image]) }),
        backgroundColor: PropTypes.string,
        height: PropTypes.number,
        children: PropTypes.node
    };

    static defaultProps = {
        height: 150,
        backgroundColor: '#333333'
    };

    render() {
        const { image, height, backgroundColor, children } = this.props;

        if (image) {
            return React.cloneElement(image, {
                style: [styles.header, { height: height }]
            }, children);
        }

        return (
            <View style={[styles.header, { height: height, backgroundColor: backgroundColor }]}>
                {children}
            </View>
        );
    }
}

const styles = {
    header: {
        paddingHorizontal: 16,
        width: 300
    }
};


text:
<?php

namespace yii\db;

/**
 * ActiveQuery represents a DB query associated with an Active Record class.
 *
 * An ActiveQuery can be a normal query or be used in a relational context.
 *
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
 *
 * Normal Query
 * ------------
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
 * - [[count()]]: returns the number of records.
 * - [[sum()]]: returns the sum over the specified column.
 * - [[average()]]: returns the average over the specified column.
 * - [[min()]]: returns the min over the specified column.
 * - [[max()]]: returns the max over the specified column.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
 * - [[column()]]: returns the value of the first column in the query result.
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
 * [[orderBy()]] to customize the query options.
 *
 * ActiveQuery also provides the following additional query options:
 *
 * - [[with()]]: list of relations that this query should be performed with.
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
 * - [[asArray()]]: whether to return each record as an array.
 *
 * These options can be configured using methods of the same name. For example:
 *
 * ```php
 * $customers = Customer::find()->with('orders')->asArray()->all();
 * ```
 *
 * Relational query
 * ----------------
 *
 * In relational context ActiveQuery represents a relation between two Active Record classes.
 *
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
 *
 * A relation is specified by [[link]] which represents the association between columns
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
 *
 * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method.
 * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
 * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
 * is to be added to relational query join condition.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Carsten Brandt <mail@cebe.cc>
 * @since  2.0
 */
class ActiveQuery extends Query implements ActiveQueryInterface
{
    use ActiveQueryTrait;
    use ActiveRelationTrait;

    /**
     * @event Event an event that is triggered when the query is initialized via [[init()]].
     */
    const EVENT_INIT = 'init';

    /**
     * @var string the SQL statement to be executed for retrieving AR records.
     * This is set by [[ActiveRecord::findBySql()]].
     */
    public $sql;
    /**
     * @var string|array the join condition to be used when this query is used in a relational context.
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
     * Otherwise, the condition will be used in the WHERE part of a query.
     * Please refer to [[Query::where()]] on how to specify this parameter.
     * @see onCondition()
     */
    public $on;
    /**
     * @var array a list of relations that this query should be joined with
     */
    public $joinWith;

    /**
     * Constructor.
     * @param string $modelClass the model class associated with this query
     * @param array  $config     configurations to be applied to the newly created query object
     */
    public function __construct($modelClass, $config = [])
    {
        $this->modelClass = $modelClass;
        parent::__construct($config);
    }

    /**
     * Initializes the object.
     * This method is called at the end of the constructor. The default implementation will trigger
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
     * to ensure triggering of the event.
     */
    public function init()
    {
        parent::init();
        $this->trigger(self::EVENT_INIT);
    }

    /**
     * Executes query and returns all results as an array.
     * @param Connection $db the DB connection used to create the DB command.
     *                       If null, the DB connection returned by [[modelClass]] will be used.
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     */
    public function prepare($builder)
    {
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
        // multiple times.
        if (!empty($this->joinWith)) {
            $this->buildJoinWith();
            $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
        }

        if (empty($this->from)) {
            /* @var $modelClass ActiveRecord */
            $modelClass = $this->modelClass;
            $tableName  = $modelClass::tableName();
            $this->from = [$tableName];
        }

        if (empty($this->select) && !empty($this->join)) {
            foreach ((array)$this->from as $alias => $table) {
                if (is_string($alias)) {
                    $this->select = ["$alias.*"];
                } elseif (is_string($table)) {
                    if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $table, $matches)) {
                        $alias = $matches[2];
                    } else {
                        $alias = $table;
                    }
                    $this->select = ["$alias.*"];
                }
                break;
            }
        }

        if ($this->primaryModel === null) {
            // eager loading
            $query = Query::create($this);
        } else {
            // lazy loading of a relation
            $where = $this->where;

            if ($this->via instanceof self) {
                // via junction table
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
                $this->filterByModels($viaModels);
            } elseif (is_array($this->via)) {
                // via relation
                /* @var $viaQuery ActiveQuery */
                list($viaName, $viaQuery) = $this->via;
                if ($viaQuery->multiple) {
                    $viaModels = $viaQuery->all();
                    $this->primaryModel->populateRelation($viaName, $viaModels);
                } else {
                    $model = $viaQuery->one();
                    $this->primaryModel->populateRelation($viaName, $model);
                    $viaModels = $model === null ? [] : [$model];
                }
                $this->filterByModels($viaModels);
            } else {
                $this->filterByModels([$this->primaryModel]);
            }

            $query       = Query::create($this);
            $this->where = $where;
        }

        if (!empty($this->on)) {
            $query->andWhere($this->on);
        }

        return $query;
    }

    /**
     * @inheritdoc
     */
    public function populate($rows)
    {
        if (empty($rows)) {
            return [];
        }

        $models = $this->createModels($rows);
        if (!empty($this->join) && $this->indexBy === null) {
            $models = $this->removeDuplicatedModels($models);
        }
        if (!empty($this->with)) {
            $this->findWith($this->with, $models);
        }
        if (!$this->asArray) {
            foreach ($models as $model) {
                $model->afterFind();
            }
        }

        return $models;
    }

    /**
     * Removes duplicated models by checking their primary key values.
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
     * @param array $models the models to be checked
     * @return array the distinctive models
     */
    private function removeDuplicatedModels($models)
    {
        $hash = [];
        /* @var $class ActiveRecord */
        $class = $this->modelClass;
        $pks   = $class::primaryKey();

        if (count($pks) > 1) {
            foreach ($models as $i => $model) {
                $key = [];
                foreach ($pks as $pk) {
                    $key[] = $model[$pk];
                }
                $key = serialize($key);
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } else {
                    $hash[$key] = true;
                }
            }
        } else {
            $pk = reset($pks);
            foreach ($models as $i => $model) {
                $key = $model[$pk];
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } elseif ($key !== null) {
                    $hash[$key] = true;
                }
            }
        }

        return array_values($models);
    }

    /**
     * Executes query and returns a single row of result.
     * @param Connection $db the DB connection used to create the DB command.
     *                       If null, the DB connection returned by [[modelClass]] will be used.
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
     *                       the query result may be either an array or an ActiveRecord object. Null will be returned
     *                       if the query results in nothing.
     */
    public function one($db = null)
    {
        $row = parent::one($db);
        if ($row !== false) {
            $models = $this->populate([$row]);

            return reset($models) ?: null;
        } else {
            return null;
        }
    }

    /**
     * Creates a DB command that can be used to execute this query.
     * @param Connection $db the DB connection used to create the DB command.
     *                       If null, the DB connection returned by [[modelClass]] will be used.
     * @return Command the created DB command instance.
     */
    public function createCommand($db = null)
    {
        /* @var $modelClass ActiveRecord */
        $modelClass = $this->modelClass;
        if ($db === null) {
            $db = $modelClass::getDb();
        }

        if ($this->sql === null) {
            list ($sql, $params) = $db->getQueryBuilder()->build($this);
        } else {
            $sql    = $this->sql;
            $params = $this->params;
        }

        return $db->createCommand($sql, $params);
    }

    /**
     * Joins with the specified relations.
     *
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
     * Based on the definition of the specified relation(s), the method will append one or multiple
     * JOIN statements to the current query.
     *
     * If the `$eagerLoading` parameter is true, the method will also eager loading the specified relations,
     * which is equivalent to calling [[with()]] using the specified relations.
     *
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
     *
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
     *
     * @param string|array  $with         the relations to be joined. Each array element represents a single relation.
     *                                    The array keys are relation names, and the array values are the corresponding anonymous functions that
     *                                    can be used to modify the relation queries on-the-fly. If a relation query does not need modification,
     *                                    you may use the relation name as the array value. Sub-relations can also be specified (see [[with()]]).
     *                                    For example,
     *
     * ```php
     * // find all orders that contain books, and eager loading "books"
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
     * Order::find()->joinWith([
     *     'books' => function ($query) {
     *         $query->orderBy('item.name');
     *     }
     * ])->all();
     * ```
     *
     * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
     *                                    When this is a boolean, it applies to all relations specified in `$with`. Use an array
     *                                    to explicitly list which relations in `$with` need to be eagerly loaded.
     * @param string|array  $joinType     the join type of the relations specified in `$with`.
     *                                    When this is a string, it applies to all relations specified in `$with`. Use an array
     *                                    in the format of `relationName => joinType` to specify different join types for different relations.
     * @return static the query object itself
     */
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
    {
        $this->joinWith[] = [(array)$with, $eagerLoading, $joinType];

        return $this;
    }

    private function buildJoinWith()
    {
        $join       = $this->join;
        $this->join = [];

        foreach ($this->joinWith as $config) {
            list ($with, $eagerLoading, $joinType) = $config;
            $this->joinWithRelations(new $this->modelClass, $with, $joinType);

            if (is_array($eagerLoading)) {
                foreach ($with as $name => $callback) {
                    if (is_integer($name)) {
                        if (!in_array($callback, $eagerLoading, true)) {
                            unset($with[$name]);
                        }
                    } elseif (!in_array($name, $eagerLoading, true)) {
                        unset($with[$name]);
                    }
                }
            } elseif (!$eagerLoading) {
                $with = [];
            }

            $this->with($with);
        }

        // remove duplicated joins added by joinWithRelations that may be added
        // e.g. when joining a relation and a via relation at the same time
        $uniqueJoins = [];
        foreach ($this->join as $j) {
            $uniqueJoins[serialize($j)] = $j;
        }
        $this->join = array_values($uniqueJoins);

        if (!empty($join)) {
            // append explicit join to joinWith()
            // https://github.com/yiisoft/yii2/issues/2880
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
        }
    }

    /**
     * Inner joins with the specified relations.
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
     * Please refer to [[joinWith()]] for detailed usage of this method.
     * @param string|array  $with         the relations to be joined with
     * @param boolean|array $eagerLoading whether to eager loading the relations
     * @return static the query object itself
     * @see joinWith()
     */
    public function innerJoinWith($with, $eagerLoading = true)
    {
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
    }

    /**
     * Modifies the current query by adding join fragments based on the given relations.
     * @param ActiveRecord $model    the primary model
     * @param array        $with     the relations to be joined
     * @param string|array $joinType the join type
     */
    private function joinWithRelations($model, $with, $joinType)
    {
        $relations = [];

        foreach ($with as $name => $callback) {
            if (is_integer($name)) {
                $name     = $callback;
                $callback = null;
            }

            $primaryModel = $model;
            $parent       = $this;
            $prefix       = '';
            while (($pos = strpos($name, '.')) !== false) {
                $childName = substr($name, $pos + 1);
                $name      = substr($name, 0, $pos);
                $fullName  = $prefix === '' ? $name : "$prefix.$name";
                if (!isset($relations[$fullName])) {
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
                } else {
                    $relation = $relations[$fullName];
                }
                $primaryModel = new $relation->modelClass;
                $parent       = $relation;
                $prefix       = $fullName;
                $name         = $childName;
            }

            $fullName = $prefix === '' ? $name : "$prefix.$name";
            if (!isset($relations[$fullName])) {
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
                if ($callback !== null) {
                    call_user_func($callback, $relation);
                }
                if (!empty($relation->joinWith)) {
                    $relation->buildJoinWith();
                }
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
            }
        }
    }

    /**
     * Returns the join type based on the given join type parameter and the relation name.
     * @param string|array $joinType the given join type(s)
     * @param string       $name     relation name
     * @return string the real join type
     */
    private function getJoinType($joinType, $name)
    {
        if (is_array($joinType) && isset($joinType[$name])) {
            return $joinType[$name];
        } else {
            return is_string($joinType) ? $joinType : 'INNER JOIN';
        }
    }

    /**
     * Returns the table name and the table alias for [[modelClass]].
     * @param ActiveQuery $query
     * @return array the table name and the table alias.
     */
    private function getQueryTableName($query)
    {
        if (empty($query->from)) {
            /* @var $modelClass ActiveRecord */
            $modelClass = $query->modelClass;
            $tableName  = $modelClass::tableName();
        } else {
            $tableName = '';
            foreach ($query->from as $alias => $tableName) {
                if (is_string($alias)) {
                    return [$tableName, $alias];
                } else {
                    break;
                }
            }
        }

        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
            $alias = $matches[2];
        } else {
            $alias = $tableName;
        }

        return [$tableName, $alias];
    }

    /**
     * Joins a parent query with a child query.
     * The current query object will be modified accordingly.
     * @param ActiveQuery $parent
     * @param ActiveQuery $child
     * @param string      $joinType
     */
    private function joinWithRelation($parent, $child, $joinType)
    {
        $via        = $child->via;
        $child->via = null;
        if ($via instanceof ActiveQuery) {
            // via table
            $this->joinWithRelation($parent, $via, $joinType);
            $this->joinWithRelation($via, $child, $joinType);

            return;
        } elseif (is_array($via)) {
            // via relation
            $this->joinWithRelation($parent, $via[1], $joinType);
            $this->joinWithRelation($via[1], $child, $joinType);

            return;
        }

        list ($parentTable, $parentAlias) = $this->getQueryTableName($parent);
        list ($childTable, $childAlias) = $this->getQueryTableName($child);

        if (!empty($child->link)) {

            if (strpos($parentAlias, '{{') === false) {
                $parentAlias = '{{' . $parentAlias . '}}';
            }
            if (strpos($childAlias, '{{') === false) {
                $childAlias = '{{' . $childAlias . '}}';
            }

            $on = [];
            foreach ($child->link as $childColumn => $parentColumn) {
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
            }
            $on = implode(' AND ', $on);
            if (!empty($child->on)) {
                $on = ['and', $on, $child->on];
            }
        } else {
            $on = $child->on;
        }
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);

        if (!empty($child->where)) {
            $this->andWhere($child->where);
        }
        if (!empty($child->having)) {
            $this->andHaving($child->having);
        }
        if (!empty($child->orderBy)) {
            $this->addOrderBy($child->orderBy);
        }
        if (!empty($child->groupBy)) {
            $this->addGroupBy($child->groupBy);
        }
        if (!empty($child->params)) {
            $this->addParams($child->params);
        }
        if (!empty($child->join)) {
            foreach ($child->join as $join) {
                $this->join[] = $join;
            }
        }
        if (!empty($child->union)) {
            foreach ($child->union as $union) {
                $this->union[] = $union;
            }
        }
    }

    /**
     * Sets the ON condition for a relational query.
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
     * Otherwise, the condition will be used in the WHERE part of a query.
     *
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getActiveUsers()
     * {
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])->onCondition(['active' => true]);
     * }
     * ```
     *
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
     * @param array        $params    the parameters (name => value) to be bound to the query.
     * @return static the query object itself
     */
    public function onCondition($condition, $params = [])
    {
        $this->on = $condition;
        $this->addParams($params);

        return $this;
    }

    /**
     * Adds an additional ON condition to the existing one.
     * The new condition and the existing one will be joined using the 'AND' operator.
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
     *                                on how to specify this parameter.
     * @param array        $params    the parameters (name => value) to be bound to the query.
     * @return static the query object itself
     * @see onCondition()
     * @see orOnCondition()
     */
    public function andOnCondition($condition, $params = [])
    {
        if ($this->on === null) {
            $this->on = $condition;
        } else {
            $this->on = ['and', $this->on, $condition];
        }
        $this->addParams($params);

        return $this;
    }

    /**
     * Adds an additional ON condition to the existing one.
     * The new condition and the existing one will be joined using the 'OR' operator.
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
     *                                on how to specify this parameter.
     * @param array        $params    the parameters (name => value) to be bound to the query.
     * @return static the query object itself
     * @see onCondition()
     * @see andOnCondition()
     */
    public function orOnCondition($condition, $params = [])
    {
        if ($this->on === null) {
            $this->on = $condition;
        } else {
            $this->on = ['or', $this->on, $condition];
        }
        $this->addParams($params);

        return $this;
    }

    /**
     * Specifies the junction table for a relational query.
     *
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getItems()
     * {
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
     *                 ->viaTable('order_item', ['order_id' => 'id']);
     * }
     * ```
     *
     * @param string   $tableName the name of the junction table.
     * @param array    $link      the link between the junction table and the table associated with [[primaryModel]].
     *                            The keys of the array represent the columns in the junction table, and the values represent the columns
     *                            in the [[primaryModel]] table.
     * @param callable $callable  a PHP callback for customizing the relation associated with the junction table.
     *                            Its signature should be `function($query)`, where `$query` is the query to be customized.
     * @return static
     * @see via()
     */
    public function viaTable($tableName, $link, callable $callable = null)
    {
        $relation  = new ActiveQuery(get_class($this->primaryModel), [
            'from'     => [$tableName],
            'link'     => $link,
            'multiple' => true,
            'asArray'  => true,
        ]);
        $this->via = $relation;
        if ($callable !== null) {
            call_user_func($callable, $relation);
        }

        return $this;
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>CodePieceExtractor.SyntacticPositionedString</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.ctl

Class CodePieceExtractor.SyntacticPositionedString

java.lang.Object

org.jetel.ctl.CodePieceExtractor.PositionedString

org.jetel.ctl.CodePieceExtractor.SyntacticPositionedString

Enclosing class:

CodePieceExtractor

public static class CodePieceExtractor.SyntacticPositionedString
extends CodePieceExtractor.PositionedString

Enhanced PositionedString that can use SyntacticPosition to index the input string.

Field Summary

Fields inherited from class org.jetel.ctl.CodePieceExtractor.PositionedString

input, lineStartPositions

Constructor Summary

Constructors

Constructor and Description

CodePieceExtractor.SyntacticPositionedString(java.lang.String input,
                                            int[] lineStartPositions)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getCodePiece(SyntacticPosition start,
            SyntacticPosition end)

java.lang.String
getExpression(SimpleNode node)

Methods inherited from class org.jetel.ctl.CodePieceExtractor.PositionedString

getCodePiece, getIndex, getLineStartPositions

Methods inherited from class java.lang.Object

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

Constructor Detail

CodePieceExtractor.SyntacticPositionedString

public CodePieceExtractor.SyntacticPositionedString(java.lang.String input,
                                            int[] lineStartPositions)

Method Detail

getCodePiece

public java.lang.String getCodePiece(SyntacticPosition start,
                            SyntacticPosition end)

getExpression

public java.lang.String getExpression(SimpleNode node)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
var points = 0;
function validate(input) {
	getAnswer();
	// console.log("Input: " + $(input).val() + " =?= " + theAnswer + " is " + ($(input).val() == theAnswer));
	if ($(input).val() == theAnswer) {
	// if ($(input).val() == "") {
		$('.button--accept[data-stack = stack_buana]').click();
		points += 100;
	}

	else {
		$('.button--reject[data-stack = stack_buana]').click();
		points -= 10;
	}

	if (!isGameOver()) resetTime();
	$(input).val("");
	$(input).focus();
	$('.score').text(points + " PTS");
	if (points < 0) {
		$('.score').addClass("negativeRed");
	}

	else {
		$('.score').removeClass("negativeRed");
	}

	var visibleCount = 0;
	$('.stack__item').each(function(i, obj) {
		if ($(this).css('opacity') != 0) {
			visibleCount++;
		}
	});

	if (visibleCount == 1) {
		gameOver();
		stopTime();
	}
}

var isOver = false;
function gameOver() {
	stopTime();
	isOver = true;

	if (points < 100) {
		swal({
			title: "Juego Terminado",
			text: "Muy mal. Necesita estudiar. Tus puntos: " + points,
			html: true,
			type: "error",
			confirmButtonText: "aprender",
			closeOnConfirm: true
		},
		function(){
			setTimeout(function(){
				$('.play').addClass('display-none');
				$('.learn').removeClass('visible-none');
		    }, 175);

			$('.play').addClass('visible-none');
			$('.learn').removeClass('display-none');
		});
	}

	else if (points < 500) {
		swal({
			title: "Juego Terminado",
			text: "Bien. Tus puntos:  " + points,
			html: true,
			confirmButtonText: "estudiar",
			closeOnConfirm: true
		},
		function(){
			setTimeout(function(){
				$('.play').addClass('display-none');
				$('.learn').removeClass('visible-none');
		    }, 175);

			$('.play').addClass('visible-none');
			$('.learn').removeClass('display-none');
		});
	}

	else {
		swal({
			title: "Juego Terminado",
			text: "MUY BIEN. Tus puntos:  " + points,
			html: true,
			type: "success",
			confirmButtonText: "felicidades",
			closeOnConfirm: true
		},
		function(){
			setTimeout(function(){
				$('.play').addClass('display-none');
				$('.learn').removeClass('visible-none');
		    }, 175);

			$('.play').addClass('visible-none');
			$('.learn').removeClass('display-none');
		});
	}
}

function isGameOver() {
	return isOver;
}


text:
import _ = require('lodash');
import useragent = require('express-useragent');

export interface Platforms {
  LINUX: String;
  LINUX_32: string;
  LINUX_64: string;
  OSX: string;
  OSX_32: string;
  OSX_64: string;
  WINDOWS: string;
  WINDOWS_32: string;
  WINDOWS_64: string;
  toType?: (platform: string) => string;
  detectFromRequest?: (req) => string[];
  detect?: (platformName, strictMatch) => string[];
  sanitize?: (platforms) => any[];
}
var Platforms: Platforms = {
  LINUX: 'linux',
  LINUX_32: 'linux_32',
  LINUX_64: 'linux_64',
  OSX: 'osx',
  OSX_32: 'osx_32',
  OSX_64: 'osx_64',
  WINDOWS: 'windows',
  WINDOWS_32: 'windows_32',
  WINDOWS_64: 'windows_64',
};

/**
 * Reduce a platfrom ID to its type
 * (ex. windows_64 to windows)
 * @param  {String} platform Platform ID
 * @return {String}          Platform type name
 */
Platforms.toType = function (platform) {
  return _.head(platform.split('_'));
};

/**
 * Detect the user's platform from a request object
 * @param  {Object} req An express request object
 * @return {String}     String representation of the detected platform
 */
Platforms.detectFromRequest = function (req) {
  // var platform;

  var source = req.headers['user-agent'];
  var ua = useragent.parse(source);

  if (ua.isWindows) return [this.WINDOWS_32, this.WINDOWS_64];
  if (ua.isMac) return [this.OSX_64];
  if (ua.isLinux64) return [this.LINUX_64, this.LINUX_32];
  if (ua.isLinux) return [this.LINUX_32];
};

/**
 * Detect and normalize the platformID from platform name input string.
 * Used to handle unnormalized inputs from user agents.
 * @param  {Object}  platformName An Asset object
 * @param  {Boolean} strictMatch  Whether to only match to the current arch
 *                                If false, 32 bit will be added for 64 bit
 * @return {String}               Full platform ID
 */
Platforms.detect = function (platformName, strictMatch) {
  var name = platformName.toLowerCase();
  var prefix = '';
  var suffixes = [];

  // Detect prefix: osx, widnows or linux
  if (_.includes(name, 'win')) {
    prefix = this.WINDOWS;
  }

  if (
    _.includes(name, 'linux') ||
    _.includes(name, 'ubuntu')
  ) {
    prefix = this.LINUX;
  }

  if (
    _.includes(name, 'mac') ||
    _.includes(name, 'osx') ||
    name.indexOf('darwin') >= 0
  ) {
    prefix = this.OSX;
  }

  // Detect architecture
  if (
    prefix === this.OSX ||
    // _.includes(name, 'x64') ||
    // _.includes(name, 'amd64') ||
    _.includes(name, '64')
  ) {
    suffixes.push('64');

    if (!strictMatch && prefix !== this.OSX) {
      suffixes.unshift('32');
    }
  } else {
    suffixes.unshift('32');
  }

  var result = [];
  _.forEach(suffixes, function (suffix) {
    result.push(prefix + '_' + suffix);
  });

  return result;
};

Platforms.sanitize = function (platforms) {
  var self = this;
  return _.map(platforms, function (platform) {
    switch (platform) {
      case self.OSX:
      case self.OSX_32:
        platform = self.OSX_64;
        break;
      default:
    }

    return platform;
  });
}

export default Platforms;


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/main_layout_ll"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.jiahaoliuliu.deeplinkingwithandroid.DetailsActivity"
    android:layout_gravity="center"
    android:gravity="center"
    android:background="@color/background_details_activity_from_main_activity"
    >

    <TextView
        android:id="@+id/source_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/white"
        />

</LinearLayout>


text:
/*
 *  The code in this repo is not supported by Red Hat/3scale.
 *  Rather it's example code of how to use the supported 3scale
 *  Java Plugin to achieve very low latency API Management.
/*
/*
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.threescale.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import java.util.Map;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import threescale.v3.api.AuthorizeResponse;
import threescale.v3.api.ServerError;
import threescale.v3.api.ServiceApi;

public class PluginServiceTest{
    private final String SUCCESSFUL_RESP = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><status><authorized>true</authorized><plan>Application Plan</plan></status>";
    private final String FAILED_RESP = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><status code=\"409\"><authorized>false</authorized><reason>usage limits are exceeded</reason><plan>Application Plan</plan></status>";

    private PluginServiceImpl pluginServiceUnderTest;
    private ServiceApi mockServiceApi;
    private Properties mockProps;
    private Map <String, Boolean> mockAuthorizations;

    @Before
    public void before() throws Exception {

        mockServiceApi = Mockito.mock(ServiceApi.class);
        mockProps = new Properties();
        mockAuthorizations = Mockito.mock(Map.class);

        pluginServiceUnderTest = new PluginServiceImpl();
        pluginServiceUnderTest.setAuthorizations(mockAuthorizations);
        pluginServiceUnderTest.setProps(mockProps);
        pluginServiceUnderTest.setServiceApi(mockServiceApi);
    }

    @Test (expected = ServerError.class)
    public void testServerErrorNoServiceId() throws ServerError  {
    	pluginServiceUnderTest.setServiceId(null);
        pluginServiceUnderTest.authRep("userKey", "method");
    }

    @Test (expected = ServerError.class)
    public void testServerErrorNoServiceToken() throws ServerError  {
    	pluginServiceUnderTest.setServiceToken(null);
        pluginServiceUnderTest.authRep("userKey", "method");
    }

    @Test
    public void testSuccessfulAuthEmptyCache() throws ServerError  {
    	mockProps.setProperty("method-token", "servicetoken");
    	mockProps.setProperty("method-serviceid", "serviceId");

        AuthorizeResponse successfulResponse = new AuthorizeResponse(200, SUCCESSFUL_RESP);
        when(mockServiceApi.authrep(any(), any(), any())).thenReturn(successfulResponse);

        AuthorizeResponse response = pluginServiceUnderTest.authRep("userKey", "method");
        //A non-null response  is what we expect from a synchronous call - made when <key>+<method or metric> not found in the cache
        assertNotNull(response);
        assertEquals(response.success(), true);
    }

    @Test
    public void testFailedAuthEmptyCache() throws ServerError  {
    	mockProps.setProperty("token", "servicetoken");
    	mockProps.setProperty("serviceid", "serviceId");

        AuthorizeResponse failResponse = new AuthorizeResponse(403, FAILED_RESP);
        when(mockServiceApi.authrep(any(), any(), any())).thenReturn(failResponse);

        AuthorizeResponse response = pluginServiceUnderTest.authRep("userKey", "method");
        //A non-null response  is what we expect from a synchronous call - made when <key>+<method or metric> not found in the cache
        assertNotNull(response);
        assertEquals(response.success(), false);
    }

    @Test
    public void testValueInCacheAsynchAuth() throws ServerError  {
    	mockProps.setProperty("token", "servicetoken");
    	mockProps.setProperty("serviceid", "serviceId");

    	when(mockAuthorizations.get("userKeymethod")).thenReturn(true);

        AuthorizeResponse response = pluginServiceUnderTest.authRep("userKey", "method");
        //A null response  is what we expect from an asynchronous call - made when <key>+<method or metric> is found in the cache.
        //Return null as we don't wait for the response
        assertNull(response);
     }

}


text:
package ca.cmput301f13t03.adventure_datetime.view;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.content.Context;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import ca.cmput301f13t03.adventure_datetime.R;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ILocalStoriesListener;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.IOnlineStoriesListener;
import ca.cmput301f13t03.adventure_datetime.model.Story;
import ca.cmput301f13t03.adventure_datetime.serviceLocator.Locator;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;

/**
 *
 * Contains three fragments/tabs where user can see list of cached stories,
 * authored stories, and online stories.
 *
 * @author James Finlay
 *
 */
public class BrowseView extends FragmentActivity implements ILocalStoriesListener,
											IOnlineStoriesListener {
	private static final String TAG = "BrowseView";

	private ViewPager _viewPager;
	private ViewPagerAdapter _adapter;
	private LinearLayout _searchBar;

	@Override
	public void OnLocalStoriesChange(Map<UUID, Story> newStories) {
		_adapter.setLocalStories(Locator.getAuthorController().checkIfNotAuthored(newStories.values()));
		_adapter.setAuthorStories(Locator.getAuthorController().checkIfAuthored(newStories.values()));
	}
	@Override
	public void OnOnlineStoriesChange(Map<UUID, Story> newStories) {
		Log.v(TAG, "online stories");
		_adapter.setOnlineStories(newStories.values());
	}

	// TODO::JF Listen for Server stories

	@Override
	public void onResume() {
		Locator.getPresenter().Subscribe((ILocalStoriesListener)this);
		Locator.getPresenter().Subscribe((IOnlineStoriesListener)this);
		super.onResume();
	}
	@Override
	public void onPause() {
		Locator.getPresenter().Unsubscribe((ILocalStoriesListener)this);
		Locator.getPresenter().Unsubscribe((IOnlineStoriesListener)this);
		super.onPause();
	}
	@Override
	public void onSaveInstanceState(Bundle outState) {}

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

		/* Search bar */
		final Button btnSearch = (Button) findViewById(R.id.search);
		final EditText txtSearch = (EditText) findViewById(R.id.content);
		_searchBar = (LinearLayout) findViewById(R.id.header);
		_searchBar.setVisibility(View.GONE);
		txtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					Locator.getUserController().search(txtSearch.getText().toString());
					txtSearch.setText("");
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
					_searchBar.setVisibility(View.GONE);
				}
				return false;
			}
		});
		btnSearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Locator.getUserController().search(txtSearch.getText().toString());
				txtSearch.setText("");
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
				_searchBar.setVisibility(View.GONE);
			}
		});

		/* Set up View Pager */
		_adapter = new ViewPagerAdapter(getSupportFragmentManager());
		_viewPager = (ViewPager) findViewById(R.id.pager);
		_viewPager.setAdapter(_adapter);

		/* Set up Tabs */
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		ActionBar.TabListener tabListener = new ActionBar.TabListener() {
			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {}

			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				_viewPager.setCurrentItem(tab.getPosition());
			}
			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
		};

		actionBar.addTab(actionBar.newTab()
				.setText("Saved")
				.setTabListener(tabListener));
		actionBar.addTab(actionBar.newTab()
				.setText("My Stories")
				.setTabListener(tabListener));
		actionBar.addTab(actionBar.newTab()
				.setText("Online")
				.setTabListener(tabListener));

		/* Change tabs when View Pager swiped */
		_viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				getActionBar().setSelectedNavigationItem(position);
				if (position != 2)
					_searchBar.setVisibility(View.GONE);
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			getActionBar().setSelectedNavigationItem(2);
			_searchBar.setVisibility(View.VISIBLE);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public class ViewPagerAdapter extends FragmentPagerAdapter {

		private BrowseFragment cached, authored, online;

		public ViewPagerAdapter(FragmentManager fm) {
			super(fm);

			cached = new BrowseFragment();
			authored = new BrowseFragment();
			online = new BrowseFragment();
		}

		public void setLocalStories(Collection<Story> stories) {
			cached.setStories(stories, BrowseFragment.SOURCE_CACHE);
		}
		public void setAuthorStories(Collection<Story> stories) {
			authored.setStories(stories, BrowseFragment.SOURCE_AUTHOR);
		}
		public void setOnlineStories(Collection<Story> stories) {
			online.setStories(stories, BrowseFragment.SOURCE_ONLINE);
		}

		@Override
		public Fragment getItem(int i) {
			switch(i) {
			case 0: return cached;
			case 1: return authored;
			case 2: return online;
			default: return null;
			}
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0: return "Saved";
			case 1: return "My Stories";
			case 2: return "Online";
			default: return "It be a Pirate!";
			}
		}
	}

}


text:
package de.uni_potsdam.hpi.bpt.bp2014.jcore;

public class ParallelGatewaySplitBehavior extends ParallelOutgoingBehavior {
    GatewayInstance gatewayInstance;

    /**
     * Initializes the ParallelGatewaySplitBehavior.
     *
     * @param gateway_id          This is the database id from the gateway.
     * @param scenarioInstance    This is an instance from the class ScenarioInstance.
     * @param fragmentInstance_id This is the database id from the fragment instance.
     * @param gatewayInstance     This is an instance from the class GatewayInstance.
     */
    ParallelGatewaySplitBehavior(int gateway_id, ScenarioInstance scenarioInstance, int fragmentInstance_id, GatewayInstance gatewayInstance) {
        this.controlNode_id = gateway_id;
        this.scenarioInstance = scenarioInstance;
        this.fragmentInstance_id = fragmentInstance_id;
        this.gatewayInstance = gatewayInstance;
    }

    @Override
    public void terminate() {
        this.checkAfterTermination();
        this.enableFollowing();
        this.runAfterTermination();
    }

    @Override
    protected ControlNodeInstance createFollowingNodeInstance(int controlNode_id) {
        for (ControlNodeInstance controlNodeInstance : scenarioInstance.getControlNodeInstances()) {
            if (controlNode_id == controlNodeInstance.controlNode_id && !controlNodeInstance.getClass().equals(ActivityInstance.class) && !controlNodeInstance.getStateMachine().state.equals("terminated")) {
                return controlNodeInstance;
            }
        }
        String type = dbControlNode.getType(controlNode_id);
        ControlNodeInstance controlNodeInstance = createControlNode(type, controlNode_id);
        this.setAutomaticExecutionToFalse(type, controlNodeInstance);
        return controlNodeInstance;
    }

    /**
     * @param type
     * @param controlNodeInstance
     */
    private void setAutomaticExecutionToFalse(String type, ControlNodeInstance controlNodeInstance) {
        switch (type) {
            case "Activity":
            case "EmailTask":
            case "WebServiceTask":
                if (!gatewayInstance.isAutomaticExecution()) {
                    ((ActivityInstance) controlNodeInstance).setAutomaticExecution(false);
                }
                break;
            case "AND":
                if (!gatewayInstance.isAutomaticExecution()) {
                    ((GatewayInstance) controlNodeInstance).setAutomaticExecution(false);
                }
                break;
        }
    }
}


text:
A set of [Pushpop](https://github.com/pushpop-project/pushpop) jobs that collect data from various APIs over time and push data into [Keen IO](https://keen.io).

There are 2 ways to use this project:

+ Use the Keen IO Project ID and Read Key specified in each collector's documentation to use the data.
+ Capture the data yourself by cloning and deploying this repository pointing to your own project ID.

Note: Install [keen-cli](https://github.com/keenlabs/keen-cli) to run example CLI queries.

### Collectors

##### Bitcoin Prices

Uses the [BitcoinAverage](https://api.bitcoinaverage.com) API to capture Bitcoin
price trends over time.

+ Code – [jobs/bitcoin_prices.rb](jobs/bitcoin_prices_job.rb)
+ Interval - Every minute
+ Contact Info - [@dzello](https://twitter.com/dzello)
+ Runs On – Heroku
+ Example Event - [Extract One](https://api.keen.io/3.0/projects/53f3a8687d8cb95095000001/queries/extraction?latest=1&event_collection=bitcoin-prices&api_key=99a06e48fd7fb1279bc40995160eb0b61a9e0efaab8b651b029f0d895f77c0a804ba089282eff28bf8ad07f337422441d0542b7feaac9fea1e92fc153ee7efc51afad3276bda8d7754a338b349d540bfb402cba0dfdc82498c217054efd8abd0f47a0c0bc963bbdf0dc938c91b17d9f2)
+ Keen IO Data Set Information
  + Project ID: `53f3a8687d8cb95095000001`
  + Read Key: `99a06e48fd7fb1279bc40995160eb0b61a9e0efaab8b651b029f0d895f77c0a804ba089282eff28bf8ad07f337422441d0542b7feaac9fea1e92fc153ee7efc51afad3276bda8d7754a338b349d540bfb402cba0dfdc82498c217054efd8abd0f47a0c0bc963bbdf0dc938c91b17d9f2`
  + Collection Name: `bitcoin-prices`

**Example CLI Queries**

Note: Make sure to set environment variables in `.env` or specify `--project` and `--read-key` parameters.

```
# price last 30 minutes piped to spark
$ keen average -c bitcoin-prices -y "USD.averages.last" -t last_30_minutes -i minutely --spark | spark
▄███▄▄▄▄▄▁▄▄▄▄▄▄▄▁▁▁▄▄▄▄██▄

# highest USD price today
$ keen maximum -c bitcoin-prices -y "USD.averages.last"
481.77

# total USD volume last 24 hours
$ keen extraction -c bitcoin-prices --property-names "USD.averages.total_vol" --latest 1
[
  {
    "USD": {
      "averages": {
        "total_vol": 38276.39
      }
    }
  }
]
```

### Contributing

More jobs! More open data sets!

If you add a job please fill out all the details (use Bitcoin Prices as a guide).
Keen IO project and credentials are not required if you expect someone to capture
the data on their own and not use a shared project.


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testsuites>
    <testsuite tests="3" failures="1" errors="1" time="0.23" name="All Tests">
        <testsuite tests="2" failures="1" errors="1" time="0.18" name="UnitTests.xctest">
            <testcase classname="CalculatorTest" name="testMultiplication" time="0.06"></testcase>
            <testcase classname="CalculatorTest" name="testDivision" time="0.12">
                <failure type="Failure" message="division by zero">CalculatorTest.m:42</failure>
            </testcase>
        </testsuite>
        <testsuite tests="1" failures="0" errors="0" time="0.05" name="UITests.xctest">
            <testcase classname="CalculatorInterfaceTest" name="testInteraction" time="0.05"></testcase>
        </testsuite>
    </testsuite>
</testsuites>


text:
require('./polyfill');

var debug = require('debug')('medicar');
var path = require('path');
var nconf = require('nconf');
var osv2Authenticate = require('./osv2Authenticate');

// all access to nconf should be through this exported variable
module.exports.nconf = nconf;

// args and environment always win
nconf.argv()
    .env();

// if cloud foundry initialization then host, port and default data directory for the file system storage are adjusted
if (runningInCloudFoundry()) {
    var cfenv = require('cfenv');
    // get the app environment from Cloud Foundry
    var appEnv = cfenv.getAppEnv();
    console.log(appEnv);
    nconf.defaults({
        'CAR_HOSTNAME': appEnv.bind,
        'CAR_PORT': appEnv.port,
        'CAR_FILE_DATADIR': './data'
    });
}

nconf.file('./config/app.json');

// the file holds VCAP_SERVICES conveniently in object format when copy/pasted from the bluemix credential GUI
// but in the environment (which is typical) it is a string that needs to be parsed
var VCAP_SERVICES = nconf.get('VCAP_SERVICES');
if (typeof(VCAP_SERVICES) === 'string') {
    VCAP_SERVICES = JSON.parse(VCAP_SERVICES);
}

module.exports.findVcapMemberOfServiceByNameOrExit = findVcapMemberOfServiceByNameOrExit;
module.exports.findVcapMemberOfServiceByName = findVcapMemberOfServiceByName;
function findVcapMemberOfServiceByNameOrExit(nconfServiceName) {
    var ret = findVcapMemberOfServiceByName(nconfServiceName);
    if (!ret) {
        console.error('exit 1');
        process.exit(1);
    }
    return ret;
}

// VCAP_SERVICES have one object per service and then an array of members.
// return the member that matches the nconf service configuration.
// log an error and return false if there is a problem with the service
function findVcapMemberOfServiceByName(nconfServiceName) {
    var nconfService = nconf.get(nconfServiceName);
    if (!nconfService) {
        console.error('Not a configured bluemix service: ' + nconfServiceName);
        return false;
    }
    var service = VCAP_SERVICES[nconfService.serviceName];
    if (!service) {
        console.error('The service name: ' + nconfServiceName + ' indicates that the following non existent service should be in VCAP_SERVICES: ' + nconfService.serviceName);
        return false;
    }

    var ret = service.find(function (element) {
        return element.name === nconfService.memberName;
    });
    if (!ret) {
        console.error('The service name: ' + nconfServiceName + '  identifies an existing service : ' + nconfService.serviceName + '  which is missing the named member: ' + nconfService.memberName);
        return false;
    }
    return ret;
}

// Identify the Object Storage v2 service.
var vcapOsv2 = findVcapMemberOfServiceByNameOrExit('serviceOsv2');  // use this mechanism
var osv2ServiceCredentials = nconf.get('osv2ServiceCredentials');   // not required and can be undefined, kept for testing
if (typeof(osv2ServiceCredentials) === 'string') {
    osv2ServiceCredentials = JSON.parse(osv2ServiceCredentials);
}
module.exports.osv2Authenticate = osv2Authenticate(osv2ServiceCredentials, vcapOsv2);

module.exports.container = nconf.get('CAR_OSV2_PUBLIC_CONTAINER_NAME');
debug('container: ' + module.exports.container);

module.exports.containerDestroy = (nconf.get('CAR_OSV2_PUBLIC_CONTAINER_DESTROY').toLowerCase() === 'true');
debug('config.containerDestroy: ' + module.exports.containerDestroy);

// file system configuration
module.exports.dataDir = nconf.get('CAR_FILE_DATADIR').replace(/\//g, path.sep);    // use linux style and replace with the windows path separator
debug('data directory: ' + module.exports.dataDir);

module.exports.tmp = 'tmp';
module.exports.HOSTNAME = 'HOSTNAME';
module.exports.group_id = 'group_id';

// on premise conifguration.  These strings are similar to those that will be used in production:
// curl cap-sg-prd-2.integration.ibmcloud.com:15188
module.exports.onpremHost = nconf.get('CAR_SG').onpremHost;
module.exports.onpremPort = nconf.get('CAR_SG').onpremPort;

/**
 *
 * @returns {boolean} true if running in cloud foundry
 */
function runningInCloudFoundry() {
    return !!process.env['CF_INSTANCE_IP'];

}


text:
This text for the "contributing"-section is overridden in the `example-plugin`.
The default text is replaced.

And THIS IS A DEMONSTRATION OF THE SHOUT-HELPER THAT IS INCLUDED IN THE PLUGIN


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IWriter.js.map


text:
import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { configureStore } from '../stores/configureStore';
import { initialStore } from '../stores/stores';

import IndexWrapper from '../container/index';
import CommentWrapper from '../container/comment';
import DetailWrapper from '../container/detail';

import App from '../container/app';

import { routeConfig } from './route_server';

import { syncHistoryWithStore } from 'react-router-redux';
import { Router, IndexRoute, Route, browserHistory, useRouterHistory, hashHistory, match } from 'react-router';
import { createHashHistory } from 'history';

var globalVar = (isNode) ? global : window;

let store = configureStore(globalVar.__REDUX_STATE__ || {});

let  history = syncHistoryWithStore(browserHistory, store);

const { pathname, search, hash } = window.location;
const location = `${pathname}${search}${hash}`;

export default class Root extends Component {

    constructor(props, context) {
        super(props, context);
    }

    render() {
        return (
            <Provider store={store}>

                    <Router history={history}>
                        <Route path="/spa.html" component={App}>
                            <IndexRoute component={IndexWrapper}/>
                            <Route path="/spa.html/comment/:id" component={CommentWrapper}/>
                            <Route path="/spa.html/detail/:id/:commentid" component={DetailWrapper}/>
                        </Route>
                    </Router>

            </Provider>
        );
    }
}

match({ routes: routeConfig, location: location }, () => {
    render(
        <Provider store={store}>

                <Router routes={routeConfig} history={history} />

        </Provider>,
        document.getElementById('pages')
    )
});

// render(
//     <Root />,
//     document.getElementById('pages')
// );