text:
/*
	Implementation of the 'Rig' Password Hashing Scheme
	September 25, 2014
	Author: Arpan Jati (arpanj@iiitd.ac.in)
	Rig : v2.0
*/

#include <stdlib.h>
#include <malloc.h>
#include <math.h>
#include <stdint.h>
#include <memory.h>
#include "rig.h"
#include "constants.h"

/* Perform the setup-phase (topmost layer) of RIG.

ChainingValue is the output of the H1 (called alpha). This value is expanded
in this phase by using the chosen function H2.

AlphaSet is the set of all values of array 'a' and,
KeySet is the set of all values of array 'k'.

One can note that in this phase the XOR difference of AlphaSet and KeySet
is the ChainingValue. This is intended. The following layers in the Iterative
Transformation phase does not have this relation.

NOTE: The previous version of this function was called 'PerformLayer_Zero', it
is renamed to make the naming consistent with the design document.

The previous versions of this method used 'memcpy' for faster memory writes,
as the algorithm is primarily memory bound. In this version we have removed
those in favour of a more concise and clean code. The optimizers in most
compilers work really well and the performance difference is negligible.
We tried AVX-2 intrinsics like _mm256_stream_si256, _mm256_stream_load_si256,
_mm256_xor_si256, gather instruction and several other techniques to no avail
as the algorithm is primarily DRAM bandwidth and latency bound and hence the
performance difference is minimal.

*/

int PerformSetupPhase(uint8_t *ChainingValue, AlphaData* AlphaSet,
	HashData* KeySet, uint64_t M, uint64_t * Count)
{
	uint64_t i = 0, j = 0, inIdx = 1;
	const uint64_t Hlen = H_BYTES_OUT / 8;

	uint64_t Hin[LAYER_LENGTH / 8];

	uint64_t t[Hlen];

	uint64_t AlphaData[Hlen];
	uint8_t Count_Bytes[CNT_BYTES];

	memcpy(AlphaData, ChainingValue, H_BYTES_OUT);

	for (i = 0; i < M; i++)	{
		inIdx = 1;
		LongToBytes((++(*Count)), Count_Bytes);
		Hin[0] = ((uint64_t*)Count_Bytes)[0];

		uint64_t* a = (uint64_t*)AlphaSet[i];
		uint64_t* k = (uint64_t*)KeySet[i];

		if (i == 0)	{
			memcpy(t, PI_CONST, H_BYTES_OUT); // Load Pi
		}

		for (j = 0; j < Hlen; j++) {
			a[j] = AlphaData[j] ^ t[j];
			Hin[inIdx++] = a[j];

			if (j < Hlen - 1) {
				Hin[Hlen + inIdx - 1] = t[j];
				k[j] = t[j];
			}
		}
		HASH_LAYER(Hin, t);
	}

	memcpy(ChainingValue, t, H_BYTES_OUT);

	return SUCCESS;
}

/*
Perform the Iterative Transformation phase of RIG (subsequent layers)

In this phase the KeySet and AlphaSet is updated iteratively.

Bit-reversal permutation is performed on indices of 'k',
For implementation, we are using Catena styled alternate row bit-permutation,
because it does not uses one extra array for memory, and also causes less
memory accesses, leading to faster runtimes (10-15% depending on
the number of iterations).

*/
int PerformIteration(AlphaData* AlphaSet, HashData* KeySet,
	uint8_t* ChainingValue,	uint64_t M, uint64_t m_cost,
	uint64_t * Count, uint64_t row)
{
	uint64_t i = 0, address = 0, j = 0, k = 0, inIdx = 1;

	const uint64_t Hlen = H_BYTES_OUT / 8;

	uint64_t Hin[LAYER_LENGTH / 8];

	uint64_t t[Hlen]; // Temp

	uint8_t Count_Bytes[CNT_BYTES];

	for (i = 0; i < M; i++)	{

		inIdx = 1;
		LongToBytes((++(*Count)), Count_Bytes);
		Hin[0] = ((uint64_t*)Count_Bytes)[0];

		// Perform bit-reversal address generation on the data.
		address = (row & 1) ? i : (BitReverse64(i) >> (64 - m_cost));

		uint64_t* a = (uint64_t*)AlphaSet[i];
		uint64_t* k = (uint64_t*)KeySet[address];

		if (i == 0)	{
			memcpy(t, ChainingValue, H_BYTES_OUT);
		}

		for (j = 0; j < Hlen; j++) {
			a[j] ^= t[j];
			Hin[inIdx++] = a[j];

			if (j < Hlen - 1) {
				k[j] ^= t[j];
				Hin[Hlen + inIdx - 1] = k[j];
			}
		}

		HASH_LAYER(Hin, t);
	}

	memcpy(ChainingValue, t, H_BYTES_OUT);

	return SUCCESS;
}

size_t getAlphaDataLength(size_t inLen, size_t sLen)
{
	return inLen + sLen + (CNT_BYTES * 4);
}

// Prepare alpha from password and salt.
void PrepareAlphaData(uint8_t* input, size_t inLen, uint8_t* salt,
	size_t sLen, uint64_t t_cost, uint64_t outputBits, uint8_t* bytes)
{
	int count = 0;

	uint8_t _T[CNT_BYTES];
	uint8_t _OutputBits[CNT_BYTES];

	uint8_t _PWLen[CNT_BYTES];
	uint8_t _SaltLen[CNT_BYTES];

	LongToBytes(t_cost, _T);
	LongToBytes(outputBits, _OutputBits);
	LongToBytes(inLen, _PWLen);
	LongToBytes(sLen, _SaltLen);

	memcpy(bytes, input, inLen);
	memcpy(bytes + inLen, _PWLen, CNT_BYTES);
	memcpy(bytes + inLen + CNT_BYTES, salt, sLen);
	memcpy(bytes + inLen + sLen + CNT_BYTES, _SaltLen, CNT_BYTES);
	memcpy(bytes + inLen + sLen + CNT_BYTES * 2, _T, CNT_BYTES);
	memcpy(bytes + inLen + sLen + CNT_BYTES * 3, _OutputBits, CNT_BYTES);
}

int PHS_FULL(void *out, size_t outlen, const void *in, size_t inlen,
	const void *salt, size_t saltlen, uint32_t t_cost, uint32_t m_cost)
{
	uint32_t i, ret = SUCCESS;

	if (t_cost < 1) return ERROR_TIME_LESS;
	if (m_cost < 1) return ERROR_COST_LESS;
	if (m_cost > 31) return ERROR_COST_MORE;
	if ((saltlen > 256) || (saltlen < 0)) return ERROR_SALTLEN_INVALID;

	uint8_t* alpha = (uint8_t *)malloc(H_BYTES_OUT);
	size_t alphaDataLength = getAlphaDataLength(inlen, saltlen);
	uint8_t* alphaData = (uint8_t *)malloc(alphaDataLength);

	PrepareAlphaData((uint8_t*)in, inlen, (uint8_t*)salt, saltlen,
		t_cost, (outlen * 8), alphaData);

	HASH_INPUT(alphaData, alphaDataLength, alpha);
	free(alphaData);

	uint64_t __M = ((uint64_t)1 << m_cost);

	uint8_t* ChainingValue = (uint8_t*)malloc(H_BYTES_OUT);

	memcpy(ChainingValue, alpha, H_BYTES_OUT);

	// TODO: The large mallocs in the lines below may fail if there isn't enough memory.
	// Need to put a alloc-check.

	HashData* KeySet = (HashData*)malloc((size_t)(H_BYTES_KS * __M));
	AlphaData* AlphaSet = (AlphaData*)malloc((size_t)(H_BYTES_OUT * __M));

	uint64_t Count = 0;
	uint64_t M = ((uint64_t)1 << m_cost);

	ret = PerformSetupPhase(ChainingValue, AlphaSet, KeySet, M, &Count);
	if (ret != SUCCESS) return ret;

	for (i = 0; i < t_cost; i++)
	{
		ret = PerformIteration(AlphaSet, KeySet, ChainingValue, M, m_cost, &Count, i);
		if (ret != SUCCESS) return ret;
	}

	uint8_t CNT[CNT_BYTES];
	LongToBytes(++Count, CNT);

	uint8_t _M[CNT_BYTES];
	LongToBytes(M, _M);

	uint8_t *H3_in = (uint8_t *)malloc(CNT_BYTES * 2 + H_BYTES_OUT + saltlen);

	memcpy(H3_in, CNT, CNT_BYTES);
	memcpy(H3_in + CNT_BYTES, ChainingValue, H_BYTES_OUT);
	memcpy(H3_in + CNT_BYTES + H_BYTES_OUT, salt, saltlen);
	memcpy(H3_in + CNT_BYTES + H_BYTES_OUT + saltlen, _M, CNT_BYTES);

	uint8_t H3_Out[H3_BYTES_OUT];

	HASH_OUTPUT(H3_in, CNT_BYTES * 2 + H_BYTES_OUT + saltlen, H3_Out);

	free(H3_in);
	free(KeySet);
	free(AlphaSet);
	free(ChainingValue);
	free(alpha);

	if (outlen <= H3_BYTES_OUT)
	{
		for (i = 0; i < outlen; i++)
		{
			((uint8_t*)out)[i] = H3_Out[i];
		}
	}
	else
	{
		return ERROR_INVALID_OUT_HLEN;
	}

	return SUCCESS;
}

int PHS(void *out, size_t outlen, const void *in, size_t inlen,
	const void *salt, size_t saltlen, unsigned int t_cost, unsigned int m_cost)
{
	return PHS_FULL(out, outlen, in, inlen, salt, saltlen, t_cost, m_cost);
}

const char * GetError(int Error)
{
	switch (Error)
	{

	case ERROR_TIME_LESS:
		return "Time Cost should be greater than 0";

	case ERROR_COST_LESS:
		return "Memory cost should be greater than 0";

	case ERROR_COST_MORE:
		return "Memory cost should be less than or equal to 32";

	case ERROR_SALTLEN_INVALID:
		return "Salt Length should be greater than 0, and less than 256 bytes";

	case ERROR_COST_MULTIPLE:
		return "Memory Cost is not a power of 2";

	case ERROR_INVALID_OUT_HLEN:
		return "Invalid Output Hash Length";

	default:
		return "Undefined Error";
	}
}

// Kind of redundant on Little-Endian platforms.
// TODO: Fix with platform check.
void LongToBytes(uint64_t val, uint8_t* b)
{
	b[7] = (uint8_t)((val >> 56) & 0xff);
	b[6] = (uint8_t)((val >> 48) & 0xff);
	b[5] = (uint8_t)((val >> 40) & 0xff);
	b[4] = (uint8_t)((val >> 32) & 0xff);

	b[3] = (uint8_t)((val >> 24) & 0xff);
	b[2] = (uint8_t)((val >> 16) & 0xff);
	b[1] = (uint8_t)((val >> 8) & 0xff);
	b[0] = (uint8_t)((val >> 0) & 0xff);
}


text:
package api.web.gw2.jsonp.v2.traits;

import api.web.gw2.mapping.core.EnumValue;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.OptionalValue;
import api.web.gw2.mapping.core.URLReference;
import api.web.gw2.mapping.core.URLValue;
import api.web.gw2.mapping.v2.traits.TraitFact;
import api.web.gw2.mapping.v2.traits.TraitFactType;

