text:
using System;
using System.Collections.Generic;
using System.Linq;
using ArcGIS.Core.Data;
using ArcGIS.Core.Data.UtilityNetwork;
using ArcGIS.Desktop.Mapping;

namespace UtilityNetworkSamples
{
  class UtilityNetworkUtils
  {

    /// <summary>
    /// GetUtilityNetworkFromFeatureClass - gets a utility network from a layer
    /// </summary>
    /// <param name="layer"></param>
    /// <returns>a UtilityNetwork object, or null if the layer does not reference a utility network</returns>
    public static UtilityNetwork GetUtilityNetworkFromLayer(Layer layer)
    {

      UtilityNetwork utilityNetwork = null;

      if (layer is UtilityNetworkLayer)
      {
        UtilityNetworkLayer utilityNetworkLayer = layer as UtilityNetworkLayer;
        utilityNetwork = utilityNetworkLayer.GetUtilityNetwork();
      }

      else if (layer is SubtypeGroupLayer)
      {
        CompositeLayer compositeLayer = layer as CompositeLayer;
        utilityNetwork = GetUtilityNetworkFromLayer(compositeLayer.Layers.First());
      }

      else if (layer is FeatureLayer)
      {
        FeatureLayer featureLayer = layer as FeatureLayer;
        using (FeatureClass featureClass = featureLayer.GetFeatureClass())
        {
          if (featureClass.IsControllerDatasetSupported())
          {
            IReadOnlyList<Dataset> controllerDatasets = new List<Dataset>();
            controllerDatasets = featureClass.GetControllerDatasets();
            foreach (Dataset controllerDataset in controllerDatasets)
            {
              if (controllerDataset is UtilityNetwork)
              {
                utilityNetwork = controllerDataset as UtilityNetwork;
              }
              else
              {
                controllerDataset.Dispose();
              }
            }
          }
        }
      }

      else if (layer is GroupLayer)
      {
        CompositeLayer compositeLayer = layer as CompositeLayer;
        foreach (Layer childLayer in compositeLayer.Layers)
        {
          utilityNetwork = GetUtilityNetworkFromLayer(childLayer);
          // Break at the first layer inside a group layer that belongs to a utility network
          if (utilityNetwork != null) break;
        }
      }

      return utilityNetwork;
    }

    /// <summary>
    /// Fetches a Row from an Element
    /// </summary>
    /// <param name="utilityNetwork">The utility network to which the element belongs</param>
    /// <param name="element">An element in a utility network</param>
    /// <returns>The Row corresponding to the Element (if any)</returns>
    public static Row FetchRowFromElement(UtilityNetwork utilityNetwork, Element element)
    {
      // Get the table from the element
      using (Table table = utilityNetwork.GetTable(element.NetworkSource))
      {
        // Create a query filter to fetch the appropriate row
        QueryFilter queryFilter = new QueryFilter()
        {
          ObjectIDs = new List<long>() { element.ObjectID }
        };

        // Fetch and return the row
        using (RowCursor rowCursor = table.Search(queryFilter))
        {
          if (rowCursor.MoveNext())
          {
            return rowCursor.Current;
          }
        }
        return null;
      }

    }

  }
}

redpajama_set_name: RedPajamaGithub


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

namespace PseudoCQRS.PropertyValueProviders
{
	public class PropertyValueProviderFactory : IPropertyValueProviderFactory
	{
		private readonly IServiceProvider _serviceProvider;

		private readonly List<IPropertyValueProvider> _propertyValueProviders;

		public PropertyValueProviderFactory( IServiceProvider serviceProvider )
		{
			_serviceProvider = serviceProvider;
			var httpContext = _serviceProvider.GetService( typeof(IHttpContextWrapper)) as IHttpContextWrapper;
			_propertyValueProviders = new List<IPropertyValueProvider>()
			{
				new CookiePropertyValueProvider( httpContext ),
				new SessionPropertyValueProvider( httpContext ),
				new RouteDataPropertyValueProvider( httpContext ),
				new QueryStringPropertyValueProvider( httpContext ),
				new FormDataPropertyValueProvider( httpContext )
			};
		}

		public IEnumerable<IPropertyValueProvider> GetPropertyValueProviders()
		{
			return _propertyValueProviders;
		}

		public IPersistablePropertyValueProvider GetPersistablePropertyValueProvider( PersistanceLocation location )
		{
			IPersistablePropertyValueProvider result = null;
			switch ( location )
			{
				case PersistanceLocation.Cookie:
					result = new CookiePropertyValueProvider(_serviceProvider.GetService(typeof(IHttpContextWrapper)) as IHttpContextWrapper );
					break;
				case PersistanceLocation.Session:
					result = new SessionPropertyValueProvider(_serviceProvider.GetService(typeof(IHttpContextWrapper)) as IHttpContextWrapper );
					break;
			}

			return result;
		}
	}
}


text:
package org.gradle.api.services.internal;

import com.google.common.collect.ImmutableList;
import org.gradle.api.artifacts.component.BuildIdentifier;
import org.gradle.api.services.BuildService;
import org.gradle.api.services.BuildServiceParameters;
import org.gradle.internal.Try;
import org.gradle.internal.instantiation.InstantiationScheme;
import org.gradle.internal.isolated.IsolationScheme;
import org.gradle.internal.isolation.IsolatableFactory;
import org.gradle.internal.service.ServiceLookup;
import org.gradle.internal.service.ServiceRegistry;

import javax.annotation.Nullable;

// TODO:configuration-cache - complain when used at configuration time, except when opted in to this
public class RegisteredBuildServiceProvider<T extends BuildService<P>, P extends BuildServiceParameters> extends BuildServiceProvider<T, P> {

    protected final ServiceRegistry internalServices;
    protected BuildServiceDetails<T, P> serviceDetails;

    @SuppressWarnings("rawtypes")
    private final IsolationScheme<BuildService, BuildServiceParameters> isolationScheme;
    private final InstantiationScheme instantiationScheme;
    private final IsolatableFactory isolatableFactory;
    private final Listener listener;
    private Try<T> instance;

    public RegisteredBuildServiceProvider(
        BuildIdentifier buildIdentifier,
        String name,
        Class<T> implementationType,
        @Nullable P parameters,
        @SuppressWarnings("rawtypes")
        IsolationScheme<BuildService, BuildServiceParameters> isolationScheme,
        InstantiationScheme instantiationScheme,
        IsolatableFactory isolatableFactory,
        ServiceRegistry internalServices,
        Listener listener,
        @Nullable Integer maxUsages
    ) {
        this.serviceDetails = new BuildServiceDetails<>(buildIdentifier, name, implementationType, parameters, maxUsages);
        this.internalServices = internalServices;
        this.isolationScheme = isolationScheme;
        this.instantiationScheme = instantiationScheme;
        this.isolatableFactory = isolatableFactory;
        this.listener = listener;
    }

    @Override
    public BuildServiceDetails<T, P> getServiceDetails() {
        return serviceDetails;
    }

    @Override
    public BuildIdentifier getBuildIdentifier() {
        return serviceDetails.getBuildIdentifier();
    }

    public String getName() {
        return serviceDetails.getName();
    }

    public Class<T> getImplementationType() {
        return serviceDetails.getImplementationType();
    }

    @Nullable
    public P getParameters() {
        return serviceDetails.getParameters();
    }

    @Nullable
    @Override
    public Class<T> getType() {
        return serviceDetails.getImplementationType();
    }

    @Override
    protected Value<? extends T> calculateOwnValue(ValueConsumer consumer) {
        return Value.of(getInstance());
    }

    private T getInstance() {
        listener.beforeGet(this);
        synchronized (this) {
            if (instance == null) {
                instance = instantiate();
            }
        }
        return instance.get();
    }

    private Try<T> instantiate() {
        // TODO - extract some shared infrastructure to take care of instantiation (eg which services are visible, strict vs lenient, decorated or not?)
        // TODO - should hold the project lock to do the isolation. Should work the same way as artifact transforms (a work node does the isolation, etc)
        P isolatedParameters = isolatableFactory.isolate(getParameters()).isolate();
        // TODO - reuse this in other places
        ServiceLookup instantiationServices = instantiationServicesFor(isolatedParameters);
        try {
            return Try.successful(instantiate(instantiationServices));
        } catch (Exception e) {
            return Try.failure(instantiationException(e));
        }
    }

    private ServiceLifecycleException instantiationException(Exception e) {
        return new ServiceLifecycleException("Failed to create service '" + getName() + "'.", e);
    }

    private T instantiate(ServiceLookup instantiationServices) {
        return instantiationScheme.withServices(instantiationServices).instantiator().newInstance(getImplementationType());
    }

    private ServiceLookup instantiationServicesFor(@Nullable P isolatedParameters) {
        return isolationScheme.servicesForImplementation(
            isolatedParameters,
            internalServices,
            ImmutableList.of(),
            serviceType -> false
        );
    }

    @Override
    public ExecutionTimeValue<? extends T> calculateExecutionTimeValue() {
        return ExecutionTimeValue.changingValue(this);
    }

    @Override
    public void maybeStop() {
        synchronized (this) {
            try {
                if (instance != null) {
                    instance.ifSuccessful(t -> {
                        if (t instanceof AutoCloseable) {
                            try {
                                ((AutoCloseable) t).close();
                            } catch (Exception e) {
                                throw new ServiceLifecycleException("Failed to stop service '" + getName() + "'.", e);
                            }
                        }
                    });
                }
            } finally {
                instance = null;
            }
        }
    }
}


text:
class CreateCharacterClasses < ActiveRecord::Migration
  def change
    create_table :character_classes do |t|
      t.string :class_name, null: false
      t.integer :level, null: false;
      t.belongs_to :character, index: true, null: false;

      t.timestamps null: false
    end
    add_index :character_classes, [:character_id, :class_name, :level], :name => 'ind_chclass_on_ch_id_and_chname_and_level', :unique=>true
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:text="Enhorabuena!"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:src="@drawable/orbit"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:text="Por tus logros, hemos enviado a tu email un vale para que pruebes el nuevo ORBIT White totalmente gratis! Sigue así!!!"/>

</LinearLayout>


text:
@implementation FLObjcCodeGenerator

- (id) initWithProjectProvider:(id<FLCodeGeneratorProjectProvider>) projectProvider {
	self = [super init];
	if(self) {
		_projectProvider = FLRetain(projectProvider);
        FLAssertNotNil(_projectProvider);
	}
	return self;
}

- (id) init {
    return [self initWithProjectProvider:nil];
}

+ (id) objcCodeGenerator:(id<FLCodeGeneratorProjectProvider>) projectProvider {
    return FLAutorelease([[[self class] alloc] initWithProjectProvider:projectProvider]);
}

#if FL_MRC
- (void)dealloc {
	[_projectProvider release];
	[super dealloc];
}
#endif

