text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace MovementTest
{
    public class SpriteAnimator
    {
        KeyboardState currentKBState;
        KeyboardState previousKBState;
        Texture2D spriteTexture;
        float timer = 0f;
        float interval = 200f;
        int currentFrame = 0;
        int frameHeight;
        int frameWidth;
        int spriteWidth;
        int spriteHeight;
        int spriteSpeed = 8;//2
        Rectangle sourceRect;
        Vector2 position;
        Vector2 origin;

        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        public Vector2 Origin
        {
            get { return origin; }
            set { origin = value; }
        }
        public Texture2D Texture
        {
            get { return spriteTexture; }
            set { spriteTexture = value; }
        }
        public Rectangle SourceRect
        {
            get { return sourceRect; }
            set { sourceRect = value; }
        }

        public SpriteAnimator(Texture2D texture, int currentFrame, int spriteWidth, int spriteHeight)
        {
            this.spriteTexture = texture;
            this.currentFrame = currentFrame;
            this.spriteWidth = spriteWidth;
            this.spriteHeight = spriteHeight;
            frameHeight = spriteTexture.Height/spriteHeight;
            frameWidth = spriteTexture.Width/spriteWidth;
        }
        public void HandleSpriteMovement(GameTime gameTime)
        {
            previousKBState = currentKBState;
            currentKBState = Keyboard.GetState();

            //(x,y,width, height)
            sourceRect = new Rectangle((currentFrame % frameWidth) * spriteWidth, (currentFrame / frameWidth)*spriteHeight, spriteWidth, spriteHeight);
            if (currentKBState.GetPressedKeys().Length == 0)
            {
                int row = currentFrame/frameWidth;
                currentFrame = row * frameWidth;
            }

            if (currentKBState.IsKeyDown(Keys.D) == true)
            {
                AnimateRight(gameTime);
                    position.X += spriteSpeed;
            }

            if (currentKBState.IsKeyDown(Keys.A) == true)
            {
                AnimateLeft(gameTime);
                    position.X -= spriteSpeed;
            }

            if (currentKBState.IsKeyDown(Keys.S) == true)
            {
                AnimateDown(gameTime);
                    position.Y += spriteSpeed;
            }

            if (currentKBState.IsKeyDown(Keys.W) == true)
            {
                AnimateUp(gameTime);
                    position.Y -= spriteSpeed;
            }

            origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
        }

        public void AnimateRight(GameTime gameTime)
        {
            if (currentKBState != previousKBState)
            {
                currentFrame = (frameWidth*3);
            }

            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            if (timer > interval)
            {
                currentFrame++;
                if (currentFrame > (frameWidth * 4)-1)
                {
                    currentFrame = (frameWidth * 3)+1;
                }
                timer = 0f;
            }
        }

        public void AnimateLeft(GameTime gameTime)
        {
            if (currentKBState != previousKBState)
            {
                currentFrame = (frameWidth);
            }

            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            if (timer > interval)
            {
                currentFrame++;

                if (currentFrame > (frameWidth * 2) - 1)
                {
                    currentFrame = (frameWidth * 1) + 1;
                }
                timer = 0f;
            }
        }

        public void AnimateUp(GameTime gameTime)
        {
            if (currentKBState != previousKBState)
            {
                currentFrame = 1;
            }

            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            if (timer > interval)
            {
                currentFrame++;

                if (currentFrame > frameWidth  - 1)
                {
                    currentFrame = 0;
                }
                timer = 0f;
            }
        }

        public void AnimateDown(GameTime gameTime)
        {
            if (currentKBState != previousKBState)
            {
                currentFrame = (frameWidth * 2) + 1;
            }

            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            if (timer > interval)
            {
                currentFrame++;

                if (currentFrame > (frameWidth * 3) - 1)
                {
                    currentFrame = (frameWidth * 2) + 1;
                }
                timer = 0f;
            }
        }

    }
}


text:
"""
The integration with PostgreSQL supports the aiopg library,
it can be enabled by using ``AiopgInstrumentor``.

.. aiopg: https://github.com/aio-libs/aiopg

Usage
-----

.. code-block:: python

    import aiopg
    from opentelemetry.instrumentation.aiopg import AiopgInstrumentor

    AiopgInstrumentor().instrument()

    cnx = await aiopg.connect(database='Database')
    cursor = await cnx.cursor()
    await cursor.execute("INSERT INTO test (testField) VALUES (123)")
    cursor.close()
    cnx.close()

    pool = await aiopg.create_pool(database='Database')
    cnx = await pool.acquire()
    cursor = await cnx.cursor()
    await cursor.execute("INSERT INTO test (testField) VALUES (123)")
    cursor.close()
    cnx.close()

API
---
"""

from typing import Collection

from opentelemetry.instrumentation.aiopg import wrappers
from opentelemetry.instrumentation.aiopg.package import _instruments
from opentelemetry.instrumentation.aiopg.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor

class AiopgInstrumentor(BaseInstrumentor):
    _CONNECTION_ATTRIBUTES = {
        "database": "info.dbname",
        "port": "info.port",
        "host": "info.host",
        "user": "info.user",
    }

    _DATABASE_SYSTEM = "postgresql"

    def instrumentation_dependencies(self) -> Collection[str]:
        return _instruments

    def _instrument(self, **kwargs):
        """Integrate with PostgreSQL aiopg library.
        aiopg: https://github.com/aio-libs/aiopg
        """

        tracer_provider = kwargs.get("tracer_provider")

        wrappers.wrap_connect(
            __name__,
            self._DATABASE_SYSTEM,
            self._CONNECTION_ATTRIBUTES,
            version=__version__,
            tracer_provider=tracer_provider,
        )

        wrappers.wrap_create_pool(
            __name__,
            self._DATABASE_SYSTEM,
            self._CONNECTION_ATTRIBUTES,
            version=__version__,
            tracer_provider=tracer_provider,
        )

    # pylint:disable=no-self-use
    def _uninstrument(self, **kwargs):
        """ "Disable aiopg instrumentation"""
        wrappers.unwrap_connect()
        wrappers.unwrap_create_pool()

    # pylint:disable=no-self-use
    def instrument_connection(self, connection, tracer_provider=None):
        """Enable instrumentation in a aiopg connection.

        Args:
            connection: The connection to instrument.
            tracer_provider: The optional tracer provider to use. If omitted
                the current globally configured one is used.

        Returns:
            An instrumented connection.
        """
        return wrappers.instrument_connection(
            __name__,
            connection,
            self._DATABASE_SYSTEM,
            self._CONNECTION_ATTRIBUTES,
            version=__version__,
            tracer_provider=tracer_provider,
        )

    def uninstrument_connection(self, connection):
        """Disable instrumentation in a aiopg connection.

        Args:
            connection: The connection to uninstrument.

        Returns:
            An uninstrumented connection.
        """
        return wrappers.uninstrument_connection(connection)

redpajama_set_name: RedPajamaGithub


text:
import {
	UPDATE_PAGE,
	UPDATE_OFFLINE,
	OPEN_SNACKBAR,
	CLOSE_SNACKBAR,
	OPEN_HEADER_PANEL,
	CLOSE_HEADER_PANEL,
} from '../actions/app.js';

const INITIAL_STATE = {
	location: '',
	page: '',
	pageExtra: '',
	offline: false,
	snackbarOpened: false,
	headerPanelOpen: false,
};

const app = (state = INITIAL_STATE, action) => {
	switch (action.type) {
	case UPDATE_PAGE:
		return {
			...state,
			location: action.location,
			page: action.page,
			pageExtra: action.pageExtra
		};
	case UPDATE_OFFLINE:
		return {
			...state,
			offline: action.offline
		};
	case OPEN_SNACKBAR:
		return {
			...state,
			snackbarOpened: true
		};
	case CLOSE_SNACKBAR:
		return {
			...state,
			snackbarOpened: false
		};
	case OPEN_HEADER_PANEL:
		return {
			...state,
			headerPanelOpen: true
		};
	case CLOSE_HEADER_PANEL:
		return {
			...state,
			headerPanelOpen: false
		};
	default:
		return state;
	}
};

export default app;


text:
/**
 * Created at 2:51:18 PM Jan 23, 2011
 */
package org.jbox2d.gwt.showcase.client.example;

import java.util.HashSet;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.gwt.showcase.client.framework.BaseExample;
import org.jbox2d.gwt.showcase.client.framework.ContactPoint;
import org.jbox2d.gwt.showcase.client.framework.ShowcaseSettings;

/**
 * @author Daniel Murphy
 */
public class CollisionProcessing extends BaseExample {

	/**
	 * @see org.jbox2d.testbed.framework.TestbedTest#initTest()
	 */
	@Override
	public void initTest() {
		// Ground body
		{
			PolygonShape shape = new PolygonShape();
			shape.setAsEdge(new Vec2(-50.0f, 0.0f), new Vec2(50.0f, 0.0f));

			FixtureDef sd = new FixtureDef();
			sd.shape = shape;

			BodyDef bd = new BodyDef();
			Body ground = m_world.createBody(bd);
			ground.createFixture(sd);
		}

		float xLo = -5.0f, xHi = 5.0f;
		float yLo = 2.0f, yHi = 35.0f;

		// Small triangle
		Vec2 vertices[] = new Vec2[3];
		vertices[0] = new Vec2(-1.0f, 0.0f);
		vertices[1] = new Vec2(1.0f, 0.0f);
		vertices[2] = new Vec2(0.0f, 2.0f);

		PolygonShape polygon = new PolygonShape();
		polygon.set(vertices, 3);

		FixtureDef triangleShapeDef = new FixtureDef();
		triangleShapeDef.shape = polygon;
		triangleShapeDef.density = 1.0f;

		BodyDef triangleBodyDef = new BodyDef();
		triangleBodyDef.type = BodyType.DYNAMIC;
		triangleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body1 = m_world.createBody(triangleBodyDef);
		body1.createFixture(triangleShapeDef);

		// Large triangle (recycle definitions)
		vertices[0].mulLocal(2.0f);
		vertices[1].mulLocal(2.0f);
		vertices[2].mulLocal(2.0f);
		polygon.set(vertices, 3);

		triangleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body2 = m_world.createBody(triangleBodyDef);
		body2.createFixture(triangleShapeDef);

		// Small box
		polygon.setAsBox(1.0f, 0.5f);

		FixtureDef boxShapeDef = new FixtureDef();
		boxShapeDef.shape = polygon;
		boxShapeDef.density = 1.0f;

		BodyDef boxBodyDef = new BodyDef();
		boxBodyDef.type = BodyType.DYNAMIC;
		boxBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body3 = m_world.createBody(boxBodyDef);
		body3.createFixture(boxShapeDef);

		// Large box (recycle definitions)
		polygon.setAsBox(2.0f, 1.0f);
		boxBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body4 = m_world.createBody(boxBodyDef);
		body4.createFixture(boxShapeDef);

		// Small circle
		CircleShape circle = new CircleShape();
		circle.m_radius = 1.0f;

		FixtureDef circleShapeDef = new FixtureDef();
		circleShapeDef.shape = circle;
		circleShapeDef.density = 1.0f;

		BodyDef circleBodyDef = new BodyDef();
		circleBodyDef.type = BodyType.DYNAMIC;
		circleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body5 = m_world.createBody(circleBodyDef);
		body5.createFixture(circleShapeDef);

		// Large circle
		circle.m_radius *= 2.0f;
		circleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));

		Body body6 = m_world.createBody(circleBodyDef);
		body6.createFixture(circleShapeDef);
	}

	/**
	 * @see org.jbox2d.testbed.framework.TestbedTest#step(org.jbox2d.testbed.framework.ShowcaseSettings)
	 */
	@Override
	public void step(ShowcaseSettings settings) {
		super.step(settings);

		// We are going to destroy some bodies according to contact
		// points. We must buffer the bodies that should be destroyed
		// because they may belong to multiple contact points.
		HashSet<Body> nuke = new HashSet<Body>();

		// Traverse the contact results. Destroy bodies that
		// are touching heavier bodies.
		for (int i = 0; i < m_pointCount; ++i) {
			ContactPoint point = points[i];

			Body body1 = point.fixtureA.getBody();
			Body body2 = point.fixtureB.getBody();
			float mass1 = body1.getMass();
			float mass2 = body2.getMass();

			if (mass1 > 0.0f && mass2 > 0.0f) {
				if (mass2 > mass1) {
					nuke.add(body1);
				}
				else {
					nuke.add(body2);
				}
			}
		}

		// Sort the nuke array to group duplicates.
		// Arrays.sort(nuke);

		// Destroy the bodies, skipping duplicates.
		for (Body b : nuke) {

			if (b != m_bomb) {
				m_world.destroyBody(b);
			}
		}
	}

	/**
	 * @see org.jbox2d.testbed.framework.TestbedTest#getTestName()
	 */
	@Override
	public String getTestName() {
		return "Collision Processing";
	}

}


