text:
import numpy as np
from lightningtrace.transformations import world_to_pixel_coords

def seq(start, stop, step=1):
    """Generate a list of values between start and stop every step
    :param start: The starting value
    :param stop: The ending values
    :param step: The step size
    :return: List of steps
    """
    n = int(round((stop - start) / float(step)))
    if n > 1:
        return [start + step * i for i in range(n + 1)]
    else:
        return []

def subset_raster(rast, band=1, bbox=None, logger=None):
    """
    :param rast: The rasterio raster object
    :param band: The band number you want to contour. Default: 1
    :param bbox: The bounding box in which to generate contours.
    :param logger: The logger object to use for this tool
    :return: A dict with the keys 'raster', 'array', 'affine', 'min', and 'max'. Raster is the original rasterio object,
    array is the numpy array, affine is the transformation for the bbox, min/max are the min/max values within the bbox.
    """
    # Affine transformations between raster and world coordinates.
    # See https://github.com/sgillies/affine
    # See https://github.com/mapbox/rasterio/blob/master/docs/windowed-rw.rst
    a = rast.affine      # Convert from pixel coordinates to world coordinates
    reverse_affine = ~a  # Convert from world coordinates to pixel coordinates

    # Copy the metadata
    kwargs = rast.meta.copy()

    # Read the band
    if bbox is not None:
        bbox = list(bbox)
        if len(bbox) != 4:
            logger.error('BBOX is not of length 4. Should be (xmin, ymin, xmax, ymax)')
            raise ValueError('BBOX is not of length 4. Should be (xmin, ymin, xmax, ymax)')

        # Restrict to the extent of the original raster if our requested
        # bbox is larger than the raster extent
        min_x = bbox[0]
        min_y = bbox[1]
        max_x = bbox[2]
        max_y = bbox[3]
        if min_x < rast.bounds[0]:
            min_x = rast.bounds[0]
        if min_y < rast.bounds[1]:
            min_y = rast.bounds[1]
        if max_x > rast.bounds[2]:
            max_x = rast.bounds[2]
        if max_y > rast.bounds[3]:
            max_y = rast.bounds[3]
        bbox = (min_x, min_y, max_x, max_y)

        # Convert the bounding box (world coordinates) to pixel coordinates
        # window = ((row_start, row_stop), (col_start, col_stop))
        window_bl = world_to_pixel_coords(rast.affine, [(bbox[0], bbox[1]),])
        window_tr = world_to_pixel_coords(rast.affine, [(bbox[2], bbox[3]),])

        window_rows = [int(window_bl[0, 1]), int(window_tr[0, 1])]
        window_cols = [int(window_bl[0, 0]), int(window_tr[0, 0])]

        window = (
          (min(window_rows), max(window_rows)),
          (min(window_cols), max(window_cols)))

        # print('')
        # print(window[0])
        # print(window[1])

        kwargs.update({
            'height': abs(window[0][1] - window[0][0]),
            'width': abs(window[1][1] - window[1][0]),
            'affine': rast.window_transform(window)
        })

    else:
        window = None

    # Read the data but only the window we set
    rast_band = rast.read(band, window=window, masked=True)
    rast_a = kwargs['affine']
    return {
        'crs': rast.crs,
        'array': rast_band,
        'affine': rast_a,
        'min': rast_band.min(),
        'max': rast_band.max()
    }


text:
package com.evolveum.midpoint.prism.impl.schema;

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

import javax.xml.namespace.QName;

import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.sun.xml.xsom.XSAnnotation;
import com.sun.xml.xsom.XSType;

/**
 * Class to be used by schema processor but also by SchemaDefinitionFactory subclasses.
 *
 * @author Radovan Semancik
 *
 */
public class SchemaProcessorUtil {

    public static boolean hasAnnotation(XSType xsType, QName annotationElementName) {
        if (xsType.getName() == null) {
            return false;
        }
        Element annotationElement = getAnnotationElement(xsType.getAnnotation(), annotationElementName);
        if (annotationElement != null) {
            return true;
        }
        if (xsType.getBaseType() != null && !xsType.getBaseType().equals(xsType)) {
            return hasAnnotation(xsType.getBaseType(), annotationElementName);
        }
        return false;
    }

    public static Element getAnnotationElement(XSAnnotation annotation, QName qname) {
        if (annotation == null) {
            return null;
        }
        List<Element> elements = getAnnotationElements(annotation, qname);
        if (elements.isEmpty()) {
            return null;
        }
        return elements.get(0);
    }

    @NotNull
    public static List<Element> getAnnotationElements(XSAnnotation annotation, QName qname) {
        List<Element> elements = new ArrayList<>();
        if (annotation == null) {
            return elements;
        }

        Element xsdAnnotation = (Element) annotation.getAnnotation();
        NodeList list = xsdAnnotation.getElementsByTagNameNS(qname.getNamespaceURI(), qname.getLocalPart());
        if (list != null && list.getLength() > 0) {
            for (int i = 0; i < list.getLength(); i++) {
                elements.add((Element) list.item(i));
            }
        }

        return elements;
    }

    public static QName getAnnotationQName(XSAnnotation annotation, QName qname) {
        Element element = getAnnotationElement(annotation, qname);
        if (element == null) {
            return null;
        }
        return DOMUtil.getQNameValue(element);
    }

    /**
     * Parses "marker" boolean annotation. This means:
     * no element: false
     * empty element: true
     * non-empty element: parse element content as boolean
     */
    public static Boolean getAnnotationBooleanMarker(XSAnnotation annotation, QName qname) throws SchemaException {
        Element element = getAnnotationElement(annotation, qname);
        if (element == null) {
            return null;
        }
        String textContent = element.getTextContent();
        if (textContent == null || textContent.isEmpty()) {
            return true;
        }
        return XmlTypeConverter.toJavaValue(element, Boolean.class);
    }

    public static <T> T getAnnotationConverted(XSAnnotation annotation, QName qname, Class<T> type) throws SchemaException {
        Element element = getAnnotationElement(annotation, qname);
        if (element == null) {
            return null;
        }
        String textContent = element.getTextContent();
        if (textContent == null || textContent.isEmpty()) {
            return null;
        }
        return XmlTypeConverter.toJavaValue(element, type);
    }

    public static Boolean getAnnotationBoolean(XSAnnotation annotation, QName qname) throws SchemaException {
        return getAnnotationConverted(annotation, qname, Boolean.class);
    }

    public static Integer getAnnotationInteger(XSAnnotation annotation, QName qname) throws SchemaException {
        return getAnnotationConverted(annotation, qname, Integer.class);
    }