- (void) generateCode {

    FLCodeProject* inputProject = nil;

    @try {
        FLAssertNotNil(_projectProvider);

        inputProject = [_projectProvider readProjectForCodeGenerator:self];
        FLAssertNotNil(inputProject);

        [self sendMessageToListeners:@selector(codeGenerator:generationWillBeginForProject:)
                    withObject:self
                    withObject:inputProject];

        FLObjcProject* project = [FLObjcProject objcProject];
        [project configureWithProjectInput:inputProject];
        [project.fileManager writeFilesToDisk:self];

        [self sendMessageToListeners:@selector(codeGenerator:generationDidFinishForProject:)
                    withObject:self
                    withObject:inputProject];
    }
    @catch(NSException* ex) {
        [self sendMessageToListeners:@selector(codeGenerator:generationDidFailForProject:withError:)
                    withObject:self
                    withObject:inputProject
                    withObject:ex.error];
        @throw;

    }
}

- (FLPromisedResult) runSynchronously {
    [self generateCode];
    return FLSuccessfulResult;
}

@end


text:
Writing your first experiment
=============================

Please note, this tutorial is a work-in-progress and not complete. In the
meantime, we recommend reviewing the :doc:`PRISONER demo </tutorials.demo>` for
an understanding of how to build a simple experiment.

Now that you have a PRISONER development server up and running, we are going to
write a simple experiment which collects some data from a participant's Facebook
account, sanitises it, and displays it in the browser.

Prerequisites
-------------
This tutorial shows an experiment being written in Python, but as this is
to only demonstrate how to use the PRISONER web service, this can be easily
adapted to any other environment. This guide assumes a working understanding of
XML files.

This example requires a Facebook account to test, and assumes you are registered
as a `Facebook developer <https://developers.facebook.com>`_. You will need to
create a Facebook app, and make a note of its App ID and Secret. A short guide
to doing this is available in our :doc:`demo tutorial </tutorials.demo>`.

In this tutorial
----------------
PRISONER experiments consist of three elements, which we will introduce and
develop during this tutorial:

* Your experimental application

* An XML privacy policy

* An XML experimental design

Privacy policies
----------------
Privacy policies are XML documents which outline the types of data your
experiment needs to collect or publish to social network sites. They contain
rules that place constraints on how your experiment handles data.
For a given type of data (for example, a tweet, or a Facebook user profile),
the policy answers the following questions:

* Is my experiment able to handle this data type?

* Can my experiment retrieve, store, or publish this data type, or a combination of these?

* Under which conditions can I retrieve, store, or publish this data type?

* Which attributes of this data type can my experiment retrieve, store, or publish?

* Which attributes need to be sanitised as they are retrieved, stored, or published?

Encoding this information in a policy file yields some advantages from both
ethical and reproducibility perspectives:

*  Policies can be written "offline" before you write any code. This allows you
   to iterate on the appropriate data-handling strategy for your experiment,
   including engagement with IRB or ethics boards, until you arrive at a final
   set of constraints for your experiment.

* PRISONER enforces this policy at runtime, so that if the experimental code you are writing attempts to violate its constraints, you cannot inadvertently collect more data than needed for your experiment.

*  The standardised representation of the policy allows other documents to be
   automatically and consistently generated, such as consent forms for
   participants which reflect the actual data-handling practices of a study, or
   human-readable summaries of the study's design for review by IRB or ethics
   boards.

*  Privacy policies are effectively a workflow standard for social network
   experiments, and allow the protocols for studies to be shared. While ideally
   coupled with the underlying experimental code to support full reproducibility
   of experiments, the platform-agnostic nature of the privacy policy allows
   other researchers to replicate a study under the same constraints, even if
   they are not using PRISONER.

Writing the privacy policy
``````````````````````````
Outside of the PRISONER directory, create a directory to store your experiment
application. In there, create a new file called policy.xml. Populate it with the following:

.. literalinclude:: code/tutorials.helloworld.policy.xml
   :language: xml

So, what does this policy do? Simply, it enumerates the objects we can collect,
and the attributes of those objects we can collect. The policy file includes a
clear hierarchy where we define policy elements for each data type, which
contains a collection of attributes we can process, and an object-policy which
describes the criteria under which we can collect objects of this type. In this
experiment, we want to collect some biographical information about the
participant in this experiment, so our policy is for the User object provided by
Facebook. The Facebook prefix defines the namespace, which means we are
explicitly requesting Facebook's representation of a User, and is not
generalisable to the other social network sites that PRISONER supports. This
means we can access Facebook-specific attributes, but at the cost of making our
experiment harder to adapt for other services. Because we only want to collect
data about the current participant, we provide an object-policy which dictates
that we can only collect a User object if it matches the ID of the participant.
This ensures our experiment can not inadvertently collect more sensitive data
than we need, such as the identitfy of the participant's friends. Although we
now have criteria for collecting the objects themselves, the objects PRISONER
returns will have no attributes. Therefore, we must specifically enumerate the
attributes we need in the attributes collection of this policy. Each policy
element enables us to retrieve that attribute. We could add additional
attribute-policy elements for each attribute to also enable us to store those
attributes if we later wish to persist these data, but this is not necessary for
this experiment.

Later, when we write the experimental application, we will provide PRISONER with this policy to initialise the experiment and allow these constraints to be enforced.

Experimental designs
----------------
Experimental design files provide PRISONER with basic metadata about your
experiment, such as its name, properties for specific services such as API keys, and the structure of any data you wish to store so PRISONER can manage the database appropriately.

Writing the experimental design
``````````````````````````````
In the same directory where you wrote your privacy policy, add another file
called design.xml, and populate it with the following:

.. literalinclude:: code/tutorials.helloworld.design.xml
   :language: xml

What does this design do? First of all, note that in the tables element, we
specify two tables. The first is marked as a "participant" table, which
indicates to PRISONER that the table stores metadata about individual
participants. This allows PRISONER's internal record of an individual
participant, including their service-specific session identifiers, to be related
to the metadata that is specific to your experiment. In this case, we identify
participants by their email address.

Our second table is marked as a "response" table, which lets PRISONER know that
data collected during the course of an experiment can be stored here. For the
purposes of this tutorial, we will store the participant's Facebook profile
along with our identifier for that participant.

The schema we have provided here does not directly translate to the underlying
database which PRISONER will instantiate on our behalf. The "mapTo" syntax in
our response table means PRISONER will store the representation of a Facebook
profile in a metatable, which individual response records will be related to.
Rather than directly accessing the database, PRISONER recommends you use its
persistence API to store responses and retrieve them, with fully-formed social
objects returned as part of the response, where appropriate.

Finally, we provide some properties, or "props", which provide miscellaneous
metadata PRISONER needs to provide your experiment. Because we are using
Facebook, we must provide the App ID and secret for our app which we noted
earlier, so make sure you edit the file with these values as appropriate.
Finally, we provide a PRISONER secret. This is a passphrase which you will
provide to PRISONER whenever you make administrative commands, such as
initialising an experiment, to make sure you are authorised to do this.

Writing the experiment app
---------------------
We're two thirds of the way there! These two policy files do a lot of the work
in telling PRISONER what your experiment needs to do. From these two files,
PRISONER can create an entire pre-briefing structure and authentication flow,
and is now able to enforce constraints on our experiment's data collection.

Let's put this into action by writing a small web app. In this example, we're
using Python and the WSGI library Werkzeug, but you can choose to follow along
in an alternative environment of your choosing. As PRISONER is exposed as a web
service, your application just consists of your experiment-specific logic, along
with some simple HTTP requests to PRISONER to initialise an experiment and
retrieve the appropriate data.

Our experimental application consists of four functions:
* Initialise the PRISONER experiment with the policy files we have prepared, and
allow PRISONER to authenticate our participant with Facebook

* Collect some data from the participant's Facebook profile

* Present the collected data to the participant

* Store a response from the participant along with a sanitised subset of the
collected data in the PRISONER database.


text:
/**
 * Handle WiFi functions for ESP32-Duktape.  Functions included are:
 *
 * * WIFI.scan(callback) - Scan for WiFi access points and when complete, invoke the callback with
 * an array of found access points.  Each record in the list of access points will include:
 *   * ssid
 *   * rssi
 *   * mac
 *
 * * WIFI.getDNS() - Return an array of two items which are the two IP addresses (as strings)
 * of the DNS servers that we may know about.
 */

#include <apps/sntp/sntp.h>
#include <duktape.h>
#include <esp_err.h>
#include <esp_event_loop.h>
#include <esp_log.h>
#include <esp_wifi.h>
#include <lwip/dns.h>
#include <lwip/sockets.h>

#include "duktape_utils.h"
#include "duktape_event.h"
#include "esp32_specific.h"
#include "logging.h"
#include "module_wifi.h"
#include "sdkconfig.h"

LOG_TAG("module_wifi");

static uint32_t g_scanCallbackStashKey = -1;
static uint32_t g_gotipCallbackStashKey = -1;
static uint32_t g_apStartCallbackStashKey = -1;

static int scanParamsDataProvider(duk_context *ctx, void *context);

/*
 * This function is called when the ESP32_DUKTAPE_CALLBACK_TYPE_FUNCTION is
 * being processed and adds the context as a parameter to the called back
 * function.  It adds an error code which is either "null" to indicate that
 * there was no error or it adds a string indicating the error.
 */
static int addError(duk_context *ctx, void *context) {
	if (context == NULL) {
		duk_push_null(ctx);
	} else {
		duk_push_string(ctx, (char *)context);
	}
	return 1;
} // addError

/**
 * Convert an authentication mode to a string.
 */
static char *authModeToString(wifi_auth_mode_t mode) {
	switch(mode) {
	case WIFI_AUTH_OPEN:
		return "open";
	case WIFI_AUTH_WEP:
		return "wep";
	case WIFI_AUTH_WPA_PSK:
		return "wpa";
	case WIFI_AUTH_WPA2_PSK:
		return "wpa2";
	case WIFI_AUTH_WPA_WPA2_PSK:
		return "wpa_wpa2";
	default:
		return "unknown";
	}
} // authModeToString

/**
 * An ESP32 WiFi event handler.
 * The types of events that can be received here are:
 *
 * SYSTEM_EVENT_AP_PROBEREQRECVED
 * SYSTEM_EVENT_AP_STACONNECTED
 * SYSTEM_EVENT_AP_STADISCONNECTED
 * SYSTEM_EVENT_AP_START
 * SYSTEM_EVENT_AP_STOP
 * SYSTEM_EVENT_SCAN_DONE
 * SYSTEM_EVENT_STA_AUTHMODE_CHANGE
 * SYSTEM_EVENT_STA_CONNECTED
 * SYSTEM_EVENT_STA_DISCONNECTED
 * SYSTEM_EVENT_STA_GOT_IP
 * SYSTEM_EVENT_STA_START
 * SYSTEM_EVENT_STA_STOP
 * SYSTEM_EVENT_WIFI_READY
 */
