text:
GUI: Dymki chatu nad glowami graczy

@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.psz-gui
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>

Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.

]]--
local selfVisible = false
local screenX, screenY = guiGetScreenSize()
local messages = {} -- {text, player, lastTick, alpha, yPos}
local timeVisible = 5500
local distanceVisible = 90
local bubble = false -- Rounded rectangle(true) or not(false)

function addBubble(text, player, tick)
    if (not messages[player]) then
        messages[player] = {}
    end
    table.insert(messages[player], {["text"] = text, ["player"] = player, ["tick"] = tick, ["endTime"] = tick + 2000, ["alpha"] = 0})
end

function removeBubble()
    table.remove(messages)
end

addEvent("onChatIncome", true)
addEventHandler("onChatIncome", root,
    function(message, messagetype)
        if source ~= localPlayer then
        addBubble(message, source, getTickCount())
        elseif selfVisible then
        addBubble(message, source, getTickCount())
    end
end
)

addEventHandler("onClientRender", root,
    function()
        local tick = getTickCount()
        local x, y, z = getElementPosition(localPlayer)
        for _, pMessage in pairs(messages) do
            for i, v in ipairs(pMessage) do
                if isElement(v.player) then
                    if tick-v.tick < timeVisible then
                        local px, py, pz = getElementPosition(v.player)
                        if getDistanceBetweenPoints3D(x, y, z, px, py, pz) < distanceVisible and isLineOfSightClear ( x, y, z, px, py, pz, true, not isPedInVehicle(v.player), false, true) and getElementInterior(v.player) == getElementInterior(localPlayer) and getElementDimension(v.player) == getElementDimension(localPlayer) then
                            v.alpha = v.alpha < 200 and v.alpha + 5 or v.alpha
                            local bx, by, bz = getPedBonePosition(v.player, 6)
                            local sx, sy = getScreenFromWorldPosition(bx, by, bz)

                            local elapsedTime = tick - v.tick
                            local duration = v.endTime - v.tick
                            local progress = elapsedTime / duration

                            if sx and sy then
                                if not v.yPos then v.yPos = sy end
                                local width = dxGetTextWidth(v.text:gsub("#%x%x%x%x%x%x", ""), 1, "default-bold")
                                local yPos = interpolateBetween ( v.yPos, 0, 0, sy - 22*i, 0, 0, progress, progress > 1 and "Linear" or "OutElastic")
                                if bubble then
                                    local i
                                    if width < 100 then
                                        i = 2
                                    elseif width > 100 and width < 400 then
                                        i = 1
                                    else
                                        i = 3
                                    end
                                    dxDrawImage ( sx-width/2-.01*screenX, yPos - .03*screenY, width+.02*screenX, 20, "images/bubble["..i.."].png", _, _, tocolor(255, 255, 255, v.alpha) )
                                else
                                    dxDrawRectangle(sx-width/2-.01*screenX, yPos - .03*screenY, width+.02*screenX, 20, tocolor(0,0,0, v.alpha+200))
                                end
                                dxDrawText(v.text, sx-width/2, yPos - .03*screenY, width, 20, tocolor( 255,255,255, v.alpha+50), 1, "default-bold", "left", "top", false, false, false, true)
                            end
                        end
                    else
                        table.remove(messages[v.player], i)
                    end
                else
                    table.remove(messages[v.player], i)
                end
            end
        end
    end
)


text:
package org.metaborg.parsetable.actions;

import org.metaborg.parsetable.productions.IProduction;
import org.metaborg.parsetable.productions.ProductionType;
import org.metaborg.parsetable.characterclasses.ICharacterClass;

public interface IActionsFactory {

    IShift getShift(int shiftStateId);

    IReduce getReduce(IProduction production, ProductionType productionType, int arity);

    IReduceLookahead getReduceLookahead(IProduction production, ProductionType productionType, int arity,
        ICharacterClass[] followRestriction);

    IAccept getAccept();

}

redpajama_set_name: RedPajamaGithub


text:
title: Asset Pipeline - Modern Frontend Development
author:
  name: Carsten Lamm
  github: https://github.com/FQ400
  url: http://www.kontextr.com
output: basic.html
--

# Asset Pipeline
## Modern Frontend Development
## by Carsten Lamm

--

### table of content

1. Background _(1)_
1. Frontend Definition _(1)_
1. Asset Pipeline? _(1)_
1. Tools _(3)_
1. Types _(1)_
1. Basic Setup _(1)_
1. Extended Setup _(2)_
1. Done _(1)_
1. Sources _(1)_

--

### My Background

- started with Rails 2 up to Rails 3 (~3 years)
- **S**ingle **P**age **A**pplications using REST-APIs
  - AngularJS (~2 year)
- node and React (~1 year)
- now back to Rails 4

--

### Frontend Development means ...

... building web applications with UI
... for mobile/desktop devices with/without touch
... with different screen resolutions.

... also use build tools to optimize performance.

... automatically test your code and layouts.

... tracking and AB-Tests.
...

--

### Asset Pipeline ...

... is a mighty building tool
... which combines and compresses assets.

... super integrated into Rails via gem.

... produces assets marked with hashes.

... provides the easiest way to invoke multiple parser.
`   => application.css.scss.erb`

--

### some Tools