    public static String dumpAnnotation(XSAnnotation annotation) {
        if (annotation == null) {
            return null;
        }
        Element xsdAnnotation = (Element) annotation.getAnnotation();
        if (xsdAnnotation == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Element element : DOMUtil.listChildElements(xsdAnnotation)) {
            sb.append(element.getLocalName()).append(", ");
        }
        return sb.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
// Copyright by Michael Zeilfelder

/** Example 030 Profiling

Profiling is used to get runtime information about code code.

There exist several independent profiling tools.
Examples for free profilers are "gprof" for the GNU toolchain and "very sleepy"
from codersnotes for Windows. Proprietary tools are for example "VTune" from
Intel or "AMD APP Profiler". Those tools work by sampling the running
application regularly to get statistic information about the called functions.
The way to use them is to compile your application with special flags
to include profiling information (some also work with debug information). They
also might allow to profile only certain parts of the code, although
most can't do that. The sampling is usually rather time-consuming which means
the application will be very slow when collecting the profiling data. It's often
useful to start with one of those tools to get an overview over the bottlenecks
in your application. Those tools have the advantage that they don't need any
modifications inside the code.

Once you need to dig deeper the Irrlicht profiler can help you. It works nearly
like a stopwatch. You add start/stop blocks into the parts of your code which
you need to check and the Irrlicht profiler will give you then the exact times
of execution for those parts. And unlike general profiler tools you don't just
get average information about the run-time but also worst-cases. Which tends
to be information you really for a stable framerate. Also the Irrlicht profiler
has a low overhead and affects only the areas which you want to time. So you
can profile applications with nearly original speed.

Irrlicht itself has such profiling information, which is useful to figure out
where the runtime inside the engine is spend. To get that profiling data you
need to recompile Irrlicht with _IRR_COMPILE_WITH_PROFILING_ enabled as
collecting profiling information is disabled by default for speed reasons.
*/

/*
	It's usually a good idea to wrap all your profile code with a define.
	That way you don't have to worry too much about the runtime profiling
	itself takes. You can remove the profiling code completely when you release
	the software by removing a single define.Or sometimes you might want to
	have several such defines for different areas of your application code.
*/
#define ENABLE_MY_PROFILE	// comment out to remove the profiling code
#ifdef ENABLE_MY_PROFILE
	// calls code X
	#define MY_PROFILE(X) X
#else
	// removes the code for X in the pre-processor
	#define MY_PROFILE(X)
#endif // IRR_PROFILE

#include <irrlicht.h>
#include "driverChoice.h"

using namespace ue;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

/*
	We have the choice between working with fixed and with automatic profiling id's.
	Here are some fixed ID's we will be using.
*/
enum EProfiles
{
	EP_APP_TIME_ONCE,
	EP_APP_TIME_UPDATED,
	EP_SCOPE1,
	EP_SCOPE2,
	EP_DRAW_SCENE
};

// For our example scenes
enum EScenes
{
	ES_NONE,	// no scene set
    ES_CUBE,
    ES_QUAKE_MAP,
    ES_DWARVES,

    ES_COUNT	// counting how many scenes we have
};

/*
    Controlling the profiling display is application specific behavior.
	We use function keys in our case and play around with all the parameters.
	In real applications you will likely only need something to make the
	profiling-display visible/invisible and switch pages while the parameters
	can be set to fixed values.
*/
class MyEventReceiver : public IEventReceiver
{
public:
	// constructor
	MyEventReceiver(ISceneManager * smgr) : GuiProfiler(0), IncludeOverview(true), IgnoreUncalled(false), ActiveScene(ES_NONE), SceneManager(smgr) {}

	virtual bool OnEvent(const SEvent& event)
	{
		if (event.EventType == EET_KEY_INPUT_EVENT)
		{
			if ( event.KeyInput.PressedDown )
			{
				/*
					Catching keys to control the profiling display and the profiler itself
				*/
				switch ( event.KeyInput.Key )
				{
					case KEY_F1:
						GuiProfiler->setVisible( !GuiProfiler->isVisible() );
					break;
					case KEY_F2:
						GuiProfiler->nextPage(IncludeOverview);
					break;
					case KEY_F3:
						GuiProfiler->previousPage(IncludeOverview);
					break;
					case KEY_F4:
						GuiProfiler->firstPage(IncludeOverview);
					break;
					case KEY_F5:
						IncludeOverview = !IncludeOverview;
						GuiProfiler->firstPage(IncludeOverview);	// not strictly needed, but otherwise the update won't update
					break;
					case KEY_F6:
						/*
							You can set more filters. This one filters out profile data which was never called.
						*/
						IgnoreUncalled = !IgnoreUncalled;
						GuiProfiler->setFilters(IgnoreUncalled ? 1 : 0, 0, 0.f, 0);
					break;
					case KEY_F7:
						GuiProfiler->setShowGroupsTogether( !GuiProfiler->getShowGroupsTogether() );
					break;
					case KEY_F8:
						NextScene();
					break;
					case KEY_F9:
					{
						u32 index = 0;
						if ( getProfiler().findGroupIndex(index, L"grp runtime") )
						{
							getProfiler().resetGroup(index);
						}
					}
					break;
					case KEY_F10:
					{
						u32 index = 0;
						if ( getProfiler().findDataIndex(index, L"scope 3") )
						{
							getProfiler().resetDataByIndex(index);
						}
					}
					break;
					case KEY_F11:
						getProfiler().resetAll();
					break;
					case KEY_KEY_F:
						GuiProfiler->setFrozen(!GuiProfiler->getFrozen());
					break;
					default:
					break;
				}
			}
		}

		return false;
	}

	/*
		Some example scenes so we have something to profile
	*/
	void NextScene()
	{
		SceneManager->clear();
		ActiveScene = (ActiveScene+1) % ES_COUNT;
		if ( ActiveScene == 0 )
			ActiveScene = ActiveScene+1;

		switch ( ActiveScene )
		{
			case ES_CUBE:
			{
				/*
					Simple scene with cube and light.
				*/
				MY_PROFILE(CProfileScope p(L"cube", L"grp switch scene");)

				SceneManager->addCameraSceneNode (0, core::vector3df(0, 0, 0),
											core::vector3df(0, 0, 100),
											-1);

				SceneManager->addCubeSceneNode (30.0f, 0, -1,
										core::vector3df(0, 20, 100),
										core::vector3df(45, 45, 45),
										core::vector3df(1.0f, 1.0f, 1.0f));

				SceneManager->addLightSceneNode(0, core::vector3df(0, 0, 0),
										video::SColorf(1.0f, 1.0f, 1.0f),
										100.0f);
			}
			break;
			case ES_QUAKE_MAP:
			{
				/*
					Our typical Irrlicht example quake map.
				*/
				MY_PROFILE(CProfileScope p(L"quake map", L"grp switch scene");)

				scene::IAnimatedMesh* mesh = SceneManager->getMesh("20kdm2.bsp");
				scene::ISceneNode* node = 0;

				if (mesh)
					node = SceneManager->addOctreeSceneNode(mesh->getMesh(0), 0, -1, 1024);
				if (node)
					node->setPosition(core::vector3df(-1300,-144,-1249));
				SceneManager->addCameraSceneNodeFPS();
			}
			break;
			case ES_DWARVES:
			{
				/*
					Stress-test Irrlicht a little bit by creating many objects.
				*/
				MY_PROFILE(CProfileScope p(L"dwarfes", L"grp switch scene");)

				scene::IAnimatedMesh* aniMesh = SceneManager->getMesh( "../media/dwarf.x" );
				if (aniMesh)
				{
					scene::IMesh * mesh = aniMesh->getMesh (0);
					if ( !mesh )
						break;

					/*
						You can never have too many dwarves. So let's make some.
					*/
					const int nodesX = 30;
					const int nodesY = 5;
					const int nodesZ = 30;

					aabbox3df bbox = mesh->getBoundingBox();
					vector3df extent = bbox.getExtent();
					const f32 GAP = 10.f;
					f32 halfSizeX = 0.5f * (nodesX*extent.X + GAP*(nodesX-1));
					f32 halfSizeY = 0.5f * (nodesY*extent.Y + GAP*(nodesY-1));
					f32 halfSizeZ = 0.5f * (nodesZ*extent.Z + GAP*(nodesZ-1));

					for ( int x = 0; x < nodesX; ++x )
					{
						ue::f32 gapX = x > 0 ? (x-1)*GAP : 0.f;
						ue::f32 posX = -halfSizeX + x*extent.X + gapX;
						for ( int y = 0; y < nodesY; ++y )
						{
							ue::f32 gapY = y > 0 ? (y-1)*GAP : 0.f;
							ue::f32 posY = -halfSizeY + y*extent.Y + gapY;
							for ( int z=0; z < nodesZ; ++z )
							{
								ue::f32 gapZ = z > 0 ? (z-1)*GAP : 0.f;
								ue::f32 posZ = -halfSizeZ + z*extent.Z + gapZ;
								scene::IAnimatedMeshSceneNode * node = SceneManager->addAnimatedMeshSceneNode(aniMesh, NULL, -1, vector3df(posX, posY, posZ) );
								node->setMaterialFlag(video::EMF_LIGHTING, false);
							}
						}
					}

					ue::scene::ICameraSceneNode * camera = SceneManager->addCameraSceneNodeFPS(0, 20.f, 0.1f );
					camera->updateAbsolutePosition();
					camera->setTarget( vector3df(0,0,0) );
					camera->updateAbsolutePosition();
					camera->setPosition(ue::core::vector3df(halfSizeX+extent.X, halfSizeY+extent.Y, halfSizeZ+extent.Z));
					camera->updateAbsolutePosition();
				}
			}
			break;
		}
	}

	IGUIProfiler * GuiProfiler;
	bool IncludeOverview;
	bool IgnoreUncalled;
	u32 ActiveScene;
	scene::ISceneManager* SceneManager;
};

void recursive(int recursion)
{
	/*
		As the profiler uses internally counters for start stop and only
		takes profile data when that counter is zero we count all recursions
		as a single call.
		If you want to profile each call on it's own you have to use explicit start/stop calls and
		stop the profile id right before the recursive call.
	*/
	MY_PROFILE(CProfileScope p3(L"recursive", L"grp runtime");)
	if (recursion > 0 )
		recursive(recursion-1);
}

int main()
{
	/*
		Setup, nothing special here.
	*/
	video::E_DRIVER_TYPE driverType=driverChoiceConsole();
	if (driverType==video::EDT_COUNT)
		return 1;

	/*
		Profiler is independent of the device - so we can time the device setup
	*/
	MY_PROFILE(s32 pDev = getProfiler().add(L"createDevice", L"grp runtime");)
	MY_PROFILE(getProfiler().start(pDev);)

	IrrlichtDevice * device = createDevice(driverType, core::dimension2d<u32>(640, 480));
	if (device == 0)
	{
		/*
			When working with start/stop you should add a stop to all exit paths.
			Although in this case it wouldn't matter as we don't do anything with it when we quit here.
		*/
		MY_PROFILE(getProfiler().stop(pDev);)
		return 1; // could not create selected driver.
	}
	MY_PROFILE(getProfiler().stop(pDev);)

	video::IVideoDriver* driver = device->getVideoDriver();
	IGUIEnvironment* env = device->getGUIEnvironment();
	scene::ISceneManager* smgr = device->getSceneManager();

	/*
		A map we use for one of our test-scenes.
	*/
	device->getFileSystem()->addFileArchive("../media/map-20kdm2.pk3");

	MyEventReceiver receiver(smgr);
	device->setEventReceiver(&receiver);
	receiver.NextScene();

	/*
		Show some info about the controls used in this example
	*/
	IGUIStaticText * staticText = env->addStaticText(
			L"<F1>  to show/hide the profiling display\n"
			L"<F2>  to show the next page\n"
			L"<F3>  to show the previous page\n"
			L"<F4>  to show the first page\n"
			L"<F5>  to flip between including the group overview\n"
			L"<F6>  to flip between ignoring and showing uncalled data\n"
			L"<F7>  to flip between showing 1 group per page or all together\n"
			L"<F8>  to change our scene\n"
			L"<F9>  to reset the \"grp runtime\" data\n"
			L"<F10> to reset the scope 3 data\n"
			L"<F11> to reset all data\n"
			L"<f>   to freeze/unfreeze the display\n"
			, recti(10,10, 250, 140), true, true, 0, -1, true);
	staticText->setWordWrap(false);

	/*
		IGUIProfiler is can be used to show active profiling data at runtime.
	*/
	receiver.GuiProfiler = env->addProfilerDisplay(core::recti(40, 140, 600, 470));
	receiver.GuiProfiler->setDrawBackground(true);

	/*
		Get a monospaced font - it's nicer when working with rows of numbers.
	 */
	IGUIFont* font = env->getFont("../media/fontcourier.bmp");
	if (font)
		receiver.GuiProfiler->setOverrideFont(font);

	/*
		Adding ID's has to be done before the start/stop calls.
		This allows start/stop to be really fast and we still have nice information like
		names and groups.
		Groups are created automatically each time an ID with a new group-name is added.
		Groups exist to sort the display data in a nicer way.
	*/
	MY_PROFILE(
		getProfiler().add(EP_APP_TIME_ONCE, L"full time", L"grp runtime");
		getProfiler().add(EP_APP_TIME_UPDATED, L"full time updated", L"grp runtime");
		getProfiler().add(EP_SCOPE1, L"scope 1", L"grp runtime");
		getProfiler().add(EP_DRAW_SCENE, L"draw scene", L"grp runtime");
	)

    /*
		Two timers which run the whole time. One will be continuously updated the other won't.
    */
	MY_PROFILE(getProfiler().start(EP_APP_TIME_ONCE);)
	MY_PROFILE(getProfiler().start(EP_APP_TIME_UPDATED);)

	s32 lastFPS = -1;
	while(device->run() && driver)
	{
		if (device->isWindowActive())
		{
			/*
				For comparison show the FPS in the title bar
			*/
			s32 fps = driver->getFPS();
			if (lastFPS != fps)
			{
				core::stringw str = L"FPS: ";
				str += fps;
				device->setWindowCaption(str.c_str());
				lastFPS = fps;
			}

			/*
				Times are only updated on stop() calls. So if we want a long-running timer
				to update we have to stop() and start() it in between.
				Note that this will also update the call-counter and is rarely needed.
			*/
			MY_PROFILE(getProfiler().stop(EP_APP_TIME_UPDATED);)
			MY_PROFILE(getProfiler().start(EP_APP_TIME_UPDATED);)

			/*
				The following CProfileScope's will all do the same thing:
				they measure the time this loop takes. They call start()
				when the object is created and call stop() when it
				is destroyed.

				The first one creates an ID on it's first call and will
				do constant string-comparisons for the name. It's
				the slowest, but most comfortable solution. Use it when you
				just need to run a quick check without the hassle of setting
				up id's.
			*/
			MY_PROFILE(CProfileScope p3(L"scope 3", L"grp runtime");)

			/*
				Second CProfileScope solution will create a data block on first
				call. So it's a little bit slower on the first run. But usually
				that's hardly noticeable.
			*/
			MY_PROFILE(CProfileScope p2(EP_SCOPE2, L"scope 2", L"grp runtime");)

			/*
				Last CProfileScope solution is the fastest one. But you must add
				the id before you can use it like that.
			*/
			MY_PROFILE(CProfileScope p1(EP_SCOPE1));

			/*
				Call a recursive function to show how profiler only counts it once.
			*/
			recursive(5);

			driver->beginScene(true, true, SColor(0,200,200,200));

			/*
				If you want to profile only some lines and not a complete scope
				then you have to work with start() and stop() calls.
			*/
			MY_PROFILE(getProfiler().start(EP_DRAW_SCENE);)
			smgr->drawAll();
			MY_PROFILE(getProfiler().stop(EP_DRAW_SCENE);)

			/*
				If it doesn't matter if the profiler takes some time you can also
				be lazy and create id's automatically on the spot:
			*/
			MY_PROFILE(s32 pEnv = getProfiler().add(L"draw env", L"grp runtime");)
			MY_PROFILE(getProfiler().start(pEnv);)
			env->drawAll();
			MY_PROFILE(getProfiler().stop(pEnv);)

			driver->endScene();
		}
	}

	/*
		Shutdown.
	*/
	device->drop();

	/*
		The profiler is independent of an device - so we can still work with it.
	*/

	MY_PROFILE(getProfiler().stop(EP_APP_TIME_UPDATED));
	MY_PROFILE(getProfiler().stop(EP_APP_TIME_ONCE));

	/*
		Print a complete overview of the profiling data to the console.
	*/
	MY_PROFILE(core::stringw output);
	MY_PROFILE(getProfiler().printAll(output));
	MY_PROFILE(printf("%s", core::stringc(output).c_str() ));

	return 0;
}

/*
**/


text:
https://www.udemy.com/ultimate-angular-2/

2016.12.04

https://github.com/xgqfrms-GitHub/express

https://github.com/xgqfrms-GitHub/socket.io

# install -g

```sh
$ npm i -g angular-cli
```
# ng new Angular2-App
# https://github.com/angular/angular-cli

```sh
$ npm i -g typescript
```
# tsc

```sh
$ npm i -g gulp
$ npm i -g browser-sync
$ npm i -g sass
$ npm i -g bootstrap
```

## install -S
```sh
$ npm i -S express
$ npm i -S sockit.io
$ npm i -S async
$ npm i -S sass
$ npm i -S bootstrap
$ npm i -S angular-material
```

## install -D
```sh
$ npm i -D browser-sync

```

## no need any more

```sh
$ npm i -g angular-material
```
# 1.x
# https://material.angularjs.org/latest/
# https://www.npmjs.com/package/angular-material

```sh
$ npm install -g angular-cli
$ npm i -S @angular/material

```
# 2.x
# https://github.com/angular/material2/blob/master/GETTING_STARTED.md
# https://github.com/angular/material2
# https://material.angular.io/


text:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class ScrabbleScoreTest {

    private String input;
    private int expectedOutput;

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {"", 0},
                {" \t\n", 0},
                {null, 0},
                {"a", 1},
                {"f", 4},
                {"street", 6},
                {"quirky", 22},
                {"MULTIBILLIONAIRE", 20},
                {"alacrity", 13},
        });
    }

    public ScrabbleScoreTest(String input, int expectedOutput) {
        this.input = input;
        this.expectedOutput = expectedOutput;
    }

    @Test
    public void test() {
        Scrabble scrabble = new Scrabble(input);

        assertEquals(expectedOutput, scrabble.getScore());
    }
}