text:
body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Override the default bootstrap behavior where horizontal description lists
   will truncate terms that are too long to fit in the left column
*/
.dl-horizontal dt {
    white-space: normal;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

.display-box {
    border: solid 1px black;
    display: block;
    padding: 10px;
    font-size: 36px;
    text-align: right;
}

.display-container {
    margin-bottom: 15px;
}

.button-row {
    margin-bottom: 10px;
}

.calculator-button {
    width: 100%;
    font-size: 24px;
    font-weight: bold;
}

.display-box .left-side {
    display: inline-block;
    float: left;
}


text:
PKG = github.com/apprenda/kismatic
BUILD_OUTPUT = out-$(GOOS)

# Set the build version
ifeq ($(origin VERSION), undefined)
	VERSION := $(shell git describe --tags --always --dirty)
endif
# Set the build branch
ifeq ($(origin BRANCH), undefined)
	BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
endif
# build date
ifeq ($(origin BUILD_DATE), undefined)
	BUILD_DATE := $(shell date -u)
endif
# If no target is defined, assume the host is the target.
ifeq ($(origin GOOS), undefined)
	GOOS := $(shell go env GOOS)
endif
# Lots of these target goarches probably won't work,
# since we depend on vendored packages also being built for the correct arch
ifeq ($(origin GOARCH), undefined)
	GOARCH := $(shell go env GOARCH)
endif
# If no target is defined, assume the host is the target.
ifeq ($(origin HOST_GOOS), undefined)
	HOST_GOOS := $(shell go env GOOS)
endif
# Lots of these target goarches probably won't work,
# since we depend on vendored packages also being built for the correct arch
ifeq ($(origin HOST_GOARCH), undefined)
	HOST_GOARCH := $(shell go env GOARCH)
endif
# Used by the integration tests to tag nodes
ifeq ($(origin CREATED_BY), undefined)
	CREATED_BY := $(shell hostname)
endif

# Versions of external dependencies
GLIDE_VERSION = v0.13.1
ANSIBLE_VERSION = 2.3.0.0
PROVISIONER_VERSION = v1.13.0
KUBERANG_VERSION = v1.3.0
GO_VERSION = 1.10.3
KUBECTL_VERSION = v1.10.5
HELM_VERSION = v2.9.1

install:
	@echo Building kismatic in container
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w /go/src/$(PKG)                      \
	    circleci/golang:$(GO_VERSION)          \
	    make bin/$(GOOS)/kismatic build-inspector-host copy-kismatic copy-playbooks copy-inspector

dist: shallow-clean
	@echo "Running dist inside contianer"
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w "/go/src/$(PKG)"                    \
	    circleci/golang:$(GO_VERSION)          \
	    make dist-common

clean:
	rm -rf bin
	rm -rf out-*
	rm -rf vendor
	rm -rf vendor-*
	rm -rf tools
	rm -rf tmp

test:
	@docker run                             \
	    --rm                                \
	    -e HOST_GOOS="linux"                \
	    -u root:root                        \
	    -v "$(shell pwd)":/go/src/$(PKG)    \
	    -w /go/src/$(PKG)                   \
	    circleci/golang:$(GO_VERSION)       \
	    make test-host

integration-test:
	mkdir -p tmp
	@echo "Running integration tests inside contianer"
	@docker run                                                 \
	    --rm                                                    \
	    -e GOOS="linux"                                         \
	    -e HOST_GOOS="linux"                                    \
	    -e VERSION="$(VERSION)"                                 \
	    -e BUILD_DATE="$(BUILD_DATE)"                           \
	    -e AWS_ACCESS_KEY_ID="$(AWS_ACCESS_KEY_ID)"             \
	    -e AWS_SECRET_ACCESS_KEY="$(AWS_SECRET_ACCESS_KEY)"     \
	    -e LEAVE_ARTIFACTS="$(LEAVE_ARTIFACTS)"                 \
	    -e CREATED_BY="$(CREATED_BY)"                           \
	    -u root:root                                            \
	    -v "$(shell pwd)":"/go/src/$(PKG)"                      \
	    -v "$(HOME)/.ssh/kismatic-integration-testing.pem":"/root/.ssh/kismatic-integration-testing.pem:ro" \
	    -v "$(shell pwd)/tmp":"/tmp/kismatic"                   \
	    -w "/go/src/$(PKG)"                                     \
	    circleci/golang:$(GO_VERSION)                           \
	    make integration-test-host

focus-integration-test:
	mkdir -p tmp
	@echo "Running integration tests inside contianer"
	@docker run                                                 \
	    --rm                                                    \
	    -e FOCUS="$(FOCUS)"                                     \
	    -e GOOS="linux"                                         \
	    -e HOST_GOOS="linux"                                    \
	    -e VERSION="$(VERSION)"                                 \
	    -e BUILD_DATE="$(BUILD_DATE)"                           \
	    -e AWS_ACCESS_KEY_ID="$(AWS_ACCESS_KEY_ID)"             \
	    -e AWS_SECRET_ACCESS_KEY="$(AWS_SECRET_ACCESS_KEY)"     \
	    -e LEAVE_ARTIFACTS="$(LEAVE_ARTIFACTS)"                 \
	    -e CREATED_BY="$(CREATED_BY)"                           \
	    -u root:root                                            \
	    -v "$(shell pwd)":"/go/src/$(PKG)"                      \
	    -v "$(HOME)/.ssh/kismatic-integration-testing.pem":"/root/.ssh/kismatic-integration-testing.pem:ro" \
	    -v "$(shell pwd)/tmp":"/tmp/kismatic"                   \
	    -w "/go/src/$(PKG)"                                     \
	    circleci/golang:$(GO_VERSION)                           \
	    make focus-integration-test-host

slow-integration-test:
	mkdir -p tmp
	@echo "Running integration tests inside contianer"
	@docker run                                                 \
	    --rm                                                    \
	    -e GOOS="linux"                                         \
	    -e HOST_GOOS="linux"                                    \
	    -e VERSION="$(VERSION)"                                 \
	    -e BUILD_DATE="$(BUILD_DATE)"                           \
	    -e AWS_ACCESS_KEY_ID="$(AWS_ACCESS_KEY_ID)"             \
	    -e AWS_SECRET_ACCESS_KEY="$(AWS_SECRET_ACCESS_KEY)"     \
	    -e LEAVE_ARTIFACTS="$(LEAVE_ARTIFACTS)"                 \
	    -e CREATED_BY="$(CREATED_BY)"                           \
	    -u root:root                                            \
	    -v "$(shell pwd)":"/go/src/$(PKG)"                      \
	    -v "$(HOME)/.ssh/kismatic-integration-testing.pem":"/root/.ssh/kismatic-integration-testing.pem:ro" \
	    -v "$(shell pwd)/tmp":"/tmp/kismatic"                   \
	    -w "/go/src/$(PKG)"                                     \
	    circleci/golang:$(GO_VERSION)                           \
	    make slow-integration-test-host

# YOU SHOULDN'T NEED TO USE ANYTHING BENEATH THIS LINE
# UNLESS YOU REALLY KNOW WHAT YOU'RE DOING
# ---------------------------------------------------------------------
all:
	@$(MAKE) GOOS=darwin dist
	@$(MAKE) GOOS=linux dist

shallow-clean:
	rm -rf $(BUILD_OUTPUT)

tar-clean:
	rm kismatic-*.tar.gz

build:
	@echo Building kismatic in container
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w /go/src/$(PKG)                      \
	    circleci/golang:$(GO_VERSION)          \
	    make build-host

build-inspector:
	@echo Building inspector in container
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w /go/src/$(PKG)                      \
	    circleci/golang:$(GO_VERSION)          \
	    make build-inspector-host

glide-install:
	@echo Glide installing in container
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w /go/src/$(PKG)                      \
	    circleci/golang:$(GO_VERSION)          \
	    make glide-install-host

glide-update:
	@echo Glide updating in container
	@docker run                                \
	    --rm                                   \
	    -e GOOS="$(GOOS)"                      \
	    -e HOST_GOOS="linux"                   \
	    -e VERSION="$(VERSION)"                \
	    -e BUILD_DATE="$(BUILD_DATE)"          \
	    -u root:root                           \
	    -v "$(shell pwd)":"/go/src/$(PKG)"     \
	    -w /go/src/$(PKG)                      \
	    circleci/golang:$(GO_VERSION)          \
	    make glide-update-host

copy-all: copy-vendors copy-inspector copy-playbooks copy-kismatic

copy-kismatic:
	mkdir -p $(BUILD_OUTPUT)
	cp bin/$(GOOS)/kismatic $(BUILD_OUTPUT)

copy-inspector:
	rm -rf $(BUILD_OUTPUT)/ansible/playbooks/inspector
	mkdir -p $(BUILD_OUTPUT)/ansible/playbooks/inspector
	cp -r bin/inspector/* $(BUILD_OUTPUT)/ansible/playbooks/inspector

copy-playbooks:
	mkdir -p $(BUILD_OUTPUT)/ansible
	rm -rf $(filter-out $(BUILD_OUTPUT)/ansible/playbooks/inspector $(BUILD_OUTPUT)/ansible/playbooks/kuberang, $(wildcard $(BUILD_OUTPUT)/ansible/playbooks/*))
	cp -r $(wildcard ansible/*) $(BUILD_OUTPUT)/ansible/playbooks

copy-vendors: # omit kismatic, inspector, terraform since we provide configs for those.
	mkdir -p $(BUILD_OUTPUT)/ansible
	cp -r vendor-ansible/out/ansible/* $(BUILD_OUTPUT)/ansible
	cp vendor-kubectl/out/kubectl-$(KUBECTL_VERSION)-$(GOOS)-$(GOARCH) $(BUILD_OUTPUT)/kubectl
	cp vendor-helm/out/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH) $(BUILD_OUTPUT)/helm
	cp vendor-provision/out/provision-$(PROVISIONER_VERSION)-$(GOOS)-$(GOARCH) $(BUILD_OUTPUT)/provision
	mkdir -p $(BUILD_OUTPUT)/ansible/playbooks/kuberang/linux/$(GOARCH)/
	cp vendor-kuberang/$(KUBERANG_VERSION)/kuberang-linux-$(GOARCH) $(BUILD_OUTPUT)/ansible/playbooks/kuberang/linux/$(GOARCH)/kuberang

tarball:
	rm -f kismatic-$(GOOS).tar.gz
	tar -czf kismatic-$(GOOS).tar.gz -C $(BUILD_OUTPUT) .

# RECIPES BELOW THIS LINE ARE INTENDED FOR CI ONLY. RUN LOCALLY AT YOUR OWN RISK.
# ---------------------------------------------------------------------

all-host:
	@$(MAKE) GOOS=darwin dist-host
	@$(MAKE) GOOS=linux dist-host

test-host:
	go test ./cmd/... ./pkg/... $(TEST_OPTS)

build-host: tools/glide-$(HOST_GOOS)-$(HOST_GOARCH) glide-install-host bin/$(GOOS)/kismatic

.PHONY: bin/$(GOOS)/kismatic
bin/$(GOOS)/kismatic:
	go build -o $@                                                              \
	    -ldflags "-X main.version=$(VERSION) -X 'main.buildDate=$(BUILD_DATE)'" \
	    ./cmd/kismatic

build-inspector-host:
	@$(MAKE) GOOS=linux bin/inspector/linux/$(GOARCH)/kismatic-inspector

.PHONY: bin/inspector/$(GOOS)/$(GOARCH)/kismatic-inspector
bin/inspector/$(GOOS)/$(GOARCH)/kismatic-inspector:
	go build -o $@                                                               \
	    -ldflags "-X main.version=$(VERSION) -X 'main.buildDate=$(BUILD_DATE)'"  \
	    ./cmd/kismatic-inspector

glide-install-host:
	tools/glide-$(HOST_GOOS)-$(HOST_GOARCH) cc
	tools/glide-$(HOST_GOOS)-$(HOST_GOARCH) install

glide-update-host:
	tools/glide-$(HOST_GOOS)-$(HOST_GOARCH) update

vendor: vendor-tools vendor-ansible/out vendor-provision/out/provision-$(PROVISIONER_VERSION)-$(GOOS)-$(GOARCH) vendor-kuberang/$(KUBERANG_VERSION) vendor-kubectl/out/kubectl-$(KUBECTL_VERSION)-$(GOOS)-$(GOARCH) vendor-helm/out/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH)

vendor-tools: tools/glide-$(HOST_GOOS)-$(HOST_GOARCH)

tools/glide-$(HOST_GOOS)-$(HOST_GOARCH):
	mkdir -p tools
	curl -L https://github.com/Masterminds/glide/releases/download/$(GLIDE_VERSION)/glide-$(GLIDE_VERSION)-$(HOST_GOOS)-$(HOST_GOARCH).tar.gz | tar -xz -C tools
	mv tools/$(HOST_GOOS)-$(HOST_GOARCH)/glide tools/glide-$(HOST_GOOS)-$(HOST_GOARCH)
	rm -r tools/$(HOST_GOOS)-$(HOST_GOARCH)

vendor-ansible/out:
	mkdir -p vendor-ansible/out
	curl -L https://github.com/apprenda/vendor-ansible/releases/download/v$(ANSIBLE_VERSION)/ansible.tar.gz -o vendor-ansible/out/ansible.tar.gz
	tar -zxf vendor-ansible/out/ansible.tar.gz -C vendor-ansible/out
	rm vendor-ansible/out/ansible.tar.gz

vendor-provision/out/provision-$(PROVISIONER_VERSION)-$(GOOS)-$(GOARCH):
	mkdir -p vendor-provision/out/
	curl -L https://github.com/apprenda/kismatic-provision/releases/download/$(PROVISIONER_VERSION)/provision-$(GOOS)-$(GOARCH) -o vendor-provision/out/provision-$(PROVISIONER_VERSION)-$(GOOS)-$(GOARCH)
	chmod +x vendor-provision/out/provision-$(PROVISIONER_VERSION)-$(GOOS)-$(GOARCH)

vendor-kuberang/$(KUBERANG_VERSION):
	mkdir -p vendor-kuberang/$(KUBERANG_VERSION)
	curl -L https://github.com/apprenda/kuberang/releases/download/$(KUBERANG_VERSION)/kuberang-linux-$(GOARCH) -o vendor-kuberang/$(KUBERANG_VERSION)/kuberang-linux-$(GOARCH)

vendor-kubectl/out/kubectl-$(KUBECTL_VERSION)-$(GOOS)-$(GOARCH):
	mkdir -p vendor-kubectl/out/
	curl -L https://storage.googleapis.com/kubernetes-release/release/$(KUBECTL_VERSION)/bin/$(GOOS)/$(GOARCH)/kubectl -o vendor-kubectl/out/kubectl-$(KUBECTL_VERSION)-$(GOOS)-$(GOARCH)
	chmod +x vendor-kubectl/out/kubectl-$(KUBECTL_VERSION)-$(GOOS)-$(GOARCH)

vendor-helm/out/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH):
	mkdir -p vendor-helm/out/
	curl -L https://storage.googleapis.com/kubernetes-helm/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH).tar.gz | tar zx -C vendor-helm
	cp vendor-helm/$(GOOS)-$(GOARCH)/helm vendor-helm/out/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH)
	rm -rf vendor-helm/$(GOOS)-$(GOARCH)
	chmod +x vendor-helm/out/helm-$(HELM_VERSION)-$(GOOS)-$(GOARCH)

dist-common: vendor build-host build-inspector-host copy-all

dist-host: shallow-clean dist-common

get-ginkgo:
	go get github.com/onsi/ginkgo/ginkgo
	cd integration-tests

integration-test-host: get-ginkgo
	@$(MAKE) GOOS=linux tarball
	ginkgo --skip "\[slow\]" -p $(GINKGO_OPTS) -v integration-tests

slow-integration-test-host: get-ginkgo
	@$(MAKE) GOOS=linux tarball
	ginkgo --focus "\[slow\]" -p $(GINKGO_OPTS) -v integration-tests

focus-integration-test-host: get-ginkgo
	@$(MAKE) GOOS=linux tarball
	ginkgo --focus $(FOCUS) $(GINKGO_OPTS) -v integration-tests

docs/generate-kismatic-cli:
	mkdir -p docs/kismatic-cli
	go run cmd/kismatic-docs/main.go
	cp docs/kismatic-cli/kismatic.md docs/kismatic-cli/README.md

docs/update-plan-file-reference.md:
	@$(MAKE) docs/generate-plan-file-reference.md > docs/plan-file-reference.md

docs/generate-plan-file-reference.md:
	@go run cmd/gen-kismatic-ref-docs/*.go -o markdown pkg/install/plan_types.go Plan

version:
	@echo VERSION=$(VERSION)
	@echo GLIDE_VERSION=$(GLIDE_VERSION)
	@echo ANSIBLE_VERSION=$(ANSIBLE_VERSION)
	@echo PROVISIONER_VERSION=$(PROVISIONER_VERSION)

CIRCLE_ENDPOINT=
ifndef CIRCLE_CI_BRANCH
	CIRCLE_ENDPOINT=https://circleci.com/api/v1.1/project/github/apprenda/kismatic
else
	CIRCLE_ENDPOINT=https://circleci.com/api/v1.1/project/github/apprenda/kismatic/tree/$(CIRCLE_CI_BRANCH)
endif

trigger-pr:
	@echo Triggering PR tests
	curl -u $(CIRCLE_CI_TOKEN): -X POST --header "Content-Type: application/json"    \
	  -d '{ "revision": "$(PR_COMMIT)", "build_parameters": {}}'                     \
	  https://circleci.com/api/v1.1/project/github/apprenda/kismatic/tree/pull/$(PR_NUMBER)

trigger-ci-slow-tests:
	@echo Triggering build with slow tests
	curl -u $(CIRCLE_CI_TOKEN): -X POST --header "Content-Type: application/json"    \
	  -d '{"build_parameters": {"RUN_SLOW_TESTS": "true"}}'                          \
	  $(CIRCLE_ENDPOINT)
trigger-ci-focused-tests:
	@echo Triggering focused test
	curl -u $(CIRCLE_CI_TOKEN): -X POST --header "Content-Type: application/json"    \
	  -d "{\"build_parameters\": {\"FOCUS\": \"$(FOCUS)\"}}"                         \
	  $(CIRCLE_ENDPOINT)


text:
using System.Runtime.InteropServices;

namespace ChocolateyInstaller
{
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll")]
        public static extern bool VerifyVersionInfoW(ref OSVERSIONINFOEXW osvi, int flags, long conditionalMask);
        [DllImport("kernel32.dll")]
        public static extern long VerSetConditionMask(long orig, int key, int op);

        public const int VER_MAJORVERSION = 0x2;
        public const int VER_MINORVERSION = 0x1;
        public const int VER_SERVICEPACKMAJOR = 0x20;
        public const int VER_GREATER_EQUAL = 3;
    }
}


text:
Changelog
=========

2.0.0
-----

- **BREAKING**: Drop Python 3.5 and 3.6 support.
- **BREAKING**: On connect, if the server supports STARTTLS, automatically try
  to upgrade the connection. STARTTLS after connect can be turned on or off
  explicitly by passing ``start_tls=True`` or ``start_tls=False`` respectively.
- **BREAKING**: Remove deprecated ``loop`` keyword argument for the SMTP class.
- Change: The ``source_address`` argument now takes a (addr, port) tuple that is
  passed as the ``local_addr`` param to ``asyncio.create_connection``, allowing
  for binding to a specific IP. The new ``local_hostname`` argument that takes
  the value to be sent to the server with the EHLO/HELO message. This behaviour
  more closely matches ``smtplib``.

  In order to not break existing usage, passing a string instead of a tuple to
  ``source_address`` will give a DeprecationWarning, and use the value as it if
  had been passed for ``local_hostname``.

  Thanks @rafaelrds and @davidmcnabnz for raising and contributing work on this
  issue.
- Bugfix: the ``mail_options`` and ``rcpt_options`` arguments to the ``send``
  coroutine no longer cause errors
- Cleanup: Refactored ``SMTP`` parent classes to remove complex inheritance
  structure.
- Cleanup: Switched to ``asyncio.run`` for sync client methods.
- Cleanup: Don't use private email.message.Message policy attribute (instead,
  set an appropriate policy based on message class)

1.1.7
-----

- Security: Fix a possible injection vulnerability (a variant of
  https://consensys.net/diligence/vulnerabilities/python-smtplib-multiple-crlf-injection/)

  Note that in order to exploit this vulnerability in aiosmtplib, the attacker would need
  control of the ``hostname`` or ``source_address`` parameters. Thanks Sam Sanoop @ Snyk
  for bringing this to my attention.
- Bugfix: include CHANGLOG in sdist release
- Type hints: fix type hints for async context exit (credit @JelleZijlstra)

1.1.6
-----

- Bugfix: fix authenticated test failures (credit @P-EB)

1.1.5
-----

- Bugfix: avoid raising ``asyncio.CancelledError`` on connection lost
- Bugfix: allow UTF-8 chars in usernames and password strings
- Feature: allow bytes type args for login usernames and passwords

1.1.4
-----

- Bugfix: parsing comma separated addresses in to header (credit @gjcarneiro)
- Feature: add py.typed file (PEP 561, credit @retnikt)

1.1.3
-----

- Feature: add pause and resume writing methods to ``SMTPProcotol``, via
  ``asyncio.streams.FlowControlMixin`` (thanks @ikrivosheev).

- Bugfix: allow an empty sender (credit @ikrivosheev)

- Cleanup: more useful error message when login called without TLS

1.1.2
-----

- Bugfix: removed ``docs`` and ``tests`` from wheel, they should only be
  in the source distribution.

1.1.1
-----

- Bugfix: Fix handling of sending legacy email API (Message) objects.

- Bugfix: Fix SMTPNotSupported error with UTF8 sender/recipient names
  on servers that don't support SMTPUTF8.

1.1.0
-----

- Feature: Added send coroutine api.

- Feature: Added SMTPUTF8 support for UTF8 chars in addresses.

- Feature: Added connected socket and Unix socket path connection options.

- Feature: Wait until the connect coroutine is awaited to get the event loop.
  Passing an explicit event loop via the loop keyword argument is deprecated
  and will be removed in version 2.0.

- Cleanup: Set context for timeout and connection exceptions properly.

- Cleanup: Use built in start_tls method on Python 3.7+.

- Cleanup: Timeout correctly if TLS handshake takes too long on Python 3.7+.

- Cleanup: Updated SMTPProcotol class and removed StreamReader/StreamWriter
  usage to remove deprecation warnings in 3.8.

- Bugfix: EHLO/HELO if required before any command, not just when using
  higher level commands.

- Cleanup: Replaced asserts in functions with more useful errors (e.g.
  RuntimeError).

- Cleanup: More useful error messages for timeouts (thanks ikrivosheev!),
  including two new exception classes, ``SMTPConnectTimeoutError`` and
  ``SMTPReadTimeoutError``

1.0.6
-----

- Bugfix: Set default timeout to 60 seconds as per documentation
  (previously it was unlimited).

1.0.5
-----

- Bugfix: Connection is now closed if an error response is received
  immediately after connecting.

1.0.4
-----

- Bugfix: Badly encoded server response messages are now decoded to utf-8,
  with error chars escaped.

- Cleanup: Removed handling for exceptions not raised by asyncio (in
  SMTPProtocol._readline)

1.0.3
-----

- Bugfix: Removed buggy close connection on __del__

- Bugfix: Fixed old style auth method parsing in ESMTP response.

- Bugfix: Cleanup transport on exception in connect method.

- Cleanup: Simplified SMTPProtocol.connection_made, __main__

1.0.2
-----

- Bugfix: Close connection lock on on SMTPServerDisconnected

- Feature: Added cert_bundle argument to connection init, connect and starttls
  methods

- Bugfix: Disconnected clients would raise SMTPResponseException: (-1 ...)
  instead of SMTPServerDisconnected

1.0.1
-----

- Bugfix: Commands were getting out of order when using the client as a context
  manager within a task

- Bugfix: multiple tasks calling connect would get confused

- Bugfix: EHLO/HELO responses were being saved even after disconnect

- Bugfix: RuntimeError on client cleanup if event loop was closed

- Bugfix: CRAM-MD5 auth was not working

- Bugfix: AttributeError on STARTTLS under uvloop

1.0.0
-----

Initial feature complete release with stable API; future changes will be
documented here.


text:
from __future__ import unicode_literals

from django.db import models
from django.contrib import admin
from datetime import datetime
from string import join
import os
import uuid

Image_Folder="profilePic/"
class Student(models.Model):
       name=models.CharField(max_length=100)
       gender=models.CharField(max_length=5)
       contactNo=models.CharField(max_length=10)
       image=models.ImageField(upload_to=Image_Folder) #pip install Pillow


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

namespace Server.Networking
{
    public static class PacketHandler
    {
        public static void Handle(byte[] packet, Socket clientSocket)
        {
            short packetLength = BitConverter.ToInt16(packet, 0);
            short packetType = BitConverter.ToInt16(packet, 2);

            Console.WriteLine("Received packet! Length: {0} | Type: {1}", packetLength, packetType);
        }
    }
}


text:
using System;
using System.Runtime.Serialization;

namespace Nenuphar.Exceptions
{
    [Serializable]
    internal class EvenementNotFoundException : Exception
    {
        private Guid id;

        public EvenementNotFoundException()
        {
        }

        public EvenementNotFoundException(Guid id)
        {
            this.id = id;
        }

        public EvenementNotFoundException(string message) : base(message)
        {
        }

        public EvenementNotFoundException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected EvenementNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="/search_engines_page/search_engines_browser_proxy.html">
<link rel="import" href="/search_engines_page/search_engine_dialog.html">
<link rel="import" href="/search_engines_page/search_engines_list.html">
<link rel="import" href="/search_engines_page/omnibox_extension_entry.html">
<link rel="import" href="/settings_shared_css.html">

<dom-module id="settings-search-engines-page">
  <link rel="import" type="css" href="chrome://resources/css/action_link.css">
  <template>

$i18n{searchEnginesDefault}

    <settings-search-engines-list engines="[[defaultEngines]]">
    </settings-search-engines-list>
    <template is="dom-if" if="[[showAddSearchEngineDialog_]]" restamp>
      <settings-search-engine-dialog></settings-search-engine-dialog>
    </template>

$i18n{searchEnginesOther}

    <settings-search-engines-list engines="[[otherEngines]]">

          $i18n{searchEnginesAddSearchEngine}
    </settings-search-engines-list>

    <template is="dom-if" if="[[showExtensionsList_]]">

$i18n{searchEnginesExtension}

      <iron-list id="extensions" class="extension-engines" selectable
          items="[[extensions]]">
        <template>
          <settings-omnibox-extension-entry engine="[[item]]"
              tabindex$="[[tabIndex]]">
          </settings-omnibox-extension-entry>
        </template>
      </iron-list>
    </template>
  </template>

</dom-module>


text:
<?php

/* OCCoreBundle:Core:index.html.twig */
class __TwigTemplate_e82156cf8d6a4be7cb532c45ebb9fa52e4ce534d860f9e79b00a90c21df7e55f extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 2
        $this->parent = $this->loadTemplate("OCCoreBundle::layout.html.twig", "OCCoreBundle:Core:index.html.twig", 2);
        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "OCCoreBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 4
    public function block_title($context, array $blocks = array())
    {
        // line 5
        echo "  Page d'accueil - ";
        $this->displayParentBlock("title", $context, $blocks);
        echo "
";
    }

    // line 8
    public function block_body($context, array $blocks = array())
    {
        // line 9
        echo "

Page d'accueil de notre site

  ";
        // line 13
        echo "  ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session", array()), "flashbag", array()), "get", array(0 => "info"), "method"));
        foreach ($context['_seq'] as $context["_key"] => $context["message"]) {
            // line 14
            echo "
Message flash : ";
            echo twig_escape_filter($this->env, $context["message"], "html", null, true);
            echo "

  ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 16
        echo "
  ";
        // line 18
        echo "
Dernières annonces

  ";
        // line 19
        echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("OCPlatformBundle:Advert:menu", array("limit" => 3)));
        echo "

