text:
layout: docpage
title: Getting Started Python
comments: true
previous_page: ./
next_page: java.html
---

[Home](../../../../) > [Documentation](../../) > [Spellchecker](./)

## COHORET for Python

Welcome to COHORTE for Python! With COHORTE, you can build modular and resilient applications using the [Python programming language](https://www.python.org), and take advantage of the many benefits of the COHORTE approach (see [what is COHORTE?]({{ site.baseurl }}/docs/1.x/what-is-cohorte)).

### Spellchecker application

The application to develop in this tutorial provides a web interface in which users can check the spell of their sentences in one or another language. It concists of three main type of components as shown in the following picture:

![SpellChecker Application](spellchecker-app-img1.png)

1. **Dictionary components**: implementing and providing the *Dictionary Service*. Each implementation indicates the language of the dictionary as a service property.
2. **Spell Checker**: implements the *Checker Service* which take as input a sentence of words, and by using the *Dictionary Service* it verifies the existance of misspelled words. It uses the adequate provided *Dictionary Service*s depending on user language choice. A list of missplened words are returned by this service.
3. **Spell Client**: is a simple web interface that shows a form to the final user to test the application. This component uses the *Checker Service* for the application's logic part, and it also requires an *HTTP Service* to publish the web interface and response to the form requests initiated by the user.

The required *HTTP Service* for the last component **Spell Client** is provided natively by the COHORTE runtime. No need to implement it! In the following, we show you how the different components are implemented in Python or Java programming languages.

### Implementation

In this section, we will detail how the different components are implemented. For simplicity, we will not use a modern Integrated Developement Environment like eclipse, we rather create simple text files for the different Python code implementing our application components.

NOTE

Check this page for instructions on how to use your prefered IDE like Eclipse (PyDev) or IDEA (PyCharm).

First, create a directory called `spellchecker`on which you will put the different components.

Create a file called `__init__.py` within the `spellchecker` package folder. This file contains the name of the different services of our application as follow:

{% highlight python %}
#!/usr/bin/python
SERVICE_DICTIONARY = 'demos.spellchecker.dictionaryService'
SERVICE_CHECKER = 'demos.spellchecker.checkerService'
{% endhighlight %}

A COHORTE Component is implemented in python as a simple module with some specific class and method decorators. The following python code `spell_dictionary_EN.py` shows the implementation of the **English Dictionary** component.

#### English Dictionary
[spell_dictionary_EN.py](https://github.com/isandlaTech/cohorte-demos/blob/master/spellchecker/bundles/spellchecker-python/src/main/python/spellchecker/spell_dictionary_EN.py)
{% highlight python %}
#!/usr/bin/python
from pelix.ipopo.decorators import ComponentFactory, Property, Provides, \
    Validate, Invalidate

@ComponentFactory("dictionary_en_factory")
@Provides(spellchecker.SERVICE_DICTIONARY)
@Property("_language","language","EN")
class SpellDictionary(object):
    def __init__(self):
        self._dictionary = None
        self._language = None

    @Validate
    def validate(self, context):
        self._dictionary = {"hello" , "world", "welcome", "to", "cohorte"}

    @Invalidate
    def invalidate(self, context):
        self._dictionary = None

    def check_word(self, word):
        word = word.lower().strip()
        return not word or word in self._dictionary

{% endhighlight %}

We have a simple Python module containing a class called `SpellDictionary`. In this module we have used several decorators defined and imported from  `pelix.ipopo` package. This package (Pelix/iPOPO project) is our python supported component-based framework in COHORTE (For more information about the supported component-based models, check [this page]({{site.baseurl}}/documentation/reference-guide/components.html) of the reference guide).

Here are some explanations of the meanning and effects of each decorator:

 * `@ComponentFactory` allows COHORTE to consider this class as a *component factory* which is an object used to instantiate $Component*s of the class `SpellDictionary` at runtime. The name given between parenthesis is the factory name.

 * `@Provides` makes this component as a service provider for the service given between parenthesis (*SERVICE_DICTIONARY*). This service has one method (*check_word*) that any provider should implement.

 * `@Property` add some contextual properties to the provider implementation of the service. Here in this example, we add the property *language* and set its value to `EN`. When another component requires the *dictionary_service*, it can filter the providers depending on this properties (for instance take only dictionary providers for english language - having language property set to `EN`).

In addition to this class decorators, we have also two method decorators:

 * `@Validate` lets the COHORTE runtime calls the decorated method when the component instance is lanched and is in a valid state.

 * `@Invalidate` lets the COHORTE runtime calls the decorated method when the component is not valid (dependencies of this component are not resolved for instance).

The french dictionary implementation (not showed here) is mainly the same as the english implementation of the **Dictionary Service**. The only differences are the *language* property set to `EN` and the *self._dictionary_* variable containing instead a set of french words.

We will now implement the **Spell Checker** service provider as shown on the following code :

#### Spell Checker

[spell_checker.py](https://github.com/isandlaTech/cohorte-demos/blob/master/spellchecker/bundles/spellchecker-python/src/main/python/spellchecker/spell_checker.py)

{% highlight python %}
#!/usr/bin/python
from pelix.ipopo.decorators import ComponentFactory, Provides, \
    Validate, Invalidate, Requires, BindField, UnbindField
import re

@ComponentFactory("checker_factory")
@Provides(spellchecker.SERVICE_CHECKER)
@Requires("_dictionaries", spellchecker.SERVICE_DICTIONARY, aggregate=True)
class SpellChecker(object):
    def __init__(self):
        self._dictionaries = []
        self.languages = {}

    @BindField('_dictionaries')
    def bind_dict(self, field, service, svc_ref):
        language = svc_ref.get_property('language')
        self.languages[language] = service

    @UnbindField('_dictionaries')
    def unbind_dict(self, field, service, svc_ref):
        language = svc_ref.get_property('language')
        del self.languages[language]

    def check(self, paragraph, language="EN"):
        checked_list = re.split(" ", paragraph)
        try:
            dictionary = self.languages[language]
        except KeyError:
            return None
        return [word for word in checked_list
                if not dictionary.check_word(word)]
{% endhighlight %}

This second component provides **Checker Service** and it requires **Dictionary Service** to operate on the input data. Notice that we have set the *aggregate* option of the `@Requires`decorator to *true* so that all the possible providers of the **Dictionary Service** are injected in the specified class attribute *_dictionaries*.

In addition to already explained decorators used in the first component, in this module we have used this two new decorators:

 * `@BindField`: calls the decorated method when a new provider of the **Dictionary Service** is detected at runtime. In this case, we want to get the service property *language* to construct a map of <language/provider> peers. This property is retrieved from the service reference *svc_ref* to the actual **Dictionary Service** provider.
 * `@UnbindField`: calls the decorated method when one provider of the *dictionary_service* in no longer available. We update our internal map in response to this change.

The *checker_service* implemented by this component has one methdd *check*. It takes a paragraph and a language parameters and uses the available **Dictionary Service$* providers to check the spell of paragraph's words. This service is used by the next component *Spell Client*.

#### Spell Client

[spell_client.py](https://github.com/isandlaTech/cohorte-demos/blob/master/spellchecker/bundles/spellchecker-python/src/main/python/spellchecker/spell_client.py)

{% highlight python %}
#!/usr/bin/python

from pelix.ipopo.decorators import ComponentFactory, Provides, Property, \
    Validate, Invalidate, Requires
from pelix.utilities import to_str

import pelix.remote
try:
    import urllib.parse as urlparse
except ImportError:
    import urlparse

@ComponentFactory("spell_client_factory")
@Provides(specifications='pelix.http.servlet')
@Property('_path', 'pelix.http.path', "/spellchecker")
@Requires("_checker", "checker_service")
@Property('_reject', pelix.remote.PROP_EXPORT_REJECT, ['pelix.http.servlet'])
class SpellClient(object):
    def __init__(self):
        self._path = None
        self._checker = None

        def do_GET(self, request, response):
            """
            Handle a GET
            """
            query = request.get_path()
            query = query[query.rfind('?')+1:]
            data = urlparse.parse_qs(query)
            paragraph = ""
            language = ""
            result = ""
            try:
                paragraph = data['paragraph'][0]
                language = data['language'][0]
                language = language.upper()
                misspelled_words = self._checker.check(paragraph, language)
                if misspelled_words is None:
                    result = 'Dictionary provider for this language is not installed!'
                else:
                    if not misspelled_words:
                        result = 'All words are well spelled !'
                    else:
                        result = "The misspelled words are: "
                        result += ""
                        result += " ".join(misspelled_words) + ""
            except (KeyError, IndexError):
                result = "Fill the language and paragraph inputs!"
            content = """
            <title>SpellChecker</title>

Spellchecker Demo

                <form action="/spellchecker" method="get" >
                    Language: <input type="radio" name="language" value="EN">EN
                    <input type="radio" name="language" value="FR">FR
                    <input type="radio" name="language" value="CN">CN

                    Paragraph: <input type="text" name="paragraph" size="50"/>

                    <input type="submit" value="Check"/>
                </form>

                {result}

            """.format(result=result)
            response.send_content(200, content)
{% endhighlight %}

This last component implements and provides the *pelix.http.servlet* so that it will be called by the web server when a request arrives. The *HTTP Service* provider (included in COHORTE) call the *do_GET* method of this component. In our example, we return via the response object a valid html page with a form asking the user to choose a language and put his sentence to check.

### Running your application

To start running your awesome first COHORTE application, you need to [download](../../downloads) and install the COHORTE runtime platform in your local machine (see the [setup section of the reference guide]({{ site.baseurl }}/documentation/reference-guide/setup.html) for more information).

In the following, we suppose that you have a Max OS X platform. Download the archive file of the COHORTE runtime from the [downloads page]({{ site.baseurl}}/downloads) (e.g., cohorte-1.0.0-macosx.tar.gz).

Extract the dowloaded file anywhere in your file system and create the *environment Variable* **$COHORTE_HOME** which has as value the fullpath to `home` sub-folder of the extracted archive file (note that you can just double click on `home/setup.command` file to setup this environment variable).

The `home` sub-folder contains the main COHORTE runtime libraries and configuration files. Whereas the `base` folder contains user-specific bundles and configurations. To run your spellchecker application you need to:

 * move your spellchecker package folder to `base/repo` folder.
 * fill the `base/conf/autorun_conf.js` file with the description of application's components to be instantiated (see more information about [the formalism in the reference guide]({{ site.baseurl }}/documentation/reference-guide/applications.html)).

{% highlight javascript %}
{
    "name" : "spellchecker-demo-app",
    "root" : {
        "name" : "spellchecker-demo",
        "components" : [ {
            "name" : "dictionary_en",
            "factory" : "dictionary_en_factory",
            "language" : "python"
        }, {
            "name" : "dictionary_fr",
            "factory" : "dictionary_fr_factory",
            "language" : "python"
        }, {
            "name" : "checker",
            "factory" : "checker_factory",
            "language" : "python"
        }, {
            "name" : "spell_client",
            "factory" : "client_factory",
            "language" : "python"
        } ]
    }
}
{% endhighlight %}

This description defines a new application named `spellchecker-demo-app`on which four components will be instantiated. The wiring between the different components is done automatically following the service-oriented architecture (service providers and service consumers) even if one component is placed in remote nodes (see [COHORTE applications reference guide]({{ site.baseurl }}/documentation/reference-guide/applications.html) for more information on how to personalise your application's architecture).

By default, with this minimal description, all the components will be instantiated in one Python isolate (as all the components are implemented in Python). Recall that a COHORTE Isolate is a seperate process (or a gateway) executing a set of components. The Python Isolate consists in Pelix platform hosting your different bundles as well as the needed system bundles (including the HTTP service provider).

COHORTE runtime components managing your application's isolates and the distribution of components among them are located on a special purpose (static) isolate (called `cohorte-isolate`). There is one `cohorte-isolate`per node, but only one is started as a **Top Isolate** which manage all other isolates.

Next, you need to launch your application...

{% highlight sh %}
./run.sh -t -c
{% endhighlight %}

NOTE

For more setup and startup configurations, please check this page.

### Test your application

The resulting Spell Client looks like this:

![SpellChecker Application](spellchecker-app-img3.png)

The important quality of this architecture is the capability to update any component without restarting the global application. This is important to allow adding new *Dictionary Service*s or updating a new efficient version of the **Spell Checker** component, without stopping the system and hence guaranting the continuity of business services.

The different application components can be deployed on different Isolates. This is important to ensure that a failure of one or more components does not affect the other ones. The isolation is managed automatically by COHORTE, this feature is explored with more details in [this tutorial](../temper/).

### Monitoring

![SpellChecker Application](spellchecker-app-img4.png)

[Home](../../../../) > [Documentation](../../) > [Spellchecker](./)


text:
sv_unstuck_func.lua

--]]

// The queue of players to unstuck
Unstuck.ToUnstuck = {}

--[[------------------------------------------------
	Name: Unstuck.Queue()
	Desc: Queue a player to be unstuck.
--]]------------------------------------------------
function Unstuck.Queue( ply )

	// Return if the player is already in the queue
	if table.HasValue( Unstuck.ToUnstuck, ply ) then return end

	table.insert( Unstuck.ToUnstuck, ply )

	local minBound, maxBound = ply:GetHull()
	Unstuck.DebugEvent(
		ply,
		Unstuck.Enumeration.Debug.COMMAND_ADD,
		Unstuck.Enumeration.Debug.NOUN_BOX,
		ply:GetPos()+minBound,
		ply:GetPos()+maxBound,
		Color(255,150,150)
	)

	return true

end

--[[------------------------------------------------
	Name: SpawnPlayer()
	Desc: Called when the unstuck function fails to
		find a suitable position for the player.
--]]------------------------------------------------
local function SpawnPlayer( ply )

	// Return if the player is not valid
	if not IsValid(ply) then return end

	// Respawn the player if enabled in the configuration
	if Unstuck.Configuration.RespawnOnFail then

		// Set a timer or repawn instantly
		if Unstuck.Configuration.RespawnTimer > 0 then
			ply:UnstuckMessage( Unstuck.Enumeration.Message.RESPAWNING )
			timer.Simple( Unstuck.Configuration.RespawnTimer, function()
				if ply:Alive() then
					ply:Spawn()
				else
					ply:UnstuckMessage( Unstuck.Enumeration.Message.RESPAWN_FAILED )
				end
			end )
		else
			ply:Spawn()
		end
	end

end

--[[------------------------------------------------
	Name: GetSurroundingTiles()
	Desc: Returns the positions surrounding
		the given position based on the 'MinCheckRange'
--]]------------------------------------------------
local function GetSurroundingTiles( ply, pos )

	local tiles = {}
	local x, y, z
	local minBound, maxBound = ply:GetHull()
	local checkRange = math.max(Unstuck.Configuration.MinCheckRange, maxBound.x, maxBound.y)

	for z = -1, 1, 1 do
		for y = -1, 1, 1 do
			for x = -1, 1, 1 do
				local testTile = Vector(x,y,z)
				testTile:Mul( checkRange )
				local tilePos = pos + testTile
				table.insert( tiles, tilePos )
			end
		end
	end

	return tiles

end

--[[------------------------------------------------
	Name: GetClearPaths()
	Desc: Returns positions that pass a traceline testPos
		from given position to table of positions.
--]]------------------------------------------------
local function GetClearPaths( ply, pos, tiles )

	local clearPaths = {}

	// Trace to the positions to ensure we don't start getting out of the map
	local filter = player.GetAll()
	table.Add( filter, ents.FindByClass( "prop_physics" ) )
	table.Add( filter, ents.FindByClass( "prop_physics_multiplayer" ) )
	table.Add( filter, ents.FindByClass( "ph_prop" ) )
	table.Add( filter, ents.FindByClass( "func_door" ) )
	table.Add( filter, ents.FindByClass( "prop_door_rotating" ) )
	table.Add( filter, ents.FindByClass( "func_door_rotating" ) )

	for _, tile in pairs( tiles ) do
		local tr = util.TraceLine({
			start = pos,
			endpos = tile,
			filter = filter,
			mask = MASK_PLAYERSOLID
		})

		if not tr.Hit and util.IsInWorld(tile) then
			Unstuck.DebugEvent(
				ply,
				Unstuck.Enumeration.Debug.COMMAND_ADD,
				Unstuck.Enumeration.Debug.NOUN_LINE,
				pos,
				tile,
				Color( 255,0,0 )
			)

			table.insert( clearPaths, tile )
		end
	end

	return clearPaths

end

--[[------------------------------------------------
	Name: FindNewPos()
	Desc:
--]]------------------------------------------------
local function FindNewPos( ply, pos, iterNum )

	coroutine.yield()
	local surroundingTiles = GetSurroundingTiles( ply, pos )
	coroutine.yield()
	local clearPaths = GetClearPaths( ply, pos, surroundingTiles )

	// We check if we can move the player to any of these positions.
	local minBound, maxBound = ply:GetHull()
	for _, tile in pairs( clearPaths ) do
		coroutine.yield()

		if Unstuck.CollisionBoxClear( ply, tile, minBound, maxBound ) then
			Unstuck.DebugEvent(
				ply,
				Unstuck.Enumeration.Debug.COMMAND_ADD,
				Unstuck.Enumeration.Debug.NOUN_BOX,
				tile + minBound,
				tile + maxBound,
				Color( 255,255,0 )
			)

			ply:SetPos( tile )
			ply:UnstuckMessage( Unstuck.Enumeration.Message.UNSTUCK )
			coroutine.yield( Unstuck.Enumeration.PositionTesting.PASSED )
		end
	end

	// Check that we can start a new iteration
	if (iterNum + 1) > Unstuck.Configuration.MaxIteration then
		coroutine.yield( Unstuck.Enumeration.PositionTesting.FAILED )
	end

	// If no positions are found, we create a new iteration at each of the clear paths.
	for _, tile in pairs( clearPaths ) do
		coroutine.yield()

		local result = Unstuck.CoroutineNewPos( ply, tile, iterNum+1 )

		// If a position is found, return a success to end the loop
		if result == Unstuck.Enumeration.PositionTesting.PASSED then
			coroutine.yield( Unstuck.Enumeration.PositionTesting.PASSED )
		end
	end

	// Return FAILED if no positions are found
	coroutine.yield( Unstuck.Enumeration.PositionTesting.FAILED )

end

--[[------------------------------------------------
	Name: Unstuck.CoroutineNewPos()
	Desc: Creates a new coroutine for each iteration of the FindNewPos function.
--]]------------------------------------------------
function Unstuck.CoroutineNewPos( ply, pos, iterNum )

	local newPosCoroutine = coroutine.create( FindNewPos )
	local NoError, NewPosResult

	// Repeat until a Pass or Fail is returned or until the end of the iteration.
	repeat
		NoError, NewPosResult = coroutine.resume( newPosCoroutine, ply, pos, iterNum )
	until ( NewPosResult == Unstuck.Enumeration.PositionTesting.FAILED
		or NewPosResult == Unstuck.Enumeration.PositionTesting.PASSED
		or not NoError )

	return NewPosResult

end

--[[------------------------------------------------
	Name: Think()
	Desc: Creates the coroutine and processes the queue to unstuck players.
--]]------------------------------------------------
local function Think()

	for key, ply in pairs( Unstuck.ToUnstuck ) do
		if IsValid( ply ) then
			local result = Unstuck.CoroutineNewPos( ply, ply:GetPos(), 1 )

			if result == Unstuck.Enumeration.PositionTesting.FAILED then
				ply:UnstuckMessage( Unstuck.Enumeration.Message.FAILED )
				SpawnPlayer( ply )
			end

			// Remove the player from the queue
			Unstuck.ToUnstuck[key] = nil
		end
	end

end
hook.Add( "Think", "Unstuck.Think", Think )

redpajama_set_name: RedPajamaGithub


text:
import jQuery from 'jquery';

module.exports = (function($) {

  var squares;
  var $window;

  function init() {
    squares = $('.SquareSelectors__square');
    $window = $(window);

    _setHeight();
    _attachEvents();
  }

  function _setHeight() {
    var width = squares.width();
    squares.height(width);
  }

  function _attachEvents() {
    $window.resize(_handleWindowResize);
    squares.click(_handleClickLinks);
  }

  function _handleWindowResize() {
    _setHeight();
  }

  function _handleClickLinks(e) {
    e.preventDefault();
    var href = this.href;

    $(this).find('.SquareSelectors__squareText').fadeOut(300);
    $(this).css('z-index', '9999');
    $(this).css('transition', 'transform 0.8s 0.3s ease-out');
    $(this).css('transform', 'scale(10)');

    setTimeout(() => window.location = href, 1000);
  }

  return {
    init: init,
  }

})(jQuery);


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;

namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
    /// <summary>
    /// Looks for code of the form "x == null ? y : x" and offers to convert it to "x ?? y";
    /// </summary>
    internal abstract class AbstractUseCoalesceExpressionDiagnosticAnalyzer<
        TSyntaxKind,
        TExpressionSyntax,
        TConditionalExpressionSyntax,
        TBinaryExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
        where TSyntaxKind : struct
        where TExpressionSyntax : SyntaxNode
        where TConditionalExpressionSyntax : TExpressionSyntax
        where TBinaryExpressionSyntax : TExpressionSyntax
    {
        protected AbstractUseCoalesceExpressionDiagnosticAnalyzer()
            : base(IDEDiagnosticIds.UseCoalesceExpressionDiagnosticId,
                   EnforceOnBuildValues.UseCoalesceExpression,
                   CodeStyleOptions2.PreferCoalesceExpression,
                   new LocalizableResourceString(nameof(AnalyzersResources.Use_coalesce_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
                   new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
        {
        }

        public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
            => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;

        protected abstract ISyntaxFacts GetSyntaxFacts();
        protected abstract bool IsTargetTyped(SemanticModel semanticModel, TConditionalExpressionSyntax conditional, System.Threading.CancellationToken cancellationToken);

        protected override void InitializeWorker(AnalysisContext context)
        {
            var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
            context.RegisterSyntaxNodeAction(AnalyzeSyntax,
                syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.TernaryConditionalExpression));
        }

        private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
        {
            var cancellationToken = context.CancellationToken;
            var conditionalExpression = (TConditionalExpressionSyntax)context.Node;

            var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language);
            if (!option.Value)
                return;

            var syntaxFacts = GetSyntaxFacts();
            syntaxFacts.GetPartsOfConditionalExpression(
                conditionalExpression, out var conditionNode, out var whenTrueNodeHigh, out var whenFalseNodeHigh);

            conditionNode = syntaxFacts.WalkDownParentheses(conditionNode);
            var whenTrueNodeLow = syntaxFacts.WalkDownParentheses(whenTrueNodeHigh);
            var whenFalseNodeLow = syntaxFacts.WalkDownParentheses(whenFalseNodeHigh);

            if (conditionNode is not TBinaryExpressionSyntax condition)
                return;

            var syntaxKinds = syntaxFacts.SyntaxKinds;
            var isEquals = syntaxKinds.ReferenceEqualsExpression == condition.RawKind;
            var isNotEquals = syntaxKinds.ReferenceNotEqualsExpression == condition.RawKind;
            if (!isEquals && !isNotEquals)
                return;

            syntaxFacts.GetPartsOfBinaryExpression(condition, out var conditionLeftHigh, out var conditionRightHigh);

            var conditionLeftLow = syntaxFacts.WalkDownParentheses(conditionLeftHigh);
            var conditionRightLow = syntaxFacts.WalkDownParentheses(conditionRightHigh);

            var conditionLeftIsNull = syntaxFacts.IsNullLiteralExpression(conditionLeftLow);
            var conditionRightIsNull = syntaxFacts.IsNullLiteralExpression(conditionRightLow);

            if (conditionRightIsNull && conditionLeftIsNull)
            {
                // null == null    nothing to do here.
                return;
            }

            if (!conditionRightIsNull && !conditionLeftIsNull)
                return;

            if (!syntaxFacts.AreEquivalent(
                    conditionRightIsNull ? conditionLeftLow : conditionRightLow,
                    isEquals ? whenFalseNodeLow : whenTrueNodeLow))
            {
                return;
            }

            // Coalesce expression cannot be target typed.  So if we had a ternary that was target typed
            // that means the individual parts themselves had no best common type, which would not work
            // for a coalesce expression.
            var semanticModel = context.SemanticModel;
            if (IsTargetTyped(semanticModel, conditionalExpression, cancellationToken))
                return;

            var conditionType = semanticModel.GetTypeInfo(
                conditionLeftIsNull ? conditionRightLow : conditionLeftLow, cancellationToken).Type;
            if (conditionType != null &&
                !conditionType.IsReferenceType)
            {
                // Note: it is intentional that we do not support nullable types here.  If you have:
                //
                //  int? x;
                //  var z = x == null ? y : x;
                //
                // then that's not the same as:   x ?? y.   ?? will unwrap the nullable, producing a
                // int and not an int? like we have in the above code.
                //
                // Note: we could look for:  x == null ? y : x.Value, and simplify that in the future.
                return;
            }

            var conditionPartToCheck = conditionRightIsNull ? conditionLeftHigh : conditionRightHigh;
            var whenPartToCheck = isEquals ? whenTrueNodeHigh : whenFalseNodeHigh;
            var locations = ImmutableArray.Create(
                conditionalExpression.GetLocation(),
                conditionPartToCheck.GetLocation(),
                whenPartToCheck.GetLocation());

            context.ReportDiagnostic(DiagnosticHelper.Create(
                Descriptor,
                conditionalExpression.GetLocation(),
                option.Notification.Severity,
                locations,
                properties: null));
        }
    }
}


text:
<?php

include "DBGateway.php";
$request = filter_input_array(INPUT_GET); // http://www.henzard.co.za/list.php?type=me&action=done
$conn = new DB();
//$conn->UpdateRecord("Items", ["Product Desc" => "Crab Apples"], ["ID" => 1]);
//echo "<pre>" . print_r($conn->ReadRecords("Items", ["Isle" => 3]), TRUE) . "</pre>";

switch ($request["action"]) {
  case "Create":
    echo json_encode($conn->CreateRecord($request["table"], json_decode($request["data"])));
    break;

  case "Read":
    echo json_encode($conn->ReadRecords($request["table"], json_decode($request["where"])));
    break;

  case "Update":
    echo json_encode($conn->UpdateRecord($request["table"], json_decode($request["data"]), json_decode($request["where"])));
    break;

  case "Delete":

    break;

  default:
    echo json_encode(["error" => "No Action Selected"]);
    break;
}


text:
function [output] = F_beamforming_freeWeight(input_layer, curr_layer)
input = input_layer.a;
[D,T,N] = size(input);

W = curr_layer.W;   % W is a 2*nCh x nBin matrix. The first half store the real parts, the second half store the imaginary parts
[D2,nBin] = size(W);
nCh = D2/2;
Wcomplex = W(1:nCh,:) + W(nCh+1:end,:)*sqrt(-1);

input2 = reshape(input, nBin, nCh, T, N);

output = bsxfun(@times, input2, Wcomplex');

output = squeeze(sum(output,2));

end


text:
CBspMapMaterial::CBspMapMaterial()
: m_isSky(false)
{
	m_passes.reserve(MAX_PASS);
}

CBspMapMaterial::~CBspMapMaterial()
{

}

void CBspMapMaterial::Update(float dt)
{
	for(unsigned int i = 0; i < m_passes.size(); i++)
	{
		const BspMapPassPtr& pass(m_passes[i]);
		pass->Update(dt);
	}
}

void CBspMapMaterial::AddPass(const BspMapPassPtr& pass)
{
	m_passes.push_back(pass);
}

BspMapPassPtr CBspMapMaterial::GetPass(unsigned int passIdx) const
{
	return m_passes[passIdx];
}

unsigned int CBspMapMaterial::GetPassCount() const
{
	return m_passes.size();
}

bool CBspMapMaterial::GetIsSky() const
{
	return m_isSky;
}

void CBspMapMaterial::SetIsSky(bool isSky)
{
	m_isSky = isSky;
}


text:
<?php

Route::get('/', 'ApiDocsController@index');


text:
'use strict'
module.exports = function(grunt) {
  grunt.initConfig({
    jsdoc: {
      dist: {
        src: ['accordion/src/*.js',"./README.md"],
        jsdoc: './node_modules/.bin/jsdoc',
        options: {
          destination: 'doc',
          configure: './node_modules/jsdoc/conf.json',
          template: './node_modules/ink-docstrap/template'
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-jsdoc');
  grunt.registerTask('default', 'jsdoc');
}


text: from pattern.web import Twitter, plaintext


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.compute.generated;

import com.azure.core.util.Context;

/** Samples for CommunityGalleryImageVersions Get. */
public final class CommunityGalleryImageVersionsGetSamples {
    /*
     * x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/GalleryRP/stable/2022-03-03/examples/communityGalleryExamples/CommunityGalleryImageVersion_Get.json
     */
    /**
     * Sample code: Get a community gallery image version.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void getACommunityGalleryImageVersion(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .virtualMachines()
            .manager()
            .serviceClient()
            .getCommunityGalleryImageVersions()
            .getWithResponse(
                "myLocation", "publicGalleryName", "myGalleryImageName", "myGalleryImageVersionName", Context.NONE);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.kurento</groupId>
		<artifactId>kurento-room</artifactId>
		<version>6.5.1-SNAPSHOT</version>
	</parent>

	<artifactId>kurento-room-client-js</artifactId>
	<packaging>jar</packaging>

	<name>Kurento Room Client JS</name>
	<description>
        Kurento Room JS library for the client-side
    </description>
	<url>http://www.kurento.org/docs/${project.version}</url>

	<licenses>
		<license>
			<name>Apache 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<organization>
		<name>Kurento</name>
		<url>http://www.kurento.org</url>
	</organization>

	<scm>
		<url>${kurento-room.scm.url}</url>
		<connection>scm:git:${kurento-room.scm.connection}</connection>
		<developerConnection>scm:git:${kurento-room.scm.connection}</developerConnection>
		<tag>develop</tag>
	</scm>

	<developers>
		<developer>
			<id>kurento.org</id>
			<name>-kurento.org Community</name>
			<organization>Kurento.org</organization>
			<organizationUrl>http://www.kurento.org</organizationUrl>
		</developer>
	</developers>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<executions>
					<execution>
						<id>exec-bower-install</id>
						<phase>compile</phase>
						<goals>
							<goal>exec</goal>
						</goals>
						<configuration>
							<executable>bower</executable>
							<workingDirectory>${project.build.directory}/classes</workingDirectory>
							<arguments>
								<argument>install</argument>
								<argument>--allow-root</argument>
							</arguments>
						</configuration>
					</execution>
				</executions>
				<configuration>
					<mainClass>${start-class}</mainClass>
				</configuration>
			</plugin>
		</plugins>

		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>.</directory>
				<filtering>true</filtering>
				<includes>
					<include>bower.json</include>
				</includes>
			</resource>
		</resources>
	</build>

	<dependencies>
		<dependency>
			<groupId>org.kurento</groupId>
			<artifactId>kurento-utils-js</artifactId>
		</dependency>
		<dependency>
			<groupId>org.kurento</groupId>
			<artifactId>kurento-jsonrpc-js</artifactId>
		</dependency>
	</dependencies>

	<profiles>
		<profile>
			<id>default</id>
			<activation>
				<property>
					<name>default</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-surefire-plugin</artifactId>
						<configuration>
							<skipTests>true</skipTests>
						</configuration>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-failsafe-plugin</artifactId>
						<configuration>
							<skipTests>true</skipTests>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>

</project>


text:
In a typical React application, one can use Flux, as suggested by Facebook. The most popular library doing so outthere is Redux. However, we think there is no need to go through another lib. Indeed, React already has its own state management. By using it, we're able to take advantage of React Component's lifecycle but are still able to decouple our business logic.

## React Containers

> Use as few React Containers as possible

A react container is one that is state aware. Indeed, in order to keep things clean, we try to dispatch the managers as few as possible. Thus, there is usually one big container that have access to all the data. And the children are as dumb as possible, using callbacks to trigger some actions directly on the parent container.

## Decoupling the logic

> Get out of React in order to prepare our road out of it

As everyone know, the front-end landscape is an ever changing dream/nightmare. Thus, let's use as few libraries as possible, and especially, let's choose our code architecture in order to be able to change components quite easily.

Our first step toward that is to simply get our stuff out of those libs. Here, that means that the state managers of our React containers are completly decoupled from the React logic.

In our apps, they are `Managers`. They are able to manage the app lifecycle, get access to the current state, and notify the changes back to the containers. Typically, in a React environnement, that would be initialized in the `componentWillMount` method, like so :

```javascript
Manager(
  () => this.state,
  this.setState
)
```

The main Manager function is actually an empty shell that calls other functions that host the logic. It can also return an object that represents the list of actions that can be acheived by this listener. For instance, if we are willing to listen to incoming connections, it would look like :

```javascript
function connections(getState, updateState) {
  messageStream
    .filter({ type } => type === 'NEW_CONNECTION')
    .subscribe(() => {
      updateState(
        getState()
          .set(
            'number_of_connections',
            getState().get('number_of_connections') + 1
          )
      )
    })
}

Manager(getState, updateState) {
  connections(getState, updateState)

  return {
    disconnectAll() {
      updateState(
        getState().set('number_of_connections', 0)
      )
    }
  }
}
```

As you might have seen in this example, there are two more things to say :

- We use **immutable** data structures in order to avoid side effects. That's how we are able to avoid any unpredictable behavior of our app and how we simplify the mental model of our global state. The library we're using for that is `immutable.js`. // TODO Reference immutability

- We try to use as much **stream** handlers as possible in order to simplify the mental model of the asynchrony events that occur in our app. That's particularly useful since we've got 4 different types of nodes communicating between eachother and we wouldn't be able to predict every single event stream. The declarative way suggested by libraries like `RxJS` makes it easier. // TODO Reference RxJS


text:
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Feel the Power of the Cloud - Magento Enterprise Cloud Edition. | Rafael Corrêa Gomes</title>
<meta name="generator" content="Jekyll v3.7.4" />
<meta property="og:title" content="Feel the Power of the Cloud - Magento Enterprise Cloud Edition." />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Magento Enterprise Cloud Edition is a platform-as-a-service offering that enables rapid deployment of fully customizable, secure, and scalable web storefronts, combined with a leading hosting and managed services infrastructure. Designed to support Magento Enterprise digital commerce software, Magento Enterprise Cloud Edition takes advantage of the architecture and functionality enhancements provided by versions 2.0.5 onward." />
<meta property="og:description" content="Magento Enterprise Cloud Edition is a platform-as-a-service offering that enables rapid deployment of fully customizable, secure, and scalable web storefronts, combined with a leading hosting and managed services infrastructure. Designed to support Magento Enterprise digital commerce software, Magento Enterprise Cloud Edition takes advantage of the architecture and functionality enhancements provided by versions 2.0.5 onward." />
<link rel="canonical" href="https://rafaelstz.github.io/blog/magento/feel-the-power-of-the-cloud-magento-enterprise-cloud-edition.html" />
<meta property="og:url" content="https://rafaelstz.github.io/blog/magento/feel-the-power-of-the-cloud-magento-enterprise-cloud-edition.html" />
<meta property="og:site_name" content="Rafael Corrêa Gomes" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2016-04-12T16:28:37-04:00" />

<link type="application/atom+xml" rel="alternate" href="https://rafaelstz.github.io/feed.xml" title="Rafael Corrêa Gomes" />
<link rel="amphtml" href="https://rafaelstz.github.io//amp/blog/magento/feel-the-power-of-the-cloud-magento-enterprise-cloud-edition.html">

<link type="application/json" rel="alternate" title="Rafael Corrêa Gomes" href="https://rafaelstz.github.io/feed.json">
<meta name="google-site-verification" content="L9c-obQotAu449hc8pH_AeHVeyOcPZVg0gDFdOPcl_o" />
<meta name="robots" content="index,follow">

<link rel="apple-touch-icon" sizes="57x57" href="https://rafaelstz.github.io/assets/favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="https://rafaelstz.github.io/assets/favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="https://rafaelstz.github.io/assets/favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="https://rafaelstz.github.io/assets/favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="https://rafaelstz.github.io/assets/favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="https://rafaelstz.github.io/assets/favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="https://rafaelstz.github.io/assets/favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="https://rafaelstz.github.io/assets/favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rafaelstz.github.io/assets/favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="https://rafaelstz.github.io/assets/favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://rafaelstz.github.io/assets/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="https://rafaelstz.github.io/assets/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://rafaelstz.github.io/assets/favicon/favicon-16x16.png">
<link rel="manifest" href="https://rafaelstz.github.io/manifest.json">
<meta name="msapplication-TileColor" content="#000000">
<meta name="msapplication-TileImage" content="https://rafaelstz.github.io/assets/favicon/ms-icon-144x144.png">
<meta name="theme-color" content="#000000">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

<link rel="manifest" href="https://rafaelstz.github.io/manifest.json"/>

<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/normalize.css">
<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/zeit.css">
<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/base.css">

    Rafael Corrêa Gomes

    Articles
    Talks
    Projects

Feel the Power of the Cloud - Magento Enterprise Cloud Edition.

Home

blog

magento

Today the Magento Imagine was officially launched Magento Enterprise Cloud Edition, but what it is?

We can define it as:
Magento Enterprise Cloud Edition is a platform-as-a-service offering that enables rapid deployment of fully customizable, secure, and scalable web storefronts, combined with a leading hosting and managed services infrastructure. Designed to support Magento Enterprise digital commerce software, Magento Enterprise Cloud Edition takes advantage of the architecture and functionality enhancements provided by versions 2.0.5 onward.

In creating Magento Enterprise Cloud Edition they established many strategic partnerships. Magento Enterprise Cloud Edition is built on AWS, a fully redundant cloud hosting infrastructure that provides optimized performance, resilience, and elastic scalability. A leading content delivery network and performance management tools come pre-integrated in the offering, simplifying contract management for merchants.

What are the advantages?

OPTIMIZED FOR MAGENTO
Magento-developed build scripts and service configuration ensure every instance is correctly tuned and configured for optimal merchant performance.

CONSISTENT, SECURE RELEASES
All code deployments are Git-based for consistency and repeatability, with read-only production environments for hardened security.

FLEXIBILITY FOR PARTNERS
A full REST API and a scriptable command line interface ensures ease of integration with external systems and compatibility with existing code management workflows.

FLEXIBLE DEPLOYMENT TOOLSET
Rapidly spin up, merge, clone, and tear down unlimited environments at will, for development tasks, QA testing, or production issue diagnosis.

CONTINUOUS CLOUD DELIVERY
Move with confidence straight from development to UAT to production, in a continuous manner across code branches and development teams.

The post-SaaS era of commerce technology

Magento Enterprise Cloud Edition offers all the benefits of modern cloud computing that are most commonly associated with SaaS solutions: Elastic scalability, high resilience and availability, PCI compliance, global availability and automated patching, while still maintaining flexibility in software customization that our merchants require.

Rafael Corrêa Gomes

I'm Lead Software Engineer at Imagination Media Magento Partner, Magento Master 2018, 3x certified, open source evangelist.

Share

            Twitter

            Facebook

            Google+

    Please enable JavaScript to view the comments powered by Disqus.


text:
package org.linguafranca.pwdb.kdbx.simple;

import org.jetbrains.annotations.NotNull;
import org.linguafranca.pwdb.Group;
import org.linguafranca.pwdb.kdbx.simple.converter.KeePassBooleanConverter;
import org.linguafranca.pwdb.kdbx.simple.converter.UuidConverter;
import org.linguafranca.pwdb.kdbx.simple.model.Times;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.convert.Convert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Implementation of {@link Group} using the Simple XML framework.
 * @author jo
 */
@SuppressWarnings({"WeakerAccess", "unused"})
@Root(name = "Group")
public class SimpleGroup extends org.linguafranca.pwdb.base.AbstractGroup<SimpleDatabase, SimpleGroup, SimpleEntry, SimpleIcon> {
    @Element(name = "UUID", type = UUID.class)
    @Convert(UuidConverter.class)
    protected UUID uuid;
    @Element(name = "Name")
    protected String name;
    @Element(name = "Notes", required = false)
    protected String notes;
    @Element(name = "IconID")
    protected int iconID;
    @Element(name = "Times")
    protected Times times;
    @Element(name = "IsExpanded", required = false, type = Boolean.class)
    @Convert(KeePassBooleanConverter.class)
    protected Boolean isExpanded;
    @Element(name = "DefaultAutoTypeSequence", required = false)
    protected String defaultAutoTypeSequence;
    @Element(name = "EnableAutoType", required = false, type = Boolean.class)
    @Convert(KeePassBooleanConverter.class)
    protected Boolean enableAutoType;
    @Element(name = "EnableSearching", required = false, type = Boolean.class)
    @Convert(KeePassBooleanConverter.class)
    protected Boolean enableSearching;
    @Element(name = "LastTopVisibleEntry", required = false, type = UUID.class)
    @Convert(UuidConverter.class)
    protected UUID lastTopVisibleEntry;
    @ElementList(inline = true, required = false)
    protected List<SimpleEntry> entry;
    @ElementList(inline = true, required = false)
    protected List<SimpleGroup> group;

    @Transient
    protected SimpleDatabase database;
    @Transient
    protected SimpleGroup parent;

    protected SimpleGroup() {
        entry = new ArrayList<>();
        group = new ArrayList<>();
        times = new Times();
    }

    public static SimpleGroup createGroup(SimpleDatabase database) {
        SimpleGroup group = new SimpleGroup();
        group.database = database;
        group.iconID = 0;
        group.name = "";
        group.uuid = UUID.randomUUID();
        return group;
    }

    @Override
    public boolean isRootGroup() {
        return database.getRootGroup().equals(this);
    }

    @Override
    public boolean isRecycleBin() {
        return database.keePassFile.meta.recycleBinUUID.equals(this.uuid);
    }

    @Override
    public SimpleGroup getParent() {
        return parent;
    }

    @Override
    public void setParent(SimpleGroup group) {
        if (isRootGroup()) {
            throw new IllegalStateException("Cannot add root group to another group");
        }
        if (this.database != group.database) {
            throw new IllegalStateException("Must be from same database");
        }
        if (parent != null) {
            parent.removeGroup(group);
            parent.touch();
        }
        parent = group;
        parent.touch();
        touch();
    }

    @Override
    public List<SimpleGroup> getGroups() {
        List<SimpleGroup> result = new ArrayList<>();
        for (SimpleGroup aGroup : group) {
            result.add(aGroup);
        }
        return result;
    }

    @Override
    public int getGroupsCount() {
        return group.size();
    }

    @Override
    public SimpleGroup addGroup(SimpleGroup group) {
        if (group.isRootGroup()) {
            throw new IllegalStateException("Cannot add root group to another group");
        }
        if (this.database != group.database) {
            throw new IllegalStateException("Must be from same database");
        }
        if (group.getParent() != null) {
            group.getParent().removeGroup(group);
        }
        group.parent = this;
        this.group.add(group);
        touch();
        return group;
    }

    @Override
    public SimpleGroup removeGroup(SimpleGroup group) {
        if (this.database != group.database) {
            throw new IllegalStateException("Must be from same database");
        }
        this.group.remove(group);
        group.parent = null;
        touch();
        return group;
    }

    @Override
    public List<SimpleEntry> getEntries() {
        List<SimpleEntry> result = new ArrayList<>();
        for (SimpleEntry entry: this.entry){
            result.add(entry);
        }
        return result;
    }

    @Override
    public int getEntriesCount() {
        return this.entry.size();
    }

    @Override
    public SimpleEntry addEntry(SimpleEntry entry) {
        if (this.database != entry.database) {
            throw new IllegalStateException("Must be from same database");
        }
        if (entry.getParent() != null) {
            entry.getParent().removeEntry(entry);
        }
        this.entry.add(entry);
        entry.parent=this;
        touch();
        return entry;
    }

    @Override
    public SimpleEntry removeEntry(SimpleEntry entry) {
        if (this.database != entry.database) {
            throw new IllegalStateException("Must be from same database");
        }
        this.entry.remove(entry);
        entry.parent = null;
        return entry;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String s) {
        this.name = s;
        touch();
    }

    @Override
    public UUID getUuid() {
        return uuid;
    }

    @Override
    public SimpleIcon getIcon() {
        return new SimpleIcon(iconID);
    }

    @Override
    public void setIcon(SimpleIcon icon) {
        this.iconID = icon.getIndex();
        touch();
    }

    @NotNull
    @Override
    public SimpleDatabase getDatabase() {
        return database;
    }

    private void touch() {
        this.times.setLastModificationTime(new Date());
        this.database.setDirty(true);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.16"/>
<title>GLFW: Bug List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="extra.css" rel="stylesheet" type="text/css"/>

		GLFW

Documentation

Download

Community

Bug List

Page Window guide

On some Linux systems, creating contexts via both the native and EGL APIs in a single process will cause the application to segfault. Stick to one API or the other on Linux for now.

<address class="footer">

Last update on Mon Jan 20 2020 for GLFW 3.3.2

</address>


text:
layout: post
title:  "Easy Voxel Art for Unity"
date:   2017-04-25 10:24:00
---

Before reading this article, please see this short animation:

![http://i.imgur.com/ENAEv2c.gif](http://i.imgur.com/ENAEv2c.gif)

And this is voxel. Basically, voxel art is like pixel art but in 3D. Instead of having pixels in a 2D canvas, you add 3D units to the space. These 3D units are commonly small enough and always the same size. As usual, people with a lot of talent & imagination create awesome worlds with this art style...

...Like a Zelda Remake.

But today we are not here to rant about people with talent, but to create original awesome characters (and worlds too) ready to use in our unity projects.

Do you remember MS Paint? we are using a similar tool to build our models, it is named [MagicaVoxel](https://ephtracy.github.io/) and the most important: it's free!

Once you became acquainted with this application and all its tools, you need a character model with the famous "T pose".

![http://i.imgur.com/Km2tf2V.gif](http://i.imgur.com/Km2tf2V.gif)

This is me creating a cheap mario clone, watch the complete video [here](https://www.youtube.com/watch?v=oLjXgBNgESA).

There're a couple of details you should take into account when designing your character model:
* It should be humanoid
* It should have legs & arms
* Perhaps it might be toony, take care of the proportions
* Fingers on hands are optional
* It is easier if character is in T position

If you followed previous tips, your character might look something like this:

![http://i.imgur.com/qJOIvNm.png](http://i.imgur.com/qJOIvNm.png)

Export your character in obj format. Now you are ready for the next step.

Create an adobe account if you haven't, and browse to [Mixamo.com](https://www.mixamo.com/store/). Upload your model (.obj file) and start with the auto-rigging tool. Set the anchor points like this:

![http://i.imgur.com/f1Zm58r.png](http://i.imgur.com/f1Zm58r.png)

Please note the dropdown selection at the bottom side. Selecting "No Fingers (25)" for Skeleton LOD is essential. Otherwise your model won't be processed correctly.

If your model is different, or the auto-rigging tool doesn't recognize the character properly, just try again moving the anchor points around the places they suppose to be. When the model rigging is done, you should be able to see it in movement. It works like magic!

Let's give a try to the animations. Luckily, Mixamo has A TON of different animations. Most of them have configurable parameters to fit almost every model. I didn't have issues with mine.

![http://i.imgur.com/vRaHzi2.png](http://i.imgur.com/vRaHzi2.png)

Take all what you need, create a pack and download it as FBX for Unity (.fbx):

![http://i.imgur.com/7PvpbHT.png](http://i.imgur.com/7PvpbHT.png)

Import this package on unity and you are ready to rock. Remember to import the texture generated by MagicalVoxel as well or your model will look dead 😁.

Extra stuff you need to do:

* Create a new object
* Add a new animator controller
* Add your animations to the animator
* Trigger changes to the FSM
* Blend animations
* Create an actual videogame

Now unless you need very specific animations, you won't need a designer/animator to make original-looking videogames anymore!

*TL;DR*
* Create a character using [MagicaVoxel](https://ephtracy.github.io/)
* Import to [Mixamo.com](https://www.mixamo.com/store/)
* Download the unity package
* Import everything to Unity
* Profit!


text:
package net.fortuna.ical4j.model.parameter;

import net.fortuna.ical4j.model.Content;
import net.fortuna.ical4j.model.Encodable;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.ParameterFactory;
import org.apache.commons.lang3.StringUtils;

/**
 * <pre>
 * Parameter Name:  DISPLAY
 *
 * Purpose:  To specify different ways in which an image for a calendar
 * or component can be displayed.
 *
 * Format Definition:  This property parameter is defined by the
 * following notation:
 *
 * displayparam = "DISPLAY" "=" displayval *("," displayval)
 *
 * displayval =   ("BADGE" /    ; image inline with the title of the
 *                              ; event
 *                 "GRAPHIC" /  ; a full image replacement for the event
 *                              ; itself
 *                 "FULLSIZE /  ; an image that is used to enhance the
 *                              ; event
 *                 "THUMBNAIL / ; a smaller variant of "FULLSIZE" to be
 *                              ; used when space for the image is
 *                              ; constrained
 *                 x-name /     ; Experimental type
 *                 iana-token)  ; Other IANA registered type
 *                              ;
 *                              ; Default is BADGE
 *
 * Description:  This property parameter MAY be specified on "IMAGE"
 * properties.  In the absence of this parameter, the value "BADGE"
 * MUST be used for the default behavior.  The value determines how a
 * client ought to present an image supplied in iCalendar data to the
 * user.
 *
 * Values for this parameter are registered with IANA as per
 * Section 8.3.  New values can be added to this registry following
 * the procedure outlined in Section 8.2.1 of [RFC5545].
 *
 * Servers and clients MUST handle x-name and iana-token values they
 * don't recognize by not displaying any image at all.
 *
 * Example:
 *
 * IMAGE;VALUE=URI;DISPLAY=BADGE,THUMBNAIL,;FMTTYPE=image/png:http://exa
 * mple.com/images/weather-cloudy.png
 * </pre>
 */
public class Display extends Parameter implements Encodable {

    private static final long serialVersionUID = 1L;

    private static final String PARAMETER_NAME = "DISPLAY";

    public enum Value {
        BADGE, GRAPHIC, FULLSIZE, THUMBNAIL
    }

    private final String[] values;

    public Display(String value) {
        super(PARAMETER_NAME, new Factory());
        String[] valueStrings = value.split(",");
        for (String valueString : valueStrings) {
            try {
                Value.valueOf(valueString);
            } catch (IllegalArgumentException iae) {
                if (!valueString.startsWith(Parameter.EXPERIMENTAL_PREFIX)) {
                    throw iae;
                }
            }
        }
        this.values = valueStrings;
    }

    @Override
    public String getValue() {
        return StringUtils.join(values, ",");
    }

    public static class Factory extends Content.Factory implements ParameterFactory<Display> {
        private static final long serialVersionUID = 1L;

        public Factory() {
            super(PARAMETER_NAME);
        }

        @Override
        public Display createParameter(final String value) {
            return new Display(value);
        }
    }
}


text:
<readable><title>2579268572_d78f8436cb</title><content>
A group of people riding a roller coaster upside down .
A group of people riding a yellow roller coaster .
Many people on a roller coaster ride are flipped upside down over a white track .
People ride upside-down on a roller coaster .
There are multiple people going over a loop on an inverted roller coaster .
</content></readable>


text:
package com.opengamma.analytics.math.linearalgebra;

import org.apache.commons.lang.Validate;
import org.apache.commons.math.linear.DecompositionSolver;
import org.apache.commons.math.linear.LUDecomposition;

import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.util.wrapper.CommonsMathWrapper;

/**
 * Wrapper for results of the Commons implementation of LU decomposition ({@link LUDecompositionCommons})
 */
public class LUDecompositionCommonsResult implements LUDecompositionResult {
  private final double _determinant;
  private final DoubleMatrix2D _l;
  private final DoubleMatrix2D _p;
  private final int[] _pivot;
  private final DecompositionSolver _solver;
  private final DoubleMatrix2D _u;

  /**
   * @param lu The result of the LU decomposition, not null. $\mathbf{L}$ cannot be singular.
   */
  public LUDecompositionCommonsResult(final LUDecomposition lu) {
    Validate.notNull(lu, "LU decomposition");
    Validate.notNull(lu.getL(), "Matrix is singular; could not perform LU decomposition");
    _determinant = lu.getDeterminant();
    _l = CommonsMathWrapper.unwrap(lu.getL());
    _p = CommonsMathWrapper.unwrap(lu.getP());
    _pivot = lu.getPivot();
    _solver = lu.getSolver();
    _u = CommonsMathWrapper.unwrap(lu.getU());
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public double getDeterminant() {
    return _determinant;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DoubleMatrix2D getL() {
    return _l;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DoubleMatrix2D getP() {
    return _p;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int[] getPivot() {
    return _pivot;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DoubleMatrix2D getU() {
    return _u;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DoubleMatrix1D solve(final DoubleMatrix1D b) {
    Validate.notNull(b);
    return CommonsMathWrapper.unwrap(_solver.solve(CommonsMathWrapper.wrap(b)));
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public double[] solve(final double[] b) {
    Validate.notNull(b);
    return _solver.solve(b);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DoubleMatrix2D solve(final DoubleMatrix2D b) {
    Validate.notNull(b);
    return CommonsMathWrapper.unwrap(_solver.solve(CommonsMathWrapper.wrap(b)));
  }

}


text:
require 'spec_helper'

describe "Goals" do
  describe "GET /goals" do
    it "works! (now write some real specs)" do
      # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
      get goals_path
      response.status.should be(200)
    end
  end
end


text:
function Test-DbaDbOwner {
    <#
    .SYNOPSIS
        Checks database owners against a login to validate which databases do not match that owner.

    .DESCRIPTION
        This function will check all databases on an instance against a SQL login to validate if that
        login owns those databases or not. By default, the function will check against 'sa' for
        ownership, but the user can pass a specific login if they use something else.

        Best Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).

        Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.

        For MFA support, please use Connect-DbaInstance.

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER TargetLogin
        Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.

    .PARAMETER InputObject
        Enables piped input from Get-DbaDatabase.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Owner, DbOwner
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbOwner

    .EXAMPLE
        PS C:\> Test-DbaDbOwner -SqlInstance localhost

        Returns all databases where the owner does not match 'sa'.

    .EXAMPLE
        PS C:\> Test-DbaDbOwner -SqlInstance localhost -TargetLogin 'DOMAIN\account'

        Returns all databases where the owner does not match 'DOMAIN\account'.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance localhost -OnlyAccessible | Test-DbaDbOwner

        Gets only accessible databases and checks where the owner does not match 'sa'.
    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [string]$TargetLogin,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Switch]$EnableException
    )
    process {
        if (-not $InputObject -and -not $Sqlinstance) {
            Stop-Function -Message 'You must specify a $SqlInstance parameter'
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        #for each database, create custom object for return set.
        foreach ($db in $InputObject) {
            $server = $db.Parent

            # dynamic sa name for orgs who have changed their sa name
            if (Test-Bound -ParameterName TargetLogin -Not) {
                $TargetLogin = ($server.logins | Where-Object {
                        $_.id -eq 1
                    }).Name
            }

            #Validate login
            if (($server.Logins.Name) -notmatch [Regex]::Escape($TargetLogin)) {
                Write-Message -Level Verbose -Message "$TargetLogin is not a login on $instance" -Target $instance
            }

            Write-Message -Level Verbose -Message "Checking $db"
            [pscustomobject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                Server       = $server.DomainInstanceName
                Database     = $db.Name
                DBState      = $db.Status
                CurrentOwner = $db.Owner
                TargetOwner  = $TargetLogin
                OwnerMatch   = ($db.owner -eq $TargetLogin)
            } | Select-DefaultView -ExcludeProperty Server
        }
    }
}


text:
namespace v8 {
namespace internal {

InvalidatedSlotsFilter::InvalidatedSlotsFilter(MemoryChunk* chunk) {
  // Adjust slots_in_free_space_are_valid_ if more spaces are added.
  DCHECK_IMPLIES(chunk->invalidated_slots() != nullptr,
                 chunk->InOldSpace() || chunk->InLargeObjectSpace());
  // The sweeper removes invalid slots and makes free space available for
  // allocation. Slots for new objects can be recorded in the free space.
  // Note that we cannot simply check for SweepingDone because pages in large
  // object space are not swept but have SweepingDone() == true.
  slots_in_free_space_are_valid_ = chunk->SweepingDone() && chunk->InOldSpace();

  InvalidatedSlots* invalidated_slots =
      chunk->invalidated_slots() ? chunk->invalidated_slots() : &empty_;
  iterator_ = invalidated_slots->begin();
  iterator_end_ = invalidated_slots->end();
  sentinel_ = chunk->area_end();
  if (iterator_ != iterator_end_) {
    invalidated_start_ = iterator_->first->address();
    invalidated_end_ = invalidated_start_ + iterator_->second;
  } else {
    invalidated_start_ = sentinel_;
    invalidated_end_ = sentinel_;
  }
  // These values will be lazily set when needed.
  invalidated_object_size_ = 0;
#ifdef DEBUG
  last_slot_ = chunk->area_start();
#endif
}

}  // namespace internal
}  // namespace v8


text:
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 48px;
  padding: 8px;
}

.header__title {
  font-size: 1rem;
}


text: Please refer to https://bitbucket.org/fourdirectionslimited/reactnativereadme


text:
({
	doInit : function(component, event, helper) {
		helper.findAcccounts(component, helper);
	},
    saveAccounts : function(component, event, helper) {
        helper.saveAccounts(component, helper);
    }
})


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.BooleanField = undefined;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _lodash = require('lodash.get');

var _lodash2 = _interopRequireDefault(_lodash);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _clear = require('material-ui/svg-icons/content/clear');

var _clear2 = _interopRequireDefault(_clear);

var _done = require('material-ui/svg-icons/action/done');

var _done2 = _interopRequireDefault(_done);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var BooleanField = exports.BooleanField = function BooleanField(_ref) {
    var source = _ref.source,
        _ref$record = _ref.record,
        record = _ref$record === undefined ? {} : _ref$record,
        elStyle = _ref.elStyle;

    if ((0, _lodash2.default)(record, source) === false) {
        return _react2.default.createElement(_clear2.default, { style: elStyle });
    }

    if ((0, _lodash2.default)(record, source) === true) {
        return _react2.default.createElement(_done2.default, { style: elStyle });
    }

    return _react2.default.createElement('span', { style: elStyle });
};

BooleanField.propTypes = {
    addLabel: _react.PropTypes.bool,
    elStyle: _react.PropTypes.object,
    label: _react.PropTypes.string,
    record: _react.PropTypes.object,
    source: _react.PropTypes.string.isRequired
};

var PureBooleanField = (0, _pure2.default)(BooleanField);

PureBooleanField.defaultProps = {
    addLabel: true,
    elStyle: {
        display: 'block',
        margin: 'auto'
    }
};

exports.default = PureBooleanField;


text:
from mistral.db import api as db_api
from mistral import engine
from mistral.engine import client
from mistral.openstack.common import log
from mistral.openstack.common import periodic_task
from mistral.openstack.common import threadgroup
from mistral import context
from mistral import dsl_parser as parser
from mistral.services import scheduler as sched
from mistral.services import trusts

LOG = log.getLogger(__name__)

class MistralPeriodicTasks(periodic_task.PeriodicTasks):

    def __init__(self, transport=None):
        super(MistralPeriodicTasks, self).__init__()
        self.transport = engine.get_transport(transport)
        self.engine = client.EngineClient(self.transport)

    @periodic_task.periodic_task(spacing=1, run_immediately=True)
    def scheduler_triggers(self, ctx):
        LOG.debug('Processing next Scheduler triggers.')

        for trigger in sched.get_next_triggers():
            wb = db_api.workbook_get(trigger['workbook_name'])
            context.set_ctx(trusts.create_context(wb))

            try:
                task = parser.get_workbook(
                    wb['definition']).get_trigger_task_name(trigger['name'])
                self.engine.start_workflow_execution(wb['name'], task)
            finally:
                sched.set_next_execution_time(trigger)
                context.set_ctx(None)

def setup(transport):
    tg = threadgroup.ThreadGroup()
    pt = MistralPeriodicTasks(transport=transport)

    tg.add_dynamic_timer(
        pt.run_periodic_tasks,
        initial_delay=None,
        periodic_interval_max=1,
        context=None)


text:
using namespace arangodb;
using namespace arangodb::aql;

std::ostream& arangodb::aql::operator<<(std::ostream& stream,
                                        ExecutionStats const& stats) {
  VPackBuilder builder{};
  stats.toVelocyPack(builder, true);
  return stream << builder.toJson();
}

std::ostream& arangodb::aql::operator<<(std::ostream& stream,
                                        AqlItemBlock const& block) {
  stream << "[";
  for (size_t row = 0; row < block.numRows(); row++) {
    if (row > 0) {
      stream << ",";
    }
    stream << " ";
    VPackBuilder builder{};
    builder.openArray();
    for (RegisterId::value_t reg = 0; reg < block.numRegisters(); reg++) {
      if (reg > 0) {
        stream << ",";
      }
      // will not work for docvecs or ranges
      builder.add(block.getValueReference(row, reg).slice());
    }
    builder.close();
    stream << builder.toJson();
  }
  stream << " ]";
  return stream;
}

bool arangodb::aql::operator==(arangodb::aql::ExecutionStats const& left,
                               arangodb::aql::ExecutionStats const& right) {
  // The below information is only set on profiling in AQL
  // They are not included on purpose as they will never be equal.
  // * nodes
  // * executionTime
  // * peakMemeoryUsage

  // clang-format off
  return left.writesExecuted == right.writesExecuted
      && left.writesIgnored == right.writesIgnored
      && left.scannedFull == right.scannedFull
      && left.scannedIndex == right.scannedIndex
      && left.filtered == right.filtered
      && left.requests == right.requests
      && left.fullCount == right.fullCount
      && left.count == right.count;
  // clang-format on
}
bool arangodb::aql::operator==(arangodb::aql::AqlItemBlock const& left,
                               arangodb::aql::AqlItemBlock const& right) {
  if (left.numRows() != right.numRows()) {
    return false;
  }
  if (left.numRegisters() != right.numRegisters()) {
    return false;
  }
  size_t const rows = left.numRows();
  RegisterCount const regs = left.numRegisters();
  for (size_t row = 0; row < rows; row++) {
    for (RegisterId::value_t reg = 0; reg < regs; reg++) {
      AqlValue const& l = left.getValueReference(row, reg);
      AqlValue const& r = right.getValueReference(row, reg);
      // Doesn't work for docvecs or ranges
      if (arangodb::basics::VelocyPackHelper::compare(l.slice(), r.slice(),
                                                      false) != 0) {
        return false;
      }
    }
  }

  return true;
}


text:
package pl.java.scalatech.domain.mainPerson;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZonedDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.annotations.ColumnTransformer;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.Email;
import org.springframework.format.annotation.DateTimeFormat;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import pl.java.scalatech.domain.SampleListener;

@Entity
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
//tag::main[]
@FilterDef(name = "byStatus", parameters = @ParamDef(name = "status", type = "boolean"))//<1>
@Filter(name = "byStatus", condition = "active = :status")//<2>
@EntityListeners( SampleListener.class )
public class Person implements Serializable{

    private static final long serialVersionUID = 5279859664147821207L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Size(min=5,max=50)
    private  String firstname;

    @Email
    private  String email;

    private LocalDate modify;
    @PrePersist
    @PreUpdate
    public void init(){
        modify = LocalDate.now();
    }

    @Column(insertable=true,updatable=false)
    @Generated(GenerationTime.INSERT)
    private LocalDate effectiveModify;

    @Type(type="yes_no") //<3>
    private Boolean disable;

    //TODO
  //@Formula("concat(disable, ' : ' ,active )")/// ? filter problem
    private String overview;

    @Formula("select count(*) From Person p WHERE p.active = 'true'") //<4>
    private int allUser;

    @ColumnTransformer(read="km * 1.6",write= "? / 1.6") //<5>
    private Double km;

    private Boolean active;

    @DateTimeFormat(pattern = "dd/MM/yy")

    //@Past
    private ZonedDateTime birthDay;
    //TODO
    //private MonetaryAmount basePrice;
    @Version
    private long version;
}
// end::main[]


text:
define([
        '../Core/Cartesian3',
        '../Core/Check',
        '../Core/Color',
        '../Core/ColorGeometryInstanceAttribute',
        '../Core/CylinderGeometry',
        '../Core/CylinderOutlineGeometry',
        '../Core/defined',
        '../Core/DeveloperError',
        '../Core/DistanceDisplayConditionGeometryInstanceAttribute',
        '../Core/GeometryInstance',
        '../Core/Iso8601',
        '../Core/ShowGeometryInstanceAttribute',
        '../Scene/MaterialAppearance',
        '../Scene/PerInstanceColorAppearance',
        './ColorMaterialProperty',
        './DynamicGeometryUpdater',
        './GeometryUpdater',
        './Property'
    ], function(
        Cartesian3,
        Check,
        Color,
        ColorGeometryInstanceAttribute,
        CylinderGeometry,
        CylinderOutlineGeometry,
        defined,
        DeveloperError,
        DistanceDisplayConditionGeometryInstanceAttribute,
        GeometryInstance,
        Iso8601,
        ShowGeometryInstanceAttribute,
        MaterialAppearance,
        PerInstanceColorAppearance,
        ColorMaterialProperty,
        DynamicGeometryUpdater,
        GeometryUpdater,
        Property) {
    'use strict';

    var positionScratch = new Cartesian3();
    var scratchColor = new Color();

    function CylinderGeometryOptions(entity) {
        this.id = entity;
        this.vertexFormat = undefined;
        this.length = undefined;
        this.topRadius = undefined;
        this.bottomRadius = undefined;
        this.slices = undefined;
        this.numberOfVerticalLines = undefined;
    }

    /**
     * A {@link GeometryUpdater} for cylinders.
     * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
     * @alias CylinderGeometryUpdater
     * @constructor
     *
     * @param {Entity} entity The entity containing the geometry to be visualized.
     * @param {Scene} scene The scene where visualization is taking place.
     */
    function CylinderGeometryUpdater(entity, scene) {
        GeometryUpdater.call(this, {
            entity: entity,
            scene: scene,
            geometryOptions: new CylinderGeometryOptions(entity),
            geometryPropertyName: 'cylinder',
            observedPropertyNames: ['availability', 'position', 'orientation', 'cylinder']
        });

        this._onEntityPropertyChanged(entity, 'cylinder', entity.cylinder, undefined);
    }

    if (defined(Object.create)) {
        CylinderGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
        CylinderGeometryUpdater.prototype.constructor = CylinderGeometryUpdater;
    }

    /**
     * Creates the geometry instance which represents the fill of the geometry.
     *
     * @param {JulianDate} time The time to use when retrieving initial attribute values.
     * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
     *
     * @exception {DeveloperError} This instance does not represent a filled geometry.
     */
    CylinderGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined('time', time);

        if (!this._fillEnabled) {
            throw new DeveloperError('This instance does not represent a filled geometry.');
        }
        //>>includeEnd('debug');

        var entity = this._entity;
        var isAvailable = entity.isAvailable(time);

        var attributes;

        var color;
        var show = new ShowGeometryInstanceAttribute(isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time));
        var distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(time);
        var distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(distanceDisplayCondition);
        if (this._materialProperty instanceof ColorMaterialProperty) {
            var currentColor;
            if (defined(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
                currentColor = this._materialProperty.color.getValue(time, scratchColor);
            }
            if (!defined(currentColor)) {
                currentColor = Color.WHITE;
            }
            color = ColorGeometryInstanceAttribute.fromColor(currentColor);
            attributes = {
                show : show,
                distanceDisplayCondition : distanceDisplayConditionAttribute,
                color : color
            };
        } else {
            attributes = {
                show : show,
                distanceDisplayCondition : distanceDisplayConditionAttribute
            };
        }

        return new GeometryInstance({
            id : entity,
            geometry : new CylinderGeometry(this._options),
            modelMatrix : entity.computeModelMatrix(time),
            attributes : attributes
        });
    };

    /**
     * Creates the geometry instance which represents the outline of the geometry.
     *
     * @param {JulianDate} time The time to use when retrieving initial attribute values.
     * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
     *
     * @exception {DeveloperError} This instance does not represent an outlined geometry.
     */
    CylinderGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined('time', time);

        if (!this._outlineEnabled) {
            throw new DeveloperError('This instance does not represent an outlined geometry.');
        }
        //>>includeEnd('debug');

        var entity = this._entity;
        var isAvailable = entity.isAvailable(time);
        var outlineColor = Property.getValueOrDefault(this._outlineColorProperty, time, Color.BLACK, scratchColor);
        var distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(time);

        return new GeometryInstance({
            id : entity,
            geometry : new CylinderOutlineGeometry(this._options),
            modelMatrix : entity.computeModelMatrix(time),
            attributes : {
                show : new ShowGeometryInstanceAttribute(isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)),
                color : ColorGeometryInstanceAttribute.fromColor(outlineColor),
                distanceDisplayCondition : DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(distanceDisplayCondition)
            }
        });
    };

    CylinderGeometryUpdater.prototype._isHidden = function(entity, cylinder) {
        return !defined(entity.position) || !defined(cylinder.length) || !defined(cylinder.topRadius) || !defined(cylinder.bottomRadius) || GeometryUpdater.prototype._isHidden.call(this, entity, cylinder);
    };

    CylinderGeometryUpdater.prototype._isDynamic = function(entity, cylinder) {
        return !entity.position.isConstant || //
                !Property.isConstant(entity.orientation) || //
                !cylinder.length.isConstant || //
                !cylinder.topRadius.isConstant || //
                !cylinder.bottomRadius.isConstant || //
                !Property.isConstant(cylinder.slices) || //
                !Property.isConstant(cylinder.outlineWidth) || //
                !Property.isConstant(cylinder.numberOfVerticalLines);
    };

    CylinderGeometryUpdater.prototype._setStaticOptions = function(entity, cylinder) {
        var slices = cylinder.slices;
        var numberOfVerticalLines = cylinder.numberOfVerticalLines;

        var options = this._options;
        var isColorMaterial = this._materialProperty instanceof ColorMaterialProperty;
        options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance.VERTEX_FORMAT : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
        options.length = cylinder.length.getValue(Iso8601.MINIMUM_VALUE);
        options.topRadius = cylinder.topRadius.getValue(Iso8601.MINIMUM_VALUE);
        options.bottomRadius = cylinder.bottomRadius.getValue(Iso8601.MINIMUM_VALUE);
        options.slices = defined(slices) ? slices.getValue(Iso8601.MINIMUM_VALUE) : undefined;
        options.numberOfVerticalLines = defined(numberOfVerticalLines) ? numberOfVerticalLines.getValue(Iso8601.MINIMUM_VALUE) : undefined;
    };

    CylinderGeometryUpdater.DynamicGeometryUpdater = DynamicCylinderGeometryUpdater;

    /**
     * @private
     */
    function DynamicCylinderGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
        DynamicGeometryUpdater.call(this, geometryUpdater, primitives, groundPrimitives);
    }

    if (defined(Object.create)) {
        DynamicCylinderGeometryUpdater.prototype = Object.create(DynamicGeometryUpdater.prototype);
        DynamicCylinderGeometryUpdater.prototype.constructor = DynamicCylinderGeometryUpdater;
    }

    DynamicCylinderGeometryUpdater.prototype._isHidden = function(entity, cylinder, time) {
        var options = this._options;
        var position = Property.getValueOrUndefined(entity.position, time, positionScratch);
        return !defined(position) || !defined(options.length) || !defined(options.topRadius) || //
               !defined(options.bottomRadius) || DynamicGeometryUpdater.prototype._isHidden.call(this, entity, cylinder, time);
    };

    DynamicCylinderGeometryUpdater.prototype._setOptions = function(entity, cylinder, time) {
        var options = this._options;
        options.length = Property.getValueOrUndefined(cylinder.length, time);
        options.topRadius = Property.getValueOrUndefined(cylinder.topRadius, time);
        options.bottomRadius = Property.getValueOrUndefined(cylinder.bottomRadius, time);
        options.slices = Property.getValueOrUndefined(cylinder.slices, time);
        options.numberOfVerticalLines = Property.getValueOrUndefined(cylinder.numberOfVerticalLines, time);
    };

    return CylinderGeometryUpdater;
});


text:
package com.gemstone.gemfire.internal.cache.partitioned;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.GemFireRethrowable;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.query.QueryException;
import com.gemstone.gemfire.cache.query.QueryExecutionLowMemoryException;
import com.gemstone.gemfire.cache.query.internal.DefaultQuery;
import com.gemstone.gemfire.cache.query.internal.QueryMonitor;
import com.gemstone.gemfire.cache.query.internal.QueryObserver;
import com.gemstone.gemfire.distributed.internal.DM;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.ReplyException;
import com.gemstone.gemfire.distributed.internal.ReplyMessage;
import com.gemstone.gemfire.distributed.internal.ReplyProcessor21;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.distributed.internal.streaming.StreamingOperation.StreamingReplyMessage;
import com.gemstone.gemfire.i18n.LogWriterI18n;
import com.gemstone.gemfire.internal.HeapDataOutputStream;
import com.gemstone.gemfire.internal.cache.ForceReattemptException;
import com.gemstone.gemfire.internal.cache.PRQueryProcessor;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.Token;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;

public final class QueryMessage extends StreamingPartitionOperation.StreamingPartitionMessage
  {
  private volatile String queryString;
  private volatile boolean cqQuery;
  private volatile Object[] parameters;
  private volatile List buckets;
  private volatile boolean isPdxSerialized;
  private volatile boolean traceOn;

//  private transient PRQueryResultCollector resultCollector = new PRQueryResultCollector();
  private transient Collection<Collection> resultCollector = new ArrayList<Collection>();
  private transient int tokenCount = 0; // counts how many end of stream tokens received
  private transient Iterator currentResultIterator;
  private transient Iterator<Collection> currentSelectResultIterator;

  /**
   * Empty constructor to satisfy {@link DataSerializer} requirements
   */
  public QueryMessage() {}

  public QueryMessage(InternalDistributedMember recipient,  int regionId, ReplyProcessor21 processor,
      DefaultQuery query, Object[] parameters, final List buckets) {
    super(recipient, regionId, processor);
    this.queryString = query.getQueryString();
    this.buckets = buckets;
    this.parameters = parameters;
    this.cqQuery = query.isCqQuery();
    this.traceOn = query.isTraced() || DefaultQuery.QUERY_VERBOSE;
  }

  /**  Provide results to send back to requestor.
    *  terminate by returning END_OF_STREAM token object
    */
  @Override
  protected Object getNextReplyObject(PartitionedRegion pr)
  throws CacheException, ForceReattemptException, InterruptedException {
    if (QueryMonitor.isLowMemory()) {
      String reason = LocalizedStrings.QueryMonitor_LOW_MEMORY_CANCELED_QUERY.toLocalizedString(QueryMonitor.getMemoryUsedDuringLowMemory());
      throw new QueryExecutionLowMemoryException(reason);
    }
    if (Thread.interrupted()) throw new InterruptedException();
    LogWriterI18n l = pr.getCache().getLoggerI18n();
    while ((this.currentResultIterator == null || !this.currentResultIterator.hasNext())) {
      if (this.currentSelectResultIterator.hasNext()) {
        Collection results = this.currentSelectResultIterator.next();
        if (l.fineEnabled()) {
          l.fine("Query result size: " + results.size());
        }
        this.currentResultIterator = results.iterator();
      } else {
        //Assert.assertTrue(this.resultCollector.isEmpty());
        return Token.END_OF_STREAM;
      }
    }
    return this.currentResultIterator.next();
  }

  @Override
  protected boolean operateOnPartitionedRegion(DistributionManager dm, PartitionedRegion r, long startTime)
  throws CacheException, QueryException, ForceReattemptException, InterruptedException {
    if (Thread.interrupted()) throw new InterruptedException();
    LogWriterI18n l = r.getCache().getLoggerI18n();
    if (DistributionManager.VERBOSE) {
      l.fine("QueryMessage operateOnPartitionedRegion: " + r.getFullPath() + " buckets " +buckets);
    }

    r.waitOnInitialization();

    //PartitionedRegionDataStore ds = r.getDataStore();

    //if (ds != null) {
    if (QueryMonitor.isLowMemory()) {
      String reason = LocalizedStrings.QueryMonitor_LOW_MEMORY_CANCELED_QUERY.toLocalizedString(QueryMonitor.getMemoryUsedDuringLowMemory());
      //throw query exception to piggyback on existing error handling as qp.executeQuery also throws the same error for low memory
      throw new QueryExecutionLowMemoryException(reason);
    }

      DefaultQuery query = new DefaultQuery(this.queryString, r.getCache());
      // Remote query, use the PDX types in serialized form.
      DefaultQuery.setPdxReadSerialized(r.getCache(), true);
      // In case of "select *" queries we can keep the results in serialized
      // form and send
      query.setRemoteQuery(true);
      QueryObserver indexObserver = query.startTrace();

      try {
        query.setIsCqQuery(this.cqQuery);
        //ds.queryLocalNode(query, this.parameters, this.buckets, this.resultCollector);
        PRQueryProcessor qp = new PRQueryProcessor(r, query, parameters, buckets);
        if (l.fineEnabled()) {
          l.fine("Started executing query from remote node: " + query.getQueryString());
        }
        qp.executeQuery(this.resultCollector);
        this.currentSelectResultIterator = this.resultCollector.iterator();
        //resultSize = this.resultCollector.size() - this.buckets.size(); //Minus END_OF_BUCKET elements.
        super.operateOnPartitionedRegion(dm, r, startTime);
      } finally {
        DefaultQuery.setPdxReadSerialized(r.getCache(), false);
        query.setRemoteQuery(false);
        query.endTrace(indexObserver, startTime, this.resultCollector);
      }
    //}
    //else {
    //  l.warning(LocalizedStrings.QueryMessage_QUERYMESSAGE_DATA_STORE_NOT_CONFIGURED_FOR_THIS_MEMBER);
    //}

    // Unless there was an exception thrown, this message handles sending the response
    return false;
  }

  @Override
  protected void appendFields(StringBuilder buff) {
    super.appendFields(buff);
    buff.append("; query=").append(this.queryString)
    .append("; bucketids=").append(this.buckets);
  }

  public int getDSFID() {
    return PR_QUERY_MESSAGE;
  }

  /** send a reply message.  This is in a method so that subclasses can override the reply message type
   *  @see PutMessage#sendReply
   */
  @Override
  protected void sendReply(InternalDistributedMember member, int procId, DM dm, ReplyException ex, PartitionedRegion pr, long startTime) {
    // if there was an exception, then throw out any data
    if (ex != null) {
      this.outStream = null;
      this.replyMsgNum = 0;
      this.replyLastMsg = true;
    }
    if (this.replyLastMsg) {
      if (pr != null && startTime > 0) {
        pr.getPrStats().endPartitionMessagesProcessing(startTime);
      }
    }
    StreamingReplyMessage.send(member, procId, ex, dm, this.outStream,
        this.numObjectsInChunk, this.replyMsgNum,
        this.replyLastMsg, this.isPdxSerialized);
  }

  @Override
  public void fromData(DataInput in)
      throws IOException, ClassNotFoundException {
    super.fromData(in);
    this.queryString = DataSerializer.readString(in);
    this.buckets = DataSerializer.readArrayList(in);
    this.parameters = DataSerializer.readObjectArray(in);
    this.cqQuery = DataSerializer.readBoolean(in);
    this.isPdxSerialized = DataSerializer.readBoolean(in);
    this.traceOn = DataSerializer.readBoolean(in);
  }

  @Override
  public void toData(DataOutput out)
      throws IOException {
    super.toData(out);
    DataSerializer.writeString(this.queryString, out);
    DataSerializer.writeArrayList((ArrayList)this.buckets, out);
    DataSerializer.writeObjectArray(this.parameters, out);
    DataSerializer.writeBoolean(this.cqQuery, out);
    DataSerializer.writeBoolean(true, out);
    DataSerializer.writeBoolean(this.traceOn, out);
  }

}


text:
namespace Microsoft.PackageManagement.MetaProvider.PowerShell {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Internal;
    using Microsoft.PackageManagement.Internal.Utility.Extensions;

    public class DynamicOption : Yieldable {
        public DynamicOption(OptionCategory category, string name, OptionType expectedType, bool isRequired, IEnumerable<object> permittedValues) {
            Name = name;
            ExpectedType = expectedType;
            IsRequired = isRequired;
            PermittedValues = permittedValues;
        }

        public DynamicOption(string name, OptionType expectedType, bool isRequired, IEnumerable<object> permittedValues) {
            Name = name;
            ExpectedType = expectedType;
            IsRequired = isRequired;
            PermittedValues = permittedValues;
        }

        public DynamicOption(OptionCategory category,string name,  OptionType expectedType, bool isRequired) : this(category, name , expectedType, isRequired, null) {
        }

        public DynamicOption(string name, OptionType expectedType, bool isRequired)
            : this(name, expectedType, isRequired, null) {
        }

        public DynamicOption() {
        }

        public string Name {get; set;}
        public OptionType ExpectedType {get; set;}
        public bool IsRequired {get; set;}
        public IEnumerable<object> PermittedValues {get; set;}

        public override bool YieldResult(PsRequest r) {
            if (r == null) {
                throw new ArgumentNullException("r");
            }
            return r.YieldDynamicOption(Name, ExpectedType.ToString(), IsRequired) && PermittedValues.WhereNotNull().Select(each => each.ToString()).ToArray().All(v => r.YieldKeyValuePair(Name, v));
        }
    }
}