static esp_err_t esp32_wifi_eventHandler(void *param_ctx, system_event_t *event) {
	LOGD(">> esp32_wifi_eventHandler");
	// Your event handling code here...
	switch(event->event_id) {

		case SYSTEM_EVENT_STA_GOT_IP: {
			if (g_gotipCallbackStashKey == -1) {
				break;
			}
			event_newCallbackRequestedEvent(
				ESP32_DUKTAPE_CALLBACK_TYPE_FUNCTION,
				g_gotipCallbackStashKey,
				addError, // No data provider function
				NULL  // No context data
			);
			g_gotipCallbackStashKey = -1;
			break;
		} // SYSTEM_EVENT_STA_GOT_IP

		case SYSTEM_EVENT_STA_DISCONNECTED: {
			if (g_gotipCallbackStashKey == -1) {
				break;
			}
			event_newCallbackRequestedEvent(
				ESP32_DUKTAPE_CALLBACK_TYPE_FUNCTION,
				g_gotipCallbackStashKey,
				addError, // No data provider function
				"STA_DISCONNECTED"
			);
			g_gotipCallbackStashKey = -1;
			break;
		} // SYSTEM_EVENT_STA_DISCONNECTED

		case SYSTEM_EVENT_AP_START: {
			if (g_apStartCallbackStashKey == -1) {
				LOGD("No AP Start callback stash key, no callback to invoke.");
				break;
			}
			// We have a stashed callback to invoke, so invoke it...
			event_newCallbackRequestedEvent(
				ESP32_DUKTAPE_CALLBACK_TYPE_FUNCTION,
				g_apStartCallbackStashKey,
				NULL, // No data provider function
				NULL  // No context data
			);
			g_apStartCallbackStashKey = -1;
			break;
		} // SYSTEM_EVENT_AP_START

		case SYSTEM_EVENT_SCAN_DONE: {
			// If we have received a scan done but no callback waiting, do nothing.
			if (g_scanCallbackStashKey == -1) {
				break;
			}
			// We now have a scan ... so let us now raise an event saying that
			// the scan has completed!
			//event_newWifiScanCompletedEvent();
			event_newCallbackRequestedEvent(
				ESP32_DUKTAPE_CALLBACK_TYPE_FUNCTION,
				g_scanCallbackStashKey,
				scanParamsDataProvider,
				NULL // No context data
			);
			g_scanCallbackStashKey = -1;
			break;
		} // SYSTEM_EVENT_SCAN_DONE

		default: {
			break;
		}
	}
	LOGD("<< esp32_wifi_eventHandler");
	return ESP_OK;
} // esp32_wifi_eventHandler

/**
 * Connect WiFi to an access point.
 * [0] - options:
 * - ssid
 * - password [optional]
 * - network [optional]
 *  - ip
 *  - gw
 *  - netmask
 * [1] - callback: a callback function
 */
static duk_ret_t js_wifi_connect(duk_context* ctx) {
	esp_err_t errRc;

	LOGD(">> js_wifi_connect");
	char* password = ""; // Default password is none.
  tcpip_adapter_ip_info_t ipInfo;
  duk_idx_t optionsIdx = 0;

  if (!duk_is_object(ctx, -2)) {
  	duk_error(ctx, 1, "Missing options object");
  }

  // [0] - Options
  // [1] - Callback | Undefined [optional]
  if (duk_is_function(ctx, -1)) {
  	// we have a callback
  	g_gotipCallbackStashKey = esp32_duktape_stash_array(ctx, 1);
  } else {
  	duk_pop(ctx); // Remove the thing that might have been a callback function
  }

	duk_get_prop_string(ctx, optionsIdx, "ssid");
	if (!duk_is_string(ctx, -1)) {
		duk_error(ctx, 1, "Invalid ssid");
	}
	const char *ssid = duk_get_string(ctx, -1);
	duk_pop(ctx);

	// The password is optional.
	if (duk_has_prop_string(ctx, optionsIdx, "password")) {
		duk_get_prop_string(ctx, -1, "password");
		if (!duk_is_string(ctx, -1)) {
			duk_error(ctx, 1, "Invalid password");
		}
		password = (char *)duk_get_string(ctx, -1);
		duk_pop(ctx);
	}

	/*
	errRc = esp_wifi_disconnect();
	if (errRc != ESP_OK) {
		LOGD("esp_wifi_disconnect rc=%s", esp32_errToString(errRc));
	}
*/
	// Handle any network options that may have been supplied.  If network options
	// were supplied then we will NOT be using DHCP and instead we should have
	// been supplied our own IP address, gateway address and netmask.  Extract
	// and use those.
	int useDHCP = 1;
	if (duk_has_prop_string(ctx, optionsIdx, "network")) {

		duk_get_prop_string(ctx, -1, "network");
		duk_get_prop_string(ctx, -1, "ip");
		const char *ipString = duk_get_string(ctx, -1);
		duk_pop(ctx);

		duk_get_prop_string(ctx, -1, "gw");
		const char *gwString = duk_get_string(ctx, -1);
		duk_pop(ctx);

		duk_get_prop_string(ctx, -1, "netmask");
		const char *netmaskString = duk_get_string(ctx, -1);
		duk_pop(ctx);

		/*
		ipString = "192.168.1.99";
		gwString = "192.168.1.1";
		netmaskString = "255.255.255.0";
		*/

		// We now try and get network IP information but check that it is good first
	  if (inet_pton(AF_INET, ipString, &ipInfo.ip) == 1 &&
	     inet_pton(AF_INET, gwString, &ipInfo.gw) == 1 &&
	     inet_pton(AF_INET, netmaskString, &ipInfo.netmask)) {
			LOGD(" - Using specific network info: ip: %s, gw: %s, netmask: %s",
				ipString, gwString, netmaskString);
			tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); // Don't run a DHCP client
			tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &ipInfo);
			useDHCP = 0;
	  } // Setup network portion
	} // We have a network object

	if (useDHCP) {
		// Since we were NOT supplied network information or couldn't use it, use DHCP.
		errRc = tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
		if (errRc != ESP_OK) {
			LOGE("tcpip_adapter_dhcpc_start() rc=%d", errRc);
			duk_error(ctx, 1, "tcpip_adapter_dhcpc_start rc=%s", esp32_errToString(errRc));
		}
	} // useDHCP is true

	// Perform the actual connection to the access point.
	LOGD("Calling esp_wifi_set_mode()");
	errRc = esp_wifi_set_mode(WIFI_MODE_STA);
	if (errRc != ESP_OK) {
		LOGE("esp_wifi_set_mode() rc=%d", errRc);
		duk_error(ctx, 1, "esp_wifi_set_mode rc=%s", esp32_errToString(errRc));
	}
	vTaskDelay(2000/portTICK_PERIOD_MS);

	LOGD(" - Connecting to access point: \"%s\" with \"%s\"", ssid, "<Password hidden>");
  wifi_config_t sta_config;
  strcpy((char *)sta_config.sta.ssid, ssid);
  strcpy((char *)sta_config.sta.password, password);
  sta_config.sta.bssid_set = 0;

	LOGD("Calling esp_wifi_set_config()");
  errRc = esp_wifi_set_config(WIFI_IF_STA, &sta_config);
	if (errRc != ESP_OK) {
		LOGE("esp_wifi_set_config() rc=%d", errRc);
		duk_error(ctx, 1, "esp_wifi_set_config rc=%s", esp32_errToString(errRc));
	}
	vTaskDelay(2000/portTICK_PERIOD_MS);

	LOGD("Calling esp_wifi_start()");
	errRc = esp_wifi_start();
	if (errRc != ESP_OK) {
		LOGE("esp_wifi_start() rc=%d", errRc);
		duk_error(ctx, 1, "esp_wifi_start rc=%s", esp32_errToString(errRc));
	}

	vTaskDelay(2000/portTICK_PERIOD_MS);

	LOGD("Performing a connect");
	LOGD("Calling esp_wifi_connect()");
	errRc = esp_wifi_connect();
	if (errRc != ESP_OK) {
		LOGE("esp_wifi_connect() rc=%d", errRc);
		duk_error(ctx, 1, "esp_wifi_connect rc=%s", esp32_errToString(errRc));
	}

	LOGD("<< js_wifi_connect");
  return 0;
} // js_wifi_connect

static duk_ret_t js_wifi_disconnect(duk_context *ctx) {
	LOGD(">> js_wifi_disconnect");
	esp_err_t errRc = esp_wifi_disconnect();
	if (errRc != ESP_OK) {
		LOGE("esp_wifi_disconnect: %s", esp32_errToString(errRc));
	}
	LOGD("<< js_wifi_disconnect");
	return 0;
} // js_wifi_disconnect

/**
 * Retrieve the DNS servers that are associated with the device.
 * The return is an object on the stack of the form:
 * [ <string>, <string>, ... ] where each of the strings is an IP address
 * of a DNS server.  The reason there are "DNS_MAX_SERVER" is that the ESP32 can have
 * a primary and secondary DNS server (and maybe more or less).
 */
static duk_ret_t js_wifi_getDNS(duk_context *ctx) {
	char ipString[20];
	ip_addr_t ip;
	int i;

	LOGD(">> js_wifi_getDNS");

	duk_idx_t idx = duk_push_array(ctx); // Create new WIFI object
	// [0] - New array - DNS servers

	// There are "DNS_MAX_SERVERS" DNS servers that may be known to us.
	for (i=0; i<DNS_MAX_SERVERS; i++) { // DNS_MAX_SERVERS comes from lwip ... see http://www.nongnu.org/lwip/2_0_0/group__dns.html

		ip = dns_getserver(i);
		inet_ntop(AF_INET, &ip, ipString, sizeof(ipString));
		LOGD("DNS: %d = %s", i, ipString);

		duk_push_string(ctx, ipString);
		// [0] - New array - DNS servers
		// [1] - IP address

		duk_put_prop_index(ctx, idx, i);
		// [0] - New array - DNS servers
	}

	LOGD("<< js_wifi_getDNS");
	return 1; // New array - DNS servers
} // js_wifi_getDNS

/**
 * WIFI.getState()
 * Return an object that describes the state of the WiFi environment.
 * {
 *    isStation:
 *    isAccessPoint:
 *    apMac:
 *    staMac:
 *    country:
 * }
 */
static duk_ret_t js_wifi_getState(duk_context *ctx) {
	wifi_mode_t mode;

	int isAccessPoint;
	int isStation;
	ESP_ERROR_CHECK(esp_wifi_get_mode(&mode));
	switch(mode) {
	case WIFI_MODE_NULL:
		isAccessPoint = 0;
		isStation = 0;
		break;
	case WIFI_MODE_STA:
		isAccessPoint = 0;
		isStation = 1;
		break;
	case WIFI_MODE_AP:
		isAccessPoint = 1;
		isStation = 0;
		break;
	case WIFI_MODE_APSTA:
		isAccessPoint = 1;
		isStation = 1;
		break;
	default:
		isAccessPoint = 0;
		isStation = 0;
		break;
	}

	char apMacString[20];
	char staMacString[20];
	uint8_t mac[6];

	ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_AP, mac));
	sprintf(apMacString, MACSTR, MAC2STR(mac));

	ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, mac));
	sprintf(staMacString, MACSTR, MAC2STR(mac));

	wifi_country_t country;
	ESP_ERROR_CHECK(esp_wifi_get_country(&country));
	char *countryString = country.cc;

	tcpip_adapter_ip_info_t staIpInfo;
	char staIpString[20];
	tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &staIpInfo);
	sprintf(staIpString, IPSTR, IP2STR(&staIpInfo.ip));

	tcpip_adapter_ip_info_t apIpInfo;
	char apIpString[20];
	tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &apIpInfo);
	sprintf(apIpString, IPSTR, IP2STR(&apIpInfo.ip));

	duk_push_object(ctx);
	duk_push_boolean(ctx, isStation);
	duk_put_prop_string(ctx, -2, "isStation");
	duk_push_boolean(ctx, isAccessPoint);
	duk_put_prop_string(ctx, -2, "isAccessPoint");
	duk_push_string(ctx, apMacString);
	duk_put_prop_string(ctx, -2, "apMac");
	duk_push_string(ctx, staMacString);
	duk_put_prop_string(ctx, -2, "staMac");
	duk_push_string(ctx, countryString);
	duk_put_prop_string(ctx, -2, "country");
	duk_push_string(ctx, staIpString);
	duk_put_prop_string(ctx, -2, "staIp");
	duk_push_string(ctx, apIpString);
	duk_put_prop_string(ctx, -2, "apIp");

	return 1;
} // End of js_wifi_getState_func

