text:
(function(){
	var component = {
		fileName: 		"World",
		classNames:		["World"],
		requirements:	["Entity"], // Extended from Entity Class
		description:	"",
		credits:		"By Luke Nickerson, 2014, 2016"
	};

	//==== WORLD
	var World = component.World = function WorldClass (options){
		options = options || {};
		options.size = options.size || {};
		options.size.x = options.size.x || 100;
		options.size.y = options.size.y || 100;

		// Extend from Entity (http://stackoverflow.com/a/15192747)
		RocketBoots.Entity.call(this, options);

		this.dimensions = options.dimensions || 2;
		this.size = new RocketBoots.Coords(options.size.x, options.size.y);
		this.min = new RocketBoots.Coords(-(this.size.x/2),-(this.size.y/2));
		this.max = new RocketBoots.Coords((this.size.x/2),(this.size.y/2));
		//this.size = new RocketBoots.Coords(600, 600);
		this.grid = {
			size : { x: 1, y: 1 }
		};
		this.entityGroups = ["all", "physical", "movable", "physics"];
		this.entities = {
			"all" : [],
			"physical" : [],
			"movable" : [],
			"physics" : []
		};
		if (options.trackTime) {
			this.day = 0;
			this.time = 0;
		}

		// World traits / booleans
		this.isBounded = options.isBounded || false;

		//console.log(this instanceof World);
	};

	component.callback = function initWorldPrototype () {
		World.prototype = new RocketBoots.Entity();	// inherit Entity
		World.prototype.constructor = World;		// point constructor back to self
		// TODO: *** ^ Add some way to auto-load entity component?

		// Sets
		World.prototype.setSizeRange = function(min, max){
			this.min.set(min);
			this.max.set(max);
			var sizeX = Math.abs(max.x) + Math.abs(min.x);
			var sizeY = Math.abs(max.y) + Math.abs(min.y);
			this.setSize(sizeX, sizeY);
		}
		World.prototype.snapToGrid = function(pos){
			pos.x = Math.round(pos.x / this.grid.size.x) * this.grid.size.x;
			pos.y = Math.round(pos.y / this.grid.size.y) * this.grid.size.y;
			return pos;
		}
		World.prototype.clearHighlighted = function(){
			this.loopOverEntities("all",function(entityIndex, ent){
				ent.isHighlighted = false;
			});
		}

		// Adds
		// *** Replace with entity functions
		/*
		World.prototype.addEntity = function(ent, groups, isFront){

			if (typeof groups == "string") groups = [groups];
			if (typeof isFront != "boolean") isFront = false;
			var grp = "", groupIndex = -1;
			// Add entity to groups
			for (var t = 0; t < groups.length; t++){
				grp = groups[t];
				this.addEntityGroup(grp);
				//console.log(ent);
				if (!ent.isInGroup(grp)) {  // Is entity not in this group yet?
					groupIndex = (this.entities[grp].push(ent) - 1);
					if (isFront) {
						ent.groups = [grp].concat(ent.groups);
					} else {
						ent.groups.push(grp);
					}
					ent.groupIndices[grp] = groupIndex;
				}
			}
			return ent;
		}
		World.prototype.addNewEntity = function(name, groups){
			var ent = new this.Entity(name, this, this.grid.size);
			groups = groups.concat("all");
			ent = this.addEntity(ent, groups);
			this.categorizeEntitiesByGroup();
			return ent;
		}

		World.prototype.addEntityGroup = function(type){
			var typeId = this.entityGroups.indexOf(type);
			if (typeId == -1) {
				typeId = (this.entityGroups.push(type) - 1);
				this.entities[type] = [];
			}
			return typeId;
		}
		World.prototype.removeEntity = function(ent, remGroups){
			//console.log("Remove groups", remGroups, typeof remGroups);
			if (typeof remGroups == "string") remGroups = [remGroups];
			else if (typeof remGroups == "undefined") remGroups = ["all"];
			// Remove "all" groups?
			if (remGroups.indexOf("all") != -1) {
				remGroups = ent.groups.join("/").split("/");
			}
			//console.log("Remove groups", remGroups, ent.groups);
			var remGroup = "", remGroupIndex = -1;
			// Loop over groups to remove
			for (var g = 0; g < remGroups.length; g++){
				remGroup = remGroups[g];
				if (ent.isInGroup(remGroup)) {

					remGroupIndex = ent.groupIndices[remGroup];
					//console.log("Removing", remGroup, remGroupIndex);
					// Remove from group array
					//this.entities[remGroup].splice(remGroupIndex, 1);
					// ^ can't splice this out or all the indices get messed up
					this.entities[remGroup][remGroupIndex] = null;
					// *** ^ This might cause memory issues??
					// Remove from entity's properties
					ent.groups.splice( ent.groups.indexOf(remGroup), 1 );
					delete ent.groupIndices[remGroup];
				}
			}
			return ent;
		}
		*/

		// Gets
		World.prototype.getRandomPosition = function(dice){
			if (typeof dice == "undefined") {
				var dice = new RocketBoots.Dice();
			}
			var x = dice.getRandomIntegerBetween(this.min.x, this.max.x);
			var y = dice.getRandomIntegerBetween(this.min.y, this.max.y);
			return new RocketBoots.Coords(x,y);
		}
		World.prototype.getRandomGridPosition = function(){
			var randPos = this.getRandomPosition();
			return this.snapToGrid(randPos);
		}
		World.prototype.getCenter = function(){
			var x = this.min.x + (this.size.x / 2);
			var y = this.min.y + (this.size.y / 2);
			return new RocketBoots.Coords(x,y);
		}
		World.prototype.getNearestEntity = function(type, pos, range){
			var nearestEnt = null;
			var nearestDistance = range;
			// *** get a subset of all entities based on range?
			// *** then only loop over them
			//console.log("------\nLoop over", type);
			this.loopOverEntitiesByType(type, function(entityIndex, ent){
				var d = ent.pos.getDistance(pos);
				//console.log(ent, d);
				if (d < nearestDistance) {
					nearestEnt = ent;
					nearestDistance = d;
				}
			});
			return nearestEnt;
		};

		// Others
		World.prototype.loopOver = function(ents, fn){
			var i = ents.length;
			while (i--) {
				//console.log("Looping over ents", i);
				if (ents[i] === null) {
					//console.warn("Entity", i, "is null", ents);
				} else {
					fn(i, ents[i]);
				}
			}
		};

		World.prototype.loopOverEntities = function(query, fn){
			var ents;
			var typeOfQuery = typeof query;
			if (typeOfQuery === 'object') {
				// TODO: fix this...
				if (typeof query.x === 'number' && typeof query.y === 'number') {
					if (typeof query.range === 'number') {
						var center = new this.Coord(query.x, query.y);
						return this.loopOverEntitiesWithinRange(query.type, center, query.range, fn);
					}
				}
			} else if (typeOfQuery === 'string') {
				return this.loopOverEntitiesByType(query, fn);
			}
		};
		World.prototype.loopOverEntitiesByType = function(type, fn) {
			var ents;
			if (typeof this.entities[type] === 'object') {
				ents = this.entities[type];
				this.loopOver(ents, fn);
			} else {
				console.warn("Cannot find type", type);
			}
			return ents;
		};

		World.prototype.loopOverEntitiesWithinRange = function(type, center, range, fn) {
			var i, ent, entsFound = [];
			if (typeof this.entities[type] === 'object') {
				ents = this.entities[type];
				i = ents.length;
				while (i--) {
					ent = ents[i];
					if (ent === null) {
						console.warn("Entity", i, "of type '", type, "' is null");
					} else if (center.getDistance(ent.pos) <= range) {
						fn(i, ent);
						entsFound.push(ent);
					}
				}
			} else {
				console.warn("Cannot find type", type);
			}
			return ents;
		};

		World.prototype.keepCoordsInBounds = function(coords){
			var wasOutOfRange = false;
			if (coords.x < this.min.x) {
				coords.x = this.min.x;
				wasOutOfRange = true;
			} else if (coords.x > this.max.x) {
				coords.x = this.max.x;
				wasOutOfRange = true;
			}
			if (coords.y < this.min.y) {
				coords.y = this.min.y;
				wasOutOfRange = true;
			} else if (coords.y > this.max.y) {
				coords.y = this.max.y;
				wasOutOfRange = true;
			}
			return wasOutOfRange;
		};

		World.prototype.isEntityInBounds = function(ent){
			var coords = ent.pos;
			return (coords.x >= this.min.x && coords.x <= this.max.x
				&& coords.y >= this.min.y && coords.y <= this.max.y);
		};

		World.prototype.categorizeEntitiesByGroup = function(){
			var w = this;
			w.entities.physical = [];
			w.entities.movable = [];
			w.entities.physics = [];
			w.loopOverEntities("all", function(entityIndex, ent){
				if (ent.isPhysical) {
					w.entities.physical.push(ent);
					if (ent.isMovable) w.entities.physics.push(ent);
				}
				if (ent.isMovable)
					w.entities.movable.push(ent);
			});
		};

		World.prototype.applyPhysics = function(physics){
			physics.apply(this);
		};

		// Bring in a pointer to the Coords class from RocketBoots or a global object
		//World.prototype.Coords = (typeof RocketBoots.Coords == "function") ? RocketBoots.Coords : Coords;
		World.prototype.Entity = (typeof RocketBoots.Entity == "function") ? RocketBoots.Entity : Entity;
	}

	// Install into RocketBoots if it exists
	if (typeof RocketBoots === "object") {
		RocketBoots.installComponent(component);
	} else { // Otherwise put the classes on the global window object
		for (var i = 0; i < component.classNames.length; i++) {
			window[component.classNames[i]] = component[component.classNames[i]];
		}
	}
})();


text:
    #ifdef BOOST_TYPE_ERASURE_SOURCE
        #define BOOST_TYPE_ERASURE_DECL BOOST_SYMBOL_EXPORT
    #else
        #define BOOST_TYPE_ERASURE_DECL BOOST_SYMBOL_IMPORT
    #endif
#else
    #define BOOST_TYPE_ERASURE_DECL
#endif

#if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TYPE_ERASURE_NO_LIB) && !defined(BOOST_TYPE_ERASURE_SOURCE)

    #define BOOST_LIB_NAME boost_type_erasure

    #if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TYPE_ERASURE_DYN_LINK)
        #define BOOST_DYN_LINK
    #endif

    #include <boost/config/auto_link.hpp>

#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
Good selectors can be hard to find. It's always nice when the elements we need have automation friendly attributes, but sometimes thats not an option. These wildcards can help when you just need to match on part of what attributes are present.