text:
import React from 'react'
import { Link, graphql } from 'gatsby'
import styled from 'styled-components'

import SEO from '../components/seo'
import SyntaxHighlighter from '../components/syntax-highlighter'

const Container = styled.div`
  margin: 3rem auto;
  max-width: 800px;
`

const PageTitle = styled.h2`
  a {
    color: black;
    font-family: 'Fira Code';
    text-decoration: underline;
  }
`

class BlogPostTemplate extends React.Component {
  render() {
    const post = this.props.data.markdownRemark
    const siteTitle = this.props.data.site.siteMetadata.title
    const { previous, next } = this.props.pageContext

    return (
      <Container>
        <SyntaxHighlighter themeName="Atelier Sulphurpool Light" />
        <SEO
          title={post.frontmatter.title}
          description={post.frontmatter.description || post.excerpt}
        />
        <PageTitle>
          <Link to="/">{siteTitle}</Link>
        </PageTitle>

{post.frontmatter.title}

          <p
            style={{
              display: `block`,
            }}
          >
            {post.frontmatter.date}

          <ul
            role="navigation"
            style={{
              display: `flex`,
              flexWrap: `wrap`,
              justifyContent: `space-between`,
              listStyle: `none`,
              padding: 0,
            }}
          >

              {previous && (
                <Link to={previous.fields.slug} rel="prev">
                  ← {previous.frontmatter.title}
                </Link>
              )}

              {next && (
                <Link to={next.fields.slug} rel="next">
                  {next.frontmatter.title} →
                </Link>
              )}

      </Container>
    )
  }
}