Derniers messages sur le forum (hypothétique)

    ";
        // line 25
        echo "    Bla bla bla...

";
    }

    public function getTemplateName()
    {
        return "OCCoreBundle:Core:index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  74 => 25,  67 => 19,  64 => 18,  61 => 16,  52 => 14,  47 => 13,  42 => 9,  39 => 8,  32 => 5,  29 => 4,  11 => 2,);
    }
}


text:
/*
 * ilisten
 *    Accept a connection from a single client on specified port.
 *    Echo all data received from the client to stdout.
 *
 * Bryan Clair
 * 2006-13
 */
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
using namespace std;

#define BUFSIZE 512

void fail(const char *str) { perror(str); exit(1); }

//
// main
//    Set up a listening socket and accept one connection.
//
int main(int argc, char *argv[])
{
  if (argc != 2) {
    fprintf(stderr,"usage: ilisten port\n");
    exit(1);
  }

  // create an address structure a passive socket at the requested port
  int err;
  struct addrinfo *host;
  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  hints.ai_flags = AI_PASSIVE;
  err = getaddrinfo(NULL,argv[1],&hints,&host);
  if (err) {
    cerr << argv[1] << " : " << gai_strerror(err) << endl;
    exit(err);
  }

  // create socket
  int serv_sock = socket(host->ai_family,SOCK_STREAM,0);
  if (serv_sock < 0) fail("socket");

  // bind public socket to listening address
  if (bind(serv_sock,host->ai_addr,host->ai_addrlen)) fail("bind");

  // set the socket to listen (allow 5 pending connections)
  if (listen(serv_sock,5)) fail("listen");

  // clean up - free the memory allocated by getaddrinfo
  freeaddrinfo(host);

  cout << "Waiting for a connection on port " << argv[1] << endl;

  // accept one incoming connection
  int new_sock = accept(serv_sock,NULL,NULL);
  if (new_sock < 0) fail("accept");

  cout << "Accepted new connection on fdesc " << new_sock << endl;

  // Promote the socket to a FILE stream for input
  FILE *client_stream = fdopen(new_sock,"r");
  if (client_stream == NULL) fail("fdopen");

  char buf[BUFSIZE];
  while (fgets(buf,BUFSIZE,client_stream) != NULL) {
    cout << buf;      // note: fgets leaves a newline at end of string
  }

  fclose(client_stream);
  cout << "Connection closed" << endl;
}