## Contains `*=`
There are times where finding a unique substring within a value is just the solution needed. In this case from the [Automation Practice](http://automationpractice.com/index.php) website, there are multiple products on a page all with the same markup and even the same text description. The link to the item though has the products unique id in it.

Rather than use [string interpolation](https://en.wikipedia.org/wiki/String_interpolation) to generate the full link text, we can instead use `*=` to match just part of attributes value.
```
<h5 itemprop="name">
    <a class="product-name" href="http://automationpractice.com/index.php?id_product=3&controller=product" title="Printed Dress" itemprop="url">
        Printed Dress
    </a>
</h5>
```
Using the class name in conjunction with `*=` to select the specific item on the page.
```
.product-name[href*='3&']
```

The site has another section with the same item listed so the first find will narrow the scope of the search to the `homefeatured` section then look up our item and click on it.
```ruby
page.find("ul[class~='homefeatured']").find(".product-name[href*='3&']").click
```
## Starts With `^=`
Sometimes part of the attribute values you need are static but with dynamic or seemingly random data at the end. What seemed like a perfectly good and unique selector suddenly stops working the next time you run you tests or when new elements are added to the page.  For cases like this using `^=` will match on the beginning of the attributes value.

For a real world example from [Ultimate QA's complicated page](https://www.ultimateqa.com/complicated-page/)

```
<input id="user_login_5c88a03ff2e3d" placeholder="Username" class="input" type="text" value="" name="log">
```
In this case the class attribute has some auto-generated value appended to the end of what otherwise would be a very easily located element.

Using `^=` with the selector to find based on `user_login`:
```
input[id^='user_login']
```

Then setting a value for that element:
``` ruby
page.find("input[id^='user_login']").set('my_name_is')
```

## Ends With `$=`
Just like using `^=` to match on the beginning of a string, to match on the end of a string use `$=`.

For a real world example from the [Association for Software Testing](https://www.associationforsoftwaretesting.org)
```
<ul id="top-menu" class="nav">
    <li id="menu-item-63669" class="menu-item menu-item-type-post_type
    menu-item-object-page menu-item-has-children menu-item-63669">
    <a href="https://www.associationforsoftwaretesting.org/about/">About</a>
</ul>

```
In this particular case it may seem just as easy to match on the link text `About`. It would work, but it gives me pause. The text could be changed, it could be internationalized and tests may work in one locale but break in others. The url to the about page is more likely to remain unchanged, but who wants to include the full url in a selector.

The selector will match on the end of the route.
```
a[href$='about/']
```
and clicking that element:
```ruby
page.find(".nav").find("a[href$='about/']")

```

## In List `~=`
Sometimes the element you are searching for has a value you want to use to locate it but it's not the only value assigned to the attribute. You often see this with the `class` attribute but it's not a problem because using the `.` selector will find a specific class in the list of assigned classes.

For a real world example from [Github](https://github.com/SeleniumHQ/selenium)

```
<a data-hotkey="g p" itemprop="url" class="js-selected-navigation-item reponav-item"
  data-selected-links="repo_pulls checks /SeleniumHQ/selenium/pulls" href="/SeleniumHQ/selenium/pulls">
```

Looking at the `data-hotkey` attribute as an example, it may not seem that bad to use the full text to match on since it is so short and a hotkey seems unlikely to change. Not every attribute is so short and friendly though, I wouldn't want to try a full text match for `data-selected-links`.

Using `~=` will look for the value in a space separated list.

The selector to find based on ` p ` value in `data-hotkey`:

```
a[data-hotkey~='p']
```

and clicking that element:
```ruby
page.find("a[data-hotkey~='p']").click

```


text:
import GeometryArc from '../geometry/arc';
import Element from './element';
import Path from './path';
import Paintable from '../mixins/paintable';
import Measurable from '../mixins/measurable';
import defineGeometryAccessors from '../accessors/define-geometry-accessors';
import { defined } from '../util';

var DEFAULT_STROKE = "#000";

var Arc = (function (Element) {
    function Arc(geometry, options) {
        if ( geometry === void 0 ) geometry = new GeometryArc();
        if ( options === void 0 ) options = {};

        Element.call(this, options);

        this.geometry(geometry);

        if (!defined(this.options.stroke)) {
            this.stroke(DEFAULT_STROKE);
        }
    }

    if ( Element ) Arc.__proto__ = Element;
    Arc.prototype = Object.create( Element && Element.prototype );
    Arc.prototype.constructor = Arc;

    Arc.prototype._bbox = function _bbox (matrix) {
        return this._geometry.bbox(matrix);
    };

    Arc.prototype.rawBBox = function rawBBox () {
        return this.geometry().bbox();
    };

    Arc.prototype.toPath = function toPath () {
        var path = new Path();
        var curvePoints = this.geometry().curvePoints();

        if (curvePoints.length > 0) {
            path.moveTo(curvePoints[0].x, curvePoints[0].y);

            for (var i = 1; i < curvePoints.length; i += 3) {
                path.curveTo(curvePoints[i], curvePoints[i + 1], curvePoints[i + 2]);
            }
        }

        return path;
    };

    Arc.prototype._containsPoint = function _containsPoint (point) {
        return this.geometry().containsPoint(point);
    };

    Arc.prototype._isOnPath = function _isOnPath (point) {
        return this.geometry()._isOnPath(point, this.options.stroke.width / 2);
    };

    return Arc;
}(Element));

Arc.prototype.nodeType = "Arc";

Paintable.extend(Arc.prototype);
Measurable.extend(Arc.prototype);
defineGeometryAccessors(Arc.prototype, [ "geometry" ]);

export default Arc;
//# sourceMappingURL=arc.js.map


text:
begin
  require 'rest_client'
  require 'xmlsimple'
  require 'json'

  # Method for logging
  def log(level, msg, update_message=false)
    @method = 'vCloud_VMPowerOperations'
    $evm.log(level, "#{@method} - #{msg}")
  end

  # dump_root
  def dump_root()
    log(:info, "Root:<$evm.root> Begin $evm.root.attributes")
    $evm.root.attributes.sort.each { |k, v| log(:info, "Root:<$evm.root> Attribute - #{k}: #{v}")}
    log(:info, "Root:<$evm.root> End $evm.root.attributes")
    log(:info, "")
  end

  def login_vcloud(servername, username, password, ref)
    url = "https://#{servername}"+"#{ref}"
    headers = {}
    headers[:content_type] = :xml
    headers[:accept] = 'application/*+xml;version=5.1'
    headers[:content_length] = 0

    params = {
      :method=>:post,
      :url=>url,
      :user=>username,
      :password=>password,
      :headers=>headers
    }
    log(:info, "Logging into vCloud: #{url}")
    authorization_response = RestClient::Request.new(params).execute
    log(:info, "Successfully logged into vCloud: #{authorization_response.code}")
    @cookie = authorization_response.headers[:x_vcloud_authorization]
    log(:info, "Detected API session cookie: #{@cookie}")
    unless authorization_response.code == 200 || authorization_response.code == 201 || authorization_response.code == 202
      raise "Failed to log into vCloud: #{authorization_response.code}"
    end
  end

  def call_vcloud(action, ref=nil, content_type=:xml, accept=:xml, body=nil)

    servername = nil || $evm.object['servername']
    username = nil || $evm.object['username']
    password = nil || $evm.object.decrypt('password')

    login_vcloud(servername, username, password, '/api/sessions' ) if @cookie.nil?

    # if ref is a url then use that one instead
    unless ref.nil?
      url = ref if ref.include?('http')
    end
    url ||= "https://#{servername}"+"#{ref}"

    headers = {}
    headers[:content_type] = content_type
    headers[:accept] = accept
    headers[:content_length] = 0
    headers[:x_vcloud_authorization] = @cookie

    params = {}
    params[:method] = action
    params[:url] = url
    params[:user] = username
    params[:password] = password
    params[:headers] = headers

    if content_type == :json
      params[:payload] = JSON.generate(body) if body
    else
      params[:payload] = body if body
    end
    log(:info, "Calling vCloud: #{url} action: #{action} payload: #{params[:payload]}")

    response = RestClient::Request.new(params).execute
    unless response.code == 200 || response.code == 201 || response.code == 202
      raise "Failure vCloud Response: #{response.code}"
    end
    # use XmlSimple to convert xml to ruby hash
    response_hash = XmlSimple.xml_in(response)
    return response_hash
  end

  log(:info, "CFME Automate Method Started", true)

  # dump all root attributes to the log
  dump_root()

  power_function = $evm.root['dialog_vcloud_operation']
  url = $evm.root['dialog_vcloud_vm']

  case power_function
  when 'on'
    href  = "#{url}"+"/power/action/powerOn"
  when 'off'
    href  = "#{url}"+"/power/action/powerOff"
  end

  log(:info, "Powering #{power_function} vCloud VM}")
  power_response = call_vcloud(:post, href, :xml, 'application/*+xml;version=5.1' )
  log(:info, "Inspecting power_response: #{power_response.inspect}")

  # Exit method
  log(:info, "CFME Automate Method Ended", true)
  exit MIQ_OK

  # Set Ruby rescue behavior
rescue => err
  log(:error, "[#{err}]\n#{err.backtrace.join("\n")}")
  exit MIQ_ABORT
end


text:
#include <aws/compute-optimizer/model/EBSFinding.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ComputeOptimizer
  {
    namespace Model
    {
      namespace EBSFindingMapper
      {

        static const int Optimized_HASH = HashingUtils::HashString("Optimized");
        static const int NotOptimized_HASH = HashingUtils::HashString("NotOptimized");

        EBSFinding GetEBSFindingForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Optimized_HASH)
          {
            return EBSFinding::Optimized;
          }
          else if (hashCode == NotOptimized_HASH)
          {
            return EBSFinding::NotOptimized;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<EBSFinding>(hashCode);
          }

          return EBSFinding::NOT_SET;
        }

        Aws::String GetNameForEBSFinding(EBSFinding enumValue)
        {
          switch(enumValue)
          {
          case EBSFinding::Optimized:
            return "Optimized";
          case EBSFinding::NotOptimized:
            return "NotOptimized";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

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


text:
let gulp = require('gulp');
let runSequence = require('run-sequence');
let to5 = require('gulp-babel');
let paths = require('../paths');
let sass = require('gulp-sass');
let compilerOptions = require('../babel-options');
let assign = Object.assign || require('object.assign');

gulp.task('build-html', function() {
  return gulp.src(paths.html)
    .pipe(gulp.dest(paths.output + 'es2015'))
    .pipe(gulp.dest(paths.output + 'commonjs'))
    .pipe(gulp.dest(paths.output + 'amd'))
    .pipe(gulp.dest(paths.output + 'system'));
});

gulp.task('build-css', function() {
  return gulp.src(paths.css)
    .pipe(gulp.dest(paths.output + 'es2015'))
    .pipe(gulp.dest(paths.output + 'commonjs'))
    .pipe(gulp.dest(paths.output + 'amd'))
    .pipe(gulp.dest(paths.output + 'system'));
});

gulp.task('build-scss', function() {
  return gulp.src(paths.scss)
    .pipe(gulp.dest(paths.output + 'styles/sass'))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.output + 'styles/css'));
});

gulp.task('build-scss-root', function() {
  return gulp.src(paths.scssRoot)
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.output + 'es2015'))
    .pipe(gulp.dest(paths.output + 'commonjs'))
    .pipe(gulp.dest(paths.output + 'amd'))
    .pipe(gulp.dest(paths.output + 'system'));
});

gulp.task('build-es2015', function() {
  return gulp.src(paths.source)
    .pipe(to5(assign({}, compilerOptions.es2015())))
    .pipe(gulp.dest(paths.output + 'es2015'));
});

gulp.task('build-commonjs', function() {
  return gulp.src(paths.source)
    .pipe(to5(assign({}, compilerOptions.commonjs())))
    .pipe(gulp.dest(paths.output + 'commonjs'));
});

gulp.task('build-amd', function() {
  return gulp.src(paths.source)
    .pipe(to5(assign({}, compilerOptions.amd())))
    .pipe(gulp.dest(paths.output + 'amd'));
});

gulp.task('build-system', function() {
  return gulp.src(paths.source)
    .pipe(to5(assign({}, compilerOptions.system())))
    .pipe(gulp.dest(paths.output + 'system'));
});

gulp.task('build', function(callback) {
  return runSequence(
    'clean',
    ['build-html', 'build-scss', 'build-scss-root', 'build-css', 'build-es2015', 'build-commonjs', 'build-amd', 'build-system'],
    callback
  );
});


text:
/**
Check if a URL is absolute.

@param url - The URL to check.

@example
```
import isAbsoluteUrl = require('is-absolute-url');

isAbsoluteUrl('http://sindresorhus.com/foo/bar');
//=> true

isAbsoluteUrl('//sindresorhus.com');
//=> false

isAbsoluteUrl('foo/bar');
//=> false
```
*/
declare function isAbsoluteUrl(url: string): boolean;

export = isAbsoluteUrl;


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for AzureFunctionActivityMethod.
 */
public final class AzureFunctionActivityMethod extends ExpandableStringEnum<AzureFunctionActivityMethod> {
    /** Static value GET for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod GET = fromString("GET");

    /** Static value POST for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod POST = fromString("POST");

    /** Static value PUT for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod PUT = fromString("PUT");

    /** Static value DELETE for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod DELETE = fromString("DELETE");

    /** Static value OPTIONS for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod OPTIONS = fromString("OPTIONS");

    /** Static value HEAD for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod HEAD = fromString("HEAD");

    /** Static value TRACE for AzureFunctionActivityMethod. */
    public static final AzureFunctionActivityMethod TRACE = fromString("TRACE");

    /**
     * Creates or finds a AzureFunctionActivityMethod from its string representation.
     * @param name a name to look for
     * @return the corresponding AzureFunctionActivityMethod
     */
    @JsonCreator
    public static AzureFunctionActivityMethod fromString(String name) {
        return fromString(name, AzureFunctionActivityMethod.class);
    }

    /**
     * @return known AzureFunctionActivityMethod values
     */
    public static Collection<AzureFunctionActivityMethod> values() {
        return values(AzureFunctionActivityMethod.class);
    }
}


text:
package org.eclipse.freemarker.internal.core.documentModel;

import org.eclipse.freemarker.internal.core.documentModel.dom.DOMDocumentForFM;
import org.eclipse.freemarker.internal.core.documentModel.dom.FMDOMModelParser;
import org.eclipse.freemarker.internal.core.documentModel.dom.FMDOMModelUpdater;
import org.eclipse.wst.html.core.internal.document.DOMStyleModelImpl;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.xml.core.internal.document.XMLModelParser;
import org.eclipse.wst.xml.core.internal.document.XMLModelUpdater;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.w3c.dom.Document;

/*
 * The PHPModel will support both the DOM style interface and Freemarker specific API's.
 */
public class DOMModelForFM extends DOMStyleModelImpl {

	/*
	 * This is modeled after what is done for JSP
	 */
	protected Document internalCreateDocument() {
		DOMDocumentForFM document = new DOMDocumentForFM();
		document.setModel(this);
		return document;
	}

	protected XMLModelParser createModelParser() {
		return new FMDOMModelParser(this);
	}

	protected XMLModelUpdater createModelUpdater() {
		return new FMDOMModelUpdater(this);
	}
	@Override
	public IndexedRegion getIndexedRegion(int offset) {
		IndexedRegion result = super.getIndexedRegion(offset);
		if(result == null && offset == getDocument().getEndOffset()){
			return (IDOMNode) getDocument().getLastChild();
		}
		return super.getIndexedRegion(offset);
	}
}


text:
.. synergy-maps documentation master file, created by
   sphinx-quickstart on Thu Jul 16 18:43:22 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

========================================
Welcome to synergy-maps's documentation!
========================================

.. include:: introduction.rst

Contents
========

.. toctree::
   :maxdepth: 4

   introduction
   frontend
   backend
   documentation
   git-structure
   API

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
{% for comment in comments %}
    {{ comment }}
{% endfor %}

{% if not model.is_fragment %}
struct {{ model.class_name }} {
struct Keys{
{% endif %}
{% for field in fields %}
    static let {{ field.settings_name }} = "{{ field.settings_key }}"
{% endfor %}
{% if not model.is_fragment %}
}
    static let  userDefaults = UserDefaults.standard
{% endif %}

{% for field in fields %}
    static var {{ field.name }}:{{ field.settings_type_annotation }}{
    set{
    {{ field.settings_set_stmt }}
    {% if model.settings_sync_on_save %}
        userDefaults.synchronize()
    {% endif %}
    }get{
    {{ field.settings_get_stmt }}
    }
    }
{% endfor %}

{% if not model.is_fragment %}
static func registerDefaults(){
let defaults : [String:Any] = [
{% for field in fields %}
    {% if field.settings_default_value != 'nil' %}
    Keys.{{ field.settings_name }}:{{ field.settings_default_value }},
    {% endif %}
{% endfor %}
]
userDefaults.register(defaults: defaults)
}

}
{% else %}
{% for field in fields %}
    Keys.{{ field.settings_name }}:{{ field.settings_default_value }},
{% endfor %}
{% endif %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yandex
{
    public enum LangType : byte { ru_RU, uk_UA, be_BY, en_US, en_BR, tr_TR }

    public enum KindType : byte { house, street, metro, district, locality }

    public enum ScoType : byte { longlat, latlong }
}


text:
namespace cel {

// Describes a function.
class FunctionDescriptor final {
 public:
  FunctionDescriptor(absl::string_view name, bool receiver_style,
                     std::vector<Kind> types, bool is_strict = true)
      : impl_(std::make_shared<Impl>(name, receiver_style, std::move(types),
                                     is_strict)) {}

  // Function name.
  const std::string& name() const { return impl_->name; }

  // Whether function is receiver style i.e. true means arg0.name(args[1:]...).
  bool receiver_style() const { return impl_->receiver_style; }

  // The argmument types the function accepts.
  //
  // TODO(issues/5): make this kinds
  const std::vector<Kind>& types() const { return impl_->types; }

  // if true (strict, default), error or unknown arguments are propagated
  // instead of calling the function. if false (non-strict), the function may
  // receive error or unknown values as arguments.
  bool is_strict() const { return impl_->is_strict; }

  // Helper for matching a descriptor. This tests that the shape is the same --
  // |other| accepts the same number and types of arguments and is the same call
  // style).
  bool ShapeMatches(const FunctionDescriptor& other) const {
    return ShapeMatches(other.receiver_style(), other.types());
  }
  bool ShapeMatches(bool receiver_style, absl::Span<const Kind> types) const;

  bool operator==(const FunctionDescriptor& other) const;

  bool operator<(const FunctionDescriptor& other) const;

 private:
  struct Impl final {
    Impl(absl::string_view name, bool receiver_style, std::vector<Kind> types,
         bool is_strict)
        : name(name),
          types(std::move(types)),
          receiver_style(receiver_style),
          is_strict(is_strict) {}

    std::string name;
    std::vector<Kind> types;
    bool receiver_style;
    bool is_strict;
  };

  std::shared_ptr<const Impl> impl_;
};

}  // namespace cel

#endif  // THIRD_PARTY_CEL_CPP_BASE_FUNCTION_H_


text:
import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store';
import { INITIAL_STATE } from './initialState';

export function requestStateReducer(
  state: RequestState = INITIAL_STATE.requestState,
  action:
    typeof actions.startRequesting.shape |
    typeof actions.endRequesting.shape |
    typeof actions.requestFailure.shape |
    typeof actions.clearErrors.shape
): RequestState {
  switch (action.type) {
    case actions.startRequesting.type: {
      return {
        ...state,
        requesting: {
          ...state.requesting,
          [action.payload]: true
        }
      };
    }
    case actions.endRequesting.type: {
      return {
        ...state,
        requesting: {
          ...state.requesting,
          [action.payload]: undefined
        }
      };
    }
    case actions.requestFailure.type: {
      const { actionType, error } = action.payload;
      return {
        ...state,
        requesting: {
          ...state.requesting,
          [actionType]: undefined
        },
        errors: {
          ...state.errors,
          [actionType]: error
        }
      };
    }
    case actions.clearErrors.type: {
      return {
        ...state,
        errors: {}
      };
    }
    default:
      return state;
  }
}


text:
package io.aeron.cluster.service;

import io.aeron.*;
import io.aeron.archive.client.AeronArchive;
import io.aeron.archive.status.RecordingPos;
import io.aeron.cluster.client.ClusterException;
import io.aeron.cluster.codecs.*;
import io.aeron.driver.Configuration;
import io.aeron.logbuffer.BufferClaim;
import io.aeron.logbuffer.Header;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.status.ReadableCounter;
import org.agrona.CloseHelper;
import org.agrona.DirectBuffer;
import org.agrona.SemanticVersion;
import org.agrona.collections.Long2ObjectHashMap;
import org.agrona.concurrent.*;
import org.agrona.concurrent.status.CountersReader;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static io.aeron.Aeron.NULL_VALUE;
import static io.aeron.archive.client.AeronArchive.NULL_POSITION;
import static io.aeron.archive.codecs.SourceLocation.LOCAL;
import static io.aeron.cluster.client.AeronCluster.SESSION_HEADER_LENGTH;
import static io.aeron.cluster.service.ClusteredServiceContainer.Configuration.*;
import static org.agrona.concurrent.status.CountersReader.NULL_COUNTER_ID;

class ClusteredServiceAgent implements Agent, Cluster, IdleStrategy
{
    static final long MARK_FILE_UPDATE_INTERVAL_MS = TimeUnit.NANOSECONDS.toMillis(MARK_FILE_UPDATE_INTERVAL_NS);

    private volatile boolean isAbort;
    private boolean isServiceActive;
    private final int serviceId;
    private int memberId = NULL_VALUE;
    private long ackId = 0;
    private long terminationPosition = NULL_POSITION;
    private long timeOfLastMarkFileUpdateMs;
    private long cachedTimeMs;
    private long clusterTime;
    private long logPosition = NULL_POSITION;
    private long closeHandlerRegistrationId;

    private final IdleStrategy idleStrategy;
    private final ClusteredServiceContainer.Context ctx;
    private final Aeron aeron;
    private final AgentInvoker aeronAgentInvoker;
    private final ClusteredService service;
    private final ConsensusModuleProxy consensusModuleProxy;
    private final ServiceAdapter serviceAdapter;
    private final EpochClock epochClock;
    private final UnsafeBuffer headerBuffer = new UnsafeBuffer(
        new byte[Configuration.MAX_UDP_PAYLOAD_LENGTH - DataHeaderFlyweight.HEADER_LENGTH]);
    private final DirectBufferVector headerVector = new DirectBufferVector(headerBuffer, 0, SESSION_HEADER_LENGTH);
    private final SessionMessageHeaderEncoder sessionMessageHeaderEncoder = new SessionMessageHeaderEncoder();
    private final Long2ObjectHashMap<ClientSession> sessionByIdMap = new Long2ObjectHashMap<>();
    private final Collection<ClientSession> unmodifiableClientSessions =
        new UnmodifiableClientSessionCollection(sessionByIdMap.values());

    private final BoundedLogAdapter logAdapter;
    private String activeLifecycleCallbackName;
    private ReadableCounter roleCounter;
    private ReadableCounter commitPosition;
    private ActiveLogEvent activeLogEvent;
    private Role role = Role.FOLLOWER;
    private TimeUnit timeUnit = null;

    ClusteredServiceAgent(final ClusteredServiceContainer.Context ctx)
    {
        logAdapter = new BoundedLogAdapter(this);
        this.ctx = ctx;

        aeron = ctx.aeron();
        aeronAgentInvoker = ctx.aeron().conductorAgentInvoker();
        service = ctx.clusteredService();
        idleStrategy = ctx.idleStrategy();
        serviceId = ctx.serviceId();
        epochClock = ctx.epochClock();

        final String channel = ctx.controlChannel();
        consensusModuleProxy = new ConsensusModuleProxy(aeron.addPublication(channel, ctx.consensusModuleStreamId()));
        serviceAdapter = new ServiceAdapter(aeron.addSubscription(channel, ctx.serviceStreamId()), this);
        sessionMessageHeaderEncoder.wrapAndApplyHeader(headerBuffer, 0, new MessageHeaderEncoder());
    }

    public void onStart()
    {
        closeHandlerRegistrationId = aeron.addCloseHandler(this::abort);
        final CountersReader counters = aeron.countersReader();
        roleCounter = awaitClusterRoleCounter(counters, ctx.clusterId());
        commitPosition = awaitCommitPositionCounter(counters, ctx.clusterId());

        recoverState(counters);
    }

    public void onClose()
    {
        aeron.removeCloseHandler(closeHandlerRegistrationId);

        if (isAbort)
        {
            ctx.abortLatch().countDown();
        }
        else
        {

            final CountedErrorHandler errorHandler = ctx.countedErrorHandler();
            if (isServiceActive)
            {
                isServiceActive = false;
                try
                {
                    service.onTerminate(this);
                }
                catch (final Throwable ex)
                {
                    errorHandler.onError(ex);
                }
            }

            if (!ctx.ownsAeronClient() && !aeron.isClosed())
            {
                for (final ClientSession session : sessionByIdMap.values())
                {
                    session.disconnect(errorHandler);
                }

                CloseHelper.close(errorHandler, logAdapter);
                CloseHelper.close(errorHandler, serviceAdapter);
                CloseHelper.close(errorHandler, consensusModuleProxy);
            }
        }

        ctx.close();
    }

    public int doWork()
    {
        int workCount = 0;

        if (checkForClockTick())
        {
            pollServiceAdapter();
            workCount += 1;
        }

        if (null != logAdapter.image())
        {
            final int polled = logAdapter.poll(commitPosition.get());
            workCount += polled;

            if (0 == polled && logAdapter.isDone())
            {
                closeLog();
            }
        }

        return workCount;
    }

    public String roleName()
    {
        return ctx.serviceName();
    }

    public Cluster.Role role()
    {
        return role;
    }

    public int memberId()
    {
        return memberId;
    }

    public Aeron aeron()
    {
        return aeron;
    }

    public ClusteredServiceContainer.Context context()
    {
        return ctx;
    }

    public ClientSession getClientSession(final long clusterSessionId)
    {
        return sessionByIdMap.get(clusterSessionId);
    }

    public Collection<ClientSession> clientSessions()
    {
        return unmodifiableClientSessions;
    }

    public void forEachClientSession(final Consumer<? super ClientSession> action)
    {
        sessionByIdMap.values().forEach(action);
    }

    public boolean closeClientSession(final long clusterSessionId)
    {
        checkForLifecycleCallback();

        final ClientSession clientSession = sessionByIdMap.get(clusterSessionId);
        if (clientSession == null)
        {
            throw new ClusterException("unknown clusterSessionId: " + clusterSessionId);
        }

        if (clientSession.isClosing())
        {
            return true;
        }

        if (consensusModuleProxy.closeSession(clusterSessionId))
        {
            clientSession.markClosing();
            return true;
        }

        return false;
    }

    public TimeUnit timeUnit()
    {
        return timeUnit;
    }

    public long time()
    {
        return clusterTime;
    }

    public long logPosition()
    {
        return logPosition;
    }

    public boolean scheduleTimer(final long correlationId, final long deadline)
    {
        checkForLifecycleCallback();

        return consensusModuleProxy.scheduleTimer(correlationId, deadline);
    }

    public boolean cancelTimer(final long correlationId)
    {
        checkForLifecycleCallback();

        return consensusModuleProxy.cancelTimer(correlationId);
    }

    public long offer(final DirectBuffer buffer, final int offset, final int length)
    {
        checkForLifecycleCallback();
        sessionMessageHeaderEncoder.clusterSessionId(0);

        return consensusModuleProxy.offer(headerBuffer, 0, SESSION_HEADER_LENGTH, buffer, offset, length);
    }

    public long offer(final DirectBufferVector[] vectors)
    {
        checkForLifecycleCallback();
        sessionMessageHeaderEncoder.clusterSessionId(0);
        vectors[0] = headerVector;

        return consensusModuleProxy.offer(vectors);
    }

    public long tryClaim(final int length, final BufferClaim bufferClaim)
    {
        checkForLifecycleCallback();
        sessionMessageHeaderEncoder.clusterSessionId(0);

        return consensusModuleProxy.tryClaim(length + SESSION_HEADER_LENGTH, bufferClaim, headerBuffer);
    }

    public IdleStrategy idleStrategy()
    {
        return this;
    }

    public void reset()
    {
        idleStrategy.reset();
    }

    public void idle()
    {
        idleStrategy.idle();
        checkForClockTick();
    }

    public void idle(final int workCount)
    {
        idleStrategy.idle(workCount);
        if (workCount <= 0)
        {
            checkForClockTick();
        }
    }

    void onJoinLog(
        final long leadershipTermId,
        final long logPosition,
        final long maxLogPosition,
        final int memberId,
        final int logSessionId,
        final int logStreamId,
        final boolean isStartup,
        final String logChannel)
    {
        logAdapter.maxLogPosition(logPosition);
        activeLogEvent = new ActiveLogEvent(
            leadershipTermId, logPosition, maxLogPosition, memberId, logSessionId, logStreamId, isStartup, logChannel);
    }

    void onServiceTerminationPosition(final long logPosition)
    {
        terminationPosition = logPosition;
    }

    void onSessionMessage(
        final long logPosition,
        final long clusterSessionId,
        final long timestamp,
        final DirectBuffer buffer,
        final int offset,
        final int length,
        final Header header)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;
        final ClientSession clientSession = sessionByIdMap.get(clusterSessionId);

        service.onSessionMessage(clientSession, timestamp, buffer, offset, length, header);
    }

    void onTimerEvent(final long logPosition, final long correlationId, final long timestamp)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;
        service.onTimerEvent(correlationId, timestamp);
    }

    void onSessionOpen(
        final long leadershipTermId,
        final long logPosition,
        final long clusterSessionId,
        final long timestamp,
        final int responseStreamId,
        final String responseChannel,
        final byte[] encodedPrincipal)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;

        if (sessionByIdMap.containsKey(clusterSessionId))
        {
            throw new ClusterException("clashing open clusterSessionId=" + clusterSessionId +
                " leadershipTermId=" + leadershipTermId + " logPosition=" + logPosition);
        }

        final ClientSession session = new ClientSession(
            clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, this);

        if (Role.LEADER == role && ctx.isRespondingService())
        {
            session.connect(aeron);
        }

        sessionByIdMap.put(clusterSessionId, session);
        service.onSessionOpen(session, timestamp);
    }

    void onSessionClose(
        final long leadershipTermId,
        final long logPosition,
        final long clusterSessionId,
        final long timestamp,
        final CloseReason closeReason)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;
        final ClientSession session = sessionByIdMap.remove(clusterSessionId);

        if (null == session)
        {
            throw new ClusterException(
                "unknown clusterSessionId=" + clusterSessionId + " for close reason=" + closeReason +
                " leadershipTermId=" + leadershipTermId + " logPosition=" + logPosition);
        }

        session.disconnect(ctx.countedErrorHandler());
        service.onSessionClose(session, timestamp, closeReason);
    }

    void onServiceAction(
        final long leadershipTermId, final long logPosition, final long timestamp, final ClusterAction action)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;
        executeAction(action, logPosition, leadershipTermId);
    }

    void onNewLeadershipTermEvent(
        final long leadershipTermId,
        final long logPosition,
        final long timestamp,
        final long termBaseLogPosition,
        final int leaderMemberId,
        final int logSessionId,
        final TimeUnit timeUnit,
        final int appVersion)
    {
        if (SemanticVersion.major(ctx.appVersion()) != SemanticVersion.major(appVersion))
        {
            ctx.errorHandler().onError(new ClusterException(
                "incompatible version: " + SemanticVersion.toString(ctx.appVersion()) +
                " log=" + SemanticVersion.toString(appVersion)));
            ctx.terminationHook().run();
        }
        else
        {
            sessionMessageHeaderEncoder.leadershipTermId(leadershipTermId);
            this.logPosition = logPosition;
            clusterTime = timestamp;
            this.timeUnit = timeUnit;

            service.onNewLeadershipTermEvent(
                leadershipTermId,
                logPosition,
                timestamp,
                termBaseLogPosition,
                leaderMemberId,
                logSessionId,
                timeUnit,
                appVersion);
        }
    }

    void onMembershipChange(
        final long logPosition, final long timestamp, final ChangeType changeType, final int memberId)
    {
        this.logPosition = logPosition;
        clusterTime = timestamp;

        if (memberId == this.memberId && changeType == ChangeType.QUIT)
        {
            terminate();
        }
    }

    void addSession(
        final long clusterSessionId,
        final int responseStreamId,
        final String responseChannel,
        final byte[] encodedPrincipal)
    {
        sessionByIdMap.put(clusterSessionId, new ClientSession(
            clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, this));
    }

    void handleError(final Throwable ex)
    {
        ctx.countedErrorHandler().onError(ex);
    }

    long offer(
        final long clusterSessionId,
        final Publication publication,
        final DirectBuffer buffer,
        final int offset,
        final int length)
    {
        checkForLifecycleCallback();

        if (role != Cluster.Role.LEADER)
        {
            return ClientSession.MOCKED_OFFER;
        }

        if (null == publication)
        {
            return Publication.NOT_CONNECTED;
        }

        sessionMessageHeaderEncoder
            .clusterSessionId(clusterSessionId)
            .timestamp(clusterTime);

        return publication.offer(headerBuffer, 0, SESSION_HEADER_LENGTH, buffer, offset, length, null);
    }

    long offer(final long clusterSessionId, final Publication publication, final DirectBufferVector[] vectors)
    {
        checkForLifecycleCallback();

        if (role != Cluster.Role.LEADER)
        {
            return ClientSession.MOCKED_OFFER;
        }

        if (null == publication)
        {
            return Publication.NOT_CONNECTED;
        }

        sessionMessageHeaderEncoder
            .clusterSessionId(clusterSessionId)
            .timestamp(clusterTime);

        vectors[0] = headerVector;

        return publication.offer(vectors, null);
    }

    long tryClaim(
        final long clusterSessionId,
        final Publication publication,
        final int length,
        final BufferClaim bufferClaim)
    {
        checkForLifecycleCallback();

        if (role != Cluster.Role.LEADER)
        {
            final int maxPayloadLength = headerBuffer.capacity() - SESSION_HEADER_LENGTH;
            if (length > maxPayloadLength)
            {
                throw new IllegalArgumentException(
                    "claim exceeds maxPayloadLength=" + maxPayloadLength + ", length=" + length);
            }

            bufferClaim.wrap(headerBuffer, 0, length + SESSION_HEADER_LENGTH);
            return ClientSession.MOCKED_OFFER;
        }

        if (null == publication)
        {
            return Publication.NOT_CONNECTED;
        }

        final long offset = publication.tryClaim(length + SESSION_HEADER_LENGTH, bufferClaim);
        if (offset > 0)
        {
            sessionMessageHeaderEncoder
                .clusterSessionId(clusterSessionId)
                .timestamp(clusterTime);

            bufferClaim.putBytes(headerBuffer, 0, SESSION_HEADER_LENGTH);
        }

        return offset;
    }

    private void role(final Role newRole)
    {
        if (newRole != role)
        {
            role = newRole;

            activeLifecycleCallbackName = "onRoleChange";
            try
            {
                service.onRoleChange(newRole);
            }
            finally
            {
                activeLifecycleCallbackName = null;
            }
        }
    }

    private void recoverState(final CountersReader counters)
    {
        final int recoveryCounterId = awaitRecoveryCounter(counters);
        logPosition = RecoveryState.getLogPosition(counters, recoveryCounterId);
        clusterTime = RecoveryState.getTimestamp(counters, recoveryCounterId);
        final long leadershipTermId = RecoveryState.getLeadershipTermId(counters, recoveryCounterId);
        sessionMessageHeaderEncoder.leadershipTermId(leadershipTermId);
        isServiceActive = true;

        activeLifecycleCallbackName = "onStart";
        try
        {
            if (NULL_VALUE != leadershipTermId)
            {
                loadSnapshot(RecoveryState.getSnapshotRecordingId(counters, recoveryCounterId, serviceId));
            }
            else
            {
                service.onStart(this, null);
            }
        }
        finally
        {
            activeLifecycleCallbackName = null;
        }

        final long id = ackId++;
        idleStrategy.reset();
        while (!consensusModuleProxy.ack(logPosition, clusterTime, id, aeron.clientId(), serviceId))
        {
            idle();
        }
    }

    private int awaitRecoveryCounter(final CountersReader counters)
    {
        idleStrategy.reset();
        int counterId = RecoveryState.findCounterId(counters, ctx.clusterId());
        while (NULL_COUNTER_ID == counterId)
        {
            idle();
            counterId = RecoveryState.findCounterId(counters, ctx.clusterId());
        }

        return counterId;
    }

    private void closeLog()
    {
        logPosition = Math.max(logAdapter.image().position(), logPosition);
        CloseHelper.close(ctx.countedErrorHandler(), logAdapter);
        role(Role.get(roleCounter.get()));
    }

    private void joinActiveLog(final ActiveLogEvent activeLog)
    {
        Subscription logSubscription = aeron.addSubscription(activeLog.channel, activeLog.streamId);
        try
        {
            memberId = activeLog.memberId;
            ctx.clusterMarkFile().memberId(memberId);
            sessionMessageHeaderEncoder.leadershipTermId(activeLog.leadershipTermId);
            role(Role.get(roleCounter.get()));

            final long id = ackId++;
            idleStrategy.reset();
            while (!consensusModuleProxy.ack(activeLog.logPosition, clusterTime, id, NULL_VALUE, serviceId))
            {
                idle();
            }

            logAdapter.image(awaitImage(activeLog.sessionId, logSubscription));
            logAdapter.maxLogPosition(activeLog.maxLogPosition);
            logSubscription = null;
        }
        finally
        {
            CloseHelper.quietClose(logSubscription);
        }

        for (final ClientSession session : sessionByIdMap.values())
        {
            if (Role.LEADER == role)
            {
                if (ctx.isRespondingService() && !activeLog.isStartup)
                {
                    session.connect(aeron);
                }

                session.resetClosing();
            }
            else
            {
                session.disconnect(ctx.countedErrorHandler());
            }
        }
    }

    private Image awaitImage(final int sessionId, final Subscription subscription)
    {
        idleStrategy.reset();
        Image image;
        while ((image = subscription.imageBySessionId(sessionId)) == null)
        {
            idle();
        }

        return image;
    }

    private ReadableCounter awaitClusterRoleCounter(final CountersReader counters, final int clusterId)
    {
        idleStrategy.reset();
        int counterId = ClusterCounters.find(counters, CLUSTER_NODE_ROLE_TYPE_ID, clusterId);
        while (NULL_COUNTER_ID == counterId)
        {
            idle();
            counterId = ClusterCounters.find(counters, CLUSTER_NODE_ROLE_TYPE_ID, clusterId);
        }

        return new ReadableCounter(counters, counterId);
    }

    private ReadableCounter awaitCommitPositionCounter(final CountersReader counters, final int clusterId)
    {
        idleStrategy.reset();
        int counterId = ClusterCounters.find(counters, COMMIT_POSITION_TYPE_ID, clusterId);
        while (NULL_COUNTER_ID == counterId)
        {
            idle();
            counterId = ClusterCounters.find(counters, COMMIT_POSITION_TYPE_ID, clusterId);
        }

        return new ReadableCounter(counters, counterId);
    }

    private void loadSnapshot(final long recordingId)
    {
        try (AeronArchive archive = AeronArchive.connect(ctx.archiveContext().clone()))
        {
            final String channel = ctx.replayChannel();
            final int streamId = ctx.replayStreamId();
            final int sessionId = (int)archive.startReplay(recordingId, 0, NULL_VALUE, channel, streamId);

            final String replaySessionChannel = ChannelUri.addSessionId(channel, sessionId);
            try (Subscription subscription = aeron.addSubscription(replaySessionChannel, streamId))
            {
                final Image image = awaitImage(sessionId, subscription);
                loadState(image);
                service.onStart(this, image);
            }
        }
    }

    private void loadState(final Image image)
    {
        final ServiceSnapshotLoader snapshotLoader = new ServiceSnapshotLoader(image, this);
        while (true)
        {
            final int fragments = snapshotLoader.poll();
            if (snapshotLoader.isDone())
            {
                break;
            }

            if (fragments == 0)
            {
                if (image.isClosed())
                {
                    throw new ClusterException("snapshot ended unexpectedly");
                }
            }

            idle(fragments);
        }

        final int appVersion = snapshotLoader.appVersion();
        if (SemanticVersion.major(ctx.appVersion()) != SemanticVersion.major(appVersion))
        {
            throw new ClusterException(
                "incompatible version: " + SemanticVersion.toString(ctx.appVersion()) +
                " snapshot=" + SemanticVersion.toString(appVersion));
        }

        timeUnit = snapshotLoader.timeUnit();
    }

    private long onTakeSnapshot(final long logPosition, final long leadershipTermId)
    {
        final long recordingId;

        try (AeronArchive archive = AeronArchive.connect(ctx.archiveContext().clone());
            ExclusivePublication publication = aeron.addExclusivePublication(
                ctx.snapshotChannel(), ctx.snapshotStreamId()))
        {
            final String channel = ChannelUri.addSessionId(ctx.snapshotChannel(), publication.sessionId());
            archive.startRecording(channel, ctx.snapshotStreamId(), LOCAL, true);
            final CountersReader counters = aeron.countersReader();
            final int counterId = awaitRecordingCounter(publication.sessionId(), counters, archive);
            recordingId = RecordingPos.getRecordingId(counters, counterId);

            snapshotState(publication, logPosition, leadershipTermId);
            checkForClockTick();
            service.onTakeSnapshot(publication);

            awaitRecordingComplete(recordingId, publication.position(), counters, counterId, archive);
        }

        return recordingId;
    }

    private void awaitRecordingComplete(
        final long recordingId,
        final long position,
        final CountersReader counters,
        final int counterId,
        final AeronArchive archive)
    {
        idleStrategy.reset();
        while (counters.getCounterValue(counterId) < position)
        {
            idle();
            archive.checkForErrorResponse();

            if (!RecordingPos.isActive(counters, counterId, recordingId))
            {
                throw new ClusterException("recording stopped unexpectedly: " + recordingId);
            }
        }
    }

    private void snapshotState(
        final ExclusivePublication publication, final long logPosition, final long leadershipTermId)
    {
        final ServiceSnapshotTaker snapshotTaker = new ServiceSnapshotTaker(
            publication, idleStrategy, aeronAgentInvoker);

        snapshotTaker.markBegin(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0, timeUnit, ctx.appVersion());

        for (final ClientSession clientSession : sessionByIdMap.values())
        {
            snapshotTaker.snapshotSession(clientSession);
        }

        snapshotTaker.markEnd(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0, timeUnit, ctx.appVersion());
    }

    private void executeAction(final ClusterAction action, final long logPosition, final long leadershipTermId)
    {
        if (ClusterAction.SNAPSHOT == action)
        {
            final long recordingId = onTakeSnapshot(logPosition, leadershipTermId);
            final long id = ackId++;
            idleStrategy.reset();
            while (!consensusModuleProxy.ack(logPosition, clusterTime, id, recordingId, serviceId))
            {
                idle();
            }
        }
    }

    private int awaitRecordingCounter(final int sessionId, final CountersReader counters, final AeronArchive archive)
    {
        idleStrategy.reset();
        int counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
        while (NULL_COUNTER_ID == counterId)
        {
            idle();
            archive.checkForErrorResponse();
            counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
        }

        return counterId;
    }

    private boolean checkForClockTick()
    {
        if (isAbort || aeron.isClosed())
        {
            isAbort = true;
            throw new AgentTerminationException("unexpected Aeron close");
        }

        final long nowMs = epochClock.time();
        if (cachedTimeMs != nowMs)
        {
            cachedTimeMs = nowMs;

            if (Thread.interrupted())
            {
                isAbort = true;
                throw new AgentTerminationException("unexpected interrupt - " + context().clusterDir());
            }

            if (null != aeronAgentInvoker)
            {
                aeronAgentInvoker.invoke();
                if (isAbort || aeron.isClosed())
                {
                    isAbort = true;
                    throw new AgentTerminationException("unexpected Aeron close");
                }
            }

            if (nowMs >= (timeOfLastMarkFileUpdateMs + MARK_FILE_UPDATE_INTERVAL_MS))
            {
                ctx.clusterMarkFile().updateActivityTimestamp(nowMs);
                timeOfLastMarkFileUpdateMs = nowMs;
            }

            return true;
        }

        return false;
    }

    private void pollServiceAdapter()
    {
        serviceAdapter.poll();

        if (null != activeLogEvent && null == logAdapter.image())
        {
            final ActiveLogEvent event = activeLogEvent;
            activeLogEvent = null;
            joinActiveLog(event);
        }

        if (NULL_POSITION != terminationPosition && logPosition >= terminationPosition)
        {
            terminate();
        }
    }

    private void terminate()
    {
        isServiceActive = false;
        activeLifecycleCallbackName = "onTerminate";
        try
        {
            service.onTerminate(this);
        }
        catch (final Exception ex)
        {
            ctx.countedErrorHandler().onError(ex);
        }
        finally
        {
            activeLifecycleCallbackName = null;
        }

        final long id = ackId++;
        while (!consensusModuleProxy.ack(logPosition, clusterTime, id, NULL_VALUE, serviceId))
        {
            idle();
        }

        terminationPosition = NULL_VALUE;
        ctx.terminationHook().run();
    }

    private void checkForLifecycleCallback()
    {
        if (null != activeLifecycleCallbackName)
        {
            throw new ClusterException(
                "sending messages or scheduling timers is not allowed from " + activeLifecycleCallbackName);
        }
    }

    private void abort()
    {
        isAbort = true;

        try
        {
            ctx.abortLatch().await(AgentRunner.RETRY_CLOSE_TIMEOUT_MS * 3L, TimeUnit.MILLISECONDS);
        }
        catch (final InterruptedException ignore)
        {
            Thread.currentThread().interrupt();
        }
    }
}


