text:
We resolved the error messages shown in Listing 7-4 by moving the `network` and
`network::server` code into the *src/network/mod.rs* and
*src/network/server.rs* files, respectively. At that point, `cargo build` was
able to build our project, but we still get some warning messages about the
`client::connect`, `network::connect`, and `network::server::connect` functions
not being used:

```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default
src/client.rs:1:1
  |
1 | fn connect() {
  | ^

warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/mod.rs:1:1
  |
1 | fn connect() {
  | ^

warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/server.rs:1:1
  |
1 | fn connect() {
  | ^
```

So why are we receiving these warnings? After all, we're building a library
with functions that are intended to be used by our *users*, and not necessarily
by us within our own project, so it shouldn't matter that these `connect`
functions go unused. The point of creating them is that they will be used by
another project and not our own.

To understand why this program invokes these warnings, let's try using the
`connect` library as if we were another project, calling it externally. To do
that, we'll create a binary crate in the same directory as our library crate,
by making a *src/main.rs* file containing this code:

Filename: src/main.rs

```rust,ignore
extern crate communicator;

fn main() {
    communicator::client::connect();
}
```

We use the `extern crate` command to bring the `communicator` library crate
into scope, because our package actually now contains *two* crates. Cargo
treats *src/main.rs* as the root file of a binary crate, which is separate from
the existing library crate whose root file is *src/lib.rs*. This pattern is
quite common for executable projects: most functionality is in a library crate,
and the binary crate uses that library crate. This way, other programs can also
use the library crate, and it's a nice separation of concerns.

From the point of view of a crate outside of the `communicator` library looking
in, all of the modules we've been creating are within a module that has the
same name as the crate, `communicator`. We call the top-level module of a crate
the *root module*.

Also note that even if we're using an external crate within a submodule of our
project, the `extern crate` should go in our root module (so in *src/main.rs*
or *src/lib.rs*). Then, in our submodules, we can refer to items from external
crates as if the items are top-level modules.

Our binary crate right now just calls our library's `connect` function from the
`client` module. However, invoking `cargo build` will now give us an error
after the warnings:

```text
error: module `client` is private
 --> src/main.rs:4:5
  |
4 |     communicator::client::connect();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

Ah ha! This tells us that the `client` module is private, and this is the crux
of the warnings. It's also the first time we've run into the concepts of
*public* and *private* in the context of Rust. The default state of all code in
Rust is private: no one else is allowed to use the code. If you don't use a
private function within your own program, since your own program is the only
code allowed to use that function, Rust will warn you that the function has
gone unused.

Once we specify that a function like `client::connect` is public, not only will
our call to that function from our binary crate be allowed, the warning that
the function is unused will go away. Marking something public lets Rust know
that we intend for the function to be used by code outside of our program. Rust
considers the theoretical external usage that's now possible as the function
"being used." Thus, when something is marked as public, Rust will not require
that it's used in our own program and will stop warning that the item is unused.

### Making a Function Public

To tell Rust to make something public, we add the `pub` keyword to the start of
the declaration of the item we want to make public. We'll focus on fixing the
warning that tells us that `client::connect` has gone unused for now, as well
as the "module `client` is private" error from our binary crate. Modify
*src/lib.rs* to make the `client` module public, like so:

Filename: src/lib.rs

```rust,ignore
pub mod client;

mod network;
```

The `pub` goes right before `mod`. Let's try building again:

```text
<warnings>
error: function `connect` is private
 --> src/main.rs:4:5
  |
4 |     communicator::client::connect();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says "function `connect` is private", so let's
edit *src/client.rs* to make `client::connect` public too:

Filename: src/client.rs

```rust
pub fn connect() {
}
```

And run `cargo build` again:

```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/mod.rs:1:1
  |
1 | fn connect() {
  | ^

warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/server.rs:1:1
  |
1 | fn connect() {
  | ^
```

It compiled, and the warning about `client::connect` not being used is gone!

Unused code warnings don't always indicate that something needs to be made
public: if you *didn't* want these functions to be part of your public API,
unused code warnings could be alerting you to code you no longer needed and can
safely delete. They could also be alerting you to a bug, if you had just
accidentally removed all places within your library where this function is
called.

In our case though, we *do* want the other two functions to be part of our
crate's public API, so let's mark them as `pub` as well to try to get rid of
the remaining warnings. Modify *src/network/mod.rs* to be:

Filename: src/network/mod.rs

```rust,ignore
pub fn connect() {
}

mod server;
```

And compile:

```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/mod.rs:1:1
  |
1 | pub fn connect() {
  | ^

warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/server.rs:1:1
  |
1 | fn connect() {
  | ^
```

Hmmm, we're still getting an unused function warning even though
`network::connect` is set to `pub`. This is because the function is public
within the module, but the `network` module that the function resides in is not
public. We're working from the interior of the library out this time, where
with `client::connect` we worked from the outside in. We need to change
*src/lib.rs* to make `network` public too:

Filename: src/lib.rs

```rust,ignore
pub mod client;

pub mod network;
```

Now if we compile, that warning is gone:

```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default
 --> src/network/server.rs:1:1
  |
1 | fn connect() {
  | ^
```

Only one warning left! Try to fix this one on your own!

### Privacy Rules

Overall, these are the rules for item visibility:

1. If an item is public, it can be accessed through any of its parent modules.
2. If an item is private, it may be accessed only by the current module and its
  child modules.

### Privacy Examples

Let's look at a few more examples to get some practice. Create a new library
project and enter the code in Listing 7-5 into your new project's *src/lib.rs*:

Filename: src/lib.rs

```rust,ignore
mod outermost {
    pub fn middle_function() {}

    fn middle_secret_function() {}

    mod inside {
        pub fn inner_function() {}

        fn secret_function() {}
    }
}

fn try_me() {
    outermost::middle_function();
    outermost::middle_secret_function();
    outermost::inside::inner_function();
    outermost::inside::secret_function();
}
```

Listing 7-5: Examples of private and public functions, some of which are
incorrect

Before you try to compile this code, make a guess about which lines in `try_me`
function will have errors. Then try compiling to see if you were right, and
read on for discussion of the errors!

#### Looking at the Errors

The `try_me` function is in the root module of our project. The module named
`outermost` is private, but the second privacy rule says the `try_me` function
is allowed to access the `outermost` module since `outermost` is in the current
(root) module, as is `try_me`.

The call to `outermost::middle_function` will work. This is because
`middle_function` is public, and `try_me` is accessing `middle_function`
through its parent module, `outermost`. We determined in the previous paragraph
that this module is accessible.

The call to `outermost::middle_secret_function` will cause a compilation error.
`middle_secret_function` is private, so the second rule applies. The root
module is neither the current module of `middle_secret_function` (`outermost`
is), nor is it a child module of the current module of `middle_secret_function`.

The module named `inside` is private and has no child modules, so it can only
be accessed by its current module, `outermost`. That means the `try_me`
function is not allowed to call `outermost::inside::inner_function` or
`outermost::inside::secret_function` either.

#### Fixing the Errors

Here are some suggestions for changing the code in an attempt to fix the
errors. Before you try each one, make a guess as to whether it will fix the
errors, then compile to see if you're right and use the privacy rules to
understand why.

* What if the `inside` module was public?
* What if `outermost` was public and `inside` was private?
* What if, in the body of `inner_function`, you called
  `::outermost::middle_secret_function()`? (The two colons at the beginning mean
  that we want to refer to the modules starting from the root module.)

Feel free to design more experiments and try them out!

Next, let's talk about bringing items into a scope with the `use` keyword.


text:
import subprocess
import shlex
from subprocess import call