/**
 * Listen as an access point
 * options:
 * - ssid
 * - password
 * - auth
 * callback function: [optional]
 */
static duk_ret_t js_wifi_listen(duk_context *ctx) {
	LOGD(">> js_wifi_listen");

  if (!duk_is_object(ctx, -2)) {
  	duk_error(ctx, 1, "Missing options object");
  }

  // [0] - Options
  // [1] - Callback | Undefined [optional]

  // Check to see if we have a callback function, if we do, stash it.
  if (duk_is_function(ctx, -1)) {
  	// we have a callback
  	g_apStartCallbackStashKey = esp32_duktape_stash_array(ctx, 1);
  } else {
  	duk_pop(ctx); // Remove the thing that might have been a callback function
  }

  // [0] - Options

	char *password = "";

	duk_get_prop_string(ctx, -1, "ssid");
	if (!duk_is_string(ctx, -1)) {
		duk_error(ctx, 1, "Invalid ssid");
	}
	const char *ssid = duk_get_string(ctx, -1);
	duk_pop(ctx);

	duk_get_prop_string(ctx, -1, "auth");
	if (!duk_is_string(ctx, -1)) {
		duk_error(ctx, 1, "Invalid auth");
	}
	const char *auth = duk_get_string(ctx, -1);
	duk_pop(ctx);

	wifi_auth_mode_t authMode;
	if (strcmp(auth, "open") == 0) {
		authMode = WIFI_AUTH_OPEN;
	}
	else if (strcmp(auth, "wep") == 0) {
		authMode = WIFI_AUTH_WEP;
	}
	else if (strcmp(auth, "wpa") == 0) {
		authMode = WIFI_AUTH_WPA_PSK;
	}
	else if (strcmp(auth, "wpa2") == 0) {
		authMode = WIFI_AUTH_WPA2_PSK;
	}
	else if (strcmp(auth, "wpa_wpa2") == 0) {
		authMode = WIFI_AUTH_WPA_WPA2_PSK;
	} else {
		duk_error(ctx, 1, "Invalid auth: %s", auth);
	}

	if (authMode != WIFI_AUTH_OPEN) {
		duk_get_prop_string(ctx, -1, "password");
		if (!duk_is_string(ctx, -1)) {
			duk_error(ctx, 1, "Invalid password");
		}
		password = (char *)duk_get_string(ctx, -1);
		duk_pop(ctx);
	}

	esp_err_t errRc = esp_wifi_stop();
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "esp_wifi_stop rc=%s", esp32_errToString(errRc));
	}

	errRc = esp_wifi_set_mode(WIFI_MODE_AP);
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "esp_wifi_set_mode rc=%s", esp32_errToString(errRc));
	}

	LOGD(" - Being an access point: %s with auth mode %s", ssid, auth);
	wifi_config_t ap_config;
	strcpy((char *)ap_config.ap.ssid, ssid);
	ap_config.ap.ssid_len = 0;
	strcpy((char *)ap_config.ap.password, password);
	ap_config.ap.channel = 0;
	ap_config.ap.authmode = authMode;
	ap_config.ap.ssid_hidden = 0;
	ap_config.ap.max_connection = 4;
	ap_config.ap.beacon_interval = 100;

	errRc = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "esp_wifi_set_config rc=%s", esp32_errToString(errRc));
	}

	errRc = esp_wifi_start();
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "esp_wifi_start rc=%s", esp32_errToString(errRc));
	}

	/*
	errRc = esp_wifi_connect();
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "esp_wifi_connect rc=%s", esp32_errToString(errRc));
	}
	*/
	return 0;
} // js_wifi_listen

/**
 * Handle a request to do a scan.  We are expecting that the caller will pass
 * in a function reference that will be a callback function.
 * [0] - Function object
 */
static duk_ret_t js_wifi_scan(duk_context *ctx) {
	LOGD(">> js_wifi_scan");
	if (!duk_is_function(ctx, 0)) {
		LOGD("Scan: not a function!");
		return 0;
	}

	// Stash the top [1] items on the value stack and place in an array in stash.
	g_scanCallbackStashKey = esp32_duktape_stash_array(ctx, 1);

	/*
	duk_push_heap_stash(ctx);
	// [0] - Function object
	// [1] - Heap stash

	if (!duk_get_prop_string(ctx, -1, "scan_callbacks_array")) {
		// [0] - Function object
		// [1] - Heap stash
		// [2] - scan_callbacks array (undefined)

		duk_pop(ctx);
		// [0] - Function object
		// [1] - Heap stash

		duk_push_array(ctx);
		// [0] - Function object
		// [1] - Heap stash
		// [2] - new array

		duk_put_prop_string(ctx, -2, "scan_callbacks_array");
		// [0] - Function object
		// [1] - Heap stash

		duk_get_prop_string(ctx, -1, "scan_callbacks_array");
		// [0] - Function object
		// [1] - Heap stash
		// [2] - scan_callbacks array
	}

	int length = duk_get_length(ctx, -1);

	duk_dup(ctx, 0);
	// [0] - Function object
	// [1] - Heap stash
	// [2] - scan_callbacks array
	// [3] - Function object

	duk_put_prop_index(ctx, -2, length); // Add the function object to the array.
	// [0] - Function object
	// [1] - Heap stash
	// [2] - scan_callbacks array

	duk_pop_3(ctx);
	// <Stack Empty>
	 */

	// Now that we have saved the callback, request that the scan is performed.
	wifi_scan_config_t conf;
	conf.channel     = 0;
	conf.bssid       = NULL;
	conf.ssid        = NULL;
	conf.show_hidden = 1;
	ESP_ERROR_CHECK(esp_wifi_scan_start(&conf, 0 /* don't block */));

	LOGD("<< js_wifi_scan");
	return 0;
} // js_wifi_scan

/*
 * [0] - An array of dotted decimal IP addresses.
 */
static duk_ret_t js_wifi_setDNS(duk_context *ctx) {
	LOGD(">> js_wifi_setDNS");
	int length = duk_get_length(ctx, -1);
	if (length > DNS_MAX_SERVERS) {
		length = DNS_MAX_SERVERS;
	}

	int i;
	for (i=0; i<length; i++) {
		duk_get_prop_index(ctx, -1, i);
		// [0] - An array of dotted decimal IP addresses.
		// [1] - An IP address
		const char *ipAddrString = duk_get_string(ctx, -1);
		LOGD("Setting DNS[%d] to %s", i, ipAddrString);
		ip_addr_t ipAddr;
		int rc = ipaddr_aton(ipAddrString, &ipAddr);
		if (rc != 1) {
			LOGE("Failed to parse IP address: %s", ipAddrString);
			return 0;
		}
		dns_setserver(i, &ipAddr);
		duk_pop(ctx);
	}
	LOGD("<< js_wifi_setDNS");
	return 0;
}

/*
 * Set and start using an SNTP time server.
 * [0] - IP address as a string
 */
static duk_ret_t js_wifi_setTimeServer(duk_context *ctx) {
	const char *ipAddressString = duk_get_string(ctx, -1);
	ip_addr_t addr;
	sntp_setoperatingmode(SNTP_OPMODE_POLL);
	inet_pton(AF_INET, ipAddressString, &addr);
	sntp_setserver(0, &addr);
	sntp_init();
	return 0;
} // js_wifi_setTimeServer

static duk_ret_t js_wifi_start(duk_context *ctx) {
	LOGD(">> js_wifi_start");
	esp_err_t errRc = esp_wifi_start();
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "js_wifi_start rc=%s", esp32_errToString(errRc));
	}
	LOGD("<< js_wifi_start");
	return 0;
} // js_wifi_start

static duk_ret_t js_wifi_stop(duk_context *ctx) {
	LOGD(">> js_wifi_stop");
	esp_err_t errRc = esp_wifi_stop();
	if (errRc != ESP_OK) {
		duk_error(ctx, 1, "js_wifi_stop rc=%s", esp32_errToString(errRc));
	}
	LOGD("<< js_wifi_stop");
	return 0;
} // js_wifi_stop

// Handle the event that a Wifi scan has completed.  Our logic here is to build an
// object that contains the results and leave that on the value stack.
//
// A published scan record will contain:
// {
//    ssid: <network id>,
//    mac: <mac address>
//    rssi: <signal strength>
//    auth: <authentication mode>
// }
//
static int scanParamsDataProvider(duk_context *ctx, void *context) {
	LOGD("Here we build the scan results ...");

	LOGD("Process a scan result event.");

	// Get the number of access points in our last scan.
	uint16_t numAp;
	ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&numAp));

	// Allocate storage for our scan results and retrieve them.
	wifi_ap_record_t *apRecords = calloc(sizeof(wifi_ap_record_t), numAp);
	ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&numAp, apRecords));
	LOGD("Number of Access Points: %d", numAp);

	// Build an array for the results ...
	duk_idx_t resultIdx = duk_push_array(ctx);
	// [0] - Array - results

	// Add each of the scan results into the array.
	int i;
	for (i=0; i<numAp; i++) {
		LOGD("%d: ssid=%s", i, apRecords[i].ssid);
		duk_idx_t scanResultIdx = duk_push_object(ctx); // Create a new scan result object
		// [0] - Array - results
		// [1] - New object

		duk_push_string(ctx, (char *)apRecords[i].ssid);
		// [0] - Array - results
		// [1] - New object
		// [2] - String (ssid)

		duk_put_prop_string(ctx, scanResultIdx, "ssid");
		// [0] - Array - results
		// [1] - New object

		duk_push_sprintf(ctx, MACSTR, MAC2STR(apRecords[i].bssid));
		// [0] - Array - results
		// [1] - New object
		// [2] - String (mac)

		duk_put_prop_string(ctx, scanResultIdx, "mac");
		// [0] - Array - results
		// [1] - New object

		duk_push_int(ctx, apRecords[i].rssi);
		// [0] - Array - results
		// [1] - New object
		// [2] - Number (rssi)

		duk_put_prop_string(ctx, scanResultIdx, "rssi");
		// [0] - Array - results
		// [1] - New object

		duk_push_string(ctx, authModeToString(apRecords[i].authmode));
		// [0] - Array - results
		// [1] - New object
		// [2] - String (auth)

		duk_put_prop_string(ctx, scanResultIdx, "auth");
		// [0] - Array - results
		// [1] - New object

		duk_put_prop_index(ctx, resultIdx, i); // Add the new record into the results array
		// [0] - Array - results
	}
	free(apRecords);
	return 1;
} //scanParamsDataProvider