text:
layout: collection
permalink: portfolio
collection: portfolio
---

Aqui você pode ver os meus principais trabalhos. Se você se interessou, entre em contato comigo! ✌


text:
from keystone.common.validation import parameter_types

_region_properties = {
    'description': parameter_types.description,
    # NOTE(lbragstad): Regions use ID differently. The user can specify the ID
    # or it will be generated automatically.
    'id': {
        'type': 'string'
    },
    'parent_region_id': {
        'type': ['string', 'null']
    },
    'url': parameter_types.url
}

region_create = {
    'type': 'object',
    'properties': _region_properties,
    'additionalProperties': True
    # NOTE(lbragstad): No parameters are required for creating regions.
}

region_update = {
    'type': 'object',
    'properties': _region_properties,
    'minProperties': 1,
    'additionalProperties': True
}

_service_properties = {
    'enabled': parameter_types.boolean,
    'name': parameter_types.name,
    'type': {
        'type': 'string',
        'minLength': 1,
        'maxLength': 255
    }
}

service_create = {
    'type': 'object',
    'properties': _service_properties,
    'required': ['type'],
    'additionalProperties': True,
}

service_update = {
    'type': 'object',
    'properties': _service_properties,
    'minProperties': 1,
    'additionalProperties': True
}

_endpoint_properties = {
    'enabled': parameter_types.boolean,
    'interface': {
        'type': 'string',
        'enum': ['admin', 'internal', 'public']
    },
    'region_id': {
        'type': 'string'
    },
    'region': {
        'type': 'string'
    },
    'service_id': {
        'type': 'string'
    },
    'url': parameter_types.url
}