class PlayBulbCandle:

	commands = {
		'setName': '0x001C', # writeReq needed get/set
		'setEffect': '0x0014', # get/set
		'setColor': '0x0016', # get/set
		'getType': '0x0023',
		'getFamily': '0x0025',
		'getFirmwareVersion': '0x0027',
		'getAppVersion': '0x0029',
		'getManufacturer': '0x002b',
		'getBatteryLevel': '0x001f',
	}

	def __init__(self, address, getName = True):
		self.address = address
		self.name = None
		if getName:
			self.getName()

	def rawComms(self, args):
		output,error = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

		# Retry logic
		if 'busy' in error or 'not implement' in error or 'timed out' in error:
			output,error = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

		ans = output.replace('Characteristic value/descriptor: ','')
		ans = ans.replace('\n','').strip()

		# Determine read or write
		commType = 'write'
		if args[3] == '--char-read':
			commType = 'read'

		# Determine address
		commAddress = args[5]

		result = {
			"device": {
				"address": self.address,
				"name": self.name
			},
			"result": "success",
			"msg": ans,
			"type": commType,
			"address": commAddress
		}

		# Remove message if its a write
		if commType == 'write':
			result['cmd'] = args[7]
		else:
			result['parsed'] = self.hexToAscii(ans)

		if len(error) > 0:
			result['result'] = 'error'
			result['msg'] = error
			return result

		return result

	def writeReq(self, address, value):
		try:
			cmd = 'gatttool -b ' + self.address + ' --char-write-req -a ' + address + ' -n "' + value + '"'
			args = shlex.split(cmd)

			return self.rawComms(args)
		except:
			pass

	def write(self, address, value):
		try:
			cmd = 'gatttool -b ' + self.address + ' --char-write -a ' + address + ' -n "' + value + '"'
			args = shlex.split(cmd)

			return self.rawComms(args)
		except:
			pass

	def read(self, address):
		try:
			cmd = 'gatttool -b ' + self.address + ' --char-read -a ' + address
			args = shlex.split(cmd)

			return self.rawComms(args)
		except:
			pass

	def hexToAscii(self, val):
		args = shlex.split(val)
		result = ''
		for arg in args:
			result = result + arg.decode('hex')
		return result

	def asciiToHex(self, val):
		args = list(val)
		result = ''
		for arg in args:
			result = result + arg.encode('hex')
		return result

	def constrainArg(self, val, min = 0, max = 255):
		if (val < min):
			return min
		if (val > max):
			return max
		return val

	def setName(self, value):
		self.name = value
		return self.writeReq(self.commands['setName'], self.asciiToHex(value))

	def getName(self):
		result = self.read(self.commands['setName'])
		self.name = result['parsed']
		return result

	def setEffect(self, white, red, green, blue, mode, speed):
		validModes = {'off': 'FF', 'fade': '01', 'jumpRgb': '02', 'fadeRgb': '03', 'candle': '04'}

		if mode not in validModes:
			raise AttributeError('Invalid mode')

		if mode == 'candle':
			speed = 0

		value = "%0.2X%0.2X%0.2X%0.2X%s00%0.2X00" % (self.constrainArg(white), self.constrainArg(red), self.constrainArg(green), self.constrainArg(blue), validModes[mode], self.constrainArg(speed))
		return self.write(self.commands['setEffect'], value)

	def getEffect(self):
		modes = {1: 'fade', 2: 'jumpRgb', 3: 'fadeRgb', 4: 'candle', 255: 'off'}

		result = self.read(self.commands['setEffect'])
		args = shlex.split(result['msg'])
		result['parsed'] = {
			'white': int(args[0], 16),
			'red': int(args[1], 16),
			'green': int(args[2], 16),
			'blue': int(args[3], 16),
			'mode': modes[int(args[4], 16)],
			'speed': int(args[6], 16)
		}
		return result

	def setColor(self, white, red, green, blue):
		value = "%0.2X%0.2X%0.2X%0.2X" % (self.constrainArg(white), self.constrainArg(red), self.constrainArg(green), self.constrainArg(blue))
		self.setEffect(0, 0, 0, 0, 'off', 0) # Sometimes blowing out the candle causes the effect to show next
		return self.write(self.commands['setColor'], value)

	def getColor(self):
		result = self.read(self.commands['setColor'])
		args = shlex.split(result['msg'])
		result['parsed'] = {
			'white': int(args[0], 16),
			'red': int(args[1], 16),
			'green': int(args[2], 16),
			'blue': int(args[3], 16)
		}
		return result

	def getType(self):
		return self.read(self.commands['getType'])

	def getFamily(self):
		return self.read(self.commands['getFamily'])

	def getFirmwareVersion(self):
		return self.read(self.commands['getFirmwareVersion'])

	def getAppVersion(self):
		return self.read(self.commands['getAppVersion'])

	def getManufacturer(self):
		return self.read(self.commands['getManufacturer'])

	def getBatteryLevel(self):
		result = self.read(self.commands['getBatteryLevel']);
		result['parsed'] = int(result['msg'], 16)
		return result

	def off(self):
		self.setColor(0, 0, 0, 0)

redpajama_set_name: RedPajamaGithub


text:
package com.google.common.truth;

import com.google.common.primitives.Ints;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

/**
 * A Subject to handle testing propositions for {@code int[]}.
 *
 * @author Christian Gruber (cgruber@israfil.net)
 */
public class PrimitiveIntArraySubject
    extends AbstractArraySubject<PrimitiveIntArraySubject, int[]> {
  PrimitiveIntArraySubject(FailureStrategy failureStrategy, @Nullable int[] o) {
    super(failureStrategy, o);
  }

  @Override
  protected String underlyingType() {
    return "int";
  }

  @Override
  protected List<Integer> listRepresentation() {
    return Ints.asList(getSubject());
  }

  /**
   * A proposition that the provided Object[] is an array of the same length and type, and
   * contains elements such that each element in {@code expected} is equal to each element
   * in the subject, and in the same position.
   */
  @Override
  public void isEqualTo(Object expected) {
    int[] actual = getSubject();
    if (actual == expected) {
      return; // short-cut.
    }
    try {
      int[] expectedArray = (int[]) expected;
      if (!Arrays.equals(actual, expectedArray)) {
        fail("is equal to", Ints.asList(expectedArray));
      }
    } catch (ClassCastException e) {
      failWithBadType(expected);
    }
  }

  @Override
  public void isNotEqualTo(Object expected) {
    int[] actual = getSubject();
    try {
      int[] expectedArray = (int[]) expected;
      if (actual == expected || Arrays.equals(actual, expectedArray)) {
        failWithRawMessage(
            "%s unexpectedly equal to %s.", getDisplaySubject(), Ints.asList(expectedArray));
      }
    } catch (ClassCastException ignored) {
    }
  }

  public IterableSubject<?, Integer, List<Integer>> asList() {
    return IterableSubject.create(failureStrategy, listRepresentation());
  }
}


text:
package com.github.lucene.store.database.config;

public class SQLServerConfigTest extends AbstractDatabaseConfigTest {

    public SQLServerConfigTest() {
        super(new SQLServerConfig());
    }

}


text:
import { createStore, compose } from "redux";
import rootReducer from "./reducer";

export default createStore(
  rootReducer,
  undefined,
  compose(window.devToolsExtension ? window.devToolsExtension() : f => f)
);


text:
next: true
sort: 1
title: Introduction
---

# Introduction

Urbit is a clean-slate system software stack defined as a
deterministic computer.  An encrypted P2P network, `%ames`, runs
on a functional operating system, Arvo, written in a strict,
typed functional language, Hoon, which compiles itself to a
combinator interpreter, Nock, whose spec gzips to 340 bytes.

What is Urbit for?  Most directly, Urbit is designed as a
personal cloud server for self-hosted web apps.  It also uses
HTTP APIs to manage data stuck in traditional web applications.

More broadly, Urbit's network tackles identity and security
problems which the Internet can't easily address.  Programming
for a deterministic single-level store is also a different
experience from Unix programming, regardless of language.

## Architectural overview

A deterministic computer?  Urbit's state is a pure function of
its event history.  In practice it uses a memory checkpoint and
an append-only log.  Every event is a transaction; Urbit is an
ACID database and a single-level store.  Urbit runs on Unix now,
but it's easy to imagine on a hypervisor or even bare metal.

A purely functional OS?  Urbit is pure -- no code inside it can
make system calls or otherwise affect the underlying platform.
Instead, the top-level event function defines an I/O protocol.
It maps an input event and the current state to a list of output
actions and the subsequent state.  In Hoon:

    $+([event state] [(list action) state])

### Nock

Nock is a sort of nano-Lisp without syntax, symbols or lambdas.
Most Lisps are one-layer: they create a practical language by
extending a theoretically simple interpreter.  The abstraction is
simple and the implementation is practical; there is no actual
codebase both simple and practical.  Hoon and Nock are two
layers: Hoon compiles itself to pure Nock.  Since Urbit is
defined in Nock, not Hoon, we can upgrade Hoon over the air.

The Nock data model is especially trivial.  A *noun* is an atom
or a cell.  An atom is any unsigned integer.  A cell is an
ordered pair of nouns.  Nouns are acyclic and expose no pointer
equality test.

### Hoon

Hoon is a strict combinator language that avoids mathematical
theory and notation.  It aims at a mechanical, imperative feel.
Hoon uses ASCII digraphs instead of keywords; there are no
user-level macros.  The type system infers only forward and does
not use unification, but is not much weaker than Haskell's.  The
compiler and inference engine is about 2000 lines of Hoon.

### Arvo

Arvo is an event-driven OS written in Hoon.  It can upgrade
itself and everything inside it over the network.  The Arvo
kernel proper is 500 lines of Hoon, which implements a typed
event system with explicit call-stack structure.  Arvo ships
it ships with modules that provide P2P networking (`%ames`), a
revision-control system (`%clay`), a web client/server (`%eyre`),
a functional build system (`%ford`), and an application engine
`(%gall)`.

### `%ames`

`%ames`, the Urbit network, is an encrypted P2P protocol over
UDP.  Its address space is semi-decentralized; 64-bit addresses
are hierarchically distributed, 128-bit addresses are
self-created.  Addresses (or *plots*) are rendered in a phonemic
syntax for memorability.  The scarcity of short plots helps
control spam and other Sybil attacks.  The short plot hierarchy
is also reused as a supernode routing system for NAT traversal.

### Apps

Urbit ships with two default applications: a REPL or shell
`:dojo`, and a distributed user-level message-bus `:talk`.
`:talk` under the hood resembles NNTP; to the user, it looks like
a self-hosted Slack or persistent IRC.

The full Urbit stack (compiler, standard library, kernel,
modules, and applications) is about 25,000 lines of Hoon.
Urbit is patent-free and MIT licensed.

## Status

Anyone can run the Urbit VM, of course.  But the `%ames` network
is officially invitation-only.  Not that we're antisocial -- just
that we're under construction.

Right now, Urbit's only practical use is to (a) build Urbit and
(b) talk about Urbit.  Its performance is lamentable.  Its
documentation is inadequate.  Its keys are test keys.  Its
planets explode on a regular basis.  We reserve the right to
reboot ("flag-day") the whole network.

However, Urbit is at least out of research mode and focused more
or less exclusively on optimization and bug-fixing.  So at least,
whatever you learn will stay true.  And bleeding edges are fun.

## Getting involved

If you're interested in following Urbit, you can:

-   Read our documentation at
    [urbit.org](http://urbit.org/docs)
-   Subscribe to our newsletter at [urbit.org](http://urbit.org).
-   Check out the
    [urbit-dev](https://groups.google.com/forum/#!forum/urbit-dev)
    mailing list.
-   Follow [@urbit_](https://twitter.com/urbit\_) on Twitter.
-   Hit us up by email, urbit@urbit.org.
    We're nice!

## Code of conduct

Everyone involved in the Urbit project needs to understand and
respect our code of conduct, which is: "don't be rude."

## Pronunciation and etymology

Urbit is always pronounced "herb it," never "your bit."  Not that
it's not your bit!  But "herb it" just sounds better.  (Yes, we
speak American and the 'h' is silent.)

The origin of the name is just the Latin *urbi*, meaning city.


text:
/*!
	@header kpi_socketfilter.h
	This header defines an API for intercepting communications at the
	socket layer.

	For the most part, socket filters want to do three things: Filter
	data in and out, watch for state changes, and intercept a few calls
	for security. The number of function pointers supplied by a socket
	filter has been significantly reduced. The filter no longer has any
	knowledge of socket buffers. The filter no longer intercepts nearly
	every internal socket call. There are two data filters, an in
	filter, and an out filter. The in filter occurs before data is
	placed in the receive socket buffer. This is done to avoid waking
	the process unnecessarily. The out filter occurs before the data is
	appended to the send socket buffer. This should cover inbound and
	outbound data. For monitoring state changes, we've added a notify
	function that will be called when various events that the filter can
	not intercept occur. In addition, we've added a few functions that a
	filter may use to intercept common operations. These functions are:
	connect (inbound), connect (outbound), bind, set socket option,
	get socket option, and listen. Bind, listen, connect in, and connect
	out could be used together to build a fairly comprehensive firewall
	without having to do much with individual packets.
 */
#ifndef __KPI_SOCKETFILTER__
#define __KPI_SOCKETFILTER__

#include <sys/kernel_types.h>
#include <sys/kpi_socket.h>

struct sockaddr;

/*!
	@enum sflt_flags
	@abstract Constants defining mbuf flags. Only the flags listed below
		can be set or retrieved.
	@constant SFLT_GLOBAL Indicates this socket filter should be
		attached to all new sockets when they're created.
	@constant SFLT_PROG Indicates this socket filter should be attached
		only when request by the application using the SO_NKE socket
		option.
	@constant SFLT_EXTENDED	Indicates that this socket filter utilizes
		the extended fields within the sflt_filter structure.
	@constant SFLT_EXTENDED_REGISTRY Indicates that this socket filter
		wants to attach to all the sockets already present on the
		system. It will also receive notifications for these sockets.
*/
enum {
	SFLT_GLOBAL		= 0x01,
	SFLT_PROG		= 0x02,
	SFLT_EXTENDED		= 0x04,
	SFLT_EXTENDED_REGISTRY	= 0x08
};
typedef	u_int32_t	sflt_flags;

/*!
	@typedef sflt_handle
	@abstract A 4 byte identifier used with the SO_NKE socket option to
		identify the socket filter to be attached.
*/
typedef	u_int32_t	sflt_handle;

/*!
	@enum sflt_event_t
	@abstract Events notify a filter of state changes and other various
		events related to the socket. These events cannot be prevented
		or intercepted, only observed.
	@constant sock_evt_connected Indicates this socket has moved to the
		connected state.
	@constant sock_evt_disconnected Indicates this socket has moved to
		the disconnected state.
	@constant sock_evt_flush_read The read socket buffer has been
		flushed.
	@constant sock_evt_shutdown The read and or write side(s) of the
		connection have been shutdown. The param will point to an
		integer that indicates the direction that has been shutdown. See
		'man 2 shutdown' for more information.
	@constant sock_evt_cantrecvmore Indicates the socket cannot receive
		more data.
	@constant sock_evt_cantsendmore Indicates the socket cannot send
		more data.
	@constant sock_evt_closing Indicates the socket is closing.
	@constant sock_evt_bound Indicates this socket has moved to the
		bound state (only for PF_INET/PF_INET6 domain).
*/
enum {
	sock_evt_connecting		= 1,
	sock_evt_connected		= 2,
	sock_evt_disconnecting		= 3,
	sock_evt_disconnected		= 4,
	sock_evt_flush_read		= 5,
	sock_evt_shutdown		= 6, /* param points to an integer specifying how (read, write, or both) see man 2 shutdown */
	sock_evt_cantrecvmore		= 7,
	sock_evt_cantsendmore		= 8,
	sock_evt_closing		= 9,
	sock_evt_bound			= 10
};
typedef	u_int32_t	sflt_event_t;

/*!
	@enum sflt_data_flag_t
	@abstract Inbound and outbound data filters may handle many
		different types of incoming and outgoing data. These flags help
		distinguish between normal data, out-of-band data, and records.
	@constant sock_data_filt_flag_oob Indicates this data is out-of-band
		data.
	@constant sock_data_filt_flag_record Indicates this data is a
		record. This flag is only ever seen on inbound data.
*/
enum {
	sock_data_filt_flag_oob		= 1,
	sock_data_filt_flag_record	= 2
};
typedef	u_int32_t	sflt_data_flag_t;

__BEGIN_DECLS

/*!
	@typedef sf_unregistered_func

	@discussion sf_unregistered_func is called to notify the filter it
		has been unregistered. This is the last function the stack will
		call and this function will only be called once all other
		function calls in to your filter have completed. Once this
		function has been called, your kext may safely unload.
	@param handle The socket filter handle used to identify this filter.
*/
typedef	void (*sf_unregistered_func)(sflt_handle handle);

/*!
	@typedef sf_attach_func

	@discussion sf_attach_func is called to notify the filter it has
		been attached to a socket. The filter may allocate memory for
		this attachment and use the cookie to track it. This filter is
		called in one of two cases:
		1) You've installed a global filter and a new socket was created.
		2) Your non-global socket filter is being attached using the SO_NKE
		socket option.
	@param cookie Used to allow the socket filter to set the cookie for
		this attachment.
	@param so The socket the filter is being attached to.
	@result If you return a non-zero value, your filter will not be
		attached to this socket.
*/
typedef	errno_t	(*sf_attach_func)(void	**cookie, socket_t so);

/*!
	@typedef sf_detach_func

	@discussion sf_detach_func is called to notify the filter it has
		been detached from a socket. If the filter allocated any memory
		for this attachment, it should be freed. This function will
		be called when the socket is disposed of.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@discussion If you return a non-zero value, your filter will not be
		attached to this socket.
*/
typedef	void (*sf_detach_func)(void *cookie, socket_t so);

/*!
	@typedef sf_notify_func

	@discussion sf_notify_func is called to notify the filter of various
		state changes and other events occuring on the socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param event The type of event that has occurred.
	@param param Additional information about the event.
*/
typedef	void (*sf_notify_func)(void *cookie, socket_t so, sflt_event_t event,
    void *param);

/*!
	@typedef sf_getpeername_func

	@discussion sf_getpeername_func is called to allow a filter to
		to intercept the getpeername function. When called, sa will
		point to a pointer to a socket address that was malloced
		in zone M_SONAME. If you want to replace this address, either
		modify the currenty copy or allocate a new one and free the
		old one.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param sa A pointer to a socket address pointer.
	@result If you return a non-zero value, processing will stop. If
		you return EJUSTRETURN, no further filters will be called
		but a result of zero will be returned to the caller of
		getpeername.
*/
typedef	int (*sf_getpeername_func)(void *cookie, socket_t so,
    struct sockaddr **sa);

/*!
	@typedef sf_getsockname_func

	@discussion sf_getsockname_func is called to allow a filter to
		to intercept the getsockname function. When called, sa will
		point to a pointer to a socket address that was malloced
		in zone M_SONAME. If you want to replace this address, either
		modify the currenty copy or allocate a new one and free the
		old one.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param sa A pointer to a socket address pointer.
	@result If you return a non-zero value, processing will stop. If
		you return EJUSTRETURN, no further filters will be called
		but a result of zero will be returned to the caller of
		getsockname.
*/
typedef	int (*sf_getsockname_func)(void *cookie, socket_t so,
    struct sockaddr **sa);

/*!
	@typedef sf_data_in_func

	@discussion sf_data_in_func is called to filter incoming data. If your
		filter intercepts data for later reinjection, it must queue
		all incoming data to preserve the order of the data. Use
		sock_inject_data_in to later reinject this data if you return
		EJUSTRETURN. Warning: This filter is on the data path. Do not
		spend excesive time. Do not wait for data on another socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param from The addres the data is from, may be NULL if the socket
		is connected.
	@param data The data being received. Control data may appear in the
		mbuf chain, be sure to check the mbuf types to find control
		data.
	@param control Control data being passed separately from the data.
	@param flags Flags to indicate if this is out of band data or a
		record.
	@result Return:
		0 - The caller will continue with normal processing of the data.
		EJUSTRETURN - The caller will stop processing the data, the
			data will not be freed.
		Anything Else - The caller will free the data and stop
			processing.
*/
typedef	errno_t	(*sf_data_in_func)(void *cookie, socket_t so,
    const struct sockaddr *from, mbuf_t *data, mbuf_t *control,
    sflt_data_flag_t flags);

/*!
	@typedef sf_data_out_func

	@discussion sf_data_out_func is called to filter outbound data. If
		your filter intercepts data for later reinjection, it must queue
		all outbound data to preserve the order of the data when
		reinjecting. Use sock_inject_data_out to later reinject this
		data.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param to The address the data is to, may be NULL if the socket
		is connected.
	@param data The data being received. Control data may appear in the
		mbuf chain, be sure to check the mbuf types to find control
		data.
	@param control Control data being passed separately from the data.
	@param flags Flags to indicate if this is out of band data or a
		record.
	@result Return:
		0 - The caller will continue with normal processing of the data.
		EJUSTRETURN - The caller will stop processing the data,
			the data will not be freed.
		Anything Else - The caller will free the data and stop
			processing.
*/
typedef	errno_t	(*sf_data_out_func)(void *cookie, socket_t so,
    const struct sockaddr *to, mbuf_t *data, mbuf_t *control,
    sflt_data_flag_t flags);

/*!
	@typedef sf_connect_in_func

	@discussion sf_connect_in_func is called to filter inbound connections.
		A protocol will call this before accepting an incoming
		connection and placing it on the queue of completed connections.
		Warning: This filter is on the data path. Do not spend excesive
		time. Do not wait for data on another socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param from The address the incoming connection is from.
	@result Return:
		0 - The caller will continue with normal processing of the
			connection.
		Anything Else - The caller will rejecting the incoming
			connection.
*/
typedef	errno_t	(*sf_connect_in_func)(void *cookie, socket_t so,
    const struct sockaddr *from);

/*!
	@typedef sf_connect_out_func

	@discussion sf_connect_out_func is called to filter outbound
		connections. A protocol will call this before initiating an
		outbound connection.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param to The remote address of the outbound connection.
	@result Return:
		0 - The caller will continue with normal processing of the
			connection.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
			from that point without further processing the connect command. The
			protocol layer will not see the call.
		Anything Else - The caller will rejecting the outbound
			connection.
*/
typedef	errno_t	(*sf_connect_out_func)(void *cookie, socket_t so,
    const struct sockaddr *to);

/*!
	@typedef sf_bind_func

	@discussion sf_bind_func is called before performing a bind
		operation on a socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param to The local address of the socket will be bound to.
	@result Return:
		0 - The caller will continue with normal processing of the bind.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
			from that point without further processing the bind command. The
			protocol layer will not see the call.
		Anything Else - The caller will rejecting the bind.
*/
typedef	errno_t	(*sf_bind_func)(void *cookie, socket_t so,
    const struct sockaddr *to);

/*!
	@typedef sf_setoption_func

	@discussion sf_setoption_func is called before performing setsockopt
		on a socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param opt The socket option to set.
	@result Return:
		0 - The caller will continue with normal processing of the
			setsockopt.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
			from that point without further propagating the set option
			command. The socket and protocol layers will not see the call.
		Anything Else - The caller will stop processing and return
			this error.
*/
typedef	errno_t	(*sf_setoption_func)(void *cookie, socket_t so, sockopt_t opt);

/*!
	@typedef sf_getoption_func

	@discussion sf_getoption_func is called before performing getsockopt
		on a socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param opt The socket option to get.
	@result Return:
		0 - The caller will continue with normal processing of the
			getsockopt.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
			from that point without further propagating the get option
			command. The socket and protocol layers will not see the call.
		Anything Else - The caller will stop processing and return
			this error.
*/
typedef	errno_t	(*sf_getoption_func)(void *cookie, socket_t so, sockopt_t opt);

/*!
	@typedef sf_listen_func

	@discussion sf_listen_func is called before performing listen
		on a socket.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@result Return:
		0 - The caller will continue with normal processing of listen.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
		from that point without further processing the listen command. The
		protocol will not see the call.
		Anything Else - The caller will stop processing and return
			this error.
*/
typedef	errno_t	(*sf_listen_func)(void *cookie, socket_t so);

/*!
	@typedef sf_ioctl_func

	@discussion sf_ioctl_func is called before performing an ioctl
		on a socket.

		All undefined ioctls are reserved for future use by Apple. If
		you need to communicate with your kext using an ioctl, please
		use SIOCSIFKPI and SIOCGIFKPI.
	@param cookie Cookie value specified when the filter attach was
		called.
	@param so The socket the filter is attached to.
	@param request The ioctl name.
	@param argp A pointer to the ioctl parameter.
	@result Return:
		0 - The caller will continue with normal processing of
			this ioctl.
		EJUSTRETURN - The caller will return with a value of 0 (no error)
			from that point without further processing or propogating
			the ioctl.
		Anything Else - The caller will stop processing and return
			this error.
*/
typedef	errno_t	(*sf_ioctl_func)(void *cookie, socket_t so,
    unsigned long request, const char* argp);

/*!
	@typedef sf_accept_func

	@discussion sf_accept_func is called after a socket is dequeued
		off the completed (incoming) connection list and before
		the file descriptor is associated with it.  A filter can
		utilize this callback to intercept the accepted socket
		in order to examine it, prior to returning the socket to
		the caller of accept.  Such a filter may also choose to
		discard the accepted socket if it wishes to do so.
	@param cookie Cookie value specified when the filter attach was called.
	@param so_listen The listening socket.
	@param so The socket that is about to be accepted.
	@param local The local address of the about to be accepted socket.
	@param remote The remote address of the about to be accepted socket.
	@result Return:
		0 - The caller will continue with normal processing of accept.
		EJUSTRETURN - The to be accepted socket will be disconnected
		    prior to being returned to the caller of accept.  No further
		    control or data operations on the socket will be allowed.
		    This is the recommended return value as it has the least
		    amount of impact, especially to applications which don't
		    check the error value returned by accept.
		Anything Else - The to be accepted socket will be closed and
		    the error will be returned to the caller of accept.
		    Note that socket filter developers are advised to exercise
		    caution when returning non-zero values to the caller,
		    since some applications don't check the error value
		    returned by accept and therefore risk breakage.
 */
typedef errno_t (*sf_accept_func)(void *cookie, socket_t so_listen, socket_t so,
    const struct sockaddr *local, const struct sockaddr *remote);

/*!
	@struct sflt_filter
	@discussion This structure is used to define a socket filter.
	@field sf_handle A value used to find socket filters by
		applications. An application can use this value to specify that
		this filter should be attached when using the SO_NKE socket
		option.
	@field sf_flags Indicate whether this filter should be attached to
		all new sockets or just those that request the filter be
		attached using the SO_NKE socket option. If this filter
		utilizes the socket filter extension fields, it must also
		set SFLT_EXTENDED.
	@field sf_name A name used for debug purposes.
	@field sf_unregistered Your function for being notified when your
		filter has been unregistered.
	@field sf_attach Your function for handling attaches to sockets.
	@field sf_detach Your function for handling detaches from sockets.
	@field sf_notify Your function for handling events. May be null.
	@field sf_data_in Your function for handling incoming data. May be
		null.
	@field sf_data_out Your function for handling outgoing data. May be
		null.
	@field sf_connect_in Your function for handling inbound
		connections. May be null.
	@field sf_connect_out Your function for handling outbound
		connections. May be null.
	@field sf_bind Your function for handling binds. May be null.
	@field sf_setoption Your function for handling setsockopt. May be null.
	@field sf_getoption Your function for handling getsockopt. May be null.
	@field sf_listen Your function for handling listen. May be null.
	@field sf_ioctl Your function for handling ioctls. May be null.
	@field sf_len Length of socket filter extension structure; developers
		must initialize this to sizeof sflt_filter_ext structure.
		This field and all fields following it will only be valid
		if SFLT_EXTENDED flag is set in sf_flags field.
	@field sf_ext_accept Your function for handling inbound connections
		at accept time.  May be null.
	@field sf_ext_rsvd Reserved for future use; you must initialize
		the reserved fields with zeroes.
*/
struct sflt_filter {
	sflt_handle			sf_handle;
	int				sf_flags;
	char				*sf_name;

	sf_unregistered_func		sf_unregistered;
	sf_attach_func			sf_attach;
	sf_detach_func			sf_detach;

	sf_notify_func			sf_notify;
	sf_getpeername_func		sf_getpeername;
	sf_getsockname_func		sf_getsockname;
	sf_data_in_func			sf_data_in;
	sf_data_out_func		sf_data_out;
	sf_connect_in_func		sf_connect_in;
	sf_connect_out_func		sf_connect_out;
	sf_bind_func			sf_bind;
	sf_setoption_func		sf_setoption;
	sf_getoption_func		sf_getoption;
	sf_listen_func			sf_listen;
	sf_ioctl_func			sf_ioctl;
	/*
	 * The following are valid only if SFLT_EXTENDED flag is set.
	 * Initialize sf_ext_len to sizeof sflt_filter_ext structure.
	 * Filters must also initialize reserved fields with zeroes.
	 */
	struct sflt_filter_ext {
		unsigned int		sf_ext_len;
		sf_accept_func		sf_ext_accept;
		void			*sf_ext_rsvd[5];	/* Reserved */
	} sf_ext;
#define	sf_len		sf_ext.sf_ext_len
#define	sf_accept	sf_ext.sf_ext_accept
};

/*!
	@function sflt_register
	@discussion Registers a socket filter. See 'man 2 socket' for a
		desciption of domain, type, and protocol.
	@param filter A structure describing the filter.
	@param domain The protocol domain these filters will be attached to.
		Only PF_INET & PF_INET6 domains are supported.
	@param type The socket type these filters will be attached to.
	@param protocol The protocol these filters will be attached to.
	@result 0 on success otherwise the errno error.
 */
extern errno_t sflt_register(const struct sflt_filter *filter, int domain,
    int type, int protocol);

/*!
	@function sflt_unregister
	@discussion Unregisters a socket filter. This will not detach the
		socket filter from all sockets it may be attached to at the
		time, it will just prevent the socket filter from being attached
		to any new sockets.
	@param handle The sf_handle of the socket filter to unregister.
	@result 0 on success otherwise the errno error.
 */
extern errno_t sflt_unregister(sflt_handle handle);

/*!
	@function sflt_attach
	@discussion Attaches a socket filter to the specified socket. A
		filter must be registered before it can be attached.
	@param socket The socket the filter should be attached to.
	@param handle The handle of the registered filter to be attached.
	@result 0 on success otherwise the errno error.
 */
extern errno_t sflt_attach(socket_t socket, sflt_handle handle);

/*!
	@function sflt_detach
	@discussion Detaches a socket filter from a specified socket.
	@param socket The socket the filter should be detached from.
	@param handle The handle of the registered filter to be detached.
	@result 0 on success otherwise the errno error.
 */
extern errno_t sflt_detach(socket_t socket, sflt_handle handle);

/* Functions for manipulating sockets */
/*
 * Inject data in to the receive buffer of the socket as if it
 * had come from the network.
 *
 * flags should match sflt_data_flag_t
 */

/*!
	@function sock_inject_data_in
	@discussion Inject data in to the receive buffer of the socket as if
		it had come from the network.
	@param so The socket to inject the data on.
	@param from The address the data is from, only necessary on
		un-connected sockets. A copy of the address will be made, caller
		is responsible for freeing the address after calling this
		function.
	@param data The data and possibly control mbufs.
	@param control The separate control mbufs.
	@param flags Flags indicating the type of data.
	@result 0 on success otherwise the errno error. If the function
		returns an error, the caller is responsible for freeing the
		mbuf.
 */
extern errno_t sock_inject_data_in(socket_t so, const struct sockaddr *from,
    mbuf_t data, mbuf_t control, sflt_data_flag_t flags);

/*!
	@function sock_inject_data_out
	@discussion Inject data in to the send buffer of the socket as if it
		had come from the client.
	@param so The socket to inject the data on.
	@param to The address the data should be sent to, only necessary on
		un-connected sockets. The caller is responsible for freeing the
		to address after sock_inject_data_out returns.
	@param data The data and possibly control mbufs.
	@param control The separate control mbufs.
	@param flags Flags indicating the type of data.
	@result 0 on success otherwise the errno error. The data and control
		values are always freed regardless of return value.
 */
extern errno_t sock_inject_data_out(socket_t so, const struct sockaddr *to,
    mbuf_t data, mbuf_t control, sflt_data_flag_t flags);

/*
 * sockopt_t accessors
 */

enum {
	sockopt_get	= 1,
	sockopt_set	= 2
};
typedef u_int8_t sockopt_dir;

/*!
	@function sockopt_direction
	@discussion Retrieves the direction of the socket option (Get or
		Set).
	@param sopt The socket option.
	@result sock_opt_get or sock_opt_set.
 */
extern sockopt_dir sockopt_direction(sockopt_t sopt);

/*!
	@function sockopt_level
	@discussion Retrieves the socket option level. (SOL_SOCKET, etc).
	@param sopt The socket option.
	@result The socket option level. See man 2 setsockopt
 */
extern int sockopt_level(sockopt_t sopt);

/*!
	@function sockopt_name
	@discussion Retrieves the socket option name. (SO_SNDBUF, etc).
	@param sopt The socket option.
	@result The socket option name. See man 2 setsockopt
 */
extern int sockopt_name(sockopt_t sopt);

/*!
	@function sockopt_valsize
	@discussion Retrieves the size of the socket option data.
	@param sopt The socket option.
	@result The length, in bytes, of the data.
 */
extern size_t sockopt_valsize(sockopt_t sopt);

/*!
	@function sockopt_copyin
	@discussion Copies the data from the socket option to a buffer.
	@param sopt The socket option.
	@param data A pointer to the buffer to copy the data in to.
	@param length The number of bytes to copy.
	@result An errno error or zero upon success.
 */
extern errno_t sockopt_copyin(sockopt_t sopt, void *data, size_t length);

/*!
	@function sockopt_copyout
	@discussion Copies the data from a buffer to a socket option.
	@param sopt The socket option.
	@param data A pointer to the buffer to copy the data out of.
	@param length The number of bytes to copy.
	@result An errno error or zero upon success.
 */
extern errno_t sockopt_copyout(sockopt_t sopt, void *data, size_t length);

__END_DECLS
#endif /* __KPI_SOCKETFILTER__ */


text:
/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_LOGGING_H
#include "gucefCORE_Logging.h"
#define GUCEF_CORE_LOGGING_H
#endif /* GUCEF_CORE_LOGGING_H ? */

#ifndef GUCEF_CORE_CCOREGLOBAL_H
#include "gucefCORE_CCoreGlobal.h"
#define GUCEF_CORE_CCOREGLOBAL_H
#endif /* GUCEF_CORE_CCOREGLOBAL_H ? */

#ifndef GUCEF_CORE_CGUCEFAPPLICATION_H
#include "CGUCEFApplication.h"
#define GUCEF_CORE_CGUCEFAPPLICATION_H
#endif /* GUCEF_CORE_CGUCEFAPPLICATION_H ? */

#ifndef GUCEF_CORE_CFILEACCESS_H
#include "CFileAccess.h"
#define GUCEF_CORE_CFILEACCESS_H
#endif /* GUCEF_CORE_CFILEACCESS_H ? */

#ifndef GUCEF_CORE_CVALUELIST_H
#include "CValueList.h"
#define GUCEF_CORE_CVALUELIST_H
#endif /* GUCEF_CORE_CVALUELIST_H ? */

#ifndef GUCEF_CORE_LOGGING_H
#include "gucefCORE_Logging.h"
#define GUCEF_CORE_LOGGING_H
#endif /* GUCEF_CORE_LOGGING_H ? */

#ifndef CSERVERPORTEXTENDER_H
#include "CServerPortExtender.h"
#define CSERVERPORTEXTENDER_H
#endif /* CSERVERPORTEXTENDER_H ? */

#ifndef CSERVERPORTEXTENDERCLIENT_H
#include "CServerPortExtenderClient.h"
#define CSERVERPORTEXTENDERCLIENT_H
#endif /* CSERVERPORTEXTENDERCLIENT_H ? */

/*-------------------------------------------------------------------------//
//                                                                         //
//      UTILITIES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

class SpeTestController : CORE::CObserver
{
    public:

    //GUCEF_INLINED_MSGEXCEPTION(

    SpeTestController()
        : CORE::CObserver()          ,
          m_client( NULL )           ,
          m_server( NULL )           ,
          m_serverConnection( NULL ) ,
          m_spe( NULL )              ,
          m_speClient( NULL )
    {
        GUCEF::CORE::CGUCEFApplication* app = &CORE::CCoreGlobal::Instance()->GetApplication();

        m_spe = new CServerPortExtender( app->GetPulseGenerator() );
        m_speClient = new CServerPortExtenderClient( app->GetPulseGenerator() );

        SubscribeTo( app );
        SubscribeTo( m_spe );
    }

    virtual ~SpeTestController()
    {
        delete m_spe;
        m_spe = NULL;

        delete m_speClient;
        m_speClient = NULL;

        delete m_client;
        m_client = NULL;

        delete m_server;
        m_server = NULL;
    }

    virtual void OnNotify( CORE::CNotifier* notifier           ,
                           const CORE::CEvent& eventid         ,
                           CORE::CICloneable* eventdata = NULL )
    {
        if ( GUCEF::CORE::CGUCEFApplication::AppInitEvent == eventid )
        {
            GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Application initializing..." );

            m_client = new COMCORE::CTCPClientSocket( false );
            m_server = new COMCORE::CTCPServerSocket( false );

            SubscribeTo( m_client );
            SubscribeTo( m_server );

            m_spe->ListenForClientsOnPort( 10001 );
            m_spe->ListenForReversedClientsOnPort( 10002 );
            m_spe->ListenForReversedControlClientOnPort( 10003 );

            m_speClient->SetLocalServer( "localhost", 10000 );
            m_speClient->SetRemoteServerSocket( 10002 );
            m_server->ListenOnPort( 10000 );
        }
        else
        if ( notifier == m_spe )
        {
            if ( CServerPortExtender::ControlSocketOpenedEvent == eventid )
            {
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Connecting to control socket" );
                m_speClient->ConnectToSPEControlSocket( "localhost", 10003 );
            }
            else
            if ( CServerPortExtender::ReversedSocketOpenedEvent == eventid )
            {

            }
            else
            if ( CServerPortExtender::ControlConnectionEstablishedEvent == eventid )
            {
                // now that we have a control connection lets try connecting a client
                // to the extended server socket
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: SPE control connection established" );
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Connecting test client to the extended server socket" );
                m_client->ConnectTo( "localhost", 10001 );
            }
        }
        else
        if ( notifier == m_server )
        {
            if ( COMCORE::CTCPServerSocket::ClientConnectedEvent == eventid )
            {
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: A client connected to the test server" );

                // Get the connection object
                COMCORE::CTCPServerSocket::TClientConnectedEventData* eData = static_cast< GUCEF::COMCORE::CTCPServerSocket::TClientConnectedEventData* >( eventdata );
                COMCORE::CTCPServerSocket::TConnectionInfo& connectionInfo = eData->GetData();

                // keep a convenience pointer to the connection object which is ok knowing how the test works
                m_serverConnection = connectionInfo.connection;

                SubscribeTo( connectionInfo.connection );
            }
        }
        else
        if ( notifier == m_client )
        {
            if ( GUCEF::COMCORE::CTCPClientSocket::ConnectedEvent == eventid )
            {
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Sending test string from the test client" );
                m_client->SendString( "Client:ThisIsATestString" );
            }
            else
            if ( GUCEF::COMCORE::CTCPClientSocket::DataRecievedEvent == eventid )
            {
                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: recieved data on the test client" );

                // Get the data buffer
                COMCORE::CTCPClientSocket::TDataRecievedEventData* eData = static_cast< COMCORE::CTCPClientSocket::TDataRecievedEventData* >( eventdata );
                const CORE::CDynamicBuffer& data = eData->GetData();

                CORE::CString testString;
                testString.Scan( (const char*)data.GetConstBufferPtr(), data.GetDataSize() );

                if ( testString == "Server:ThisIsATestString" )
                {
                    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: data was successfully communicated from the test server to the test client using the SPE functionality!!!" );

                    // Now see if we can do it again with a data packet of a different size
                     m_client->SendString( "Client:ThisIsTheSecondTestString" );
                }
                else
                if ( testString == "Server:ThisIsTheSecondTestString" )
                {
                    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: data was successfully communicated from the test server to the test client using the SPE functionality for the second time!!!" );
                    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Finished the test successfully, we can now shut down" );
                    CORE::CCoreGlobal::Instance()->GetApplication().Stop();
                }
                else
                {
                    // error
                }
            }
        }
        else
        if ( notifier == m_serverConnection )
        {
            if ( COMCORE::CTCPServerConnection::DataRecievedEvent == eventid )
            {
                // Get the data buffer
                COMCORE::CTCPServerConnection::TDataRecievedEventData* eData = static_cast< COMCORE::CTCPServerConnection::TDataRecievedEventData* >( eventdata );
                const CORE::CDynamicBuffer& data = eData->GetData();

                CORE::CString testString;
                testString.Scan( (const char*)data.GetConstBufferPtr(), data.GetDataSize() );

                GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: Received data on the test server: " + testString );

                if ( testString == "Client:ThisIsATestString" )
                {
                    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: data was successfully communicated from the test client to the test server using the SPE functionality!!!" );

                    m_serverConnection->SendString( "Server:ThisIsATestString" );
                }
                else
                if ( testString == "Client:ThisIsTheSecondTestString" )
                {
                    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SpeTestController: data was successfully communicated from the test client to the test server using the SPE functionality for the second time!!!" );

                    m_serverConnection->SendString( "Server:ThisIsTheSecondTestString" );
                }
                else
                {
                    // error
                }
            }
        }
    }

    COMCORE::CTCPClientSocket* m_client;
    COMCORE::CTCPServerSocket* m_server;
    COMCORE::CTCPServerConnection* m_serverConnection;
    CServerPortExtender* m_spe;
    CServerPortExtenderClient* m_speClient;
};

/*-------------------------------------------------------------------------*/

int
TestSPE( int argc , char* argv[], CORE::CValueList& keyValueList )
{GUCEF_TRACE;

    SpeTestController testController;
    return CORE::CCoreGlobal::Instance()->GetApplication().main( argc, argv, true );
}

/*-------------------------------------------------------------------------*/

void
ParseParams( const int argc                 ,
             char* argv[]                   ,
             CORE::CValueList& keyValueList )
{GUCEF_TRACE;

    keyValueList.DeleteAll();
    GUCEF::CORE::CString argString;
    if ( argc > 0 )
    {
        argString = *argv;

        // Combine the argument strings back into a single string because we don't want to use
        // a space as the seperator
        for ( int i=1; i<argc; ++i )
        {
            argString += ' ' + CORE::CString( argv[ i ] );
        }

        // Parse the param list based on the ' symbol
        keyValueList.SetMultiple( argString, '\'' );
    }
}

/*-------------------------------------------------------------------------*/

void
GucefAppSignalHandler( int signal )
{GUCEF_TRACE;

    ::GUCEF::CORE::CCoreGlobal::Instance()->GetApplication().Stop();
}

/*-------------------------------------------------------------------------*/

/*
 *      Application entry point
 */
//GUCEF_OSMAIN_BEGIN
GUCEF_OSSERVICEMAIN_BEGIN( "ServerPortExtender" )
{GUCEF_TRACE;

    // Parse the application parameters
    CORE::CValueList keyValueList;
    ParseParams( argc, argv, keyValueList );

    CORE::CString outputDir = CORE::RelativePath( keyValueList.GetValueAlways( "outputDir" ) );
    if ( outputDir.IsNULLOrEmpty() )
    {
        outputDir = CORE::RelativePath( "$CURWORKDIR$" );
    }
    CORE::CreateDirs( outputDir );

    CORE::CString logFilename = CORE::CombinePath( outputDir, "ServerPortExtender_Log.txt" );

    keyValueList.Set( "logfile", logFilename );

    CORE::CRollingFileAccess logFileAccess( logFilename, "w" );
    logFileAccess.SetMaxRolloverFilesBeforeDeletion( 10 );
    CORE::CStdLogger logger( logFileAccess );
    CORE::CCoreGlobal::Instance()->GetLogManager().AddLogger( &logger );

    CORE::CPlatformNativeConsoleLogger console;
    if ( GUCEF_APP_TYPE == GUCEF_APP_TYPE_CONSOLE )
        CORE::CCoreGlobal::Instance()->GetLogManager().AddLogger( console.GetLogger() );

    CORE::CCoreGlobal::Instance()->GetLogManager().FlushBootstrapLogEntriesToLogs();
    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Flushed to log @ " + logFilename );

    GUCEF_OSMAIN_SIGNAL_HANDLER( GucefAppSignalHandler );

    // Do we want to display the console window?
    #ifdef GUCEF_MSWIN_BUILD
    CORE::CMSWinConsoleLogger* consoleOut = NULL;
    bool showConsole = true;
    if ( keyValueList.HasKey( "showConsole" ) )
    {
        showConsole = CORE::StringToBool( keyValueList.GetValue( "showConsole" ) );
    }
    if ( showConsole )
    {
        consoleOut = new CORE::CMSWinConsoleLogger();
        CORE::CCoreGlobal::Instance()->GetLogManager().AddLogger( consoleOut );

        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: Enabled console output" );
    }
    #endif /* GUCEF_MSWIN_BUILD ? */

    // Check if we want to do a diagnostic test
    bool runTest = false;
    if ( keyValueList.HasKey( "runTest" ) )
    {
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: Found request for diagnostic test,.. running test" );
        runTest = CORE::StringToBool( keyValueList.GetValue( "runTest" ) );
    }
    if ( runTest )
    {
        TestSPE( argc, argv, keyValueList );
    }

    // Check for the application role
    bool actAsServer = true;
    if ( keyValueList.HasKey( "appRole" ) )
    {
        CORE::CString appRole = keyValueList.GetValue( "appRole" );
        if ( appRole == "client" )
        {
            actAsServer = false;
        }
    }

    if ( actAsServer )
    {
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: application role set to server" );

        CORE::UInt16 extendedServerPort = 10234;
        if ( keyValueList.HasKey( "extendedServerPort" ) )
        {
            extendedServerPort = keyValueList.GetValue( "extendedServerPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: extended server port set to " + CORE::UInt16ToString( extendedServerPort ) );

        CORE::UInt16 serverControlPort = 10236;
        if ( keyValueList.HasKey( "serverControlPort" ) )
        {
            serverControlPort = keyValueList.GetValue( "serverControlPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: server control port set to " + CORE::UInt16ToString( serverControlPort ) );

        CORE::UInt16 reversedServerPort = 10235;
        if ( keyValueList.HasKey( "reversedServerPort" ) )
        {
            reversedServerPort = keyValueList.GetValue( "reversedServerPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: reversed server port set to " + CORE::UInt16ToString( reversedServerPort ) );

        CORE::CGUCEFApplication* app = &CORE::CCoreGlobal::Instance()->GetApplication();
        CServerPortExtender serverPortExtender( app->GetPulseGenerator() );

        serverPortExtender.ListenForReversedControlClientOnPort( serverControlPort );
        serverPortExtender.ListenForReversedClientsOnPort( reversedServerPort );
        serverPortExtender.ListenForClientsOnPort( extendedServerPort );

        return app->main( argc, argv, true );
    }
    else
    {
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: application role set to client" );

        CORE::UInt16 actualServerPort = 10234;
        if ( keyValueList.HasKey( "actualServerPort" ) )
        {
            actualServerPort = keyValueList.GetValue( "actualServerPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: actual server port set to " + CORE::UInt16ToString( actualServerPort ) );

        CORE::CString actualServerHostname = "localhost";
        if ( keyValueList.HasKey( "actualServerHostname" ) )
        {
            actualServerHostname = keyValueList.GetValue( "actualServerHostname" ).AsString();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: actual server hostname set to " + actualServerHostname );

        CORE::UInt16 reversedServerPort = 10235;
        if ( keyValueList.HasKey( "reversedServerPort" ) )
        {
            reversedServerPort = keyValueList.GetValue( "reversedServerPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: reversed server port set to " + CORE::UInt16ToString( reversedServerPort ) );

        CORE::CString speServerHostname = "localhost";
        if ( keyValueList.HasKey( "speServerHostname" ) )
        {
            speServerHostname = keyValueList.GetValue( "speServerHostname" ).AsString();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: SPE server hostname set to " + speServerHostname );

        CORE::UInt16 speServerPort = 10236;
        if ( keyValueList.HasKey( "speServerControlPort" ) )
        {
            speServerPort = keyValueList.GetValue( "speServerControlPort" ).AsUInt16();
        }
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "SPE: SPE server port set to " + CORE::UInt16ToString( speServerPort ) );

        CORE::CGUCEFApplication* app = &CORE::CCoreGlobal::Instance()->GetApplication();
        CServerPortExtenderClient serverPortExtenderClient( app->GetPulseGenerator() );

        serverPortExtenderClient.SetLocalServer( actualServerHostname, actualServerPort );
        serverPortExtenderClient.SetRemoteServerSocket( reversedServerPort );

        serverPortExtenderClient.ConnectToSPEControlSocket( speServerHostname, speServerPort );
        return app->main( argc, argv, true );
    }

    #ifdef GUCEF_MSWIN_BUILD
    delete consoleOut;
    consoleOut = NULL;
    #endif /* GUCEF_MSWIN_BUILD ? */

    return 0;
}
GUCEF_OSMAIN_END

/*---------------------------------------------------------------------------*/


text:
package org.drools.workbench.models.guided.dtable.shared.auditlog;

import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.LimitedEntryConditionCol52;

/**
 * Details of a Limited Entry Condition column
 */
public class LimitedEntryConditionColumnDetails extends ConditionColumnDetails {

    private static final long serialVersionUID = 7986730411677479010L;

    private DTCellValue52 value;

    public LimitedEntryConditionColumnDetails() {
    }

    public LimitedEntryConditionColumnDetails( final LimitedEntryConditionCol52 column ) {
        super( column );
        this.value = column.getValue();
    }

    public DTCellValue52 getValue() {
        return value;
    }

}


text:
package com.facebook.buck.android;

import com.facebook.buck.jvm.java.CalculateAbi;
import com.facebook.buck.jvm.java.JavaLibrary;
import com.facebook.buck.jvm.java.JavaLibraryDescription;
import com.facebook.buck.jvm.java.JavaSourceJar;
import com.facebook.buck.jvm.java.JavacOptions;
import com.facebook.buck.jvm.java.JavacOptionsFactory;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Either;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.query.Query;
import com.facebook.buck.rules.query.QueryUtils;
import com.facebook.buck.util.DependencyMode;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;

import java.nio.file.Path;
import java.util.Optional;
import java.util.stream.Collectors;

public class AndroidLibraryDescription
    implements Description<AndroidLibraryDescription.Arg>, Flavored,
    ImplicitDepsInferringDescription<AndroidLibraryDescription.Arg> {
  public static final BuildRuleType TYPE = BuildRuleType.of("android_library");

  private static final Flavor DUMMY_R_DOT_JAVA_FLAVOR =
      AndroidLibraryGraphEnhancer.DUMMY_R_DOT_JAVA_FLAVOR;

  public enum JvmLanguage {
    JAVA,
    KOTLIN,
    SCALA,
  }

  private final JavacOptions defaultOptions;
  private final boolean suggestDependencies;
  private final AndroidLibraryCompilerFactory compilerFactory;

  public AndroidLibraryDescription(
      JavacOptions defaultOptions,
      boolean suggestDependencies,
      AndroidLibraryCompilerFactory compilerFactory) {
    this.defaultOptions = defaultOptions;
    this.suggestDependencies = suggestDependencies;
    this.compilerFactory = compilerFactory;
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @Override
  public <A extends Arg> BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      CellPathResolver cellRoots,
      A args) throws NoSuchBuildTargetException {
    if (params.getBuildTarget().getFlavors().contains(JavaLibrary.SRC_JAR)) {
      return new JavaSourceJar(params, args.srcs, args.mavenCoords);
    }

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);

    JavacOptions javacOptions = JavacOptionsFactory.create(
        defaultOptions,
        params,
        resolver,
        ruleFinder,
        args
    );

    final ImmutableSet.Builder<BuildRule> queriedDepsBuilder = ImmutableSet.builder();
    if (args.depsQuery.isPresent()) {
      queriedDepsBuilder.addAll(
          QueryUtils.resolveDepQuery(
              params,
              args.depsQuery.get(),
              resolver,
              cellRoots,
              targetGraph)
              .collect(Collectors.toList()));

    }
    final ImmutableSet<BuildRule> queriedDeps = queriedDepsBuilder.build();

    AndroidLibraryGraphEnhancer graphEnhancer = new AndroidLibraryGraphEnhancer(
        params.getBuildTarget(),
        params.copyReplacingExtraDeps(
            Suppliers.ofInstance(
                ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(queriedDeps)
                    .addAll(resolver.getAllRules(args.exportedDeps))
                    .build())),
        javacOptions,
        DependencyMode.FIRST_ORDER,
        /* forceFinalResourceIds */ false,
        args.resourceUnionPackage,
        args.finalRName,
        false);

    boolean hasDummyRDotJavaFlavor =
        params.getBuildTarget().getFlavors().contains(DUMMY_R_DOT_JAVA_FLAVOR);
    if (CalculateAbi.isAbiTarget(params.getBuildTarget())) {
      if (hasDummyRDotJavaFlavor) {
        return graphEnhancer.getBuildableForAndroidResourcesAbi(resolver, ruleFinder);
      }
      BuildTarget libraryTarget = CalculateAbi.getLibraryTarget(params.getBuildTarget());
      BuildRule libraryRule = resolver.requireRule(libraryTarget);
      return CalculateAbi.of(
          params.getBuildTarget(),
          ruleFinder,
          params,
          Preconditions.checkNotNull(libraryRule.getSourcePathToOutput()));
    }
    Optional<DummyRDotJava> dummyRDotJava = graphEnhancer.getBuildableForAndroidResources(
        resolver,
        /* createBuildableIfEmpty */ hasDummyRDotJavaFlavor);

    if (hasDummyRDotJavaFlavor) {
      return dummyRDotJava.get();
    } else {
      ImmutableSet<Either<SourcePath, Path>> additionalClasspathEntries = ImmutableSet.of();
      if (dummyRDotJava.isPresent()) {
        additionalClasspathEntries = ImmutableSet.of(
            Either.ofLeft(dummyRDotJava.get().getSourcePathToOutput()));
        ImmutableSortedSet<BuildRule> newDeclaredDeps = ImmutableSortedSet.<BuildRule>naturalOrder()
            .addAll(params.getDeclaredDeps().get())
            .add(dummyRDotJava.get())
            .build();
        params = params.copyReplacingDeclaredAndExtraDeps(
            Suppliers.ofInstance(newDeclaredDeps),
            params.getExtraDeps());
      }

      AndroidLibraryCompiler compiler =
          compilerFactory.getCompiler(args.language.orElse(JvmLanguage.JAVA));

      ImmutableSortedSet<BuildRule> exportedDeps = resolver.getAllRules(args.exportedDeps);

      ImmutableSortedSet.Builder<BuildRule> declaredDepsBuilder =
          ImmutableSortedSet.<BuildRule>naturalOrder()
              .addAll(params.getDeclaredDeps().get())
              .addAll(queriedDeps)
              .addAll(compiler.getDeclaredDeps(args, resolver));

      ImmutableSortedSet<BuildRule> declaredDeps = declaredDepsBuilder.build();

      ImmutableSortedSet<BuildRule> extraDeps =
          ImmutableSortedSet.<BuildRule>naturalOrder()
              .addAll(params.getExtraDeps().get())
              .addAll(BuildRules.getExportedRules(
                  Iterables.concat(
                      declaredDeps,
                      exportedDeps,
                      resolver.getAllRules(args.providedDeps))))
              .addAll(ruleFinder.filterBuildRuleInputs(javacOptions.getInputs(ruleFinder)))
              .addAll(compiler.getExtraDeps(args, resolver))
              .build();

      BuildRuleParams androidLibraryParams =
          params.copyReplacingDeclaredAndExtraDeps(
              Suppliers.ofInstance(declaredDeps),
              Suppliers.ofInstance(extraDeps));
      return AndroidLibrary.builder(
          androidLibraryParams,
          resolver,
          compiler.compileToJar(args, javacOptions, resolver),
          suggestDependencies,
          javacOptions)
          .setArgs(args)
          .setAdditionalClasspathEntries(additionalClasspathEntries)
          .setTrackClassUsage(compiler.trackClassUsage(javacOptions))
          .setTests(args.tests)
          .build();
    }
  }

  @Override
  public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
    return flavors.isEmpty() ||
        flavors.equals(ImmutableSet.of(JavaLibrary.SRC_JAR)) ||
        flavors.equals(ImmutableSet.of(DUMMY_R_DOT_JAVA_FLAVOR));
  }

  @Override
  public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      Arg constructorArg) {
    return compilerFactory.getCompiler(constructorArg.language.orElse(JvmLanguage.JAVA))
        .findDepsForTargetFromConstructorArgs(buildTarget, cellRoots, constructorArg);
  }

  @SuppressFieldNotInitialized
  public static class Arg extends JavaLibraryDescription.Arg {
    public Optional<SourcePath> manifest;
    public Optional<String> resourceUnionPackage;
    public Optional<String> finalRName;
    public Optional<JvmLanguage> language;
    public Optional<Query> depsQuery;
  }
}


text:
package com.xgqfrms.dao.impl;

import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;

import com.xgqfrms.dao.IuserDao;
import com.xgqfrms.vo.User;

public class UserDaoImpl implements IuserDao {
	private Connection conn = null;
	private PreparedStatement pstmt = null;

	public UserDaoImpl(Connection conn) {
		this.conn = conn;
	}

	public boolean findLogin(User user) throws Exception {
		boolean flag = false;
		try {
			String sql = "SELECT name FROM user WHERE userid=? AND password=?";
			this.pstmt = this.conn.prepareStatement(sql);
			this.pstmt.setString(1, user.getUserid());
			this.pstmt.setString(2, user.getPassword());
			ResultSet rs = this.pstmt.executeQuery();

			if (rs.next()) {
				user.setUsername(rs.getString(1)); // 取出一个用户的真实姓名
				flag = true;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (this.pstmt != null) {
				try {
					this.pstmt.close();
				} catch (Exception e) {
					throw e;
				}
			}
		}

		return flag;
	}
}


text:
import { SET_DRAGGING_DATA, CLEAR_DRAGGING_DATA } from '../actions'

const initialState = {}

function dragStore(state = initialState, action) {
    switch (action.type) {
        case SET_DRAGGING_DATA:
            return Object.assign({}, action.payload)
        case CLEAR_DRAGGING_DATA:
            return {}
        default:
            return state
    }
}

export default dragStore


text:
CC=python
MAKE=make
FLAKES=pyflakes

.PHONY: clean

# Remove all the compiled files
clean:
	@echo "Cleaning..."
	find . -name "*.pyc" | xargs rm -rf

help:
	@echo "*** Help ***"
	@echo "#> make [all] - compile all files"
	@echo "#> make clean - remove all .pyc files"


text:
#ifndef IBEHAVIOUR_H
#define	IBEHAVIOUR_H

#include <memory>

#include <Engine/NonCopyable.hpp>
#include <Engine/Window.hpp>
#include <Engine/ResourceManager.hpp>
#include <Engine/EventDispatcher.hpp>

namespace Engine
{
	class GameObject;

	namespace Behaviour
	{
		class IBehaviour : private NonCopyable
		{
		public:
			/**
			 * Constructor.
			 *
			 * @param window Shared pointer to the window.
			 * @param resourceManager Shared pointer to the resource manager.
			 * @param sceneEventDispatcher Shared pointer to the scene's Event
			 * Dispatcher.
			 * @param gameObjectEventDispatcher Shared pointer to the Game
			 * Object's Event Dispatcher.
			 * @param gameObject Weak pointer to the Game Object that the
			 * behaviour is attached to.
			 */
			IBehaviour(std::shared_ptr<Window> window,
				std::shared_ptr<ResourceManager> resourceManager,
				std::shared_ptr<EventDispatcher> sceneEventDispatcher,
				std::shared_ptr<EventDispatcher> gameObjectEventDispatcher,
				std::weak_ptr<GameObject> gameObject);

			/**
			 * Destructor.
			 */
			virtual ~IBehaviour();

			/**
			 * Implement this method to perform actions at regular intervals.
			 *
			 * @param deltaTime Time since last call (in seconds).
			 */
			virtual void Update(double deltaTime) = 0;

		protected:
			/**
			 * Returns a shared pointer to the main game window.
			 *
			 * @return Shared pointer to the window.
			 */
			std::shared_ptr<Window> GetWindow() const;

			/**
			 * Returns a shared pointer to the resource manager.
			 *
			 * @return Shared pointer to the resource manager.
			 */
			std::shared_ptr<ResourceManager> GetResourceManager() const;

			/**
			 * Returns a shared pointer to the scene's event dispatcher.
			 *
			 * @return Shared pointer to the scene's event dispatcher.
			 */
			std::shared_ptr<EventDispatcher> GetSceneEventDispatcher() const;

			 /**
			  * Returns a shared pointer to the game object's event dispatcher.
			  *
			  * @return Shared pointer to the game object's event dispatcher.
			  */
			std::shared_ptr<EventDispatcher> GetGameObjectEventDispatcher() const;

			/**
			 * Returns a weak pointer to the game object that the behaviour is
			 * attached to.
			 *
			 * @return Weak pointer to the game object.
			 */
			std::weak_ptr<GameObject> GetGameObject() const;

		private:
			/**
			 * Shared pointer to the window.
			 */
			std::shared_ptr<Window> m_window;

			/**
			 * Shared pointer to the resource manager.
			 */
			std::shared_ptr<ResourceManager> m_resourceManager;

			/**
			 * Shared pointer to the event dispatcher for the scene that the
			 * Game Object belongs to.
			 */
			std::shared_ptr<EventDispatcher> m_sceneEventDispatcher;

			/**
			 * Shared pointer to the event dispatcher for the Game Object
			 */
			std::shared_ptr<EventDispatcher> m_gameObjectEventDispatcher;

			/**
			 * Weak pointer to the game object that the behaviour is attached
			 * to.
			 */
			std::weak_ptr<GameObject> m_gameObject;
		};
	}
}

#endif


text:
unsigned int GetNextWorkRequired(const CBlockIndex* pindexPrev, const CBlockHeader *pblock, const Consensus::Params& params)
{
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Genesis block
    if (!pindexPrev)
        return nProofOfWorkLimit;

    // Only change once per difficulty adjustment interval
    uint32_t nHeight = pindexPrev->nHeight + 1;
    if (nHeight % params.DifficultyAdjustmentInterval() == 0) {
        // Go back by what we want to be 14 days worth of blocks
        assert(nHeight >= params.DifficultyAdjustmentInterval());
        uint32_t nHeightFirst = nHeight - params.DifficultyAdjustmentInterval();
        const CBlockIndex *pindexFirst = pindexPrev->GetAncestor(nHeightFirst);
        assert(pindexFirst);

        return CalculateNextWorkRequired(pindexPrev, pindexFirst->GetBlockTime(), params);
    }

    if (params.fPowAllowMinDifficultyBlocks) {
        // Special difficulty rule for testnet:
        // If the new block's timestamp is more than 2* 10 minutes then allow
        // mining of a min-difficulty block.
        if (pblock->GetBlockTime() > pindexPrev->GetBlockTime() + 2 * params.nPowTargetSpacing) {
            return nProofOfWorkLimit;
        }

        // Return the last non-special-min-difficulty-rules-block
        const CBlockIndex *pindex = pindexPrev;
        while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) {
            pindex = pindex->pprev;
        }

        return pindex->nBits;
    }

    // We can't go below the minimum, so early exit.
    uint32_t nBits = pindexPrev->nBits;
    if (nBits == nProofOfWorkLimit)
        return nProofOfWorkLimit;

    if (Application::uahfChainState() == Application::UAHFDisabled)
        return nBits;

    // If producing the last 6 block took less than 12h, we keep the same
    // difficulty.
    const CBlockIndex *pindex6 = pindexPrev->GetAncestor(nHeight - 7);
    assert(pindex6);
    int64_t mtp6blocks = pindexPrev->GetMedianTimePast() - pindex6->GetMedianTimePast();
    if (mtp6blocks < 12 * 3600)
        return nBits;

    // If producing the last 6 block took more than 12h, increase the difficulty
    // target by 1/4 (which reduces the difficulty by 20%). This ensure the
    // chain does not get stuck in case we lose hashrate abruptly.
    arith_uint256 nPow;
    nPow.SetCompact(nBits);
    nPow += (nPow >> 2);

    // Make sure we do not go below allowed values.
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    if (nPow > bnPowLimit)
        nPow = bnPowLimit;

    return nPow.GetCompact();
}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    LogPrintf("  nActualTimespan = %d  before bounds\n", nActualTimespan);
    if (nActualTimespan < params.nPowTargetTimespan/4)
        nActualTimespan = params.nPowTargetTimespan/4;
    if (nActualTimespan > params.nPowTargetTimespan*4)
        nActualTimespan = params.nPowTargetTimespan*4;

    // Retarget
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    arith_uint256 bnNew;
    arith_uint256 bnOld;
    bnNew.SetCompact(pindexLast->nBits);
    bnOld = bnNew;
    bnNew *= nActualTimespan;
    bnNew /= params.nPowTargetTimespan;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    /// debug print
    LogPrintf("GetNextWorkRequired RETARGET\n");
    LogPrintf("params.nPowTargetTimespan = %d    nActualTimespan = %d\n", params.nPowTargetTimespan, nActualTimespan);
    LogPrintf("Before: %08x  %s\n", pindexLast->nBits, bnOld.ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.ToString());

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return error("CheckProofOfWork(): nBits below minimum work");

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return error("CheckProofOfWork(): hash doesn't match nBits");

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}


text:
require "#{File.dirname(__FILE__)}/spec_helper"

class MyQueue < Jober::Queue
  def initialize(*args)
    super
    @counter = 0
  end

  attr_reader :counter

  def perform(x)
    @counter += x
  end
end

class MyQueueR2 < Jober::Queue
  def initialize(*args)
    super
    @counter = 0
  end

  attr_reader :counter

  def perform(x)
    @counter += x
    retry_event if @counter < 10
  end
end

class MyQueueR3 < Jober::Queue
  def initialize(*args)
    super
    @counter = 0
  end

  attr_reader :counter

  def perform(x)
    @counter += x
    retry_event_later if @counter < 10
  end
end

class Jasdfoadsfjaf < Jober::Queue
  set_queue_name 'human_name'

  def perform
  end
end

describe "Queue" do
  it "should set internals" do
    w = MyQueue.new
    w.queue_name.should == 'Jober::queue:my'
  end

  it "should execute" do
    MyQueue.enqueue(1)
    MyQueue.enqueue(2)
    MyQueue.enqueue(3)
    MyQueue.new.execute.counter.should == 6
  end

  it "should register class" do
    Jober.classes.should include(MyQueue)
  end

  it "custom queue name" do
    10.times { Jasdfoadsfjaf.enqueue }
    Jober.llens['human_name'].should == 10
  end

  it "retry_event" do
    MyQueueR2.enqueue(1)
    MyQueueR2.new.execute.counter.should == 10
  end

  it "retry_event_later" do
    MyQueueR3.enqueue(1)
    MyQueueR3.new.execute.counter.should == 10
  end

end


text:
<?php
use SwaggerGen\GenerateModels;
use SwaggerGen\GenerateRequests;

require __DIR__.'/vendor/autoload.php';

$namespace = "SturentsLib\\Api";
$dir = "src/";
$yaml = __DIR__.'/swagger/api.yml';
$uri = "/api";

shell_exec("find ./{$dir}/Models -type f -delete");
shell_exec("find ./{$dir}/Requests -type f -delete");

$generate_models = new GenerateModels($namespace);
$count = $generate_models->runFull($yaml, $dir);

echo "Generated $count files in $dir\n";

$generate_requests = new GenerateRequests($namespace);
$count = $generate_requests->runFull($yaml, $dir);

echo "Generated $count files in $dir\n";


text:
namespace Egg { namespace Mesh
{
	class Geometry;

	class GeometryLoader
	{
		static std::shared_ptr<Mesh::Geometry> createGeometryFromMemory(ID3D11Device* device, BYTE* data, unsigned int nBytes);

	public:
		static std::shared_ptr<Mesh::Geometry> createGeometryFromFile(ID3D11Device* device, const char* filename);
	};

}} // namespace Egg::Mesh