/**
 * Create the WIFI module in Global.
 */
void ModuleWIFI(duk_context *ctx) {
	duk_push_global_object(ctx);
	// [0] - Global object

	duk_push_object(ctx); // Create new WIFI object
	// [0] - Global object
	// [1] - New object

	ADD_FUNCTION("connect",       js_wifi_connect,       2);
	ADD_FUNCTION("disconnect",    js_wifi_disconnect,    0);
	ADD_FUNCTION("getDNS",        js_wifi_getDNS,        0);
	ADD_FUNCTION("getState",      js_wifi_getState,      0);
	ADD_FUNCTION("listen",        js_wifi_listen,        2);
	ADD_FUNCTION("scan",          js_wifi_scan,          1);
	ADD_FUNCTION("setDNS",        js_wifi_setDNS,        1);
	ADD_FUNCTION("setTimeServer", js_wifi_setTimeServer, 1);
	ADD_FUNCTION("start",         js_wifi_start,         0);
	ADD_FUNCTION("stop",          js_wifi_stop,          0);

	duk_put_prop_string(ctx, 0, "WIFI"); // Add WIFI to global
	// [0] - Global object

	duk_pop(ctx);

	// Setup the new Event handler
	esp_event_loop_set_cb(esp32_wifi_eventHandler, NULL); // No return code to check.
} // ModuleWIFI


text:
package com.jeroenreijn.examples.view;

import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractTemplateView;
import org.trimou.Mustache;

public class TrimouView extends AbstractTemplateView {
	private Mustache mustache;

	protected TrimouView() {
	}

	public TrimouView(final Mustache mustache) {
		this.mustache = mustache;
	}

	public void setMustache(final Mustache mustache) {
		this.mustache = mustache;
	}

	@Override
	protected void renderMergedTemplateModel(final Map<String, Object> model, final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		Objects.requireNonNull(mustache, "mustache must not be null");

		response.setCharacterEncoding("UTF-8");

		try (PrintWriter writer = response.getWriter()) {
			mustache.render(writer, model);
		}
	}
}


text:
/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

using System;
using Server.Network;

namespace Server.Gumps
{
    public class GumpItemProperty : GumpEntry
    {
        private int m_Serial;

        public GumpItemProperty(int serial)
        {
            m_Serial = serial;
        }

        public int Serial
        {
            get
            {
                return m_Serial;
            }
            set
            {
                Delta(ref m_Serial, value);
            }
        }

        public override string Compile()
        {
            return String.Format("{{ itemproperty {0} }}", m_Serial);
        }

        private static byte[] m_LayoutName = Gump.StringToBuffer("itemproperty");

        public override void AppendTo(IGumpWriter disp)
        {
            disp.AppendLayout(m_LayoutName);
            disp.AppendLayout(m_Serial);
        }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="DynamicBindingListBase.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>This is the base class from which collections</summary>
//-----------------------------------------------------------------------
#if NETFX_CORE || (ANDROID || IOS)
using System;
using Csla;

namespace Csla
{
  /// <summary>
  /// This is the base class from which collections
  /// of editable root business objects should be
  /// derived.
  /// </summary>
  /// <typeparam name="T">
  /// Type of editable root object to contain within
  /// the collection.
  /// </typeparam>
  /// <remarks>
  /// <para>
  /// Your subclass should implement a factory method
  /// and should override or overload
  /// DataPortal_Fetch() to implement data retrieval.
  /// </para><para>
  /// Saving (inserts or updates) of items in the collection
  /// should be handled through the SaveItem() method on
  /// the collection.
  /// </para><para>
  /// Removing an item from the collection
  /// through Remove() or RemoveAt() causes immediate deletion
  /// of the object, by calling the object's Delete() and
  /// Save() methods.
  /// </para>
  /// </remarks>
  [Serializable]
  public class DynamicBindingListBase<T> : DynamicListBase<T>
    where T : Core.IEditableBusinessObject, Core.IUndoableObject, Core.ISavable, Csla.Serialization.Mobile.IMobileObject
  { }
}
#else
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Csla.Core;

namespace Csla
{
  /// <summary>
  /// This is the base class from which collections
  /// of editable root business objects should be
  /// derived.
  /// </summary>
  /// <typeparam name="T">
  /// Type of editable root object to contain within
  /// the collection.
  /// </typeparam>
  /// <remarks>
  /// <para>
  /// Your subclass should implement a factory method
  /// and should override or overload
  /// DataPortal_Fetch() to implement data retrieval.
  /// </para><para>
  /// Saving (inserts or updates) of items in the collection
  /// should be handled through the SaveItem() method on
  /// the collection.
  /// </para><para>
  /// Removing an item from the collection
  /// through Remove() or RemoveAt() causes immediate deletion
  /// of the object, by calling the object's Delete() and
  /// Save() methods.
  /// </para>
  /// </remarks>
  [Serializable()]
  public abstract class DynamicBindingListBase<T> :
    Core.ExtendedBindingList<T>,
    Core.IParent,
    Server.IDataPortalTarget
    where T : Core.IEditableBusinessObject, Core.IUndoableObject, Core.ISavable, IBusinessObject
  {
    /// <summary>
    /// Creates an instance of the object.
    /// </summary>
    public DynamicBindingListBase()
    {
      Initialize();
      AllowNew = true;
    }

#region Initialize

    /// <summary>
    /// Override this method to set up event handlers so user
    /// code in a partial class can respond to events raised by
    /// generated code.
    /// </summary>
    protected virtual void Initialize()
    { /* allows subclass to initialize events before any other activity occurs */ }

#endregion

#region  SaveItem Methods

    private bool _activelySaving;

    /// <summary>
    /// Saves the specified item in the list.
    /// </summary>
    /// <param name="item">
    /// Reference to the item to be saved.
    /// </param>
    /// <remarks>
    /// This method properly saves the child item,
    /// by making sure the item in the collection
    /// is properly replaced by the result of the
    /// Save() method call.
    /// </remarks>
    public T SaveItem(T item)
    {
      return SaveItem(IndexOf(item));
    }

    /// <summary>
    /// Saves the specified item in the list.
    /// </summary>
    /// <param name="index">
    /// Index of the item to be saved.
    /// </param>
    /// <remarks>
    /// This method properly saves the child item,
    /// by making sure the item in the collection
    /// is properly replaced by the result of the
    /// Save() method call.
    /// </remarks>
    public virtual T SaveItem(int index)
    {
      bool raisingEvents = this.RaiseListChangedEvents;
      this.RaiseListChangedEvents = false;
      _activelySaving = true;

      T item = default(T);
      T result = default(T);
      try
      {
        item = this[index];
        result = item;
        T savable = item;

        // clone the object if possible
        ICloneable clonable = savable as ICloneable;
        if (clonable != null)
          savable = (T)clonable.Clone();

        // commit all changes
        int editLevel = savable.EditLevel;
        for (int tmp = 1; tmp <= editLevel; tmp++)
          savable.AcceptChanges(editLevel - tmp, false);

        // do the save
        result = (T)savable.Save();

        if (!ReferenceEquals(result, item))
        {
          // restore edit level to previous level
          for (int tmp = 1; tmp <= editLevel; tmp++)
            result.CopyState(tmp, false);

          // put result into collection
          this[index] = result;
        }

        if (!ReferenceEquals(savable, item))
        {
          // raise Saved event from original object
          Core.ISavable original = item as Core.ISavable;
          if (original != null)
            original.SaveComplete(result);
        }

        OnSaved(result, null);
      }
      finally
      {
        _activelySaving = false;
        this.RaiseListChangedEvents = raisingEvents;
      }
      this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
      return result;
    }

#endregion

#region Saved Event
    [NonSerialized]
    [NotUndoable]
    private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers;
    [NotUndoable]
    private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers;

    /// <summary>
    /// Event raised when an object has been saved.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
      "CA1062:ValidateArgumentsOfPublicMethods")]
    public event EventHandler<Csla.Core.SavedEventArgs> Saved
    {
      add
      {
        if (value.Method.IsPublic &&
           (value.Method.DeclaringType.IsSerializable ||
            value.Method.IsStatic))
          _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
            System.Delegate.Combine(_serializableSavedHandlers, value);
        else
          _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
            System.Delegate.Combine(_nonSerializableSavedHandlers, value);
      }
      remove
      {
        if (value.Method.IsPublic &&
           (value.Method.DeclaringType.IsSerializable ||
            value.Method.IsStatic))
          _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
            System.Delegate.Remove(_serializableSavedHandlers, value);
        else
          _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
            System.Delegate.Remove(_nonSerializableSavedHandlers, value);
      }
    }

    /// <summary>
    /// Raises the Saved event.
    /// </summary>
    /// <param name="newObject">
    /// Reference to object returned from the save.
    /// </param>
    /// <param name="e">
    /// Reference to any exception that occurred during
    /// the save.
    /// </param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void OnSaved(T newObject, Exception e)
    {
      Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, null);
      if (_nonSerializableSavedHandlers != null)
        _nonSerializableSavedHandlers.Invoke(this, args);
      if (_serializableSavedHandlers != null)
        _serializableSavedHandlers.Invoke(this, args);
    }

#endregion

#region  Insert, Remove, Clear

    /// <summary>
    /// Adds a new item to the list.
    /// </summary>
    /// <returns>The added object</returns>
    protected override object AddNewCore()
    {
      T item = Csla.DataPortal.Create<T>();
      Add(item);
      this.OnAddingNew(new AddingNewEventArgs(item));
      return item;
    }

    /// <summary>
    /// Gives the new object a parent reference to this
    /// list.
    /// </summary>
    /// <param name="index">Index at which to insert the item.</param>
    /// <param name="item">Item to insert.</param>
    protected override void InsertItem(int index, T item)
    {
      item.SetParent(this);
      base.InsertItem(index, item);
    }

    /// <summary>
    /// Removes an item from the list.
    /// </summary>
    /// <param name="index">Index of the item
    /// to be removed.</param>
    protected override void RemoveItem(int index)
    {
      // delete item from database
      T item = this[index];

      // only delete/save the item if it is not new
      bool raiseEventForNewItem = false;
      if (!item.IsNew)
      {
        item.Delete();
        SaveItem(index);
      }
      else
      {
        raiseEventForNewItem = true;
      }

      base.RemoveItem(index);
      if (raiseEventForNewItem)
        OnSaved(item, null);
    }

    /// <summary>
    /// Replaces item in the list.
    /// </summary>
    /// <param name="index">Index of the item
    /// that was replaced.</param>
    /// <param name="item">New item.</param>
    protected override void SetItem(int index, T item)
    {
      item.SetParent(this);
      base.SetItem(index, item);
    }

#endregion

#region  IParent Members