endpoint_create = {
    'type': 'object',
    'properties': _endpoint_properties,
    'required': ['interface', 'service_id', 'url'],
    'additionalProperties': True
}

endpoint_update = {
    'type': 'object',
    'properties': _endpoint_properties,
    'minProperties': 1,
    'additionalProperties': True
}


text:
<script type="text/html" id="survey-rows">
    <!-- ko foreach: { data: koRows, as: 'row'} -->
    <div data-bind="visible: row.koVisible, css: panel.data.css.row">
        <!-- ko foreach: { data: row.koElements, as: 'question' , afterRender: row.koAfterRender } -->
            <!-- ko if: question.isPanel -->
            <!-- ko template: { name: 'survey-panel', data: question, afterRender: $parent.panel.koPanelAfterRender } --><!-- /ko -->
            <!-- /ko -->
            <!-- ko if: !question.isPanel -->
            <!-- ko template: { name: 'survey-question', data: question, afterRender: $parent.panel.koQuestionAfterRender } --><!-- /ko -->
            <!-- /ko -->
        <!-- /ko -->
    </div>
    <!-- /ko -->
</script>


text:
$: << File.dirname(__FILE__)
require 'bitescript/asm'
require 'bitescript/signature'
require 'bitescript/bytecode'
require 'bitescript/builder'