import java.util.Optional;
import java.util.OptionalInt;

/**
 * Default JSON-P implementation of a trait fact.
 *
 * @author Fabrice Bouyé
 */
public abstract class JsonpTraitFact implements TraitFact {

    @OptionalValue
    @LocalizedResource
    private Optional<String> text = Optional.empty();
    @EnumValue
    private TraitFactType type = TraitFactType.UNKNOWN;
    @URLValue
    private URLReference icon = URLReference.empty();
    @IdValue
    @OptionalValue
    private OptionalInt requiresTrait = OptionalInt.empty();
    @OptionalValue
    private OptionalInt overrides = OptionalInt.empty();

    /**
     * Creates a new empty instance;
     */
    public JsonpTraitFact() {
    }

    @Override
    public Optional<String> getText() {
        return text;
    }

    @Override
    public URLReference getIcon() {
        return icon;
    }

    @Override
    public OptionalInt getRequiresTrait() {
        return requiresTrait;
    }

    @Override
    public OptionalInt getOverrides() {
        return overrides;
    }
}

redpajama_set_name: RedPajamaGithub


text:
author: izabela
tags:
  - web3js
  - blockchain
  - BrightTreasury
date: 2022-06-07T09:28:13.015Z
title: How Can Non-Technical People Contribute to Kusama and Polkadot Networks? Part 2
layout: post
image: /images/blog_post_contribute_to_web3_part2.png
hidden: false
comments: true
published: true
---
**Following [part 1 of our guide on how to support Web3](/blog/how-to-contribute-to-kusama-and-polkadot-part-1) if you are not a software developer, we are coming to you with other ideas. Check them out, find ones that suit you well, and be a part of the Web3 revolution.** 😉

## Make videos for the Kusama and Polkadot communities

According to Google Trends, YouTube users as well as Google searchers also started to be more interested in all Web3 things. 😉 If you are a YouTuber or aspire to be one – you might consider creating content about Web3.

![YouTube Trends](/images/google_trends_youtube.png)

Also, if your video can be of value to the community, you can submit an idea for it on BrightTreasury. If the community appreciates your creative plans, you can turn them into a proposal and get funds to cover your expenses.

**Example of proposal for video production:**

