text:
package com.acme;

import com.attivio.TestUtils;
import com.attivio.app.Attivio;
import com.attivio.app.config.Configuration;
import com.attivio.client.ContentFeeder;
import com.attivio.client.SearchClient;
import com.attivio.messages.QueryRequest;
import com.attivio.messages.QueryResponse;
import com.attivio.model.FieldNames;
import com.attivio.model.document.AttivioDocument;
import org.junit.Assert;
import org.junit.Test;

/**
 * Sample integration test.
 *
 * This integration test can be used for basic integration testing
 * as well as debugging/tracing throughout the entire system.
 *
 */
public class SampleIntegrationTest extends BaseTest {

  @Test
  public void simpleTest() throws Exception {
    ContentFeeder feeder = null;
    try {
      // 'attivio.xml' should be replaced with your project's main configuration file
      Configuration cfg = TestUtils.getConfiguration("attivio.xml");

      Attivio.getInstance().start(cfg, true);

      // feed some content
      feeder = new ContentFeeder();
      feeder.setMessageResultListener(new SampleMessageResultListener());
      feeder.setIngestWorkflowName("ingest");
      AttivioDocument doc = new AttivioDocument("1234");
      doc.setField(FieldNames.TITLE, "test 123");
      feeder.feed(doc);
      feeder.commit();
      feeder.waitForCompletion();

      // now search for documents
      SearchClient searcher = new SearchClient();
      QueryRequest req = new QueryRequest("*:*");
      QueryResponse resp = searcher.search(req);
      Assert.assertEquals(1, resp.getTotalRows());

    } finally {
      if (feeder != null) feeder.disconnect();
      Attivio.getInstance().shutdown();
    }

  }

}


text:
{% extends "templates/base.html" %}

{% block body %}

Skald Dev

            Version

            Build Date

            Revision

            PIXI Version

Feature Tests

Select one of the tests below to start:

        {% for test in all_tests %}