module BiteScript
  VERSION = '0.0.3'

  include BiteScript::ASM
  JAVA1_4 = Opcodes::V1_4
  JAVA1_5 = Opcodes::V1_5
  JAVA1_6 = Opcodes::V1_6
  JAVA1_7 = Opcodes::V1_7

  class << self
    attr_accessor :bytecode_version

    BiteScript.bytecode_version = JAVA1_4
  end
end


text:
layout: data_model
title: EffectsType
this_version: 1.2
---

EffectsTypeIncident Schema

Represents a list of incident effects that an incident is tagged with.

      <form id="nav-version">
        <select>

            <option value="1.2" selected="selected">STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" >STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      Effect1..n

          ControlledVocabularyStringType

Represents a single effect that this incident is tagged with.

This field is implemented through the xsi:type controlled vocabulary extension mechanism. The default vocabulary type is IncidentEffectVocab-1.0 in the http://stix.mitre.org/default_vocabularies-1 namespace. This type is defined in the stix_default_vocabularies.xsd file or at the URL http://stix.mitre.org/XMLSchema/default_vocabularies/1.2.0/stix_default_vocabularies.xsd.

Users may also define their own vocabulary using the type extension mechanism, specify a vocabulary name and reference using the attributes, or simply use this as a string field.