export default BlogPostTemplate

export const pageQuery = graphql`
  query BlogPostBySlug($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      excerpt(pruneLength: 160)
      html
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
        description
      }
    }
  }
`


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

import com.hatapp.comandas.entity.Pedidos;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author ivan
 */
@Stateless
public class PedidosFacade extends AbstractFacade<Pedidos> {
    @PersistenceContext(unitName = "SistemaComandasPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public PedidosFacade() {
        super(Pedidos.class);
    }

}


text:
This sample serves all endpoints in the routes/ folder, and returns application/json results parsed along with CJSON.

**N.B.: You need to have a NodeMCU built with the CJSON module for this sample to work.**

## Procedure
Upload the following files to your NodeMCU:

1. Espress base files
 * espress.lc
 * espress_init.lc
 * http_default_handler.lc
 * http_getondata.lc
 * http_prototypes.lc
 * http_request.lc
 * http_request_buffer.lc
 * http_request_processor.lc
 * http_response.lc
 * http_response_send.lc
 * http_response_sendfile.lc
 * plugins/routes_auto.lc => routes_auto.lc

2. Relevant Espress status-codes
 * status-codes/http-200 => http-200
 * status-codes/http-401 => http-401
 * status-codes/http-404 => http-404
 * status-codes/http-405 => http-405
 * status-codes/http-500 => http-500

3. Sample files
 * **init.lua**
 * server.lua => server.lc
 * routes/askme.post.lua  => routes/askme.post.lc
 * routes/hello.get.lua  => routes/hello.get.lc

Replace the wifi settings with your own in **init.lua**

Access both resources like this:

[GET] http://IP/api/hello
[POST] http://IP/api/askme  with the following JSON body:
```json
{
  "question": "How are you?"
}
```


text:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.PredictionMode;
import java.lang.reflect.Method;
import java.util.List;
/*$PackageName*/import __PackageName__.*;/*PackageName$*/

public class Main {
    public static void main(String[] args) {
        try {
            String fileName = "../../Text";

            if (args.length > 0) {
                fileName = args[0];
            }

            CharStream codeStream = CharStreams.fromFileName(fileName);
            __TemplateLexerName__ lexer = new __TemplateLexerName__(codeStream);
            List<? extends Token> tokens = lexer.getAllTokens();

/*$ParserPart*/
            String rootRule = null;
            String mode = "ll";

            if (args.length > 1) {
                rootRule = args[1];
                if (args.length > 2) {
                    // TODO: process OnlyTokenize parameter
                    if (args.length > 3) {
                        mode = args[3].toLowerCase();
                    }
                }
            }

            ListTokenSource tokensSource = new ListTokenSource(tokens);
            CommonTokenStream tokensStream = new CommonTokenStream(tokensSource);
            __TemplateParserName__ parser = new __TemplateParserName__(tokensStream);
            PredictionMode predictionMode = mode.equals("sll")
                ? PredictionMode.SLL
                : mode.equals("ll")
                    ? PredictionMode.LL
                    : PredictionMode.LL_EXACT_AMBIG_DETECTION;
            parser.getInterpreter().setPredictionMode(predictionMode);
            String ruleName = rootRule == null ? __TemplateParserName__.ruleNames[0] : rootRule;
            Method parseMethod = __TemplateParserName__.class.getDeclaredMethod(ruleName);
            ParserRuleContext ast = (ParserRuleContext)parseMethod.invoke(parser);
            String stringTree = ast.toStringTree(parser);
            System.out.print("Tree " + stringTree);
/*ParserPart$*/
        }
        catch (Exception e) {
        }
    }
}


text:
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L