text:
GameObject::GameObject()
{
}

GameObject::~GameObject()
{
}


text:
def oom(exp):
    if exp == 'm':
        return 1.e-3
    elif exp == 'u':
        return 1.e-6
    elif exp == 'n':
        return 1.e-9
    elif exp == 'p':
        return 1.e-12
    elif exp == 'f':
        return 1.e-15
    elif exp == 'a':
        return 1.e-18
    elif exp == 'z':
        return 1.e-21
    elif exp == 'y':
        return 1.e-24
    elif exp == 'k':
        return 1.e3
    elif exp == 'M':
        return 1.e6
    elif exp == 'G':
        return 1.e9
    elif exp == 'T':
        return 1.e12

def parse_print_file(filename,rise_th,fall_th):
    import re
    f = open(filename)
    comment = re.compile(r"^\*")
    start_value = re.compile(r"^x")
    stop_value = re.compile(r"^y")
    signal_name = re.compile(r"\s+([\w\[\]\(\)]+)\s+$")
    signal_name_wrap = re.compile(r"\s+\+\s+\+\s+([\w\[\]\(\)]+)")
    numbers = re.compile(r"([\d\.]+)([TGMkmunpfazy]?)\s+([\d\.]+)([TGMkmunpfazy]?)")
    found_start = 0
    current_signal_name = ''
    signal_value = 0
    read_numbers = False
    rising_edges = {}
    falling_edges = {}

    rise_check_time = 10.0e-9
    fall_check_time = 10.0e-9
    check_wait_time = 0.7e-9
    epsilon = 0.01
    last_voltage = 0

    for line in f:
        if found_start > 0:
            if found_start < 3:
                found_start += 1
                continue
            elif found_start >= 3 and not read_numbers:
                m = signal_name.match(line)
                if m:
                    current_signal_name = m.group(1)
                    signal_value = 0
                else:
                    m = signal_name_wrap.match(line)
                    if m:
                        current_signal_name += m.group(1)
                    else:
                        read_numbers = True

                found_start += 1
        else:
            read_numbers = False
            if comment.match(line):
                continue
            elif start_value.match(line):
                found_start = 1

        if read_numbers:
            if stop_value.match(line):
                found_start = 0
            else:
                m = numbers.search(line)
                if m:
                    time = float(m.group(1))
                    if m.group(2):
                        time = time*oom(m.group(2))
                    voltage = float(m.group(3))
                    if m.group(4):
                        voltage = voltage*oom(m.group(4))
                    if signal_value == 0:
                        if voltage < fall_th:
                            signal_value = 'R'
                        elif voltage > rise_th:
                            signal_value = 'F'
                    elif signal_value == 'R':
                        if voltage > rise_th:
                            # found a threshold crossing
                            # register a rising edge and go
                            # to check state
                            if not rising_edges.has_key(current_signal_name):
                                rising_edges[current_signal_name] = []
                            rising_edges[current_signal_name].append(time)
                            # go to check state
                            signal_value = 'R_check'
                            rise_check_time = time
                            last_voltage = voltage
                    elif signal_value == 'R_check':
                        # if max. check state time has been reached
                        # check again if the signal has settled high
                        if time > (rise_check_time + check_wait_time):
                            if voltage < rise_th:
                                # drop last rising edge if signal hasn't
                                # settled high
                                del rising_edges[current_signal_name][-1]
                                #print "Dropping rising edge for "+current_signal_name
                                # since last rising edge was a failure, look again for a rising edge
                                signal_value = 'R'
                            else:
                                # go look for a falling edge
                                signal_value = 'F'
                        # if max. check state time has not been reached
                        # check for monotony
                        else:
                            if last_voltage > voltage and (last_voltage - voltage) > epsilon:
                                del rising_edges[current_signal_name][-1]
                                #print "Dropping rising edge for "+current_signal_name
                                signal_value = 'R_wait'
                            else:
                                last_voltage = voltage

                    elif signal_value == 'R_wait':
                        if time > (rise_check_time + check_wait_time):
                            if voltage < fall_th:
                                signal_value = 'R'
                            elif voltage > rise_th:
                                signal_value = 'F'

                    elif signal_value == 'F':
                        if voltage < fall_th:
                            # found a threshold crossing
                            # register a falling edge and go
                            # to check state
                            if not falling_edges.has_key(current_signal_name):
                                falling_edges[current_signal_name] = []
                            falling_edges[current_signal_name].append(time)
                            # go to check state
                            signal_value = 'F_check'
                            fall_check_time = time
                            last_voltage = voltage

                    elif signal_value == 'F_check':
                        # if max. check state time has been reached
                        # check again if the signal has settled low
                        if time > (fall_check_time + check_wait_time):
                            if voltage > fall_th:
                                del falling_edges[current_signal_name][-1]
                                #print "Dropping falling edge for "+current_signal_name
                                # since last falling edge was a failure, look again for a falling edge
                                signal_value = 'F'
                            else:
                                signal_value = 'R'
                        # if max. check state time has not been reached
                        # check for monotony
                        else:
                            if last_voltage < voltage and (voltage - last_voltage) > epsilon:
                                del falling_edges[current_signal_name][-1]
                                #print "Dropping falling edge for "+current_signal_name
                                signal_value = 'F_wait'
                            else:
                                last_voltage = voltage

                    elif signal_value == 'F_wait':
                        if time > (fall_check_time + check_wait_time):
                            if voltage < fall_th:
                                signal_value = 'F'
                            elif voltage > rise_th:
                                signal_value = 'R'

    f.close()

    return rising_edges,falling_edges