text:
using System.Collections.Generic;
using Templater;

namespace TheElvenScrolls.Wrappers.Abstractions
{
    public interface IToolbox
    {
        IList<string> Justify(string text, int width);
        string JustifyNextLine(ref string left, int width);
        int PredictLength(string text);
        string CreateTemplate(IList<string> text, Template template);
    }
}


text:
import { debounce } from "lodash"
import { DeepZoomTileID } from "./DeepZoomTile"

/**
 * The Pyramid class is responsible for deciding which tiles to load at any given point in time.
 *
 * After every update it traverses from the top of the pyramid to the bottom, loading layer-by-layer.
 */
export class DeepZoomPyramid {
  // Tile IDs indexed by level
  levels: DeepZoomTileID[][] = []
  // Store whether or not a tile is loaded and what to do when it should be loaded
  currentTiles: { [id: string]: { loaded: boolean; onShouldLoad: null | (() => void) } } = {}

  /**
   * Called by Tile on initial render
   */
  willMount(id: DeepZoomTileID) {
    if (!this.levels[id.level]) {
      this.levels[id.level] = [id]
    } else {
      this.levels[id.level].push(id)
    }
    this.currentTiles[id.toString()] = { loaded: false, onShouldLoad: null }
  }

  /**
   * Called by Tile after the Tile has mounted
   */
  didMount({ id, onShouldLoad }: { id: DeepZoomTileID; onShouldLoad: () => void }) {
    this.currentTiles[id.toString()].onShouldLoad = onShouldLoad
    this.update()
  }

  /**
   * Called by Tile after the Tile unmounts
   */
  didUnmount(id: DeepZoomTileID) {
    delete this.currentTiles[id.toString()]
    const levelIds = this.levels[id.level]
    if (levelIds.length === 1) {
      delete this.levels[id.level]
    } else {
      levelIds.splice(levelIds.indexOf(id), 1)
    }
    this.update()
  }

  /**
   * Called by Tile after the Tile's image loads
   */
  didLoad(id: DeepZoomTileID) {
    this.currentTiles[id.toString()].loaded = true
    this.update()
  }

  isTileFinishedLoading(id: DeepZoomTileID) {
    const current = this.currentTiles[id.toString()]
    if (!current) {
      // this tile is not being shown so yes it kinda has finished
      return true
    }
    return current.loaded
  }

  triggerLoad(id: DeepZoomTileID) {
    const record = this.currentTiles[id.toString()]
    if (record && record.onShouldLoad) {
      record.onShouldLoad()
      record.onShouldLoad = null
    }
  }

  private _update() {
    // 25 is safe because that's like 2^25 pixels wide or tall.
    for (let level = 25; level >= 0; level--) {
      const levelIds = this.levels[level]
      if (!levelIds) {
        continue
      }
      let isLoading = false
      for (const id of levelIds) {
        if (!this.isTileFinishedLoading(id)) {
          this.triggerLoad(id)
          isLoading = true
        }
      }
      if (isLoading) {
        return
      }
    }
  }

  // tslint:disable-next-line:member-ordering
  update = debounce(this._update.bind(this), 16, { trailing: true })
}


text:
function onRequest(context) {
    var constants = require("/app/modules/constants.js");
    var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
    var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
    var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"];

    var groupId = request.getParameter("groupId");

    var viewModel = {};
    var title = "Devices";
    if (groupId) {
        var group = groupModule.getGroup(groupId);
        if (group) {
            title = group.name + " " + title;
            viewModel.roles = groupModule.getRolesOfGroup(groupId);
            viewModel.group = group;
        }
    }
    viewModel.title = title;
    var currentUser = session.get(constants.USER_SESSION_KEY);
    if (currentUser) {
        viewModel.permissions = {};
        var uiPermissions = userModule.getUIPermissions();
        viewModel.permissions.list = stringify(uiPermissions);
        if (uiPermissions.ADD_DEVICE) {
            viewModel.permissions.enroll = true;
        }
        viewModel.currentUser = currentUser;
        var deviceCount = 0;
        if (groupId) {
            deviceCount = groupModule.getGroupDeviceCount(groupId);
        } else {
            deviceCount = deviceModule.getDevicesCount();
        }
        if (deviceCount > 0) {
            viewModel.deviceCount = deviceCount;
            var utility = require("/app/modules/utility.js").utility;
            var typesListResponse = deviceModule.getDeviceTypes();
            var deviceTypes = [];
            if (typesListResponse["status"] == "success") {
                var data = typesListResponse.content.deviceTypes;
                if (data) {
                    for (var i = 0; i < data.length; i++) {
                        var config = utility.getDeviceTypeConfig(data[i]);
						var category = "iot";
						var label =  data[i];
						var analyticsEnabled = "false";
						var groupingEnabled = "true";
						var analyticsView = null;
                        if (config) {
							var deviceType = config.deviceType;
							category = deviceType.category;
							label = deviceType.label;
							analyticsEnabled = deviceType.analyticsEnabled;
							groupingEnabled = deviceType.groupingEnabled;
							analyticsView = deviceType.analyticsView;
                        }

                        deviceTypes.push({
                                             "type": data[i],
                                             "category": category,
                                             "label": label,
                                             "thumb": utility.getDeviceThumb(data[i]),
                                             "analyticsEnabled": analyticsEnabled,
                                             "groupingEnabled": groupingEnabled,
                                             "analyticsView" : analyticsView
                                         });
                    }
                }
            }
            viewModel.deviceTypes = stringify(deviceTypes);
        }
    }

    var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
    var serverUrl = mdmProps["httpsURL"];
    var portalUrl = mdmProps["portalURL"];
    var userDomain = context.user.domain;
    viewModel.serverUrl = serverUrl;
    viewModel.portalUrl = portalUrl;
    viewModel.userDomain = userDomain;
    return viewModel;
}