[node](https://nodejs.org/en/) - Javascript on the server
[npm](https://www.npmjs.com/) - Node Package Manager including package.json
[grunt](http://gruntjs.com/) - Asset build tool - JSON based
[gulp](https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md) - Asset build tool - stream based
[bower](http://bower.io/) - Package Manager for Javascript & CSS libs
[webpack](https://webpack.github.io/) - Asset build tool - works fine with babel/ES2015
[EcmaScript 2015](https://github.com/lukehoban/es6features) - latest Javascript, needs to be transpiled (source-to-source)
[babel](https://babeljs.io/) - Javascript compiler for ES2015
[bundler](http://bundler.io/) - Ruby Package Manager
[Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html) - Asset build tool - sprockets based

--

### grouped tools

![](./grouped_tools.jpg)

--

## Confusion by google: rails + ______

- rails webpack
- rails gulp
- rails ES6

--

### kind of web app

- API/multiple clients - SPA
- (no) API/one client
- enterprise app / small website
- progressive enhancement vs graceful degradation

--

### Basic Setup

- bundler for ruby dependencies
- (bower for CSS/JS dependencies) => [rails-assets.org](rails-assets.org)

**Gemfile**
`source 'https://rails-assets.org'`
`gem 'rails-assets-lodash'`

**Assets**
`//= lodash`
`//= require_tree .`

--

### extended setup ES2015 / ES6

**npm >= v3**
`npm install babel-preset-es2015 --save-dev`

**.babelrc**
`{ "presets": ["es2015"] }`

**Gemfile**
`gem sprockets-es6`

**initializer/es6.rb**
`require "sprockets/es6"`

--

### Done - can be used

- all files like `*.js.es6` are found
- can be access via `//= require class_es6` directive

**open point**
- es2015 for inline scripts
- es2015 modules
  - defined but not implemented

--
### Sources

[Wiki Compiler](https://en.wikipedia.org/wiki/Source-to-source_compiler)
[Standard ECMA-262 6th Edition / June 2015](http://www.ecma-international.org/ecma-262/6.0/)
[Cleaver](https://www.npmjs.com/package/cleaver)
[Sprockets](https://github.com/rails/sprockets)
[Progressive Enhancement](https://en.wikipedia.org/wiki/Progressive_enhancement)
[Graceful Degradation](https://en.wikipedia.org/wiki/Fault_tolerance)
[Babel Rails](https://babeljs.io/docs/setup/#rails)


text:
var React = require('react');
var metrika = require('./metrika.js');

module.exports = React.createClass({
    perform_action: function(action) {        // performing action [action] @buttons.skip
        $.ajax({
            url: '/v1/changelogs/' + this.props.changelog_id + '/' + action + '/',
            method: 'POST',
            dataType: 'json',
            headers: {'X-CSRFToken': $.cookie('csrftoken')},
            success: function(data) {
                metrika.reach_goal(action.toUpperCase());

                if (this.props.on_skip !== undefined) {
                    this.props.on_skip();
                }
            }.bind(this),
            error: function(xhr, status, err) {
                console.error('Unable to perform action ' + action + ' on changelog', status, err.toString());
            }.bind(this)
        });
    },
    skip: function (e) {
        e.preventDefault();
        this.perform_action('skip', true);
    },
    handle_popup_click: function (e) {
        // popup click @buttons.report
        e.nativeEvent.stopImmediatePropagation();
    },
    render: function() {
        return (<div className="skip-button">
                    <button className="button"
                            onClick={this.skip}
                            title="Click me to show next package.">Show next</button>
                </div>);
    }
});


text:
#ifndef _TIMB_RADIO_
#define _TIMB_RADIO_ 1

#include <linux/i2c.h>

struct timb_radio_platform_data {
	int i2c_adapter; /* I2C adapter where the tuner and dsp are attached */
	struct i2c_board_info *tuner;
	struct i2c_board_info *dsp;
};

#endif


text:
package prometheus

import (
	"sync"

	"github.com/prometheus/client_golang/prometheus"
)

// metricFamily stores our cached metrics:
type metricFamily struct {
	counters           map[string]*prometheus.CounterVec
	gauges             map[string]*prometheus.GaugeVec
	timings            map[string]*prometheus.SummaryVec
	defaultLabels      prometheus.Labels
	mutex              sync.Mutex
	prometheusRegistry *prometheus.Registry
	timingObjectives   map[float64]float64
}

// newMetricFamily returns a new metricFamily (useful in case we want to change the structure later):
func (r *Reporter) newMetricFamily() metricFamily {

	// Take quantile thresholds from our pre-defined list:
	timingObjectives := make(map[float64]float64)
	for _, percentile := range r.options.Percentiles {
		if quantileThreshold, ok := quantileThresholds[percentile]; ok {
			timingObjectives[percentile] = quantileThreshold
		}
	}

	return metricFamily{
		counters:           make(map[string]*prometheus.CounterVec),
		gauges:             make(map[string]*prometheus.GaugeVec),
		timings:            make(map[string]*prometheus.SummaryVec),
		defaultLabels:      r.convertTags(r.options.DefaultTags),
		prometheusRegistry: r.prometheusRegistry,
		timingObjectives:   timingObjectives,
	}
}

// getCounter either gets a counter, or makes a new one:
func (mf *metricFamily) getCounter(name string, labelNames []string) *prometheus.CounterVec {
	mf.mutex.Lock()
	defer mf.mutex.Unlock()

	// See if we already have this counter:
	counter, ok := mf.counters[name]
	if !ok {

		// Make a new counter:
		counter = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name:        name,
				ConstLabels: mf.defaultLabels,
			},
			labelNames,
		)

		// Register it and add it to our list:
		mf.prometheusRegistry.MustRegister(counter)
		mf.counters[name] = counter
	}

	return counter
}

// getGauge either gets a gauge, or makes a new one:
func (mf *metricFamily) getGauge(name string, labelNames []string) *prometheus.GaugeVec {
	mf.mutex.Lock()
	defer mf.mutex.Unlock()

	// See if we already have this gauge:
	gauge, ok := mf.gauges[name]
	if !ok {

		// Make a new gauge:
		gauge = prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name:        name,
				ConstLabels: mf.defaultLabels,
			},
			labelNames,
		)

		// Register it and add it to our list:
		mf.prometheusRegistry.MustRegister(gauge)
		mf.gauges[name] = gauge
	}

	return gauge
}

// getTiming either gets a timing, or makes a new one:
func (mf *metricFamily) getTiming(name string, labelNames []string) *prometheus.SummaryVec {
	mf.mutex.Lock()
	defer mf.mutex.Unlock()

	// See if we already have this timing:
	timing, ok := mf.timings[name]
	if !ok {

		// Make a new timing:
		timing = prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Name:        name,
				ConstLabels: mf.defaultLabels,
				Objectives:  mf.timingObjectives,
			},
			labelNames,
		)

		// Register it and add it to our list:
		mf.prometheusRegistry.MustRegister(timing)
		mf.timings[name] = timing
	}

	return timing
}


text:
module Breeze
  module Gallery
    class Gallery
      include Mongoid::Document
      identity :type => String

      field :title
      field :description

      field :full_width, type: Integer
      field :full_height, type: Integer
      field :thumb_width, type: Integer
      field :thumb_height, type: Integer
      field :preview_width, type: Integer
      field :preview_height, type: Integer

      has_many_related :images, :class_name => "Breeze::Gallery::Image"

      validates_presence_of :title
      validates_uniqueness_of :title
    end
  end
end


text:
namespace OpenQA.Selenium.DevTools.Console
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Represents an adapter for the Console domain to simplify the command interface.
    /// </summary>
    public class ConsoleAdapter
    {
        private readonly DevToolsSession m_session;
        private readonly string m_domainName = "Console";
        private Dictionary<string, DevToolsEventData> m_eventMap = new Dictionary<string, DevToolsEventData>();

        public ConsoleAdapter(DevToolsSession session)
        {
            m_session = session ?? throw new ArgumentNullException(nameof(session));
            m_session.DevToolsEventReceived += OnDevToolsEventReceived;
            m_eventMap["messageAdded"] = new DevToolsEventData(typeof(MessageAddedEventArgs), OnMessageAdded);
        }

        /// <summary>
        /// Gets the DevToolsSession associated with the adapter.
        /// </summary>
        public DevToolsSession Session
        {
            get { return m_session; }
        }

        /// <summary>
        /// Issued when new console message is added.
        /// </summary>
        public event EventHandler<MessageAddedEventArgs> MessageAdded;

        /// <summary>
        /// Does nothing.
        /// </summary>
        public async Task<ClearMessagesCommandResponse> ClearMessages(ClearMessagesCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ClearMessagesCommandSettings, ClearMessagesCommandResponse>(command ?? new ClearMessagesCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Disables console domain, prevents further console messages from being reported to the client.
        /// </summary>
        public async Task<DisableCommandResponse> Disable(DisableCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<DisableCommandSettings, DisableCommandResponse>(command ?? new DisableCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Enables console domain, sends the messages collected so far to the client by means of the
        /// `messageAdded` notification.
        /// </summary>
        public async Task<EnableCommandResponse> Enable(EnableCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<EnableCommandSettings, EnableCommandResponse>(command ?? new EnableCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }

        private void OnDevToolsEventReceived(object sender, DevToolsEventReceivedEventArgs e)
        {
            if (e.DomainName == m_domainName)
            {
                if (m_eventMap.ContainsKey(e.EventName))
                {
                    var eventData = m_eventMap[e.EventName];
                    var eventArgs = e.EventData.ToObject(eventData.EventArgsType);
                    eventData.EventInvoker(eventArgs);
                }
            }
        }

        private void OnMessageAdded(object rawEventArgs)
        {
            MessageAddedEventArgs e = rawEventArgs as MessageAddedEventArgs;
            if (e != null && MessageAdded != null)
            {
                MessageAdded(this, e);
            }
        }
    }
}


text:
if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
  echo -e "Building and committing dist and docs...\n"

  TEMP_DIR=$HOME/tmp
  FALCOR_DOCS_DIR=$TEMP_DIR/falcordocs
  FALCOR_BUILD_DIR=$TEMP_DIR/falcorbuild
  GH_PAGES_DIR=$TEMP_DIR/gh-pages
  DEPLOYABLE_REPO=git@github.com:Netflix/falcor.git
  CURRENT_RELEASE=master

  mkdir -p $TEMP_DIR

  if [ -d "$FALCOR_BUILD_DIR" ]; then
    rm -rf $FALCOR_BUILD_DIR
  fi

  if [ -d "$FALCOR_DOCS_DIR" ]; then
    rm -rf $FALCOR_DOCS_DIR
  fi

  if [ -d "$GH_PAGES_DIR" ]; then
    rm -rf $GH_PAGES_DIR
  fi

  git config --global user.email "falcorbuild@netflix.com"
  git config --global user.name "Falcor Build"

  openssl aes-256-cbc -K $encrypted_00000eb5a141_key -iv $encrypted_00000eb5a141_iv -in deployKey.enc -out deployKey -d
  chmod 0600 deployKey
  eval `ssh-agent -s`
  ssh-add deployKey

  # Need https url to push changes, and also need to move from detached head to built branch.
  git remote add deployable $DEPLOYABLE_REPO
  git checkout $TRAVIS_BRANCH

  # Generate Docs
  npm run doc
  npm run dist

  git add dist/.
  git add doc/.
  git commit -m "Travis build $TRAVIS_BUILD_NUMBER committed dist/ and doc/"
  git push deployable $TRAVIS_BRANCH

  if [ "$TRAVIS_BRANCH" == "$CURRENT_RELEASE" ]; then

    echo -e "Updating gh-pages...\n"

    cp -R doc $FALCOR_DOCS_DIR
    cp -R dist $FALCOR_BUILD_DIR

    # Change Working Directory to $HOME
    cd $HOME

    git clone --quiet --branch=gh-pages $DEPLOYABLE_REPO $GH_PAGES_DIR > /dev/null

    # Change Working Directory to $HOME/gh-pages
    cd $GH_PAGES_DIR

    rsync -r $FALCOR_DOCS_DIR/ doc/
    rsync -r $FALCOR_BUILD_DIR/ build/

    git add .
    git commit -m "Travis build $TRAVIS_BUILD_NUMBER off $TRAVIS_BRANCH pushed to gh-pages"
    git push origin gh-pages

    echo -e "Deployed docs and build to gh-pages\n"
  fi
fi


text:
This gem is a wrapper for the [Charist.js](https://github.com/gionkunz/chartist-js) library.
The state of this gem is that it is fully functional, but you can not change the settings yet.
I am currently working on a generator so that you can customize the settings file to your liking.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'chartist-rails'
```

## Usage

Add this to your `app/assets/javascripts/application.js.coffee`:

```
#= require chartist
```

Or if you're using pure javascript, add this to your `app/assets/javascripts/application.js`:

```
//= require chartist
```

Then add this to your `app/assets/stylesheets/applcation.css`:

```
*= require chartist.min
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/chartist-rails/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
@import '..';

.highlighted_well {
  stroke: var(--c-highlight);
  fill: color-mod(var(--c-highlight) alpha(20%));
}

.selected_well {
  stroke: var(--c-highlight);
  fill: transparent;
}

.missing_tip {
  stroke: var(--c-near-black);
  fill: var(--c-light-gray);
}


text:
set(CMAKE_Fortran_VERBOSE_FLAG "-v")
set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-fixed")
set(CMAKE_Fortran_FORMAT_FREE_FLAG "-free")

set(CMAKE_Fortran_COMPILE_OPTIONS_PIC "-KPIC")
set(CMAKE_SHARED_LIBRARY_Fortran_FLAGS "-KPIC")
set(CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS "-G")
set(CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG "-R")
set(CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG_SEP ":")
set(CMAKE_SHARED_LIBRARY_SONAME_Fortran_FLAG "-h")
set(CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG "-R")

set(CMAKE_Fortran_FLAGS_INIT "")
set(CMAKE_Fortran_FLAGS_DEBUG_INIT "-g")
set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "-xO2 -xspace -DNDEBUG")
set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-xO3 -DNDEBUG")
set(CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "-g -xO2 -DNDEBUG")
set(CMAKE_Fortran_MODDIR_FLAG "-moddir=")
set(CMAKE_Fortran_MODPATH_FLAG "-M")

set(CMAKE_Fortran_CREATE_PREPROCESSED_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <FLAGS> -F <SOURCE> -o <PREPROCESSED_SOURCE>")
set(CMAKE_Fortran_CREATE_ASSEMBLY_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")


text:
"use strict";

class MouseEvents extends Implementations {
	static implement() {
		_selectors.control_button.on(_utils.click, MouseEvents.control_button_click);
		_selectors.got_it_button.on(_utils.click, MouseEvents.got_it_button_click);

		_selectors.play_wrapper.on(_utils.click, _selectors_string.play_button + _selectors_string.not_disabled, MouseEvents.play_button_click);
		_selectors.play_wrapper.on(_utils.click, _selectors_string.pause_button + _selectors_string.not_disabled, MouseEvents.pause_button_click);
		_selectors.play_wrapper.on(_utils.click, _selectors_string.stop_button + _selectors_string.not_disabled, MouseEvents.stop_button_click);
	}
}


text:
static bool storage_ok = false;

static uint32_t custom_fonts[] = {
    PBL_IF_ROUND_ELSE(RESOURCE_ID_NEPTUN_56, RESOURCE_ID_NEPTUN_48), PBL_IF_ROUND_ELSE(RESOURCE_ID_TIMEPIECE_50, RESOURCE_ID_TIMEPIECE_43),
    PBL_IF_ROUND_ELSE(RESOURCE_ID_ALANDEN_65, RESOURCE_ID_ALANDEN_56), RESOURCE_ID_KOMIKA_BOOGIE_48
};

//Singleton. Shoot me.
Settings settings;

static GColor set_colour(DictionaryIterator *iter, int key) {
    Tuple *colour = dict_find(iter, key);
    GColor result = GColorWhite;
    if(colour) {
        int colour_value = colour->value->int32;
        result = GColorFromHEX(colour_value);
        persist_write_int(key, colour_value);
        APP_LOG(APP_LOG_LEVEL_DEBUG, "Setting colour to %X", colour_value);
    } else {
        APP_LOG(APP_LOG_LEVEL_ERROR, "Problem with colour");
    }
    return result;
}

static GColor persist_read_colour(int key, GColor def) {
    int colour_value = persist_read_int(key);
    if(!storage_ok || !persist_exists(key) || colour_value < 0 || colour_value > 16777215) {
        APP_LOG(APP_LOG_LEVEL_ERROR, "Cannot set colour to %X", colour_value);
        return def;
    }
    return GColorFromHEX(colour_value);
}

static bool persist_read_bool_def(int key, bool def) {
    if(!storage_ok || !persist_exists(key))
        return def;
    return persist_read_bool(key);
}

static int persist_read_int_def(int key, int def, int min, int max) {
    if(!storage_ok || !persist_exists(key))
        return def;
    int val = persist_read_int(key);
    APP_LOG(APP_LOG_LEVEL_DEBUG, "Val %d", val);
    if(val < min) return min;
    if(val > max) return max;
    return val;
}

static int8_t font_offset(int id) {
    if(id == 3) return 10;
    #ifdef PBL_ROUND
    if(id==1) return -5;
    if(id==2) return -10;
    #endif
    return 0;
}

void update_settings(DictionaryIterator *iterator) {
    //perhaps settings
    storage_ok = true;
    persist_write_int(KEY_STORAGE_OK, KEY_STORAGE_OK);

    settings.bg = set_colour(iterator, KEY_BG);
    settings.colours[0] = set_colour(iterator, KEY_C1);
    settings.colours[1] = set_colour(iterator, KEY_C2);
    settings.colours[2] = set_colour(iterator, KEY_C3);
    settings.colours[3] = set_colour(iterator, KEY_C4);
    settings.colours[4] = set_colour(iterator, KEY_C5);
    settings.fg = set_colour(iterator, KEY_FG);

    fonts_unload_custom_font(settings.font_main_big);
    int font_id = dict_find(iterator, KEY_FONT)->value->int8;
    settings.font_main_big = fonts_load_custom_font(resource_get_handle(custom_fonts[font_id]));
    persist_write_int(KEY_FONT, font_id);
    settings.font_big_y_offset = font_offset(font_id);

    bool size = dict_find(iterator, KEY_SIZE_DATE)->value->int8 == 1;
    persist_write_bool(KEY_SIZE_DATE, size);
    settings.font_date = fonts_get_system_font(size ? FONT_KEY_GOTHIC_14 : FONT_KEY_GOTHIC_24_BOLD);

    size = dict_find(iterator, KEY_SIZE_WEATHER)->value->int8 == 1;
    persist_write_bool(KEY_SIZE_WEATHER, size);
    settings.font_temp = fonts_get_system_font(size ? FONT_KEY_GOTHIC_24_BOLD : FONT_KEY_GOTHIC_14);

    settings.disco_vibrate = dict_find(iterator, KEY_DISCO_VIBRATE)->value->int8 == 1;
    persist_write_bool(KEY_DISCO_VIBRATE, settings.disco_vibrate);

    settings.disco_desaturate = dict_find(iterator, KEY_DESATURATE)->value->int8 == 1;
    persist_write_bool(KEY_DESATURATE, settings.disco_desaturate);

    settings.show_weather = dict_find(iterator, KEY_WEATHER)->value->int8 == 1;
    persist_write_bool(KEY_WEATHER, settings.show_weather);

    settings.show_date = dict_find(iterator, KEY_DATE)->value->int8 == 1;
    persist_write_bool(KEY_DATE, settings.show_date);

    settings.fahrenheit = dict_find(iterator, KEY_TEMP_UNITS_F)->value->int8 == 1;
    persist_write_bool(KEY_TEMP_UNITS_F, settings.fahrenheit);

    settings.num_colours = dict_find(iterator, KEY_N_COLOURS)->value->int8;
    persist_write_int(KEY_N_COLOURS, settings.num_colours);
}

void init_settings() {
    int font_id = 0;
    if(persist_exists(KEY_STORAGE_OK) && persist_read_int(KEY_STORAGE_OK) == KEY_STORAGE_OK) {
        APP_LOG(APP_LOG_LEVEL_DEBUG, "Reading from storage");
        storage_ok = true; //else storage empty or corrupt
        font_id = persist_read_int(KEY_FONT);
    } else {
        APP_LOG(APP_LOG_LEVEL_DEBUG, "No stored settings");
    }
    settings = (Settings) {
        .bg = persist_read_colour(KEY_BG, DEF_BG),
        .fg = persist_read_colour(KEY_FG, DEF_FG),
        //Settings
        .disco_vibrate = persist_read_bool_def(KEY_DISCO_VIBRATE, true),
        .disco_desaturate = persist_read_bool_def(KEY_DESATURATE, true),
        .show_weather = persist_read_bool_def(KEY_WEATHER, true),
        .show_date = persist_read_bool_def(KEY_DATE, true),
        .fahrenheit = persist_read_bool_def(KEY_TEMP_UNITS_F, false),
        //Fonts
        .font_main_big = fonts_load_custom_font(resource_get_handle(custom_fonts[font_id])),
        .font_big_y_offset = font_offset(font_id),
        .font_date = fonts_get_system_font(persist_read_bool_def(KEY_SIZE_DATE, false) ?
                                           FONT_KEY_GOTHIC_14 : FONT_KEY_GOTHIC_24_BOLD),
        .font_temp = fonts_get_system_font(persist_read_bool_def(KEY_SIZE_WEATHER, false) ?
                                           FONT_KEY_GOTHIC_24_BOLD : FONT_KEY_GOTHIC_14),
        .num_colours = persist_read_int_def(KEY_N_COLOURS, DEF_N_COLOURS, 3, 5)
    };
    //Ribbon Colours
    settings.colours[0] = persist_read_colour(KEY_C1, DEF_C1);
    settings.colours[1] = persist_read_colour(KEY_C2, DEF_C2);
    settings.colours[2] = persist_read_colour(KEY_C3, DEF_C3);
    settings.colours[3] = persist_read_colour(KEY_C4, DEF_C4);
    settings.colours[4] = persist_read_colour(KEY_C5, DEF_C5);
}

void destroy_settings() {
    fonts_unload_custom_font(settings.font_main_big);
}


text:
package com.google.idea.blaze.base.lang.buildfile.psi;

import com.google.idea.blaze.base.lang.buildfile.psi.Argument.Keyword;
import com.google.idea.blaze.base.lang.buildfile.psi.util.PsiUtils;
import com.google.idea.blaze.base.lang.buildfile.references.AttributeSpecificStringLiteralReferenceProvider;
import com.google.idea.blaze.base.lang.buildfile.references.ExternalWorkspaceReferenceFragment;
import com.google.idea.blaze.base.lang.buildfile.references.LabelReference;
import com.google.idea.blaze.base.lang.buildfile.references.LoadedSymbolReference;
import com.google.idea.blaze.base.lang.buildfile.references.PackageReferenceFragment;
import com.google.idea.blaze.base.lang.buildfile.references.QuoteType;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import javax.annotation.Nullable;

/** PSI node for string literal expressions */
public class StringLiteral extends BuildElementImpl implements LiteralExpression {

  /**
   * Removes the leading and trailing quotes. Naive implementation intended for resolving references
   * (in which case escaped characters, raw strings, etc. are unlikely).
   */
  public static String stripQuotes(String string) {
    return textRangeInElement(string).substring(string);
  }

  /** The range of text characters, excluding leading and trailing quotes. */
  public static TextRange textRangeInElement(String string) {
    // TODO: Handle escaped characters, etc. here?
    // (extract logic from BuildLexerBase.addStringLiteral)
    if (string.startsWith("\"\"\"")) {
      return string.length() <= 3
          ? TextRange.EMPTY_RANGE
          : TextRange.create(3, endTrimIndex(string, '"', 3));
    }
    if (string.startsWith("'''")) {
      return string.length() <= 3
          ? TextRange.EMPTY_RANGE
          : TextRange.create(3, endTrimIndex(string, '\'', 3));
    }
    if (string.startsWith("\"")) {
      return TextRange.create(1, endTrimIndex(string, '"', 1));
    }
    if (string.startsWith("'")) {
      return TextRange.create(1, endTrimIndex(string, '\'', 1));
    }
    return TextRange.allOf(string);
  }

  private static int endTrimIndex(String string, char quoteChar, int numberQuoteChars) {
    int trimIndex = string.length();
    for (int i = 1;
        i <= Math.min(numberQuoteChars, string.length() - numberQuoteChars);
        i++, trimIndex--) {
      if (string.charAt(string.length() - i) != quoteChar) {
        break;
      }
    }
    return trimIndex;
  }

  public static QuoteType getQuoteType(@Nullable String rawText) {
    if (rawText == null) {
      return QuoteType.NoQuotes;
    }
    if (rawText.startsWith("\"\"\"")) {
      return QuoteType.TripleDouble;
    }
    if (rawText.startsWith("'''")) {
      return QuoteType.TripleSingle;
    }
    if (rawText.startsWith("'")) {
      return QuoteType.Single;
    }
    if (rawText.startsWith("\"")) {
      return QuoteType.Double;
    }
    return QuoteType.NoQuotes;
  }

  public StringLiteral(ASTNode astNode) {
    super(astNode);
  }

  @Override
  protected void acceptVisitor(BuildElementVisitor visitor) {
    visitor.visitStringLiteral(this);
  }

  /** Removes the leading and trailing quotes */
  public String getStringContents() {
    return stripQuotes(getText());
  }

  public QuoteType getQuoteType() {
    return getQuoteType(getText());
  }

  /**
   * Labels are taken to reference: - the actual target they reference - the BUILD package specified
   * before the colon (only if explicitly present)
   */
  @Override
  public PsiReference[] getReferences() {
    // first look for attribute-specific references
    String attributeName = getParentAttributeName();
    if (attributeName != null) {
      PsiReference[] refs =
          AttributeSpecificStringLiteralReferenceProvider.findReferences(attributeName, this);
      if (refs.length != 0) {
        return refs;
      }
    }
    PsiReference primaryReference = getReference();
    if (primaryReference instanceof LabelReference) {
      LabelReference labelReference = (LabelReference) primaryReference;
      return new PsiReference[] {
        primaryReference,
        new PackageReferenceFragment(labelReference),
        new ExternalWorkspaceReferenceFragment(labelReference)
      };
    }
    return primaryReference != null
        ? new PsiReference[] {primaryReference}
        : PsiReference.EMPTY_ARRAY;
  }

  /** The primary reference -- this is the target referenced by the full label */
  @Nullable
  @Override
  public PsiReference getReference() {
    LoadStatement load = getLoadStatementParent();
    if (load != null) {
      StringLiteral importNode = load.getImportPsiElement();
      if (importNode == null) {
        return null;
      }
      LabelReference importReference = new LabelReference(importNode, false);
      if (this.equals(importNode)) {
        return importReference;
      }
      return new LoadedSymbolReference(this, importReference);
    }
    return new LabelReference(this, true);
  }

  /** If this string is an attribute value within a BUILD rule, return the attribute type. */
  @Nullable
  private String getParentAttributeName() {
    Keyword parentKeyword = PsiUtils.getParentOfType(this, Keyword.class, true);
    return parentKeyword != null ? parentKeyword.getName() : null;
  }

  @Nullable
  public LoadStatement getLoadStatementParent() {
    PsiElement parent = getParent();
    if (parent instanceof LoadStatement) {
      // the skylark extension label
      return (LoadStatement) parent;
    }
    if (parent instanceof AssignmentStatement) {
      // could be part of an aliased symbol
      parent = parent.getParent();
    }
    return parent instanceof LoadedSymbol ? (LoadStatement) parent.getParent() : null;
  }

  @Override
  public String getPresentableText() {
    return getText();
  }
}


text:
LuCI - Internationalisation

Description:
A very minimalistic but yet effective internationalisation module

FileId:
$Id: i18n.lua 9520 2012-12-02 13:30:46Z jow $

License:
Copyright 2008 Steven Barth <steven@midlink.org>

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.

]]--

--- LuCI translation library.
module("luci.i18n", package.seeall)
require("luci.util")

local tparser = require "luci.template.parser"

table   = {}
i18ndir = luci.util.libpath() .. "/i18n/"
loaded  = {}
context = luci.util.threadlocal()
default = "en"

--- Clear the translation table.
function clear()
end

--- Load a translation and copy its data into the translation table.
-- @param file	Language file
-- @param lang	Two-letter language code
-- @param force	Force reload even if already loaded (optional)
-- @return		Success status
function load(file, lang, force)
end

--- Load a translation file using the default translation language.
-- Alternatively load the translation of the fallback language.
-- @param file	Language file
-- @param force	Force reload even if already loaded (optional)
function loadc(file, force)
end

--- Set the context default translation language.
-- @param lang	Two-letter language code
function setlanguage(lang)
	context.lang   = lang:gsub("_", "-")
	context.parent = (context.lang:match("^([a-z][a-z])_"))
	if not tparser.load_catalog(context.lang, i18ndir) then
		if context.parent then
			tparser.load_catalog(context.parent, i18ndir)
			return context.parent
		end
	end
	return context.lang
end

--- Return the translated value for a specific translation key.
-- @param key	Default translation text
-- @return		Translated string
function translate(key)
	return tparser.translate(key) or key
end

--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- @param key		Default translation text
-- @param ...		Format parameters
-- @return			Translated and formatted string
function translatef(key, ...)
	return tostring(translate(key)):format(...)
end

--- Return the translated value for a specific translation key
-- and ensure that the returned value is a Lua string value.
-- This is the same as calling tostring(translate(...))
-- @param key		Default translation text
-- @return			Translated string
function string(key)
	return tostring(translate(key))
end

--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- Ensure that the returned value is a Lua string value.
-- This is the same as calling tostring(translatef(...))
-- @param key		Default translation text
-- @param ...		Format parameters
-- @return			Translated and formatted string
function stringf(key, ...)
	return tostring(translate(key)):format(...)
end


text:
/**
 * << detailed description >>
 *
 * @file TopologyFusionReaction.cpp
 * @brief << brief description >>
 * @author clonker
 * @date 23.06.17
 * @copyright BSD-3
 */

#include <readdy/model/topologies/reactions/SpatialTopologyReaction.h>

#include <regex>
#include <readdy/model/topologies/TopologyRegistry.h>
#include <readdy/model/Utils.h>

namespace readdy::model::top::reactions {

  ReactionId SpatialTopologyReaction::counter = 0;

  SpatialTopologyReaction STRParser::parse(const std::string &descriptor, scalar rate, scalar radius) const {
      SpatialTopologyReaction reaction;
      reaction._rate = rate;
      reaction._radius = radius;

      parse_descriptor(descriptor, reaction);
      return reaction;
  }

  SpatialTopologyReaction STRParser::parse(const std::string &descriptor,
                                           std::function<scalar(const GraphTopology &, const GraphTopology&)> rate_func,
                                           scalar radius) const {
      SpatialTopologyReaction reaction;
      reaction._rate_is_const = false;
      reaction._rate_function = std::move(rate_func);
      reaction._radius = radius;

      parse_descriptor(descriptor, reaction);
      if (reaction.is_topology_particle_reaction()) {
          throw std::invalid_argument("Dynamic rate functions are only implemented for topology-topology "
                                      "reactions. For topology-particle reactions use a constant rate.");
      }
      return reaction;
  }

  void STRParser::parse_descriptor(const std::string &descriptor, SpatialTopologyReaction &reaction) const {
      namespace mutil = readdy::model::util;
      namespace rutil = readdy::util;

      log::trace("begin parsing \"{}\"", descriptor);
      auto arrowPos = descriptor.find(mutil::arrow);
      if (arrowPos == std::string::npos) {
          throw std::invalid_argument(fmt::format(
                  "the descriptor must contain an arrow (\"{}\") to indicate lhs and rhs.", mutil::arrow
          ));
      }
      if (descriptor.find(mutil::arrow, arrowPos + 1) != std::string::npos) {
          throw std::invalid_argument(fmt::format(
                  "the descriptor must not contain more than one arrow (\"{}\").", mutil::arrow
          ));
      }
      auto lhs = descriptor.substr(0, arrowPos);
      auto rhs = descriptor.substr(arrowPos + std::strlen(mutil::arrow), std::string::npos);

      rutil::str::trim(lhs);
      rutil::str::trim(rhs);

      std::string name;
      {
          auto colonPos = lhs.find(':');
          if (colonPos == std::string::npos) {
              throw std::invalid_argument("The descriptor did not contain a colon ':' to specify the end of the name.");
          }
          name = rutil::str::trim_copy(lhs.substr(0, colonPos));
          lhs = rutil::str::trim_copy(lhs.substr(colonPos + 1, std::string::npos));
      }
      reaction._name = name;

      static std::regex particleTypeRegex(R"(\(([^\)]*)\))");
      static std::regex topologyTypeRegex(R"([^(]*)");

      static auto getTop = [](const std::string &s) {
          std::smatch topMatch;
          if (std::regex_search(s, topMatch, topologyTypeRegex)) {
              return rutil::str::trim_copy(topMatch.str());
          }
          throw std::invalid_argument(fmt::format("The term \"{}\" did not contain a topology type.", s));
      };
      static auto getParticleType = [](const std::string &s) {
          std::smatch ptMatch;
          if (std::regex_search(s, ptMatch, particleTypeRegex)) {
              auto pt = rutil::str::trim_copy(ptMatch.str());
              return rutil::str::trim_copy(pt.substr(1, pt.size() - 2));
          }
          throw std::invalid_argument(fmt::format("The term \"{}\" did not contain a particle type.", s));
      };

      static auto treatTerm = [](const std::string &s) {
          return std::make_tuple(getParticleType(s), getTop(s));
      };

      static auto treatSide = [](const std::string &s) {
          auto plusPos = s.find('+');
          if (plusPos == std::string::npos) {
              throw std::invalid_argument("The left hand side of the topology reaction did not contain a '+'.");
          }
          auto educt1 = rutil::str::trim_copy(s.substr(0, plusPos));
          auto educt2 = rutil::str::trim_copy(s.substr(plusPos + 1, std::string::npos));

          std::string t1, t2, p1, p2;
          std::tie(p1, t1) = treatTerm(educt1);
          std::tie(p2, t2) = treatTerm(educt2);

          return std::make_tuple(p1, t1, p2, t2);
      };

      std::string lhs_p1, lhs_t1, lhs_p2, lhs_t2;
      {
          std::tie(lhs_p1, lhs_t1, lhs_p2, lhs_t2) = treatSide(lhs);
      }

      std::string rhs_p1, rhs_t1, rhs_p2, rhs_t2;
      bool rhs_fusion {false};
      {
          auto plusPos = rhs.find('+');
          rhs_fusion = plusPos == std::string::npos;
          if (plusPos == std::string::npos) {
              // fusion type
              std::string fuse;
              std::tie(fuse, rhs_t1) = treatTerm(rhs);
              rhs_t2 = "";

              auto separatorPos = fuse.find(mutil::bond);
              if (separatorPos == std::string::npos) {
                  throw std::invalid_argument(fmt::format(
                          "The right-hand side was of fusion type but there was no bond \"{}\" defined.", mutil::bond
                  ));
              }

              rhs_p1 = rutil::str::trim_copy(fuse.substr(0, separatorPos));
              rhs_p2 = rutil::str::trim_copy(fuse.substr(separatorPos + std::strlen(mutil::bond), std::string::npos));
          } else {
              // enzymatic type
              std::tie(rhs_p1, rhs_t1, rhs_p2, rhs_t2) = treatSide(rhs);
          }

          log::trace(R"(got lhs with toplogies "{}" and "{}", particle types "{}" and "{}")", lhs_t1, lhs_t2, lhs_p1,
                     lhs_p2);
          log::trace(R"(got rhs with topologies "{}" and "{}", particles "{}" and "{}")", rhs_t1, rhs_t2, rhs_p1, rhs_p2);
      }

      const auto &particle_types = _topology_registry.get().particleTypeRegistry();

      if(lhs_t2.empty()) {
          // we are in the topology-particle case
          reaction._top_types = std::make_tuple(_topology_registry.get().idOf(lhs_t1), EmptyTopologyId);
          reaction._types = std::make_tuple(particle_types.idOf(lhs_p1), particle_types.idOf(lhs_p2));
          reaction._types_to = std::make_tuple(particle_types.idOf(rhs_p1), particle_types.idOf(rhs_p2));
          reaction._top_types_to = std::make_tuple(_topology_registry.get().idOf(rhs_t1), EmptyTopologyId);
          if(rhs_fusion) {
              // we are in the fusion case
              reaction._mode = STRMode::TP_FUSION;
          } else {
              // we are in the enzymatic case
              reaction._mode = STRMode::TP_ENZYMATIC;
          }
      } else {
          // we are in the topology-topology case
          reaction._top_types = std::make_tuple(_topology_registry.get().idOf(lhs_t1),
                                                _topology_registry.get().idOf(lhs_t2));
          reaction._types = std::make_tuple(particle_types.idOf(lhs_p1), particle_types.idOf(lhs_p2));
          reaction._types_to = std::make_tuple(particle_types.idOf(rhs_p1), particle_types.idOf(rhs_p2));
          if(rhs_fusion) {
              // we are in the fusion case
              std::smatch option_match;
              std::regex option_rx(R"(\[(.*?)\])");
              // check for options
              if(std::regex_search(rhs, option_match, option_rx)) {
                  auto option_str = option_match.str();
                  std::vector<std::string> options = parse_options(
                          option_str.substr(1, option_str.length()-2)
                  );
                  if (!has_option_allow_self(options)) {
                      throw std::runtime_error("Option \"self=true\" is missing. This option is currently required for all valid options. If you don't want to allow self fusion, ommit the option block (in square brackets).");
                  }
                  reaction._mode = STRMode::TT_FUSION_ALLOW_SELF;
                  int d = get_distance(options);
                  if (d == -1) reaction._min_graph_distance = 0;
                  else reaction._min_graph_distance = (unsigned) d;
              } else {
                  reaction._mode = STRMode::TT_FUSION;
              }
              reaction._top_types_to = std::make_tuple(_topology_registry.get().idOf(rhs_t1), EmptyTopologyId);
          } else {
              // we are in the enzymatic case
              reaction._mode = STRMode::TT_ENZYMATIC;
              reaction._top_types_to = std::make_tuple(_topology_registry.get().idOf(rhs_t1),
                                                       _topology_registry.get().idOf(rhs_t2));
          }
      }
  }

  std::vector<std::string> STRParser::parse_options(const std::string &option_str) const {
    std::vector<std::string> options;
    size_t pos = 0;
    std::string s = option_str.substr();
    std::string o;
    while ((pos = s.find(",")) != std::string::npos) {
      o = s.substr(0, pos);
      readdy::util::str::trim(o);
      options.push_back(o);
      s.erase(0, pos + 1);
    }
    readdy::util::str::trim(s);
    options.push_back(s);
    return options;
  }

  bool STRParser::has_option_allow_self(const std::vector<std::string> &options) const {
    auto it = std::find(options.begin(),
			options.end(),
			"self=true");
    if (it != options.end()) return true;
    return false;
  }

  int STRParser::get_distance(const std::vector<std::string> &options) const {
    for (auto &o: options) {
      if(o.find("distance>") == std::string::npos) continue;
      auto dist = std::stoi(o.substr(9));
      return dist;
    }
    return -1;
  }
}


text:
Phinject
========

[![Build Status](https://travis-ci.org/aztech-digital/phinject.png?branch=master)](https://travis-ci.org/aztech-digital/phinject)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/coverage/g/aztech-digital/phinject.svg?style=flat)](https://scrutinizer-ci.com/g/aztech-digital/phinject/?branch=master)
[![Code Coverage](https://img.shields.io/scrutinizer/g/aztech-digital/phinject.svg?style=flat)](https://scrutinizer-ci.com/g/aztech-digital/phinject/?branch=master)
[![HHVM Support](https://img.shields.io/hhvm/aztech/phinject.svg)](http://hhvm.h4cc.de/package/aztech/phinject)

[![License](https://img.shields.io/packagist/l/aztech/phinject.svg?style=flat)](https://packagist.org/packages/aztech/phinject)
[![Latest Stable Version](https://img.shields.io/packagist/v/aztech/phinject.svg?style=flat)](https://packagist.org/packages/aztech/phinject)

Phinject is a simple dependency injection container, with extensible activation & injection strategies.

## Setup

[Composer](https://getcomposer.org) is the only supported way of installing Phinject. From the root of your project, run the following command:

```
composer require aztech/phinject
```

## Features

- Compatible with the [container-interop](https://github.com/container-interop/container-interop) specification
- Compatible with [delegate containers](https://github.com/container-interop/container-interop/blob/master/docs/Delegate-lookup.md).
- YAML, JSON or PHP based configuration.
- Lazy-loading dependencies.
- Remote proxies (undocumented).
- Aliases (undocumented).
- Extensible configuration syntax (undocumented).

## Usage

The documentation is available [here](./doc/).

We have a [getting started](./doc/01-Getting-started.md) guide, followed by more comprehensive documentation (although not yet exhaustive, but that will come):

- [Injection types](./doc/02-Injection-types.md)
- [References](./doc/03-References.md)
- [Activators](./doc/04-Activators.md)
- [Lifecycle of objects](./doc/05-Lifecycle.md)
- Remote objects (TODO: Write documentation)
- Container interoperability (TODO: Write documentation).
- [Extending the configuration syntax](./doc/07-Extensibility.md)

**Note** All the documentation examples are written using a YAML based configuration, however, you can also use JSON or PHP configuration files. (TODO: Document usage of PHP & JSON config file)

## Credits

This library is originally a fork on `oliviermadre/dic-it`, available [here](https://github.com/oliviermadre/dic-it).

Most of the core features have however been refactored or rewritten, enough that I felt it was time to re-brand this package, in order to both prevent confusion with the original package, and because I did not like the name.


text:
layout: post
title: Covfefe CTF Vulnhub
---

QCovfefe is a beginnerCTF hosted on VulnHub. As always thank you to VulnHub for hosting these images and Viper for his work on this one.

On my network this grabbed a 192.168.0.146 address. I used an app called Fing to get this piece of information

To start things off I did a little recon and scanned the machine with the nmap command *nmap -T4 -A -v -p- 192.168.0.146
The following ports were found open
    - 22 which was running SSH
	- 80 which was running NGINX 1.10.3
	- 31337 - Wekzeug httpd Python

I started by scanning port 80 with nikto and did not find anything interesting. I also checked to see if there was a robots.txt file which there was not.

At this point I decided to take a look at the lesser known HTTP server hoping this was a sign of weakness. Lucky for me this server did have a robots.txt file
with the following entries .basrc, .profile, and taxes. I first broswed to taxes and was greated with my first flag *Good job! Here is a flag: flag1{make_america_great_again}*

After looking through the .bashrc and .profile I could not find anything of interest so I decided to run nikto against port 31337.
on top of the already known files it found a .bash_history, and a .ssh folder. At this point I started to believe this was being
run from a user's home directory. Browsing to .ssh gave us the text ['id_rsa', 'authorized_keys', id_rsa.pub']

.ssh is usually a directory on machines so I browsed to /.ssh/id_rsa, ip/.ssh/authorized_keys, ip/.ssh/id_rsa.pub
and downloaded the contents. Looking through the authorized_keys it appears our username is simon.

Trying to connect with the id_rsa file ends up failing because the file is encrypted. Luckily for us we can run
ssh2john id_rsa > unencrypted. At this point we can now search for the password using the command
cat rockyou.txt | john --pipe --rules unencrypted and this gives us the word starwars.

Connecting to the system is now trivial with the command ssh -i id_rsa simon@192.168.0.113 and the password starwars.

After connecting to the system I releazed my assumption was right and we are in a simon's home directory. A quick look around
reveals there is nothing else of interest here. I went to check out the /root/ directory.

The root directory had a flag.txt file which was not readable and a C file named read_message.c. Opening the read_message.called
gives us flag 2 *flag2{use_the_source_luke}*

At this point it is time to take a look at the program for exploits. I have to admit I am not a buffer overflow or exploit guru
but this program has a pretty trivial bufferoverflow in the name array. However, this will not do anything for us if we are not root.
Checking out /usr/local/bin/ I relealized this program runs as a setuid program so if we can get execution of a /bin/sh we will be root.

So, like I said the array was overflowable and it only checks that the first 5 characters are Simon. So I threw the string
*Simonthisisjunkkkkkkk/bin/dash* at the program and was able to pop a shell. cat flag.txt gave us
*You did it! Congratulations, here's the final flag: flag3{das_bof_meister}* and Covfefe is now complete.

I spent much more time on this exploit than I would like to admit. I totally forgot /bin/sh was aliased to /bin/dash/
in Debian. Instead of looking in GDB I just assumed I had something wrong. Moral of the store pay attention to the
OS you are in.

Enjoy!


text:
package com.game.bizModule.human.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 角色入口实体
 *
 * @author hjj2019
 * @since 2015/7/11
 *
 */
@Entity
@Table(name = "t_human")
public class HumanEntryEntity {
    /** 玩家角色 UId */
    @Id @Column(name = "human_uid", updatable = false)
    public Long _humanUId = null;
    /** 平台 UId 字符串 */
    @Column(name = "platform_uid_str", length = 64, nullable = false, updatable = false)
    public String _platformUIdStr = null;
    /** 角色全名 */
    @Column(name = "full_name", length = 48, nullable = false, updatable = false)
    public String _fullName = null;
    /** 角色名称 */
    @Column(name = "human_name", length = 32, nullable = false, updatable = false)
    public String _humanName = null;
    /** 服务器名称 */
    @Column(name = "server_name", length = 16, nullable = false, updatable = false)
    public String _serverName = null;
    /** 角色等级 */
    @Column(name = "human_level", nullable = false, updatable = false)
    public Integer _humanLevel = 0;
}


text:
package com.example.actiontab;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity implements TabListener{
    private ActionBar actionBar;
    private static final String SELECTED_ITEM = "selected_item";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.addTab(actionBar.newTab().setText("Page 1").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Page 2").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Page 3").setTabListener(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        Fragment fragment = new DummyFragment();
        Bundle args = new Bundle();
        args.putInt(DummyFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
        fragment.setArguments(args);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

}


text:
#pragma once
#include <aws/compute-optimizer/ComputeOptimizer_EXPORTS.h>
#include <aws/compute-optimizer/model/EnhancedInfrastructureMetrics.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ComputeOptimizer
{
namespace Model
{
  class AWS_COMPUTEOPTIMIZER_API GetEffectiveRecommendationPreferencesResult
  {
  public:
    GetEffectiveRecommendationPreferencesResult();
    GetEffectiveRecommendationPreferencesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetEffectiveRecommendationPreferencesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The status of the enhanced infrastructure metrics recommendation preference.
     * Considers all applicable preferences that you might have set at the resource,
     * account, and organization level.

A status of Active confirms
     * that the preference is applied in the latest recommendation refresh, and a
     * status of Inactive confirms that it's not yet applied to
     * recommendations.

To validate whether the preference is applied to your
     * last generated set of recommendations, review the
     * effectiveRecommendationPreferences value in the response of the
     * GetAutoScalingGroupRecommendations and
     * GetEC2InstanceRecommendations actions.

For more information, see
     * Enhanced
     * infrastructure metrics in the Compute Optimizer User Guide.

     */
    inline const EnhancedInfrastructureMetrics& GetEnhancedInfrastructureMetrics() const{ return m_enhancedInfrastructureMetrics; }

    /**
     *
The status of the enhanced infrastructure metrics recommendation preference.
     * Considers all applicable preferences that you might have set at the resource,
     * account, and organization level.

A status of Active confirms
     * that the preference is applied in the latest recommendation refresh, and a
     * status of Inactive confirms that it's not yet applied to
     * recommendations.

To validate whether the preference is applied to your
     * last generated set of recommendations, review the
     * effectiveRecommendationPreferences value in the response of the
     * GetAutoScalingGroupRecommendations and
     * GetEC2InstanceRecommendations actions.

For more information, see
     * Enhanced
     * infrastructure metrics in the Compute Optimizer User Guide.

     */
    inline void SetEnhancedInfrastructureMetrics(const EnhancedInfrastructureMetrics& value) { m_enhancedInfrastructureMetrics = value; }

    /**
     *
The status of the enhanced infrastructure metrics recommendation preference.
     * Considers all applicable preferences that you might have set at the resource,
     * account, and organization level.

A status of Active confirms
     * that the preference is applied in the latest recommendation refresh, and a
     * status of Inactive confirms that it's not yet applied to
     * recommendations.

To validate whether the preference is applied to your
     * last generated set of recommendations, review the
     * effectiveRecommendationPreferences value in the response of the
     * GetAutoScalingGroupRecommendations and
     * GetEC2InstanceRecommendations actions.

For more information, see
     * Enhanced
     * infrastructure metrics in the Compute Optimizer User Guide.

     */
    inline void SetEnhancedInfrastructureMetrics(EnhancedInfrastructureMetrics&& value) { m_enhancedInfrastructureMetrics = std::move(value); }

    /**
     *
The status of the enhanced infrastructure metrics recommendation preference.
     * Considers all applicable preferences that you might have set at the resource,
     * account, and organization level.

A status of Active confirms
     * that the preference is applied in the latest recommendation refresh, and a
     * status of Inactive confirms that it's not yet applied to
     * recommendations.

To validate whether the preference is applied to your
     * last generated set of recommendations, review the
     * effectiveRecommendationPreferences value in the response of the
     * GetAutoScalingGroupRecommendations and
     * GetEC2InstanceRecommendations actions.

For more information, see
     * Enhanced
     * infrastructure metrics in the Compute Optimizer User Guide.

     */
    inline GetEffectiveRecommendationPreferencesResult& WithEnhancedInfrastructureMetrics(const EnhancedInfrastructureMetrics& value) { SetEnhancedInfrastructureMetrics(value); return *this;}

    /**
     *
The status of the enhanced infrastructure metrics recommendation preference.
     * Considers all applicable preferences that you might have set at the resource,
     * account, and organization level.

A status of Active confirms
     * that the preference is applied in the latest recommendation refresh, and a
     * status of Inactive confirms that it's not yet applied to
     * recommendations.

To validate whether the preference is applied to your
     * last generated set of recommendations, review the
     * effectiveRecommendationPreferences value in the response of the
     * GetAutoScalingGroupRecommendations and
     * GetEC2InstanceRecommendations actions.

For more information, see
     * Enhanced
     * infrastructure metrics in the Compute Optimizer User Guide.

     */
    inline GetEffectiveRecommendationPreferencesResult& WithEnhancedInfrastructureMetrics(EnhancedInfrastructureMetrics&& value) { SetEnhancedInfrastructureMetrics(std::move(value)); return *this;}

  private:

    EnhancedInfrastructureMetrics m_enhancedInfrastructureMetrics;
  };

} // namespace Model
} // namespace ComputeOptimizer
} // namespace Aws


text:
"use strict";

var crypto = require('crypto');
var stream = require('stream');

var Readable = stream.Readable;
require('util').inherits(RandomChunkStream, Readable);

module.exports = RandomChunkStream;

function RandomChunkStream(options) {
  this.maxchunksize = options.maxchunksize>>>0;
  this.size = options.size>>>0;
  this.buffer = Buffer.allocUnsafe(this.size);
  this.cursor = 0;
  Readable.call(this, options);
}

RandomChunkStream.prototype._read = function() {
  var buffer = this.buffer;
  var slicelen = (Math.random()*this.maxchunksize|0) + 1;
  slicelen = Math.min(slicelen, this.size - this.cursor);
  crypto.randomBytes(slicelen).copy(buffer, this.cursor);
  var n = this.cursor + slicelen;
  this.push(buffer.slice(this.cursor, n));
  this.cursor = n;
  if (n >= this.size)
    this.push(null);
};


text:
export function boolean(value: any): value is boolean {
	return value === true || value === false;
}

export function string(value: any): value is string {
	return typeof value === 'string' || value instanceof String;
}

export function number(value: any): value is number {
	return typeof value === 'number' || value instanceof Number;
}

export function error(value: any): value is Error {
	return value instanceof Error;
}

export function func(value: any): value is Function {
	return typeof value  === 'function';
}

export function array<T>(value: any): value is T[] {
	return Array.isArray(value);
}

export function stringArray(value: any): value is string[] {
	return array(value) && (<any[]>value).every(elem => string(elem));
}


text:
package Google::Ads::AdWords::v201809::ProductImage;
use strict;
use warnings;

__PACKAGE__->_set_element_form_qualified(1);

sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };

our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;

sub __get_attr_class {
    return $XML_ATTRIBUTE_CLASS;
}

use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);

{ # BLOCK to scope variables

my %productImage_of :ATTR(:get<productImage>);
my %description_of :ATTR(:get<description>);
my %displayCallToAction_of :ATTR(:get<displayCallToAction>);

__PACKAGE__->_factory(
    [ qw(        productImage
        description
        displayCallToAction

    ) ],
    {
        'productImage' => \%productImage_of,
        'description' => \%description_of,
        'displayCallToAction' => \%displayCallToAction_of,
    },
    {
        'productImage' => 'Google::Ads::AdWords::v201809::Image',
        'description' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'displayCallToAction' => 'Google::Ads::AdWords::v201809::DisplayCallToAction',
    },
    {

        'productImage' => 'productImage',
        'description' => 'description',
        'displayCallToAction' => 'displayCallToAction',
    }
);

} # end BLOCK

1;

=pod

=head1 NAME

Google::Ads::AdWords::v201809::ProductImage

=head1 DESCRIPTION

Perl data type class for the XML Schema defined complexType
ProductImage from the namespace https://adwords.google.com/api/adwords/cm/v201809.

Represents product image specific data.

=head2 PROPERTIES

The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:

=over

=item * productImage

=item * description

=item * displayCallToAction

=back

=head1 METHODS

=head2 new

Constructor. The following data structure may be passed to new():

=head1 AUTHOR

Generated by SOAP::WSDL

=cut


text:
from ansible.module_utils.api import basic_auth_argument_spec

ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: netapp_e_volume
version_added: "2.2"
short_description: Manage storage volumes (standard and thin)
description:
    - Create or remove volumes (standard and thin) for NetApp E/EF-series storage arrays.
options:
  api_username:
      required: true
      description:
      - The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.
  api_password:
      required: true
      description:
      - The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.
  api_url:
      required: true
      description:
      - The url to the SANtricity WebServices Proxy or embedded REST API.
      example:
      - https://prod-1.wahoo.acme.com/devmgr/v2
  validate_certs:
      required: false
      default: true
      description:
      - Should https certificates be validated?
  ssid:
    required: true
    description:
    - The ID of the array to manage (as configured on the web services proxy).
  state:
    required: true
    description:
    - Whether the specified volume should exist or not.
    choices: ['present', 'absent']
  name:
    required: true
    description:
    - The name of the volume to manage
  storage_pool_name:
    required: true
    description:
    - "Required only when requested state is 'present'.  The name of the storage pool the volume should exist on."
  size_unit:
    description:
    - The unit used to interpret the size parameter
    choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
    default: 'gb'
  size:
    required: true
    description:
    - "Required only when state = 'present'.  The size of the volume in (size_unit)."
  segment_size_kb:
    description:
    - The segment size of the new volume
    default: 512
  thin_provision:
    description:
    - Whether the volume should be thin provisioned.  Thin volumes can only be created on disk pools (raidDiskPool).
    default: False
    choices: ['yes','no','true','false']
  thin_volume_repo_size:
    description:
    - Initial size of the thin volume repository volume (in size_unit)
    required: True
  thin_volume_max_repo_size:
    description:
    - Maximum size that the thin volume repository volume will automatically expand to
    default: same as size (in size_unit)
  ssd_cache_enabled:
    description:
    - Whether an existing SSD cache should be enabled on the volume (fails if no SSD cache defined)
    default: None (ignores existing SSD cache setting)
    choices: ['yes','no','true','false']
  data_assurance_enabled:
    description:
    - If data assurance should be enabled for the volume
    default: false

# TODO: doc thin volume parameters

author: Kevin Hulquest (@hulquest)

'''
EXAMPLES = '''
    - name: No thin volume
      netapp_e_volume:
        ssid: "{{ ssid }}"
        name: NewThinVolumeByAnsible
        state: absent
        log_path: /tmp/volume.log
        api_url: "{{ netapp_api_url }}"
        api_username: "{{ netapp_api_username }}"
        api_password: "{{ netapp_api_password }}"
        validate_certs: "{{ netapp_api_validate_certs }}"
      when: check_volume

    - name: No fat volume
      netapp_e_volume:
        ssid: "{{ ssid }}"
        name: NewVolumeByAnsible
        state: absent
        log_path: /tmp/volume.log
        api_url: "{{ netapp_api_url }}"
        api_username: "{{ netapp_api_username }}"
        api_password: "{{ netapp_api_password }}"
        validate_certs: "{{ netapp_api_validate_certs }}"
      when: check_volume
'''
RETURN = '''
---
msg: "Standard volume [workload_vol_1] has been created."
msg: "Thin volume [workload_thin_vol] has been created."
msg: "Volume [workload_vol_1] has been expanded."
msg: "Volume [workload_vol_1] has been deleted."
msg: "Volume [workload_vol_1] did not exist."
msg: "Volume [workload_vol_1] already exists."
'''

import json
import logging
import time
from traceback import format_exc

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import open_url
from ansible.module_utils.six.moves.urllib.error import HTTPError

def request(url, data=None, headers=None, method='GET', use_proxy=True,
            force=False, last_mod_time=None, timeout=10, validate_certs=True,
            url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
    try:
        r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
                     force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
                     url_username=url_username, url_password=url_password, http_agent=http_agent,
                     force_basic_auth=force_basic_auth)
    except HTTPError:
        err = get_exception()
        r = err.fp

    try:
        raw_data = r.read()
        if raw_data:
            data = json.loads(raw_data)
        else:
            raw_data is None
    except:
        if ignore_errors:
            pass
        else:
            raise Exception(raw_data)

    resp_code = r.getcode()

    if resp_code >= 400 and not ignore_errors:
        raise Exception(resp_code, data)
    else:
        return resp_code, data

def ifilter(predicate, iterable):
    # python 2, 3 generic filtering.
    if predicate is None:
        predicate = bool
    for x in iterable:
        if predicate(x):
            yield x

class NetAppESeriesVolume(object):
    def __init__(self):
        self._size_unit_map = dict(
            bytes=1,
            b=1,
            kb=1024,
            mb=1024 ** 2,
            gb=1024 ** 3,
            tb=1024 ** 4,
            pb=1024 ** 5,
            eb=1024 ** 6,
            zb=1024 ** 7,
            yb=1024 ** 8
        )

        self._post_headers = dict(Accept="application/json")
        self._post_headers['Content-Type'] = 'application/json'

        argument_spec = basic_auth_argument_spec()
        argument_spec.update(dict(
            state=dict(required=True, choices=['present', 'absent']),
            ssid=dict(required=True, type='str'),
            name=dict(required=True, type='str'),
            storage_pool_name=dict(type='str'),
            size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'],
                           type='str'),
            size=dict(type='int'),
            segment_size_kb=dict(default=128, choices=[8, 16, 32, 64, 128, 256, 512], type='int'),
            ssd_cache_enabled=dict(type='bool'),  # no default, leave existing setting alone
            data_assurance_enabled=dict(default=False, type='bool'),
            thin_provision=dict(default=False, type='bool'),
            thin_volume_repo_size=dict(type='int'),
            thin_volume_max_repo_size=dict(type='int'),
            # TODO: add cache, owning controller support, thin expansion policy, etc
            log_path=dict(type='str'),
            api_url=dict(type='str'),
            api_username=dict(type='str'),
            api_password=dict(type='str'),
            validate_certs=dict(type='bool'),
        ))

        self.module = AnsibleModule(argument_spec=argument_spec,
                                    required_if=[
                                        ('state', 'present', ['storage_pool_name', 'size']),
                                        ('thin_provision', 'true', ['thin_volume_repo_size'])
                                    ],
                                    supports_check_mode=True)
        p = self.module.params

        log_path = p['log_path']

        # logging setup
        self._logger = logging.getLogger(self.__class__.__name__)
        self.debug = self._logger.debug

        if log_path:
            logging.basicConfig(level=logging.DEBUG, filename=log_path)

        self.state = p['state']
        self.ssid = p['ssid']
        self.name = p['name']
        self.storage_pool_name = p['storage_pool_name']
        self.size_unit = p['size_unit']
        self.size = p['size']
        self.segment_size_kb = p['segment_size_kb']
        self.ssd_cache_enabled = p['ssd_cache_enabled']
        self.data_assurance_enabled = p['data_assurance_enabled']
        self.thin_provision = p['thin_provision']
        self.thin_volume_repo_size = p['thin_volume_repo_size']
        self.thin_volume_max_repo_size = p['thin_volume_max_repo_size']

        if not self.thin_volume_max_repo_size:
            self.thin_volume_max_repo_size = self.size

        self.validate_certs = p['validate_certs']

        try:
            self.api_usr = p['api_username']
            self.api_pwd = p['api_password']
            self.api_url = p['api_url']
        except KeyError:
            self.module.fail_json(msg="You must pass in api_username "
                                      "and api_password and api_url to the module.")

    def get_volume(self, volume_name):
        self.debug('fetching volumes')
        # fetch the list of volume objects and look for one with a matching name (we'll need to merge volumes and thin-volumes)
        try:
            (rc, volumes) = request(self.api_url + "/storage-systems/%s/volumes" % (self.ssid),
                                    headers=dict(Accept="application/json"), url_username=self.api_usr,
                                    url_password=self.api_pwd, validate_certs=self.validate_certs)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to obtain list of standard/thick volumes.  Array Id [%s]. Error[%s]." % (self.ssid,
                                                                                str(err)))

        try:
            self.debug('fetching thin-volumes')
            (rc, thinvols) = request(self.api_url + "/storage-systems/%s/thin-volumes" % (self.ssid),
                                     headers=dict(Accept="application/json"), url_username=self.api_usr,
                                     url_password=self.api_pwd, validate_certs=self.validate_certs)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to obtain list of thin volumes.  Array Id [%s]. Error[%s]." % (self.ssid, str(err)))

        volumes.extend(thinvols)

        self.debug("searching for volume '%s'" % volume_name)
        volume_detail = next(ifilter(lambda a: a['name'] == volume_name, volumes), None)

        if volume_detail:
            self.debug('found')
        else:
            self.debug('not found')

        return volume_detail

    def get_storage_pool(self, storage_pool_name):
        self.debug("fetching storage pools")
        # map the storage pool name to its id
        try:
            (rc, resp) = request(self.api_url + "/storage-systems/%s/storage-pools" % (self.ssid),
                                 headers=dict(Accept="application/json"), url_username=self.api_usr,
                                 url_password=self.api_pwd, validate_certs=self.validate_certs)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to obtain list of storage pools.  Array Id [%s]. Error[%s]." % (self.ssid, str(err)))

        self.debug("searching for storage pool '%s'" % storage_pool_name)
        pool_detail = next(ifilter(lambda a: a['name'] == storage_pool_name, resp), None)

        if pool_detail:
            self.debug('found')
        else:
            self.debug('not found')

        return pool_detail

    def create_volume(self, pool_id, name, size_unit, size, segment_size_kb, data_assurance_enabled):
        volume_add_req = dict(
            name=name,
            poolId=pool_id,
            sizeUnit=size_unit,
            size=size,
            segSize=segment_size_kb,
            dataAssuranceEnabled=data_assurance_enabled,
        )

        self.debug("creating volume '%s'" % name)
        try:
            (rc, resp) = request(self.api_url + "/storage-systems/%s/volumes" % (self.ssid),
                                 data=json.dumps(volume_add_req), headers=self._post_headers, method='POST',
                                 url_username=self.api_usr, url_password=self.api_pwd,
                                 validate_certs=self.validate_certs,
                                 timeout=120)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to create volume.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name, self.ssid,
                                                                                str(err)))

    def create_thin_volume(self, pool_id, name, size_unit, size, thin_volume_repo_size,
                           thin_volume_max_repo_size, data_assurance_enabled):
        thin_volume_add_req = dict(
            name=name,
            poolId=pool_id,
            sizeUnit=size_unit,
            virtualSize=size,
            repositorySize=thin_volume_repo_size,
            maximumRepositorySize=thin_volume_max_repo_size,
            dataAssuranceEnabled=data_assurance_enabled,
        )

        self.debug("creating thin-volume '%s'" % name)
        try:
            (rc, resp) = request(self.api_url + "/storage-systems/%s/thin-volumes" % (self.ssid),
                                 data=json.dumps(thin_volume_add_req), headers=self._post_headers, method='POST',
                                 url_username=self.api_usr, url_password=self.api_pwd,
                                 validate_certs=self.validate_certs,
                                 timeout=120)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to create thin volume.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name,
                                                                                self.ssid,
                                                                                str(err)))

    def delete_volume(self):
        # delete the volume
        self.debug("deleting volume '%s'" % self.volume_detail['name'])
        try:
            (rc, resp) = request(
                self.api_url + "/storage-systems/%s/%s/%s" % (self.ssid, self.volume_resource_name,
                                                              self.volume_detail['id']),
                method='DELETE', url_username=self.api_usr, url_password=self.api_pwd,
                validate_certs=self.validate_certs, timeout=120)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to delete volume.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name, self.ssid,
                                                                                str(err)))

    @property
    def volume_resource_name(self):
        if self.volume_detail['thinProvisioned']:
            return 'thin-volumes'
        else:
            return 'volumes'

    @property
    def volume_properties_changed(self):
        return self.volume_ssdcache_setting_changed  # or with other props here when extended

        # TODO: add support for r/w cache settings, owning controller, scan settings, expansion policy, growth alert threshold

    @property
    def volume_ssdcache_setting_changed(self):
        # None means ignore existing setting
        if self.ssd_cache_enabled is not None and self.ssd_cache_enabled != self.volume_detail['flashCached']:
            self.debug("flash cache setting changed")
            return True

    def update_volume_properties(self):
        update_volume_req = dict()

        # conditionally add values so we ignore unspecified props
        if self.volume_ssdcache_setting_changed:
            update_volume_req['flashCache'] = self.ssd_cache_enabled

        self.debug("updating volume properties...")
        try:
            (rc, resp) = request(
                self.api_url + "/storage-systems/%s/%s/%s/" % (self.ssid, self.volume_resource_name,
                                                               self.volume_detail['id']),
                data=json.dumps(update_volume_req), headers=self._post_headers, method='POST',
                url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs,
                timeout=120)
        except Exception:
            err = get_exception()
            self.module.fail_json(
                msg="Failed to update volume properties.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name,
                                                                                self.ssid,
                                                                                str(err)))

    @property
    def volume_needs_expansion(self):
        current_size_bytes = int(self.volume_detail['capacity'])
        requested_size_bytes = self.size * self._size_unit_map[self.size_unit]

        # TODO: check requested/current repo volume size for thin-volumes as well

        # TODO: do we need to build any kind of slop factor in here?
        return requested_size_bytes > current_size_bytes

    def expand_volume(self):
        is_thin = self.volume_detail['thinProvisioned']
        if is_thin:
            # TODO: support manual repo expansion as well
            self.debug('expanding thin volume')
            thin_volume_expand_req = dict(
                newVirtualSize=self.size,
                sizeUnit=self.size_unit
            )
            try:
                (rc, resp) = request(self.api_url + "/storage-systems/%s/thin-volumes/%s/expand" % (self.ssid,
                                                                                self.volume_detail[
                                                                                'id']),
                                     data=json.dumps(thin_volume_expand_req), headers=self._post_headers, method='POST',
                                     url_username=self.api_usr, url_password=self.api_pwd,
                                     validate_certs=self.validate_certs, timeout=120)
            except Exception:
                err = get_exception()
                self.module.fail_json(
                    msg="Failed to expand thin volume.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name,
                                                                                self.ssid,
                                                                                str(err)))

                # TODO: check return code
        else:
            self.debug('expanding volume')
            volume_expand_req = dict(
                expansionSize=self.size,
                sizeUnit=self.size_unit
            )
            try:
                (rc, resp) = request(
                    self.api_url + "/storage-systems/%s/volumes/%s/expand" % (self.ssid,
                                                                              self.volume_detail['id']),
                    data=json.dumps(volume_expand_req), headers=self._post_headers, method='POST',
                    url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs,
                    timeout=120)
            except Exception:
                err = get_exception()
                self.module.fail_json(
                    msg="Failed to expand volume.  Volume [%s].  Array Id [%s]. Error[%s]." % (self.name,
                                                                                self.ssid,
                                                                                str(err)))

            self.debug('polling for completion...')

            while True:
                try:
                    (rc, resp) = request(self.api_url + "/storage-systems/%s/volumes/%s/expand" % (self.ssid,
                                                                                self.volume_detail[
                                                                                'id']),
                                         method='GET', url_username=self.api_usr, url_password=self.api_pwd,
                                         validate_certs=self.validate_certs)
                except Exception:
                    err = get_exception()
                    self.module.fail_json(
                        msg="Failed to get volume expansion progress.  Volume [%s].  Array Id [%s]. Error[%s]." % (
                            self.name, self.ssid, str(err)))

                action = resp['action']
                percent_complete = resp['percentComplete']

                self.debug('expand action %s, %s complete...' % (action, percent_complete))

                if action == 'none':
                    self.debug('expand complete')
                    break
                else:
                    time.sleep(5)

    def apply(self):
        changed = False
        volume_exists = False
        msg = None

        self.volume_detail = self.get_volume(self.name)

        if self.volume_detail:
            volume_exists = True

            if self.state == 'absent':
                self.debug("CHANGED: volume exists, but requested state is 'absent'")
                changed = True
            elif self.state == 'present':
                # check requested volume size, see if expansion is necessary
                if self.volume_needs_expansion:
                    self.debug(
                        "CHANGED: requested volume size %s%s is larger than current size %sb" % (self.size,
                                                                                self.size_unit,
                                                                                self.volume_detail[
                                                                                'capacity']))
                    changed = True

                if self.volume_properties_changed:
                    self.debug("CHANGED: one or more volume properties have changed")
                    changed = True

        else:
            if self.state == 'present':
                self.debug("CHANGED: volume does not exist, but requested state is 'present'")
                changed = True

        if changed:
            if self.module.check_mode:
                self.debug('skipping changes due to check mode')
            else:
                if self.state == 'present':
                    if not volume_exists:
                        pool_detail = self.get_storage_pool(self.storage_pool_name)

                        if not pool_detail:
                            self.module.fail_json(msg='Requested storage pool (%s) not found' % self.storage_pool_name)

                        if self.thin_provision and not pool_detail['diskPool']:
                            self.module.fail_json(
                                msg='Thin provisioned volumes can only be located on disk pools (not volume groups)')

                        pool_id = pool_detail['id']

                        if not self.thin_provision:
                            self.create_volume(pool_id, self.name, self.size_unit, self.size, self.segment_size_kb,
                                               self.data_assurance_enabled)
                            msg = "Standard volume [%s] has been created." % (self.name)

                        else:
                            self.create_thin_volume(pool_id, self.name, self.size_unit, self.size,
                                                    self.thin_volume_repo_size, self.thin_volume_max_repo_size,
                                                    self.data_assurance_enabled)
                            msg = "Thin volume [%s] has been created." % (self.name)

                    else:  # volume exists but differs, modify...
                        if self.volume_needs_expansion:
                            self.expand_volume()
                            msg = "Volume [%s] has been expanded." % (self.name)

                    # this stuff always needs to run on present (since props can't be set on creation)
                    if self.volume_properties_changed:
                        self.update_volume_properties()
                        msg = "Properties of volume [%s] has been updated." % (self.name)

                elif self.state == 'absent':
                    self.delete_volume()
                    msg = "Volume [%s] has been deleted." % (self.name)
        else:
            self.debug("exiting with no changes")
            if self.state == 'absent':
                msg = "Volume [%s] did not exist." % (self.name)
            else:
                msg = "Volume [%s] already exists." % (self.name)

        self.module.exit_json(msg=msg, changed=changed)

def main():
    v = NetAppESeriesVolume()

    try:
        v.apply()
    except Exception:
        e = get_exception()
        v.debug("Exception in apply(): \n%s" % format_exc(e))
        v.module.fail_json(msg="Module failed. Error [%s]." % (str(e)))

if __name__ == '__main__':
    main()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net;

import dominio.eccezioni.GiocatoreDisconnessoException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.SocketTimeoutException;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author root
 */
public class Leggi extends Observable implements Runnable {

    private BufferedReader reader;
    private String message = "";
    private boolean disconnesso = false;
    PrintStream out;

    public Leggi(BufferedReader in) {
        reader = in;

    }

    /**
     * legge i messaggi
     */
    public void run() {

        try {
            message = reader.readLine();
            printMessage();

        } catch (SocketTimeoutException e) {
            run();

        } catch (IOException ex) {
            Logger.getLogger(Leggi.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            run();
        }
        if (message != null) {
            run();
        }
    }

    /**
     * stampa i messaggi
     */
    public void printMessage() {
        if (message != null) {
            this.setChanged();
            this.notifyObservers(message);
        } else if (message == null) {
            disconnesso = true;
            this.setChanged();
            this.notifyObservers(new GiocatoreDisconnessoException());
        }
    }

}


text:
package android.support.v4.app;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.InsetDrawable;
import android.support.v4.view.ViewCompat;
import android.view.Window;

// Referenced classes of package android.support.v4.app:
//            ActionBarDrawerToggle

private class <init> extends InsetDrawable
    implements android.graphics.drawable.it>
{

    private final boolean mHasMirroring;
    private float mOffset;
    private float mPosition;
    private final Rect mTmpRect;
    final ActionBarDrawerToggle this$0;

    public void draw(Canvas canvas)
    {
        int i = 1;
        copyBounds(mTmpRect);
        canvas.save();
        boolean flag;
        int j;
        if (ViewCompat.getLayoutDirection(ActionBarDrawerToggle.access$400(ActionBarDrawerToggle.this).getWindow().getDecorView()) == 1)
        {
            flag = true;
        } else
        {
            flag = false;
        }
        if (flag)
        {
            i = -1;
        }
        j = mTmpRect.width();
        canvas.translate(-mOffset * (float)j * mPosition * (float)i, 0.0F);
        if (flag && !mHasMirroring)
        {
            canvas.translate(j, 0.0F);
            canvas.scale(-1F, 1.0F);
        }
        super.draw(canvas);
        canvas.restore();
    }

    public float getPosition()
    {
        return mPosition;
    }

    public void setOffset(float f)
    {
        mOffset = f;
        invalidateSelf();
    }

    public void setPosition(float f)
    {
        mPosition = f;
        invalidateSelf();
    }

    private (Drawable drawable)
    {
        boolean flag = false;
        this$0 = ActionBarDrawerToggle.this;
        super(drawable, 0);
        if (android.os.ideDrawable.this._fld0 > 18)
        {
            flag = true;
        }
        mHasMirroring = flag;
        mTmpRect = new Rect();
    }

    mTmpRect(Drawable drawable, mTmpRect mtmprect)
    {
        this(drawable);
    }
}


text:
package br.com.mv.modulo.components.element.container;

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

import org.apache.commons.lang3.StringUtils;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;

public class MVFormGroup extends MVDiv{

	//FIXME:REMOVER ESTAS PROPRIDADES E ALTERAR A MANEIRA COMO É FEITA A VALIDAÇÃO.
	private Map<String, String> hasError;

	public void setValue(String value) {
		if(hasError == null){
			hasError = new HashMap<>();
		}
		hasError.put("value", value);
	}

	public void setRequired(String value) {
		if(hasError == null){
			hasError = new HashMap<>();
		}
		hasError.put("required", value);
	}

	public void setVisible(String value) {
		koBinding.setVisible(value);
	}

	public MVFormGroup(Arguments arguments, Element context) {
		super(arguments, context);
		domAttribute.addClassCss("form-group");

		//FIXME:REMOVER O TRECHO ABAIXO E ALTERAR A MANEIRA COMO É FEITA A VALIDAÇÃO.
		StringBuilder hasError = new StringBuilder();
		String value = this.hasError.get("value");
		String required = this.hasError.get("required");

		if(StringUtils.isNotBlank(value) && StringUtils.isNotBlank(required)){
			hasError.append(required);
			hasError.append(" && ");
			hasError.append(value).append(".isModified()");
			hasError.append(" && ");
			hasError.append("!");
			hasError.append(value).append(".isValid()");

			this.koCss.put("'has-error'", hasError.toString());
		}

	}
}


text:
class Cassandra::Flow::Action::Flag < Cassandra::Flow::Action
  action!
  attr_reader :flag, :scope, :condition, :catalog
  LIMIT_HISTORY = 5

  def setup!(name, scope, &condition)
    @flag      = name
    @scope     = Array scope
    @condition = condition

    append_name @flag.to_s
    append_name @scope.join('_')
    build_catalog
  end

  def transform(type, data)
    lock_name = [name, scope.map {|it| data[it] }].join('.')

    lock lock_name do
      record   = catalog.one scope: lock_name
      previous = record[:data] if record
      all      = record ? record[:all] : []

      case type
      when :insert
        all << data
        reflag = !previous || condition.call(data, previous)

        if all.size >= 2*LIMIT_HISTORY
          all = all.sort {|a,b| condition.call(a,b) ? -1 : 1 }.first(LIMIT_HISTORY)
        end

        if reflag
          catalog.insert scope: lock_name, data: data, all: all
          data = data.dup
          data[flag] = true
        else
          catalog.insert scope: lock_name, data: previous, all: all
        end

        if reflag and previous
          propagate_next :remove, previous.merge(flag => true)
          propagate_next :insert, previous
        end
      when :remove
        if all.delete data
          if data == previous
            data = data.dup
            data[flag] = true

            new_data = all.sort {|a,b| condition.call(a,b) ? -1 : 1 }.first
            if new_data
              propagate_next :remove, new_data
              catalog.insert scope: lock_name, data: new_data, all: all
              propagate_next :insert, new_data.merge(flag => true)
            else
              catalog.remove scope: lock_name
            end
          else
            catalog.insert scope: lock_name, data: previous, all: all
          end
        end
      when :check
        log_inspect lock_name
        log_inspect all

        if data == all.sort {|a,b| condition.call(a,b) ? -1 : 1 }.first
          data = data.merge flag => true
        end
      else
        raise ArgumentError, "unsupported type: #{type}"
      end

      data
    end
  end

  private

  def build_catalog
    @catalog = Cassandra::Mapper.new keyspace_name, name do
      key  :scope
      type :data, :marshal
      type :all,  :marshal
    end
  end
end


text:
namespace qi
{
  namespace details
  {
    // @brief Try to construct an absolute path from the given path,
    // using the platform specificity and the current program location.
    //
    // If the input path is absolute it will not change.
    // If the input path is relative and has parent information (./bar or foo/bar)
    // it will be searched from the current directory.
    // Otherwise, it will be searched in the folders given in input (first currentDirectory, then environmentPaths).
    // In this case, the file pointed by the input path within the folder shall exist and be executable.
    //
    // @param path Path to transform.
    // @param currentDirectory Path to search relative paths from. Default value: bfs::current_path()
    // @param environmentPaths List of directories to search relative path with no parent information (e.g. bar).
    // Same role as 'PATH' environment variable
    // Default value: ::boost::this_process::path()
    // @return An absolute path. The empty path if an error occurred.

    QI_API_TESTONLY Path searchExecutableAbsolutePath(const Path& path,
                                                      const boost::filesystem::path& currentDirectory = boost::filesystem::current_path(),
                                                      std::vector<boost::filesystem::path> environmentPaths = ::boost::this_process::path());
  }
}