[https://treasury.bright.dev/proposals/148/](https://treasury.bright.dev/proposals/148/info?networkId=kusama)

## Follow the best sources on Web3

Element, Discord, and Twitter are the best sources for updates from the Polkadot and Kusama networks.

Servers to join on **Discord**:

* [Kusama](https://discord.com/invite/9AWjTf8wSk)
* [Polkadot](https://discord.com/invite/wGUDt2p)

Channels to join on **Element**:

* [Polkadot Daily Digest](https://matrix.to/#/#dailydigest:web3.foundation)
* [Polkadot Direction](https://matrix.to/#/#polkadot-direction:matrix.parity.io)
* [Kusama Direction](https://matrix.to/#/#kusama:matrix.parity.io)

**Twitter** accounts to follow:

* [Polkadot](https://twitter.com/Polkadot)
* [Kusama](https://twitter.com/kusamanetwork)
* [Web3 Foundation](https://twitter.com/Web3foundation)
* [BillLaboon](https://twitter.com/BillLaboon) – Head of Education and Grants at Web3 Foundation

If you are into **newsletters**, here are the ones you could start to follow:

* [Web3 Foundation newsletter](https://web3.foundation/news/)
* [The dotleap newsletter](https://newsletter.dotleap.com) – covers news about Polkadot, Substrate, Kusama, and Web3 Foundation. Everything is in one place.

## Appreciate others with Treasury tips

Have you noticed someone's great contribution and you believe they should be recognized and rewarded? **You can suggest someone from the community who deserves to receive a tip paid in $KSM or $DOT**. After that, the council decides on the amount of the tip. The easiest way to suggest a tip beneficiary is via [BrightTreasury's Tips Module](https://treasury.bright.dev/tips/?utm_source=brightinventions_blog&utm_medium=link_article&utm_campaign=contributetoweb3_2&utm_id=content_marketing).

via GIPHY

## Provide feedback for Kusama and Polkadot applications

When someone contributes to Polkadot and Kusama nets, they often need one thing – feedback. As a potential user, your thoughts on the planned and existing solutions are precious. We encourage you to **leave feedback for community creators whether they have built a plugin or published some educational content**.

You can even discuss their ideas on [BrightTreasury](https://treasury.bright.dev/?utm_source=brightinventions_blog&utm_medium=link_article&utm_campaign=contributetoweb3_2&utm_id=content_marketing) before they turn them into a proposal. Let them know if their idea can be of use or maybe it shouldn't be developed because something similar already exists. Don't be a silent member. Contribute by using your voice!

**We hope that you have got inspired to contribute to the community. See you on the Web3 path!**


text:
module MaterialsHelper
  def attributes_for_material(material)
    material.getSqlCriteria().inject("") do |s, entry|
      key, value = entry.first, entry.last
      value = material.getUriForDisplay() if key == "url"
      "#{s} #{key}=\"#{h(value)}\""
    end
  end

  def current_modification? modification
    @deployed_revision.isRealRevision() && (modification.getRevision() == @deployed_revision.getRevision())
  end

  def latest_modification? modification
    modification.equals(@modifications.first())
  end

  def has_modification? material
    material_service.hasModificationFor(material)
  end

  def dependency_material? material
    material.getType() == "DependencyMaterial"
  end

  def stage_url_from_identifier locator
    stage_url(:id => stage_service.findStageIdByLocator(locator))
  end

  def render_simple_comment(comment)
    if comment.match(/\"TYPE\":\"PACKAGE_MATERIAL\"/)
      package_comment_map = package_material_display_comment(comment)
      trackback_url = package_comment_map['TRACKBACK_URL'].blank? ? l.string('NOT_PROVIDED') : package_comment_map['TRACKBACK_URL']
      result = package_comment_map['COMMENT'] || "#{l.string('TRACKBACK')}#{trackback_url}"
      return result
    end
    comment
  end

  def render_comment_markup_for(comment, pipeline_name)
    if comment.match(/\"TYPE\":\"PACKAGE_MATERIAL\"/)
      render_comment_for_package_material(comment)
    else
      render_tracking_tool_link_for_comment(comment, pipeline_name)
    end
  end

  def render_comment(modification, pipeline_name)
    render_comment_markup_for(modification.getComment(),pipeline_name)
  end

  def render_comment_for_package_material(comment)
    package_comment_map = package_material_display_comment(comment)
    "#{get_comment(package_comment_map)}#{l.string('TRACKBACK')}#{get_trackback_url(package_comment_map)}"
  end

  def render_tracking_tool_link(modification, pipeline_name)
    render_tracking_tool_link_for_comment(modification.getComment(), pipeline_name)
  end

  def render_tracking_tool_link_for_comment(comment, pipeline_name)
    comment_renderer = go_config_service.getCommentRendererFor(pipeline_name)
    simple_format comment_renderer.render(comment)
  end

  def package_material_display_comment(comment)
    ActiveSupport::JSON.decode(comment)
  end

  def get_comment(comment_map)
    comment_map['COMMENT'].blank? ? "" : "#{comment_map['COMMENT']}<br/>"
  end

  def get_trackback_url(comment_map)
    comment_map['TRACKBACK_URL'].blank? ? l.string('NOT_PROVIDED') : link_to(comment_map['TRACKBACK_URL'], comment_map['TRACKBACK_URL'])
  end

  def material_type_from_class(material)
    material.getClass().getSimpleName().gsub(/MaterialConfig$/, '').downcase
  end

  def admin_material_edit_path(material)
    send("admin_#{material_type_from_class(material)}_edit_path", :finger_print => material.getPipelineUniqueFingerprint())
  end
end


text:
package com.example.wayne.coolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by wayne on 2017/3/1.
 */

public class Now {
    @SerializedName("tmp")
    public String temperature;
    @SerializedName("cond")
    public More more;
    public class More{
        @SerializedName("text")
        public String info;
    }
}


text:
struct PrintConsole;

class BackgroundLayer
{
public:
	BackgroundLayer();
	~BackgroundLayer();

	// Tile layer functions
	void InitTiled(int bgId, uint8 metaTileSizeX, uint8 metaTileSizeY);
	void LoadTilesImage(const uint16* pImage, uint16 sizeBytes);
	void DrawTile(uint16 metaTileIndex, uint16 metaTileMapX, uint16 metaTileMapY);

	// Returns pointer to the tiles image buffer
	const uint8* GetTilesImagePtr() const;

	// Console layer functions
	void InitConsole(PrintConsole* pConsole); // Transfers ownership of pointer (this class will delete it)
	bool IsTextLayer() const;
	void ActivateTextLayer(); // Call so subsequent iprintfs render to this layer
	void ClearText();

	// 3D layer functions
	void Init3d(int bgId);

	void SetEnabled(bool enabled);

	void SetPriority(int priority);

	// Need to call GraphicsEngine::Update() for scroll values to take effect
	void SetScroll(int x, int y);

private:
	int mBgId;
	PrintConsole* mpConsole;

	uint8* mpTileMap;
	uint8 mMetaTileSizeX;
	uint8 mMetaTileSizeY;

	// Cached constants
	uint8 mNumHwTilesPerMetaTileX;
	uint8 mNumHwTilesPerMetaTileY;
};

#endif // GS_BACKGROUND_RENDERER_H


text:
progstr=$1
progpid=`pgrep -o $progstr`
while [ "$progpid" = "" ]; do
  progpid=`pgrep -o $progstr`
done
gdb -ex continue -p $progpid


text:
package au.gov.amsa.ais;

import java.math.BigInteger;

import com.github.davidmoten.guavamini.annotations.VisibleForTesting;

/**
 * Decodes the AtoN type code as per Table 71 in 1371-4.pdf.
 *
 * @author pxg
 *
 */
public final class AtonTypeDecoder {

	/**
	 * Private constructor.
	 */
	private AtonTypeDecoder() {
		// private constructor.
	}

	/**
	 * Visible for test coverage only (calls the private constructor).
	 */
	@VisibleForTesting
	static void forTestCoverageOnly() {
		new AtonTypeDecoder();
	}

	private static String[] categoryTypes = { "Fixed - ", "Floating - " };

	private static String[] atonTypes = { "Not specified", "Reference point",
			"RACON", "Fixed structure", "Reserved for future use",
			"Light, without sectors", "Light, with sectors",
			"Leading Light Front", "Leading Light Rear", "Beacon, Cardinal N",
			"Beacon, Cardinal E", "Beacon, Cardinal S", "Beacon, Cardinal W",
			"Beacon, Port hand", "Beacon, Starboard hand",
			"Beacon, Preferred Channel port hand",
			"Beacon, Preferred Channel starboard hand",
			"Beacon, Isolated danger", "Beacon, Safe water",
			"Beacon, Special mark", "Cardinal Mark N", "Cardinal Mark E",
			"Cardinal Mark S", "Cardinal Mark W", "Port hand Mark",
			"Starboard hand Mark", "Preferred Channel Port hand",
			"Preferred Channel Starboard hand", "Isolated danger",
			"Safe Water", "Special Mark", "Light Vessel, LANBY, Rigs" };

	/**
	 * Returns the AtoN type for given integer. If integer is null then returns
	 * null.
	 *
	 * @param ts
	 * @return
	 */
	public static String getAtonType(BigInteger ts) {
		if (ts == null)
			return null;
		else
			return getAtonType(ts.intValue());
	}

	/**
	 * Returns the AtoN type for given integer. If integer is null then returns
	 * null.
	 *
	 * @param ts
	 * @return
	 */
	public static String getAtonType(Integer ts) {
		if (ts == null)
			return null;
		if (ts < 0 || ts > 31) {
			return "unknown code " + ts.intValue();
		} else {
			if (ts >= 0 && ts < 5) {
				return atonTypes[ts];
			} else if (ts < 20) {
				return categoryTypes[0] + atonTypes[ts];
			} else {
				return categoryTypes[1] + atonTypes[ts];
			}
		}
	}

}


text:
'use strict';

const factory = require('./helpers/factory');
const {Engine} = require('../');
const {EventEmitter} = require('events');

describe('issues', () => {
  describe('issue 19 - save state', () => {
    it('make sure there is something to save on activity start event', async () => {
      const messages = [];
      const services = {
        timeout: (cb, time) => {
          setTimeout(cb, time);
        },
        log: (message) => {
          messages.push(message);
        },
      };

      const listener = new EventEmitter();
      const engine = new Engine({
        name: 'Engine',
        source: factory.resource('issue-19.bpmn'),
        listener,
      });

      const states = [];

      listener.on('activity.start', (activity, engineApi) => {
        states.push(engineApi.getState());
      });

      const end = engine.waitFor('end');

      await engine.execute({
        listener,
        variables: {
          timeout: 100,
        },
        services,
      });

      await end;

      expect(states).to.have.length(7);

      for (const state of states) {
        expect(state).to.have.property('definitions').with.length(1);
        expect(state.definitions[0]).to.have.property('execution');
        expect(state.definitions[0].execution).to.have.property('processes').with.length(1);
        expect(state.definitions[0].execution.processes[0]).to.have.property('execution');
        expect(state.definitions[0].execution.processes[0].execution).to.have.property('children').with.length(7);

        const children = state.definitions[0].execution.processes[0].execution.children;

        expect(children.map(({id}) => id)).to.eql(['Start', 'Parallel1', 'Task_A', 'Task_B', 'Parallel2', 'Task_C', 'End']);
      }

      let [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[0].definitions[0].execution.processes[0].execution.children;
      expect(Start, 'state 0 Start').to.have.property('status', 'started');
      expect(Parallel1, 'state 0 Parallel1').to.not.have.property('status');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[1].definitions[0].execution.processes[0].execution.children;
      expect(Start, 'state 1 Start').to.have.property('status', 'end');
      expect(Parallel1, 'state 1 Parallel1').to.have.property('status', 'started');
      expect(Task_A, 'state 1 Task_A').to.not.have.property('status');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[2].definitions[0].execution.processes[0].execution.children;
      expect(Parallel1, 'state 2 Parallel1').to.have.property('status', 'end');
      expect(Task_A, 'state 2 Task_A').to.have.property('status', 'started');
      expect(Task_B, 'state 2 Task_B').to.not.have.property('status');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[3].definitions[0].execution.processes[0].execution.children;
      expect(Parallel1, 'state 3 Parallel1').to.have.property('status', 'end');
      expect(Task_A, 'state 3 Task_A').to.not.have.property('status');
      expect(Task_B, 'state 3 Task_B').to.have.property('status', 'started');
      expect(Parallel2, 'state 3 Parallel2').to.not.have.property('status');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[4].definitions[0].execution.processes[0].execution.children;
      expect(Task_A, 'state 4 Task_A').to.not.have.property('status');
      expect(Task_B, 'state 4 Task_B').to.have.property('status', 'end');
      expect(Parallel2, 'state 4 Parallel2').to.have.property('status', 'started');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[5].definitions[0].execution.processes[0].execution.children;
      expect(Parallel2, 'state 5 Parallel2').to.have.property('status', 'end');
      expect(Task_C, 'state 5 Task_C').to.have.property('status', 'started');
      expect(End, 'state 5 End').to.not.have.property('status');

      [Start, Parallel1, Task_A, Task_B, Parallel2, Task_C, End] = states[6].definitions[0].execution.processes[0].execution.children;
      expect(Task_C, 'state 6 Task_C').to.have.property('status', 'end');
      expect(End, 'state 6 End').to.have.property('status', 'started');
    });
  });

  describe('issue 74 - setting engine output from script', () => {
    const source = `<?xml version="1.0" encoding="UTF-8"?>
    <bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_01d9p2c" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.2.3">
      <bpmn:process id="first_process" isExecutable="true" camunda:versionTag="1.0" camunda:historyTimeToLive="365">
        <bpmn:startEvent id="StartEvent_0an034v" />
        <bpmn:sequenceFlow id="SequenceFlow_19p3cf1" sourceRef="StartEvent_0an034v" targetRef="Task_0nh74lm" />
        <bpmn:endEvent id="IntermediateThrowEvent_1jovaga" name="Throw" />
        <bpmn:sequenceFlow id="SequenceFlow_0zn9m7b" sourceRef="Task_0nh74lm" targetRef="Task_1yzzr7e" />
        <bpmn:scriptTask id="Task_0nh74lm" name="Script" scriptFormat="javascript">
          <bpmn:script>environment.output.test = "set from script"; next()</bpmn:script>
        </bpmn:scriptTask>
        <bpmn:userTask id="Task_1yzzr7e" name="Get input">
          <bpmn:extensionElements>
            <camunda:properties>
              <camunda:property name="text" value="123" />
            </camunda:properties>
            <camunda:formData>
              <camunda:formField id="FormField_0ks539t" label="1" type="enum" />
            </camunda:formData>
          </bpmn:extensionElements>
        </bpmn:userTask>
        <bpmn:sequenceFlow id="SequenceFlow_183i0pk" sourceRef="Task_1yzzr7e" targetRef="IntermediateThrowEvent_1jovaga" />
      </bpmn:process>
      <bpmn:message id="Message_1my3vry" name="Message_3fks037" />
      <bpmn:signal id="Signal_0hs208i" name="Signal_0usjrve" />
    </bpmn:definitions>`;

    it('engine output is not altered during execution', async () => {
      const listener = new EventEmitter();
      const engine = new Engine({
        name: 'Engine',
        source,
        listener,
      });

      listener.on('activity.wait', (api) => {
        // When we get to the UserTask, the ScriptTask should be completed and set the output
        expect(api.environment.output.test, 'execution output').to.equal('set from script');
        expect(engine.environment.output.test, 'engine output').to.be.undefined;
      });

      await engine.execute({ listener });
    });

    it('merges execution output to engine output from a script at engine completion', async () => {
      const listener = new EventEmitter();
      const engine = new Engine({
        name: 'Engine',
        source,
        listener,
      });

      listener.on('activity.wait', (exec) => exec.signal());

      await engine.execute({ listener });

      expect(engine.environment.output.test).to.equal('set from script');
    });

    it('resumes with correct state', async () => {
      let state;

      const listener = new EventEmitter();
      const engine = new Engine({
        name: 'Engine',
        source,
        listener,
      });

      const resumeListener = new EventEmitter();
      const resumeEngine = new Engine({
        name: 'Engine',
        source,
        listener: resumeListener,
      });

      resumeListener.on('activity.wait', (exec) => {
        expect(exec.environment.output.test).to.equal('set from script');
      });

      listener.on('activity.wait', (exec) => {
        expect(exec.environment.output.test).to.equal('set from script');

        engine.getState().then((s) => {
          state = s;
          engine.stop();
        });
      });

      await engine.execute({ listener });

      resumeEngine.recover(state);

      await resumeEngine.resume({ listener: resumeListener });
    });
  });
});


text:
package graph

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"regexp"

	"sourcegraph.com/sourcegraph/go-nnz/nnz"
	"sourcegraph.com/sourcegraph/srclib/util/sqltypes"
)

type (
	DefPath  string
	TreePath string
)

// START DefKey OMIT
// DefKey specifies a definition, either concretely or abstractly. A concrete
// definition key has a non-empty CommitID and refers to a definition defined in a
// specific commit. An abstract definition key has an empty CommitID and is
// considered to refer to definitions from any number of commits (so long as the
// Repo, UnitType, Unit, and Path match).
//
// You can think of CommitID as the time dimension. With an empty CommitID, you
// are referring to a definition that may or may not exist at various times. With a
// non-empty CommitID, you are referring to a specific definition of a definition at
// the time specified by the CommitID.
type DefKey struct {
	// Repo is the VCS repository that defines this definition. Its Elasticsearch mapping is defined
	// separately.
	Repo string `json:",omitempty"`

	// CommitID is the ID of the VCS commit that this definition was defined in. The
	// CommitID is always a full commit ID (40 hexadecimal characters for git
	// and hg), never a branch or tag name.
	CommitID string `db:"commit_id" json:",omitempty"`

	// UnitType is the type name of the source unit (obtained from unit.Type(u))
	// that this definition was defined in.
	UnitType string `db:"unit_type" json:",omitempty"`

	// Unit is the name of the source unit (obtained from u.Name()) that this
	// definition was defined in.
	Unit string `json:",omitempty"`

	// Path is a unique identifier for the def, relative to the source unit.
	// It should remain stable across commits as long as the def is the
	// "same" def. Its Elasticsearch mapping is defined separately (because
	// it is a multi_field, which the struct tag can't currently represent).
	//
	// Path encodes no structural semantics. Its only meaning is to be a stable
	// unique identifier within a given source unit. In many languages, it is
	// convenient to use the namespace hierarchy (with some modifications) as
	// the Path, but this may not always be the case. I.e., don't rely on Path
	// to find parents or children or any other structural propreties of the
	// def hierarchy). See Def.TreePath instead.
	Path DefPath
}

// END DefKey OMIT

func (s DefKey) String() string {
	b, err := json.Marshal(s)
	if err != nil {
		panic("DefKey.String: " + err.Error())
	}
	return string(b)
}

// START Def OMIT
type Def struct {
	// DefKey is the natural unique key for a def. It is stable
	// (subsequent runs of a grapher will emit the same defs with the same
	// DefKeys).
	DefKey

	// TreePath is a structurally significant path descriptor for a def. For
	// many languages, it may be identical or similar to DefKey.Path.
	// However, it has the following constraints, which allow it to define a
	// def tree.
	//
	// A tree-path is a chain of '/'-delimited components. A component is either a
	// def name or a ghost component.
	// - A def name satifies the regex [^/-][^/]*
	// - A ghost component satisfies the regex -[^/]*
	// Any prefix of a tree-path that terminates in a def name must be a valid
	// tree-path for some def.
	// The following regex captures the children of a tree-path X: X(/-[^/]*)*(/[^/-][^/]*)
	TreePath TreePath `db:"treepath" json:",omitempty"`

	// Name of the definition. This need not be unique.
	Name string

	// Kind is the kind of thing this definition is. This is
	// language-specific. Possible values include "type", "func",
	// "var", etc.
	Kind string

	File string

	DefStart int `db:"def_start"`
	DefEnd   int `db:"def_end"`

	// Exported is whether this def is part of a source unit's
	// public API. For example, in Java a "public" field is
	// Exported.
	Exported bool

	// Local is whether this def is local to a function or some
	// other inner scope. Local defs do *not* have module,
	// package, or file scope. For example, in Java a function's
	// args are Local, but fields with "private" scope are not
	// Local.
	Local nnz.Bool

	// Test is whether this def is defined in test code (as opposed to main
	// code). For example, definitions in Go *_test.go files have Test = true.
	Test bool `json:",omitempty"`

	// Private is whether this definition is private, i.e., if it came from a private repository.
	Private nnz.Bool `json:",omitempty"`

	// Data contains additional language- and toolchain-specific information
	// about the def. Data is used to construct function signatures,
	// import/require statements, language-specific type descriptions, etc.
	Data sqltypes.JSON `json:",omitempty"`
}

// END Def OMIT

var treePathRegexp = regexp.MustCompile(`^(?:[^/]+)(?:/[^/]+)*$`)

func (p TreePath) IsValid() bool {
	return treePathRegexp.MatchString(string(p))
}

func (s *Def) Fmt() DefPrintFormatter { return PrintFormatter(s) }

func (s *Def) sortKey() string { return s.DefKey.String() }

// Propagate describes type/value propagation in code. A Propagate entry from A
// (src) to B (dst) indicates that the type/value of A propagates to B. In Tern,
// this is indicated by A having a "fwd" property whose value is an array that
// includes B.
//
//
// ## Motivation & example
//
// For example, consider the following JavaScript code:
//
//   var a = Foo;
//   var b = a;
//
// Foo, a, and b are each their own def. We could resolve all of them to the
// def of their original type (perhaps Foo), but there are occasions when you
// do want to see only the definition of a or b and examples thereof. Therefore,
// we need to represent them as distinct defs.
//
// Even though Foo, a, and b are distinct defs, there are propagation
// relationships between them that are important to represent. The type of Foo
// propagates to both a and b, and the type of a propagates to b. In this case,
// we would have 3 Propagates: Propagate{Src: "Foo", Dst: "a"}, Propagate{Src:
// "Foo", Dst: "b"}, and Propagate{Src: "a", Dst: "b"}. (The propagation
// relationships could be described by just the first and last Propagates, but
// we explicitly include all paths as a denormalization optimization to avoid
// requiring an unbounded number of DB queries to determine which defs a type
// propagates to or from.)
//
//
// ## Directionality
//
// Propagation is unidirectional, in the general case. In the example above, if
// Foo referred to a JavaScript object and if the code were evaluated, any
// *runtime* type changes (e.g., setting a property) on Foo, a, and b would be
// reflected on all of the others. But this doesn't hold for static analysis;
// it's not always true that if a property "a.x" or "b.x" exists, then "Foo.x"
// exists. The simplest example is when Foo is an external definition. Perhaps
// this example file (which uses Foo as a library) modifies Foo to add a new
// property, but other libraries that use Foo would never see that property
// because they wouldn't be executed in the same context as this example file.
// So, in general, we cannot say that Foo receives all types applied to defs
// that Foo propagates to.
//
//
// ## Hypothetical Python example
//
// Consider the following 2 Python files:
//
//   """file1.py"""
//   class Foo(object): end
//
//   """file2.py"""
//   from .file1 import Foo
//   Foo2 = Foo
//
// In this example, there would be one Propagate: Propagate{Src: "file1/Foo",
// Dst: "file2/Foo2}.
type Propagate struct {
	// Src is the def whose type/value is being propagated to the dst def.
	SrcRepo     string
	SrcPath     DefPath
	SrcUnit     string
	SrcUnitType string

	// Dst is the def that is receiving a propagated type/value from the src def.
	DstRepo     string
	DstPath     DefPath
	DstUnit     string
	DstUnitType string
}

// SQL

func (x DefPath) Value() (driver.Value, error) {
	return string(x), nil
}

func (x *DefPath) Scan(v interface{}) error {
	if data, ok := v.([]byte); ok {
		*x = DefPath(data)
		return nil
	}
	return fmt.Errorf("%T.Scan failed: %v", x, v)
}

func (x TreePath) Value() (driver.Value, error) {
	return string(x), nil
}

func (x *TreePath) Scan(v interface{}) error {
	if data, ok := v.([]byte); ok {
		*x = TreePath(data)
		return nil
	}
	return fmt.Errorf("%T.Scan failed: %v", x, v)
}

// Debugging

func (x Def) String() string {
	s, _ := json.Marshal(x)
	return string(s)
}

// Sorting

type Defs []*Def

func (vs Defs) Len() int           { return len(vs) }
func (vs Defs) Swap(i, j int)      { vs[i], vs[j] = vs[j], vs[i] }
func (vs Defs) Less(i, j int) bool { return vs[i].sortKey() < vs[j].sortKey() }

func (defs Defs) Keys() (keys []DefKey) {
	keys = make([]DefKey, len(defs))
	for i, def := range defs {
		keys[i] = def.DefKey
	}
	return
}

func (defs Defs) KeySet() (keys map[DefKey]struct{}, err error) {
	keys = make(map[DefKey]struct{})
	for _, def := range defs {
		if _, in := keys[def.DefKey]; in {
			return nil, fmt.Errorf("duplicate def key %+v", def.DefKey)
		}
		keys[def.DefKey] = struct{}{}
	}
	return keys, nil
}


text:
package io.fsq.rogue

import com.mongodb.BasicDBObjectBuilder
import java.util.regex.Pattern
import scala.Iterable

abstract class QueryClause[V](
    val fieldName: String,
    val actualIndexBehavior: MaybeIndexed,
    val conditions: (CondOps.Value, V)*
) {
  def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    conditions foreach { case (op, v) =>
      q.add(op.toString, if (signature) 0 else v)
    }
  }
  var negated: Boolean = false
  var expectedIndexBehavior: MaybeIndexed = Index
}

abstract class IndexableQueryClause[V, Ind <: MaybeIndexed](
    fname: String,
    actualIB: Ind,
    conds: (CondOps.Value, V)*
) extends QueryClause[V](fname, actualIB, conds: _*)

trait ShardKeyClause

case class AllQueryClause[V](
    override val fieldName: String,
    vs: java.util.List[V]
) extends IndexableQueryClause[java.util.List[V], Index](
      fieldName,
      Index,
      CondOps.All -> vs
    ) {}

case class InQueryClause[V](
    override val fieldName: String,
    vs: java.util.List[V]
) extends IndexableQueryClause[java.util.List[V], Index](
      fieldName,
      Index,
      CondOps.In -> vs
    ) {}

case class GtQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.Gt -> v
    ) {}

case class GtEqQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.GtEq -> v
    ) {}

case class LtQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.Lt -> v
    ) {}

case class LtEqQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.LtEq -> v
    ) {}

case class BetweenQueryClause[V](
    override val fieldName: String,
    lower: V,
    upper: V
) extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.GtEq -> lower,
      CondOps.LtEq -> upper
    ) {}

case class StrictBetweenQueryClause[V](
    override val fieldName: String,
    lower: V,
    upper: V
) extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.Gt -> lower,
      CondOps.Lt -> upper
    ) {}

case class NeQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.Ne -> v
    ) {}

case class NearQueryClause[V](override val fieldName: String, v: V)
    extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan,
      CondOps.Near -> v
    ) {}

case class NearSphereQueryClause[V](
    override val fieldName: String,
    lat: Double,
    lng: Double,
    radians: Radians
) extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan
    ) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    q.add(
      CondOps.NearSphere.toString,
      if (signature) 0 else QueryHelpers.list(List(lat, lng))
    )
    q.add(CondOps.MaxDistance.toString, if (signature) 0 else radians.value)
  }
}

case class ModQueryClause[V](
    override val fieldName: String,
    v: java.util.List[V]
) extends IndexableQueryClause[java.util.List[V], IndexScan](
      fieldName,
      IndexScan,
      CondOps.Mod -> v
    ) {}

case class TypeQueryClause(override val fieldName: String, v: MongoType.Value)
    extends IndexableQueryClause[Int, IndexScan](
      fieldName,
      IndexScan,
      CondOps.Type -> v.id
    ) {}

case class ExistsQueryClause(override val fieldName: String, v: Boolean)
    extends IndexableQueryClause[Boolean, IndexScan](
      fieldName,
      IndexScan,
      CondOps.Exists -> v
    ) {}

case class NinQueryClause[V](
    override val fieldName: String,
    vs: java.util.List[V]
) extends IndexableQueryClause[java.util.List[V], DocumentScan](
      fieldName,
      DocumentScan,
      CondOps.Nin -> vs
    ) {}

case class SizeQueryClause(override val fieldName: String, v: Int)
    extends IndexableQueryClause[Int, DocumentScan](
      fieldName,
      DocumentScan,
      CondOps.Size -> v
    ) {}

case class RegexQueryClause[Ind <: MaybeIndexed](
    override val fieldName: String,
    actualIB: Ind,
    p: Pattern
) extends IndexableQueryClause[Pattern, Ind](fieldName, actualIB) {
  val flagMap = Map(
    Pattern.CANON_EQ -> "c",
    Pattern.CASE_INSENSITIVE -> "i",
    Pattern.COMMENTS -> "x",
    Pattern.DOTALL -> "s",
    Pattern.LITERAL -> "t",
    Pattern.MULTILINE -> "m",
    Pattern.UNICODE_CASE -> "u",
    Pattern.UNIX_LINES -> "d"
  )

  def flagsToString(flags: Int) = {
    (for {
      (mask, char) <- flagMap
      if (flags & mask) != 0
    } yield char).mkString
  }

  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    q.add("$regex", if (signature) 0 else p.toString)
    q.add("$options", if (signature) 0 else flagsToString(p.flags))
  }

}

case class RawQueryClause(f: BasicDBObjectBuilder => Unit)
    extends IndexableQueryClause("raw", DocumentScan) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    f(q)
  }
}