def parse_print_file_tran(filename,rise_th,fall_th,slew_lower_rise,slew_upper_rise,slew_lower_fall,slew_upper_fall):
    import re
    f = open(filename)
    comment = re.compile(r"^\*")
    start_value = re.compile(r"^x")
    stop_value = re.compile(r"^y")
    signal_name = re.compile(r"\s+([\w\[\]\(\)]+)\s+$")
    signal_name_wrap = re.compile(r"\s+\+\s+\+\s+([\w\[\]\(\)]+)")
    numbers = re.compile(r"([\d\.]+)([TGMkmunpfazy]?)\s+([\d\.]+)([TGMkmunpfazy]?)(e[+-]\d+)?")
    found_start = 0
    current_signal_name = ''
    signal_value = 0
    read_numbers = False
    rising_edges = {}
    falling_edges = {}

    for line in f:
        if found_start > 0:
            if found_start < 3:
                found_start += 1
                continue
            elif found_start >= 3 and not read_numbers:
                m = signal_name.match(line)
                if m:
                    current_signal_name = m.group(1)
                    signal_value = 0
                else:
                    m = signal_name_wrap.match(line)
                    if m:
                        current_signal_name += m.group(1)
                    else:
                        read_numbers = True

                found_start += 1
        else:
            read_numbers = False
            if comment.match(line):
                continue
            elif start_value.match(line):
                found_start = 1

        if read_numbers:
            if stop_value.match(line):
                found_start = 0
            else:
                m = numbers.search(line)
                if m:
                    time = float(m.group(1))
                    if m.group(2):
                        time = time*oom(m.group(2))
                    voltage = float(m.group(3))
                    if m.group(5):
                        voltage = float(m.group(3)+m.group(5))
                    elif m.group(4):
                        voltage = float(m.group(3))*oom(m.group(4))
                    # if time>1.100e-9 and time < 1.110e-9:
                        # print m.groups()
                        # print voltage

                    if signal_value == 0:
                        if not rising_edges.has_key(current_signal_name):
                            rising_edges[current_signal_name] = []
                        if not falling_edges.has_key(current_signal_name):
                            falling_edges[current_signal_name] = []

                        if voltage < fall_th:
                            signal_value = 'R'
                            # print time,signal_value
                        elif voltage > rise_th:
                            signal_value = 'F'
                            # print time,signal_value
                    elif signal_value == 'R':
                        if voltage > slew_lower_rise:
                            rising_edges[current_signal_name].append(time)
                            signal_value = 'R1'
                            # print time,signal_value
                    elif signal_value == 'R1':
                        if voltage > rise_th:
                            rising_edges[current_signal_name].append(time)
                            signal_value = 'R2'
                            # print time,signal_value
                    elif signal_value == 'R2':
                        if voltage > slew_upper_rise:
                            rising_edges[current_signal_name].append(time)
                            signal_value = 'F'
                            # print time,signal_value

                    elif signal_value == 'F':
                        if voltage < slew_upper_fall:
                            falling_edges[current_signal_name].append(time)
                            signal_value = 'F1'
                            # print time,signal_value
                    elif signal_value == 'F1':
                        if voltage < fall_th:
                            falling_edges[current_signal_name].append(time)
                            signal_value = 'F2'
                            # print time,signal_value
                    elif signal_value == 'F2':
                        if voltage < slew_lower_fall:
                            falling_edges[current_signal_name].append(time)
                            signal_value = 'R'
                            # print time,signal_value

    f.close()
    return rising_edges,falling_edges

if __name__ == '__main__':
    import getopt,sys
    opts, args = getopt.getopt(sys.argv[1:],"")
    filename = args[0]
    rise_th = args[1]
    fall_th = args[2]

    rising_edges = None
    falling_edges = None

    if len(args) > 3:
        slew_lower_rise = args[3]
        slew_upper_rise = args[4]
        slew_lower_fall = args[5]
        slew_upper_fall = args[6]
        rising_edges,falling_edges = parse_print_file_tran(filename,float(rise_th),float(fall_th),float(slew_lower_rise),float(slew_upper_rise),float(slew_lower_fall),float(slew_upper_fall))
    else:
        rising_edges,falling_edges = parse_print_file(filename,float(rise_th),float(fall_th))

    import pickle
    with open(filename+'_rising', 'w') as output:
        pickle.dump(rising_edges,output,pickle.HIGHEST_PROTOCOL)
    with open(filename+'_falling', 'w') as output:
        pickle.dump(falling_edges,output,pickle.HIGHEST_PROTOCOL)

    sys.exit(0)


text:
import {
  CssSelectorGenerated,
  CssSelectorType,
  CssSelectorTypes,
  ElementData,
  ElementSelectorData,
  OPERATOR,
} from "./types.js";
import { OPERATOR_DATA, SELECTOR_PATTERN } from "./constants.js";
import { getElementSelectorsByType } from "./utilities-selectors.js";

/**
 * Creates data describing a specific selector.
 */
export function createElementSelectorData(
  selector: CssSelectorGenerated
): ElementSelectorData {
  return {
    value: selector,
    include: false,
  };
}

/**
 * Creates data describing an element within CssSelector chain.
 */
export function createElementData(
  element: Element,
  selectorTypes: CssSelectorTypes,
  operator: OPERATOR = OPERATOR.NONE
): ElementData {
  const selectors = {};
  selectorTypes.forEach((selectorType) => {
    Reflect.set(
      selectors,
      selectorType,
      getElementSelectorsByType(element, selectorType).map(
        createElementSelectorData
      )
    );
  });
  return {
    element,
    operator: OPERATOR_DATA[operator],
    selectors,
  };
}

/**
 * Constructs selector from element data.
 */
export function constructElementSelector({
  selectors,
  operator,
}: ElementData): CssSelectorGenerated {
  let pattern = [...SELECTOR_PATTERN];
  // `nthoftype` already contains tag
  if (selectors[CssSelectorType.tag] && selectors[CssSelectorType.nthoftype]) {
    pattern = pattern.filter((item) => item !== CssSelectorType.tag);
  }

  let selector = "";
  pattern.forEach((selectorType) => {
    const selectorsOfType = selectors[selectorType] || [];
    selectorsOfType.forEach(({ value, include }) => {
      if (include) {
        selector += value;
      }
    });
  });

  return (operator.value + selector) as CssSelectorGenerated;
}