#endregion

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: ClearCanvas.Common.Plugin]

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AIM.Annotaion.View.WinForm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Northwestern University")]
[assembly: AssemblyProduct("AIM.Annotaion.View.WinForm")]
[assembly: AssemblyCopyright("Copyright © 2008-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("77e68f51-e5f5-4b53-a109-689af795cedc")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
package com.marakana.android.yamba;

import com.marakana.android.yamba.R;

import android.os.Bundle;

public class StatusActivity extends BaseActivity
//	implements OnSharedPreferenceChangeListener
	{
//	protected SharedPreferences prefs;
//	protected YambaClient yamba;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_activity_status);

//		prefs = PreferenceManager.getDefaultSharedPreferences(this);
//      prefs.registerOnSharedPreferenceChangeListener(this);
	}

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

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//	  switch (item.getItemId()) {
//	  case R.id.itemServiceStart:
//		    startService(new Intent(this, UpdaterService.class));
//		    break;
//	  case R.id.itemServiceStop:
//	    stopService(new Intent(this, UpdaterService.class));
//	    break;
//	  case R.id.itemPrefs:
//	    startActivity(new Intent(this, PrefsActivity.class));
//	  break;
//	  }
//
//	  return true;
//	}

//	@Override
//	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//        // invalidate yamba object
//        yamba = null;
//	}
//
//	public YambaClient getYambaClient() {
//		  if (yamba == null) {
//		    String username, password;
//		    username = prefs.getString("username", "student");
//		    password = prefs.getString("password", "password");
//
//		    // Connect
//		    yamba = new YambaClient(username, password);
//		  }
//		  return yamba;
//		}
}


text:
var myCheck : boolean = true;
var BG : GameObject;

function OnMouseDown () {
	if(myCheck == true){
	BG.SetActiveRecursively(false);
	myCheck = false;
	return myCheck;}
	if(myCheck == false){
	BG.SetActiveRecursively(true);
	myCheck = true; }
	return myCheck;}


text:
"""
The project pages map for basic_i18n
"""
from optimus.pages.views.base import PageViewBase

# from optimus.conf import settings
"""
Page objects
"""

class Index(PageViewBase):
    """
    Default index page
    """

    title = "My project"
    template_name = "index.html"
    destination = "index_{language_code}.html"

# Enabled pages to build
PAGES = [
    Index(destination="index.html"),
    Index(lang="fr_FR"),
]


text:
require 'httpauth'

module OAuth2::Provider::Rack
  class AccessTokenHandler
    attr_reader :app, :env, :request

    def initialize(app, env)
      @app = app
      @env = env
      @request = env['oauth2']
    end

    def process
      if request.post?
        block_unsupported_grant_types || handle_basic_auth_header || block_invalid_clients || handle_grant_type
      else
        Responses.only_supported 'POST'
      end
    end

    def handle_basic_auth_header
      with_required_params 'grant_type' do |grant_type|
        if grant_type == 'client_credentials' && request.env['HTTP_AUTHORIZATION'] =~ /^Basic/
          @env['oauth2'].params['client_id'], @env['oauth2'].params['client_secret'] = HTTPAuth::Basic.unpack_authorization(request.env['HTTP_AUTHORIZATION'])
          next
        end
      end
    end

    def handle_grant_type
      send grant_type_handler_method(request.params["grant_type"])
    end

    def handle_password_grant_type
      with_required_params 'username', 'password' do |username, password|
        if resource_owner = OAuth2::Provider.resource_owner_class.authenticate_with_username_and_password(username, password)
          token_response OAuth2::Provider.access_token_class.create!(
            :authorization => OAuth2::Provider.authorization_class.create!(:resource_owner => resource_owner, :client => oauth_client)
          )
        else
          Responses.json_error 'invalid_grant'
        end
      end
    end

    def handle_authorization_code_grant_type
      with_required_params 'code', 'redirect_uri' do |code, redirect_uri|
        if token = oauth_client.authorization_codes.claim(code, redirect_uri)
          token_response token
        else
          Responses.json_error 'invalid_grant'
        end
      end
    end

    def handle_refresh_token_grant_type
      with_required_params 'refresh_token' do |refresh_token|
        if token = oauth_client.access_tokens.refresh_with(refresh_token)
          token_response token
        else
          Responses.json_error 'invalid_grant'
        end
      end
    end

    def handle_client_credentials_grant_type
      token_response OAuth2::Provider.access_token_class.create!(
        :authorization => OAuth2::Provider.authorization_class.create!(:resource_owner => oauth_client, :client => oauth_client),
        :refresh_token => nil
      )
    end

    def with_required_params(*names, &block)
      missing_params = names - request.params.keys
      if missing_params.empty?
        yield *request.params.values_at(*names)
      else
        if missing_params.size == 1
          Responses.json_error 'invalid_request', :description => "missing '#{missing_params.join}' parameter"
        else
          describe_parameters = missing_params.map{|x| "'#{x}'"}.join(", ")
          Responses.json_error 'invalid_request', :description => "missing #{describe_parameters} parameters"
        end
      end
    end

    def token_response(token)
      json = token.as_json.tap do |json|
        json[:state] = request.params['state'] if request.params['state']
      end
      [200, {'Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate'}, [ActiveSupport::JSON.encode(json)]]
    end

    def block_unsupported_grant_types
      with_required_params 'grant_type' do |grant_type|
        unless respond_to?(grant_type_handler_method(grant_type), true)
          Responses.json_error 'unsupported_grant_type'
        end
      end
    end

    def block_invalid_clients
      with_required_params 'grant_type', 'client_id', 'client_secret' do |grant_type, client_id, client_secret|
        @oauth_client = OAuth2::Provider.client_class.find_by_oauth_identifier_and_oauth_secret(client_id, client_secret)
        if @oauth_client.nil?
          Responses.json_error 'invalid_client'
        elsif !@oauth_client.allow_grant_type?(grant_type)
          Responses.json_error 'unauthorized_client'
        end
      end
    end

    def oauth_client
      @oauth_client
    end

    def grant_type_handler_method(grant_type)
      "handle_#{grant_type}_grant_type"
    end
  end
end


text:
package svn

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"github.com/gonuts/iochan"
)