text:
/*************************************************************************/
/*  base_button.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "base_button.h"

#include "core/os/keyboard.h"
#include "scene/main/window.h"
#include "scene/scene_string_names.h"

void BaseButton::_unpress_group() {
	if (!button_group.is_valid()) {
		return;
	}

	if (toggle_mode) {
		status.pressed = true;
	}

	for (BaseButton *E : button_group->buttons) {
		if (E == this) {
			continue;
		}

		E->set_pressed(false);
	}
}

void BaseButton::gui_input(const Ref<InputEvent> &p_event) {
	ERR_FAIL_COND(p_event.is_null());

	if (status.disabled) { // no interaction with disabled button
		return;
	}

	Ref<InputEventMouseButton> mouse_button = p_event;
	bool ui_accept = p_event->is_action("ui_accept") && !p_event->is_echo();

	bool button_masked = mouse_button.is_valid() && (mouse_button_to_mask(mouse_button->get_button_index()) & button_mask) != MouseButton::NONE;
	if (button_masked || ui_accept) {
		was_mouse_pressed = button_masked;

		on_action_event(p_event);
		return;
	}

	Ref<InputEventMouseMotion> mouse_motion = p_event;
	if (mouse_motion.is_valid()) {
		if (status.press_attempt) {
			bool last_press_inside = status.pressing_inside;
			status.pressing_inside = has_point(mouse_motion->get_position());
			if (last_press_inside != status.pressing_inside) {
				update();
			}
		}
	}
}

void BaseButton::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_MOUSE_ENTER: {
			status.hovering = true;
			update();
		} break;

		case NOTIFICATION_MOUSE_EXIT: {
			status.hovering = false;
			update();
		} break;

		case NOTIFICATION_DRAG_BEGIN:
		case NOTIFICATION_SCROLL_BEGIN: {
			if (status.press_attempt) {
				status.press_attempt = false;
				update();
			}
		} break;

		case NOTIFICATION_FOCUS_ENTER: {
			update();
		} break;

		case NOTIFICATION_FOCUS_EXIT: {
			if (status.press_attempt) {
				status.press_attempt = false;
				update();
			} else if (status.hovering) {
				update();
			}
		} break;

		case NOTIFICATION_VISIBILITY_CHANGED:
		case NOTIFICATION_EXIT_TREE: {
			if (p_what == NOTIFICATION_VISIBILITY_CHANGED && is_visible_in_tree()) {
				break;
			}
			if (!toggle_mode) {
				status.pressed = false;
			}
			status.hovering = false;
			status.press_attempt = false;
			status.pressing_inside = false;
		} break;
	}
}

void BaseButton::_pressed() {
	GDVIRTUAL_CALL(_pressed);
	pressed();
	emit_signal(SNAME("pressed"));
}

void BaseButton::_toggled(bool p_pressed) {
	GDVIRTUAL_CALL(_toggled, p_pressed);
	toggled(p_pressed);
	emit_signal(SNAME("toggled"), p_pressed);
}

void BaseButton::on_action_event(Ref<InputEvent> p_event) {
	if (p_event->is_pressed()) {
		status.press_attempt = true;
		status.pressing_inside = true;
		emit_signal(SNAME("button_down"));
	}

	if (status.press_attempt && status.pressing_inside) {
		if (toggle_mode) {
			bool is_pressed = p_event->is_pressed();
			if (Object::cast_to<InputEventShortcut>(*p_event)) {
				is_pressed = false;
			}
			if ((is_pressed && action_mode == ACTION_MODE_BUTTON_PRESS) || (!is_pressed && action_mode == ACTION_MODE_BUTTON_RELEASE)) {
				if (action_mode == ACTION_MODE_BUTTON_PRESS) {
					status.press_attempt = false;
					status.pressing_inside = false;
				}
				status.pressed = !status.pressed;
				_unpress_group();
				if (button_group.is_valid()) {
					button_group->emit_signal(SNAME("pressed"), this);
				}
				_toggled(status.pressed);
				_pressed();
			}
		} else {
			if ((p_event->is_pressed() && action_mode == ACTION_MODE_BUTTON_PRESS) || (!p_event->is_pressed() && action_mode == ACTION_MODE_BUTTON_RELEASE)) {
				_pressed();
			}
		}
	}

	if (!p_event->is_pressed()) {
		Ref<InputEventMouseButton> mouse_button = p_event;
		if (mouse_button.is_valid()) {
			if (!has_point(mouse_button->get_position())) {
				status.hovering = false;
			}
		}
		status.press_attempt = false;
		status.pressing_inside = false;
		emit_signal(SNAME("button_up"));
	}

	update();
}

void BaseButton::pressed() {
}

void BaseButton::toggled(bool p_pressed) {
}

void BaseButton::set_disabled(bool p_disabled) {
	if (status.disabled == p_disabled) {
		return;
	}

	status.disabled = p_disabled;
	if (p_disabled) {
		if (!toggle_mode) {
			status.pressed = false;
		}
		status.press_attempt = false;
		status.pressing_inside = false;
	}
	update();
}

bool BaseButton::is_disabled() const {
	return status.disabled;
}

void BaseButton::set_pressed(bool p_pressed) {
	if (!toggle_mode) {
		return;
	}
	if (status.pressed == p_pressed) {
		return;
	}
	status.pressed = p_pressed;

	if (p_pressed) {
		_unpress_group();
		if (button_group.is_valid()) {
			button_group->emit_signal(SNAME("pressed"), this);
		}
	}
	_toggled(status.pressed);

	update();
}

void BaseButton::set_pressed_no_signal(bool p_pressed) {
	if (!toggle_mode) {
		return;
	}
	if (status.pressed == p_pressed) {
		return;
	}
	status.pressed = p_pressed;

	update();
}

bool BaseButton::is_pressing() const {
	return status.press_attempt;
}

bool BaseButton::is_pressed() const {
	return toggle_mode ? status.pressed : status.press_attempt;
}

bool BaseButton::is_hovered() const {
	return status.hovering;
}

BaseButton::DrawMode BaseButton::get_draw_mode() const {
	if (status.disabled) {
		return DRAW_DISABLED;
	};

	if (!status.press_attempt && status.hovering) {
		if (status.pressed) {
			return DRAW_HOVER_PRESSED;
		}

		return DRAW_HOVER;
	} else {
		/* determine if pressed or not */

		bool pressing;
		if (status.press_attempt) {
			pressing = (status.pressing_inside || keep_pressed_outside);
			if (status.pressed) {
				pressing = !pressing;
			}
		} else {
			pressing = status.pressed;
		}

		if (pressing) {
			return DRAW_PRESSED;
		} else {
			return DRAW_NORMAL;
		}
	}

	return DRAW_NORMAL;
}

void BaseButton::set_toggle_mode(bool p_on) {
	// Make sure to set 'pressed' to false if we are not in toggle mode
	if (!p_on) {
		set_pressed(false);
	}

	toggle_mode = p_on;
}

bool BaseButton::is_toggle_mode() const {
	return toggle_mode;
}

void BaseButton::set_shortcut_in_tooltip(bool p_on) {
	shortcut_in_tooltip = p_on;
}

bool BaseButton::is_shortcut_in_tooltip_enabled() const {
	return shortcut_in_tooltip;
}

void BaseButton::set_action_mode(ActionMode p_mode) {
	action_mode = p_mode;
}

BaseButton::ActionMode BaseButton::get_action_mode() const {
	return action_mode;
}

void BaseButton::set_button_mask(MouseButton p_mask) {
	button_mask = p_mask;
}

MouseButton BaseButton::get_button_mask() const {
	return button_mask;
}

void BaseButton::set_keep_pressed_outside(bool p_on) {
	keep_pressed_outside = p_on;
}

bool BaseButton::is_keep_pressed_outside() const {
	return keep_pressed_outside;
}

void BaseButton::set_shortcut(const Ref<Shortcut> &p_shortcut) {
	shortcut = p_shortcut;
	set_process_shortcut_input(shortcut.is_valid());
}

Ref<Shortcut> BaseButton::get_shortcut() const {
	return shortcut;
}

void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) {
	ERR_FAIL_COND(p_event.is_null());

	if (!_is_focus_owner_in_shortcut_context()) {
		return;
	}

	if (!is_disabled() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) {
		on_action_event(p_event);
		accept_event();
	}
}

String BaseButton::get_tooltip(const Point2 &p_pos) const {
	String tooltip = Control::get_tooltip(p_pos);
	if (shortcut_in_tooltip && shortcut.is_valid() && shortcut->has_valid_event()) {
		String text = shortcut->get_name() + " (" + shortcut->get_as_text() + ")";
		if (!tooltip.is_empty() && shortcut->get_name().nocasecmp_to(tooltip) != 0) {
			text += "\n" + atr(tooltip);
		}
		tooltip = text;
	}
	return tooltip;
}

void BaseButton::set_button_group(const Ref<ButtonGroup> &p_group) {
	if (button_group.is_valid()) {
		button_group->buttons.erase(this);
	}

	button_group = p_group;

	if (button_group.is_valid()) {
		button_group->buttons.insert(this);
	}

	update(); //checkbox changes to radio if set a buttongroup
}

Ref<ButtonGroup> BaseButton::get_button_group() const {
	return button_group;
}

void BaseButton::set_shortcut_context(Node *p_node) {
	if (p_node != nullptr) {
		shortcut_context = p_node->get_instance_id();
	} else {
		shortcut_context = ObjectID();
	}
}

Node *BaseButton::get_shortcut_context() const {
	Object *ctx_obj = ObjectDB::get_instance(shortcut_context);
	Node *ctx_node = Object::cast_to<Node>(ctx_obj);

	return ctx_node;
}

bool BaseButton::_is_focus_owner_in_shortcut_context() const {
	if (shortcut_context == ObjectID()) {
		// No context, therefore global - always "in" context.
		return true;
	}

	Node *ctx_node = get_shortcut_context();
	Control *vp_focus = get_viewport() ? get_viewport()->gui_get_focus_owner() : nullptr;

	// If the context is valid and the viewport focus is valid, check if the context is the focus or is a parent of it.
	return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
}

bool BaseButton::_was_pressed_by_mouse() const {
	return was_mouse_pressed;
}