text:
__author__ = 'amaier1'

from semant import extract_entities


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.google.api.grpc</groupId>
  <artifactId>proto-google-cloud-speech-v2</artifactId>
  <version>4.2.0-SNAPSHOT</version><!-- {x-version-update:proto-google-cloud-speech-v2:current} -->
  <name>proto-google-cloud-speech-v2</name>
  <description>Proto library for google-cloud-speech</description>
  <parent>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-speech-parent</artifactId>
    <version>4.2.0-SNAPSHOT</version><!-- {x-version-update:google-cloud-speech:current} -->
  </parent>
  <dependencies>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.api.grpc</groupId>
      <artifactId>proto-google-common-protos</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.api.grpc</groupId>
      <artifactId>proto-google-iam-v1</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.api</groupId>
      <artifactId>api-common</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
  </dependencies>
</project>


text:
module Spree
  class Printables::Order::PackagingSlipView < Printables::Order::InvoiceView
    def number
      printable.number
    end

    def after_save_actions
    end
  end
end


text:
using UnityEngine;
using System.Collections;

public class GolemWall : MonoBehaviour {

    public float damageFromProjectiles = 2f;

    public float wallLifetime = 8f;
    private float lifeTimer = 0f;

    public delegate void DestroyEvent();
    public event DestroyEvent onDestroy;

	// Update is called once per frame
	void Update () {
        lifeTimer += Time.deltaTime;
        CheckLife();
	}

    void OnCollisionEnter(Collision collision)
    {
        Projectile p = collision.collider.GetComponent<Projectile>();
        if (p != null)
        {
            TakeDamage();
        }
    }

    void TakeDamage()
    {
        // add damage to life timer
        lifeTimer += damageFromProjectiles;
        CheckLife();
    }

    void CheckLife()
    {
        if (lifeTimer >= wallLifetime)
        {
            if (onDestroy != null) onDestroy();
            Destroy(gameObject);
        }
    }
}


text:
namespace Certify.Models.Shared
{
    public class FeedbackReport
    {
        public string EmailAddress { get; set; }
        public string Comment { get; set; }
        public object SupportingData { get; set; }
        public bool IsException { get; set; }
        public string AppVersion { get; set; }
    }
}


text:
module Rack
  module Handler
    class RegisteringMyself
    end

    register :registering_myself, RegisteringMyself
  end
end


text:
current_tab_id = '#publications_nav_item';
updateActiveTab(current_tab_id);

var store_test;

var output = [];

function storeResults(res) {
    output.push(res);
}

function publicationDataHandler(store) {

    function onDone() {
        // Deal with 'output' object here
        // Need to recursively get all the shit we need
        // Sorting output (by descending date)
        output = output.sort(compareDateDesc);

        // Loop counter
        var counter = 0

        function loopArray(arr_elem) {
            // Variable to store element output
            var elem_output = [];

            getAllPublications(store, arr_elem['?name'].value, function (out) {
                // Appending to element output array
                elem_output.push(out);
            }, function onElemDone() {

                // Variables to store unique elements
                var descriptions = [];
                var media_url = [];

                // Store for seen stuff
                var seen_descriptions = new Set();
                var seen_media = new Set();

                // Iterating over all output to extract multiples fields
                // This must be done like this because rdflib.js is trash,
                // and DOES NOT respect SPARQL queries correctly
                for (var idx in elem_output) {
                    var elem = elem_output[idx];

                    // Isolating descriptions
                    if (elem['?predicate'].value === relIRI('hasDescription')) {
                        // Checking if it is already in the set
                        if (!seen_descriptions.has(elem['?desc'].value)) {
                            // Adding to set if not seen
                            seen_descriptions.add(elem['?desc'].value);
                            // Adding element to descriptions array
                            descriptions.push(elem);
                        }
                    }

                    // Isolating media URLs
                    if (elem['?predicate'].value === relIRI('hasMedia')) {
                        // Checking if it already in the set
                        if (!seen_media.has(elem['?obj'].value)) {
                            // Adding to set if not see
                            seen_media.add(elem['?obj'].value);
                            // Adding element to the media array
                            media_url.push(elem['?obj'].value);
                        }
                    }
                }

                descriptions.sort(function(a, b) {
                    return a['?priority'].value - b['?priority'].value;
                });

                // Remapping output array
                var template_elem = elem_output.reduce(templateElemArrayRemap, {});

                // Adding descriptions
                template_elem['description'] = descriptions.map(
                    a => a['?description_text'].value
                );

                // Adding media URL
                template_elem['media_url'] = media_url;

                // Build item HTML with layout engine
                var item_html = layoutPublication(template_elem, arr_elem['?name'].value);

                // Add to page
                $('.entities').append(item_html)

                // Append counter
                counter++;

                // Reset element array
                elem_output = [];

                // If counter is still less than output size, run again
                if (counter < output.length) {
                    loopArray(output[counter]);
                } else {
                    // Last iteration; reload JS
                    $.getScript('dist/js/global_handlers.js');
                }
            });
        }

        loopArray(output[counter]);
    }

    // Getting all WorkExperience instances (for sorting)
    getOfType(store, 'Publication', storeResults, onDone);
}

// Starting page load with graph data handler
loadGraphData(publicationDataHandler);


text:
package com.lagodiuk.gp.symbolic.example;

import com.lagodiuk.gp.symbolic.core.SymbolicRegressionEngine;
import com.lagodiuk.gp.symbolic.core.SymbolicRegressionFunctions;
import com.lagodiuk.gp.symbolic.interpreter.Context;
import com.lagodiuk.gp.symbolic.interpreter.Expression;
import com.lagodiuk.gp.symbolic.interpreter.ExpressionFitness;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Launcher
{
	public static class TestExpressionFitnessX implements ExpressionFitness
	{
		@Override
		public double fitness(Expression expression, Context context)
		{
			double delt = 0;
			for(int i = -20; i < 20; i++)
			{
				context.setVariable("x", i);
				double target = (i * i * i * 5) + i + 10;
				// double target = ((((3 * i * i * i) - (i * i * 7)) + (i * 10)) -
				// 35) * i;
				// double target = i * i;
				// double target = ( i + 100 ) * ( i - 100 );
				// double target = i + 6;
				// double target = (Math.cos((i * Math.PI) / 10) * 10) + i;
				// (2)^(SIN(A2*5)*3)+A2
				// double target = Math.pow(2, Math.sin(i * 5) * 3) + i;
				double x = target - expression.eval(context);
				delt += x * x;
			}
			return delt;
		}
	}
	public static class TestExpressionFitnessXY implements ExpressionFitness
	{
		@Override
		public double fitness(Expression expression, Context context)
		{
			double delt = 0;
			for(int x = -10; x < 10; x += 2)
			{
				context.setVariable("x", x);
				for(int y = -10; y < 10; y += 2)
				{
					context.setVariable("y", y);
					// double target = (x * 5) + (y * (y - 4));
					// double target = x + y;
					// double target = (x * 5) + (y * (y - 4)) + (x * y);
					// double target = x * x;
					double target = (x * x) + (y * y);
					double val = target - expression.eval(context);
					delt += val * val;
				}
			}
			return delt;
		}
	}
	private static <T> List<T> list(T... items)
	{
		return new LinkedList<>(Arrays.asList(items));
	}
	public static double prevFitValue = -1.0;
	public static void main(String[] args)
	{
		final SymbolicRegressionEngine sre = new SymbolicRegressionEngine(
			new TestExpressionFitnessXY(),
			list("x", "y"),
			list(SymbolicRegressionFunctions.values()));

		sre.addIterationListener((SymbolicRegressionEngine engine) ->
		{
			final Expression best = sre.getBestSyntaxTree();
			final double     fit  = sre.getFitness(best);

			if(Double.compare(fit, prevFitValue) != 0)
				System.out.println("Func = " + best.print());
			System.out.println(String.format("%s \t %s", engine.getIteration(), fit));
			prevFitValue = fit;
			if(fit < 10)
				engine.terminate();
		});

		sre.evolve(200);

		System.out.println(sre.getBestSyntaxTree().print());
	}
}


text:
<?php namespace Nathanmac\InstantMessenger\Services;

use Nathanmac\InstantMessenger\Message;

interface MessengerService {

    /**
     * Send message to the external service
     *
     * @param Message $message
     * @return mixed
     */
    public function send(Message $message);

}


text:
cask :v1 => 'prey' do
  version '1.4.2'
  sha256 '0b3c8a82ab2e437c4dd935051206598440093ac4cb74b51bac96bb6313b1c9ef'

  # amazonaws.com is the official download host per the vendor homepage
  url "https://prey-releases.s3.amazonaws.com/node-client/#{version}/prey-mac-#{version}-x64.pkg"
  name 'Prey'
  homepage 'https://preyproject.com'
  license :gpl

  pkg "prey-mac-#{version}-x64.pkg"

  uninstall :pkgutil => 'com.prey.agent',
            :launchctl => 'com.prey.agent'

  caveats <<-EOS.undent
    To complete installation, Prey requires an API key. It may be set
    as an environment variable as follows:

      API_KEY="abcdef123456" brew cask install prey
  EOS
end