{{test}}

        {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
@extends('protected.master')

@section('title', 'Admin Dashboard')

@section('content')

	@if (Session::has('flash_message'))

{{ Session::get('flash_message') }}

	@endif

Admin Page

This page is for admins only!

@stop


text:
Get NowJS http://www.nowjs.com/
=========

###NowJS makes realtime web apps really easy.

Go to Github or
Download the master tgz

Install From npm
----------------

`npm install now` or `npm install now -g` to install globally

NowJS is a Node.js module. The client javascript (now.js) is served by the NowJS server.

NowJS uses the excellent socket.io and node-proxy libraries.

2 Step Setup
==============

**1. On the server**

    var httpServer = require('http').createServer(function(req, response){ /* Serve your static files */ })
    httpServer.listen(8080);

    var nowjs = require("now");
    var everyone = nowjs.initialize(httpServer);

    everyone.now.logStuff = function(msg){
        console.log(msg);
    }

**2. On the client**

<script type="text/javascript" src="http://localhost:8080/nowjs/now.js"></script>

<script type="text/javascript">
  now.ready(function(){
    // "Hello World!" will print on server
    now.logStuff("Hello World!");
  });
</script>

FAQ
-------

**Q: Can I pass in a callback or closure, for example, if the remote function is asynchronous?**

A: Yes. This is 100% supported

**Q: How do I use NowJS with [Express](https://github.com/visionmedia/express)?**

A: Very easily.

    var app = express.createServer();
    var server = app.listen(3000);
    var everyone = require("now").initialize(server);

**Q: How do I disable WebSockets or only use xhr-polling?**

A: You can specifiy exactly which transports to use as an initialization options as follows:

    var nowjs = require("now");
    var everyone = nowjs.initialize(yourHttpServer, {socketio: {transports: ['xhr-polling', 'jsonp-polling']}});

**Q: Error: " SyntaxError: Unexpected token *" / Can I statically host the now.js file?**

A: On the client side, make sure you link to now.js like this

You do not need to host the file /nowjs/now.js. It is automatically hosted by the NowJS using the http server you pass into the .initialize(...) in your server code. If you choose to host now.js yourself, you can, but **do not use the version in github repo** you MUST save the file at `http://myserver:myport/nowjs/now.js` and host that, because it is automatically configured for your server.

Further Reading
---------------

Now that you have NowJS, try the NowJS [User Manual](http://nowjs.com/doc) and [Quick Chat Example](http://nowjs.com/guide)

Have more questions? Please contact us:
Email: team@nowjs.com

IRC: [#nowjs on freenode](http://webchat.freenode.net/?nick=nowjs.&channels=nowjs)

Twitter: [@NowJSTeam](http://twitter.com/nowjsteam)


text:
+++
title = "Academic: the website designer for Hugo"

date = 2016-04-20
lastmod = 2018-01-13
draft = false

tags = ["academic"]
summary = "Create a beautifully simple website or blog in under 10 minutes."

[header]
image = "headers/getting-started.png"
caption = "Image credit: [**Academic**](https://github.com/gcushen/hugo-academic/)"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-default.png"
caption = "Default"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-ocean.png"
caption = "Ocean"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-dark.png"
caption = "Dark"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-forest.png"
caption = "Default"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-coffee-playfair.png"
caption = "Coffee theme with Playfair font"

[[gallery_item]]
album = "1"
image = "https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/theme-1950s.png"
caption = "1950s"
+++

**Academic** is a framework to help you create a beautiful website quickly. Perfect for personal sites, blogs, or business/project sites. [Check out the latest demo](https://themes.gohugo.io/theme/academic/) of what you'll get in less than 10 minutes. Then head on over to the [Quick Start guide](https://sourcethemes.com/academic/docs/) or take a look at the [Release Notes](https://sourcethemes.com/academic/updates/).

[![Screenshot](https://raw.githubusercontent.com/gcushen/hugo-academic/master/academic.png)](https://github.com/gcushen/hugo-academic/)

Key features:

- Easily manage various content including homepage, blog posts, publications, talks, and projects
- Extensible via **color themes** and **widgets/plugins**
- Write in [Markdown](https://sourcethemes.com/academic/docs/writing-markdown-latex/) for easy formatting and code highlighting, with [LaTeX](https://en.wikibooks.org/wiki/LaTeX/Mathematics) for mathematical expressions
- Social/academic network linking, [Google Analytics](https://analytics.google.com), and [Disqus](https://disqus.com) comments
- Responsive and mobile friendly
- Simple and refreshing one page design
- Multilingual and easy to customize

## Color Themes

Academic is available in different color themes and font themes.

{{< gallery >}}

## Install

You can choose from one of the following four methods to install:

* one-click install using your web browser (recommended)
* install on your computer using Git with the Command Prompt/Terminal app
* install on your computer by downloading the ZIP files
* install on your computer with RStudio

### Quick install using your web browser

1. [Install Academic with Netlify](https://app.netlify.com/start/deploy?repository=https://github.com/sourcethemes/academic-kickstart)
    * Netlify will provide you with a customizable URL to access your new site
2. On GitHub, go to your newly created `academic-kickstart` repository and edit `config.toml` to personalize your site. Shortly after saving the file, your site will automatically update
3. Read the [Quick Start Guide](https://sourcethemes.com/academic/docs/) to learn how to add Markdown content. For inspiration, refer to the [Markdown content](https://github.com/gcushen/hugo-academic/tree/master/exampleSite) which powers the [Demo](https://themes.gohugo.io/theme/academic/)

### Install with Git

Prerequisites:

* [Download and install Git](https://git-scm.com/downloads)
* [Download and install Hugo](https://gohugo.io/getting-started/installing/#quick-install)

1. [Fork](https://github.com/sourcethemes/academic-kickstart#fork-destination-box) the *Academic Kickstart* repository and clone your fork with Git:

        git clone https://github.com/sourcethemes/academic-kickstart.git My_Website

    *Note that if you forked Academic Kickstart, the above command should be edited to clone your fork, i.e. replace `sourcethemes` with your GitHub username.*

2. Initialize the theme:

        cd My_Website
        git submodule update --init --recursive

### Install with ZIP

1. [Download](https://github.com/sourcethemes/academic-kickstart/archive/master.zip) and extract *Academic Kickstart*
2. [Download](https://github.com/gcushen/hugo-academic/archive/master.zip) and extract the *Academic theme* to the `themes/academic/` folder from the above step

### Install with RStudio

[View the guide to installing Academic with RStudio](https://sourcethemes.com/academic/docs/install/#install-with-rstudio)

## Quick start

1. If you installed on your computer, view your new website by running the following command:

        hugo server

    Now visit [localhost:1313](http://localhost:1313) and your new Academic powered website will appear. Otherwise, if using Netlify, they will provide you with your URL.

2. Read the [Quick Start Guide](https://sourcethemes.com/academic/docs/) to learn how to add Markdown content, customize your site, and deploy it. For inspiration, refer to the [Markdown content](https://github.com/gcushen/hugo-academic/tree/master/exampleSite) which powers the [Demo](https://themes.gohugo.io/theme/academic/)

3. Build your site by running the `hugo` command. Then [host it for free using Github Pages](https://georgecushen.com/create-your-website-with-hugo/) or Netlify (refer to the first installation method). Alternatively, copy the generated `public/` directory (by FTP, Rsync, etc.) to your production web server (such as a university's hosting service).

## Updating

Feel free to *star* the project on [Github](https://github.com/gcushen/hugo-academic/) to help keep track of updates and check out the [release notes](https://sourcethemes.com/academic/updates) prior to updating your site.

Before updating the framework, it is recommended to make a backup of your entire website directory (or at least your `themes/academic` directory) and record your current version number.

By default, Academic is installed as a Git submodule which can be updated by running the following command:

```bash
git submodule update --remote --merge
```

[Check out the update guide](https://sourcethemes.com/academic/docs/update/) for full instructions and alternative methods.

## Feedback & Contributing

Please use the [issue tracker](https://github.com/gcushen/hugo-academic/issues) to let me know about any bugs or feature requests, or alternatively make a pull request.

For support, head over to the [Hugo discussion forum](http://discuss.gohugo.io).

## License

Copyright 2016-present [George Cushen](https://georgecushen.com).

Released under the [MIT](https://github.com/gcushen/hugo-academic/blob/master/LICENSE.md) license.


text:
typedef struct
{
    i8 state;
    bool dma;
    u16 audlenLatch;
    u16 audlen;
    u16 audperLatch;
    i32 audper;
    u16 audvolLatch;
    u16 audvol;
    u16 auddat;
}
AudioChannelInfo;

typedef struct
{
    AudioChannelInfo channel[4];
}
AudioInfo;


text:
<?php
declare(strict_types = 1);

namespace Domain\Command\HtmlPage;

use Domain\Entity\HtmlPage\Identity;

final class SpecifyTitle
{
    private Identity $identity;
    private string $title;

    public function __construct(Identity $identity, string $title)
    {
        $this->identity = $identity;
        $this->title = $title;
    }

    public function identity(): Identity
    {
        return $this->identity;
    }

    public function title(): string
    {
        return $this->title;
    }
}


text:
typedef enum testStatus {ERROR, PASS, FAIL} TestStatus;

TestStatus test_file(char* filename, int printParsingResults) {

    NSString *path = [NSString stringWithCString:filename encoding:NSUTF8StringEncoding];

    //NSLog(@"--- %@", path);

//    if([path hasSuffix:@"n_structure_100000_opening_arrays.json"]) return ERROR;
//    if([path hasSuffix:@"n_structure_empty.json"]) return ERROR;

    NSData *data = [NSData dataWithContentsOfFile:path];

    JSONDecoder *decoder = [JSONDecoder decoderWithParseOptions:JKParseOptionNone];

    NSError *error = nil;
    id o = [decoder objectWithData:data error:&error];

    if (printParsingResults) {
        NSLog(@"--------------------------------\n");
        NSLog(@"-- file: %@\n", path);
        NSLog(@"-- contents: %@\n", data);
        NSLog(@"-- parsed: %d\n", o != NULL);
        if(o != NULL) {
            NSLog(@"-- o: %@", o);
        }
    }

    //    if (value == NULL) {
    //        fprintf(stderr, "Unable to parse data\n");
    //        free(file_contents);
    //        return 1;
    //    }

    return o != nil ? PASS : FAIL;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        const char* path = argv[1];

        int printParsingResults = 0;

        int result = test_file(path, printParsingResults);

        if (result == PASS) {
            return 0;
        } else {
            return 1;
        }

    }
    return 0;
}


text:
<?php

namespace Symfony\Component\Templating\Asset;

/**
 * Asset package interface.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
interface PackageInterface
{
    /**
     * Returns the asset package version.
     *
     * @return string The version string
     */
    public function getVersion();

    /**
     * Returns an absolute or root-relative public path.
     *
     * @param string           $path    A path
     * @param string|bool|null $version A specific version for the path
     *
     * @return string The public path
     */
    public function getUrl($path, $version = null);
}


text:
#ifndef LOWPASS_H_
#define LOWPASS_H_

/*
simple resonant filter posted to musicdsp.org by Paul Kellett http://www.musicdsp.org/archive.php?classid=3#259

// set feedback amount given f and q between 0 and 1
fb = q + q/(1.0 - f);

// for each sample...
buf0 = buf0 + f * (in - buf0 + fb * (buf0 - buf1));
buf1 = buf1 + f * (buf0 - buf1);
out = buf1;

fixed point version of the filter
"dave's blog of art and programming" http://www.pawfal.org/dave/blog/2011/09/
*/

// we are using .n fixed point (n bits for the fractional part)
#define FX_SHIFT 8
#define SHIFTED_1 ((uint8_t) 255)

/** A resonant low pass filter for audio signals.
*/
class LowPassFilter
{

public:

	/** Constructor.
	*/
	LowPassFilter(){;
	}

	/** Set the cut off frequency,
	@param cutoff use the range 0-255 to represent 0-8192 Hz (AUDIO_RATE/2).
	Be careful of distortion at the lower end, especially with high resonance.
	*/
	void setCutoffFreq(uint8_t cutoff)
	{
		f = cutoff;
		fb = q+ucfxmul(q, SHIFTED_1 - cutoff);
	}

	/** Set the resonance. If you hear unwanted distortion, back off the resonance.
	@param resonance in the range 0-255, with 255 being most resonant.
	*/
	void setResonance(uint8_t resonance)
	{
		q = resonance;
	}

	/** Calculate the next sample, given an input signal.
	@param in the signal input.
	@return the signal output.
	@note Timing: about 11us.
	*/
	//	10.5 to 12.5 us, mostly 10.5 us (was 14us)
	inline
	int next(int in)
	{
		//setPin13High();
		buf0+=fxmul(((in - buf0) + fxmul(fb, buf0-buf1)), f);
		buf1+=ifxmul(buf0-buf1, f); // could overflow if input changes fast
		//setPin13Low();
		return buf1;
	}

private:
	uint8_t q;
	uint8_t f;
	unsigned int fb;
	int buf0,buf1;

	// // multiply two fixed point numbers (returns fixed point)
	// inline
	// long fxmul(long a, long b)
	// {
	// 	return (a*b)>>FX_SHIFT;
	// }

	// multiply two fixed point numbers (returns fixed point)
	inline
	unsigned int ucfxmul(uint8_t a, uint8_t b)
	{
		return (((unsigned int)a*b)>>FX_SHIFT);
	}

		// multiply two fixed point numbers (returns fixed point)
	inline
	int ifxmul(int a, uint8_t b)
	{
		return ((a*b)>>FX_SHIFT);
	}

	// multiply two fixed point numbers (returns fixed point)
	inline
	long fxmul(long a, int b)
	{
		return ((a*b)>>FX_SHIFT);
	}

};

/**
@example 10.Audio_Filters/LowPassFilter/LowPassFilter.ino
This example demonstrates the LowPassFilter class.
*/

#endif /* LOWPASS_H_ */


text:
/* Licensed 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.flowable.app.model.editor.decisiontable;

import java.util.List;
import java.util.Map;

/**
 * Created by yvoswillens on 14/08/15.
 */
public class DecisionTableExpressionRepresentation {

    public static final String VARIABLE_TYPE_VARIABLE = "variable";

    protected String id;
    protected String variableId;
    protected String variableType;
    protected String type;
    protected String label;
    protected List<Map<String, String>> entries;
    protected boolean newVariable;

    public boolean isNewVariable() {
        return newVariable;
    }

    public void setNewVariable(boolean newVariable) {
        this.newVariable = newVariable;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getVariableId() {
        return variableId;
    }

    public void setVariableId(String variableId) {
        this.variableId = variableId;
    }

    public String getVariableType() {
        return variableType;
    }

    public void setVariableType(String variableType) {
        this.variableType = variableType;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public List<Map<String, String>> getEntries() {
        return entries;
    }

    public void setEntries(List<Map<String, String>> entries) {
        this.entries = entries;
    }
}


text:
package reflection;

import java.lang.reflect.Constructor;
import java.util.Map;

public class MapaDeClasses {

	private Map<String, String> mapa;

	public Class getClass(String chave) throws Exception {
		String valor = mapa.get(chave);
		if (valor != null) {
			return Class.forName(valor);
		} else {
			throw new RuntimeException("Chave inválida");
		}
	}

	public Object getInstancia(String chave) throws Exception {
		return getClass(chave).newInstance();
	}

	public Object getInstancia(String chave, Object[] params) throws Exception {
		Class clazz = getClass(chave);
		Class<?>[] tiposParams = new Class<?>[params.length];
		for (int i = 0; i < tiposParams.length; i++) {
			tiposParams[i] = params[i].getClass();
		}
		Constructor<?> constructor = clazz.getConstructor(tiposParams);
		return constructor.newInstance(params);
	}
}


text:
export default {
  element: 'form',
  mutate: function(element) {
    element.setAttribute('tabindex', 0);
    element.setAttribute('disabled', 'disabled');
  },
};


text:
def assert
  raise "Assertion failed!" unless yield
end

name = "bettysue"
assert { name == "bettysue" }
assert { name == "billybob" }

# 2. Pseudocode what happens when the code above runs
#define assert
#raise error unless yield is returned
#assert does not have arguments
#billybob is not equal to name

# 3. Copy your selected challenge here
require_relative 'my_solution'

describe CreditCard do
  describe '#initialize' do
    it 'Expects a single argument for the card' do
      expect(CreditCard.instance_method(:initialize).arity).to eq 1
    end

    it 'raises ArgumentError on card > 16' do
      expect { CreditCard.new(11111111111111112) }.to raise_error(ArgumentError)
    end

    it 'raises ArgumentError on card < 16' do
      expect { CreditCard.new(1) }.to raise_error(ArgumentError)
    end
  end

    it 'returns true for a valid card' do
      card = CreditCard.new(4408041234567901)
      expect(card.check_card).to eq true
    end

    it 'returns false for a bad card' do
      card = CreditCard.new(4408041234567906)
      expect(card.check_card).to eq false
    end
  end
end

# 4. Convert your driver test code from that challenge into Assert Statements

assert([object, :message, args])

assert(
  (CreditCard()===true)
  'Expects a single argument for the card'
  "1. "
  )

assert(
    (CreditCard.new===16),
    "CreditCard should have 16 digits",
    "2. "
    )

assert(
  CreditCard.new(4408041234567901)===true
  'returns true for a valid card'
  "3. "
  )

assert(
  CreditCard.new(4408041234567906)===false
  'returns false for a bad card'
  "4. "
  )

# 5. Reflection
#What concepts did you review or learn in this challenge?
  #I learned how to write test statements.
#What is still confusing to you about Ruby?
  #I am still confused about ways to identify what I want to select. I think I need to do more research on syntax.
#What are you going to study to get more prepared for Phase 1?
  #Syntax and i want to do some of the bonus challenges if I will have time before the program starts.


text:
namespace StressGAS {

using Menge::Agents::BaseAgent;

/////////////////////////////////////////////////////////////////////
//                   Implementation of TimedStressFunction
/////////////////////////////////////////////////////////////////////

TimedStressFunction::TimedStressFunction(float duration, BaseAgent* agent, AgentStressor* stressor,
                                         float coolDuration)
    : StressFunction(agent, stressor, coolDuration) {
  _stressRate = 1.f / duration;
}

/////////////////////////////////////////////////////////////////////

float TimedStressFunction::updateStress() {
  _stressLevel += Menge::SIM_TIME_STEP * _stressRate;
  if (_stressLevel > 1.f) {
    _stressLevel = 1.f;
  }
  return _stressLevel;
}

}  // namespace StressGAS


text:
/* @flow */
import AttributeBase, { type AttributeJSON } from './AttributeBase';
import {
  type DeserializeWireBaseOptions,
  type SerializeJSONContext,
} from '../../Serializable';
import type { Equals } from '../../Equatable';
import { InvalidFormatError } from '../../errors';
import { toJSONAttributeUsage } from './AttributeUsage';

import common, {
  type UInt256,
} from '../../common';
import utils, {
  type BinaryWriter,
  IOHelper,
  JSONHelper,
} from '../../utils';

export type UInt256AttributeUsage =
  0x00 |
  0x30 |
  0xa1 |
  0xa2 |
  0xa3 |
  0xa4 |
  0xa5 |
  0xa6 |
  0xa7 |
  0xa8 |
  0xa9 |
  0xaa |
  0xab |
  0xac |
  0xad |
  0xae |
  0xaf;

export type UInt256AttributeAdd = {|
  usage: UInt256AttributeUsage,
  value: UInt256,
|};

export default class UInt256Attribute
  extends AttributeBase<UInt256AttributeUsage, UInt256> {

  constructor({ usage, value }: UInt256AttributeAdd) {
    super();
    this.usage = usage;
    this.value = value;
    this.size = IOHelper.sizeOfUInt8 + IOHelper.sizeOfUInt256;
  }

  equals: Equals = utils.equals(
    UInt256Attribute,
    (other) => (
      this.usage === other.usage &&
      common.uInt256Equal(this.value, other.value)
    ),
  );

  serializeWireBase(writer: BinaryWriter): void {
    super.serializeWireBase(writer);
    writer.writeUInt256(this.value);
  }

  // eslint-disable-next-line
  static deserializeWireBase(options: DeserializeWireBaseOptions): this {
    const { reader } = options;
    const { usage } = super.deserializeAttributeWireBase(options);
    if (!(
      usage === 0x00 ||
      usage === 0x30 ||
      usage === 0xa1 ||
      usage === 0xa2 ||
      usage === 0xa3 ||
      usage === 0xa4 ||
      usage === 0xa5 ||
      usage === 0xa6 ||
      usage === 0xa7 ||
      usage === 0xa8 ||
      usage === 0xa9 ||
      usage === 0xaa ||
      usage === 0xab ||
      usage === 0xac ||
      usage === 0xad ||
      usage === 0xae ||
      usage === 0xaf
    )) {
      throw new InvalidFormatError();
    }
    const value = reader.readUInt256();
    return new this({ usage, value });
  }

  // eslint-disable-next-line
  serializeJSON(context: SerializeJSONContext): AttributeJSON {
    return {
      usage: toJSONAttributeUsage(this.usage),
      data: JSONHelper.writeUInt256(this.value),
    };
  }
}


text:
$("#user-navigation .exit-app").addClass("mobile");
$("#user-navigation .exit-app a").on("click",function(e){
	e.preventDefault();
	if(navigator.Backbutton) {
		navigator.Backbutton.goHome(function() {
			//toastr.success('success home')
		}, function() {
			//toastr.error('fail home')
		});
	}
});


text:
namespace Ui {
class StakeReportDialog;
}

class WalletModel;

class StakeReportDialog : public QDialog
{
    Q_OBJECT

public:
    explicit StakeReportDialog(QWidget *parent = 0);
    ~StakeReportDialog();

    void setModel(WalletModel *model);
    void showEvent(QShowEvent* event);

private:
    Ui::StakeReportDialog *ui;
    WalletModel *ex_model;

    qint64 nLastReportUpdate;
    bool disablereportupdate;
    bool alreadyConnected;

    void updateStakeReport(bool fImmediate);

private slots:
    void updateStakeReportTimer();

public slots:
    void updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64);
    void updateStakeReportNow();
    void updateDisplayUnit(int);
    void CopyAllToClipboard();

};

#endif // STAKEREPORTDIALOG_H


text:
package com.fortitudetec.presto;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;

import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorTableHandle;
import com.facebook.presto.spi.ConnectorTableLayout;
import com.facebook.presto.spi.ConnectorTableLayoutHandle;
import com.facebook.presto.spi.ConnectorTableLayoutResult;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.Constraint;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.SchemaTablePrefix;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;

public abstract class BaseReadOnlyConnectorMetadata implements ConnectorMetadata {

  private static final String DEFAULT_COMMENT = "";

  @Override
  public ConnectorTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) {
    return new BaseTableHandle(tableName);
  }

  @Override
  public List<ConnectorTableLayoutResult> getTableLayouts(ConnectorSession session, ConnectorTableHandle table,
      Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) {
    BaseTableHandle tableHandle = (BaseTableHandle) table;
    BaseTableLayoutHandle baseTableLayoutHandle = createTableLayoutHandle(tableHandle);
    ConnectorTableLayout layout = new ConnectorTableLayout(baseTableLayoutHandle);
    return ImmutableList.of(new ConnectorTableLayoutResult(layout, constraint.getSummary()));
  }

  protected BaseTableLayoutHandle createTableLayoutHandle(BaseTableHandle tableHandle) {
    BaseTableLayoutHandle baseTableLayoutHandle = new BaseTableLayoutHandle(tableHandle);
    return baseTableLayoutHandle;
  }

  @Override
  public ConnectorTableLayout getTableLayout(ConnectorSession session, ConnectorTableLayoutHandle handle) {
    BaseTableLayoutHandle layout = (BaseTableLayoutHandle) handle;
    List<ConnectorTableLayoutResult> tableLayouts = getTableLayouts(session, layout.getTable(),
        Constraint.<ColumnHandle>alwaysTrue(), Optional.empty());
    ConnectorTableLayoutResult connectorTableLayoutResult = tableLayouts.get(0);
    return connectorTableLayoutResult.getTableLayout();
  }

  @Override
  public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle,
      ColumnHandle columnHandle) {
    BaseColumnHandle baseColumnHandle = (BaseColumnHandle) columnHandle;
    return new ColumnMetadata(baseColumnHandle.getColumnName(), baseColumnHandle.getType(), DEFAULT_COMMENT, false);
  }

  @Override
  public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table) {
    BaseTableHandle baseTableHandle = (BaseTableHandle) table;
    Builder<ColumnMetadata> builder = ImmutableList.builder();
    Map<String, ColumnHandle> columnHandles = getColumnHandles(session, table);
    for (Entry<String, ColumnHandle> e : columnHandles.entrySet()) {
      ColumnMetadata columnMetadata = getColumnMetadata(session, table, e.getValue());
      builder.add(columnMetadata);
    }
    return new ConnectorTableMetadata(baseTableHandle.getTableName(), builder.build());
  }

  @Override
  public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session,
      SchemaTablePrefix prefix) {
    ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> mapBuilder = ImmutableMap.builder();
    List<String> listSchemaNames = listSchemaNames(session);
    for (String schema : listSchemaNames) {
      List<SchemaTableName> listTables = listTables(session, schema);
      for (SchemaTableName schemaTableName : listTables) {
        if (prefix.matches(schemaTableName)) {
          Builder<ColumnMetadata> builder = ImmutableList.builder();
          ConnectorTableHandle tableHandle = getTableHandle(session, schemaTableName);
          Map<String, ColumnHandle> columnHandles = getColumnHandles(session, tableHandle);
          for (Entry<String, ColumnHandle> e : columnHandles.entrySet()) {
            builder.add(getColumnMetadata(session, tableHandle, e.getValue()));
          }
          mapBuilder.put(schemaTableName, builder.build());
        }
      }
    }
    return mapBuilder.build();
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="mColorPrimary">#FFBA86FC</color>
    <color name="mColorPrimaryVariant">#FF3700B3</color>
    <color name="mColorPrimaryDark">#FF000000</color>
    <color name="mColorOnPrimary">#FF000000</color>
    <color name="mColorSecondary">#FF03DAC6</color>
    <color name="mColorSecondaryVariant">#FF03DAC6</color>
    <color name="mColorOnSecondary">#FF000000</color>
    <color name="mColorSurface">#FF000000</color>
    <color name="mColorOnSurface">#FFFFFFFF</color>
</resources>


text:
'''Checker which requires argparse.'''

from __future__ import absolute_import, division, print_function, with_statement

import os
import sys

from commitcheck.argutils import git_create_parser, git_get_type
from commitcheck.checkers import Pattern
from commitcheck.checkers.gitchecker import Checker

def main(argv=None):
    argv = sys.argv if argv is None else argv

    # Create parser and parse args.
    parser = git_create_parser(description='Commit checker')
    args = parser.parse_args(argv[1:])
    check_type = git_get_type(args)
    if check_type is None:
        print('Unknown check type: %s' % (args.type))
        return 1

    # Setup to do check.
    path = os.getcwd()
    patterns = [
        Pattern(r'[ \t]+$', 'PTWS', 'Trailing whitespace'),
    ]
    checker = Checker(path, patterns, checks=[r'.*\.py'])
    checker.verbose = args.verbose
    return checker.check(check_type, args.revisions)

if __name__ == '__main__':
    sys.exit(main())


text:
/* eslint-disable no-console, max-len, camelcase, no-unused-vars */
const { strict: assert } = require('assert');
const querystring = require('querystring');
const crypto = require('crypto');
const { inspect } = require('util');

const isEmpty = require('lodash/isEmpty');
const bodyParser = require('koa-body');
const Router = require('koa-router');

const { renderError } = require('../../lib/helpers/defaults')(); // make your own, you'll need it anyway
const Account = require('../support/account');

const keys = new Set();
const debug = (obj) => querystring.stringify(Object.entries(obj).reduce((acc, [key, value]) => {
  keys.add(key);
  if (isEmpty(value)) return acc;
  acc[key] = inspect(value, { depth: null });
  return acc;
}, {}), '<br/>', ': ', {
  encodeURIComponent(value) { return keys.has(value) ? `<strong>${value}</strong>` : value; },
});

module.exports = (provider) => {
  const router = new Router();
  const { constructor: { errors: { SessionNotFound } } } = provider;

  router.use(async (ctx, next) => {
    ctx.set('cache-control', 'no-store');
    try {
      await next();
    } catch (err) {
      if (err instanceof SessionNotFound) {
        ctx.status = err.status;
        const { message: error, error_description } = err;
        renderError(ctx, { error, error_description }, err);
      } else {
        throw err;
      }
    }
  });

  router.get('/interaction/:uid', async (ctx, next) => {
    const {
      uid, prompt, params, session,
    } = await provider.interactionDetails(ctx.req, ctx.res);
    const client = await provider.Client.find(params.client_id);

    switch (prompt.name) {
      case 'login': {
        return ctx.render('login', {
          client,
          uid,
          details: prompt.details,
          params,
          title: 'Sign-in',
          google: ctx.google,
          session: session ? debug(session) : undefined,
          dbg: {
            params: debug(params),
            prompt: debug(prompt),
          },
        });
      }
      case 'consent': {
        return ctx.render('interaction', {
          client,
          uid,
          details: prompt.details,
          params,
          title: 'Authorize',
          session: session ? debug(session) : undefined,
          dbg: {
            params: debug(params),
            prompt: debug(prompt),
          },
        });
      }
      default:
        return next();
    }
  });

  const body = bodyParser({
    text: false, json: false, patchNode: true, patchKoa: true,
  });

  router.get('/interaction/callback/google', (ctx) => {
    const nonce = ctx.res.locals.cspNonce;
    return ctx.render('repost', { layout: false, upstream: 'google', nonce });
  });

  router.post('/interaction/:uid/login', body, async (ctx) => {
    const { prompt: { name } } = await provider.interactionDetails(ctx.req, ctx.res);
    assert.equal(name, 'login');

    const account = await Account.findByLogin(ctx.request.body.login);

    const result = {
      login: {
        accountId: account.accountId,
      },
    };

    return provider.interactionFinished(ctx.req, ctx.res, result, {
      mergeWithLastSubmission: false,
    });
  });

  router.post('/interaction/:uid/federated', body, async (ctx) => {
    const { prompt: { name } } = await provider.interactionDetails(ctx.req, ctx.res);
    assert.equal(name, 'login');

    const path = `/interaction/${ctx.params.uid}/federated`;

    switch (ctx.request.body.upstream) {
      case 'google': {
        const callbackParams = ctx.google.callbackParams(ctx.req);

        // init
        if (!Object.keys(callbackParams).length) {
          const state = `${ctx.params.uid}|${crypto.randomBytes(32).toString('hex')}`;
          const nonce = crypto.randomBytes(32).toString('hex');

          ctx.cookies.set('google.state', state, { path, sameSite: 'strict' });
          ctx.cookies.set('google.nonce', nonce, { path, sameSite: 'strict' });

          ctx.status = 303;
          return ctx.redirect(ctx.google.authorizationUrl({
            state, nonce, scope: 'openid email profile',
          }));
        }

        // callback
        const state = ctx.cookies.get('google.state');
        ctx.cookies.set('google.state', null, { path });
        const nonce = ctx.cookies.get('google.nonce');
        ctx.cookies.set('google.nonce', null, { path });

        const tokenset = await ctx.google.callback(undefined, callbackParams, { state, nonce, response_type: 'id_token' });
        const account = await Account.findByFederated('google', tokenset.claims());

        const result = {
          login: {
            accountId: account.accountId,
          },
        };
        return provider.interactionFinished(ctx.req, ctx.res, result, {
          mergeWithLastSubmission: false,
        });
      }
      default:
        return undefined;
    }
  });

  router.post('/interaction/:uid/confirm', body, async (ctx) => {
    const interactionDetails = await provider.interactionDetails(ctx.req, ctx.res);
    const { prompt: { name, details }, params, session: { accountId } } = interactionDetails;
    assert.equal(name, 'consent');

    let { grantId } = interactionDetails;
    let grant;

    if (grantId) {
      // we'll be modifying existing grant in existing session
      grant = await provider.Grant.find(grantId);
    } else {
      // we're establishing a new grant
      grant = new provider.Grant({
        accountId,
        clientId: params.client_id,
      });
    }

    if (details.missingOIDCScope) {
      grant.addOIDCScope(details.missingOIDCScope.join(' '));
    }
    if (details.missingOIDCClaims) {
      grant.addOIDCClaims(details.missingOIDCClaims);
    }
    if (details.missingResourceScopes) {
      // eslint-disable-next-line no-restricted-syntax
      for (const [indicator, scope] of Object.entries(details.missingResourceScopes)) {
        grant.addResourceScope(indicator, scope.join(' '));
      }
    }

    grantId = await grant.save();

    const consent = {};
    if (!interactionDetails.grantId) {
      // we don't have to pass grantId to consent, we're just modifying existing one
      consent.grantId = grantId;
    }

    const result = { consent };
    return provider.interactionFinished(ctx.req, ctx.res, result, {
      mergeWithLastSubmission: true,
    });
  });

  router.get('/interaction/:uid/abort', async (ctx) => {
    const result = {
      error: 'access_denied',
      error_description: 'End-User aborted interaction',
    };

    return provider.interactionFinished(ctx.req, ctx.res, result, {
      mergeWithLastSubmission: false,
    });
  });

  return router;
};


text:
try:
    sdc.importLock()
    import datetime
finally:
    sdc.importUnlock()

# single threaded - no entityName because we need only one offset
entityName = ''

# get previously committed offset or use 0
if sdc.lastOffsets.containsKey(entityName):
    offset = int(sdc.lastOffsets.get(entityName))
else:
    offset = 0

# get record prefix from user parameters or default to empty string
if sdc.userParams.containsKey('recordPrefix'):
    prefix = sdc.userParams.get('recordPrefix')
else:
    prefix = ''

cur_batch = sdc.createBatch()

record = sdc.createRecord('record created ' + str(datetime.datetime.now()))
hasNext = True
while hasNext:

    try:
        offset = offset + 1
        record = sdc.createRecord('record created ' + str(datetime.datetime.now()))
        value = prefix + entityName + ':' + str(offset)
        record.value = value
        cur_batch.add(record)

        # if the batch is full, process it and start a new one
        if cur_batch.size() >= sdc.batchSize:
            # blocks until all records are written to all destinations
            # (or failure) and updates offset
            # in accordance with delivery guarantee
            cur_batch.process(entityName, str(offset))
            cur_batch = sdc.createBatch()
            # if the pipeline has been stopped, we should end the script
            if sdc.isStopped():
                hasNext = False

    except Exception as e:
        cur_batch.addError(record, str(e))
        cur_batch.process(entityName, str(offset))
        hasNext = False

if cur_batch.size() + cur_batch.errorCount() + cur_batch.eventCount() > 0:
    cur_batch.process(entityName, str(offset))


text:
// BSD License (http://lemurproject.org/galago-license)
/*
 * ScoreCombinationIteratorTest.java
 * JUnit based test
 *
 * Created on October 9, 2007, 2:43 PM
 */
package org.lemurproject.galago.core.retrieval.extents;

import org.junit.Test;
import org.lemurproject.galago.core.retrieval.iterator.WeightedSumIterator;
import org.lemurproject.galago.core.retrieval.processing.ScoringContext;
import org.lemurproject.galago.core.retrieval.query.NodeParameters;

import java.io.IOException;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author trevor
 */
public class WeightedSumIteratorTest {

  private static final int[] docsA = new int[]{5, 10, 15, 20};
  private static final double[] scoresA = new double[]{-1.0, -2.0, -3.0, -4.0};
  private static final int[] docsB = new int[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
  private static final double[] scoresB = new double[]{-2, -4, -6, -8, -10, -12, -14, -16, -18, -20};
  private static final int[] docsTogether = new int[]{2, 4, 5, 6, 8, 10, 12, 14, 15, 16, 18, 20};
  private static final double[] scoresTogether = new double[]{-1.99999, -3.99999, -0.99999, -5.99999, -7.99999, -1.99966, -11.99999, -13.99998, -2.99999, -15.99987, -17.99908, -3.99999};
  // sjh: weight testing
  private static final double[] weights = new double[]{0.4, 1.6};
  private static final double[] normalWeightedScoresTogether = new double[]{-2.22314, -4.22314, -2.60943, -6.22314, -8.22314, -3.60809, -12.22314, -14.22313, -4.60943, -16.22311, -18.22291, -5.60943};
  private static final double[] unnormalweightedScoresTogether = new double[]{-1.52999, -3.52999, -1.91629, -5.52999, -7.52999, -2.91494, -11.52999, -13.52999, -3.91629, -15.52996, -17.52976, -4.91629};

  @Test
  public void testScore() throws IOException {
    FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA, -25);
    FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB, -25);
    FakeScoreIterator[] iterators = {one, two};

    WeightedSumIterator instance = new WeightedSumIterator(new NodeParameters(), iterators);
    int[] lengths = new int[12];
    Arrays.fill(lengths, 100);
    ScoringContext ctx = new ScoringContext();
    for (int i = 0; i < 12; i++) {
      ctx.document = docsTogether[i];
      assertEquals(scoresTogether[i], instance.score(ctx), 0.00001);
      instance.movePast(docsTogether[i]);
    }
  }

  @Test
  public void testNormalWeightedScore() throws IOException {
    FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA, -25);
    FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB, -25);
    FakeScoreIterator[] iterators = {one, two};

    NodeParameters weightParameters = new NodeParameters();
    weightParameters.set("0", weights[0]);
    weightParameters.set("1", weights[1]);
    weightParameters.set("norm", true);
    WeightedSumIterator instance = new WeightedSumIterator(weightParameters, iterators);
    int[] lengths = new int[12];
    Arrays.fill(lengths, 100);
    ScoringContext ctx = new ScoringContext();
    for (int i = 0; i < 12; i++) {
      ctx.document = docsTogether[i];
      assertEquals(normalWeightedScoresTogether[i], instance.score(ctx), 0.0001);
      instance.movePast(docsTogether[i]);
    }
  }

  @Test
  public void testUnnormalizedWeightings() throws IOException {
    FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA, -25);
    FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB, -25);
    FakeScoreIterator[] iterators = {one, two};

    NodeParameters weightParameters = new NodeParameters();
    weightParameters.set("0", weights[0]);
    weightParameters.set("1", weights[1]);
    weightParameters.set("norm", false);
    WeightedSumIterator instance = new WeightedSumIterator(weightParameters, iterators);
    int[] lengths = new int[12];
    Arrays.fill(lengths, 100);
    ScoringContext ctx = new ScoringContext();
    for (int i = 0; i < 12; i++) {
      ctx.document = docsTogether[i];
      assertEquals(unnormalweightedScoresTogether[i], instance.score(ctx), 0.0001);
      instance.movePast(docsTogether[i]);
    }
  }

  @Test
  public void testMovePast() throws Exception {
    FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA, -25);
    FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB, -25);
    FakeScoreIterator[] iterators = {one, two};

    WeightedSumIterator instance = new WeightedSumIterator(new NodeParameters(), iterators);
    instance.movePast(5);
  }

  @Test
  public void testMoveTo() throws Exception {
    FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA, -25);
    FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB, -25);
    FakeScoreIterator[] iterators = {one, two};

    WeightedSumIterator instance = new WeightedSumIterator(new NodeParameters(), iterators);

    instance.syncTo(5);
  }
}


text:
package org.apache.felix.ipojo.runtime.core.components;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.runtime.core.services.NoService;

@Component(name="OneDuplicateInstance")
public class OneDuplicateInstance implements NoService {
}


text:
'use strict';

var Packet = require('./packet');
var util = require('util');
var NodeBox = require('./sandbox/node');
var PortBox = require('./sandbox/port');
var xNode = require('./node/interface');

// Running within vm is also possible and api should stay
// compatible with that, but disable for now.
// vm = require('vm'),

/**
 * Error Event.
 *
 * @event Node#error
 * @type {object}
 * @property {object} node - An export of this node
 * @property {string} msg - The error message
 */

/**
 * Executed Event.
 *
 * @event Node#executed
 * @type {object}
 * @property {object} node - An export of this node
 */

/**
 * Context Update event.
 *
 * @event Node#contextUpdate
 */

/**
 * Output Event.
 *
 * Fired multiple times on output
 *
 * Once for every output port.
 *
 * @event Node#output
 * @type {object}
 * @property {object} node - An export of this node
 * @property {string} port - The output port
 * @property {string} out - A (reference) to the output
 */

/**
 *
 * Node
 *
 * TODO:
 *   do not copy all those properties extend the node object itself.
 *   however, do not forget the difference between a nodeDefinition
 *   and a node.
 *
 *   node contains the process definition, which is the node
 *   definition merged with the instance configuration.
 *
 * @author Rob Halff <rob.halff@gmail.com>
 * @param {String} id
 * @param {Object} node
 * @param {String} identifier
 * @param {CHI} CHI
 * @constructor
 * @public
 */
function Node(id, node, identifier, CHI) {

  // not sure where to call this yet.
  Node.super_.apply(this, [id, node, identifier, CHI]);

  this.type = 'node';

  this.state = {};

  /**
   *
   * Indicates whether this instance is active.
   *
   * This works together with the active state
   * of the sandbox.
   *
   * When a blackbox sends async output done()
   * should be used to inform us it is done.
   *
   * @member {Boolean} active
   * @public
   */
  this.active = false;

  /**
   *
   * Indicates whether this node expects async input.
   *
   * Async input listening is done by:
   *
   *   on.input.<port-name> = function() {}
   *
   * Any node can send async output.
   *
   * Async nodes are handled differently, their function body
   * is only executed once, during startup.
   *
   * I think the port input function can be handled the same
   * as a normal function body, we'll just have several
   * functions to execute based on what input port is targeted.
   *
   * The common state is represented in the `state` object.
   * This is the only variable which is accessible to all ports
   * and during startup.
   *
   */

  // detection of async is still needed.
  // Really should all just be different classes.
  // Problem now, we have to run the nodebox to
  // determine async, which is a super hacky way.
  this.async = node.type === 'async' ? true : false;
  this.async = node.async ? true : this.async;

  // used for the async port sandboxes
  this.portBox = {};

  this.nodebox = new NodeBox();

  // done() is added to the nodebox
  this.nodebox.set('done', this.complete.bind(this));
  this.nodebox.set('cb', this._asyncOutput.bind(this));
  this.nodebox.set('state', this.state);

  // will be filled during portFill

  // this can be overriden by connections
  // a functionality which probably will be removed
  this._setup();

/*
  Object.defineProperty(this, 'status', {
    enumerable: true,
    configurable: false,
    get: function() {
      // go through all status options here.

      // node box

      // port boxes, have to take done() into account
    }
  });
*/

  /** @member {Mixed} chi */
  this.chi = {};

  /** delay interval */
  this.interval = 100;

  /** @member {Object} input */
  this.input = {};

  /** @member {Object} context */
  this.context = {};

  /** @member {Object} dependencies */
  this.dependencies = node.dependencies || {};

  /** @member {Array} expose */
  this.expose = node.expose;

  /** @member {String} fn */
  this.fn = node.fn;

  /**
   * @member {Numeric} nodeTimeout
   * @default 3000
   */
  this.nodeTimeout = node.nodeTimeout || 3000;

  /**
   *
   * inputTimeout in milliseconds
   *
   * If inputTimeout === `false` there will be no timeout
   *
   * @member {Mixed} inputTimeout
   * @default 3000
   */
  this.inputTimeout = typeof node.inputTimeout === 'undefined' ?
    3000 : node.inputTimeout;

  /** @private */
  this.__halted = false; // was halted by a hold

  /** @private */
  this._inputTimeout = null;

  // Solving yet another `design` problem
  // object containing the current connections in use
  // will be reset during free Port.
  // Also belongs to the port objects.
  this._activeConnections = {};

  this.status = 'init';

  // setup the core
  this._fillCore(node.fn, node.name);

  // If this node is async, run it once
  // all ports will be setup and sandbox state will be filled.
  if (this.async) {
    this._loadAsync();
  }

}

util.inherits(Node, xNode);

// TODO: this generic, however options does not exists anymore, it's settings
Node.prototype._setup = function() {

  for (var port in this.ports.input) {
    if (this.ports.input.hasOwnProperty(port)) {
      if (this.ports.input[port].options) {
        for (var opt in this.ports.input[port].options) {
          if (this.ports.input[port].options.hasOwnProperty(opt)) {
            this.setPortOption(
              'input',
              port,
              opt,
              this.ports.input[port].options[opt]);
          }
        }
      }
    }
  }

};

Node.prototype.start = function() {

  var sb;

  if (this.status === 'created') {

    this.setStatus('started');

    if (this.nodebox.on.start) {
      // Run onStart functionality first
      sb = this._createPortBox(this.nodebox.on.start.toString());
      sb.run(this);
      this.nodebox.state = this.state = sb.state;
    }

    this.emit('started', {
      node: this.export()
    });

  }

};

Node.prototype.hasData = function(port) {
  return undefined !== this.input[port];
};

Node.prototype.fill = function(target, data) {

  var p = data instanceof Packet ? data : new Packet(data);
  var ret = this._receive(p, target);

  if (ret !== true) {
    // ok doesn't say much by itself.
    // especially since on next cycle it could be filled
    // filled is more valuable
    if (this.ports.input.hasOwnProperty(target.port)) {
      this.ports.input[target.port].rejects++;
      this.ports.input[target.port].lastError = ret;
    }
  }

  return ret;

};

/**
 * Usage of `$`
 *
 * Idea is to do the reverse of super() all extending `classes`
 * only have $ methods.
 *
 * @param {type} port
 * @param {type} data
 * @returns {undefined}
 * @shielded
 */
Node.prototype.$setContextProperty = function(port, data) {
  this.context[port] = data;
};

Node.prototype.clearContextProperty = function(port) {

  delete this.context[port];

  this.event(':contextClear', {
    node: this,
    port: port
  });
};

/**
 *
 * Starts the node
 *
 * TODO: dependencies are always the same, only input is different.
 * dependencies must be created during createScript.
 * also they must be wrapped within a function.
 * otherwise you cannot overwrite window and document etc.
 * ...Maybe statewise it's a good thing, dependencies are re-required.
 *
 * FIXME: this method does too much on it's own.
 *
 * Note: start is totally unprotected, it assumes the input is validated
 * and all required ports are filled.
 * Start should never really be called directly, the node starts when
 * input is ready.
 *
 * @param {Function} fn
 * @param {String} name
 * @fires Node#error
 * @fires Node#require
 * @fires Node#expose
 * @private
 */
Node.prototype._delay = 0;

Node.prototype.__start = function() {

  if (this.active) {
    // try again, note: this is different from input queueing..
    // used for longer running processes.
    this._delay = this._delay + this.interval;
    setTimeout(this.start.bind(this), 500 + this._delay);
    return false;
  }

  // set active state.
  this.active = true;

  // Note: moved to the beginning.
  this.runCount++;

  if (!this.async) {
    if (this.nodebox.on) {
      if (this.nodebox.on.shutdown) {
        this.shutdown();
      }
    }
  }

  this.nodebox.input = this.input;

  // difference in notation, TODO: explain these constructions.
  // done before compile.
  // this.nodebox.output = this.async ? this._asyncOutput.bind(this) : {};

  this._runOnce();

};

/**
 *
 * Runs the node
 *
 * @fires Node#nodeTimeout
 * @fires Node#start
 * @fires Node#executed
 * @private
 */
Node.prototype._runOnce = function() {

  var t = setTimeout(function() {

    /**
     * Timeout Event.
     *
     * @event Node#nodeTimeout
     * @type {object}
     * @property {object} node - An export of this node
     */
    this.event(':nodeTimeout', {node: this.export()});

  }.bind(this), this.nodeTimeout);

  /**
   * Start Event.
   *
   * @event Node#start
   * @type {object}
   * @property {object} node - An export of this node
   */
  this.event(':start', {node: this.export()});

  //this.nodebox.runInNewContext(this.sandbox);
  //
  // ok, this depends on what is the code whether it's running or not...
  // that's why async should be definied per port.
  this.setStatus('running');

  this.nodebox.run();
  this.state = this.nodebox.state;

  this.event(':executed', {node: this});

  clearTimeout(t);

  // Ok if there are portboxes, how to treat this first run.
  // it's a setup phase. yet it will fire complete.
  this._output(this.nodebox.output);
};

/**
 *
 * Fills the core of this node with functionality.
 *
 * @param {Function} fn
 * @param {String} name
 * @fires Node#fillCore
 * @private
 */
Node.prototype._fillCore = function(fn, name) {

  /**
   * Fill Core Event.
   *
   * @event Node#fillCore
   * @type {object}
   * @property {object} node - An export of this node
   * @property {function} fn - The function being installed
   * @property {string} fn - The name of the function
   */
  this.event(':fillCore', {
    node: this.export(),
    fn: fn,
    name: name
  });

  this.nodebox.require(this.dependencies.npm);
  this.nodebox.expose(this.expose, this.CHI);

  // still not working..
  this.nodebox.set('output', this.async ? this._asyncOutput.bind(this) : {});

  this.nodebox.compile(fn);

  this.setStatus('created');

};

/**
 *
 * Executes the async variant
 *
 * state is the only variable which will persist.
 *
 * @param {string} fn - Portbox Function Body
 * @returns {PortBox}
 * @private
 */
Node.prototype._createPortBox = function(fn) {

  var portbox = new PortBox();
  // state is not remembered ?
  portbox.set('state', this.nodebox.state);
  //portbox.set('state', this.nodebox.args.state);
  portbox.set('output', this._asyncOutput.bind(this));
  portbox.require(this.dependencies.npm, true);
  portbox.expose(this.expose, this.CHI);

  fn = fn.slice(
    fn.indexOf('{') + 1,
    fn.lastIndexOf('}')
  );

  portbox.compile(fn);

  return portbox;

};

/**
 *
 * @private
 */
Node.prototype._loadAsync = function() {

  // This collects the port definitions they
  // attach to `on`
  this.nodebox.run();

  for (var port in this.ports.input) {

    if (this.ports.input.hasOwnProperty(port)) {

      // If there is a port function defined for this port
      // it means it's async
      if (this.nodebox.on.input.hasOwnProperty(port)) {

        this.portBox[port] = this._createPortBox(
          this.nodebox.on.input[port].toString()
        );

        // (dynamically) declare this port as async
        // for clarity this could also be pre-defined within the definition.

        // Seems like soon this will be the own option anyway..
        this.async = true;
        this.ports.input[port].async = true;

      } else {

        // It is a sync port

      }

    }
  }

  this.setStatus('created');

  // could just act on general status change event, who uses this?
  this.emit('created', {
    node: this.export()
  });

  this.state = this.nodebox.state;

  // setup phase for async, they can use output = {}
  // note: this runs during creation, maybe not the best setup.
  // but works for now.
  // Ok during init and you use output = is useless
  // it sends output but there are no listeners yet.
  // links are not yet setup
  // So how to do this, I setup an api using require.
  // that's during script load.
  // so then it's setup, I need to send it out.
  // but if all is async, it will not be send out.
  // on.start
  // so if on.start is found I run it overhere.
  // the main problem is, I never 'start' async nodes.
  // sync nodes are started but also internally.
  // Normally nodes should first be created and sit idle.
  // Because nodes are started by connections or iips.
  // there is no fixed starting point.
  // ok I can do if !this.started and on.start is set.
  // then run it.
  // this._output(this.nodebox.output);

};

// Ok here is what to do:
//
// - Put async in this.input[port] if it's not filled yet
// - Check whether all is filled
// - if so, fill all sync (fill.defaults)
// - fill defaults also fills all other async stuff.
// - fill async port.

/**
*
* Generic Callback wrapper
*
* Will collect the arguments and pass them on to the next node
*
* So technically the next node is the callback.
*
* Parameters are defined on the output as ports.
*
* Each callback argument must be defined as output port in the callee's schema
*
* e.g.
*
*  node style callback:
*
*  ports.output: { err: ..., result: ... }
*
*  connect style callback:
*
*  ports.output: { req: ..., res: ..., next: ... }
*
* The order of appearance of arguments must match those of the ports within
* the json schema.
*
* TODO: Within the schema you must define the correct type otherwise output
* will be refused
*
*
* @private
*/
Node.prototype._callbackWrapper = function() {

  var i;
  var obj = {};
  var ports;

  ports = this.outPorts;

  for (i = 0; i < arguments.length; i++) {

    if (!ports[i]) {

      // TODO: eventemitter expects a new Error()
      // not the object I send
      // Not sure what to do here, it's not really fatal.
      this.event(':error', {
        msg: Error(
          util.format('Unexpected extra port of type %s',
          typeof arguments[i] === 'object' ?
            arguments[i].constructor.name : typeof arguments[i]
          )
        )
      });

    } else {

      obj[ports[i]] = arguments[i];

    }
  }

  this._output(obj);

};

/**
*
* Execute the delegated callback for this node.
*
* [fs, 'readFile', '/etc/passwd']
*
* will execute:
*
* fs['readFile']('/etc/passwd', this.callbackWrapper);
*
* @param {Object} output
* @fires Node#branching
* @private
*/
Node.prototype._delegate = function(output) {

  // pop() because splice will return an array.
  var fn = output.splice(0, 1).pop();
  var method = output.splice(0, 1).pop();

  /**
   * Branching Event.
   *
   * Fired when a delegated callback gets executed.
   *
   * Sending it away on it's own quest.
   *
   * @event Node#branching
   * @type {object}
   * @property {object} node - An export of this node
   * @property {string} method - The method name
   */
  this.event(':branching', {
    // TODO: the _function_ way is not covered now.
    // rendering this.event a bit useless...
    node: this.export(),
    method: method
  });

  output.push(this._callbackWrapper.bind(this));
  fn[method].apply(fn, output);
};

/**
*
* This node handles the output of the `blackbox`
*
* It is specific to the API of the internal Chix node function.
*
* out = { port1: data, port2: data }
* out = [fs.readFile, arg1, arg2 ]
*
* Upon output the input will be freed.
*
* @param {Object} output
* @param {Object} chi
* @fires Node#output
* @private
*/
Node.prototype._asyncOutput = function(output, chi) {

  var port;

  // Ok, delegate and object output has
  // synchronous output on _all_ ports
  // however we do not know if we we're called from
  // the function type of output..
  for (port in output) {
    if (output.hasOwnProperty(port)) {
      this.sendPortOutput(port, output[port], chi);
    }
  }

};

/**
 *
 * Output
 *
 * Directs the output to the correct handler.
 *
 * If output is a function it is handled by asyncOutput.
 *
 * If it's an array, it means it's the shorthand variant
 *
 * e.g. output = [fs, 'readFile']
 *
 * This will be handled by the delegate() method.
 *
 * Otherwise it is a normal output object containing the output for the ports.
 *
 * e.g. { out1: ...,  out2: ...,  error: ... } etc.
 *
 * TODO: not sure if this should always call complete.
 *
 * @param {Object} output
 * @private
 */
Node.prototype._output = function(output) {

  var port;

  if (typeof output === 'function') {
    output.call(this, this._asyncOutput.bind(this));
    return;
  }

  if (Array.isArray(output)) {
    this._delegate(output);
    return;
  }

  for (port in output) {
    if (output.hasOwnProperty(port)) {
      this.sendPortOutput(port, output[port]);
    }
  }

  this.complete();

};

/**
 *
 * @param {string} port
 * @private
 */

Node.prototype._runPortBox = function(port) {

  var sb = this.portBox[port];
  // fill in the values

  this.event(':start', {node: this.export()});

  sb.set('data', this.input[port]);
  sb.set('x', this.chi);
  sb.set('state', this.state);
  // sb.set('source', source); is not used I hope
  sb.set('input', this.input); // add all (sync) input.

  this.setStatus('running');
  var ret = sb.run(this);

  if(ret === false) {
    // if ret === false input should be revoked and re-queued.
    // which means it must look like we didn't accept the packet in
    // the first place.
    return false;
  }

  // todo portbox itself should probably also
  // maintain it's runcount, this one is cumulative
  this.runCount++;

  this.nodebox.state = this.state = sb.state;

  this.event(':executed', {
    node: this,
    port: port
  });

};

/**
*
* Contains much of the port's logic, this should be abstracted out
* into port objects.
*
* For now just add extra functionality overhere.
*
* TODO:
*  - Detect if the input port is defined as Array.
*  - If it is an array, detect what is it's behaviour
*
* Behaviours:
*  - Multiple non-array ports are connected: wait until all have send
*    their input and release the array of data.
*  - One port is connect of the type Array, just accept it and run
*  - Multiple array ports give input/are connected... same as the above
*  Arrays will be handled one by one.
*  - So basically, if we receive an array, we process it.
*  If it is not we will join multiple connections.
*  - If there is only one port connected and it is not of an array type
*    We will just sit there and wait forever,
*    because we cannot make an array out of it.
* - I think the rules should be simple, if you want it more complex,
*   just solve it within the flow by adding extra nodes.
*   What a port does must be understandable.  So that's why it's also good if
*   you can specify different kind of port behaviour.
*   So if you do not like a certain kind of behaviour, just select another one.
*   Yet all should be simple to grasp. You could also explain an array as being
*   a port that expects multiple.
*
*   The filled concept stays the same, the only thing changing is when we
*   consider something to be filled.
*
*   So.. where is the port type information.
*
// TODO: once a connection overwrites a setting.
// it will not be put back, this is a choice.
// at what point do we set persistent from a link btw?
//
// TODO: has become a bit of a weird method now.
*/

Node.prototype.handlePortSettings = function(port) {
  if (this.ports.input.hasOwnProperty(port)) {
  }
};

/**
 * Fill one of our ports.
 *
 * First the input data will be validated. A port
 * will only be filled if the data is of the correct type
 * or even structure.
 *
 * The following events will be emitted:
 *
 *   - `portFill`
 *   - `inputTimeout`
 *   - `clearTimeout` (TODO: remove this)
 *
 * FIXME:
 *  - options are set and overwritten on portFill
 *    which is probably undesired in most cases.
 *
 *  - portFill is the one who triggers the start of a node
 *    it's probably better to trigger an inputReady event.
 *    and start the node based on that.
 *
 * @param {Connector} target
 * @param {Packet} p
 * @returns {Node.error.error|Boolean}
 * #private
 */
Node.prototype._fillPort = function(target, p) {

  var res;

  if (undefined === p.data) {
    return Error('data may not be `undefined`');
  }

  // Not used
  //this.handlePortSettings(target.port);

  // PACKET WRITE, TEST THIS
  p.data = this._handleFunctionType(target.port, p.data);

  res = this._validateInput(target.port, p.data);

  if (util.isError(res)) {

    return res;

  } else {

    // todo: this logic must be externalized.
    // node doesn't know about persist
    if (!target.has('persist')) {

      try {

        // CHI MERGING check this.
        // Or is this to early, can we still get a reject?
        this.CHI.merge(this.chi, p.chi);
      } catch (e) {
        console.log('Packet', p);
        // this means chi was not cleared,
        // yet the input which caused the chi setting
        // freed the port, so how is this possible.
        return this.error(util.format(
          '%s: chi item overlap during fill of port `%s`\n' +
          'chi arriving:\n%s\nchi already collected:\n%s',
          this.identifier,
          target.port,
          JSON.stringify(p.chi),
          JSON.stringify(this.chi)
        ));
      }

    }

    // this.filled++;

    /**
     * Port Fill Event.
     *
     * Occurs when a port is filled with data
     *
     * At this point the data is already validated
     *
     * @event Node#portFill
     * @type {object}
     * @property {object} node - An export of this node
     * @property {string} port - Name of the port
     */
    //this.event(':portFill', {
    //todo: not all events are useful to send as output
    //TODO: just _do_ emit both
    this.emit('portFill', {
      node: this.export(),
      link: target.wire,
      port: target.port
    });

    this.event(':portFill', {
      node: this.export(),
      link: target.wire,
      port: target.port
    });

    if (
      !this._inputTimeout &&
      this.inputTimeout &&
      //!this.getPortOption('input', port, 'persist')
      !target.has('persist')
      ) {

      this._inputTimeout = setTimeout(function() {

      /**
       * Input Timeout Event.
       *
       * Occurs when there is an input timeout for this node.
       *
       * This depends on the inputTimeout property of the node.
       * If inputTimeout is false, this event will never occur.
       *
       * @event Node#inputTimeout
       * @type {object}
       * @property {object} node - An export of this node
       */
        this.event(':inputTimeout', {
          node: this.export()
        });

      }.bind(this), this.inputTimeout);
    }

    // used during free port to find back our connections.
    // Should belong to the port object (non existant yet)
    if (target.wire) { // direct node.fill() does not have it

      // does not really happen can be removed..
      if (this._activeConnections[target.port]) {
        throw Error('There still is a connection active');
      } else {
        this._activeConnections[target.port] = target.wire;
      }
    }

    // set input port data
    // this could be changed to still contain the Packet.
    this._fillInputPort(target.port, p.data);

    return this._readyOrNot();

  }

};

/**
 *
 * @param {string} port
 * @param {Mixed} value
 * @private
 */
Node.prototype._fillInputPort = function(port, value) {

  this.input[port] = value;

  // increment fill counter
  this.ports.input[port].fills++;

};

/* Unused?
Node.prototype.syncFilled = function() {

  var port;

  for (port in this.input) {
    if (!this.ports.input[port].async &&
       typeof this.input[port] === 'undefined') {
      return false;
    }
  }

  return true;

};

Node.prototype.syncFilledCount = function() {

  var port;

  var cnt = 0;
  for (port in this.input) {
    if (!this.ports.input[port].async &&
       typeof this.input[port] !== 'undefined') {
      cnt++;
    }
  }

  return cnt;

};
*/

/***
 *
 * Async problem.
 *
 * start() -> isStartable()
 *
 * If links are not connected yet, this logic will not work.
 * However, how to know we are complete.
 * addnode addnode addlink addlink etk
 *
 *
 *
 */
// ok, nice, multiple ip's will not be possible?, yep..
Node.prototype.isStartable = function() {

  if (this.hasConnections()) {
    // should never happen with IIPs so fix that bug first
    return false;
  }

  var fillable = 0;
  for (var port in this.ports.input) {
    // null is possible..
    if (this.ports.input[port].default !== undefined) {
      fillable++;
    } else if (this.context[port]) {
      fillable++;
    } else if (port === ':start') {
      fillable++;
    } else if (!this.ports.input[port].required) {
      fillable++;
    }
  }

  return fillable === this.inPorts.length;

};

/**
 *
 * Determines whether we are ready to go.
 * And starts the node accordingly.
 *
 * TODO: it's probably not so smart to consider default
 * it means we can never send an IIP to a port with a default.
 * Because the default will already trigger the node to run.
 *
 * @private
 */
Node.prototype._readyOrNot = function() {

  // all connected ports are filled.
  if (this._allConnectedSyncFilled()) {

    if (this._inputTimeout) {
      clearTimeout(this._inputTimeout);
    }

    // Check context/defaults and fill it
    var ret = this._fillDefaults();

    // TODO: if all are async, just skip all the above
    // async must be as free flow as possible.
    if (util.isError(ret)) {

      // this *is* a node error.
      return this.error(ret);

    } else {

      // temp for debug
      //this.ready = true;

      // todo better to check for ready..
      if (this.status !== 'hold') {

        if (this.async) {

          // really have no clue why these must run together
          // and why I try to support 4 different ways of writing
          // a component and sqeeze it into one class.

          var async_ran = 0;
          for (var port in this.ports.input) {

            // run all async which have input.
            // persistent async will have input etc.
            if (this.ports.input[port].async &&
               this.input[port] !== undefined) {

              ret = this._runPortBox(port);

              if (ret === false) {
                // revoke input
                if (async_ran > 0) {
                  // only problem now is the multpile async ports.
                  //
                  throw Error('Input revoked, yet one async already ran');
                }
                return false;
              }

              async_ran++;

            }
          }

          if (async_ran > 0) {
            this.freeInput();
          }

        } else { // not async

          if (Object.keys(this.input).length !== this.inPorts.length) {

            return this.error(util.format(
              'Input does not match, Input: %s, InPorts: %s',
              Object.keys(this.input).toString(),
              this.inPorts.toString()
            ));

          } else {

            this.setStatus('running');
            this.__start();

          }

        }

      } else {
        this.__halted = true;
      }

    }

    return true;
  }

  return false;

};

/**
 *
 * Fills the ports with context and defaults.
 *
 * Both can be overridden by just sending to these ports.
 *
 * This means even though nothing was directly send to this
 * ports they are still considered filled.
 *
 * I should check here whether a port is async.
 * then if it's not bail out. on, has this information.
 * But it's a bit hackish to test that.
 * But for now just do that. Let's internally
 * just set ports.input[port].async to true during
 * build-up.
 *
 * @private
 */
Node.prototype._fillDefaults = function() {

  var ret;

  for (var port in this.ports.input) {
    if (this.ports.input.hasOwnProperty(port)) {
      ret = this._fillDefault(port);
      if (util.isError(ret)) {
        return ret;
      }
    }
  }

  return true;

};

Node.prototype._checkIt = function(obj, key, input, context, persist) {

  if (obj[key].properties) { //
    var init;

    if (!input[key]) {
      input[key] = {};
      init = true;
    }

    for (var k in obj[key].properties) {
      if (obj[key].properties.hasOwnProperty(k)) {
        if (!this._checkIt(
          obj[key].properties,
          k,
          input[key],
          context ? context[key] : {},
          persist ? persist[key] : {}
        )) {
  /*
          throw new Error([
            this.identifier + ': Cannot determine input for property:',
            key + '[' + k + ']'
          ].join(' '));
  */
        }
      }
    }

    if (!Object.keys(input[key]).length && init) {
      // remove empty object again
      delete input[key]; // er ref will not work probably.
    }

    return true;

  } else {

    // check whether input was defined for this port
    if (!input.hasOwnProperty(key)) {
      // if there is context, use that.
      if (context && context.hasOwnProperty(key)) {
        input[key] = context[key];
        return true;
      // check the existance of default (a value of null is also valid)
      } else if (persist && persist.hasOwnProperty(key)) {
        input[key] = persist[key];
        return true;
      } else if (obj[key].hasOwnProperty('default')) {
        input[key] = obj[key].default;
        return true;
      } else if (obj[key].required === false) {
        // filled but empty let the node handle it.
        input[key] = null;
        return true;
      } else {
        return false;
      }

    } else {
      return true;
    }

  }
};

// also fill the defaults one level deep..
/**
 *
 * @param {string} port
 * @private
 */
Node.prototype._fillDefault = function(port) {
  if (!this._checkIt(
    this.ports.input,
    port,
    this.input,
    this.context
    ) && !this.ports.input[port].async) {

    if (port[0] !== ':') {
      // fail hard
      return Error(util.format(
        '%s: Cannot determine input for port `%s`',
        this.identifier,
        port
      ));
    }

  }
};

/**
 *
 * Frees the input
 *
 * After a node has run the input ports are freed,
 * removing their reference.
 *
 * Exceptions:
 *
 *  - If the port is set to persistent, it will keep it's
 *    reference to the variable and stay filled.
 *
 * NOTE: at the moment a port doesn't have a filled state.
 *  we only count how many ports are filled to determine
 *  if we are ready to run.
 *
 * if a node is still in active state it's input can also not
 * be freed... at the moment it will do so, which is bad.
 *
 * @public
 */
Node.prototype.freeInput = function() {

  var i;

  // this.filled = 0;

  // Reset this.chi.
  // must be before freePort otherwise chi will overlap
  this.chi = {};

  var port;

  var freed = [];
  for (i = 0; i < this.inPorts.length; i++) {

    port = this.inPorts[i];

    // TODO: don't call freeInput in the first place if undefined
    if (this.input[port] !== undefined) {
      this.freePort(port);
      freed.push(port);
    }
  }

};

Node.prototype.$portIsFilled = function(port) {
  return this.input.hasOwnProperty(port);
};

Node.prototype.clearInput = function(port) {
  delete this.input[port];
};

Node.prototype.freePort = function(port) {

  var persist = this.getPortOption('input', port, 'persist');
  if (persist) {
    // persist, chi, hmz, seeze to exist.
    // but wouldn't matter much, with peristent ports.
    // TODO: this.filled is not used anymore.

    // indexes are persisted per index.
    if (Array.isArray(persist)) {
      for (var k in this.input[port]) {
        if (persist.indexOf(k) === -1) {
          // remove
          delete this.input[port][k];
        }
      }
    }

  } else {

    // this also removes context and default..
    this.clearInput(port);

    this.event(':freePort', {
      node: this.export(),
      link: this._activeConnections[port], // can be undefined, ok
      port: port
    });

    this.emit('freePort', {
      node: this.export(),
      link: this._activeConnections[port],
      port: port
    });

    // delete reference to active connection (if there was one)
    // delete this._activeConnections[port];
    this._activeConnections[port] = null;
  }

};

/**
*
* Checks whether all required ports are filled
*
* Used to determine if this node should start running.
*
* @public
*/
Node.prototype.allConnectedFilled = function() {
  for (var port in this.openPorts) {
    if (this.input[port] === undefined) {
      return false;
    }
  }
  return true;
};

/**
 *
 * @private
 */
Node.prototype._allConnectedSyncFilled = function() {

  for (var i = 0; i < this.openPorts.length; i++) {
    var port = this.openPorts[i];
    if (!this.ports.input[port].async) {

      if (this.ports.input[port].indexed) {
        if (this.ports.input[port].type === 'object') {
          return this._objectPortIsFilled(port);
        } else {
          return this._arrayPortIsFilled(port);
        }
      } else if (this.input[port] === undefined) {
        return false;
      }
    }
  }

  return true;
};

/**
*
* Wires a source port to one of our ports
*
* target is the target object of the connection.
* which consist of a source and target object.
*
* So in this calink.se the target is _our_ port.
*
* If a connection is made to the virtual `:start` port
* it will be created automatically if it does not exist already.
*
* The port will be set to the open state and the connection
* will be registered.
*
* A port can have multiple connections.
*
* TODO: the idea was to also keep track of
*       what sources are connected.
*
* @private
*/
Node.prototype._initStartPort = function() {
  // add it to known ports
  if (!this.portExists('input', ':start')) {
    this.addPort('input', ':start', {
      type: 'any',
      rejects: 0,
      fills: 0
    });
  }
};

/**
*
* Holds all input until release is called
*
* @public
*/
Node.prototype.hold = function() {
  this.setStatus('hold');
};

/**
*
* Releases the node if it was on hold
*
* @public
*/
Node.prototype.release = function() {

  this.setStatus('ready');

  if (this.__halted) {
    this.__halted = false;
    this._readyOrNot();
  }
};

/**
*
* Node completion
*
* Sends an empty string to the :complete port.
* Each node automatically has one of those available.
*
* Emits the complete event and frees all input ports.
*
* @private
*/
Node.prototype.complete = function() {

  this.active = false;

  // uses this.event() now.
  // this.sendPortOutput(':complete', '', this.chi);

  /**
   * Complete Event.
   *
   * The node has completed.
   *
   * TODO: a node can set itself as being active
   * active must be taken into account before calling
   * a node complete. As long as a node is active
   * it is not complete.
   *
   * @event Node#complete
   * @type {object}
   * @property {object} node - An export of this node
   */

  this.freeInput();

  this.setStatus('complete');

  this.event(':complete', {node: this.export()});

};

/**
 *
 * Runs the shutdown method of the blackbox
 *
 * An asynchronous node can define a shutdown function:
 *
 *   on.shutdown = function() {
 *
 *     // do shutdown stuff
 *
 *   }
 *
 * When a network shuts down, this function will be called.
 * To make sure all nodes shutdown gracefully.
 *
 * e.g. A node starting a http server can use this
 *      method to shutdown the server.
 *
 * @param {function} cb
 * @returns {undefined}
 * @public
 */
Node.prototype.shutdown = function(cb) {
  if (this.nodebox.on && this.nodebox.on.shutdown) {

    // TODO: nodes now do nothing with the callback, they should..
    // otherwise we will hang
    this.nodebox.on.shutdown(cb);

    // TODO: send the nodebox, or just the node export?
    this.event(':shutdown', this.nodebox);

  } else {
    if (cb) {
      cb();
    }
  }
};

/**
*
* Cleanup
*
* Reminder: interesting things could be done with .listeners()
*
* TODO: events also seem to be registered in this._events
*  added by the EventEmitter we extend. They seem to be
*  registered once they are emitted the first time.
*  probably the below is not even necessary.
*  So, find out what EventEmitter really does.
*
*  e.g.
*
* _events:
*  { contextUpdate: [Function],
*    inputTimeout: [Function],
*    nodeTimeout: [Function],
*    start: [Function],
*    error: [Function],
*    complete: [Function],
*    require: [Function],
*    expose: [Function],
*    output: [Function] }
*
* @public
*/
Node.prototype.destroy = function() {
  for (var i = 0; i < Node.events.length; i++) {
    this.removeAllListeners(Node.events[i]);
  }
};

/**
 *
 * Live reset, connections, etc. stay alive.
 *
 */
Node.prototype.reset = function() {

  // clear persistence
  this.persist = {};

  // clear any input
  this.freeInput();

  // reset status
  // note: also will retrigger the .start thing on nodebox.
  this.status = 'created';

  // reset any internal state.
  this.state = {};

  this.runCount = 0;

};

module.exports = Node;


text:
(function () {
    var WalkRightState = YYC.Class(WalkState_X, {
        Protected: {
            P_setPlayerState: function () {
                this.P_context.setPlayerState(this.P_context.standRightState);
            },
            P_computeTarget: function () {
                var currentCellPos = this.P_context.sprite.getCurrentCellPosition();

                return {
                    x: currentCellPos.x + 1,
                    y: currentCellPos.y
                };
            },
            P_computeTargetByMoving: function () {
                var currentCellPos = this.P_context.sprite.getCellPosition(this.P_context.sprite.x, this.P_context.sprite.y);

                return {
                    x: this.P_context.sprite.moving ? currentCellPos.x + 1 : currentCellPos.x,
                    y: currentCellPos.y
                };
            },
            P_checkBorder: function (target) {
                if (target.x >= window.mapData[0].length) {
                    return true;
                }

                return false;
            },
            P_setDir: function () {
                var sprite = this.P_context.sprite;

                sprite.setAnim("walk_right");
                sprite.dirX = 1;
            },
            P_stop: function () {
                var sprite = this.P_context.sprite;

                sprite.dirX = 0;
            }
        },
        Public: {
            walkRight: function () {
                this.P_checkMapAndSetDir();
            }
        }
    });

    window.WalkRightState = WalkRightState;
}());


text:
<?php

error_reporting(E_ALL);
set_include_path('../src/'.PATH_SEPARATOR.get_include_path());
date_default_timezone_set('UTC');

include 'Cezpdf.php';

class Creport extends Cezpdf
{
    public function __construct($p, $o)
    {
        parent::__construct($p, $o, 'color', array(0.8, 0.8, 0.8));
    }
}
$pdf = new Creport('a4', 'portrait');

$pdf->ezSetMargins(20, 20, 20, 20);

$mainFont = 'Times-Roman';
// select a font
$pdf->selectFont($mainFont);
$size = 12;

$height = $pdf->getFontHeight($size);
// modified to use the local file if it can
$pdf->openHere('Fit');

$pdf->ezText("ROS PDF Image Example\n", 18);

$pdf->ezText('PNG grayscaled', 10);
$pdf->ezImage('images/test_grayscaled.png', 0, 0, 'none', 'right');
$pdf->ezText('PNG grayscaled with alpha channel');
$pdf->ezImage('images/test_grayscaled_alpha.png', 0, 0, 'none', 'right');
$pdf->ezText('PNG true color plus alpha channel #1');
$pdf->ezImage('images/test_alpha.png', 0, 0, 'none', 'right');
$pdf->ezText("PNG indexed:\n\n");
$pdf->ezImage('images/test_indexed.png', 0, 0, 'none', 'right');
$pdf->ezNewPage();
$pdf->ezText("PNG indexed transparent (NOT SUPPORTED):\n\n");
$pdf->ezImage('images/test_indexed_transparent.png', 0, 0, 'none', 'right');
$pdf->ezText('JPEG from an external resource');
$pdf->ezImage('https://github.com/rospdf/pdf-php/raw/master/ros.jpg', 0, 0, 'none', 'right');

$pdf->ezText("GIF image converted into JPG\n\n");
$pdf->ezImage('images/test_alpha.gif', 0, 0, 'none', 'right');

if (isset($_GET['d']) && $_GET['d']) {
    echo $pdf->ezOutput(true);
} else {
    $pdf->ezStream(array('compress' => 0));
}

//error_log($pdf->messages);
;


text:
layout: post
title: Cimbalino Toolkit 2.5.0
date: 2017-05-11T12:00:40+01:00
image: /wp-content/uploads/2014/06/Cimbalino.Toolkit@4x-400x270.png
categories:
  - Windows
  - Windows Phone
tags:
  - Cimbalino
  - UWP
  - Windows
  - Windows 10
  - Windows Phone
  - WPDev
---

Yesterday I released [**Cimbalino Toolkit**](http://cimbalino.org/) version 2.5.0!

Here's what's changed on this version:

- Cimbalino.Toolkit.Core now targets the .NET Standard 1.0
- Cimbalino.Toolkit.Core will now behave as the rest of the toolkit in regards to throwing `NotImplementedExceptions` only on specific cases
- Exposed overrideable async methods in `ExtendedPageBase`
- Other fixes and improvements

From the above, I'd like to emphasise the huge advantage of supporting .NET Standard 1.0: this means **you can now use Cimbalino.Tookit.Core in all .NET platforms: .NET Framework, .NET Core, and Mono!**


text:
<?php
namespace Admin\Controller;

use Admin\Service\ColisServiceInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;

class DeleteController extends AbstractActionController
{
	protected $colisService;

	public function __construct(ColisServiceInterface $colisService)
	{
		$this->colisService = $colisService;
	}

	private function isAdmin() {
		$session = new Container("User");
		$admin = $session->offsetGet('admin');
		if (0 < $admin){
			return true;
		}

		return false;
	}

	public function deleteAction()
	{

	    if ( !$this->isAdmin() )
	    {
	    	return $this->redirect()->toUrl('/');
	    }

		try{
		    $colis = $this->colisService->findColis($this->params('id'));
		} catch (\InvalidArgumentException $e) {

		    echo "Can't find id " . $this->param('id');
			return $this->redirect()->toRoute('Monitor');
		}

		$request = $this->getRequest();

		if ($request->isPost())
		{
			$del = $request->getPost('delete_confirmation', 'no');

			if ($del === 'yes')
			{
				$this->colisService->deleteColis($colis);
			}

			return $this->redirect()->toRoute('admin');

		}

		return new ViewModel(array('colis' => $colis));
	}

}


text:
#include "config.h"

#include "socket-ssl.h"

#include <stdlib.h>
#include <sys/select.h>

#include <guacamole/error.h>
#include <guacamole/socket.h>
#include <openssl/ssl.h>

static ssize_t __guac_socket_ssl_read_handler(guac_socket* socket,
        void* buf, size_t count) {

    /* Read from socket */
    guac_socket_ssl_data* data = (guac_socket_ssl_data*) socket->data;
    int retval;

    retval = SSL_read(data->ssl, buf, count);

    /* Record errors in guac_error */
    if (retval <= 0) {
        guac_error = GUAC_STATUS_SEE_ERRNO;
        guac_error_message = "Error reading data from secure socket";
    }

    return retval;

}

static ssize_t __guac_socket_ssl_write_handler(guac_socket* socket,
        const void* buf, size_t count) {

    /* Write data to socket */
    guac_socket_ssl_data* data = (guac_socket_ssl_data*) socket->data;
    int retval;

    retval = SSL_write(data->ssl, buf, count);

    /* Record errors in guac_error */
    if (retval <= 0) {
        guac_error = GUAC_STATUS_SEE_ERRNO;
        guac_error_message = "Error writing data to secure socket";
    }

    return retval;

}

static int __guac_socket_ssl_select_handler(guac_socket* socket, int usec_timeout) {

    guac_socket_ssl_data* data = (guac_socket_ssl_data*) socket->data;

    fd_set fds;
    struct timeval timeout;
    int retval;

    /* Initialize fd_set with single underlying file descriptor */
    FD_ZERO(&fds);
    FD_SET(data->fd, &fds);

    /* No timeout if usec_timeout is negative */
    if (usec_timeout < 0)
        retval = select(data->fd + 1, &fds, NULL, NULL, NULL);

    /* Handle timeout if specified */
    else {
        timeout.tv_sec = usec_timeout/1000000;
        timeout.tv_usec = usec_timeout%1000000;
        retval = select(data->fd + 1, &fds, NULL, NULL, &timeout);
    }

    /* Properly set guac_error */
    if (retval <  0) {
        guac_error = GUAC_STATUS_SEE_ERRNO;
        guac_error_message = "Error while waiting for data on secure socket";
    }

    if (retval == 0) {
        guac_error = GUAC_STATUS_TIMEOUT;
        guac_error_message = "Timeout while waiting for data on secure socket";
    }

    return retval;

}

static int __guac_socket_ssl_free_handler(guac_socket* socket) {

    /* Shutdown SSL */
    guac_socket_ssl_data* data = (guac_socket_ssl_data*) socket->data;
    SSL_shutdown(data->ssl);

    /* Close file descriptor */
    close(data->fd);

    free(data);
    return 0;
}

guac_socket* guac_socket_open_secure(SSL_CTX* context, int fd) {

    /* Allocate socket and associated data */
    guac_socket* socket = guac_socket_alloc();
    guac_socket_ssl_data* data = malloc(sizeof(guac_socket_ssl_data));

    /* Init SSL */
    data->context = context;
    data->ssl = SSL_new(context);
    SSL_set_fd(data->ssl, fd);

    /* Accept SSL connection, handle errors */
    if (SSL_accept(data->ssl) <= 0) {

        guac_error = GUAC_STATUS_INTERNAL_ERROR;
        guac_error_message = "SSL accept failed";

        free(data);
        guac_socket_free(socket);
        return NULL;
    }

    /* Store file descriptor as socket data */
    data->fd = fd;
    socket->data = data;

    /* Set read/write handlers */
    socket->read_handler   = __guac_socket_ssl_read_handler;
    socket->write_handler  = __guac_socket_ssl_write_handler;
    socket->select_handler = __guac_socket_ssl_select_handler;
    socket->free_handler   = __guac_socket_ssl_free_handler;

    return socket;

}


text:
package br.com.cams7.siscom.jpa.domain.pk;

import java.io.Serializable;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

import br.com.cams7.siscom.jpa.domain.entity.ProdutoEntity;

/**
 * The primary key class for the req_det database table.
 *
 */
@Embeddable
public class RequisicaoDetalhePK implements Serializable {
	// default serial version id, required for serializable classes.
	private static final long serialVersionUID = 1L;

	@NotNull
	@Column(name = "cod_req_cab", insertable = false, updatable = false)
	private Long requisicaoId;

	@NotEmpty
	@Size(min = ProdutoEntity.ID_SIZE_MIN, max = ProdutoEntity.ID_SIZE_MAX)
	@Column(name = "cod_produto", length = ProdutoEntity.ID_SIZE_MAX, insertable = false, updatable = false)
	private String produtoId;

	public RequisicaoDetalhePK() {
		super();
	}

	public RequisicaoDetalhePK(Long requisicaoId, String produtoId) {
		this();

		this.requisicaoId = requisicaoId;
		this.produtoId = produtoId;
	}

	public Long getRequisicaoId() {
		return this.requisicaoId;
	}

	public void setRequisicaoId(Long requisicaoId) {
		this.requisicaoId = requisicaoId;
	}

	public String getProdutoId() {
		return this.produtoId;
	}

	public void setProdutoId(String produtoId) {
		this.produtoId = produtoId;
	}

	public boolean equals(Object entityPK) {
		if (this == entityPK) {
			return true;
		}
		if (!(entityPK instanceof RequisicaoDetalhePK)) {
			return false;
		}
		RequisicaoDetalhePK pk = (RequisicaoDetalhePK) entityPK;
		return this.requisicaoId.equals(pk.requisicaoId)
				&& this.produtoId.equals(pk.produtoId);
	}

	public int hashCode() {
		final int prime = 31;
		int hash = 17;
		hash = hash * prime + this.requisicaoId.hashCode();
		hash = hash * prime + this.produtoId.hashCode();

		return hash;
	}
}


text:
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour
{
	public GameObject menu;

	public static bool IsFocus = false;

	private void Awake ()
	{
		print ("enable menu!");
		menu.SetActive (true);
	}

	void OnApplicationFocus (bool focusStatus)
	{
		IsFocus = focusStatus;
	}

	//	void OnGUI() {
	//		GUI.Label(new Rect(Screen.width - 200, 5, 200, 50), IsFocus ? "IsFocus" : "IsFuzz");
	//	}
}