case class EmptyQueryClause[V](override val fieldName: String)
    extends IndexableQueryClause[V, Index](fieldName, Index) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {}
}

case class EqClause[V, Ind <: MaybeIndexed](
    override val fieldName: String,
    value: V
) extends IndexableQueryClause[V, Index](fieldName, Index) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    q.add(fieldName, if (signature) 0 else value)
  }
}

case class WithinCircleClause[V](
    override val fieldName: String,
    lat: Double,
    lng: Double,
    radius: Double
) extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan
    ) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    val value =
      if (signature) 0
      else QueryHelpers.list(List(QueryHelpers.list(List(lat, lng)), radius))
    q.push("$within").add("$center", value).pop
  }
}

case class WithinBoxClause[V](
    override val fieldName: String,
    lat1: Double,
    lng1: Double,
    lat2: Double,
    lng2: Double
) extends IndexableQueryClause[V, PartialIndexScan](
      fieldName,
      PartialIndexScan
    ) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    val value =
      if (signature) 0
      else {
        QueryHelpers.list(
          List(QueryHelpers.list(lat1, lng1), QueryHelpers.list(lat2, lng2))
        )
      }
    q.push("$within").add("$box", value).pop
  }
}

case class ElemMatchWithPredicateClause[V](
    override val fieldName: String,
    clauses: Seq[QueryClause[_]]
) extends IndexableQueryClause[V, DocumentScan](fieldName, DocumentScan) {
  override def extend(q: BasicDBObjectBuilder, signature: Boolean): Unit = {
    import io.fsq.rogue.MongoHelpers.AndCondition
    val nested = q.push("$elemMatch")
    MongoHelpers.MongoBuilder.buildCondition(
      AndCondition(clauses.toList, None, None),
      nested,
      signature
    )
    nested.pop
  }
}