text:
(function() {
  function searchOverlay(query, caseInsensitive) {
    var startChar;
    if (typeof query == "string") {
      startChar = query.charAt(0);
      query = new RegExp("^" + query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"),
                         caseInsensitive ? "i" : "");
    } else {
      query = new RegExp("^(?:" + query.source + ")", query.ignoreCase ? "i" : "");
    }
    if (typeof query == "string") return {token: function(stream) {
      if (stream.match(query)) return "searching";
      stream.next();
      stream.skipTo(query.charAt(0)) || stream.skipToEnd();
    }};
    return {token: function(stream) {
      if (stream.match(query)) return "searching";
      while (!stream.eol()) {
        stream.next();
        if (startChar)
          stream.skipTo(startChar) || stream.skipToEnd();
        if (stream.match(query, false)) break;
      }
    }};
  }

  function SearchState() {
    this.posFrom = this.posTo = this.query = null;
    this.overlay = null;
  }
  function getSearchState(cm) {
    return cm.state.search || (cm.state.search = new SearchState());
  }
  function queryCaseInsensitive(query) {
    return typeof query == "string" && query == query.toLowerCase();
  }
  function getSearchCursor(cm, query, pos) {
    // Heuristic: if the query string is all lowercase, do a case insensitive search.
    return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
  }
  function dialog(cm, text, shortText, deflt, f) {
    if (cm.openDialog) cm.openDialog(text, f, {value: deflt, bottom: true});
    else f(prompt(shortText, deflt));
  }
  function confirmDialog(cm, text, shortText, fs) {
    if (cm.openConopenDialogfirm) cm.openConfirm(text, fs, {bottom: true});
    else if (confirm(shortText)) fs[0]();
  }
  function parseQuery(query) {
    var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
    return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
  }
  var queryDialog =
    'Search: <input type="text" style="width: 10em"/> (Use /re/ syntax for regexp search)';
  function doSearch(cm, rev) {
    var state = getSearchState(cm);
    if (state.query) return findNext(cm, rev);
    dialog(cm, queryDialog, "Search for:", cm.getSelection(), function(query) {
      cm.operation(function() {
        if (!query || state.query) return;
        state.query = parseQuery(query);
        cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
        state.overlay = searchOverlay(state.query);
        cm.addOverlay(state.overlay);
        state.posFrom = state.posTo = cm.getCursor();
        findNext(cm, rev);
      });
    });
  }
  function findNext(cm, rev) {cm.operation(function() {
    var state = getSearchState(cm);
    var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
    if (!cursor.find(rev)) {
      cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
      if (!cursor.find(rev)) return;
    }
    cm.setSelection(cursor.from(), cursor.to());
    cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
    state.posFrom = cursor.from(); state.posTo = cursor.to();
  });}
  function clearSearch(cm) {cm.operation(function() {
    var state = getSearchState(cm);
    if (!state.query) return;
    state.query = null;
    cm.removeOverlay(state.overlay);
  });}

  var replaceQueryDialog =
    'Replace: <input type="text" style="width: 10em"/> (Use /re/ syntax for regexp search)';
  var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
  var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
  function replace(cm, all) {
    dialog(cm, replaceQueryDialog, "Replace:", cm.getSelection(), function(query) {
      if (!query) return;
      query = parseQuery(query);
      dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
        if (all) {
          cm.operation(function() {
            for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
              if (typeof query != "string") {
                var match = cm.getRange(cursor.from(), cursor.to()).match(query);
                cursor.replace(text.replace(/\$(\d)/, function(_, i) {return match[i];}));
              } else cursor.replace(text);
            }
          });
        } else {
          clearSearch(cm);
          var cursor = getSearchCursor(cm, query, cm.getCursor());
          var advance = function() {
            var start = cursor.from(), match;
            if (!(match = cursor.findNext())) {
              cursor = getSearchCursor(cm, query);
              if (!(match = cursor.findNext()) ||
                  (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
            }
            cm.setSelection(cursor.from(), cursor.to());
            cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
            confirmDialog(cm, doReplaceConfirm, "Replace?",
                          [function() {doReplace(match);}, advance]);
          };
          var doReplace = function(match) {
            cursor.replace(typeof query == "string" ? text :
                           text.replace(/\$(\d)/, function(_, i) {return match[i];}));
            advance();
          };
          advance();
        }
      });
    });
  }

  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  CodeMirror.commands.findNext = doSearch;
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  CodeMirror.commands.clearSearch = clearSearch;
  CodeMirror.commands.replace = replace;
  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
})();


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ForgedSoftware.Measurement.Number;

namespace ForgedSoftware.Measurement.Entities {

	/// <summary>
	/// A dimension definition is the definition of a dimensioned,
	/// measurable value, that can be obtained via direct observation of the world.
	///
	/// A DimensionDefinition should not be confused with a Dimension. The former
	/// is the definition of something that can be measured in the world. The latter
	/// is a specific quanitifier for part of an actual observation or quantity.
	/// </summary>
	/// <example>
	/// Examples of dimensions are: length, mass, acceleration, time
	/// </example>
	public class DimensionDefinition : Entity {

		public DimensionDefinition() {
			Units = new List<Unit>();
			OtherNames = new List<string>();
			OtherSymbols = new List<string>();
			Derived = new List<Dimension>();
		}

		// Basic Properties
		public string Name { get; set; }
		public List<string> OtherNames { get; private set; }
		public string Symbol { get; set; }
		public List<string> OtherSymbols { get; private set; }
		public string BaseUnitName { get; set; }
		public bool Vector { get; set; }
		public bool IsDimensionless { get; set; }
		public string InheritedUnits { get; set; }

		// Calculated Properties
		public List<Unit> Units { get; private set; }
		public Unit BaseUnit { get; set; }

		#region Derived

		public string DerivedString { get; set; }
		public List<Dimension> Derived { get; private set; }

		public bool IsDerived() {
			return Derived.Count > 0;
		}

		public void UpdateDerived() {
			Derived.Clear();
			if (string.IsNullOrEmpty(DerivedString)) {
				return;
			}
			foreach (Match match in Regex.Matches(DerivedString, @"(^\w+|([\*|/])(\w+))")) {
				if (match.Success) {
					string type;
					string systemName;
					if (!string.IsNullOrEmpty(match.Groups[3].Value)) {
						type = match.Groups[2].Value;
						systemName = match.Groups[3].Value;
					} else {
						type = "*";
						systemName = match.Groups[1].Value;
					}
					if (systemName != "1") {
						Unit baseUnit = MeasurementCorpus.FindBaseUnit(systemName);
						if (baseUnit == null) {
							throw new Exception("All derived entries must be the name of a dimension or the '1' placeholder");
						}
						if (type != "*" && type != "/") {
							throw new Exception("Derived divider is not valid - must be either '*' or '/'");
						}
						int power = (type == "*") ? 1 : -1;
						Derived.Add(new Dimension(baseUnit, power));
					}
				}
			}
			var computedValue = new DoubleWrapper(1);
			Derived = Derived.SimpleSimplify(ref computedValue);
		}

		#endregion

	}
}


text:
package com.thebluealliance.androidclient.helpers;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class AwardHelperTest {

    @Test
    public void testCreateEventKey() {
        String eventKey = "2015cthar";
        int awardEnum = 12;

        String awardKey = AwardHelper.createAwardKey(eventKey, awardEnum);
        assertEquals("2015cthar:12", awardKey);
    }

    @Test
    public void testValidateKey() {
        String[] validKeys = new String[]{"2015cthar:12", "2015necmp:1"};
        String[] invalidKeys = new String[]{"asldf:5", "2015cthar:foo", "2015cthar", null};

        for (String key : validKeys) {
            assertTrue(AwardHelper.validateAwardKey(key));
        }

        for (String key : invalidKeys) {
            assertFalse(AwardHelper.validateAwardKey(key));
        }
    }
}


text:
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace MediaLive
{
namespace Model
{
  enum class HlsManifestCompression
  {
    NOT_SET,
    GZIP,
    NONE
  };

namespace HlsManifestCompressionMapper
{
AWS_MEDIALIVE_API HlsManifestCompression GetHlsManifestCompressionForName(const Aws::String& name);

AWS_MEDIALIVE_API Aws::String GetNameForHlsManifestCompression(HlsManifestCompression value);
} // namespace HlsManifestCompressionMapper
} // namespace Model
} // namespace MediaLive
} // namespace Aws


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView
            android:id="@+id/processCount"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            tools:text="@string/process_count" />

        <TextView
            android:id="@+id/memoryStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            tools:text="@string/memory_status" />

    </LinearLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/processList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fastScrollEnabled="true"
            android:scrollbars="vertical" />

    </android.support.v4.widget.SwipeRefreshLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <Button
            android:id="@+id/selectAll"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:backgroundTint="@color/colorPrimary"
            android:text="@string/select_all"
            android:textColor="@android:color/white" />

        <Button
            android:id="@+id/selectOthers"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:backgroundTint="@color/colorPrimary"
            android:text="@string/select_others"
            android:textColor="@android:color/white" />

        <Button
            android:id="@+id/killAllSelect"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:backgroundTint="@color/colorPrimary"
            android:text="@string/kill_all_select"
            android:textColor="@android:color/white" />
    </LinearLayout>

</LinearLayout>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.EditAndContinue
{
    internal struct RudeEditDiagnostic
    {
        public readonly RudeEditKind Kind;
        public readonly TextSpan Span;
        public readonly ushort SyntaxKind;
        public readonly string[] Arguments;

        internal RudeEditDiagnostic(RudeEditKind kind, TextSpan span, SyntaxNode node = null, string[] arguments = null)
        {
            this.Kind = kind;
            this.Span = span;
            this.SyntaxKind = (ushort)(node != null ? node.RawKind : 0);
            this.Arguments = arguments;
        }

        internal Diagnostic ToDiagnostic(SyntaxTree tree)
        {
            var descriptor = RudeEditDiagnosticDescriptors.GetDescriptor(this.Kind);
            return Diagnostic.Create(descriptor, tree.GetLocation(this.Span), Arguments);
        }
    }
}


text:
authors:
- Arne Semsrott
date: 2019-06-18
image:
  src: /files/jobs/fds1.png
  title: "FragDenStaat-Logo"
  license:
  license_url:
tags:
- FragDenStaat
- In eigener Sache
- OKF
type: post
layout: post
card: true
published: true
featured: blue
title: "Neue Stelle bei FragDenStaat: Wir suchen Projektmanager*in! (75-100%, ab August 2019)"
---

## Wer wir sind

FragDenStaat ist das Portal für Informationsfreiheit in Deutschland. Seit 2011 ermöglicht es allen Menschen, einfach und transparent Informationen von Behörden zu befreien – mit technischen Tools, Kampagnen, Klagen und journalistischer Berichterstattung.

Informationsfreiheit ist uns ein Herzensanliegen. FragDenStaat ist ursprünglich als ehrenamtliches Projekt gestartet und wird inzwischen von einem kleinen Team getragen. Damit erreichen wir deutlich mehr Menschen als früher. Unsere Entwicklung hat aber gerade erst angefangen: Wir haben viel Raum für neue Ideen, experimentieren gerne und suchen dafür Verstärkung!

Trägerverein von FragDenStaat ist der gemeinnützige Verein Open Knowledge Foundation Deutschland mit Sitz in Berlin, der sich für offenes Wissen, Transparenz und Beteiligung einsetzt. Unsere Arbeit ist unabhängig, überparteilich und interdisziplinär.

## Wen wir suchen

Für das Projektmanagement sind wir auf der Suche nach einer politikinteressierten Persönlichkeit, die Lust hat, gemeinsam mit uns FragDenStaat weiterzuentwickeln. Insbesondere in den Bereichen Community und Fundraising wollen wir das Berliner Kernteam - Stefan, Arne, Lea und Sebastian - verstärken.

In diesen Bereichen wirst Du vor allem arbeiten:

- Entwicklung und Umsetzung einer Strategie zum Community-Management von FragDenStaat sowie zur Einbindung von Ehrenamtlichen

- Weiterentwicklung der Strategie zur Gewinnung von Fördermitgliedern sowie zum Stiftungsfundraising

- Bearbeitung von externen Anfragen, zum Beispiel von Behörden und Partner*innen

- Kommunikation mit der Community von FragDenStaat

- Unterstützung bei der Entwicklung von Kampagnen und Kooperationen mit NGOs und Journalist*innen, darunter der Volksentscheid Transparenz

Wir möchten die anfallenden Tätigkeiten und auch die wöchentliche Arbeitszeit so arrangieren, dass sie zu Dir passen.

## Profil