    void Csla.Core.IParent.ApplyEditChild(Core.IEditableBusinessObject child)
    {
      if (!_activelySaving && child.EditLevel == 0)
        SaveItem((T)child);
    }

    void Csla.Core.IParent.RemoveChild(Core.IEditableBusinessObject child)
    {
      if (child.IsNew)
        Remove((T)child);
    }

    IParent Csla.Core.IParent.Parent
    {
      get { return null; }
    }

#endregion

#region  Cascade Child events

    /// <summary>
    /// Handles any PropertyChanged event from
    /// a child object and echoes it up as
    /// a ChildChanged event.
    /// </summary>
    /// <param name="sender">Object that raised the event.</param>
    /// <param name="e">Property changed args.</param>
    [EditorBrowsable(EditorBrowsableState.Never)]
    protected override void Child_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
      for (int index = 0; index < this.Count; index++)
      {
        if (ReferenceEquals(this[index], sender))
        {
          PropertyDescriptor descriptor = GetPropertyDescriptor(e.PropertyName);
          if (descriptor != null)
            OnListChanged(new ListChangedEventArgs(
              ListChangedType.ItemChanged, index, GetPropertyDescriptor(e.PropertyName)));
          else
            OnListChanged(new ListChangedEventArgs(
              ListChangedType.ItemChanged, index));
          return;
        }
      }
      OnChildPropertyChanged(sender, e);
      base.Child_PropertyChanged(sender, e);
    }

    void Child_BusyChanged(object sender, BusyChangedEventArgs e)
    {
      OnBusyChanged(e);
    }

    /// <summary>
    /// Override this method to be notified when a child object
    /// has been changed.
    /// </summary>
    /// <param name="sender">
    /// Child object where the PropertyChanged event originated.
    /// </param>
    /// <param name="e">
    /// PropertyChangedEventArgs from the child object.
    /// </param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void OnChildPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    { }

    private static PropertyDescriptorCollection _propertyDescriptors;

    private PropertyDescriptor GetPropertyDescriptor(string propertyName)
    {
      if (_propertyDescriptors == null)
        _propertyDescriptors = TypeDescriptor.GetProperties(this.GetType());
      PropertyDescriptor result = null;
      foreach (PropertyDescriptor desc in _propertyDescriptors)
        if (desc.Name == propertyName)
        {
          result = desc;
          break;
        }
      return result;
    }

#endregion

#region  Serialization Notification

    /// <summary>
    /// This method is called on a newly deserialized object
    /// after deserialization is complete.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected override void OnDeserialized()
    {
      foreach (IEditableBusinessObject child in this)
      {
        child.SetParent(this);
        INotifyPropertyChanged c = child as INotifyPropertyChanged;
        if (c != null)
          c.PropertyChanged += new PropertyChangedEventHandler(Child_PropertyChanged);
      }
      base.OnDeserialized();
    }

#endregion

#region  Data Access

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")]
    private void DataPortal_Create(object criteria)
    {
      throw new NotSupportedException(Properties.Resources.CreateNotSupportedException);
    }

    /// <summary>
    /// Override this method to allow retrieval of an existing business
    /// object based on data in the database.
    /// </summary>
    /// <param name="criteria">An object containing criteria values to identify the object.</param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
    protected virtual void DataPortal_Fetch(object criteria)
    {
      throw new NotSupportedException(Properties.Resources.FetchNotSupportedException);
    }

    private void DataPortal_Update()
    {
      throw new NotSupportedException(Properties.Resources.UpdateNotSupportedException);
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")]
    private void DataPortal_Delete(object criteria)
    {
      throw new NotSupportedException(Properties.Resources.DeleteNotSupportedException);
    }

    /// <summary>
    /// Called by the server-side DataPortal prior to calling the
    /// requested DataPortal_xyz method.
    /// </summary>
    /// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member"), EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
    {

    }

    /// <summary>
    /// Called by the server-side DataPortal after calling the
    /// requested DataPortal_xyz method.
    /// </summary>
    /// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member"), EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
    {

    }

    /// <summary>
    /// Called by the server-side DataPortal if an exception
    /// occurs during data access.
    /// </summary>
    /// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
    /// <param name="ex">The Exception thrown during data access.</param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member"), EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
    {

    }

#endregion

#region ToArray

    /// <summary>
    /// Get an array containing all items in the list.
    /// </summary>
    public T[] ToArray()
    {
      List<T> result = new List<T>();
      foreach (T item in this)
        result.Add(item);
      return result.ToArray();
    }

#endregion

#region IDataPortalTarget Members

    void Csla.Server.IDataPortalTarget.CheckRules()
    { }

    void Csla.Server.IDataPortalTarget.MarkAsChild()
    { }

    void Csla.Server.IDataPortalTarget.MarkNew()
    { }

    void Csla.Server.IDataPortalTarget.MarkOld()
    { }

    void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
    {
      this.DataPortal_OnDataPortalInvoke(e);
    }

    void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
    {
      this.DataPortal_OnDataPortalInvokeComplete(e);
    }

    void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
    {
      this.DataPortal_OnDataPortalException(e, ex);
    }

    void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e)
    { }

    void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
    { }

    void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
    { }

#endregion

#region IsBusy

    /// <summary>
    /// Gets a value indicating whether this object
    /// is currently running an async operation.
    /// </summary>
    public override bool IsBusy
    {
      get
      {
        // run through all the child objects
        // and if any are dirty then then
        // collection is dirty
        foreach (T child in this)
          if (child.IsBusy)
            return true;

        return false;
      }
    }

#endregion
  }
}
#endif


text:
package org.apache.maven.continuum.initialization;

/**
 * @author Jason van Zyl
 */
public interface ContinuumInitializer
{
    String DEFAULT_PROJECT_GROUP_GROUP_ID = "default";

    String ROLE = ContinuumInitializer.class.getName();

    void initialize()
        throws ContinuumInitializationException;

}


text:
/**
 * Software Version Strophe Plugin
 * Implements http://xmpp.org/extensions/xep-0092.html
 */

Strophe.addConnectionPlugin('version', {

  _connection: null,

  init: function (conn) {
    this._connection = conn;
    Strophe.addNamespace('XEP0092', 'jabber:iq:version');
  },

  handlify: function (callback) {
    return [
      this._connection.addHandler(callback, Strophe.NS.XEP0092, 'iq', 'result', null, null),
      this._connection.addHandler(this._onGet.bind(this), Strophe.NS.XEP0092, 'iq', 'get', null, null)
    ];
  },

  request: function (to) {
    var iq = $iq({to: to, type: 'get'});
	  msg.c('query', {xmlns: Strophe.NS.XEP0092});
	  this._connection.send(iq.tree());
    console.log(iq);
  },

  _onGet: function (stanza) {
    console.log(stanza);
    var iq = $iq({to: $(stanza).attr('from'), type: 'result', id: $(stanza).attr('id')});
    var query = $build('query', {xmlns: Strophe.NS.XEP0092});
	  query.c('name', {}, App.name);
	  query.c('version', {}, App.version + App.minorVersion);
	  query.c('os', {}, Lungo.Core.environment().os ? Lungo.Core.environment().os.name : 'PC');
	  iq.cnode(query.tree());
	  console.log(iq.tree());
	  this._connection.send(iq.tree());
    return true;
  }

});


text:
import React from 'react';
import { Table,Button } from 'antd';
import weiGuDong from '../../appConstants/assets/images/微股东.png';
import normalCard from '../../appConstants/assets/images/普卡.png';
import silverCard from '../../appConstants/assets/images/银卡.png';
import goldenCard from '../../appConstants/assets/images/金卡.png';
import superGoldenCard from '../../appConstants/assets/images/白金卡.png';

// In the fifth row, other columns are merged into first column
// by setting it's colSpan to be 0

const UserListTable = React.createClass({

    jinLevels() {
        return ['注册用户(0%)', weiGuDong, normalCard, silverCard, goldenCard, superGoldenCard];
    },

	getColumns(){

        const jinLevels = this.jinLevels();

		const columns = [{
		  title: '姓名',
		  dataIndex: 'user_name',
          key : 'user_name',
		  render(text, record, index) {
		      return (

                        {text.slice(0, 1)}

{text}

		      );
		  },
		}, {
		  title: '级别',
		  dataIndex: 'level',
          key : 'level',
          render(text, record, index) {
              // console.log('text', text, 'index', index);
              if (text == '0') {
                  return {jinLevels[text]}
              }
              return (

              )
          }
		}, {
		  title: '邮币卡账号',
		  dataIndex: 'account',
          key : 'account'
		}, {
		  title: '总手续费',
		  dataIndex: 'fees',
          key : 'fees'
		}, {
		  title: '总盈亏',
		  dataIndex: 'profit_and_loss',
		  key : 'profit_and_loss'
		}, {
		  title: '交易时间',
		  dataIndex: 'transaction_date',
		  key : 'transaction_date'
		}, {
		  title: '操作',
		  render(text, record, index){
		  	return (
		  		<Button type="primary" size="small" disabled icon="search">个人详情</Button>
		  	)
		  }
		}];

		return columns;
	},

    onChange(page) {
        this.props.onPageChange(page);
    },

	render(){
		const columns = this.getColumns();
        const dataSource = this.props.dataSource.list;
        const pagination = {
            defaultPageSize : this.props.defaultPageSize,
            onChange : this.onChange,
            total : this.props.total,
            current : parseInt(this.props.currentPage)
        };
		return(

		)
	}
});

export default UserListTable;


text:
package com.haulmont.cuba.web.gui.components.datagrid;

import com.haulmont.cuba.gui.components.data.DataGridItems;
import com.haulmont.cuba.web.widgets.data.SortableDataProvider;

public class SortableDataGridDataProvider<T>
        extends DataGridDataProvider<T>
        implements SortableDataProvider<T> {

    public SortableDataGridDataProvider(DataGridItems.Sortable<T> dataGridSource,
                                        DataGridItemsEventsDelegate<T> dataEventsDelegate) {
        super(dataGridSource, dataEventsDelegate);
    }

    public DataGridItems.Sortable<T> getSortableDataGridSource() {
        return (DataGridItems.Sortable<T>) dataGridItems;
    }

    @Override
    public void sort(Object[] propertyId, boolean[] ascending) {
        getSortableDataGridSource().sort(propertyId, ascending);
    }

    @Override
    public void resetSortOrder() {
        getSortableDataGridSource().resetSortOrder();
    }
}


text:
import {ajaxApi} from '../utils';

//模拟登录接口
export function getToken(data) {
    return ajaxApi('/session', {
        method: 'post',
        data,
    });
}


text:
layout: post
title: Rails Devise scoped views
comments: true
tags:
  - rails
  - devise
---

If you have more than one Devise model in your application (such as User and Admin),
by default Devise uses the same views for all models. But Devise offers an easy way to customize views.

### Enable scoped views

Set `config.scoped_views = true` inside the `config/initializers/devise.rb` file.

`/config/initializers/devise.rb`

```rb
config.scoped_views = true
```

### Create devise models (e.g., user, admin)

```bash
$ rails g devise user
$ rails g devise admin
```

### Configure devise modules to be included in each devise model