class ModifyClause(val operator: ModOps.Value, fields: (String, _)*) {
  def extend(q: BasicDBObjectBuilder): Unit = {
    fields foreach { case (name, value) => q.add(name, value) }
  }
}

class ModifyAddEachClause(fieldName: String, values: Iterable[_])
    extends ModifyClause(ModOps.AddToSet) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    q.push(fieldName).add("$each", QueryHelpers.list(values)).pop
  }
}

class ModifyPushEachClause(fieldName: String, values: Iterable[_])
    extends ModifyClause(ModOps.Push) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    q.push(fieldName).add("$each", QueryHelpers.list(values)).pop
  }
}

class ModifyPushEachSliceClause(
    fieldName: String,
    slice: Int,
    values: Iterable[_]
) extends ModifyClause(ModOps.Push) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    q.push(fieldName)
      .add("$each", QueryHelpers.list(values))
      .add("$slice", slice)
      .pop
  }
}

class ModifyPushEachSlicePositionClause(
    fieldName: String,
    slice: Int,
    position: Int,
    values: Iterable[_]
) extends ModifyClause(ModOps.Push) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    q.push(fieldName)
      .add("$each", QueryHelpers.list(values))
      .add("$slice", slice)
      .add("$position", position)
      .pop
  }
}

class ModifyBitClause(fieldName: String, value: Int, op: BitOps.Value)
    extends ModifyClause(ModOps.Bit) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    q.push(fieldName).add(op.toString, value).pop
  }
}

class ModifyPullWithPredicateClause[V](
    fieldName: String,
    clauses: Seq[QueryClause[_]]
) extends ModifyClause(ModOps.Pull) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    import io.fsq.rogue.MongoHelpers.AndCondition
    MongoHelpers.MongoBuilder.buildCondition(
      AndCondition(clauses.toList, None, None),
      q,
      false
    )
  }
}

class ModifyPullObjWithPredicateClause[V](
    fieldName: String,
    clauses: Seq[QueryClause[_]]
) extends ModifyClause(ModOps.Pull) {
  override def extend(q: BasicDBObjectBuilder): Unit = {
    import io.fsq.rogue.MongoHelpers.AndCondition
    val nested = q.push(fieldName)
    MongoHelpers.MongoBuilder.buildCondition(
      AndCondition(clauses.toList, None, None),
      nested,
      false
    )
    nested.pop
  }
}


text:
package org.x.job.commons.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;

import java.io.IOException;

public class HDFSUtils {

    public static void getDateNodeHost() throws IOException{

        Configuration conf = getConf();

        FileSystem fs=FileSystem.get(conf);
        DistributedFileSystem hdfs = (DistributedFileSystem)fs;
        DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();
        for(int i=0;i<dataNodeStats.length;i++){
            System.out.println("DataNode_"+i+"_Name:"+dataNodeStats[i].getHostName());
        }
    }
    /*
     * upload the local file to the hds
     * 路径是全路径
     */
    public static void uploadLocalFile2HDFS(String s, String d)
            throws IOException
    {
        Configuration conf = getConf();
        FileSystem hdfs = FileSystem.get(conf);
        Path src = new Path(s);
        Path dst = new Path(d);
        hdfs.copyFromLocalFile(src, dst);
        hdfs.close();
    }

    /*
     * create a new file in the hdfs.
     * notice that the toCreateFilePath is the full path
     * and write the content to the hdfs file.
     */
    public static void createNewHDFSFile(String toCreateFilePath, String content) throws IOException
    {
        Configuration conf = getConf();
        FileSystem hdfs = FileSystem.get(conf);

        FSDataOutputStream os = hdfs.create(new Path(toCreateFilePath));
        os.write(content.getBytes("UTF-8"));
        os.close();
        os.flush();
        hdfs.close();
    }

    /*
     * delete the hdfs file
     * notice that the dst is the full path name
     */
    public static boolean deleteHDFSFile(String dst) throws IOException
    {
        Configuration conf = getConf();
        FileSystem hdfs = FileSystem.get(conf);

        Path path = new Path(dst);
        boolean isDeleted = hdfs.delete(path);
        hdfs.close();
        return isDeleted;
    }

    /*
     * read the hdfs file content
     * notice that the dst is the full path name
     */
    public static byte[] readHDFSFile(String dst) throws Exception
    {
        Configuration conf = getConf();
        FileSystem fs = FileSystem.get(conf);

        // check if the file exists
        Path path = new Path(dst);
        if ( fs.exists(path) )
        {
            FSDataInputStream is = fs.open(path);
            // get the file info to create the buffer
            FileStatus stat = fs.getFileStatus(path);
            // create the buffer
            byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];
            is.readFully(0, buffer);

            is.close();
            fs.close();

            return buffer;
        }
        else
        {
            throw new Exception("the file is not found .");
        }
    }

    /*
     * make a new dir in the hdfs
     * the dir may like '/tmp/testdir'
     */
    public static void mkdir(String dir) throws IOException
    {
        Configuration conf = getConf();
        FileSystem fs = FileSystem.get(conf);
        fs.mkdirs(new Path(dir));

        fs.close();
    }

    /*
     * delete a dir in the hdfs
     * dir may like '/tmp/testdir'
     */
    public static void deleteDir(String dir) throws IOException
    {
        Configuration conf = getConf();
        FileSystem fs = FileSystem.get(conf);
        fs.delete(new Path(dir));
        fs.close();
    }
    //文件系统连接到 hdfs的配置信息
    private static Configuration getConf(){
        Configuration conf = new Configuration();
        // 这句话很关键,这些信息就是hadoop配置文件中的信息
        conf.set("mapred.job.tracker", "192.168.102.136:9001");
        conf.set("fs.default.name", "hdfs://192.168.102.136:9000");
        return conf;
    }

    /**
     * @Title: listAll
     * @Description: 列出目录下所有文件
     * @return void    返回类型
     * @throws
     */
    public static void listAll(String dir) throws IOException
    {
        Configuration conf = getConf();
        FileSystem fs = FileSystem.get(conf);
        FileStatus[] stats = fs.listStatus(new Path(dir));
        for(int i = 0; i < stats.length; ++i)
        {
            if (!stats[i].isDir())
            {
                // regular file
                System.out.println(stats[i].getPath().toString());
            }
            else
            {
                // dir
                System.out.println(stats[i].getPath().toString());
            }
//          else if(stats[i].())
//          {
//              // is s symlink in linux
//              System.out.println(stats[i].getPath().toString());
//          }

        }
        fs.close();
    }

}


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var g = require('../globalize');
var optional = require('optional');
var ursa = optional('ursa');
var fs = require('fs');
var path = require('path');
var SignedXml = require('xml-crypto').SignedXml;
var uuid = require('uuid');
var Security = require('./security');
var xmlHandler = require('../parser/xmlHandler');

function addMinutes(date, minutes) {
  return new Date(date.getTime() + minutes * 60000);
}

function dateStringForSOAP(date) {
  return date.getUTCFullYear() + '-' + ('0' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + date.getUTCDate()).slice(-2) + 'T' + ('0' + date.getUTCHours()).slice(-2) + ":" + ('0' + date.getUTCMinutes()).slice(-2) + ":" + ('0' + date.getUTCSeconds()).slice(-2) + "Z";
}

function generateCreated() {
  return dateStringForSOAP(new Date());
}

function generateExpires() {
  return dateStringForSOAP(addMinutes(new Date(), 10));
}

function insertStr(src, dst, pos) {
  return [dst.slice(0, pos), src, dst.slice(pos)].join('');
}

function generateId() {
  return uuid.v4().replace(/-/gm, '');
}

var WSSecurityCert = function (_Security) {
  _inherits(WSSecurityCert, _Security);

  function WSSecurityCert(privatePEM, publicP12PEM, password, encoding) {
    _classCallCheck(this, WSSecurityCert);

    var _this2 = _possibleConstructorReturn(this, (WSSecurityCert.__proto__ || Object.getPrototypeOf(WSSecurityCert)).call(this));

    if (!ursa) {
      throw new Error(g.f('Module {{ursa}} must be installed to use {{WSSecurityCert}}'));
    }
    _this2.privateKey = ursa.createPrivateKey(privatePEM, password, encoding);
    _this2.publicP12PEM = publicP12PEM.toString().replace('-----BEGIN CERTIFICATE-----', '').replace('-----END CERTIFICATE-----', '').replace(/(\r\n|\n|\r)/gm, '');

    _this2.signer = new SignedXml();
    _this2.signer.signingKey = _this2.privateKey.toPrivatePem();
    _this2.x509Id = 'x509-' + generateId();

    var references = ['http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/2001/10/xml-exc-c14n#'];

    _this2.signer.addReference('//*[local-name(.)=\'Body\']', references);
    _this2.signer.addReference('//*[local-name(.)=\'Timestamp\']', references);

    var _this = _this2;
    _this2.signer.keyInfoProvider = {};
    _this2.signer.keyInfoProvider.getKeyInfo = function (key) {
      var x509Id = _this.x509Id;
      var xml = '<wsse:SecurityTokenReference>\n    <wsse:Reference URI="' + x509Id + '" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>\n    </wsse:SecurityTokenReference>';
      return xml;
    };
    return _this2;
  }

  _createClass(WSSecurityCert, [{
    key: 'postProcess',
    value: function postProcess(headerElement, bodyElement) {
      this.created = generateCreated();
      this.expires = generateExpires();

      var binaryToken = this.publicP12PEM,
          created = this.created,
          expires = this.expires,
          id = this.x509Id;

      var secElement = headerElement.element('wsse:Security').attribute('xmlns:wsse', 'http://docs.oasis-open.org/wss/2004/01/' + 'oasis-200401-wss-wssecurity-secext-1.0.xsd').attribute('xmlns:wsu', 'http://docs.oasis-open.org/wss/2004/01/' + 'oasis-200401-wss-wssecurity-utility-1.0.xsd').attribute('soap:mustUnderstand', '1');
      secElement.element('wsse:BinarySecurityToken').attribute('EncodingType', 'http://docs.oasis-open.org/wss/2004/01/' + 'oasis-200401-wss-soap-message-security-1.0#Base64Binary').attribute('ValueType', 'http://docs.oasis-open.org/wss/2004/01/' + 'oasis-200401-wss-x509-token-profile-1.0#X509v3').attribute('wsu:Id', id).text(binaryToken);
      var tsElement = secElement.element('wsu:Timestamp').attribute('wsu:Id', '_1');
      tsElement.element('wsu:Created', created);
      tsElement.element('wsu:Expires', expires);

      var xmlWithSec = headerElement.doc().end({ pretty: true });

      this.signer.computeSignature(xmlWithSec);
      var sig = this.signer.getSignatureXml();

      xmlHandler.parseXml(secElement, sig);
    }
  }]);

  return WSSecurityCert;
}(Security);

module.exports = WSSecurityCert;