func path_exists(name string) bool {
	_, err := os.Stat(name)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func is_in_slice(elmt string, slice []string) bool {
	for _, v := range slice {
		if v == elmt {
			return true
		}
	}
	return false
}

// Repo models a git repository
type Repo struct {
	local_branches  []string // the list of local branches
	remote_branches []string // the list of remote branches
	tags            []string // the list of svn-tags
}

type Context struct {
	Repo Repo // Git repository we are working on

	Url string // SVN URL to work from

	Verbose       bool
	Metadata      bool   // include metadata in git logs (git-svn-id)
	NoMinimizeUrl bool   // accept URLs as-is without attempting to connect a higher level directory
	RootIsTrunk   bool   // use this if the root level of the repo is equivalent to the trunk and there are no tags or branches
	Rebase        bool   // instead of cloning a new project, rebase an existing one against SVN
	UserName      string // username for transports that needs it (http(s), svn)
	Trunk         string // subpath to trunk from repository URL
	Branches      string // subpath to branches from repository URL
	Tags          string // subpath to tags from repository URL
	Exclude       string // regular expression to filter paths when fetching
	Revision      string // start importing from SVN revision START_REV; optionally end at END_REV. e.g. START_REV:END_REV

	NoTrunk    bool   // do not import anything from trunk
	NoBranches bool   // do not import anything from branches
	NoTags     bool   // do not import anything from tags
	Authors    string // path to file containing svn-to-git authors mapping
}

func NewContext(svnurl string) *Context {
	ctx := &Context{
		Repo: Repo{
			local_branches:  []string{},
			remote_branches: []string{},
			tags:            []string{},
		},
		Url:           svnurl,
		Verbose:       true,
		Metadata:      false,
		NoMinimizeUrl: false,
		RootIsTrunk:   false,
		Rebase:        false,
		UserName:      "",
		Trunk:         "trunk",
		Branches:      "branches",
		Tags:          "tags",
		Exclude:       "",
		Revision:      "",
		NoTrunk:       false,
		NoBranches:    false,
		NoTags:        false,
		Authors:       os.ExpandEnv("$HOME/.config/go-svn2git/authors"),
	}
	if !path_exists(ctx.Authors) {
		ctx.Authors = ""
	}
	return ctx
}

func NewContextFrom(svnurl string,
	Verbose       bool,
	Metadata      bool,   // include metadata in git logs (git-svn-id)
	NoMinimizeUrl bool,   // accept URLs as-is without attempting to connect a higher level directory
	RootIsTrunk   bool,   // use this if the root level of the repo is equivalent to the trunk and there are no tags or branches
	Rebase        bool,   // instead of cloning a new project, rebase an existing one against SVN
	UserName      string, // username for transports that needs it (http(s), svn)
	Trunk         string, // subpath to trunk from repository URL
	Branches      string, // subpath to branches from repository URL
	Tags          string, // subpath to tags from repository URL
	Exclude       string, // regular expression to filter paths when fetching
	Revision      string, // start importing from SVN revision START_REV; optionally end at END_REV. e.g. START_REV:END_REV

	NoTrunk    bool,   // do not import anything from trunk
	NoBranches bool,   // do not import anything from branches
	NoTags     bool,   // do not import anything from tags
	Authors    string, // path to file containing svn-to-git authors mapping
) *Context {
	ctx := &Context{
		Repo: Repo{
			local_branches:  []string{},
			remote_branches: []string{},
			tags:            []string{},
		},
		Url:           svnurl,
		Verbose:       Verbose,
		Metadata:      Metadata,
		NoMinimizeUrl: NoMinimizeUrl,
		RootIsTrunk:   RootIsTrunk,
		Rebase:        Rebase,
		UserName:      UserName,
		Trunk:         Trunk,
		Branches:      Branches,
		Tags:          Tags,
		Exclude:       Exclude,
		Revision:      Revision,
		NoTrunk:       NoTrunk,
		NoBranches:    NoBranches,
		NoTags:        NoTags,
		Authors:       os.ExpandEnv(Authors),
	}
	if !path_exists(ctx.Authors) {
		ctx.Authors = ""
	}
	return ctx
}

func (ctx *Context) print_cmd(cmd *exec.Cmd) {
	if ctx.Verbose {
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
	}
}

func (ctx *Context) debug_cmd(cmd *exec.Cmd) {
	if ctx.Verbose {
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
}

func (ctx *Context) git_cmd(cmdargs ...string) []string {
	lines := []string{}
	cmd := exec.Command("git", cmdargs...)
	if ctx.Verbose {
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
	}
	out, err := cmd.CombinedOutput()
	if err != nil {
		// ignore error
		return lines
	}
	r := bufio.NewReader(bytes.NewBuffer(out))
	for line := range iochan.ReaderChan(r, "\n") {
		lines = append(lines, line)
	}
	return lines
}

func (ctx *Context) Run() error {
	var err error
	if ctx.Rebase {
		err = ctx.get_branches()
	} else {
		err = ctx.do_clone()
	}
	if err != nil {
		return err
	}

	err = ctx.fix_tags()
	if err != nil {
		return err
	}

	err = ctx.fix_branches()
	if err != nil {
		return err
	}

	err = ctx.fix_trunk()
	if err != nil {
		return err
	}

	err = ctx.optimize_repos()
	if err != nil {
		return err
	}

	return err
}

func (ctx *Context) get_branches() error {
	var err error = nil
	// get the list of local and remote branches
	// ignore console color codes
	cmd := exec.Command("git", "branch", "-l", "--no-color")
	if ctx.Verbose {
		fmt.Printf(":: --> building list of [local branches]...\n")
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
	}
	out, err := cmd.CombinedOutput()
	if err != nil {
		return err
	}
	lines := bufio.NewReader(bytes.NewBuffer(out))
	for line := range iochan.ReaderChan(lines, "\n") {
		if ctx.Verbose {
			fmt.Printf("   %q\n", line)
		}
		if strings.HasPrefix(line, "*") {
			line = strings.Replace(line, "*", "", 1)
		}
		line = strings.Trim(line, " \r\n")
		if ctx.Verbose {
			fmt.Printf("-> %q\n", line)
		}
		ctx.Repo.local_branches = append(ctx.Repo.local_branches, line)
	}

	// remote branches...
	cmd = exec.Command("git", "branch", "-r", "--no-color")
	if ctx.Verbose {
		fmt.Printf(":: --> building list of [remote branches]...\n")
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
	}
	out, err = cmd.CombinedOutput()
	if err != nil {
		return err
	}
	lines = bufio.NewReader(bytes.NewBuffer(out))
	for {
		line, err1 := lines.ReadString('\n')
		if err1 != nil {
			if err1 != io.EOF {
				err = err1
			}
			break
		}
		if ctx.Verbose {
			fmt.Printf("   %q\n", line)
		}
		if strings.HasPrefix(line, "*") {
			line = strings.Replace(line, "*", "", 1)
		}
		line = strings.Trim(line, " \r\n")
		if ctx.Verbose {
			fmt.Printf("-> %q\n", line)
		}
		ctx.Repo.remote_branches = append(ctx.Repo.remote_branches, line)
	}

	// tags are remote branches that start with "svn/tags/"
	if ctx.Verbose {
		fmt.Printf(":: --> building list of [svn-tags]...\n")
	}
	for _, branch := range ctx.Repo.remote_branches {
		if strings.HasPrefix(branch, "svn/tags/") {
			tag := branch //branch[len("svn/tags/"):]
			if ctx.Verbose {
				fmt.Printf(":: adding tag %q...\n", tag)
			}
			ctx.Repo.tags = append(ctx.Repo.tags, tag)

		}
	}
	return err
}

func (ctx *Context) do_clone() error {
	var err error = nil

	cmdargs := []string{
		"svn", "init", "--prefix=svn/",
	}
	var cmd *exec.Cmd = nil
	if ctx.RootIsTrunk {
		// non-standard repository layout.
		// The repository root is effectively 'trunk.'
		if ctx.UserName != "" {
			cmdargs = append(cmdargs, fmt.Sprintf("--username=%s", ctx.UserName))
		}
		if ctx.Metadata {
			cmdargs = append(cmdargs, "--no-metadata")
		}
		if ctx.NoMinimizeUrl {
			cmdargs = append(cmdargs, "--no-minimize-url")
		}
		cmdargs = append(cmdargs, fmt.Sprintf("--trunk=%s", ctx.Url))
	} else {
		// add each component to the command that was passed as an argument
		if ctx.UserName != "" {
			cmdargs = append(cmdargs, fmt.Sprintf("--username=%s", ctx.UserName))
		}
		if ctx.Metadata {
			cmdargs = append(cmdargs, "--no-metadata")
		}
		if ctx.NoMinimizeUrl {
			cmdargs = append(cmdargs, "--no-minimize-url")
		}
		if ctx.Trunk != "" {
			cmdargs = append(cmdargs, fmt.Sprintf("--trunk=%s", ctx.Trunk))
		}
		if ctx.Tags != "" {
			cmdargs = append(cmdargs, fmt.Sprintf("--tags=%s", ctx.Tags))
		}
		if ctx.Branches != "" {
			cmdargs = append(cmdargs, fmt.Sprintf("--branches=%s", ctx.Branches))
		}
		cmdargs = append(cmdargs, ctx.Url)
	}
	cmd = exec.Command("git", cmdargs...)
	if ctx.Verbose {
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	err = cmd.Run()
	if err != nil {
		return err
	}

	if ctx.Authors != "" {
		cmd := exec.Command("git", "config", "--local", "svn.authorsfile",
			ctx.Authors)

		if ctx.Verbose {
			fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
		}
		err = cmd.Run()
		if err != nil {
			return err
		}

	} else {
		if ctx.Verbose {
			fmt.Printf("no authors file...\n")
		}
	}

	cmdargs = []string{"svn", "fetch"}
	if ctx.Revision != "" {
		rev := strings.Split(ctx.Revision, ":")
		switch len(rev) {
		case 0:
			panic("the impossible happened!")
		case 1:
			if rev[0] == "" {
				return fmt.Errorf("invalid empty argument to '-revision' flag")
			}
			rev = []string{rev[0], "HEAD"}
		case 2:
			if rev[0] == "" {
				rev[0] = "0"
			}
			if rev[1] == "" {
				rev[1] = "HEAD"
			}
		default:
			return fmt.Errorf("invalid argument to '-revision' flag (%q)", ctx.Revision)
		}
		cmdargs = append(cmdargs,
			"-r",
			fmt.Sprintf("%s:%s", rev[0], rev[1]),
		)
	}
	if ctx.Exclude != "" {
		patterns := []string{}
		if ctx.RootIsTrunk {
			if ctx.Trunk != "" {
				patterns = append(patterns, ctx.Trunk+"[/]")
			}
			if ctx.Tags != "" {
				patterns = append(patterns, ctx.Tags+"[/][^/]+[/]")
			}
			if ctx.Branches != "" {
				patterns = append(patterns, ctx.Branches+"[/][^/]+[/]")
			}
		}
		regex := fmt.Sprintf("^(?:%s)(?:%s)",
			strings.Join(patterns, "|"),
			ctx.Exclude)
		cmdargs = append(cmdargs,
			fmt.Sprintf("--ignore-paths=\"%s\"", regex),
		)
	}

	cmd = exec.Command("git", cmdargs...)
	if ctx.Verbose {
		fmt.Printf(":: running %s\n", strings.Join(cmd.Args, " "))
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	err = cmd.Run()
	if err != nil {
		return err
	}

	err = ctx.get_branches()
	if err != nil {
		return err
	}

	return err
}

func (ctx *Context) fix_tags() error {
	var err error = nil
	usr := make(map[string]string)

	// we only change git config values if ctx.Repo.tags are available.
	// so it stands to reason we should revert them only in that case.
	defer func() {
		if len(ctx.Repo.tags) == 0 {
			return
		}
		for name, v := range usr {
			vv := strings.Trim(v, " ")
			if vv != "" {
				cmd := exec.Command("git", "config", "--local", name,
					strconv.Quote(vv))
				_ = cmd.Run()
			} else {
				cmd := exec.Command("git", "config", "--local", "--unset", name)
				_ = cmd.Run()
			}
			//fmt.Printf("%s: %q %q\n", name, v, vv)
		}
	}()

	git_cfg := func(k string) (string, error) {
		cmd := exec.Command("git", "config", "--local", "--get", k)
		out, err := cmd.CombinedOutput()
		if err != nil {
			// ignore error!
			return "", nil
		}
		r := bufio.NewReader(bytes.NewBuffer(out))
		lines := []string{}
		for line := range iochan.ReaderChan(r, "\n") {
			lines = append(lines, line)
		}
		if len(lines) != 1 {
			return "", fmt.Errorf("too many lines (%d)", len(lines))
		}
		return lines[0], err
	}
	usr["user.name"], _ = git_cfg("user.name")
	usr["user.email"], _ = git_cfg("user.name")

	for itag, tag := range ctx.Repo.tags {
		tag = strings.Trim(tag, " ")
		id := tag[len("svn/tags/"):]
		if ctx.Verbose {
			hdr := ""
			if itag > 0 {
				hdr = "\n"
			}
			fmt.Printf("%s:: processing svn tag [%s]...\n", hdr, tag)
		}
		subject := ctx.git_cmd("log", "-1", "--pretty=format:%s", tag)[0]
		date := ctx.git_cmd("log", "-1", "--pretty=format:%ci", tag)[0]
		author := ctx.git_cmd("log", "-1", "--pretty=format:%an", tag)[0]
		email := ctx.git_cmd("log", "-1", "--pretty=format:%ae", tag)[0]

		cmd := exec.Command("git", "config", "--local", "user.name",
			"\""+author+"\"")
		ctx.print_cmd(cmd)
		_ = cmd.Run()

		cmd = exec.Command("git", "config", "--local", "user.email",
			"\""+email+"\"")
		ctx.print_cmd(cmd)
		_ = cmd.Run()

		cmd = exec.Command("git", "tag", "-a", "-m",
			fmt.Sprintf("\"%s\"", subject),
			id,
			tag)
		cmd.Env = os.Environ()
		cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_COMMITTER_DATE=%s", date))
		ctx.print_cmd(cmd)
		err = cmd.Run()
		if err != nil {
			fmt.Printf("**error** %v\n", err)
			return err
		}

		cmd = exec.Command("git", "branch", "-d", "-r", tag)
		ctx.print_cmd(cmd)
		err = cmd.Run()
		if err != nil {
			fmt.Printf("**error** %v\n", err)
			return err
		}

		//fmt.Printf("tag: %q - subject: %q\n", tag, subject)
	}
	return err
}

func (ctx *Context) fix_branches() error {
	var err error = nil
	svn_branches := []string{}
	for _, v := range ctx.Repo.remote_branches {
		if is_in_slice(v, ctx.Repo.tags) {
			if ctx.Verbose {
				fmt.Printf("-- discard [%s]...\n", v)
			}
			continue
		}
		if strings.HasPrefix(v, "svn/") {
			svn_branches = append(svn_branches, v)
		}
	}
	if ctx.Verbose {
		fmt.Printf("svn-branches: %v\n", svn_branches)
	}

	if ctx.Rebase {
		cmd := exec.Command("git", "svn", "fetch")
		ctx.print_cmd(cmd)
		if ctx.Verbose {
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
		}
		err = cmd.Run()
		if err != nil {
			return err
		}
	}

	for _, branch := range svn_branches {
		branch = branch[len("svn/"):]
		if ctx.Rebase && (is_in_slice(branch, ctx.Repo.local_branches) || branch == "trunk") {
			lbranch := branch
			if branch == "trunk" {
				lbranch = "master"
			}
			cmd := exec.Command("git", "checkout", "-f", lbranch)
			ctx.print_cmd(cmd)
			ctx.debug_cmd(cmd)
			err = cmd.Run()
			if err != nil {
				return err
			}

			cmd = exec.Command("git", "rebase",
				fmt.Sprintf("remotes/svn/%s", branch),
			)
			ctx.print_cmd(cmd)
			ctx.debug_cmd(cmd)
			err = cmd.Run()
			if err != nil {
				return err
			}
			continue
		}

		if branch == "trunk" || is_in_slice(branch, ctx.Repo.local_branches) {
			continue
		}

		cmd := exec.Command("git", "branch", branch,
			fmt.Sprintf("remotes/svn/%s", branch))
		ctx.print_cmd(cmd)
		ctx.debug_cmd(cmd)
		err = cmd.Run()
		if err != nil {
			return err
		}

		cmd = exec.Command("git", "checkout", branch)
		ctx.print_cmd(cmd)
		ctx.debug_cmd(cmd)
		err = cmd.Run()
		if err != nil {
			return err
		}
	}
	return err
}

func (ctx *Context) fix_trunk() error {
	var err error = nil
	trunk := ""
	for _, v := range ctx.Repo.remote_branches {
		if strings.Trim(v, " ") == "trunk" {
			trunk = "trunk"
			break
		}
	}
	var cmds []string
	if trunk != "" && !ctx.Rebase {
		cmds = []string{
			"git checkout svn/trunk",
			"git branch -D master",
			"git checkout -f -b master",
		}
	} else {
		cmds = []string{"git checkout -f master"}
	}
	for _, cmdstr := range cmds {
		cmdargs := strings.Split(cmdstr, " ")
		cmd := exec.Command(cmdargs[0], cmdargs[1:]...)
		ctx.print_cmd(cmd)
		ctx.debug_cmd(cmd)
		err = cmd.Run()
		if err != nil {
			return err
		}
	}
	return err
}

func (ctx *Context) optimize_repos() error {
	var err error = nil
	cmd := exec.Command("git", "gc")
	ctx.print_cmd(cmd)
	ctx.debug_cmd(cmd)
	err = cmd.Run()
	return err
}

func (ctx *Context) verify_working_tree_is_clean() error {
	cmd := exec.Command("git", "status", "--porcelain", "--untracked-files=no")
	out, err := cmd.CombinedOutput()
	if len(out) != 0 {
		fmt.Printf("** you have pending changes. The working tree must be clean in order to continue.\n")
	}
	return err
}

// EOF


text:
#include <aws/inspector2/model/DateFilter.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Inspector2
{
namespace Model
{

DateFilter::DateFilter() :
    m_endInclusiveHasBeenSet(false),
    m_startInclusiveHasBeenSet(false)
{
}

DateFilter::DateFilter(JsonView jsonValue) :
    m_endInclusiveHasBeenSet(false),
    m_startInclusiveHasBeenSet(false)
{
  *this = jsonValue;
}

DateFilter& DateFilter::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("endInclusive"))
  {
    m_endInclusive = jsonValue.GetDouble("endInclusive");

    m_endInclusiveHasBeenSet = true;
  }

  if(jsonValue.ValueExists("startInclusive"))
  {
    m_startInclusive = jsonValue.GetDouble("startInclusive");

    m_startInclusiveHasBeenSet = true;
  }

  return *this;
}

JsonValue DateFilter::Jsonize() const
{
  JsonValue payload;

  if(m_endInclusiveHasBeenSet)
  {
   payload.WithDouble("endInclusive", m_endInclusive.SecondsWithMSPrecision());
  }

  if(m_startInclusiveHasBeenSet)
  {
   payload.WithDouble("startInclusive", m_startInclusive.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace Inspector2
} // namespace Aws


text:
package edu.clemson.cs.r2jt.typeandpopulate.entry;

import edu.clemson.cs.r2jt.absyn.ResolveConceptualElement;
import edu.clemson.cs.r2jt.typeandpopulate.ModuleIdentifier;

public abstract class ModuleEntry extends SymbolTableEntry {

    public ModuleEntry(String name, ResolveConceptualElement definingElement) {
        super(name, definingElement, ModuleIdentifier.GLOBAL);
    }
}


text:
//
//  foodViewController.m
//  ShoppingCart
//
//  Created by sin on 2017/03/07.
//  Copyright © 2017年 shinji. All rights reserved.
//

#import "FoodViewController.h"
#import "Food.h"

@interface FoodViewController ()

@property (strong, nonatomic) NSMutableArray<NSString*>* itemsForTextFName;
@property (strong, nonatomic) Food* food;

@end

@implementation FoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.foodTableView.delegate = self;
    self.foodTableView.dataSource = self;
    self.itemsForTextFName = [@[@"foodID",@"foodName",@"foodPrice",@"foodMadeInCountry",@"foodCalorie",@"foodSize",@"foodIngredients"] mutableCopy];

    self.foodTextFieldArray = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)addItem:(UIButton *)sender {

    FoodTableViewCell* cell = [self.foodTableView dequeueReusableCellWithIdentifier:@"clothTextFieldID"];
    if(!cell){
        cell = [[FoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"clothTextFieldID"];
    }

    NSMutableArray* txtfieldArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.foodTextFieldArray.count; i++) {
        UITextField* te = [self.foodTextFieldArray objectAtIndex:i];
        [txtfieldArray addObject:te.text];
    }
    NSString* foodIng            = txtfieldArray[6];
    NSMutableArray* ingredients = [[NSMutableArray alloc] init];
    [ingredients addObject:foodIng];

    self.food = [[Food alloc]
                 initWithID:(int)txtfieldArray[0]
                 productName:txtfieldArray[1]
                 productPrice:[txtfieldArray[2] floatValue]
                 productMadeInCountry:txtfieldArray[3]
                 productSize:(int)txtfieldArray[4]
                 foodCalorie:(int)txtfieldArray[5]
                 foodIngredients:ingredients
                 ];

    [self.delegate addItemIntoCart:self.food];
    [self.navigationController popViewControllerAnimated:YES];

}

- (IBAction)btnClose:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if(indexPath.section == 0){
        //Step 1: Cell creation
        FoodTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"foodTextFieldID"];
        if(!cell){
            cell = [[FoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"foodTextFieldID"];
        }

        //Step2: Data Binding
        cell.foodTextField.delegate = self;
        cell.foodTextField.placeholder = [self.itemsForTextFName objectAtIndex:indexPath.row];
        cell.foodTextField.tag = indexPath.row + 1;
        self.foodTextFieldArray[indexPath.row] = cell.foodTextField;

        return  cell;

    }else{
        return 0;
    }

}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemsForTextFName.count;
}

@end


text:
package com.davidsoergel.trees.htpn;

import com.davidsoergel.dsutils.collections.OrderedPair;
import com.davidsoergel.dsutils.collections.SerializableOrderedPair;

import java.io.Serializable;

/**
 * @author David Soergel
 * @version $Id$
 */
public class SerializableHierarchicalTypedPropertyNode<K extends Comparable<K> & Serializable, V extends Serializable>

		extends AbstractHierarchicalTypedPropertyNode<K, V, SerializableHierarchicalTypedPropertyNode<K, V>>
	{
	/*	public BasicHierarchicalTypedPropertyNode<S, T> newChild()
		 {
		 BasicHierarchicalTypedPropertyNode<S, T> result = new SerializableHierarchicalTypedPropertyNodeImpl<S, T>();
		 //children.add(result);  // setParent calls registerChild
		 result.setParent(this);
		 return result;
		 }
 */
	public SerializableHierarchicalTypedPropertyNode<K, V> newChild(final OrderedPair<K, V> payload)
		{
		SerializableHierarchicalTypedPropertyNode<K, V> result = new SerializableHierarchicalTypedPropertyNode<K, V>();
		//children.add(result);  // setParent calls registerChild
		result.setPayload(payload);
		result.setParent(this);
		return result;
		}

	/**
	 * Set the value of this node.  If this node expects a plugin and the value is a Class (or a String naming a Class),
	 * then create the children array if necessary and populate it with defaults.  Act similarly for a PluginMap.
	 *

	 * If the children array already exists, and the value was previously null or the same class, then we merge the
	 * defaults non-destructively.
	 *
	 * @param value
	 * @throws HierarchicalPropertyNodeException
	 *
	 */
	public void setValue(V value) //throws HierarchicalPropertyNodeException
		{

		/*setValueForce(value);
		}

	protected void setValueForce(V value) //throws HierarchicalPropertyNodeException
		{*/
		/*	boolean destructive = true;
		  T currentValue = getValue();
		  if (currentValue == null || currentValue == value)
			  {
			  destructive = false;
			  }
  */
		// do any required string parsing, including class names
		/*	if (value instanceof String)
		   {
		   value = parseValueString((String) value);
		   }*/
		//this.value = value;
		payload = new SerializableOrderedPair<K, V>(getKey(), value);

		// REVIEW possible hack re setting PluginMap values on an HTPN

//** All PluginMap functionality needs revisiting
		/*
		if (isPluginMap() && value != null)// value instanceof PluginMap
			{
			throw new HierarchicalPropertyNodeException(
					"Can't set a plugin value on a regular HTPN; need to use the StringNamed version");
			}
		else */
		if (isClassBoundPlugin() && value != null)
			{
			throw new Error( //HierarchicalPropertyNodeException(
			                 "Can't set a plugin value on a regular HTPN; need to use the StringNamed version");
			}
		else
			{
			clearChildren();
			}

		// if the value is a String giving a class name that is not currently loadable, we may yet add children later
		}

	@Override
	public void registerChild(final SerializableHierarchicalTypedPropertyNode<K, V> a)
		{
		//assert a instanceof SerializableHierarchicalTypedPropertyNode;
		super.registerChild(a);
		}

	@Override
	public void unregisterChild(final SerializableHierarchicalTypedPropertyNode<K, V> a)
		{
		//assert a instanceof SerializableHierarchicalTypedPropertyNode;
		super.unregisterChild(a);
		}
	}


text:
@interface FakeQuestionBuilder : QuestionBuilder
@property (copy) NSString *json;
@property (copy) NSArray *arrayToReturn;
@property (copy) NSError *errorToSet;
@end


text:
    #define ILP_USE_ARC __has_feature(objc_arc)
#endif

#if ILP_USE_ARC
    #define ILP_RETAIN(xx)           xx
    #define ILP_RELEASE(xx)
    #define ILP_AUTORELEASE(xx)      xx
#else
    #define ILP_RETAIN(xx)           [xx retain];
    #define ILP_RELEASE(xx)          [xx release];
    #define ILP_AUTORELEASE(xx)      [xx autorelease];
#endif

typedef void(^ITWLoadingPanelBasicBlock)(void);

@interface ITWLoadingPanel : UIView

@property (nonatomic, strong) IBOutlet UIButton *cancelBtn;
@property (nonatomic, strong) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView *activityView;
@property (nonatomic, strong) IBOutlet UIImageView *successImageView;
@property (nonatomic, strong) IBOutlet UILabel *cancelLabel;
@property (nonatomic, strong) IBOutlet UILabel *titleLabel;
@property (nonatomic, readonly) CFTimeInterval animationDuration;
@property (nonatomic, copy) ITWLoadingPanelBasicBlock onDisappearBlock;
@property (nonatomic, copy) ITWLoadingPanelBasicBlock onCancelBlock;

+ (id)sharedInstance;

+ (id)panel;

+ (ITWLoadingPanel *)showPanelInView:(UIView *)view
                               title:(NSString *)title
                         cancelTitle:(NSString *)cancelTitle
                              cancel:(ITWLoadingPanelBasicBlock)cancel
                           disappear:(ITWLoadingPanelBasicBlock)disappear;

+ (ITWLoadingPanel *)showPanelInView:(UIView *)view
                               title:(NSString *)title
                         cancelTitle:(NSString *)cancelTitle
                              cancel:(ITWLoadingPanelBasicBlock)cancel;

+ (ITWLoadingPanel *)showPanelInView:(UIView *)view
                               title:(NSString *)title
                         cancelTitle:(NSString *)cancelTitle;

+ (void)showSuccess;

- (void)showSuccess;

+ (void)hidePanel;

- (void)hidePanel;

+ (void)setProgress:(float)progress animated:(BOOL)animated;

+ (float)progress;

+ (CFTimeInterval)animationDuration;

- (CFTimeInterval)animationDuration;

+ (CFTimeInterval)disappearWaitTime;

- (CFTimeInterval)disappearWaitTime;

@end