text:
title: Building a multilanguage Jekyll blog
date: 2013-04-07
layout: post
draft: false
path: /en/2013/04/building-a-multinlingual-jekyll-blog/
category: Web development
tags:
  - blog
  - jekyll
  - i18n
description: As a first post, what about sharing the way I managed to build this blog? Having a both english and french Jekyll website is not that hard, but you have to care about some crucial points.
---

## Note on compatibility

What follows consider the use of Jekyll `v0.12.1`.

Looking for Jekyll `v1.5`? Go have a look [to the one of April 2014](/en/2014/04/multilingual-blog-with-jekyll-1-5/).

Please note that some major changes happened in Jekyll `v1.0.0` which made some of the following tricks not working anymore (I'm thinking about plugins). I'll write a new post when upgrade my own Jekyll to v1.0+.

If you wish, you can still install the old Jekyll version with the following command:

```bash
# Install the old version of jekyll
$ sudo gem install jekyll --version 0.12.1

# Uninstall your current version if you dowloaded it
$ sudo gem uninstall jekyll --version <your current version>
```

## Why Jekyll?

I won't write a n-th post about the reason of choosing Jekyll as the static site generator for my blog. There are already [plenty of them](https://www.google.fr/search?q=moving+blog+to+jekyll).

I'll just sum it up with the following bullet-points :

* **I don't need to deal with a database**. I just want to Keep It Simple (Stupid) and front-end will just do it well.
* **I want to have my website updated when I push it to Github**. I could have done some hook to deal with that but I don't have to, thanks to [Github Pages](https://help.github.com/categories/20/articles).
* **I love keeping myself up-to-date with new trends**. And the Jekyll approach just sounds good to me.

I could recommend you [the post from Harry Roberts](http://csswizardry.com/2012/12/a-new-css-wizardry/) and [the one from Hugo Giraudel](http://hugogiraudel.com/2013/02/21/jekyll) which comforted me in my choice.

## What about multilingual?

The thing is, Jekyll is not actually build to support multinlingual blogs. The [Liquid `date` filter](http://liquid.rubyforge.org/classes/Liquid/StandardFilters.html#M000012) will display the english version of the date.
Futhermore, if you want to distinguish posts by their language, then you have to create a category per language. But the Jekyll `.paginator` is not build to deal with categories, which is kind of a problem.

Nevertheless, I wanted to create my blog both in French and English for few reasons :

1. **Most of the nicest websites treating about front-end development are in English**, which is fine but I would like to see few of them written in my native language for other French developers who may not be fluent in English (even if they should be).
2. **I'm French and proud to be**. Although I love English, there's no reason for me not to write some posts in my native language too.
3. **This is a challenge** and I love challenges… as every developer does, right?

So here's the strategy:

* English is the default language, at the root level.
* Each language represents a category, which could be done thanks to the folders architecture.
* The French part should be under the `/fr` base url, which is fine with the previous statements.
* English posts should only display into `/index.html`, - French posts should only display into `/fr/index.html` (and the pagination should be done accordingly).
* It should Keep It Simple (Stupid).

Let's build the architecture for the source files:

```
.
|-- _includes/      # Partials included in other files
|-- _layouts/       # Templates of the website
|-- _plugins/       # Plugins to override Jekyll workflow
|-- assets/         # LESS/CSS, JS, images, …
|-- fr/             # French category
|   |-- _posts/     # French posts
|   |-- index.html  # French html files
|   |-- about.html
|   |-- (…)
|
|-- en/             # English category
|   |-- _posts/     # English posts
|
|-- index.html      # Default html files (EN)
|-- about.html
|-- (…)
|-- _config.yml     # Jekyll configuration file
```

When launched, Jekyll generates the static final website into the `_site/` folder.

I use the `_config.yml` file to put some locale variables I could use in the main templates.

This is definitely **not the cleanest solution** in my humble opinion, but it's quite easy to deal with and it works fine for the moment. It may change in the future in a smarter way to handle this.

## Plugins on the road

In order to solve the mentioned problems, I used 2 plugins to override the regular Jekyll workflow.

#### 1. Pagination per category

[category_pagination.rb](https://github.com/nicoespeon/nicoespeon.github.io/blob/develop/_plugins/category_pagination.rb) has the paginator only considers posts of the current category in order to distinguish the two languages.

I modified the original plugin to have the default category, at root level, set as the _English_ one instead of displaying all of the `site.posts`.

#### 2. i18n Filter

[i18n_filter.rb](https://github.com/nicoespeon/nicoespeon.github.io/blob/develop/_plugins/i18n_filter.rb) customizes the `page.date` treatment accordingly to the locale.

I've had to add the [\_locales/fr.yml](https://github.com/nicoespeon/nicoespeon.github.io/blob/develop/_locales/fr.yml) file to create the `localize` function. It performs just as the `date` does, but it displays the French format for the date.

## The Github thing

Plugins are set up, templates are built, design has been completed, the git workflow is ready and so is the remote repository on Github. _Let's push!_

[The DNS redirection for my custom domain](https://help.github.com/articles/setting-up-a-custom-domain-with-pages) just works fine but… wait. It doesn't play as expected.
Damn it! I just notice that Github is running Jekyll in `--safe` mode, which means that plugins are disabled. And so are my category pagination and my i18n filter.

**For every problem, a solution**, with Google being your best friend. [I found inspiration](http://charliepark.org/jekyll-with-plugins/) to redesign my personal workflow in that way.

_Let's have a look to my branching model._

The `master` branch correspond to the compiled website (the one generated into `_site/` directory) so that Github can deliver it directly as a static website, thanks to the `.nojekyll` file.
The `develop` branch correspond to the source files, as I would like to keep them tracked and open-sourced. They would be compiled with Jekyll in order to proceed to deployment.
There's no more merge from `develop` into `master` as there's only deployments from now. I just work on `develop` and, when I'm ready, I deploy the whole site with a new commit on `master`.

Of course I already pushed the first commits when I realized I was wrong. But instead of recreating the whole repo and rebase my git history, I decided to deal with it with just few commits to correct the situation. There's no shame in doing mistakes after all.

I just created a [Makefile](https://github.com/nicoespeon/nicoespeon.github.io/blob/develop/Makefile) in order to do all that stuff with a `make deploy` command. And voilà!

## And here we go

Here we are, it just works perfectly and I'm now ready to go with a both English and French, Jekyll-flavored, Github-hosted blog _\o/_

There is still enhancements I should take care of -such as deploying a Google Analytics and a comments system- but I'm satisfied with the result. The challenge is taken up and the journey has begun. **Let's transform these posts into a monster.**


text:
package com.leroymerlin.pandroid.log;

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

public class PandroidLogger implements LogWrapper {

    protected boolean debuggable = false;
    protected int logLevel = VERBOSE;

    private static PandroidLogger logger;

    public List<LogWrapper> loggers = new ArrayList<>();

    protected PandroidLogger() {
    }

    public static LogWrapper getInstance() {
        if (logger == null)
            logger = new PandroidLogger();
        return logger;
    }

    @Override
    public void addLogger(LogWrapper logWrapper) {
        loggers.add(logWrapper);
        logWrapper.setDebug(debuggable);
        logWrapper.setLogLevel(logLevel);
    }

    @Override
    public void removeLogger(LogWrapper logWrapper) {
        loggers.remove(logWrapper);
    }

    @Override
    public void setLogLevel(int level) {
        logLevel = level;
        for (LogWrapper logger : loggers) {
            logger.setLogLevel(level);
        }
    }

    @Override
    public void setDebug(boolean isDebug) {
        debuggable = isDebug;
        for (LogWrapper logger : loggers) {
            logger.setDebug(isDebug);
        }
    }

    public void v(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.v(tag, msg);
        }
    }

    public void v(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.v(tag, msg, tr);
        }
    }

    public void d(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.d(tag, msg);
        }
    }

    public void d(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.d(tag, msg, tr);
        }
    }

    public void i(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.i(tag, msg);
        }
    }

    public void i(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.i(tag, msg, tr);
        }
    }

    public void w(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.w(tag, msg);
        }
    }

    public void w(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.w(tag, msg, tr);
        }
    }

    public void w(String tag, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.w(tag, tr);
        }
    }

    public void e(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.e(tag, msg);
        }
    }

    public void e(String tag, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.e(tag, tr);
        }
    }

    public void e(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.e(tag, msg, tr);
        }
    }

    public void wtf(String tag, String msg) {
        for (LogWrapper logger : loggers) {
            logger.wtf(tag, msg);
        }
    }

    public void wtf(String tag, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.wtf(tag, tr);
        }

    }

    public void wtf(String tag, String msg, Throwable tr) {
        for (LogWrapper logger : loggers) {
            logger.wtf(tag, msg, tr);
        }
    }

    @Override
    public void addKey(String key, String value) {
        for (LogWrapper logger : loggers) {
            logger.addKey(key, value);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
importScripts("../require.js");

require.config( {

	paths: {
		"config": "../config"
	}

} );

require( [
	"require",
	"config",
	"systems/spring",
	"systems/gravity",
	"solvers/euler",
	"solvers/rk4merged",
	"steppers/boundary"
], function(require, config) {

	// Clones an object (without functions) effectively
	function cloneObj(obj) {
		return JSON.parse(JSON.stringify(obj));
	}

	// returns an object with id relative to base
	// e.g. with id = "foo.bar", returns base.foo.bar
	function getObj(base, id) {
		return id.length > 1 ? getObj(base[id.shift()], id) : base[id[0]];
	}

	// sets object with id relative to base with value
	// see getObj(base, id)
	function setObj(base, id, val) {
		if (id.length === 1) {
			base[id[0]] = val;
			return;
		}
		setObj(base[id.shift()], id, val);
	}

	// hasOwnProperty()
	var has = (function(){
		var Has = Object.prototype.hasOwnProperty;
		return function has(obj, key) {
			Has.call(obj,key);
		}
	})();

	/* Converts an object into map (allows functions) */
	function createHash(data) {
		var out = Object.create? Object.create(null) : {}, i;
		for ( i in data ) {
			if (data.hasOwnProperty(i)) {
				out[i] = data[i];
			}
		}
		return out;
	}
	//*/

	// Variables:
	var
		// The data to work on (e.g. it could contain x-y position, and time)
		data = cloneObj(config.initData),

		// The initial data which data resets to
		dataInit = cloneObj(data),

	// Physical Systems
		systems = {

			// A simple spring - mass system
			"spring": require("systems/spring"),

			// A simple linear-gravity with mass system
			"gravity": require("systems/gravity")

		},
		// The current physical system
		getAccel = systems[config.system],

	// Numerical 2nd order diff eq solvers
		solvers = {

			// The Euler Method
			"euler": require("solvers/euler"),

			// The Runge-Kutta Method: RK4
			// according to https://www.youtube.com/watch?v=smfX0Jt_f0I
			"rk4merged": require("solvers/rk4merged")

		},
		// The current colver
		solveStep = solvers[config.solver],

	// Functions which provide the "step" in the simulation
		steppers = {

			"boundary": require("steppers/boundary")

		},
		step = steppers[config.stepper];

	// Timer vars:

		// # of steps to perform each tick
		simStep = config.simulation.simStep,
		// a new value to change to
		simStepNew = simStep,

		// # of simulation seconds every real second
		simRate = config.simulation.simRate,
		simRateNew = simRate,

		// update-needed flag to allow updating step/rate when available
		varNeedUpdate = false,

		// Just a variable to keep track of the previous
		// time stamp. This is to calculate time steps
		prevTime = 0,

		// stop flag: stops the loop in tick()
		_stop = false,

		// Frames per second (not really used)
		fps = 0/0;

	// Command functions:
		commands = {
			"start": start,
			"stop": stop,
			"close": function () {
				self.close();
			},
			"reset": reset,
			"set": set,
			"get": get
		},
		setItems = {
			"solver": function(val) {
				switch (typeof val) {
					case "string":
						solvers[val] && (solveStep = solvers[val]);
						break;
					case "function":
						solveStep = val;
						brea;
				}
			},
			"system": function(val) {
				switch (typeof val) {
					case "string":
						systems[val] && (getAccel = systems[val]);
						break;
					case "function":
						getAccel = val;
				}
			},
			"simStep": function(val) {
				if (typeof val !== "number") {
					return;
				}
				simStepNew = val;
				varNeedUpdate = true;
			},
			"simRate": function(rate) {
				if (typeof val !== "number") {
					return;
				}
				simRateNew = rate;
				varNeedUpdate = true;
			},
			"data": function(value) {
				if (typeof val !== "object") {
					return;
				}
				data = cloneObj(value);
			},
			"dataInit": function(value) {
				if (typeof val !== "object") {
					return;
				}
				//data = cloneObj(value);
				dataInit = cloneObj(value);
			}
		};

	/* Convert objects to "hashes" */
	systems = createHash(systems);
	solvers = createHash(solvers);
	steppers = createHash(steppers);
	commands = createHash(commands);
	setItems = createHash(setItems);
	//*/

	// get(arg)
	function get(arg) {
		//TODO
		throw "caint get anything yet until implemented";
	}

	// set() - Sets a particular value
	function set(arg) {	// TODO: very similar to onmessage handler. merge?
		var key = arg.key,
			id,
			value = arg.value,
			keyStart;
		if (!key) return;
		if (typeof key === "string") {

			id = key.split(".");

			if (has(setItems, key)) {
				setItems[key](value);
			} else if ((keyStart = id.shift()) === "data") {
				setObj(data,id,cloneObj(value));
				//data[key] = cloneObj(value);
			} else if (keyStart === "dataInit") {
				setObj(dataInit,id,cloneObj(value));
				//dataInit[key] = cloneObj(value);
			}

		} else if (typeof key.length === "number") {
			for (var i=0, len = key.length, ckey; i<len; i++) {
				ckey = key[i];
				id = ckey.split(".");
				if (has(setItems, ckey)) {
					setItems[ckey](value);
				} else if ((keyStart=id.shift()) === "data") {
					setObj(data,id,cloneObj(value));
					//data[ckey] = cloneObj(value);
				} else if (keyStart === "dataInit") {
					setObj(dataInit,id,cloneObj(value));
					//dataInit[ckey] = cloneObj(value);
				}
			}
		} else if (typeof value === "object") {
			for (var i in value) {
				if (has(value, i)) {
					set(i,value[i]);
				}
			}
		}
	}

	// reset() - Resets data with dataInit
	function reset() {
		data = cloneObj(dataInit);
	}

	// start() - starts the simulation
	function start() {
		prevTime = Date.now();
		_stop = false;
		setTimeout(tick,0);
	}

	// stop() - stops the simulation
	function stop() {
		_stop = true;
	}

	// publishes the changes back to the worker spawner
	function publishChanges() {
		self.postMessage({
			"type": "data",
			"fps": fps,
			"variables": data
		});
	}

	// onmessage - handle commands to worker
	self.addEventListener("message", function(evt) {

		// cmd: a string or array of strings specifying the command to take
		var data = evt.data, cmd = data.cmd;

		// if cmd doesn't exist return as we can't do much about it
		if (!cmd) return;

		// if cmd is string, just call command if it exists
		if (typeof cmd === "string" && has(commands, cmd)) {
			commands[cmd](data);
		} else
		// else if it looks like array, loop through and exec
		if (typeof cmd.length === "number") {

			for (var i=0, len = cmd.length; i<len; i++) {
				has(commands, cmd[i]) && commands[cmd[i]](data);
			}

		}

	});

	// tick()
	function tick() {

		if (varNeedUpdate) updateTimerVars();

		// return and do nothing if the stop flag is held true
		if (_stop) return;

		// self explanatory
		var i = 0,
			currentTime = Date.now(),
			dt = (currentTime - prevTime) * simRate / simStep / 1000;
		for ( ; i < simStep; i++ ) {
			step(dt, data, solveStep, getAccel);
		}
		prevTime = currentTime;
		fps = simRate/dt;
		publishChanges();
		setTimeout(tick,0);

	}

	// update the simulation-rate/step variables
	function updateTimerVars() {
		simRate = simRateNew;
		simStep = simStepNew;
		varNeedUpdate = false;
	}

	self.postMessage({
		type: "ready"
	});

});


text:
package org.ovirt.engine.ui.uicommonweb.models.templates;

import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.UIConstants;

/**
 * It allows for frontend to distinguish between regular template and latest template.
 *

 *     Note: Latest template instance equals to its pattern.
 *

 *         VmTemplate a = ...
 *         LatestVmTemplate b = new LatestVmTemplate(a);
 *         a.equals(b); // returns true
 *

 *

 */
public class LatestVmTemplate extends VmTemplate {

    public LatestVmTemplate(VmTemplate template) {
        super(template);

        setNaming();
    }

    /**
     * Just because serializable classes require non-parametric constructor.
     */
    public LatestVmTemplate() {
        super();
        setNaming();
    }

    private void setNaming() {
        final UIConstants constants = ConstantsManager.getInstance().getConstants();
        this.setTemplateVersionName(constants.latestTemplateVersionName());
        this.setDescription(constants.latestTemplateVersionDescription());
    }
}


text:
package io.lacker.classifier;

public interface StateClassifier<T> {

  boolean isAlive(T state);
}


text:
@interface NSObject (MyAdditions_ToDictionary)

//- (NSDictionary*) dictionaryRepresentation;

@end


text:
require '2017-06-01/generated/azure_mgmt_stor_simple8000_series'
require 'profiles/latest/storsimple8000series_latest_profile_client'


text:
<?php

namespace ALttP\Region\Standard;

use ALttP\Boss;
use ALttP\Item;
use ALttP\Location;
use ALttP\Region;
use ALttP\Support\LocationCollection;
use ALttP\World;

/**
 * Eastern Palace Region and it's Locations contained within
 */
class EasternPalace extends Region
{
    protected $name = 'Eastern Palace';
    public $music_addresses = [
        0x1559A,
    ];

    protected $map_reveal = 0x2000;

    protected $region_items = [
        'BigKey',
        'BigKeyP1',
        'Compass',
        'CompassP1',
        'Key',
        'KeyP1',
        'Map',
        'MapP1',
    ];

    /**
     * Create a new Eastern Palace Region and initalize it's locations
     *
     * @param World $world World this Region is part of
     *
     * @return void
     */
    public function __construct(World $world)
    {
        parent::__construct($world);

        // set a default boss
        $this->boss = Boss::get("Armos Knights", $world);

        $this->locations = new LocationCollection([
            new Location\Chest("Eastern Palace - Compass Chest", [0xE977], null, $this),
            new Location\BigChest("Eastern Palace - Big Chest", [0xE97D], null, $this),
            new Location\Chest("Eastern Palace - Cannonball Chest", [0xE9B3], null, $this),
            new Location\Chest("Eastern Palace - Big Key Chest", [0xE9B9], null, $this),
            new Location\Chest("Eastern Palace - Map Chest", [0xE9F5], null, $this),
            new Location\Drop("Eastern Palace - Boss", [0x180150], null, $this),

            new Location\Prize\Pendant("Eastern Palace - Prize", [null, 0x1209D, 0x53EF8, 0x53EF9, 0x180052, 0x18007C, 0xC6FE], null, $this),
        ]);
        $this->locations->setChecksForWorld($world->id);
        $this->prize_location = $this->locations["Eastern Palace - Prize"];
    }

    /**
     * Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
     * within for No Glitches
     *
     * @return $this
     */
    public function initalize()
    {
        $this->locations["Eastern Palace - Big Chest"]->setRequirements(function ($locations, $items) {
            return $items->has('BigKeyP1');
        });

        $this->locations["Eastern Palace - Big Key Chest"]->setRequirements(function ($locations, $items) {
            return $items->has('Lamp', $this->world->config('item.require.Lamp', 1));
        });

        $this->can_complete = function ($locations, $items) {
            return $this->locations["Eastern Palace - Boss"]->canAccess($items);
        };

        $this->locations["Eastern Palace - Boss"]->setRequirements(function ($locations, $items) {
            return $items->canShootArrows($this->world)
                && ($items->has('Lamp', $this->world->config('item.require.Lamp', 1))
                    || ($this->world->config('itemPlacement') === 'advanced' && $items->has('FireRod')))
                && $items->has('BigKeyP1')
                && $this->boss->canBeat($items, $locations)
                && (!$this->world->config('region.wildCompasses', false) || $items->has('CompassP1') || $this->locations["Eastern Palace - Boss"]->hasItem(Item::get('CompassP1', $this->world)))
                && (!$this->world->config('region.wildMaps', false) || $items->has('MapP1') || $this->locations["Eastern Palace - Boss"]->hasItem(Item::get('MapP1', $this->world)));
        })->setFillRules(function ($item, $locations, $items) {
            if (
                !$this->world->config('region.bossNormalLocation', true)
                && ($item instanceof Item\Key || $item instanceof Item\BigKey
                    || $item instanceof Item\Map || $item instanceof Item\Compass)
            ) {
                return false;
            }

            return true;
        })->setAlwaysAllow(function ($item, $items) {
            return $this->world->config('region.bossNormalLocation', true)
                && ($item == Item::get('CompassP1', $this->world) || $item == Item::get('MapP1', $this->world));
        });

        $this->can_enter = function ($locations, $items) {
            return $items->has('RescueZelda');
        };

        $this->prize_location->setRequirements($this->can_complete);

        return $this;
    }
}


text:
<!-- Just for playing around with yaml-js in browser console -->
<!-- Run http-server from this directory for scripts properly -->
<script src="bower_components/yaml-js/yaml.js"></script>
<script src="bower_components/lodash/lodash.js"></script>
<script src="bower_components/js-yaml/dist/js-yaml.js"></script>

<script>

</script>


text:
package com.welcu.android.zxingfragmentlib.camera.open;

import android.hardware.Camera;

/**
 * Provides an abstracted means to open a {@link android.hardware.Camera}. The API changes over Android API versions and
 * this allows the app to use newer API methods while retaining backwards-compatible behavior.
 */
public interface OpenCameraInterface {

  Camera open();

}


text:
puts "What is your first name?"
first_name = gets.chomp
puts "What is your middle name?"
middle_name = gets.chomp
puts "What is your last name?"
last_name = gets.chomp
puts "Hello, " + first_name + " " + middle_name + " " + last_name + "!. It\'s nice to meet you."

# Bigger, better favorite number: Write a program that asks for a person's favorite number.
# Have your program add 1 to the number, and then suggest the result as a bigger and better number.
puts "What is your favorite number?"
favorite_number = gets.chomp.to_i
bigger_better_number = favorite_number + 1
puts favorite_number.to_s + " is a good number, but " + bigger_better_number.to_s + " is a bigger and better number, dont\'t you think?"

# How do you define a local variable?
# A local variable works within a mathod, so they are defined within the method.
# How do you define a method?
# A method is defined by giving it a name and the local variables it uses.
# What is the difference between a local variable and a method?
# Local variables work within the method, and methods contain ways or operations using local variables to perform a task.
# How do you run a ruby program from the command line?
# By calling up the irb with the command "irb"
# How do you run an RSpec file from the command line?
# type "rspec [name of spec file]"
# What was confusing about this material? What made sense?
#So far, nothing is particularily confusing.


text:
package com.siyeh.ig.initialization;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightInspectionTestCase;

public class InstanceVariableUninitializedUseInspectionTest extends LightInspectionTestCase {
  @Override
  protected InspectionProfileEntry getInspection() {
    return new InstanceVariableUninitializedUseInspection();
  }

  public void testInstanceVariableUninitializedUse() { doTest(); }
}


text:
<!doctype html>

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

    <title>Appacitive - Documentation</title>
    <link rel="shortcut icon" href="favicon.ico" />

    <link href="style/bootstrap.min.css" rel="stylesheet" />
    <link href="style/theme/white/style.css" rel="stylesheet" />
    <link href="style/custom.css" rel="stylesheet" />

    <link href="style/highlight.css" rel="stylesheet" />

    <meta content="Appacitive - Documentation" property="og:title">
    <meta content="Appacitive - Documentation." name="description">

Home

Features

Pricing

Blogs

Documentation

Support

Login

.Net

javascript

Rest

iOS

Android


text:
'use strict';

import { module } from 'angular';
import _ from 'lodash';

export const GOOGLE_LOADBALANCER_DETAILS_LOADBALANCERTYPE_LOADBALANCERTYPE_COMPONENT =
  'spinnaker.deck.gce.loadBalancer.loadBalancerType';
export const name = GOOGLE_LOADBALANCER_DETAILS_LOADBALANCERTYPE_LOADBALANCERTYPE_COMPONENT; // for backwards compatibility
module(GOOGLE_LOADBALANCER_DETAILS_LOADBALANCERTYPE_LOADBALANCERTYPE_COMPONENT, []).component('gceLoadBalancerType', {
  template: '<span>{{ $ctrl.type }}</span>',
  bindings: {
    loadBalancer: '=',
  },
  controller: function () {
    this.type = (function (lb) {
      if (lb.loadBalancerType === 'HTTP') {
        if (_.isString(lb.certificate)) {
          return 'HTTPS';
        } else {
          return 'HTTP';
        }
      } else {
        return lb.loadBalancerType;
      }
    })(this.loadBalancer);
  },
});


text:
#ifndef _IPXE_ROTATE_H
#define _IPXE_ROTATE_H

/** @file
 *
 * Bit operations
 */

FILE_LICENCE ( GPL2_OR_LATER );

#include <stdint.h>

static inline __attribute__ (( always_inline )) uint32_t
rol32 ( uint32_t data, unsigned int rotation ) {
        return ( ( data << rotation ) | ( data >> ( 32 - rotation ) ) );
}

static inline __attribute__ (( always_inline )) uint32_t
ror32 ( uint32_t data, unsigned int rotation ) {
        return ( ( data >> rotation ) | ( data << ( 32 - rotation ) ) );
}

static inline __attribute__ (( always_inline )) uint64_t
rol64 ( uint64_t data, unsigned int rotation ) {
        return ( ( data << rotation ) | ( data >> ( 64 - rotation ) ) );
}

static inline __attribute__ (( always_inline )) uint64_t
ror64 ( uint64_t data, unsigned int rotation ) {
        return ( ( data >> rotation ) | ( data << ( 64 - rotation ) ) );
}

#endif /* _IPXE_ROTATE_H */


text:
@implementation UIView (ChainStyle)

- (UIView*(^)(CGFloat temp))X{
	return  ^(CGFloat value){
		CGRect rect = self.frame;
		rect.origin.x = value;
		self.frame = rect;
		return self;
	};
}

- (UIView*(^)(CGFloat temp))Y{
	return  ^(CGFloat value){
		CGRect rect = self.frame;
		rect.origin.y = value;
		self.frame = rect;
		return self;
	};
}

- (UIView*(^)(CGFloat temp))Width{
	return  ^(CGFloat value){
		CGRect rect = self.frame;
		rect.size.width = value;
		self.frame = rect;
		return self;
	};
}

- (UIView*(^)(CGFloat temp))Height{
	return  ^(CGFloat value){
		CGRect rect = self.frame;
		rect.size.height = value;
		self.frame = rect;
		return self;
	};
}

@end


text:
using System.Linq;
using System.Threading.Tasks;
using Chinchilla.Integration.Features.Messages;
using Xunit;

namespace Chinchilla.Integration.Features
{
    public class PublisherConfirmsFeature : Feature
    {
        [Fact]
        public async Task ShouldCreatePublisherWithoutConfirms()
        {
            using (var bus = await CreateBus())
            {
                var publisher = bus.CreatePublisher<HelloWorldMessage>(p => p.Confirm(false));

                var receipts = Enumerable.Range(0, 100)
                    .Select(_ => publisher.Publish(new HelloWorldMessage()))
                    .ToArray();

                publisher.Dispose();

                Assert.True(receipts.All(r => r.Status == PublishStatus.None));
            }
        }

        [Fact]
        public async Task ShouldWaitForAllMessagesToBeConfirmedWhenDisposing()
        {
            using (var bus = await CreateBus())
            {
                var publisher = bus.CreatePublisher<HelloWorldMessage>(p => p.Confirm(true));

                var receipts = Enumerable.Range(0, 100)
                    .Select(_ => publisher.Publish(new HelloWorldMessage()))
                    .ToArray();

                publisher.Dispose();

                Assert.True(receipts.All(r => r.IsConfirmed));
            }
        }
    }
}


text:
using System;
using System.CodeDom;

namespace IronAHK.Scripting
{
    partial class Emit
    {
        void EmitMethod(CodeMemberMethod method)
        {
            if (options.BlankLinesBetweenMembers)
                WriteSpace();

            WriteSpace();
            writer.Write(method.Name);
            writer.Write(Parser.ParenOpen);
            bool first = true;

            foreach (CodeParameterDeclarationExpression param in method.Parameters)
            {
                if (!first)
                    writer.Write(Parser.SingleSpace);

                switch (param.Direction)
                {
                    case FieldDirection.Out:
                        throw new NotSupportedException();

                    case FieldDirection.Ref:
                        writer.Write(Parser.FunctionParamRef);
                        writer.Write(Parser.SingleSpace);
                        break;
                }

                writer.Write(param.Name);

                if (first)
                    first = false;
                else
                    writer.Write(Parser.DefaultMulticast);

            }

            writer.Write(Parser.ParenClose);
            WriteSpace();
            writer.Write(Parser.BlockOpen);

            depth++;
            WriteSpace();
            writer.Write(Parser.FunctionGlobal);
            EmitStatements(method.Statements);
            depth--;

            WriteSpace();
            writer.Write(Parser.BlockClose);
        }
    }
}


text:
// $Id: MEM_Addr.cpp 79134 2007-07-31 18:23:50Z johnnyw $

// Defines the Internet domain address family address format.

#include "ace/MEM_Addr.h"

#if (ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1)

#if !defined (__ACE_INLINE__)
#include "ace/MEM_Addr.inl"
#endif /* __ACE_INLINE__ */

#include "ace/Log_Msg.h"
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_unistd.h"
#include "ace/os_include/os_netdb.h"

ACE_RCSID (ace,
           MEM_Addr,
           "$Id: MEM_Addr.cpp 79134 2007-07-31 18:23:50Z johnnyw $")

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE(ACE_MEM_Addr)

// Transform the current address into string format.

ACE_MEM_Addr::ACE_MEM_Addr (void)
  : ACE_Addr (AF_INET, sizeof (ACE_MEM_Addr))
{
  // ACE_TRACE ("ACE_MEM_Addr::ACE_MEM_Addr");
  this->initialize_local (0);
}

ACE_MEM_Addr::ACE_MEM_Addr (const ACE_MEM_Addr &sa)
  : ACE_Addr (AF_INET, sizeof (ACE_MEM_Addr))
{
  ACE_TRACE ("ACE_MEM_Addr::ACE_MEM_Addr");
  this->external_.set (sa.external_);
  this->internal_.set (sa.internal_);
}

ACE_MEM_Addr::ACE_MEM_Addr (const ACE_TCHAR port_number[])
  : ACE_Addr (AF_INET, sizeof (ACE_MEM_Addr))
{
  ACE_TRACE ("ACE_MEM_Addr::ACE_MEM_Addr");
  u_short pn = static_cast<u_short> (ACE_OS::strtoul (port_number,
                                                      0,
                                                      10));
  this->initialize_local (pn);
}

ACE_MEM_Addr::ACE_MEM_Addr (u_short port_number)
  : ACE_Addr (AF_INET, sizeof (ACE_MEM_Addr))
{
  ACE_TRACE ("ACE_MEM_Addr::ACE_MEM_Addr");
  this->initialize_local (port_number);
}

ACE_MEM_Addr::~ACE_MEM_Addr (void)
{
}

int
ACE_MEM_Addr::initialize_local (u_short port_number)
{
  ACE_TCHAR name[MAXHOSTNAMELEN + 1];
  if (ACE_OS::hostname (name, MAXHOSTNAMELEN+1) == -1)
    return -1;

  this->external_.set (port_number, name);
  this->internal_.set (port_number, ACE_TEXT ("localhost"));
  return 0;
}

int
ACE_MEM_Addr::same_host (const ACE_INET_Addr &sap)
{
  ACE_TRACE ("ACE_MEM_Addr::same_host");

  // ACE_INET_Addr::operator== takes port number into account, so get
  // the addresses without a port number and compare.
  ACE_INET_Addr me (this->external_);
  ACE_INET_Addr you (sap);
  me.set_port_number (0);
  you.set_port_number (0);
  return me == you;
}

int
ACE_MEM_Addr::addr_to_string (ACE_TCHAR s[],
                              size_t size,
                              int ipaddr_format) const
{
  ACE_TRACE ("ACE_MEM_Addr::addr_to_string");

  return this->external_.addr_to_string (s, size, ipaddr_format);
}

// Transform the string into the current addressing format.

int
ACE_MEM_Addr::string_to_addr (const ACE_TCHAR s[])
{
  ACE_TRACE ("ACE_MEM_Addr::string_to_addr");

  u_short pn = static_cast<u_short> (ACE_OS::strtoul (s,
                                                      0,
                                                      10));
  return this->set (pn);
}

// Return the address.

void *
ACE_MEM_Addr::get_addr (void) const
{
  ACE_TRACE ("ACE_MEM_Addr::get_addr");
  return this->external_.get_addr ();
}

// Set a pointer to the address.
void
ACE_MEM_Addr::set_addr (void *addr, int len)
{
  ACE_TRACE ("ACE_MEM_Addr::set_addr");

  this->external_.set_addr (addr, len);
  this->internal_.set_port_number (this->external_.get_port_number ());
}

int
ACE_MEM_Addr::get_host_name (ACE_TCHAR hostname[],
                              size_t len) const
{
  ACE_TRACE ("ACE_MEM_Addr::get_host_name");
  return this->external_.get_host_name (hostname, len);
}

// Return the character representation of the hostname.

const char *
ACE_MEM_Addr::get_host_name (void) const
{
  ACE_TRACE ("ACE_MEM_Addr::get_host_name");
  return this->external_.get_host_name ();
}

u_long
ACE_MEM_Addr::hash (void) const
{
  return this->external_.hash ();
}

void
ACE_MEM_Addr::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_TRACE ("ACE_MEM_Addr::dump");

  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  this->external_.dump ();
  this->internal_.dump ();
  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}

ACE_END_VERSIONED_NAMESPACE_DECL

#endif /* ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1 */


text:
import Keccak from 'keccakjs';

export default function getFunctionSignature(signature) {
  return new Keccak(256).update(signature).digest('hex').substr(0, 8);
}


text:
package org.apache.olingo.ext.proxy.api.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Identifies a compound key.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CompoundKey {
//No additional methods needed for now.
}


text:
namespace System.Reflection
{
    using System;

    [Flags]
////[Serializable]
    public enum MethodAttributes
    {
        // NOTE: This Enum matchs the CorMethodAttr defined in CorHdr.h

        // member access mask - Use this mask to retrieve accessibility information.
        MemberAccessMask      = 0x0007,
        PrivateScope          = 0x0000,     // Member not referenceable.
        Private               = 0x0001,     // Accessible only by the parent type.
        FamANDAssem           = 0x0002,     // Accessible by sub-types only in this Assembly.
        Assembly              = 0x0003,     // Accessibly by anyone in the Assembly.
        Family                = 0x0004,     // Accessible only by type and sub-types.
        FamORAssem            = 0x0005,     // Accessibly by sub-types anywhere, plus anyone in assembly.
        Public                = 0x0006,     // Accessibly by anyone who has visibility to this scope.
        // end member access mask

        // method contract attributes.
        Static                = 0x0010,     // Defined on type, else per instance.
        Final                 = 0x0020,     // Method may not be overridden.
        Virtual               = 0x0040,     // Method virtual.
        HideBySig             = 0x0080,     // Method hides by name+sig, else just by name.
        CheckAccessOnOverride = 0x0200,

        // vtable layout mask - Use this mask to retrieve vtable attributes.
        VtableLayoutMask      = 0x0100,
        ReuseSlot             = 0x0000,     // The default.
        NewSlot               = 0x0100,     // Method always gets a new slot in the vtable.
        // end vtable layout mask

        // method implementation attributes.
        Abstract              = 0x0400,     // Method does not provide an implementation.
        SpecialName           = 0x0800,     // Method is special.  Name describes how.

        // interop attributes
        PinvokeImpl           = 0x2000,     // Implementation is forwarded through pinvoke.
        UnmanagedExport       = 0x0008,     // Managed method exported via thunk to unmanaged code.
        RTSpecialName         = 0x1000,     // Runtime should check name encoding.

        // Reserved flags for runtime use only.
        ReservedMask          = 0xd000,
        HasSecurity           = 0x4000,     // Method has security associate with it.
        RequireSecObject      = 0x8000,     // Method calls another method containing security code.
    }
}


text:
import os
import telnetlib

from oslo_log import log as logging
from oslo_utils import timeutils

from sahara.conductor import resource as res
from sahara import context
from sahara.i18n import _
from sahara.i18n import _LI
from sahara.plugins.cdh import commands as cmd
from sahara.plugins import exceptions as ex
from sahara.plugins import utils as u
from sahara.utils import edp as edp_u

PATH_TO_CORE_SITE_XML = '/etc/hadoop/conf/core-site.xml'
HADOOP_LIB_DIR = '/usr/lib/hadoop-mapreduce'

CM_API_PORT = 7180

LOG = logging.getLogger(__name__)

class AbstractPluginUtils(object):
    # c_helper and db_helper will be defined in derived classes.
    c_helper = None
    db_helper = None

    def get_role_name(self, instance, service):
        # NOTE: role name must match regexp "[_A-Za-z][-_A-Za-z0-9]{0,63}"
        shortcuts = {
            'ALERTPUBLISHER': 'AP',
            'DATANODE': 'DN',
            'EVENTSERVER': 'ES',
            'HIVEMETASTORE': 'HVM',
            'HIVESERVER2': 'HVS',
            'HOSTMONITOR': 'HM',
            'JOBHISTORY': 'JS',
            'MASTER': 'M',
            'NAMENODE': 'NN',
            'NODEMANAGER': 'NM',
            'OOZIE_SERVER': 'OS',
            'REGIONSERVER': 'RS',
            'RESOURCEMANAGER': 'RM',
            'SECONDARYNAMENODE': 'SNN',
            'SERVER': 'S',
            'SERVICEMONITOR': 'SM',
            'SPARK_YARN_HISTORY_SERVER': 'SHS',
            'WEBHCAT': 'WHC'
        }
        return '%s_%s' % (shortcuts.get(service, service),
                          instance.hostname().replace('-', '_'))

    def get_manager(self, cluster):
        return u.get_instance(cluster, 'CLOUDERA_MANAGER')

    def get_namenode(self, cluster):
        return u.get_instance(cluster, "HDFS_NAMENODE")

    def get_datanodes(self, cluster):
        return u.get_instances(cluster, 'HDFS_DATANODE')

    def get_secondarynamenode(self, cluster):
        return u.get_instance(cluster, 'HDFS_SECONDARYNAMENODE')

    def get_historyserver(self, cluster):
        return u.get_instance(cluster, 'YARN_JOBHISTORY')

    def get_resourcemanager(self, cluster):
        return u.get_instance(cluster, 'YARN_RESOURCEMANAGER')

    def get_nodemanagers(self, cluster):
        return u.get_instances(cluster, 'YARN_NODEMANAGER')

    def get_oozie(self, cluster):
        return u.get_instance(cluster, 'OOZIE_SERVER')

    def get_hive_metastore(self, cluster):
        return u.get_instance(cluster, 'HIVE_METASTORE')

    def get_hive_servers(self, cluster):
        return u.get_instances(cluster, 'HIVE_SERVER2')

    def get_hue(self, cluster):
        return u.get_instance(cluster, 'HUE_SERVER')

    def get_spark_historyserver(self, cluster):
        return u.get_instance(cluster, 'SPARK_YARN_HISTORY_SERVER')

    def get_zookeepers(self, cluster):
        return u.get_instances(cluster, 'ZOOKEEPER_SERVER')

    def get_hbase_master(self, cluster):
        return u.get_instance(cluster, 'HBASE_MASTER')

    def convert_process_configs(self, configs):
        p_dict = {
            "CLOUDERA": ['MANAGER'],
            "NAMENODE": ['NAMENODE'],
            "DATANODE": ['DATANODE'],
            "SECONDARYNAMENODE": ['SECONDARYNAMENODE'],
            "RESOURCEMANAGER": ['RESOURCEMANAGER'],
            "NODEMANAGER": ['NODEMANAGER'],
            "JOBHISTORY": ['JOBHISTORY'],
            "OOZIE": ['OOZIE_SERVER'],
            "HIVESERVER": ['HIVESERVER2'],
            "HIVEMETASTORE": ['HIVEMETASTORE'],
            "WEBHCAT": ['WEBHCAT'],
            "HUE": ['HUE_SERVER'],
            "SPARK_ON_YARN": ['SPARK_YARN_HISTORY_SERVER'],
            "ZOOKEEPER": ['SERVER'],
            "MASTER": ['MASTER'],
            "REGIONSERVER": ['REGIONSERVER']
        }
        if isinstance(configs, res.Resource):
            configs = configs.to_dict()
        for k in configs.keys():
            if k in p_dict.keys():
                item = configs[k]
                del configs[k]
                newkey = p_dict[k][0]
                configs[newkey] = item
        return res.Resource(configs)

    def convert_role_showname(self, showname):
        name_dict = {
            'CLOUDERA_MANAGER': 'MANAGER',
            'HDFS_NAMENODE': 'NAMENODE',
            'HDFS_DATANODE': 'DATANODE',
            'HDFS_SECONDARYNAMENODE': 'SECONDARYNAMENODE',
            'YARN_RESOURCEMANAGER': 'RESOURCEMANAGER',
            'YARN_NODEMANAGER': 'NODEMANAGER',
            'YARN_JOBHISTORY': 'JOBHISTORY',
            'OOZIE_SERVER': 'OOZIE_SERVER',
            'HIVE_SERVER2': 'HIVESERVER2',
            'HIVE_METASTORE': 'HIVEMETASTORE',
            'HIVE_WEBHCAT': 'WEBHCAT',
            'HUE_SERVER': 'HUE_SERVER',
            'SPARK_YARN_HISTORY_SERVER': 'SPARK_YARN_HISTORY_SERVER',
            'ZOOKEEPER_SERVER': 'SERVER',
            'HBASE_MASTER': 'MASTER',
            'HBASE_REGIONSERVER': 'REGIONSERVER',
            'FLUME_AGENT': 'AGENT',
            'IMPALA_CATALOGSERVER': 'CATALOGSERVER',
            'IMPALA_STATESTORE': 'STATESTORE',
            'IMPALAD': 'IMPALAD',
            'KEY_VALUE_STORE_INDEXER': 'HBASE_INDEXER',
            'SENTRY_SERVER': 'SENTRY_SERVER',
            'SOL_SERVER': 'SOLR_SERVER',
            'SQOOP_SERVER': 'SQOOP_SERVER',
        }
        return name_dict.get(showname, showname)

    def install_packages(self, instances, packages):
        with context.ThreadGroup() as tg:
            for i in instances:
                tg.spawn('cdh-inst-pkgs-%s' % i.instance_name,
                         self._install_pkgs, i, packages)

    def _install_pkgs(self, instance, packages):
        with instance.remote() as r:
            cmd.install_packages(r, packages)

    def start_cloudera_agents(self, instances):
        with context.ThreadGroup() as tg:
            for i in instances:
                tg.spawn('cdh-agent-start-%s' % i.instance_name,
                         self.start_cloudera_agent, i)

    def start_cloudera_agent(self, instance):
        mng_hostname = self.get_manager(instance.cluster).hostname()
        with instance.remote() as r:
            cmd.start_ntp(r)
            cmd.configure_agent(r, mng_hostname)
            cmd.start_agent(r)

    def configure_swift(self, cluster):
        if self.c_helper.is_swift_enabled(cluster):
            instances = u.get_instances(cluster)
            with context.ThreadGroup() as tg:
                for i in instances:
                    tg.spawn('cdh-swift-conf-%s' % i.instance_name,
                             self.configure_swift_to_inst, i)

    def configure_swift_to_inst(self, instance):
        cluster = instance.cluster
        with instance.remote() as r:
            r.execute_command('sudo curl %s -o %s/hadoop-openstack.jar' % (
                self.c_helper.get_swift_lib_url(cluster), HADOOP_LIB_DIR))

    def put_hive_hdfs_xml(self, cluster):
        servers = self.get_hive_servers(cluster)
        with servers[0].remote() as r:
            conf_path = edp_u.get_hive_shared_conf_path('hdfs')
            r.execute_command(
                'sudo su - -c "hadoop fs -mkdir -p %s" hdfs'
                % os.path.dirname(conf_path))
            r.execute_command(
                'sudo su - -c "hadoop fs -put /etc/hive/conf/hive-site.xml '
                '%s" hdfs' % conf_path)

    def configure_hive(self, cluster):
        manager = self.get_manager(cluster)
        with manager.remote() as r:
            self.db_helper.create_hive_database(cluster, r)

    def create_hive_hive_directory(self, cluster):
        # Hive requires /tmp/hive-hive directory
        namenode = self.get_namenode(cluster)
        with namenode.remote() as r:
            r.execute_command(
                'sudo su - -c "hadoop fs -mkdir -p /tmp/hive-hive" hdfs')
            r.execute_command(
                'sudo su - -c "hadoop fs -chown hive /tmp/hive-hive" hdfs')

    def install_extjs(self, cluster):
        extjs_remote_location = self.c_helper.get_extjs_lib_url(cluster)
        extjs_vm_location_dir = '/var/lib/oozie'
        extjs_vm_location_path = extjs_vm_location_dir + '/extjs.zip'
        with self.get_oozie(cluster).remote() as r:
            if r.execute_command('ls %s/ext-2.2' % extjs_vm_location_dir,
                                 raise_when_error=False)[0] != 0:
                r.execute_command('curl -L -o \'%s\' %s' % (
                    extjs_vm_location_path,  extjs_remote_location),
                    run_as_root=True)
                r.execute_command('unzip %s -d %s' % (
                    extjs_vm_location_path, extjs_vm_location_dir),
                    run_as_root=True)

    def start_cloudera_manager(self, cluster):
        manager = self.get_manager(cluster)
        with manager.remote() as r:
            cmd.start_cloudera_db(r)
            cmd.start_manager(r)

        timeout = 300
        LOG.debug("Waiting %(timeout)s seconds for Manager to start : " % {
            'timeout': timeout})
        s_time = timeutils.utcnow()
        while timeutils.delta_seconds(s_time, timeutils.utcnow()) < timeout:
            try:
                conn = telnetlib.Telnet(manager.management_ip, CM_API_PORT)
                conn.close()
                break
            except IOError:
                context.sleep(2)
        else:
            message = _("Cloudera Manager failed to start in %(timeout)s "
                        "minutes on node '%(node)s' of cluster "
                        "'%(cluster)s'") % {
                            'timeout': timeout / 60,
                            'node': manager.management_ip,
                            'cluster': cluster.name}
            raise ex.HadoopProvisionError(message)

        LOG.info(_LI("Cloudera Manager has been started"))

    def configure_os(self, instances):
        with context.ThreadGroup() as tg:
            for inst in instances:
                tg.spawn('cdh-repo-conf-%s' % inst.instance_name,
                         self._configure_repo_from_inst, inst)

    def _configure_repo_from_inst(self, instance):
        LOG.debug("Configure repos from instance '%(instance)s'" % {
                  'instance': instance.instance_name})
        cluster = instance.cluster

        cdh5_key = self.c_helper.get_cdh5_key_url(cluster)
        cm5_key = self.c_helper.get_cm5_key_url(cluster)

        with instance.remote() as r:
            if cmd.is_ubuntu_os(r):
                cdh5_key = (cdh5_key or
                            self.c_helper.DEFAULT_CDH5_UBUNTU_REPO_KEY_URL)
                cm5_key = (cm5_key or
                           self.c_helper.DEFAULT_CM5_UBUNTU_REPO_KEY_URL)

                cdh5_repo_content = self.c_helper.CDH5_UBUNTU_REPO
                cm5_repo_content = self.c_helper.CM5_UBUNTU_REPO

                cmd.write_ubuntu_repository(r, cdh5_repo_content, 'cdh')
                cmd.add_apt_key(r, cdh5_key)
                cmd.write_ubuntu_repository(r, cm5_repo_content, 'cm')
                cmd.add_apt_key(r, cm5_key)
                cmd.update_repository(r)

            if cmd.is_centos_os(r):
                cdh5_repo_content = self.c_helper.CDH5_CENTOS_REPO
                cm5_repo_content = self.c_helper.CM5_CENTOS_REPO

                cmd.write_centos_repository(r, cdh5_repo_content, 'cdh')
                cmd.write_centos_repository(r, cm5_repo_content, 'cm')
                cmd.update_repository(r)


text:
//
//   Copyright 2014 Slack Technologies, Inc.
//
//   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.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#import "SLKTextInputbar.h"
#import "SLKTextView.h"
#import "SLKTypingIndicatorView.h"
#import "SLKTypingIndicatorProtocol.h"

#import "SLKTextView+SLKAdditions.h"
#import "UIScrollView+SLKAdditions.h"
#import "UIView+SLKAdditions.h"

#import "SLKUIConstants.h"

/**
 UIKeyboard notification replacement, posting reliably only when showing/hiding the keyboard (not when resizing keyboard, or with inputAccessoryView reloads, etc).
 Only triggered when using SLKTextViewController's text view.
 */
UIKIT_EXTERN NSString *const SLKKeyboardWillShowNotification;
UIKIT_EXTERN NSString *const SLKKeyboardDidShowNotification;
UIKIT_EXTERN NSString *const SLKKeyboardWillHideNotification;
UIKIT_EXTERN NSString *const SLKKeyboardDidHideNotification;

UIKIT_EXTERN NSString *const SLKTextInputbarDidMoveNotification;

typedef NS_ENUM(NSUInteger, SLKKeyboardStatus) {
    SLKKeyboardStatusDidHide,
    SLKKeyboardStatusWillShow,
    SLKKeyboardStatusDidShow,
    SLKKeyboardStatusWillHide
};

/** @name A drop-in UIViewController subclass with a growing text input view and other useful messaging features. */
NS_CLASS_AVAILABLE_IOS(7_0) @interface SLKTextViewController : UIViewController <SLKTextViewDelegate, UITableViewDelegate, UITableViewDataSource,
                                                                                UICollectionViewDelegate, UICollectionViewDataSource,
                                                                                UIGestureRecognizerDelegate, UIAlertViewDelegate>

/** The main table view managed by the controller object. Created by default initializing with -init or initWithNibName:bundle: */
@property (nonatomic, readonly) UITableView *tableView;

/** The main collection view managed by the controller object. Not nil if the controller is initialised with -initWithCollectionViewLayout: */
@property (nonatomic, readonly) UICollectionView *collectionView;

/** The main scroll view managed by the controller object. Not nil if the controller is initialised with -initWithScrollView: */
@property (nonatomic, readonly) UIScrollView *scrollView;

/** The bottom toolbar containing a text view and buttons. */
@property (nonatomic, readonly) SLKTextInputbar *textInputbar;

/** The default typing indicator used to display user names horizontally. */
@property (nonatomic, readonly) SLKTypingIndicatorView *typingIndicatorView;

/**
 The custom typing indicator view. Default is kind of SLKTypingIndicatorView.
 To customize the typing indicator view, you will need to call -registerClassForTypingIndicatorView: nside of any initialization method.
 To interact with it directly, you will need to cast the return value of -typingIndicatorProxyView to the appropriate type.
 */
@property (nonatomic, readonly) UIView <SLKTypingIndicatorProtocol> *typingIndicatorProxyView;

/** A single tap gesture used to dismiss the keyboard. SLKTextViewController is its delegate. */
@property (nonatomic, readonly) UIGestureRecognizer *singleTapGesture;

/** A vertical pan gesture used for bringing the keyboard from the bottom. SLKTextViewController is its delegate. */
@property (nonatomic, readonly) UIPanGestureRecognizer *verticalPanGesture;

/** YES if control's animation should have bouncy effects. Default is YES. */
@property (nonatomic, assign) BOOL bounces;

/** YES if text view's content can be cleaned with a shake gesture. Default is NO. */
@property (nonatomic, assign) BOOL shakeToClearEnabled;

/** YES if keyboard can be dismissed gradually with a vertical panning gesture. Default is YES. */
@property (nonatomic, assign, getter = isKeyboardPanningEnabled) BOOL keyboardPanningEnabled;

/** YES if an external keyboard has been detected (this value updates only when the text view becomes first responder). */
@property (nonatomic, readonly, getter=isExternalKeyboardDetected) BOOL externalKeyboardDetected;

/** YES if the keyboard has been detected as undocked or split (iPad Only). */
@property (nonatomic, readonly, getter=isKeyboardUndocked) BOOL keyboardUndocked;

/** YES if after right button press, the text view is cleared out. Default is YES. */
@property (nonatomic, assign) BOOL shouldClearTextAtRightButtonPress;

/** YES if the scrollView should scroll to bottom when the keyboard is shown. Default is NO.*/
@property (nonatomic, assign) BOOL shouldScrollToBottomAfterKeyboardShows;

/**
 YES if the main table view is inverted. Default is YES.
 This allows the table view to start from the bottom like any typical messaging interface.
 If inverted, you must assign the same transform property to your cells to match the orientation (ie: cell.transform = tableView.transform;)
 Inverting the table view will enable some great features such as content offset corrections automatically when resizing the text input and/or showing autocompletion.
 */
@property (nonatomic, assign, getter = isInverted) BOOL inverted;

/** YES if the view controller is presented inside of a popover controller. If YES, the keyboard won't move the text input bar and tapping on the tableView/collectionView will not cause the keyboard to be dismissed. This property is compatible only with iPad. */
@property (nonatomic, assign, getter = isPresentedInPopover) BOOL presentedInPopover;

/** Convenience accessors (accessed through the text input bar) */
@property (nonatomic, readonly) SLKTextView *textView;
@property (nonatomic, readonly) UIButton *leftButton;
@property (nonatomic, readonly) UIButton *rightButton;

#pragma mark - Initialization
///------------------------------------------------
/// @name Initialization
///------------------------------------------------

/**
 Initializes a text view controller to manage a table view of a given style.
 If you use the standard -init method, a table view with plain style will be created.

 @param style A constant that specifies the style of main table view that the controller object is to manage (UITableViewStylePlain or UITableViewStyleGrouped).
 @return An initialized SLKTextViewController object or nil if the object could not be created.
 */
- (instancetype)initWithTableViewStyle:(UITableViewStyle)style SLK_DESIGNATED_INITIALIZER;

/**
 Initializes a collection view controller and configures the collection view with the provided layout.
 If you use the standard -init method, a table view with plain style will be created.

 @param layout The layout object to associate with the collection view. The layout controls how the collection view presents its cells and supplementary views.
 @return An initialized SLKTextViewController object or nil if the object could not be created.
 */
- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout SLK_DESIGNATED_INITIALIZER;

/**
 Initializes a text view controller to manage an arbitraty scroll view. The caller is responsible for configuration of the scroll view, including wiring the delegate.

 @param a UISCrollView to be used as the main content area.
 @return An initialized SLKTextViewController object or nil if the object could not be created.
 */
- (instancetype)initWithScrollView:(UIScrollView *)scrollView SLK_DESIGNATED_INITIALIZER;

/**
 Initializes either a table or collection view controller.
 You must override either +tableViewStyleForCoder: or +collectionViewLayoutForCoder: to define witch view to be layed out.

 @param decoder An unarchiver object.
 @return An initialized SLKTextViewController object or nil if the object could not be created.
 */
- (instancetype)initWithCoder:(NSCoder *)decoder SLK_DESIGNATED_INITIALIZER;

/**
 Returns the tableView style to be configured when using Interface Builder. Default is UITableViewStylePlain.
 You must override this method if you want to configure a tableView.

 @param decoder An unarchiver object.
 @return The tableView style to be used in the new instantiated tableView.
 */
+ (UITableViewStyle)tableViewStyleForCoder:(NSCoder *)decoder;

/**
 Returns the tableView style to be configured when using Interface Builder. Default is nil.
 You must override this method if you want to configure a collectionView.

 @param decoder An unarchiver object.
 @return The collectionView style to be used in the new instantiated collectionView.
 */
+ (UICollectionViewLayout *)collectionViewLayoutForCoder:(NSCoder *)decoder;

#pragma mark - Keyboard Handling
///------------------------------------------------
/// @name Keyboard Handling
///------------------------------------------------

/**
 Presents the keyboard, if not already, animated.
 You can override this method to perform additional tasks associated with presenting the keyboard.
 You SHOULD call super to inherit some conditionals.

 @param animated YES if the keyboard should show using an animation.
 */
- (void)presentKeyboard:(BOOL)animated;

/**
 Dimisses the keyboard, if not already, animated.
 You can override this method to perform additional tasks associated with dismissing the keyboard.
 You SHOULD call super to inherit some conditionals.

 @param animated YES if the keyboard should be dismissed using an animation.
 */
- (void)dismissKeyboard:(BOOL)animated;

/**
 Verifies if the text input bar should still move up/down even if it is not first responder. Default is NO.
 You can override this method to perform additional tasks associated with presenting the view.
 You don't need call super since this method doesn't do anything.

 @param responder The current first responder object.
 @return YES so the text input bar still move up/down.
 */
- (BOOL)forceTextInputbarAdjustmentForResponder:(UIResponder *)responder;

/**
 Verifies if the text input bar should still move up/down when it is first responder. Default is NO.
 This is very useful when presenting the view controller in a custom modal presentation, when there keyboard events are being handled externally to reframe the presented view.
 You SHOULD call super to inherit some conditionals.
 */
- (BOOL)ignoreTextInputbarAdjustment NS_REQUIRES_SUPER;

/**
 Notifies the view controller that the keyboard changed status.
 You can override this method to perform additional tasks associated with presenting the view.
 You don't need call super since this method doesn't do anything.

 @param status The new keyboard status.
 */
- (void)didChangeKeyboardStatus:(SLKKeyboardStatus)status;

#pragma mark - Interaction Notifications
///------------------------------------------------
/// @name Interaction Notifications
///------------------------------------------------

/**
 Notifies the view controller that the text will update.
 You can override this method to perform additional tasks associated with text changes.
 You MUST call super at some point in your implementation.
 */
- (void)textWillUpdate NS_REQUIRES_SUPER;

/**
 Notifies the view controller that the text did update.
 You can override this method to perform additional tasks associated with text changes.
 You MUST call super at some point in your implementation.

 @param If YES, the text input bar will be resized using an animation.
 */
- (void)textDidUpdate:(BOOL)animated NS_REQUIRES_SUPER;

/**
 Notifies the view controller that the text selection did change.
 Use this method a replacement of UITextViewDelegate's -textViewDidChangeSelection: which is not reliable enough when using third-party keyboards (they don't forward events properly sometimes).

 You can override this method to perform additional tasks associated with text changes.
 You MUST call super at some point in your implementation.
 */
- (void)textSelectionDidChange NS_REQUIRES_SUPER;

/**
 Notifies the view controller when the left button's action has been triggered, manually.
 You can override this method to perform additional tasks associated with the left button.
 You don't need call super since this method doesn't do anything.

 @param sender The object calling this method.
 */
- (void)didPressLeftButton:(id)sender;

/**
 Notifies the view controller when the right button's action has been triggered, manually or by using the keyboard return key.
 You can override this method to perform additional tasks associated with the right button.
 You MUST call super at some point in your implementation.

 @param sender The object calling this method.
 */
- (void)didPressRightButton:(id)sender NS_REQUIRES_SUPER;

- (void)rebindRightButton;

/**
 Verifies if the right button can be pressed. If NO, the button is disabled.
 You can override this method to perform additional tasks. You SHOULD call super to inherit some conditionals.

 @return YES if the right button can be pressed.
 */
- (BOOL)canPressRightButton;

/**
 Notifies the view controller when the user has pasted a supported media content (images and/or videos).
 You can override this method to perform additional tasks associated with image/video pasting. You don't need to call super since this method doesn't do anything.
 Only supported pastable medias configured in SLKTextView will be forwarded (take a look at SLKPastableMediaType).

 @para userInfo The payload containing the media data, content and media types.
 */
- (void)didPasteMediaContent:(NSDictionary *)userInfo;

/**
 Verifies that the typing indicator view should be shown. Default is YES, if meeting some requierements.
 You can override this method to perform additional tasks.
 You SHOULD call super to inherit some conditionals.

 @return YES if the typing indicator view should be presented.
 */
- (BOOL)canShowTypingIndicator;

/**
 Notifies the view controller when the user has shaked the device for undoing text typing.
 You can override this method to perform additional tasks associated with the shake gesture.
 Calling super will prompt a system alert view with undo option. This will not be called if 'undoShakingEnabled' is set to NO and/or if the text view's content is empty.
 */
- (void)willRequestUndo;

/**
 Notifies the view controller when the user has pressed the Return key (↵) with an external keyboard.
 You can override this method to perform additional tasks.
 You MUST call super at some point in your implementation.
 */
- (void)didPressReturnKey:(id)sender NS_REQUIRES_SUPER;

/**
 Notifies the view controller when the user has pressed the Escape key (Esc) with an external keyboard.
 You can override this method to perform additional tasks.
 You MUST call super at some point in your implementation.
 */
- (void)didPressEscapeKey:(id)sender NS_REQUIRES_SUPER;

/**
 Notifies the view controller when the user has pressed the arrow key with an external keyboard.
 You can override this method to perform additional tasks.
 You MUST call super at some point in your implementation.
 */
- (void)didPressArrowKey:(id)sender NS_REQUIRES_SUPER;

#pragma mark - Text Input Bar Adjustment
///------------------------------------------------
/// @name Text Input Bar Adjustment
///------------------------------------------------

/** YES if the text inputbar is hidden. Default is NO. */
@property (nonatomic, getter=isTextInputbarHidden) BOOL textInputbarHidden;

/**
 Changes the visibility of the text input bar.
 Calling this method with the animated parameter set to NO is equivalent to setting the value of the toolbarHidden property directly.

 @param hidden Specify YES to hide the toolbar or NO to show it.
 @param animated Specify YES if you want the toolbar to be animated on or off the screen.
 */
- (void)setTextInputbarHidden:(BOOL)hidden animated:(BOOL)animated;

#pragma mark - Text Edition
///------------------------------------------------
/// @name Text Edition
///------------------------------------------------

/** YES if the text editing mode is active. */
@property (nonatomic, readonly, getter = isEditing) BOOL editing;

/**
 Re-uses the text layout for edition, displaying an accessory view on top of the text input bar with options (cancel & save).
 You can override this method to perform additional tasks
 You MUST call super at some point in your implementation.

 @param text The string text to edit.
 */
- (void)editText:(NSString *)text NS_REQUIRES_SUPER;

/**
 Notifies the view controller when the editing bar's right button's action has been triggered, manually or by using the external keyboard's Return key.
 You can override this method to perform additional tasks associated with accepting changes.
 You MUST call super at some point in your implementation.

 @param sender The object calling this method.
 */
- (void)didCommitTextEditing:(id)sender NS_REQUIRES_SUPER;

/**
 Notifies the view controller when the editing bar's right button's action has been triggered, manually or by using the external keyboard's Esc key.
 You can override this method to perform additional tasks associated with accepting changes.
 You MUST call super at some point in your implementation.

 @param sender The object calling this method.
 */
- (void)didCancelTextEditing:(id)sender NS_REQUIRES_SUPER;

#pragma mark - Text Auto-Completion
///------------------------------------------------
/// @name Text Auto-Completion
///------------------------------------------------

/** The table view used to display autocompletion results. */
@property (nonatomic, readonly) UITableView *autoCompletionView;

/** YES if the autocompletion mode is active. */
@property (nonatomic, readonly, getter = isAutoCompleting) BOOL autoCompleting;

/** The recently found prefix symbol used as prefix for autocompletion mode. */
@property (nonatomic, readonly, copy) NSString *foundPrefix;

/** The range of the found prefix in the text view content. */
@property (nonatomic, readonly) NSRange foundPrefixRange;

/** The recently found word at the text view's caret position. */
@property (nonatomic, readonly, copy) NSString *foundWord;

/** An array containing all the registered prefix strings for autocompletion. */
@property (nonatomic, readonly, copy) NSArray *registeredPrefixes;

/**
 Registers any string prefix for autocompletion detection, useful for user mentions and/or hashtags autocompletion.
 The prefix must be valid string (i.e: '@', '#', '\', and so on). This also checks if no repeated prefix are inserted.
 Prefixes can be of any length.

 @param prefixes An array of prefix strings.
 */
- (void)registerPrefixesForAutoCompletion:(NSArray *)prefixes;

/**
 Notifies the view controller either the autocompletion prefix or word have changed.
 Use this method to modify your data source or fetch data asynchronously from an HTTP resource.
 Once your data source is ready, make sure to call -showAutoCompletionView: to display the view accordingly.
 You don't need call super since this method doesn't do anything.

 @param prefix The detected prefix.
 @param word The derected word.
 */
- (void)didChangeAutoCompletionPrefix:(NSString *)prefix andWord:(NSString *)word;

/**
 Use this method to programatically show/hide the autocompletion view.
 Right before the view is shown, -reloadData is called. So avoid calling it manually.

 @param show YES if the autocompletion view should be shown.
 */
- (void)showAutoCompletionView:(BOOL)show;

/**
 Verifies that the autocompletion view should be shown. Default is NO.
 To enabled autocompletion, you MUST override this method to perform additional tasks, before the autocompletion view is shown (i.e. populating the data source).

 @return YES if the autocompletion view should be shown.
 */
- (BOOL)canShowAutoCompletion DEPRECATED_MSG_ATTRIBUTE("Override -didChangeAutoCompletionPrefix:andWord: instead");

/**
 Returns a custom height for the autocompletion view. Default is 0.0.
 You can override this method to return a custom height.

 @return The autocompletion view's height.
 */
- (CGFloat)heightForAutoCompletionView;

/**
 Returns the maximum height for the autocompletion view. Default is 140 pts.
 You can override this method to return a custom max height.

 @return The autocompletion view's max height.
 */
- (CGFloat)maximumHeightForAutoCompletionView;

/**
 Cancels and hides the autocompletion view, animated.
 */
- (void)cancelAutoCompletion;

/**
 Accepts the autocompletion, replacing the detected word with a new string, keeping the prefix.
 This method is a convinience of -acceptAutoCompletionWithString:keepPrefix:

 @param string The string to be used for replacing autocompletion placeholders.
 */
- (void)acceptAutoCompletionWithString:(NSString *)string;

/**
 Accepts the autocompletion, replacing the detected word with a new string, and optionally replacing the prefix too.

 @param string The string to be used for replacing autocompletion placeholders.
 @param keepPrefix YES if the prefix shouldn't be overidden.
 */
- (void)acceptAutoCompletionWithString:(NSString *)string keepPrefix:(BOOL)keepPrefix;

#pragma mark - Text Caching
///------------------------------------------------
/// @name Text Caching
///------------------------------------------------

/**
 Returns the key to be associated with a given text to be cached. Default is nil.
 To enable text caching, you must override this method to return valid key.
 The text view will be populated automatically when the view controller is configured.
 You don't need to call super since this method doesn't do anything.

 @return The string key for which to enable text caching.
 */
- (NSString *)keyForTextCaching;

/**
 Removes the current's vien controller cached text.
 To enable this, you must return a valid key string in -keyForTextCaching.
 */
- (void)clearCachedText;

/**
 Removes all the cached text from disk.
 */
+ (void)clearAllCachedText;

#pragma mark - Customization
///------------------------------------------------
/// @name Customization
///------------------------------------------------

/**
 Registers a class for customizing the behavior and appearance of the text view.
 You need to call this method inside of any initialization method.

 @param aClass A SLKTextView subclass.
 */
- (void)registerClassForTextView:(Class)aClass;

/**
 Registers a class for customizing the behavior and appearance of the typing indicator view.
 You need to call this method inside of any initialization method.
 Make sure to conform to SLKTypingIndicatorProtocol and implement the required methods.

 @param aClass A UIView subclass conforming to the SLKTypingIndicatorProtocol.
 */
- (void)registerClassForTypingIndicatorView:(Class)aClass;

#pragma mark - Delegate Methods Requiring Super
///------------------------------------------------
/// @name Delegate Methods Requiring Super
///------------------------------------------------

/** SLKTextViewDelegate */
- (BOOL)textView:(SLKTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_REQUIRES_SUPER;
- (BOOL)textView:(SLKTextView *)textView shouldInsertSuffixForFormattingWithSymbol:(NSString *)symbol prefixRange:(NSRange)prefixRange NS_REQUIRES_SUPER;

/** UIScrollViewDelegate */
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView NS_REQUIRES_SUPER;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate NS_REQUIRES_SUPER;
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView NS_REQUIRES_SUPER;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView NS_REQUIRES_SUPER;

/** UIGestureRecognizerDelegate */
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer NS_REQUIRES_SUPER;

/** UIAlertViewDelegate */
#ifndef __IPHONE_8_0
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_REQUIRES_SUPER;
#endif

#pragma mark - Life Cycle Methods Requiring Super
///------------------------------------------------
/// @name Life Cycle Methods Requiring Super
///------------------------------------------------

/**
 Configures view hierarchy and layout constraints. If you override these methods, make sure to call super.
 */
- (void)loadView NS_REQUIRES_SUPER;
- (void)viewDidLoad NS_REQUIRES_SUPER;
- (void)viewWillAppear:(BOOL)animated NS_REQUIRES_SUPER;
- (void)viewDidAppear:(BOOL)animated NS_REQUIRES_SUPER;
- (void)viewWillDisappear:(BOOL)animated NS_REQUIRES_SUPER;
- (void)viewDidDisappear:(BOOL)animated NS_REQUIRES_SUPER;
- (void)viewWillLayoutSubviews NS_REQUIRES_SUPER;
- (void)viewDidLayoutSubviews NS_REQUIRES_SUPER;

@end


text:
package com.boldijarpaul.backend.servlets;

import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;

import entities.GcmData;
import entities.GcmModel;

@Path("/push")
public class PushServlet {

	private static final String GCM = "https://gcm-http.googleapis.com/gcm/send";
	private static OkHttpClient client = new OkHttpClient();

	private String sendNotification(String message) throws IOException {
		GcmModel gcmModel = new GcmModel("/topics/all", new GcmData(message));

		String json = new Gson().toJson(gcmModel);

		Request request = new Request.Builder()
				.addHeader("Authorization",
						"key=AIzaSyDLhXqM-Y-o46j_THzQY8QLCbN2lD7_4T4")
				.url(GCM)
				.post(RequestBody.create(
						MediaType.parse("application/json; charset=utf-8"),
						json)).build();
		return client.newCall(request).execute().body().string();
	}

	@GET
	@Path("")
	public String getText(@QueryParam("message") String message)
			throws IOException {
		return sendNotification(message == null ? "Hello!" : message);

	}
}


text:
Changelog
=========

## v2.0.3 - Nov 10, 2016

  * Add `:crypto` to the application list

## v2.0.0 - Aug 20, 2014

  * Fix a mistake in the message format used for sending output from the
    external process. The old format was

        {<pid>, :data, <data>}

    the new format is

        {<pid>, :data, :out | :err, <data>}

  * Add support for sending OS signals to external processes

## v1.1.3 - Aug 18, 2014

  * Fix issues with sending large inputs. There was a related issue in goon, so
    you'll need to update it to v1.0.2.

## v1.1.2 - Aug 4, 2014

  * support Elixir versions 0.14.3 up to 2.0.0

## v1.1.1 - Jul 14, 2014

  * add missing type for the `Result` struct (minor change)

## v1.1.0 - Jul 14, 2014

  * support files opened in raw mode for input and output
  * update for Elixir v0.14.3 by adding type definition for the `Process`
    struct

## v1.0.0 – Jun 21, 2014

  * initial release on hex.pm

## v1.0.0-beta – Jun 19, 2014

  * initial release


text:
```
sudo docker exec -i -t dockerfuse_jboss-fuse-redhat_1 bash
```

#Build
```
docker-compose -f dev.yml build
```

# Up
```
docker-compose -f dev.yml up
```


text:
import json
import logging
from typing import List
from typing import Optional

from click import Command
from click import Context
from click import Group
from click import argument
from click import group
from click import option
from click import pass_context

from repokid import CONFIG
from repokid import get_hooks
from repokid.commands.repo import _repo_all_roles
from repokid.commands.repo import _repo_role
from repokid.commands.repo import _repo_stats
from repokid.commands.repo import _rollback_role
from repokid.commands.role import _display_role
from repokid.commands.role import _display_roles
from repokid.commands.role import _find_roles_with_permissions
from repokid.commands.role import _remove_permissions_from_roles
from repokid.commands.role_cache import _update_role_cache
from repokid.commands.schedule import _cancel_scheduled_repo
from repokid.commands.schedule import _schedule_repo
from repokid.commands.schedule import _show_scheduled_roles
from repokid.types import RepokidConfig

logger = logging.getLogger("repokid")

def _generate_default_config(filename: str = "") -> RepokidConfig:
    """
    Generate and return a config dict; will write the config to a file if a filename is provided

    Args:
        filename (string): Name of file to write the generated config (represented in JSON)

    Returns:
        dict: Template for Repokid config as a dictionary
    """
    config_dict = {
        "query_role_data_in_batch": False,
        "batch_processing_size": 100,
        "filter_config": {
            "AgeFilter": {"minimum_age": 90},
            "BlocklistFilter": {
                "all": [],
                "blocklist_bucket": {
                    "bucket": "<BLOCKLIST_BUCKET>",
                    "key": "<PATH/blocklist.json>",
                    "account_number": "<S3_blocklist_account>",
                    "region": "<S3_blocklist_region",
                    "assume_role": "<S3_blocklist_assume_role>",
                },
            },
            "ExclusiveFilter": {
                "all": ["<GLOB_PATTERN>"],
                "<ACCOUNT_NUMBER>": ["<GLOB_PATTERN>"],
            },
        },
        "active_filters": [
            "repokid.filters.age:AgeFilter",
            "repokid.filters.lambda:LambdaFilter",
            "repokid.filters.blocklist:BlocklistFilter",
            "repokid.filters.optout:OptOutFilter",
        ],
        "aardvark_api_location": "<AARDVARK_API_LOCATION>",
        "connection_iam": {
            "assume_role": "RepokidRole",
            "session_name": "repokid",
            "region": "us-east-1",
        },
        "dynamo_db": {
            "assume_role": "RepokidRole",
            "account_number": "<DYNAMO_TABLE_ACCOUNT_NUMBER>",
            "endpoint": "<DYNAMO_TABLE_ENDPOINT (http://localhost:8000 if using docker compose)>",
            "region": "<DYNAMO_TABLE_REGION>",
            "session_name": "repokid",
        },
        "hooks": ["repokid.hooks.loggers"],
        "logging": {
            "version": 1,
            "disable_existing_loggers": "False",
            "formatters": {
                "standard": {
                    "format": "%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"
                },
                "json": {"class": "json_log_formatter.JSONFormatter"},
            },
            "handlers": {
                "file": {
                    "class": "logging.handlers.RotatingFileHandler",
                    "level": "INFO",
                    "formatter": "standard",
                    "filename": "repokid.log",
                    "maxBytes": 10485760,
                    "backupCount": 100,
                    "encoding": "utf8",
                },
                "json_file": {
                    "class": "logging.handlers.RotatingFileHandler",
                    "level": "INFO",
                    "formatter": "json",
                    "filename": "repokid.json",
                    "maxBytes": 10485760,
                    "backupCount": 100,
                    "encoding": "utf8",
                },
                "console": {
                    "class": "logging.StreamHandler",
                    "level": "INFO",
                    "formatter": "standard",
                    "stream": "ext://sys.stdout",
                },
            },
            "loggers": {
                "repokid": {
                    "handlers": ["file", "json_file", "console"],
                    "level": "INFO",
                }
            },
        },
        "opt_out_period_days": 90,
        "dispatcher": {
            "session_name": "repokid",
            "region": "us-west-2",
            "to_rr_queue": "COMMAND_QUEUE_TO_REPOKID_URL",
            "from_rr_sns": "RESPONSES_FROM_REPOKID_SNS_ARN",
        },
        "repo_requirements": {
            "oldest_aa_data_days": 5,
            "exclude_new_permissions_for_days": 14,
        },
        "repo_schedule_period_days": 7,
        "warnings": {"unknown_permissions": False},
    }
    if filename:
        try:
            with open(filename, "w") as f:
                json.dump(config_dict, f, indent=4, sort_keys=True)
        except OSError as e:
            print(f"Unable to open {filename} for writing: {e}")
        else:
            print(f"Successfully wrote sample config to {filename}")
    return config_dict

class AliasedGroup(Group):
    """AliasedGroup provides backward compatibility with the previous Repokid CLI commands"""

    def get_command(self, ctx: Context, cmd_name: str) -> Optional[Command]:
        rv = Group.get_command(self, ctx, cmd_name)
        if rv:
            return rv
        dashed = cmd_name.replace("_", "-")
        for cmd in self.list_commands(ctx):
            if cmd == dashed:
                return Group.get_command(self, ctx, cmd)
        return None

@group(cls=AliasedGroup)
@pass_context
def cli(ctx: Context) -> None:
    ctx.ensure_object(dict)

    if not CONFIG:
        config = _generate_default_config()
    else:
        config = CONFIG

    ctx.obj["config"] = config
    ctx.obj["hooks"] = get_hooks(config.get("hooks", ["repokid.hooks.loggers"]))

@cli.command()
@argument("filename")
@pass_context
def config(ctx: Context, filename: str) -> None:
    _generate_default_config(filename=filename)

@cli.command()
@argument("account_number")
@pass_context
def update_role_cache(ctx: Context, account_number: str) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    _update_role_cache(account_number, config, hooks)

@cli.command()
@argument("account_number")
@option("--inactive", is_flag=True, default=False, help="Include inactive roles")
@pass_context
def display_role_cache(ctx: Context, account_number: str, inactive: bool) -> None:
    _display_roles(account_number, inactive=inactive)

@cli.command()
@argument("permissions", nargs=-1)
@option("--output", "-o", required=False, help="File to write results to")
@pass_context
def find_roles_with_permissions(
    ctx: Context, permissions: List[str], output: str
) -> None:
    _find_roles_with_permissions(permissions, output)

@cli.command()
@argument("permissions", nargs=-1)
@option("--role-file", "-f", required=True, help="File to read roles from")
@option("--commit", "-c", is_flag=True, default=False, help="Commit changes")
@pass_context
def remove_permissions_from_roles(
    ctx: Context, permissions: List[str], role_file: str, commit: bool
) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    _remove_permissions_from_roles(permissions, role_file, config, hooks, commit=commit)

@cli.command()
@argument("account_number")
@argument("role_name")
@pass_context
def display_role(ctx: Context, account_number: str, role_name: str) -> None:
    config = ctx.obj["config"]
    _display_role(account_number, role_name, config)

@cli.command()
@argument("account_number")
@argument("role_name")
@option("--commit", "-c", is_flag=True, default=False, help="Commit changes")
@pass_context
def repo_role(ctx: Context, account_number: str, role_name: str, commit: bool) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    _repo_role(account_number, role_name, config, hooks, commit=commit)

@cli.command()
@argument("account_number")
@argument("role_name")
@option("--selection", "-s", required=True, type=int)
@option("--commit", "-c", is_flag=True, default=False, help="Commit changes")
@pass_context
def rollback_role(
    ctx: Context,
    account_number: str,
    role_name: str,
    selection: int,
    commit: bool,
) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    _rollback_role(
        account_number, role_name, config, hooks, selection=selection, commit=commit
    )

@cli.command()
@argument("account_number")
@option("--commit", "-c", is_flag=True, default=False, help="Commit changes")
@pass_context
def repo_all_roles(ctx: Context, account_number: str, commit: bool) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    logger.info("Updating role data")
    _update_role_cache(account_number, config, hooks)
    _repo_all_roles(account_number, config, hooks, commit=commit, scheduled=False)

@cli.command()
@argument("account_number")
@pass_context
def schedule_repo(ctx: Context, account_number: str) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    logger.info("Updating role data")
    _update_role_cache(account_number, config, hooks)
    _schedule_repo(account_number, config, hooks)

@cli.command()
@argument("account_number")
@pass_context
def show_scheduled_roles(ctx: Context, account_number: str) -> None:
    _show_scheduled_roles(account_number)

@cli.command()
@argument("account_number")
@option("--role", "-r", required=False, type=str)
@option("--all", "-a", is_flag=True, default=False, help="cancel for all roles")
@pass_context
def cancel_scheduled_repo(
    ctx: Context, account_number: str, role: str, all: bool
) -> None:
    _cancel_scheduled_repo(account_number, role_name=role, is_all=all)

@cli.command()
@argument("account_number")
@option("--commit", "-c", is_flag=True, default=False, help="Commit changes")
@pass_context
def repo_scheduled_roles(ctx: Context, account_number: str, commit: bool) -> None:
    config = ctx.obj["config"]
    hooks = ctx.obj["hooks"]
    _update_role_cache(account_number, config, hooks)
    _repo_all_roles(account_number, config, hooks, commit=commit, scheduled=True)

@cli.command()
@argument("account_number")
@option("--output", "-o", required=True, help="File to write results to")
@pass_context
def repo_stats(ctx: Context, account_number: str, output: str) -> None:
    _repo_stats(output, account_number=account_number)

if __name__ == "__main__":
    cli()


text:
<?php
/**
 *  * Created by mtils on 27.01.18 at 15:54.
 **/

namespace Ems\Queue;

use DateTime;
use Ems\Contracts\Queue\Job;
use Ems\Contracts\Queue\Queue as QueueContract;
use Ems\Contracts\Queue\Driver;
use Ems\Queue\Drivers\NullDriver;
use Ems\TestCase;

class QueueTest extends TestCase
{
    public function test_implements_interface()
    {
        $this->assertInstanceOf(QueueContract::class, $this->newQueue());
    }

    public function test_run_creates_job()
    {
        $queue = $this->newQueue();

        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $this->assertEquals(0, $queue->count());
        $job = $queue->run($operation, $args, $handle);

        $this->assertEquals(1, $queue->count());

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::QUEUED, $job->state());

        $this->assertEquals([Queue::$defaultChannel], $queue->channelNames());

        $this->assertEquals([$job], $queue->all());
    }

    public function test_at_sets_plannedStart()
    {
        $queue = $this->newQueue();

        $date = new DateTime('2017-12-01 00:00:00');
        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $job = $queue->at($date)->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::QUEUED, $job->state());

        $this->assertEquals($date, $job->plannedStart());
    }

    public function test_at_sets_plannedStart_by_planned_start()
    {
        $queue = $this->newQueue();

        $start = '+1 day';
        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $job = $queue->at($start)->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::QUEUED, $job->state());

        $this->assertGreaterThan(new DateTime(), $job->plannedStart());
    }

    public function test_tries_sets_maxTries()
    {
        $queue = $this->newQueue();

        $tries = 16;
        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $job = $queue->tries($tries)->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::QUEUED, $job->state());

        $this->assertEquals($tries, $job->maxTries());
    }

    public function test_timeout_sets_timeout()
    {
        $queue = $this->newQueue();

        $timeout = 86400;
        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $job = $queue->timeout($timeout)->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::QUEUED, $job->state());

        $this->assertEquals($timeout, $job->timeout());
    }

    public function test_channel_sets_channel()
    {
        $otherChannel = $this->mock(Driver::class);

        $queue = $this->newQueue();
        $this->assertSame($queue, $queue->addChannel('local', $otherChannel));

        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $otherChannel->shouldReceive('push')
                     ->once()
                     ->andReturn(Queue::RUNNING);

        $job = $queue->onChannel('local')->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::RUNNING, $job->state());

        $this->assertEquals('local', $job->channelName());

        $otherChannel->shouldReceive('pop')
                     ->with('local')
                     ->andReturn($job);

        $this->assertSame($job, $queue->pop('local'));
    }

    public function test_channel_sets_channel_on_proxy()
    {
        $otherChannel = $this->mock(Driver::class);

        $queue = $this->newQueue();
        $this->assertSame($queue, $queue->addChannel('local', $otherChannel));

        $operation = [QueueTest::class, 'nullDriver'];
        $args = [1, 2];
        $handle = 'handle';

        $otherChannel->shouldReceive('push')
            ->once()
            ->andReturn(Queue::RUNNING);

        $job = $queue->onChannel('local')->run($operation, $args, $handle);

        $this->assertInstanceOf(Job::class, $job);
        $this->assertEquals($operation, $job->operation());
        $this->assertEquals($args, $job->arguments());
        $this->assertEquals(QueueContract::RUNNING, $job->state());

        $this->assertEquals('local', $job->channelName());

        $otherChannel->shouldReceive('pop')
            ->with('local')
            ->andReturn($job);

        $this->assertSame($job, $queue->timeout(6000)->pop('local'));
    }

    public function test_addChannel_on_proxy()
    {
        $otherChannel = $this->mock(Driver::class);

        $queue = $this->newQueue()->timeout(8000);
        $this->assertSame($queue, $queue->addChannel('local', $otherChannel));
        $this->assertEquals(['default', 'local'], $queue->channelNames());
    }

    public function test_removeChannel_removes_channel()
    {
        $queue = $this->newQueue();
        $this->assertSame($queue, $queue->addChannel('remote', $this->nullDriver()));

        $this->assertEquals([Queue::$defaultChannel, 'remote'], $queue->channelNames());
        $this->assertSame($queue, $queue->removeChannel('remote'));
        $this->assertEquals([Queue::$defaultChannel], $queue->channelNames());
    }

    public function test_removeChannel_on_proxy()
    {
        $otherChannel = $this->mock(Driver::class);

        $queue = $this->newQueue()->timeout(8000);
        $this->assertSame($queue, $queue->addChannel('local', $otherChannel));
        $this->assertEquals(['default', 'local'], $queue->channelNames());
        $this->assertSame($queue, $queue->removeChannel('local'));
        $this->assertEquals(['default'], $queue->channelNames());
    }

    public function test_count_on_proxy()
    {
        $queue = $this->newQueue()->timeout(8000);
        $this->assertEquals(0, $queue->count());
    }

    public function test_all_on_proxy()
    {
        $queue = $this->newQueue()->timeout(8000);
        $this->assertEquals([], $queue->all());
    }

    /**
     * @expectedException \Ems\Contracts\Core\Errors\NotFound
     */
    public function test_push_to_unknown_channel_throws_exception()
    {
        $queue = $this->newQueue();
        $queue->onChannel('foo')->run('strpos');
    }

    protected function newQueue(Driver $driver=null)
    {
        return new Queue($driver ?: $this->nullDriver());
    }

    protected function nullDriver()
    {
        return new NullDriver();
    }
}