text:
/* $Id: MappingConnectorPool.java 1549105 2013-12-08 18:54:09Z kwright $ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.authorities.mappingconnectorpool;

import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.authorities.interfaces.*;

import java.util.*;
import java.io.*;

/** An implementation of IMappingConnectorPool.
* Coordination and allocation among cluster members is managed within.
* These objects are thread-local, so do not share them among threads.
*/
public class MappingConnectorPool implements IMappingConnectorPool
{
  public static final String _rcsid = "@(#)$Id: MappingConnectorPool.java 1549105 2013-12-08 18:54:09Z kwright $";

  /** Local connector pool */
  protected final static LocalPool localPool = new LocalPool();

  // This implementation is a place-holder for the real one, which will likely fold in the pooling code
  // as we strip it out of MappingConnectorFactory.

  /** Thread context */
  protected final IThreadContext threadContext;

  /** Constructor */
  public MappingConnectorPool(IThreadContext threadContext)
    throws ManifoldCFException
  {
    this.threadContext = threadContext;
  }

  /** Get multiple mapping connectors, all at once.  Do this in a particular order
  * so that any connector exhaustion will not cause a deadlock.
  *@param orderingKeys are the keys which determine in what order the connectors are obtained.
  *@param mappingConnections are the connections to use the build the connector instances.
  */
  @Override
  public IMappingConnector[] grabMultiple(String[] orderingKeys, IMappingConnection[] mappingConnections)
    throws ManifoldCFException
  {
    // For now, use the MappingConnectorFactory method.  This will require us to extract info
    // from each mapping connection, however.
    String[] connectionNames = new String[mappingConnections.length];
    String[] classNames = new String[mappingConnections.length];
    ConfigParams[] configInfos = new ConfigParams[mappingConnections.length];
    int[] maxPoolSizes = new int[mappingConnections.length];

    for (int i = 0; i < mappingConnections.length; i++)
    {
      connectionNames[i] = mappingConnections[i].getName();
      classNames[i] = mappingConnections[i].getClassName();
      configInfos[i] = mappingConnections[i].getConfigParams();
      maxPoolSizes[i] = mappingConnections[i].getMaxConnections();
    }
    return localPool.grabMultiple(threadContext,
      orderingKeys, connectionNames, classNames, configInfos, maxPoolSizes);
  }

  /** Get a mapping connector.
  * The connector is specified by an mapping connection object.
  *@param mappingConnection is the mapping connection to base the connector instance on.
  */
  @Override
  public IMappingConnector grab(IMappingConnection mappingConnection)
    throws ManifoldCFException
  {
    return localPool.grab(threadContext, mappingConnection.getName(),
      mappingConnection.getClassName(),
      mappingConnection.getConfigParams(), mappingConnection.getMaxConnections());
  }

  /** Release multiple mapping connectors.
  *@param connections are the connections describing the instances to release.
  *@param connectors are the connector instances to release.
  */
  @Override
  public void releaseMultiple(IMappingConnection[] connections, IMappingConnector[] connectors)
    throws ManifoldCFException
  {
    String[] connectionNames = new String[connections.length];
    for (int i = 0; i < connections.length; i++)
    {
      connectionNames[i] = connections[i].getName();
    }
    localPool.releaseMultiple(threadContext, connectionNames, connectors);
  }

  /** Release a mapping connector.
  *@param connection is the connection describing the instance to release.
  *@param connector is the connector to release.
  */
  @Override
  public void release(IMappingConnection connection, IMappingConnector connector)
    throws ManifoldCFException
  {
    localPool.release(threadContext, connection.getName(), connector);
  }

  /** Idle notification for inactive mapping connector handles.
  * This method polls all inactive handles.
  */
  @Override
  public void pollAllConnectors()
    throws ManifoldCFException
  {
    localPool.pollAllConnectors(threadContext);
  }

  /** Flush only those connector handles that are currently unused.
  */
  @Override
  public void flushUnusedConnectors()
    throws ManifoldCFException
  {
    localPool.flushUnusedConnectors(threadContext);
  }

  /** Clean up all open mapping connector handles.
  * This method is called when the connector pool needs to be flushed,
  * to free resources.
  */
  @Override
  public void closeAllConnectors()
    throws ManifoldCFException
  {
    localPool.closeAllConnectors(threadContext);
  }

  /** Actual static mapping connector pool */
  protected static class LocalPool extends org.apache.manifoldcf.core.connectorpool.ConnectorPool<IMappingConnector>
  {
    public LocalPool()
    {
      super("_MAPPINGCONNECTORPOOL_");
    }

    @Override
    protected boolean isInstalled(IThreadContext tc, String className)
      throws ManifoldCFException
    {
      IMappingConnectorManager connectorManager = MappingConnectorManagerFactory.make(tc);
      return connectorManager.isInstalled(className);
    }

    @Override
    protected boolean isConnectionNameValid(IThreadContext tc, String connectionName)
      throws ManifoldCFException
    {
      IMappingConnectionManager connectionManager = MappingConnectionManagerFactory.make(tc);
      return connectionManager.load(connectionName) != null;
    }

    public IMappingConnector[] grabMultiple(IThreadContext tc, String[] orderingKeys, String[] connectionNames, String[] classNames, ConfigParams[] configInfos, int[] maxPoolSizes)
      throws ManifoldCFException
    {
      return grabMultiple(tc,IMappingConnector.class,orderingKeys,connectionNames,classNames,configInfos,maxPoolSizes);
    }

  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
simpledb.index.planner
</TITLE>

<META NAME="date" CONTENT="2008-07-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

simpledb.index.planner

Classes

IndexUpdatePlanner


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="whitespace21.xsl"?>
<doc></doc>


text:
ngPourOver
==========

Installation Steps
----------

 * `bower install ng-pourover`;
 * `cd ng-pourover`;
 * `npm install`;
 * `node example/server.js` (if necessary after `npm install`);
 * Browse to [http://localhost:5001/](http://localhost:5001/);

Getting Started
----------

NYTimes' [PourOver](http://nytimes.github.io/pourover/) module allows for quick filtering and sorting.

In the `example` we are filtering within ~10 milliseconds a 100,000 collection.

Getting started with `ngPourOver` is fairly straightforward – you first need to add the dependency `PourOver` into your controller.

```javascript
$myApp.controller('myController', ['PourOver', function(PourOver) {

}]);
```

You then have everything you need to initialise your collection – assuming your collection is currently stored in the `collection` variable.

```javascript
$scope.collection = new PourOver(collection);
```

If you attempt the aforementioned without adding the `poCollection` filter – the work-horse of the `ngPourOver` module, then things won't be pretty. Ensure you've added the `poCollection` to your template.

```html
<li ng-repeat="model in collection | poCollection">
```

Logically the next step is to define your first filter on a property – let's say you have a property called `name` defined in your collection.

```javascript
$scope.collection.addExactFilter('word');
```

Afterwards you're able to begin filtering on this property.

```javascript
$scope.collection.filterBy('word', 'Supercalifragilisticexpialidocious');
```

You're even able to unfilter all with the `unfilter` method, and unfilter a specific filter with `unfilterBy`.

Unit Tests
----------

All of `ngPourOver`'s unit tests are written in [Jasmine](http://jasmine.github.io/) and can be run with `grunt test` after you have followed the [installation steps](#installation-steps) above.

Please open a pull request for all commits, and ensure all tests are passing before opening your PR.

**Every developer's dream:**


text:
RSpec.describe Hyrax::ResourceName do
  subject(:name) { described_class.new(work_class) }
  let(:work_class) { Monograph }

  it 'has a namespaced route key' do
    expect(name.route_key).to start_with 'hyrax_'
  end

  it 'has a namespaced singular route key' do
    expect(name.singular_route_key).to start_with 'hyrax_'
  end

  context 'when a legacy resource is registered with Wings' do
    let(:work_class) { Hyrax::Test::BookResource }

    it 'uses the legacy route key' do
      expect(name.route_key).to eq 'test_books'
    end

    it 'uses the legacy singular route key' do
      expect(name.singular_route_key).to eq 'test_book'
    end
  end
end


text:
Modified from the Diva sources
to fix a bug when flipping shapes.


text:
package edu.latrobe.blaze.modules.jvm

import edu.latrobe._
import edu.latrobe.blaze._
import edu.latrobe.blaze.modules._

abstract class ZeroMean_JVM
  extends ZeroMean
    with MapLayer_JVM[ZeroMeanBuilder] {

  final val (runningMean, runningMeanReference) = {
    val ref = builder.runningMeanReference
    val tmp = weightBufferBuilder.get(ref)
    if (tmp.isDefined) {
      val result = tmp.get.asInstanceOf[RealArrayTensor]
      (result, None)
    }
    else {
      val result = RealArrayTensor.zeros(runningMeanLayout)
      val newRef = weightBufferBuilder.register(ref, result)
      (result, Some(newRef))
    }
  }

  // ---------------------------------------------------------------------------
  //    Weights related.
  // ---------------------------------------------------------------------------
  override def refresh(): Unit = {}

  // ---------------------------------------------------------------------------
  //    Forward propagation related.
  // ---------------------------------------------------------------------------
  final override protected def doPredictForUnitTraining(inPlaceAllowed: Boolean,
                                                        input:          Tensor,
                                                        learningRate:   Real)
  : (Tensor, PredictContext) = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForUnitTraining(out, learningRate)
    (out, EmptyContext)
  }

  protected def doPredictForUnitTraining(output:       RealArrayTensor,
                                         learningRate: Real)
  : Unit

  final override protected def doPredictForUnitInference(inPlaceAllowed: Boolean,
                                                         input:          Tensor)
  : Tensor = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForUnitInference(out)
    out
  }

  protected def doPredictForUnitInference(output: RealArrayTensor)
  : Unit

  final override protected def doPredictForChannelTraining(inPlaceAllowed: Boolean,
                                                           input:          Tensor,
                                                           learningRate:   Real)
  : (Tensor, PredictContext) = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForChannelTraining(out, learningRate)
    (out, EmptyContext)
  }

  protected def doPredictForChannelTraining(output:       RealArrayTensor,
                                            learningRate: Real)
  : Unit