```rb
class Admin < ApplicationRecord
  devise :database_authenticatable, :trackable, :validatable
  ...
end
```

```rb
class User < ApplicationRecord
  devise :database_authenticatable, :registerable, :recoverable, :rememberable,
         :trackable, :validatable, :confirmable, :omniauthable
  ...
end
```

### Create devise controllers

```bash
$ rails g devise:controllers users
$ rails g devise:controllers admins
```

### Configure namespaced devise routes

```rb
Rails.application.routes.draw do
  devise_for :admins, controllers: {
    sessions:           "admins/sessions"
  }
  devise_for :users, controllers: {
    sessions:           "users/sessions",
    passwords:          "users/passwords",
    registrations:      "users/registrations",
    confirmations:      "users/confirmations",
    omniauth_callbacks: "users/omniauth_callbacks"
  }
  ...
end
```

### Delete unnecessary devise files

- `app/views/devise/*`
- `app/controllers/admins/passwords_controller.rb`
- `app/controllers/admins/registrations_controller.rb`
- etc

---

## References

- [plataformatec/devise#configuring-views](https://github.com/plataformatec/devise#configuring-views)
- [Rails - Devise Gem remove Sign up and Forgot Password modules](http://stackoverflow.com/a/23009970/3837223)
- [Rails で devise ひとつで複数モデルを管理しよう](http://qiita.com/Yama-to/items/54ab4ce08e126ef7dade)


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.folding;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.PossiblyDumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * Used by LanguageFolding class if more than one FoldingBuilder were specified
 * for a particular language.
 *
 * @author Konstantin Bulenkov
 * @see LanguageFolding
 */
public class CompositeFoldingBuilder extends FoldingBuilderEx implements PossiblyDumbAware {
  public static final Key<FoldingBuilder> FOLDING_BUILDER = new Key<>("FOLDING_BUILDER");
  private final List<? extends FoldingBuilder> myBuilders;

  CompositeFoldingBuilder(List<? extends FoldingBuilder> builders) {
    myBuilders = builders;
  }

  @Override
  @NotNull
  public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
    final List<FoldingDescriptor> descriptors = new ArrayList<>();
    final Set<TextRange> rangesCoveredByDescriptors = ContainerUtil.newHashSet();

    for (FoldingBuilder builder : DumbService.getInstance(root.getProject()).filterByDumbAwareness(myBuilders)) {
      for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptorsNoPlaceholderCaching(builder, root, document, quick)) {
        if (rangesCoveredByDescriptors.add(descriptor.getRange())) {
          descriptor.getElement().putUserData(FOLDING_BUILDER, builder);
          descriptors.add(descriptor);
        }
      }
    }

    return descriptors.toArray(FoldingDescriptor.EMPTY);
  }

  @Override
  public String getPlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) {
    final FoldingBuilder builder = node.getUserData(FOLDING_BUILDER);
    return !mayUseBuilder(node, builder) ? node.getText() :
           builder instanceof FoldingBuilderEx ? ((FoldingBuilderEx)builder).getPlaceholderText(node, range)
                                               : builder.getPlaceholderText(node);
  }

  @Override
  public String getPlaceholderText(@NotNull ASTNode node) {
    final FoldingBuilder builder = node.getUserData(FOLDING_BUILDER);
    return !mayUseBuilder(node, builder) ? node.getText() : builder.getPlaceholderText(node);
  }

  @Override
  public boolean isCollapsedByDefault(@NotNull ASTNode node) {
    final FoldingBuilder builder = node.getUserData(FOLDING_BUILDER);
    return mayUseBuilder(node, builder) && builder.isCollapsedByDefault(node);
  }

  private static boolean mayUseBuilder(@NotNull ASTNode node, @Nullable FoldingBuilder builder) {
    if (builder == null) return false;
    if (DumbService.isDumbAware(builder)) return true;

    Project project = getProjectByNode(node);
    return project == null || !DumbService.isDumb(project);
  }

  @Nullable
  private static Project getProjectByNode(@NotNull ASTNode node) {
    PsiElement psi = node.getPsi();
    if (psi == null) {
      ASTNode parent = node.getTreeParent();
      psi = parent == null ? null : parent.getPsi();
    }
    return psi == null ? null : psi.getProject();
  }

  @Override
  public String toString() {
    return getClass().getSimpleName() + myBuilders;
  }

  @Override
  public boolean isDumbAware() {
    for (FoldingBuilder builder : myBuilders) {
      if (DumbService.isDumbAware(builder)) {
        return true;
      }
    }
    return false;
  }
}


text:
package java.util.logging;

import java.beans.BeansFactory;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.ListResourceBundle;
import java.util.Properties;
import java.util.StringTokenizer;
import libcore.io.IoUtils;

/*-[
#include "java/io/IOException.h"
]-*/

/**
 * {@code LogManager} is used to maintain configuration properties of the
 * logging framework, and to manage a hierarchical namespace of all named
 * {@code Logger} objects.
 *

 * There is only one global {@code LogManager} instance in the
 * application, which can be get by calling static method
 * {@link #getLogManager()}. This instance is created and
 * initialized during class initialization and cannot be changed.
 *

 * The {@code LogManager} class can be specified by
 * java.util.logging.manager system property, if the property is unavailable or
 * invalid, the default class {@link java.util.logging.LogManager} will
 * be used.
 *

 * On initialization, {@code LogManager} reads its configuration from a
 * properties file, which by default is the "lib/logging.properties" in the JRE
 * directory.
 *

 * However, two optional system properties can be used to customize the initial
 * configuration process of {@code LogManager}.
 *

 *
"java.util.logging.config.class"

 *
"java.util.logging.config.file"

 *

 *

 * These two properties can be set in three ways, by the Preferences API, by the
 * "java" command line property definitions, or by system property definitions
 * passed to JNI_CreateJavaVM.
 *

 * The "java.util.logging.config.class" should specifies a class name. If it is
 * set, this given class will be loaded and instantiated during
 * {@code LogManager} initialization, so that this object's default
 * constructor can read the initial configuration and define properties for
 * {@code LogManager}.
 *

 * If "java.util.logging.config.class" property is not set, or it is invalid, or
 * some exception is thrown during the instantiation, then the
 * "java.util.logging.config.file" system property can be used to specify a
 * properties file. The {@code LogManager} will read initial
 * configuration from this file.
 *

 * If neither of these properties is defined, or some exception is thrown
 * during these two properties using, the {@code LogManager} will read
 * its initial configuration from default properties file, as described above.
 *

 * The global logging properties may include:
 *

 *
"handlers". This property's values should be a list of class names for
 * handler classes separated by whitespace, these classes must be subclasses of
 * {@code Handler} and each must have a default constructor, these
 * classes will be loaded, instantiated and registered as handlers on the root
 * {@code Logger} (the {@code Logger} named ""). These
 * {@code Handler}s maybe initialized lazily.

 *
"config". The property defines a list of class names separated by
 * whitespace. Each class must have a default constructor, in which it can
 * update the logging configuration, such as levels, handlers, or filters for
 * some logger, etc. These classes will be loaded and instantiated during
 * {@code LogManager} configuration

 *

 *

 * This class, together with any handler and configuration classes associated
 * with it, must be loaded from the system classpath when
 * {@code LogManager} configuration occurs.
 *

 * Besides global properties, the properties for loggers and Handlers can be
 * specified in the property files. The names of these properties will start
 * with the complete dot separated names for the handlers or loggers.
 *

 * In the {@code LogManager}'s hierarchical namespace,
 * {@code Loggers} are organized based on their dot separated names. For
 * example, "x.y.z" is child of "x.y".
 *

 * Levels for {@code Loggers} can be defined by properties whose name end
 * with ".level". Thus "alogger.level" defines a level for the logger named as
 * "alogger" and for all its children in the naming hierarchy. Log levels
 * properties are read and applied in the same order as they are specified in
 * the property file. The root logger's level can be defined by the property
 * named as ".level".
 *

 * This class is thread safe. It is an error to synchronize on a
 * {@code LogManager} while synchronized on a {@code Logger}.
 */
public class LogManager {

    /** The shared logging permission. */
    private static final LoggingPermission perm = new LoggingPermission("control", null);

    /** The singleton instance. */
    static LogManager manager;

    /**
     * The {@code String} value of the {@link LoggingMXBean}'s ObjectName.
     */
    public static final String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging";

    /**
     * Get the {@code LoggingMXBean} instance. this implementation always throws
     * an UnsupportedOperationException.
     *
     * @return the {@code LoggingMXBean} instance
     */
    public static LoggingMXBean getLoggingMXBean() {
        throw new UnsupportedOperationException();
    }

    // FIXME: use weak reference to avoid heap memory leak
    private Hashtable<String, Logger> loggers;

    /** The configuration properties */
    private Properties props;

    /** the property change listener */
    private PropertyChangeSupport listeners;

    static {     // init LogManager singleton instance
        String className = System.getProperty("java.util.logging.manager");
        if (className != null) {
            manager = (LogManager) getInstanceByClass(className);
        }
        if (manager == null) {
            manager = new LogManager();
        }
        checkConfiguration();

        // if global logger has been initialized, set root as its parent
        Logger root = new Logger("", null);
        root.setLevel(Level.INFO);
        Logger.global.setParent(root);

        manager.addLogger(root);
        manager.addLogger(Logger.global);
    }

    private static native void checkConfiguration() /*-[
      // To disable on iOS to improve startup performance, define
      // DISABLE_JAVA_LOG_CONFIGURATION to non-zero in project.
      #if !defined(DISABLE_JAVA_LOG_CONFIGURATION) || DISABLE_JAVA_LOG_CONFIGURATION == 0
        @try {
          [JavaUtilLoggingLogManager_manager readConfiguration];
        }
        @catch (JavaIoIOException *e) {
          [e printStackTrace];
        }
      #endif
    ]-*/;