Bei uns gibt es viel Raum für Deine eigenen Ideen. Das Projekt lebt von dem starkem Engagement und Einsatz aller Teammitglieder. Dementsprechend wünschen wir uns von Dir, dass Du eigenständig arbeitest, gerne Verantwortung übernimmst und ein gutes Zeitmanagement mitbringst. Das wichtigste Handwerk für das Projektmanagement bei FragDenStaat ist Kommunikation. Wenn Du Freude daran hast, mit anderen Menschen in Kontakt zu treten, bist Du bei uns genau richtig. Toll wäre, wenn Du eine grundsätzliche Offenheit gegenüber Technik mitbringst.
Was wir bieten

Wir bieten Dir:

- die Möglichkeit, mit viel Gestaltungsspielraum eigene Ideen umzusetzen

- enge Zusammenarbeit mit dem hauptamtlichen Team von FragDenStaat

- flexible Arbeitszeiten

- dazuzulernen in den Bereichen, die Dir wichtig sind

- ein sehr spannendes Arbeitsumfeld bei der Open Knowledge Foundation in Berlin

- eine gute Büroatmosphäre, gratis Getränke und eine oft aufgefüllte Snackbox

- eine Vergütung nach [TV-L E 13 Stufe 1](https://oeffentlicher-dienst.info/tv-l/allg/)

Die Stelle ist zum **1. August 2019** zu besetzen. Sie ist derzeit aus finanziellen Gründen auf ein Jahr befristet. Wir streben aber an, die Stelle dauerhaft zu besetzen.

Wir freuen uns insbesondere über die Bewerbungen von Frauen, Menschen mit Migrationshintergrund und Menschen anderer Gruppen, die in der IT-Welt unterrepräsentiert sind. Von Bewerbungsfotos und Angaben zu Alter und Familienstand bitten wir abzusehen.

Bitte schicke uns Deine Bewerbung inkl. möglichem Beginn und bevorzugtem Stundenumfang **bis zum 23. Juni 2019** per E-Mail an arne.semsrott@okfn.de, gerne auch PGP-verschlüsselt. Formalien interessieren uns wenig. Wir möchten vor allem wissen, woran Du Interesse hast, wofür Du dich engagierst, was Du gut kannst, was Dich bewegt und motiviert. Zeugnisse brauchen wir nicht.


text:
package org.efaps.esjp.products;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.Dimension;
import org.efaps.admin.datamodel.Dimension.UoM;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.CachedMultiPrintQuery;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CIProducts;
import org.efaps.ui.wicket.util.EFapsKey;
import org.efaps.util.EFapsException;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 *
 */
@EFapsUUID("82271caf-5d4e-4ec9-bb99-8cbfaff5f8a7")
@EFapsApplication("eFapsApp-Products")
public abstract class BOM_Base
{

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @return new empty Return
     * @throws EFapsException on error
     */
    public Return insertTrigger(final Parameter _parameter)
        throws EFapsException
    {
        final Map<?, ?> values = (HashMap<?, ?>) _parameter.get(ParameterValues.NEW_VALUES);
        final Attribute attr = _parameter.getInstance().getType().getAttribute("To");

        final QueryBuilder queryBldr = new QueryBuilder(CIProducts.ProductAbstract);
        queryBldr.addWhereAttrEqValue(CIProducts.ProductAbstract.ID, (Object[]) values.get(attr));
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIProducts.ProductAbstract.Dimension);
        Dimension dimension = null;
        if (multi.execute()) {
            multi.next();
            dimension = Dimension.get(multi.<Long>getAttribute(CIProducts.ProductAbstract.Dimension));
        }
        if (dimension != null) {
            final Update update = new Update(_parameter.getInstance());
            update.add(CIProducts.BOMAbstract.UoM, dimension.getBaseUoM().getId());
            update.execute();
        }
        return new Return();
    }

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @return new empty Return
     * @throws EFapsException on error
     */
    public Return editBOMQuantity(final Parameter _parameter)
        throws EFapsException
    {
        @SuppressWarnings("unchecked") final Map<String, String> oidMap = (Map<String, String>) _parameter
                        .get(ParameterValues.OIDMAP4UI);
        final String[] rowKeys = _parameter.getParameterValues(EFapsKey.TABLEROW_NAME.getKey());
        final String[] quantity = _parameter.getParameterValues("quantity");
        for (int i = 0; i < rowKeys.length; i++) {
            final Instance inst = Instance.get(oidMap.get(rowKeys[i]));
            final Update update = new Update(inst);
            update.add(CIProducts.BOMAbstract.Quantity, quantity[i]);
            update.execute();
        }
        return new Return();
    }

    public List<ProductBOMBean> getBOMProducts(final Parameter _parameter,
                                               final Instance _prodInst,
                                               final BigDecimal _quantity,
                                               final UoM _uoM)
        throws EFapsException
    {
        BigDecimal quantity = _quantity;
        // if an uom is given ensure that is normed on base
        if (_uoM != null && !_uoM.equals(_uoM.getDimension().getBaseUoM())) {
            quantity = quantity.multiply(new BigDecimal(_uoM.getDenominator()))
                            .setScale(8, BigDecimal.ROUND_HALF_UP)
                            .divide(new BigDecimal(_uoM.getNumerator()), BigDecimal.ROUND_HALF_UP);

        }
        return getBOMProducts(_parameter, _prodInst, quantity);
    }

    public List<ProductBOMBean> getBOMProducts(final Parameter _parameter,
                                               final Instance _prodInst,
                                               final BigDecimal _quantity)
        throws EFapsException
    {
        final List<ProductBOMBean> ret = new ArrayList<>();

        final QueryBuilder queryBldr = new QueryBuilder(CIProducts.ProductionBOM);
        queryBldr.addWhereAttrEqValue(CIProducts.ProductionBOM.From, _prodInst);
        final CachedMultiPrintQuery multi = queryBldr.getCachedPrint4Request();
        final SelectBuilder selBOMProd = SelectBuilder.get().linkto(CIProducts.ProductionBOM.To);
        final SelectBuilder selBOMProdInst = new SelectBuilder(selBOMProd).instance();
        final SelectBuilder selBOMProdName = new SelectBuilder(selBOMProd).attribute(CIProducts.ProductAbstract.Name);
        final SelectBuilder selBOMProdDescr = new SelectBuilder(selBOMProd)
                        .attribute(CIProducts.ProductAbstract.Description);
        final SelectBuilder selBOMProdUoM = new SelectBuilder(selBOMProd)
                        .attribute(CIProducts.ProductAbstract.DefaultUoM);
        multi.addSelect(selBOMProdInst, selBOMProdName, selBOMProdDescr, selBOMProdUoM);
        multi.addAttribute(CIProducts.BOMAbstract.Quantity, CIProducts.BOMAbstract.UoM);
        multi.execute();
        while (multi.next()) {
            final ProductBOMBean bean = getProductBOMBean(_parameter);
            ret.add(bean);
            bean.setInstance(multi.<Instance>getSelect(selBOMProdInst))
                            .setName(multi.<String>getSelect(selBOMProdName))
                            .setDescription(multi.<String>getSelect(selBOMProdDescr));

            final Long defaultUoMID = multi.<Long>getSelect(selBOMProdUoM);
            final UoM uom = Dimension.getUoM(multi.<Long>getAttribute(CIProducts.BOMAbstract.UoM));
            BigDecimal quantity = multi.getAttribute(CIProducts.BOMAbstract.Quantity);

            if (defaultUoMID != null) {
                final UoM defaultUoM = Dimension.getUoM(defaultUoMID);
                if (!defaultUoM.equals(uom)) {
                    quantity = quantity.multiply(new BigDecimal(uom.getNumerator()))
                                    .setScale(8, BigDecimal.ROUND_HALF_UP)
                                    .divide(new BigDecimal(uom.getDenominator()), BigDecimal.ROUND_HALF_UP);
                    quantity = quantity.multiply(new BigDecimal(defaultUoM.getDenominator()))
                                    .setScale(8, BigDecimal.ROUND_HALF_UP)
                                    .divide(new BigDecimal(defaultUoM.getNumerator()), BigDecimal.ROUND_HALF_UP);
                }
                bean.setUoM(defaultUoM);
            } else {
                if (!uom.equals(uom.getDimension().getBaseUoM())) {
                    quantity = quantity.multiply(new BigDecimal(uom.getNumerator()))
                                    .setScale(8, BigDecimal.ROUND_HALF_UP)
                                    .divide(new BigDecimal(uom.getDenominator()), BigDecimal.ROUND_HALF_UP);
                    bean.setUoM(uom.getDimension().getBaseUoM());
                } else {
                    bean.setUoM(uom);
                }
            }
            bean.setQuantity(quantity.multiply(_quantity));
        }
        return ret;
    }

    protected ProductBOMBean getProductBOMBean(final Parameter _parameter)
    {
        return new ProductBOMBean();
    }

    public static class ProductBOMBean
    {

        private Instance instance;

        private String name;

        private String description;

        private UoM uoM;

        private BigDecimal quantity;

        /**
         * Getter method for the instance variable {@link #instance}.
         *
         * @return value of instance variable {@link #instance}
         */
        public Instance getInstance()
        {
            return this.instance;
        }

        /**
         * Setter method for instance variable {@link #instance}.
         *
         * @param _instance value for instance variable {@link #instance}
         */
        public ProductBOMBean setInstance(final Instance _instance)
        {
            this.instance = _instance;
            return this;
        }

        /**
         * Getter method for the instance variable {@link #name}.
         *
         * @return value of instance variable {@link #name}
         */
        public String getName()
        {
            return this.name;
        }

        /**
         * Setter method for instance variable {@link #name}.
         *
         * @param _name value for instance variable {@link #name}
         */
        public ProductBOMBean setName(final String _name)
        {
            this.name = _name;
            return this;
        }

        /**
         * Getter method for the instance variable {@link #description}.
         *
         * @return value of instance variable {@link #description}
         */
        public String getDescription()
        {
            return this.description;
        }

        /**
         * Setter method for instance variable {@link #description}.
         *
         * @param _description value for instance variable {@link #description}
         */
        public ProductBOMBean setDescription(final String _description)
        {
            this.description = _description;
            return this;
        }

        /**
         * Getter method for the instance variable {@link #uoM}.
         *
         * @return value of instance variable {@link #uoM}
         */
        public UoM getUoM()
        {
            return this.uoM;
        }

        /**
         * Setter method for instance variable {@link #uoM}.
         *
         * @param _uoM value for instance variable {@link #uoM}
         */
        public ProductBOMBean setUoM(final UoM _uoM)
        {
            this.uoM = _uoM;
            return this;
        }

        /**
         * Getter method for the instance variable {@link #quantity}.
         *
         * @return value of instance variable {@link #quantity}
         */
        public BigDecimal getQuantity()
        {
            return this.quantity;
        }

        /**
         * Setter method for instance variable {@link #quantity}.
         *
         * @param _quantity value for instance variable {@link #quantity}
         */
        public ProductBOMBean setQuantity(final BigDecimal _quantity)
        {
            this.quantity = _quantity;
            return this;
        }

    }
}


text:
<?xml-stylesheet href="css3-modsel-168.css" type="text/css"?>
<test>

This test has .

(If the previous line just reads "This test has ." then this test has failed.)

</test>