  final override protected def doPredictForChannelInference(inPlaceAllowed: Boolean,
                                                            input:          Tensor)
  : Tensor = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForChannelInference(out)
    out
  }

  protected def doPredictForChannelInference(output: RealArrayTensor)
  : Unit

  final override protected def doPredictForSampleTraining(inPlaceAllowed: Boolean,
                                                          input:          Tensor,
                                                          learningRate:   Real)
  : (Tensor, PredictContext) = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForSampleTraining(out, learningRate)
    (out, EmptyContext)
  }

  protected def doPredictForSampleTraining(output:       RealArrayTensor,
                                           learningRate: Real)
  : Unit

  final override protected def doPredictForSampleInference(inPlaceAllowed: Boolean,
                                                           input:          Tensor)
  : Tensor = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForSampleInference(out)
    out
  }

  protected def doPredictForSampleInference(output: RealArrayTensor)
  : Unit

  final override protected def doPredictForBatchTraining(inPlaceAllowed: Boolean,
                                                         input:          Tensor,
                                                         learningRate:   Real)
  : (Tensor, PredictContext) = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForBatchTraining(out, learningRate)
    (out, EmptyContext)
  }

  protected def doPredictForBatchTraining(output:       RealArrayTensor,
                                          learningRate: Real)
  : Unit

  final override protected def doPredictForBatchInference(inPlaceAllowed: Boolean,
                                                          input:          Tensor)
  : Tensor = {
    val out = {
      if (inPlaceAllowed) {
        input.asOrToRealArrayTensor
      }
      else {
        input.toRealArrayTensor
      }
    }
    doPredictForBatchInference(out)
    out
  }

  protected def doPredictForBatchInference(output: RealArrayTensor)
  : Unit

  // ---------------------------------------------------------------------------
  //    Back propagation related.
  // ---------------------------------------------------------------------------
  final override protected def doDeriveInputErrorForUnit(context: PredictContext,
                                                         error:   Tensor)
  : RealArrayTensor = {
    val err = error.asOrToRealArrayTensor
    doDeriveInputErrorForUnit(context, err)
    err
  }

  protected def doDeriveInputErrorForUnit(context: PredictContext,
                                          error:   RealArrayTensor)
  : Unit

  final override protected def doDeriveInputErrorForChannel(context: PredictContext,
                                                            error:   Tensor)
  : RealArrayTensor = {
    val err = error.asOrToRealArrayTensor
    doDeriveInputErrorForChannel(context, err)
    err
  }

  protected def doDeriveInputErrorForChannel(context: PredictContext,
                                             error:   RealArrayTensor)
  : Unit

  final override protected def doDeriveInputErrorForSample(context: PredictContext,
                                                           error:   Tensor)
  : RealArrayTensor = {
    val err = error.asOrToRealArrayTensor
    doDeriveInputErrorForSample(context, err)
    err
  }

  protected def doDeriveInputErrorForSample(context: PredictContext,
                                            error:   RealArrayTensor)
  : Unit

  final override protected def doDeriveInputErrorForBatch(context: PredictContext,
                                                          error:   Tensor)
  : RealArrayTensor = {
    val err = error.asOrToRealArrayTensor
    doDeriveInputErrorForBatch(context, err)
    err
  }

  protected def doDeriveInputErrorForBatch(context: PredictContext,
                                           error:   RealArrayTensor)
  : Unit

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="http://octavioturra.github.io/color-picker/">

    <meta property="og:title" content="<color-picker>">
    <meta property="og:description" content="Paper.js and canvas element wrapper.">
    <meta property="og:url" content="http://octavioturra.github.io/color-picker/">
    <meta property="og:image" content="http://octavioturra.github.io/color-picker/demo/fb.png">

    <title><color-picker></title>

    <link rel="icon" href="https://github.global.ssl.fastly.net/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure.css">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto+Slab">
    <link rel="stylesheet" href="demo/demo.css">

    <link rel="import" href="src/color-picker.html">

<color

picker>

                Simple dual color picker.

Install

Install the component using Bower

$ bower install color-picker

                        Fork on GitHub
                        Download as ZIP

<color-picker>

Simple dual color picker.

In the following demo, we set a basic color-picker.

                    <color-picker></color-picker>

<color-picker></color-picker>

In the following demo, we simple switch color priority.

                    <color-picker id="picker"></color-picker>
                    <button id="switcher">Switch</button>

<color-picker id="picker"></color-picker>
<script>
window.addEventListener('polymer-ready', function(e) {

	var switcher = document.querySelector('#switcher');
	var picker = document.querySelector('#picker');

	switcher.style.backgroundColor = picker.primary;
	switcher.style.color = picker.secundary;

	switcher.addEventListener('click', function(){
			picker.switchColor();
			switcher.style.backgroundColor = picker.primary;
			switcher.style.color = picker.secundary;
	});
});
</script>

We have 3 picker style behaviors:

                    <color-picker label="With shadow" class="shadow"></color-picker>

                    <color-picker label="With square" class="square"></color-picker>

                    <color-picker label="With square and shadow" class="square shadow"></color-picker>

It has 3 label style behaviors:

                    <color-picker label="None"></color-picker>

                    <color-picker label="Horizontal" class="horizontal"></color-picker>

                    <color-picker label="Vertical" class="vertical"></color-picker>

It has 3 label style behaviors:

                    <color-picker label="None"></color-picker>

                    <color-picker label="Horizontal" class="horizontal"></color-picker>

                    <color-picker label="Vertical" class="vertical"></color-picker>

Accepts HEX, RGB, HSL and names for color initial input:

                    <color-picker label="None" primary="red" secundary="HSL(20%, 10%, 30%)"></color-picker>

Features

                        Color-picker

                       	Simple dual color picker.

Usage

1. Import Web Components' polyfill

<script src="bower_components/platform/platform.js"></script>

2. Import Custom Element

<link rel="import" href="bower_components/paper-canvas/dist/color-picker.html">

3. Start using it!

<color-picker></color-picker>

                Made by Octávio Turra under MIT license

    <link href="demo/highlight.github.css" rel="stylesheet">


text:
package org.gradle.play.tasks;

import com.google.common.collect.Lists;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileOperations;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.file.RelativeFile;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.SourceTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.compile.BaseForkOptions;
import org.gradle.language.base.internal.tasks.SimpleStaleClassCleaner;
import org.gradle.language.base.internal.tasks.StaleClassCleaner;
import org.gradle.platform.base.internal.toolchain.ResolvedTool;
import org.gradle.play.internal.javascript.DefaultJavaScriptCompileSpec;
import org.gradle.play.internal.javascript.JavaScriptCompileSpec;
import org.gradle.play.toolchain.PlayToolChain;
import org.gradle.language.base.internal.compile.Compiler;

import javax.inject.Inject;
import java.io.File;
import java.util.List;

/**
 * Task to minify JavaScript assets.
 */
@Incubating
public class JavaScriptMinify extends SourceTask {
    private File destinationDir;
    private ResolvedTool<Compiler<JavaScriptCompileSpec>> compilerTool;
    private BaseForkOptions forkOptions;

    public JavaScriptMinify() {
        this.include("**/*.js");
    }