    /**
     * Default constructor. This is not public because there should be only one
     * {@code LogManager} instance, which can be get by
     * {@code LogManager.getLogManager()}. This is protected so that
     * application can subclass the object.
     */
    protected LogManager() {
        loggers = new Hashtable<String, Logger>();
        props = new Properties();
        listeners = BeansFactory.newPropertyChangeSupportSafe(this);
        // add shutdown hook to ensure that the associated resource will be
        // freed when JVM exits
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override public void run() {
                reset();
            }
        });
    }

    /**
     * Does nothing.
     */
    public void checkAccess() {
    }

    /**
     * Add a given logger into the hierarchical namespace. The
     * {@code Logger.addLogger()} factory methods call this method to add newly
     * created Logger. This returns false if a logger with the given name has
     * existed in the namespace
     *

     * Note that the {@code LogManager} may only retain weak references to
     * registered loggers. In order to prevent {@code Logger} objects from being
     * unexpectedly garbage collected it is necessary for applications
     * to maintain references to them.
     *

     *
     * @param logger
     *            the logger to be added.
     * @return true if the given logger is added into the namespace
     *         successfully, false if the given logger exists in the namespace.
     */
    public synchronized boolean addLogger(Logger logger) {
        String name = logger.getName();
        if (loggers.get(name) != null) {
            return false;
        }
        addToFamilyTree(logger, name);
        loggers.put(name, logger);
        logger.setManager(this);
        return true;
    }

    private void addToFamilyTree(Logger logger, String name) {
        Logger parent = null;
        // find parent
        int lastSeparator;
        String parentName = name;
        while ((lastSeparator = parentName.lastIndexOf('.')) != -1) {
            parentName = parentName.substring(0, lastSeparator);
            parent = loggers.get(parentName);
            if (parent != null) {
                setParent(logger, parent);
                break;
            } else if (getProperty(parentName + ".level") != null ||
                    getProperty(parentName + ".handlers") != null) {
                parent = Logger.getLogger(parentName);
                setParent(logger, parent);
                break;
            }
        }
        if (parent == null && (parent = loggers.get("")) != null) {
            setParent(logger, parent);
        }

        // find children
        // TODO: performance can be improved here?
        String nameDot = name + '.';
        Collection<Logger> allLoggers = loggers.values();
        for (final Logger child : allLoggers) {
            Logger oldParent = child.getParent();
            if (parent == oldParent && (name.length() == 0 || child.getName().startsWith(nameDot))) {
                final Logger thisLogger = logger;
                child.setParent(thisLogger);
                if (oldParent != null) {
                    // -- remove from old parent as the parent has been changed
                    oldParent.children.remove(child);
                }
            }
        }
    }

    /**
     * Get the logger with the given name.
     *
     * @param name
     *            name of logger
     * @return logger with given name, or {@code null} if nothing is found.
     */
    public synchronized Logger getLogger(String name) {
        return loggers.get(name);
    }

    /**
     * Get a {@code Enumeration} of all registered logger names.
     *
     * @return enumeration of registered logger names
     */
    public synchronized Enumeration<String> getLoggerNames() {
        return loggers.keys();
    }

    /**
     * Get the global {@code LogManager} instance.
     *
     * @return the global {@code LogManager} instance
     */
    public static LogManager getLogManager() {
        return manager;
    }

    /**
     * Get the value of property with given name.
     *
     * @param name
     *            the name of property
     * @return the value of property
     */
    public String getProperty(String name) {
        return props.getProperty(name);
    }

    /**
     * Re-initialize the properties and configuration. The initialization
     * process is same as the {@code LogManager} instantiation.
     *

     * Notice : No {@code PropertyChangeEvent} are fired.
     *

     *
     * @throws IOException
     *             if any IO related problems happened.
     */
    public void readConfiguration() throws IOException {
        // check config class
        String configClassName = System.getProperty("java.util.logging.config.class");
        if (configClassName == null || getInstanceByClass(configClassName) == null) {
            // if config class failed, check config file
            String configFile = System.getProperty("java.util.logging.config.file");

            if (configFile == null) {
                // if cannot find configFile, use default logging.properties
                configFile = System.getProperty("java.home") + File.separator + "lib" +
                        File.separator + "logging.properties";
            }

            InputStream input = null;
            try {
                if (new File(configFile).exists()) {
                    input = new FileInputStream(configFile);
                } else {
                    // fall back to using the built-in logging.properties file
                    input = LogManager.class.getResourceAsStream("logging.properties");
                    if (input == null) {
                        input = new ByteArrayInputStream(
                            IOSLogHandler.IOS_LOG_MANAGER_DEFAULTS.getBytes());
                    }
                }
                readConfiguration(new BufferedInputStream(input));
            } finally {
                IoUtils.closeQuietly(input);
            }
        }
    }

    // use SystemClassLoader to load class from system classpath
    static Object getInstanceByClass(final String className) {
        try {
            Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(className);
            return clazz.newInstance();
        } catch (Exception e) {
            try {
                Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
                return clazz.newInstance();
            } catch (Exception innerE) {
                System.err.println("Loading class '" + className + "' failed");
                System.err.println(innerE);
                return null;
            }
        }
    }

    // actual initialization process from a given input stream
    private synchronized void readConfigurationImpl(InputStream ins)
            throws IOException {
        reset();
        props.load(ins);

        // The RI treats the root logger as special. For compatibility, always
        // update the root logger's handlers.
        Logger root = loggers.get("");
        if (root != null) {
            root.setManager(this);
        }

        // parse property "config" and apply setting
        String configs = props.getProperty("config");
        if (configs != null) {
            StringTokenizer st = new StringTokenizer(configs, " ");
            while (st.hasMoreTokens()) {
                String configerName = st.nextToken();
                getInstanceByClass(configerName);
            }
        }

        // set levels for logger
        Collection<Logger> allLoggers = loggers.values();
        for (Logger logger : allLoggers) {
            String property = props.getProperty(logger.getName() + ".level");
            if (property != null) {
                logger.setLevel(Level.parse(property));
            }
        }
        if (listeners != null) {
          listeners.firePropertyChange(null, null, null);
        }
    }

    /**
     * Re-initialize the properties and configuration from the given
     * {@code InputStream}
     *

     * Notice : No {@code PropertyChangeEvent} are fired.
     *

     *
     * @param ins
     *            the input stream
     * @throws IOException
     *             if any IO related problems happened.
     */
    public void readConfiguration(InputStream ins) throws IOException {
        checkAccess();
        readConfigurationImpl(ins);
    }

    /**
     * Reset configuration.
     *
     *
All handlers are closed and removed from any named loggers. All loggers'
     * level is set to null, except the root logger's level is set to
     * {@code Level.INFO}.
     */
    public synchronized void reset() {
        checkAccess();
        props = new Properties();
        Enumeration<String> names = getLoggerNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Logger logger = getLogger(name);
            if (logger != null) {
                logger.reset();
            }
        }
        Logger root = loggers.get("");
        if (root != null) {
            root.setLevel(Level.INFO);
        }
    }

    /**
     * Add a {@code PropertyChangeListener}, which will be invoked when
     * the properties are reread.
     *
     * @param l
     *            the {@code PropertyChangeListener} to be added.
     */
    public void addPropertyChangeListener(PropertyChangeListener l) {
        if (l == null) {
            throw new NullPointerException("l == null");
        }
        if (listeners == null) {
            BeansFactory.throwNotLoadedError();
        }
        checkAccess();
        listeners.addPropertyChangeListener(l);
    }

    /**
     * Remove a {@code PropertyChangeListener}, do nothing if the given
     * listener is not found.
     *
     * @param l
     *            the {@code PropertyChangeListener} to be removed.
     */
    public void removePropertyChangeListener(PropertyChangeListener l) {
        if (listeners == null) {
            BeansFactory.throwNotLoadedError();
        }
        checkAccess();
        listeners.removePropertyChangeListener(l);
    }

    /**
     * Returns a named logger associated with the supplied resource bundle.
     *
     * @param resourceBundleName the resource bundle to associate, or null for
     *      no associated resource bundle.
     */
    synchronized Logger getOrCreate(String name, String resourceBundleName) {
        Logger result = getLogger(name);
        if (result == null) {

        result = new Logger(name, resourceBundleName);
            addLogger(result);
        }
        return result;
    }

    /**
     * Sets the parent of this logger in the namespace. Callers must first
     * {@link #checkAccess() check security}.
     *
     * @param newParent
     *            the parent logger to set.
     */
    synchronized void setParent(Logger logger, Logger newParent) {
        logger.parent = newParent;

        if (logger.levelObjVal == null) {
            setLevelRecursively(logger, null);
        }
        newParent.children.add(logger);
    }

    /**
     * Sets the level on {@code logger} to {@code newLevel}. Any child loggers
     * currently inheriting their level from {@code logger} will be updated
     * recursively.
     *
     * @param newLevel the new minimum logging threshold. If null, the logger's
     *      parent level will be used; or {@code Level.INFO} for loggers with no
     *      parent.
     */
    synchronized void setLevelRecursively(Logger logger, Level newLevel) {
        int previous = logger.levelIntVal;
        logger.levelObjVal = newLevel;

        if (newLevel == null) {
            logger.levelIntVal = logger.parent != null
                    ? logger.parent.levelIntVal
                    : Level.INFO.intValue();
        } else {
            logger.levelIntVal = newLevel.intValue();
        }

        if (previous != logger.levelIntVal) {
            for (Logger child : logger.children) {
                if (child.levelObjVal == null) {
                    setLevelRecursively(child, null);
                }
            }
        }
    }

}


text:
URHO3D_DEFINE_PLUGIN_MAIN(Urho3D::GamePlugin);

namespace Urho3D
{

GamePlugin::GamePlugin(Context* context)
    : PluginApplication(context)
{
}

void GamePlugin::Load()
{
    // Register custom components/subsystems/events when plugin is loaded.
    RotateObject::RegisterObject(context_, this);
    FPSCameraController::RegisterObject(context_, this);
}

void GamePlugin::Unload()
{
    // Finalize plugin, ensure that no objects provided by the plugin are alive. Some of that work is automated by
    // parent class. Objects that had factories registered through PluginApplication::RegisterFactory<> have their
    // attributes automatically unregistered, factories/subsystems removed.
}

void GamePlugin::Start()
{
    // Set up any game state here. Configure input. Create objects. Add UI. Game application assumes control of the
    // input.
    context_->GetSubsystem<Input>()->SetMouseVisible(false);
    context_->GetSubsystem<Input>()->SetMouseMode(MM_WRAP);
}

void GamePlugin::Stop()
{
    // Tear down any game state here. Unregister events. Remove objects. Editor takes back the control.
}

}


text:
% imodwtj -- Compute inverse MODWT for jth level.
%
%****f* wmtsa.dwt/imodwtj
%
% NAME
%   imodwtj -- Compute inverse MODWT for jth level.
%
% SYNOPSIS
%   Vout = imodwtj(Wt_j, Vin, ht, gt, j)
%
% INPUTS
%   Wt_j            - MODWT wavelet coefficients for jth level.
%   Vin             - Scaling coefficients at J0, or j-1 level.
%   ht              - MODWT avelet filter coefficients.
%   gt              - MODWT Scaling filter coefficients.
%   j               - Level of decomposition.
%
% OUTPUTS
%   Vout            - MODWT scaling coefficients (residuals) for jth level.
%
% DESCRIPTION
%   modwtj is a Mex-Function written in C, which implements the Pyramid Alogrithm
%   of the MODWT for the jth level.  It is usually used as an internal function
%   called by imodwt or imodwt_mra.
%
%   To compile, type:  mex modwtj.c
%
% EXAMPLE
%   Vout = imodwtj(Wt_j, Vin, ht, gt, j);
%
% ALGORITHM
%
%
% REFERENCES
%   Percival, D. B. and A. T. Walden (2000) Wavelet Methods for
%   Time Series Analysis. Cambridge: Cambridge University Press.
%
% SEE ALSO
%   imodwt, imodwt_mra
%

% AUTHOR
%   Charlie Cornish
%   Brandon Whitcher
%
% CREATION DATE
%   2003-05-01
%
% COPYRIGHT
%
%
% CREDITS
%   Based on the original function (imodwt.c) by Brandon Whitcher.
%
% REVISION
%   $Revision: 612 $
%
%***

%   $Id: imodwtj.m 612 2005-10-28 21:42:24Z ccornish $