void BaseButton::_bind_methods() {
	ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &BaseButton::set_pressed);
	ClassDB::bind_method(D_METHOD("is_pressed"), &BaseButton::is_pressed);
	ClassDB::bind_method(D_METHOD("set_pressed_no_signal", "pressed"), &BaseButton::set_pressed_no_signal);
	ClassDB::bind_method(D_METHOD("is_hovered"), &BaseButton::is_hovered);
	ClassDB::bind_method(D_METHOD("set_toggle_mode", "enabled"), &BaseButton::set_toggle_mode);
	ClassDB::bind_method(D_METHOD("is_toggle_mode"), &BaseButton::is_toggle_mode);
	ClassDB::bind_method(D_METHOD("set_shortcut_in_tooltip", "enabled"), &BaseButton::set_shortcut_in_tooltip);
	ClassDB::bind_method(D_METHOD("is_shortcut_in_tooltip_enabled"), &BaseButton::is_shortcut_in_tooltip_enabled);
	ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &BaseButton::set_disabled);
	ClassDB::bind_method(D_METHOD("is_disabled"), &BaseButton::is_disabled);
	ClassDB::bind_method(D_METHOD("set_action_mode", "mode"), &BaseButton::set_action_mode);
	ClassDB::bind_method(D_METHOD("get_action_mode"), &BaseButton::get_action_mode);
	ClassDB::bind_method(D_METHOD("set_button_mask", "mask"), &BaseButton::set_button_mask);
	ClassDB::bind_method(D_METHOD("get_button_mask"), &BaseButton::get_button_mask);
	ClassDB::bind_method(D_METHOD("get_draw_mode"), &BaseButton::get_draw_mode);
	ClassDB::bind_method(D_METHOD("set_keep_pressed_outside", "enabled"), &BaseButton::set_keep_pressed_outside);
	ClassDB::bind_method(D_METHOD("is_keep_pressed_outside"), &BaseButton::is_keep_pressed_outside);

	ClassDB::bind_method(D_METHOD("set_shortcut", "shortcut"), &BaseButton::set_shortcut);
	ClassDB::bind_method(D_METHOD("get_shortcut"), &BaseButton::get_shortcut);

	ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group);
	ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group);

	ClassDB::bind_method(D_METHOD("set_shortcut_context", "node"), &BaseButton::set_shortcut_context);
	ClassDB::bind_method(D_METHOD("get_shortcut_context"), &BaseButton::get_shortcut_context);

	GDVIRTUAL_BIND(_pressed);
	GDVIRTUAL_BIND(_toggled, "button_pressed");

	ADD_SIGNAL(MethodInfo("pressed"));
	ADD_SIGNAL(MethodInfo("button_up"));
	ADD_SIGNAL(MethodInfo("button_down"));
	ADD_SIGNAL(MethodInfo("toggled", PropertyInfo(Variant::BOOL, "button_pressed")));

	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_in_tooltip"), "set_shortcut_in_tooltip", "is_shortcut_in_tooltip_enabled");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "button_pressed"), "set_pressed", "is_pressed");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "action_mode", PROPERTY_HINT_ENUM, "Button Press,Button Release"), "set_action_mode", "get_action_mode");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "button_mask", PROPERTY_HINT_FLAGS, "Mouse Left, Mouse Right, Mouse Middle"), "set_button_mask", "get_button_mask");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "keep_pressed_outside"), "set_keep_pressed_outside", "is_keep_pressed_outside");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut", PROPERTY_HINT_RESOURCE_TYPE, "Shortcut"), "set_shortcut", "get_shortcut");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "button_group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut_context", PROPERTY_HINT_RESOURCE_TYPE, "Node"), "set_shortcut_context", "get_shortcut_context");

	BIND_ENUM_CONSTANT(DRAW_NORMAL);
	BIND_ENUM_CONSTANT(DRAW_PRESSED);
	BIND_ENUM_CONSTANT(DRAW_HOVER);
	BIND_ENUM_CONSTANT(DRAW_DISABLED);
	BIND_ENUM_CONSTANT(DRAW_HOVER_PRESSED);

	BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_PRESS);
	BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_RELEASE);
}

BaseButton::BaseButton() {
	set_focus_mode(FOCUS_ALL);
}

BaseButton::~BaseButton() {
	if (button_group.is_valid()) {
		button_group->buttons.erase(this);
	}
}

void ButtonGroup::get_buttons(List<BaseButton *> *r_buttons) {
	for (BaseButton *E : buttons) {
		r_buttons->push_back(E);
	}
}

TypedArray<BaseButton> ButtonGroup::_get_buttons() {
	TypedArray<BaseButton> btns;
	for (const BaseButton *E : buttons) {
		btns.push_back(E);
	}

	return btns;
}

BaseButton *ButtonGroup::get_pressed_button() {
	for (BaseButton *E : buttons) {
		if (E->is_pressed()) {
			return E;
		}
	}

	return nullptr;
}

void ButtonGroup::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_pressed_button"), &ButtonGroup::get_pressed_button);
	ClassDB::bind_method(D_METHOD("get_buttons"), &ButtonGroup::_get_buttons);

	ADD_SIGNAL(MethodInfo("pressed", PropertyInfo(Variant::OBJECT, "button", PROPERTY_HINT_RESOURCE_TYPE, "BaseButton")));
}

ButtonGroup::ButtonGroup() {
	set_local_to_scene(true);
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources xmlns:tools="http://schemas.android.com/tools">
  <string name="altitude">Altitud</string>
  <string name="cannot_edit_completed_form">Este formulario no podrá ser editado una vez que se haya marcado como completado. Este puede ser encriptado.</string>
  <string name="capture_video">Grabar video</string>
  <string name="password">Contraseña</string>
  <!--http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html-->
  <!--http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html-->
  <!--http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html-->
  <!--http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html-->
  <!--http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html-->
  <string name="default_google_sheets_url"></string>
</resources>


text:
lib = File.expand_path("../../lib", __FILE__)
$:.unshift lib unless $:.include?(lib)

require "minitest/autorun"
require "mocha/setup"

class MiniTest::Unit::TestCase
  def data_file(name)
    File.read(data_file_path(name))
  end

  def data_file_path(name)
    File.expand_path("../data/#{name}", __FILE__)
  end
end


text:
package cocoa.uikit

import cocoa.foundation.{BOOL, NSArray, NSInteger, NSObject, NSObjectClass, NSString, NSTimeInterval, NSURL, id}

import scalanative.native._

@ObjC
class UIApplication extends NSObject { //extends UIResponder {
  @inline def beginIgnoringInteractionEvents(): Unit = extern
  @inline def endIgnoringInteractionEvents(): Unit = extern
  @inline def openURL(url: NSURL): BOOL = extern
  @inline def canOpenURL(url: NSURL): BOOL = extern
  @inline def openURL(url: NSURL, options: id, completion: Ptr[Byte]): Unit = extern
//  @inline def sendEvent(event: UIEvent): Unit = extern
//  @inline def sendAction(action: SEL, target: id, sender: id, event: UIEvent): BOOL = extern
//  @inline def supportedInterfaceOrientationsForWindow(window: UIWindow): UIInterfaceOrientationMask = extern
//  @inline def beginBackgroundTaskWithExpirationHandler(handler: Ptr[Byte]): UIBackgroundTaskIdentifier = extern
//  @inline def beginBackgroundTaskWithName(taskName: NSString, handler: Ptr[Byte]): UIBackgroundTaskIdentifier = extern
//  @inline def endBackgroundTask(identifier: UIBackgroundTaskIdentifier): Unit = extern
  @inline def setMinimumBackgroundFetchInterval(minimumBackgroundFetchInterval: NSTimeInterval): Unit = extern
//  @inline def delegate(): id[UIApplicationDelegate] = extern
//  @inline def setDelegate(delegate: id[UIApplicationDelegate]): Unit = extern
  @inline def isIgnoringInteractionEvents(): BOOL = extern
  @inline def isIdleTimerDisabled(): BOOL = extern
  @inline def setIdleTimerDisabled(idleTimerDisabled: BOOL): Unit = extern
//  @inline def keyWindow(): UIWindow = extern
//  @inline def windows(): NSArray[__kindof UIWindow] = extern
  @inline def isNetworkActivityIndicatorVisible(): BOOL = extern
  @inline def setNetworkActivityIndicatorVisible(networkActivityIndicatorVisible: BOOL): Unit = extern
//  @inline def statusBarStyle(): UIStatusBarStyle = extern
  @inline def isStatusBarHidden(): BOOL = extern
//  @inline def statusBarOrientation(): UIInterfaceOrientation = extern
  @inline def statusBarOrientationAnimationDuration(): NSTimeInterval = extern
//  @inline def statusBarFrame(): CGRect = extern
  @inline def applicationIconBadgeNumber(): NSInteger = extern
  @inline def setApplicationIconBadgeNumber(applicationIconBadgeNumber: NSInteger): Unit = extern
  @inline def applicationSupportsShakeToEdit(): BOOL = extern
  @inline def setApplicationSupportsShakeToEdit(applicationSupportsShakeToEdit: BOOL): Unit = extern
//  @inline def applicationState(): UIApplicationState = extern
  @inline def backgroundTimeRemaining(): NSTimeInterval = extern
//  @inline def backgroundRefreshStatus(): UIBackgroundRefreshStatus = extern
  @inline def isProtectedDataAvailable(): BOOL = extern
//  @inline def userInterfaceLayoutDirection(): UIUserInterfaceLayoutDirection = extern
//  @inline def preferredContentSizeCategory(): UIContentSizeCategory = extern
  @inline def registerForRemoteNotifications(): Unit = extern
  @inline def unregisterForRemoteNotifications(): Unit = extern
//  @inline def registerForRemoteNotificationTypes(types: UIRemoteNotificationType): Unit = extern
//  @inline def enabledRemoteNotificationTypes(): UIRemoteNotificationType = extern
  @inline def isRegisteredForRemoteNotifications(): BOOL = extern
//  @inline def presentLocalNotificationNow(notification: UILocalNotification): Unit = extern
//  @inline def scheduleLocalNotification(notification: UILocalNotification): Unit = extern
//  @inline def cancelLocalNotification(notification: UILocalNotification): Unit = extern
  @inline def cancelAllLocalNotifications(): Unit = extern
//  @inline def scheduledLocalNotifications(): NSArray[UILocalNotification] = extern
//  @inline def setScheduledLocalNotifications(scheduledLocalNotifications: NSArray[UILocalNotification]): Unit = extern
//  @inline def registerUserNotificationSettings(notificationSettings: UIUserNotificationSettings): Unit = extern
//  @inline def currentUserNotificationSettings(): UIUserNotificationSettings = extern
  @inline def beginReceivingRemoteControlEvents(): Unit = extern
  @inline def endReceivingRemoteControlEvents(): Unit = extern
//  @inline def setNewsstandIconImage(image: UIImage): Unit = extern
//  @inline def shortcutItems(): NSArray[UIApplicationShortcutItem] = extern
//  @inline def setShortcutItems(shortcutItems: NSArray[UIApplicationShortcutItem]): Unit = extern
  @inline def extendStateRestoration(): Unit = extern
  @inline def completeStateRestoration(): Unit = extern
  @inline def ignoreSnapshotOnNextApplicationLaunch(): Unit = extern
  @inline def setStatusBarHidden(hidden: BOOL, animated: BOOL): Unit = extern
//  @inline def setStatusBarOrientation(interfaceOrientation: UIInterfaceOrientation, animated: BOOL): Unit = extern
//  @inline def setStatusBarStyle(statusBarStyle: UIStatusBarStyle, animated: BOOL): Unit = extern
//  @inline def setStatusBarHidden(hidden: BOOL, animation: UIStatusBarAnimation): Unit = extern
  @inline def setKeepAliveTimeout(timeout: NSTimeInterval, keepAliveHandler: Ptr[Byte]): BOOL = extern
  @inline def clearKeepAliveTimeout(): Unit = extern
  @inline def isProximitySensingEnabled(): BOOL = extern
  @inline def setProximitySensingEnabled(proximitySensingEnabled: BOOL): Unit = extern
//  @inline def statusBarOrientation(): UIInterfaceOrientation = extern
//  @inline def setStatusBarOrientation(statusBarOrientation: UIInterfaceOrientation): Unit = extern
//  @inline def statusBarStyle(): UIStatusBarStyle = extern
//  @inline def setStatusBarStyle(statusBarStyle: UIStatusBarStyle): Unit = extern
  @inline def setStatusBarHidden(statusBarHidden: BOOL): Unit = extern
}

@ObjCClass
abstract class UIApplicationClass extends NSObjectClass { // extends UIResponderClass
  @inline def sharedApplication(): UIApplication = extern
  @inline def registerObjectForStateRestoration(`object`: id, restorationIdentifier: NSString): Unit = extern
}

object UIApplication extends UIApplicationClass {
  override type InstanceType = UIApplication
}