    @Inject
    protected FileResolver getFileResolver() {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns the tool chain that will be used to compile the javascript source.
     *
     * @return The tool chain.
     */
    @Incubating
    @Inject
    public PlayToolChain getToolChain() {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns the output directory that processed javascript is written to.
     *
     * @return The output directory.
     */
    @OutputDirectory
    public File getDestinationDir() {
        return destinationDir;
    }

    /**
     * Sets the output directory where processed javascript should be written.
     *
     * @param destinationDir The output directory.
     */
    public void setDestinationDir(File destinationDir) {
        this.destinationDir = destinationDir;
    }

    public void setCompilerTool(ResolvedTool<Compiler<JavaScriptCompileSpec>> compilerTool) {
        this.compilerTool = compilerTool;
    }

    /**
     * The fork options to be applied to the javascript compiler.
     *
     * @return The fork options for the javascript compiler.
     */
    public BaseForkOptions getForkOptions() {
        if (forkOptions == null) {
            forkOptions = new BaseForkOptions();
        }
        return forkOptions;
    }

    @TaskAction
    void compileJavaScriptSources() {
        StaleClassCleaner cleaner = new SimpleStaleClassCleaner(getOutputs());
        cleaner.setDestinationDir(getDestinationDir());
        cleaner.execute();

        MinifyFileVisitor visitor = new MinifyFileVisitor();
        getSource().visit(visitor);

        JavaScriptCompileSpec spec = new DefaultJavaScriptCompileSpec(visitor.relativeFiles, getDestinationDir(), getForkOptions());
        compilerTool.get().execute(spec);
    }

    /**
     * Copies each file in the source set to the output directory and gathers relative files for compilation
     */
    class MinifyFileVisitor implements FileVisitor {
        List<RelativeFile> relativeFiles = Lists.newArrayList();

        @Override
        public void visitDir(FileVisitDetails dirDetails) {
            new File(destinationDir, dirDetails.getRelativePath().getPathString()).mkdirs();
        }

        @Override
        public void visitFile(final FileVisitDetails fileDetails) {
            final File outputFileDir = new File(destinationDir, fileDetails.getRelativePath().getParent().getPathString());

            // Copy the raw form
            FileOperations fileOperations = (ProjectInternal) getProject();
            fileOperations.copy(new Action<CopySpec>() {
                @Override
                public void execute(CopySpec copySpec) {
                    copySpec.from(fileDetails.getFile()).into(outputFileDir);
                }
            });

            // Capture the relative file
            relativeFiles.add(new RelativeFile(fileDetails.getFile(), fileDetails.getRelativePath()));
        }
    }
}


text:
var fs = require("fs"),
    path = require("path"),
    urlparse = require("url").parse,
    assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    _ = require("underscore-contrib"),
    Step = require("step"),
    Activity = require("../lib/model/activity").Activity,
    User = require("../lib/model/user").User,
    Person = require("../lib/model/person").Person,
    schema = require("../lib/schema").schema,
    URLMaker = require("../lib/urlmaker").URLMaker,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("automatic repair of user profile");

var tc = JSON.parse(fs.readFileSync(path.resolve(__dirname, "config.json")));

suite.addBatch({

    "When we set up the app": {
        topic: function() {

            var cb = this.callback;
            // Need this to make IDs

            URLMaker.hostname = "example.net";

            // Dummy databank

            tc.params.schema = schema;

            var db = Databank.get(tc.driver, tc.params);

            db.connect(tc.params, function(err) {
                var mod;

                if (err) {
                    cb(err, null);
                } else {
                    DatabankObject.bank = db;
                    cb(null, db);
                }
            });
        },
        "it works": function(err, db) {
            assert.ifError(err);
            assert.isObject(db);
        },
        teardown: function(db) {
            if (_.isObject(db) && _.isFunction(db.disconnect)) {
                db.disconnect(function(err) {});
            }
        },
        "and we get a profile with bad standard feeds": {
            topic: function(db) {
                var user;
                Step(
                    function() {
                        var props = {
                            nickname: "george",
                            password: "flat-top1"
                        };
                        User.create(props, this);
                    },
                    function(err, results) {
                        var profile;
                        if (err) throw err;
                        user = results;
                        profile = user.profile;
                        profile.replies = {
                            url: "http://example.com/api/person/AAAAAAAA/replies"
                        };
                        profile.likes = {
                            url: "http://example.com/api/person/AAAAAAAA/likes"
                        };
                        profile.shares = {
                            url: "http://example.com/api/person/AAAAAAAA/shares"
                        };
                        // Note: we're routing around the Person
                        db.update("person", profile.id, profile, this);
                    },
                    function(err, results) {
                        if (err) throw err;
                        Person.get(results.id, this);
                    },
                    this.callback
                );
            },
            "the feeds are automatically corrected": function(err, person) {
                assert.ifError(err);
                assert.equal(urlparse(person.replies.url).hostname, "example.net");
                assert.equal(urlparse(person.likes.url).hostname, "example.net");
                assert.equal(urlparse(person.shares.url).hostname, "example.net");
            }
        },
        "and we get a profile with missing links": {
            topic: function(db) {
                var user;
                Step(
                    function() {
                        var props = {
                            nickname: "harold",
                            password: "bad-haircut-4"
                        };
                        User.create(props, this);
                    },
                    function(err, results) {
                        var profile;
                        if (err) throw err;
                        user = results;
                        profile = user.profile;
                        delete profile.links["activity-inbox"];
                        delete profile.links["activity-outbox"];
                        // Note: we're routing around the Person
                        db.update("person", profile.id, profile, this);
                    },
                    function(err, results) {
                        if (err) throw err;
                        Person.get(results.id, this);
                    },
                    this.callback
                );
            },
            "the feeds are automatically corrected": function(err, person) {
                assert.ifError(err);
                assert.isObject(person);
                assert.isObject(person.links);
                assert.isObject(person.links["activity-inbox"]);
                assert.equal(urlparse(person.links["activity-inbox"].href).hostname, "example.net");
                assert.isObject(person.links["activity-outbox"]);
                assert.equal(urlparse(person.links["activity-outbox"].href).hostname, "example.net");
            }
        }
    }
});

suite["export"](module);


text:
package net.haugr.cws.api.responses;

import net.haugr.cws.api.common.Constants;
import net.haugr.cws.api.common.ReturnCode;

/**
 *
The response from the MasterKey request is limited to error information,
 * or information about the successful changing or altering a key. The message
 * from the response will provide more detailed information about what happened
 * internally.

 *
 *
Please see {@link CwsResponse} for information about the result of the
 * processing.

 *
 * @author Kim Jensen
 * @since CWS 1.0
 */
public final class MasterKeyResponse extends CwsResponse {

    /** {@link Constants#SERIAL_VERSION_UID}. */
    private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;

    // =========================================================================
    // Object Constructors
    // =========================================================================

    /**
     * Empty Constructor, to use if the setters are invoked. This is required
     * for WebServices to work properly.
     */
    public MasterKeyResponse() {
        // Empty Constructor, required for WebServices
    }

    /**
     * Error Constructor, used if an error occurred, and the request could not
     * complete successfully.
     *
     * @param returnCode    The CWS Return Code
     * @param returnMessage The CWS Return Message
     */
    public MasterKeyResponse(final ReturnCode returnCode, final String returnMessage) {
        super(returnCode, returnMessage);
    }
}


text:
package com.jdon.model.factory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.jdon.annotation.Component;
import com.jdon.container.access.xml.AppConfigureCollection;
import com.jdon.container.pico.Startable;
import com.jdon.model.config.ConfigureReader;
import com.jdon.model.config.ModelMapping;
import com.jdon.util.Debug;

/**
 * 根据modelmapping.xml生产相应的实例 下面两个方法预先需要执行: loadMapping(); //获取xml
 * createModelClass();//预先创建一些class
 *
 * ModelFactory是有状态的类。
 *
 * @author banq
 */
@Component
public final class ModelHandlerClassXMLBuilder implements Startable {
	public final static String module = ModelHandlerClassXMLBuilder.class.getName();

	private final ModelHandlerClassFactory modelHandlerClassFactory;

	private final Map configLoadedList = new HashMap();

	/**
	 * key is formName /value is ModelMapping
	 */
	private final Map mps = new HashMap();

	/**
	 * key is formName /value is Model class
	 */
	private final Map modelClasses = new HashMap();

	/**
	 * key is formName /value is ModelHandler class
	 */
	private final Map handlerClasses = new HashMap();

	public ModelHandlerClassXMLBuilder(AppConfigureCollection appConfigureFiles, ModelHandlerClassFactory handlerClassFactory) {
		this.modelHandlerClassFactory = handlerClassFactory;
		Iterator iter = appConfigureFiles.getConfigList().iterator();
		while (iter.hasNext()) {
			String configFile = (String) iter.next();
			if (!configLoadedList.containsKey(configFile)) {
				ConfigureReader configureReader = new ConfigureReader(configFile);
				Debug.logVerbose("[JdonFramework]init configFile = " + configFile, module);
				configLoadedList.put(configFile, configureReader);
			}
		}
	}

	/**
	 * 将所有的ConfigureLoader包含的内容合并在一起。 本方法相当于start() 参考 {@link #detroy()} method
	 *
	 */
	public void start() {
		try {
			Iterator iter = configLoadedList.keySet().iterator();
			while (iter.hasNext()) {
				String configFile = (String) iter.next();
				Debug.logVerbose("[JdonFramework] start configFile = " + configFile, module);
				ConfigureReader configureLoader = (ConfigureReader) configLoadedList.get(configFile);
				Map modelMappings = configureLoader.load();
				mps.putAll(modelMappings);

				Iterator mpsIter = modelMappings.keySet().iterator();
				while (mpsIter.hasNext()) {
					String formName = (String) mpsIter.next();
					build(formName);
				}
			}
			configLoadedList.clear();
		} catch (Exception ex) {
			Debug.logError("[JdonFramework] !!!!!!!framework started error: " + ex, module);
		}
	}

	private void build(String formName) {
		Debug.logVerbose("[JdonFramework] start build model for formName = " + formName, module);
		ModelMapping modelMapping = (ModelMapping) mps.get(formName);
		try {

			Class modelClass = modelHandlerClassFactory.createModel(modelMapping);
			modelClasses.put(formName, modelClass);

			Class keyClassType = modelHandlerClassFactory.createModelKeyClassType(modelMapping, modelClass);
			modelMapping.setKeyClassType(keyClassType);

			handlerClasses.put(formName, modelHandlerClassFactory.createHandler(modelMapping));
		} catch (Exception e) {
			Debug.logError("[JdonFramework] build error: " + e, module);
		}
	}

	/**
	 * 清除内存
	 */
	public void stop() {
		mps.clear();
		configLoadedList.clear();
		modelClasses.clear();
		handlerClasses.clear();
	}

	public ModelMapping getModelMapping(String formName) {
		return (ModelMapping) mps.get(formName);
	}

	/**
	 * @return Returns the handlerClasses.
	 */
	public Class getHandlerClasses(String formName) {
		return (Class) handlerClasses.get(formName);
	}

	/**
	 * @return Returns the modelClasses.
	 */
	public Class getModelClasses(String formName) {
		return (Class) modelClasses.get(formName);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>

<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
                       android:accountType="net.jmreyes.tutela"
                       android:icon="@drawable/ic_launcher"
                       android:label="@string/app_name"
                       android:smallIcon="@drawable/ic_launcher" />


text:
package org.onosproject.incubator.net.virtual;

import com.google.common.testing.EqualsTester;
import org.junit.Test;
import org.onosproject.net.TestDeviceParams;

import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

/**
 * Test of the default virtual host model entity.
 */
public class DefaultVirtualHostTest extends TestDeviceParams {

    /**
     * Checks that the DefaultVirtualHost class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(DefaultVirtualHost.class);
    }

    /**
     * Tests the DefaultVirtualHost equality method.
     */
    @Test
    public void testEquality() {
        DefaultVirtualHost host1 =
                new DefaultVirtualHost(NetworkId.networkId(0), HID1, MAC1, VLAN1, LOC1, IPSET1);
        DefaultVirtualHost host2 =
                new DefaultVirtualHost(NetworkId.networkId(0), HID1, MAC1, VLAN1, LOC1, IPSET1);
        DefaultVirtualHost host3 =
                new DefaultVirtualHost(NetworkId.networkId(0), HID2, MAC1, VLAN1, LOC1, IPSET1);
        DefaultVirtualHost host4 =
                new DefaultVirtualHost(NetworkId.networkId(1), HID2, MAC1, VLAN1, LOC1, IPSET1);

        new EqualsTester().addEqualityGroup(host1, host2).addEqualityGroup(host3)
                .addEqualityGroup(host4).testEquals();
    }
}


text:
<?php

      global $wp_customize;

      echo '
';

        echo '
';

          echo '
';

            $zerif_testimonials_title = get_theme_mod('zerif_testimonials_title',__('Testimonials','zerif-lite'));

            if( !empty($zerif_testimonials_title) ):

              echo '
'.$zerif_testimonials_title.'
';

            elseif ( isset( $wp_customize ) ):

              echo '

';

            endif;

            $zerif_testimonials_subtitle = get_theme_mod('zerif_testimonials_subtitle');

            if( !empty($zerif_testimonials_subtitle) ):

              echo '
'.wp_kses_post( $zerif_testimonials_subtitle ).'
';

            elseif ( isset( $wp_customize ) ):

              echo '

';

            endif;

          echo '
';

          echo '
';

            echo '
';

              $pinterest_style = '';
              $zerif_testimonials_pinterest_style = get_theme_mod('zerif_testimonials_pinterest_style');
              if( isset($zerif_testimonials_pinterest_style) && $zerif_testimonials_pinterest_style != 0 ) {
                $pinterest_style = 'testimonial-masonry';
              }

              echo '
';

                  if(is_active_sidebar( 'sidebar-testimonials' )):
                    dynamic_sidebar( 'sidebar-testimonials' );
                  else:

                    if ( file_exists( get_stylesheet_directory_uri().'/images/testimonial1.jpg' ) ):
                      the_widget('zerif_testimonial_widget', 'title=Dana Lorem&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri=' . get_stylesheet_directory_uri() . '/images/testimonial1.jpg');
                    else:
                      the_widget('zerif_testimonial_widget', 'title=Dana Lorem&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri=' . get_template_directory_uri() . '/images/testimonial1.jpg');
                    endif;

                    if ( file_exists( get_stylesheet_directory_uri().'/images/testimonial2.jpg' ) ):
                      the_widget('zerif_testimonial_widget', 'title=Linda Guthrie&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri=' . get_stylesheet_directory_uri() . '/images/testimonial2.jpg');
                    else:
                      the_widget( 'zerif_testimonial_widget','title=Linda Guthrie&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri='.get_template_directory_uri().'/images/testimonial2.jpg' );
                    endif;

                    if ( file_exists( get_stylesheet_directory_uri().'/images/testimonial3.jpg' ) ):
                      the_widget( 'zerif_testimonial_widget','title=Cynthia Henry&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri='.get_stylesheet_directory_uri().'/images/testimonial3.jpg' );
                    else:
                      the_widget( 'zerif_testimonial_widget','title=Cynthia Henry&text=Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur nec sem vel sapien venenatis mattis non vitae augue. Nullam congue commodo lorem vitae facilisis. Suspendisse malesuada id turpis interdum dictum.&image_uri='.get_template_directory_uri().'/images/testimonial3.jpg' );
                    endif;
                  endif;

              echo '
';

            echo '
';

          echo '
';

                    echo '
';

?>

  More Testimonials

  <?php
    echo '
';
?>


text:
#ifndef USERNAMEGETTER_H
#define USERNAMEGETTER_H

#include <QObject>
#include <QSqlDatabase>
#include "httpgetter.h"

class MainWindow;

class UserNameGetter : public HttpGetter
{
  Q_OBJECT
public:
  UserNameGetter(MainWindow* mwin, QObject* parent, QString userID);
  ~UserNameGetter();

  void get();

private:
  QString userID;
private slots:
  void gotReply(QNetworkReply* reply);

signals:
  void got(QString username);

};

#endif // USERNAMEGETTER_H


text:
<?php
/**
 * Created by PhpStorm.
 * User: mmorais
 * Date: 22/01/17
 * Time: 06:00
 */

namespace App\Http\Services;

interface CRUDService
{
    public function get($id);
    public function getAll();
    public function save(array $array);
    public function update($id,array $array);
    public function delete($id);
}