text:
namespace content {

class RendererPpapiHost;

class PepperFileSystemHost :
    public ppapi::host::ResourceHost,
    public base::SupportsWeakPtr<PepperFileSystemHost> {
 public:
  PepperFileSystemHost(RendererPpapiHost* host,
                       PP_Instance instance,
                       PP_Resource resource,
                       PP_FileSystemType type);
  virtual ~PepperFileSystemHost();

  // ppapi::host::ResourceHost override.
  virtual int32_t OnResourceMessageReceived(
      const IPC::Message& msg,
      ppapi::host::HostMessageContext* context) OVERRIDE;
  virtual PepperFileSystemHost* AsPepperFileSystemHost() OVERRIDE;

  // Supports FileRefs direct access on the host side.
  PP_FileSystemType GetType() const { return type_; }
  bool IsOpened() const { return opened_; }
  GURL GetRootUrl() const { return root_url_; }

 private:
  // Callback for OpenFileSystem.
  void DidOpenFileSystem(const std::string& name_unused, const GURL& root);
  void DidFailOpenFileSystem(base::PlatformFileError error);

  int32_t OnHostMsgOpen(ppapi::host::HostMessageContext* context,
                        int64_t expected_size);
  int32_t OnHostMsgInitIsolatedFileSystem(
      ppapi::host::HostMessageContext* context,
      const std::string& fsid);

  RendererPpapiHost* renderer_ppapi_host_;
  ppapi::host::ReplyMessageContext reply_context_;
  base::WeakPtrFactory<PepperFileSystemHost> weak_factory_;

  PP_FileSystemType type_;
  bool opened_;  // whether open is successful.
  GURL root_url_;
  bool called_open_;  // whether open has been called.

  DISALLOW_COPY_AND_ASSIGN(PepperFileSystemHost);
};

}  // namespace content

#endif  // CONTENT_RENDERER_PEPPER_PEPPER_FILE_SYSTEM_HOST_H_


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Beep::Sound do
  it "should be able to call the default beep command without arguments" do
    Beep::Sound.should_receive(:system).with('beep')
    Beep::Sound.generate
  end
  it "should allow a beep to be generated with a given frequency" do
    Beep::Sound.should_receive(:system).with('beep -f 100')
    Beep::Sound.generate([{:frequency => 100}])
  end
  it "should allow a beep to be generated with a given duration in milliseconds" do
    Beep::Sound.should_receive(:system).with('beep -l 1000')
    Beep::Sound.generate([{:duration => 1000}])
  end
  it "should allow a beep to be generated with a given pause after the beep" do
    Beep::Sound.should_receive(:system).with('beep -D 1000')
    Beep::Sound.generate([{:pause => 1000}])
  end
  it "should be able to handle multiple beeps with a single command" do
    sounds = [
      {:frequency => 100, :duration => 200, :pause => 300},
      {:frequency => 400, :duration => 500, :pause => 600},
      {:frequency => 700, :duration => 800, :pause => 900},
    ]
    Beep::Sound.should_receive(:system).with('beep -f 100 -l 200 -D 300 -n -f 400 -l 500 -D 600 -n -f 700 -l 800 -D 900')
    Beep::Sound.generate(sounds)
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace spec\LdapTools\Event;

use PhpSpec\ObjectBehavior;

class LdapObjectCreationEventSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('foo');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Event\LdapObjectCreationEvent');
    }

    function it_should_have_type_Event()
    {
        $this->shouldHaveType('LdapTools\Event\Event');
    }

    function it_should_implement_EventInterface()
    {
        $this->shouldImplement('LdapTools\Event\EventInterface');
    }

    function it_should_get_the_event_name()
    {
        $this->getName()->shouldBeEqualTo('foo');
    }

    function it_should_set_data()
    {
        $data = ['foo'];
        $this->setData($data);
        $this->getData()->shouldBeEqualTo($data);
    }

    function it_should_set_the_container()
    {
        $container = 'dc=foo,dc=bar';
        $this->setContainer($container);
        $this->getContainer()->shouldBeEqualTo($container);
    }

    function it_should_set_the_dn()
    {
        $dn = 'cn=foobar,dc=foo,dc=bar';
        $this->setDn($dn);
        $this->getDn()->shouldBeEqualTo($dn);
    }

    function it_should_get_the_type()
    {
        $this->beConstructedWith('foo', 'bar');
        $this->getType()->shouldBeEqualTo('bar');
    }
}


text:
module Maestrano::Connector::Rails
  class AllSynchronizationsJob < ::ActiveJob::Base
    queue_as :default

    # Trigger synchronization of all active organizations
    def perform(name = nil, count = nil)
      Maestrano::Connector::Rails::Organization
        .where.not(oauth_provider: nil, encrypted_oauth_token: nil)
        .where(sync_enabled: true)
        .select(:id)
        .find_each do |organization|
        Maestrano::Connector::Rails::SynchronizationJob.set(wait: rand(3600)).perform_later(organization.id, {})
      end
    end
  end
end


text:
ActiveRecord::Schema.define(:version => 20111213010047) do

  create_table "asset_locations", :force => true do |t|
    t.string   "description"
    t.string   "rfid_tag"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "asset_tags", :force => true do |t|
    t.string   "uuid"
    t.string   "asset_type"
    t.string   "asset_id"
    t.string   "asset_location_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "books", :force => true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class GoPrimitiveDot extends React.Component<IconBaseProps> { }


text:
package com.scorpiac.javarant;

public enum Sort {
    ALGO,
    RECENT,
    TOP;

    @Override
    public String toString() {
        return name().toLowerCase();
    }
}


text:
<?php

final class PhutilConsoleList extends PhutilConsoleView {

  private $items = array();
  private $wrap = true;

  public function addItem($item) {
    $this->items[] = $item;
    return $this;
  }

  public function addItems(array $items) {
    foreach ($items as $item) {
      $this->addItem($item);
    }
    return $this;
  }

  public function getItems() {
    return $this->items;
  }

  public function setWrap($wrap) {
    $this->wrap = $wrap;
    return $this;
  }

  protected function drawView() {
    $output = array();
    foreach ($this->getItems() as $item) {
      if ($this->wrap) {
        $item = phutil_console_wrap($item, 8);
      }
      $item = '      - '.$item;
      $output[] = $item;
    }

    return $this->drawLines($output);
  }

}


text:
from corepy.spre.spe import InstructionOperand, Label
from corepy.arch.x86_64.lib.memory import MemoryReference
#import corepy.arch.x86_64.types.registers as regs

# ------------------------------
# x86 Operands
# ------------------------------

class x86InstructionOperand(InstructionOperand):
  def __eq__(self, other):
    return type(self) == type(other)

class FixedRegisterOperand(x86InstructionOperand):
  def __init__(self, name, gp_equiv, gp_reg):
    self.gp_equiv = gp_equiv
    self.gp_reg = gp_reg
    x86InstructionOperand.__init__(self, name)
    return

  def __eq__(self, other):
    # Fixed registers (ie 'eax') are equivalent to themselves, but are also
    # equivalent to x86RegisterOperands of the same gp_equiv type.
    if isinstance(other, FixedRegisterOperand):
      return self.name == other.name and self.gp_equiv == other.gp_equiv
    elif isinstance(other, x86RegisterOperand):
      return self.gp_equiv == other.gp_equiv
    return False

  def check(self, value):
    return isinstance(value, self.gp_equiv) and self.name == value.name

  def render(value):
    raise Exception('Fixed register (e.g., ax, al, eax) operands cannot be rendered')

class x86ConstantOperand(x86InstructionOperand):
  def __init__(self, name, const):
    self.const = const
    x86InstructionOperand.__init__(self, name)
    return

  def check(self, value):
    return type(self.const) == type(value) and self.const == value

  def __eq__(self, other):
    return (type(self) == type(other) and self.const == other.const) or (isinstance(other, x86ImmediateOperand) and other.fits(self.const))

class x86ImmediateOperand(x86InstructionOperand):
  def __init__(self, name, range):
    self.range = range
    x86InstructionOperand.__init__(self, name)
    return

  # This so instances with different names can be created, i.e. reg8_t('rd')
  def __call__(self, name):
    return self.__class__(name, self.range)

  def check(self, value):
    return self.fits(value)

  def fits(self, value):
    return isinstance(value, (int, long)) and (self.range[0] <= value and value < self.range[1])

  def __eq__(self, other):
    # Carefully written so that an immediate with a larger range is equal.
    return isinstance(other, x86ImmediateOperand) and self.range[0] >= other.range[0] and self.range[1] <= other.range[1]

class x86LabelOperand(x86InstructionOperand):
  relative_op = True

  def __init__(self, name, range):
    x86InstructionOperand.__init__(self, name)
    self.range = range
    return

  def check(self, value):
    return self.fits(value)

  def fits(self, value):
    return isinstance(value, Label)

class x86RegisterOperand(x86InstructionOperand):
  def __init__(self, name, gp_equiv):
    self.gp_equiv = gp_equiv
    x86InstructionOperand.__init__(self, name)
    return

  # This so instances with different names can be created, i.e. reg8_t('rd')
  def __call__(self, name):
    return self.__class__(name, self.gp_equiv)

  def __eq__(self, other):
    return type(self) == type(other) and self.gp_equiv == other.gp_equiv

  def check(self, value):
    return isinstance(value, self.gp_equiv)

class x86MemoryOperand(x86InstructionOperand):
  def __init__(self, name, size):
    self.size = size
    x86InstructionOperand.__init__(self, name)
    return

  def __eq__(self, other):
    return type(self) == type(other) and self.size == other.size

  def check(self, value):
    # Careful to support 'mem' operand with no size
    if isinstance(value, MemoryReference):
      return self.size == value.data_size
    return False

class x86PrefixOperand(x86InstructionOperand):
  def __init__(self, name, value):
    self.value = value
    x86InstructionOperand.__init__(self, name)

  def check(self, value):
    return True

# Immediate values

class Rel8off(x86ImmediateOperand):
  relative_op = True

class Rel32off(x86ImmediateOperand):
  relative_op = True

class Imm8(x86ImmediateOperand): pass
class Imm16(x86ImmediateOperand): pass
class Imm32(x86ImmediateOperand): pass
class Imm64(x86ImmediateOperand): pass


text:
package ws.wamp.jawampa.transport.netty;

import java.util.List;

import ws.wamp.jawampa.WampMessages.WampMessage;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import ws.wamp.jawampa.WampSerialization;

public class WampDeserializationHandler extends MessageToMessageDecoder<WebSocketFrame> {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(WampDeserializationHandler.class);

    enum ReadState {
        Closed,
        Reading,
        Error
    }

    ReadState readState = ReadState.Closed;

    final WampSerialization serialization;

    public WampSerialization serialization() {
        return serialization;
    }

    public WampDeserializationHandler(WampSerialization serialization) {
        this.serialization = serialization;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        readState = ReadState.Reading;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        readState = ReadState.Reading;
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        readState = ReadState.Closed;
        ctx.fireChannelInactive();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out)
        throws Exception
    {
        if (readState != ReadState.Reading) return;

        ObjectMapper objectMapper = serialization.getObjectMapper();
        if (frame instanceof TextWebSocketFrame) {
            // Only want Text frames when text subprotocol
            if (!serialization.isText())
                throw new IllegalStateException("Received unexpected TextFrame");

            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;

            // If we receive an invalid frame on of the following functions will throw
            // This will lead Netty to closing the connection
            ArrayNode arr = objectMapper.readValue(
                    new ByteBufInputStream(textFrame.content()), ArrayNode.class);

            if (logger.isDebugEnabled()) {
                logger.debug("Deserialized Wamp Message: {}", arr.toString());
            }

            WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
            out.add(recvdMessage);
        } else if (frame instanceof BinaryWebSocketFrame) {
            // Only want Binary frames when binary subprotocol
            if (serialization.isText())
                throw new IllegalStateException("Received unexpected BinaryFrame");

            BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;

            // If we receive an invalid frame on of the following functions will throw
            // This will lead Netty to closing the connection
            ArrayNode arr = objectMapper.readValue(
                    new ByteBufInputStream(binaryFrame.content()), ArrayNode.class);

            if (logger.isDebugEnabled()) {
                logger.debug("Deserialized Wamp Message: {}", arr.toString());
            }

            WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
            out.add(recvdMessage);
        } else if (frame instanceof PongWebSocketFrame) {
            // System.out.println("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            // System.out.println("WebSocket Client received closing");
            readState = ReadState.Closed;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // We caught an exception.
        // Most probably because we received an invalid message
        readState = ReadState.Error;
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
           .addListener(ChannelFutureListener.CLOSE);
    }
}


text:
import warnings
import os.path as op
import numpy as np

from nose.tools import assert_true, assert_raises
from numpy.testing import assert_array_equal

from mne import io, read_events, Epochs, pick_types
from mne.decoding import Scaler, FilterEstimator
from mne.decoding import PSDEstimator, EpochsVectorizer

warnings.simplefilter('always')  # enable b/c these tests throw warnings

tmin, tmax = -0.2, 0.5
event_id = dict(aud_l=1, vis_l=3)
start, stop = 0, 8

data_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(data_dir, 'test_raw.fif')
event_name = op.join(data_dir, 'test-eve.fif')

def test_scaler():
    """Test methods of Scaler
    """
    raw = io.Raw(raw_fname, preload=False)
    events = read_events(event_name)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[1:13:3]

    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), preload=True)
    epochs_data = epochs.get_data()
    scaler = Scaler(epochs.info)
    y = epochs.events[:, -1]

    # np invalid divide value warnings
    with warnings.catch_warnings(record=True):
        X = scaler.fit_transform(epochs_data, y)
        assert_true(X.shape == epochs_data.shape)
        X2 = scaler.fit(epochs_data, y).transform(epochs_data)

    assert_array_equal(X2, X)

    # Test inverse_transform
    with warnings.catch_warnings(record=True):  # invalid value in mult
        Xi = scaler.inverse_transform(X, y)
    assert_array_equal(epochs_data, Xi)

    # Test init exception
    assert_raises(ValueError, scaler.fit, epochs, y)
    assert_raises(ValueError, scaler.transform, epochs, y)

def test_filterestimator():
    """Test methods of FilterEstimator
    """
    raw = io.Raw(raw_fname, preload=False)
    events = read_events(event_name)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[1:13:3]
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), preload=True)
    epochs_data = epochs.get_data()

    # Add tests for different combinations of l_freq and h_freq
    filt = FilterEstimator(epochs.info, l_freq=1, h_freq=40)
    y = epochs.events[:, -1]
    with warnings.catch_warnings(record=True):  # stop freq attenuation warning
        X = filt.fit_transform(epochs_data, y)
        assert_true(X.shape == epochs_data.shape)
        assert_array_equal(filt.fit(epochs_data, y).transform(epochs_data), X)

    filt = FilterEstimator(epochs.info, l_freq=0, h_freq=40)
    y = epochs.events[:, -1]
    with warnings.catch_warnings(record=True):  # stop freq attenuation warning
        X = filt.fit_transform(epochs_data, y)

    filt = FilterEstimator(epochs.info, l_freq=1, h_freq=1)
    y = epochs.events[:, -1]
    with warnings.catch_warnings(record=True):  # stop freq attenuation warning
        assert_raises(ValueError, filt.fit_transform, epochs_data, y)

    filt = FilterEstimator(epochs.info, l_freq=1, h_freq=None)
    with warnings.catch_warnings(record=True):  # stop freq attenuation warning
        X = filt.fit_transform(epochs_data, y)

    # Test init exception
    assert_raises(ValueError, filt.fit, epochs, y)
    assert_raises(ValueError, filt.transform, epochs, y)

def test_psdestimator():
    """Test methods of PSDEstimator
    """
    raw = io.Raw(raw_fname, preload=False)
    events = read_events(event_name)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[1:13:3]
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), preload=True)
    epochs_data = epochs.get_data()
    psd = PSDEstimator(2 * np.pi, 0, np.inf)
    y = epochs.events[:, -1]
    X = psd.fit_transform(epochs_data, y)

    assert_true(X.shape[0] == epochs_data.shape[0])
    assert_array_equal(psd.fit(epochs_data, y).transform(epochs_data), X)

    # Test init exception
    assert_raises(ValueError, psd.fit, epochs, y)
    assert_raises(ValueError, psd.transform, epochs, y)

def test_epochs_vectorizer():
    """Test methods of EpochsVectorizer
    """
    raw = io.Raw(raw_fname, preload=False)
    events = read_events(event_name)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[1:13:3]
    with warnings.catch_warnings(record=True):
        epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                        baseline=(None, 0), preload=True)
    epochs_data = epochs.get_data()
    vector = EpochsVectorizer(epochs.info)
    y = epochs.events[:, -1]
    X = vector.fit_transform(epochs_data, y)

    # Check data dimensions
    assert_true(X.shape[0] == epochs_data.shape[0])
    assert_true(X.shape[1] == epochs_data.shape[1] * epochs_data.shape[2])

    assert_array_equal(vector.fit(epochs_data, y).transform(epochs_data), X)

    # Check if data is preserved
    n_times = epochs_data.shape[2]
    assert_array_equal(epochs_data[0, 0, 0:n_times], X[0, 0:n_times])

    # Check inverse transform
    Xi = vector.inverse_transform(X, y)
    assert_true(Xi.shape[0] == epochs_data.shape[0])
    assert_true(Xi.shape[1] == epochs_data.shape[1])
    assert_array_equal(epochs_data[0, 0, 0:n_times], Xi[0, 0, 0:n_times])

    # check if inverse transform works with different number of epochs
    Xi = vector.inverse_transform(epochs_data[0], y)
    assert_true(Xi.shape[1] == epochs_data.shape[1])
    assert_true(Xi.shape[2] == epochs_data.shape[2])

    # Test init exception
    assert_raises(ValueError, vector.fit, epochs, y)
    assert_raises(ValueError, vector.transform, epochs, y)


text:
/* eslint-env mocha */
import App, { Reaction } from './'

import assert from 'assert'
import { state } from './tags'

describe('Reaction', () => {
  it('should watch state', () => {
    let grabbedValue = 0
    const foo = Reaction(
      {
        foo: state`foo`,
      },
      ({ foo }) => {
        grabbedValue = foo
      }
    )
    const app = {
      reactions: {
        foo,
      },
      state: {
        foo: 'bar',
      },
      sequences: {
        changeFoo: ({ store }) => store.set(state`foo`, 'bar2'),
      },
    }
    const controller = App(app)
    controller.getSequence('changeFoo')()
    assert.strictEqual(grabbedValue, 'bar2')
  })
  it('should grab state dynamically', () => {
    let grabbedValue = null
    const foo = Reaction(
      {
        foo: state`foo`,
      },
      ({ foo, get }) => {
        grabbedValue = foo + get(state`bar`)
      }
    )
    const app = {
      reactions: {
        foo,
      },
      state: {
        foo: 'bar',
        bar: 'baz',
      },
      sequences: {
        changeFoo: ({ store }) => store.set(state`foo`, 'bar2'),
      },
    }
    const controller = App(app)
    controller.getSequence('changeFoo')()
    assert.strictEqual(grabbedValue, 'bar2baz')
  })
})


text:
<?php

namespace IPS\Http;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * URL Class
 *
 * This class represents a URL using the RFC 3986 definition of a URI (i.e. that
 * RFC is used, but objects of this class can only represent URLs, not URIs which
 * are not URLs or URNs) with the extra provision that we allow protocol-relative URLs
 *
 * @see	RFC 3986
 */
class _Url
{
	const PROTOCOL_AUTOMATIC = 0;
	const PROTOCOL_HTTPS = 1;
	const PROTOCOL_HTTP = 2;
	const PROTOCOL_RELATIVE = 3;

	const COMPONENT_SCHEME = 'scheme';
	const COMPONENT_USERNAME = 'user';
	const COMPONENT_PASSWORD = 'pass';
	const COMPONENT_HOST = 'host';
	const COMPONENT_PORT = 'port';
	const COMPONENT_PATH = 'path';
	const COMPONENT_QUERY = 'query';
	const COMPONENT_QUERY_KEY = 'queryKey';
	const COMPONENT_QUERY_VALUE = 'queryValue';
	const COMPONENT_FRAGMENT = 'fragment';

	/* !Factory Methods */

	/**
	 * Build Internal URL
	 *
	 * @param	string			$queryString	The query string
	 * @param	string|null		$base			Key for the URL base. If NULL, defaults to current controller location
	 * @param	string			$seoTemplate	The key for making this a friendly URL
	 * @param	string|array	$seoTitles		The title(s) needed for the friendly URL
	 * @param	int				$protocol		Protocol (one of the PROTOCOL_* constants)
	 * @return	\IPS\Http\Url\Internal
	 */
	public static function internal( $queryString, $base=NULL, $seoTemplate=NULL, $seoTitles=array(), $protocol = 0 )
	{
		/* If we don't have a base, assume the template location */
		if ( !$base )
		{
			if ( \IPS\Dispatcher::hasInstance() )
			{
				if ( \IPS\Dispatcher::i()->controllerLocation === 'setup' )
				{
					return new static( ( \IPS\Request::i()->isSecure()  ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . ( $_SERVER['QUERY_STRING'] ? rtrim( mb_substr( $_SERVER['REQUEST_URI'], 0, -mb_strlen( $_SERVER['QUERY_STRING'] ) ), '?' ) : $_SERVER['REQUEST_URI'] ) . '?' . $queryString );
				}
				else
				{
					$base = \IPS\Dispatcher::i()->controllerLocation;
				}
			}
			else
			{
				$base = 'front';
			}
		}

		/* Front-End Friendly */
		if ( $base === 'front' and $seoTemplate and \IPS\Settings::i()->use_friendly_urls )
		{
			return \IPS\Http\Url\Friendly::friendlyUrlFromQueryString( $queryString, $seoTemplate, $seoTitles, $protocol );
		}
		/* Front-End not friendly */
		elseif ( $base === 'front' )
		{
			return \IPS\Http\Url\Internal::createInternalFromComponents( 'front', $protocol, $queryString ? 'index.php' : '', $queryString );
		}
		/* Admin */
		elseif ( $base === 'admin' )
		{
			/* Front: Never disclose adsess in front pages */
			if ( \IPS\Dispatcher::hasInstance() and \IPS\Dispatcher::i()->controllerLocation !== 'admin' )
			{
				/* If there is a query string (like a link from an error page, pass through the redirector so we don't disclose the location */
				if ( $queryString )
				{
					return \IPS\Http\Url\Internal::createInternalFromComponents( 'front', $protocol, 'index.php', 'app=core&module=system&controller=redirect&do=admin&_data=' . base64_encode( $queryString ) );
				}
				/* Or if it's just a normal link like in the user bar, show that */
				else
				{
					return \IPS\Http\Url\Internal::createInternalFromComponents(
						'admin',
						\IPS\Settings::i()->logins_over_https ? static::PROTOCOL_HTTPS : $protocol,
						\IPS\CP_DIRECTORY . '/'
					);
				}
			}
			/* Within ACP */
			else
			{
				return \IPS\Http\Url\Internal::createInternalFromComponents(
					'admin',
					\IPS\Settings::i()->logins_over_https ? static::PROTOCOL_HTTPS : $protocol,
					\IPS\CP_DIRECTORY . '/',
					array( 'adsess' => session_id() ) + static::convertQueryAsStringToArray( $queryString )
				);
			}
		}
		/* None */
		else
		{
			return static::createFromString( static::baseUrl( $protocol ) . $queryString, FALSE );
		}
	}

	/**
	 * Build External URL
	 *
	 * @param	string			$url
	 * @return	\IPS\Http\Url
	 * @throws	\InvalidArgumentException
	 */
	public static function external( $url )
	{
		return new static( $url, TRUE );
	}

	/**
	 * Build IPS-External URL
	 *
	 * @param	string			$url
	 * @return	\IPS\Http\Url
	 */
	public static function ips( $url )
	{
		return new static( "https://remoteservices.invisionpower.com/{$url}/?version=" . \IPS\Application::getAvailableVersion('core') );
	}

	/**
	 * Create from components - all arguments should be UNENCODED
	 *
	 * @param	string				$host		Host
	 * @param	string|NULL			$scheme		Scheme (NULL for protocol-relative)
	 * @param	string|NULL			$path		Path
	 * @param	string|array|NULL	$query		Query
	 * @param	int|NULL			$port		Port
	 * @param	string|NULL			$username	Username
	 * @param	string|NULL			$password	Password
	 * @param	string|NULL			$fragment	Fragment
	 * @return	\IPS\Http\Url
	 */
	public static function createFromComponents( $host, $scheme = NULL, $path = NULL, $query = NULL, $port = NULL, $username = NULL, $password = NULL, $fragment = NULL )
	{
		$obj = new static('');

		$obj->data[ static::COMPONENT_SCHEME ] = $scheme;
		$obj->data[ static::COMPONENT_HOST ] = $host;
		$obj->data[ static::COMPONENT_PORT ] = $port;
		$obj->data[ static::COMPONENT_USERNAME ] = $username;
		$obj->data[ static::COMPONENT_PASSWORD ] = $password;
		$obj->data[ static::COMPONENT_PATH ] = $path;
		$obj->data[ static::COMPONENT_FRAGMENT ] = $fragment;

		if ( is_array( $query ) )
		{
			$obj->data[ static::COMPONENT_QUERY ] = static::convertQueryAsArrayToString( $query );
			$obj->queryString = $query;
		}
		elseif ( is_string( $query ) )
		{
			$obj->data[ static::COMPONENT_QUERY ] = $query;
			$obj->queryString = static::convertQueryAsStringToArray( $query );
		}

		$obj->reconstructUrlFromData();

		return $obj;
	}

	/**
	 * Create from string
	 * This method is somewhat performance-intensive and should only be used either for creating friendly URLs, or if it is not known
	 * if the URL will be internal or external. If you know the URL will be external, use new \IPS\Http\Url( ... )
	 *
	 * @param	string	$url				A valid URL as per our definition (see phpDoc on class)
	 * @param	bool	$couldBeFriendly	If the URL is known to not be friendly, FALSE can be passed here to save the performance implication of checking the URL
	 * @param	bool	$autoEncode			If true, any invalid components will be automatically encoded rather than an exception thrown - useful if the entire link is user-provided
	 * @return	\IPS\Http\Url
	 * @throws	\IPS\Http\Url\Exception
	 */
	public static function createFromString( $url, $couldBeFriendly=TRUE, $autoEncode=FALSE )
	{
		/* Decode it */
		$components = static::componentsFromUrlString( $url, $autoEncode );

		/* Is it internal? */
		$baseUrlComponents = static::componentsFromUrlString( static::baseUrl() );
		if ( $components[ static::COMPONENT_HOST ] === $baseUrlComponents[ static::COMPONENT_HOST ] and
			$components[ static::COMPONENT_USERNAME ] === $baseUrlComponents[ static::COMPONENT_USERNAME ] and
			$components[ static::COMPONENT_PASSWORD ] === $baseUrlComponents[ static::COMPONENT_PASSWORD ] and
			$components[ static::COMPONENT_PORT ] === $baseUrlComponents[ static::COMPONENT_PORT ] and
			mb_substr( $components[ static::COMPONENT_PATH ], 0, mb_strlen( $baseUrlComponents[ static::COMPONENT_PATH ] ) ) === $baseUrlComponents[ static::COMPONENT_PATH ]
		)
		{
			$pathFromBaseUrl = mb_substr( $components[ static::COMPONENT_PATH ], mb_strlen( $baseUrlComponents[ static::COMPONENT_PATH ] ) );

			/* Admin */
			if ( preg_match( '/^' . preg_quote( \IPS\CP_DIRECTORY, '/' ) . '($|\/)/', $pathFromBaseUrl ) )
			{
				return \IPS\Http\Url\Internal::createInternalFromComponents( 'admin', $components[ static::COMPONENT_SCHEME ], $pathFromBaseUrl, $components[ static::COMPONENT_QUERY ], $components[ static::COMPONENT_FRAGMENT ] );
			}
			/* Front-End: Not friendly or unrewritten friendly */
			elseif ( !$pathFromBaseUrl or $pathFromBaseUrl === 'index.php' )
			{
				$potentialFurl = trim( mb_substr( $components[ static::COMPONENT_QUERY ], 0, mb_strpos( $components[ static::COMPONENT_QUERY ], '&' ) ?: NULL ), '/' );
				if ( $couldBeFriendly and $return = \IPS\Http\Url\Friendly::createFriendlyUrlFromComponents( $components, $potentialFurl ) )
				{
					return $return;
				}
				else
				{
					return \IPS\Http\Url\Internal::createInternalFromComponents( 'front', $components[ static::COMPONENT_SCHEME ], $pathFromBaseUrl, $components[ static::COMPONENT_QUERY ], $components[ static::COMPONENT_FRAGMENT ] );
				}
			}
			/* Front-End: Rewritten friendly */
			elseif ( $couldBeFriendly and $return = \IPS\Http\Url\Friendly::createFriendlyUrlFromComponents( $components, rtrim( mb_substr( $components[ static::COMPONENT_PATH ], mb_strlen( $baseUrlComponents[ static::COMPONENT_PATH ] ) ), '/' ) ) )
			{
				return $return;
			}
			/* Other */
			else
			{
				return \IPS\Http\Url\Internal::createInternalFromComponents( 'none', $components[ static::COMPONENT_SCHEME ], $pathFromBaseUrl, $components[ static::COMPONENT_QUERY ], $components[ static::COMPONENT_FRAGMENT ] );
			}
		}
		/* Nope, external */
		else
		{
			return \IPS\Http\Url::createFromComponents( $components['host'], $components['scheme'], $components['path'], $components['query'], $components['port'], $components['user'], $components['pass'], $components['fragment'] );
		}
	}

	/* !Instance */

	/**
	 * @brief	URL, with all components appropriately encoded
	 */
	protected $url = NULL;

	/**
	 * @brief	All the different components, decoded
	 */
	public $data = array(
		self::COMPONENT_SCHEME => NULL,
		self::COMPONENT_HOST => NULL,
		self::COMPONENT_PORT => NULL,
		self::COMPONENT_USERNAME => NULL,
		self::COMPONENT_PASSWORD => NULL,
		self::COMPONENT_PATH => NULL,
		self::COMPONENT_QUERY => NULL,
		self::COMPONENT_FRAGMENT => NULL,
	);

	/**
	 * @brief	Query string as decoded array
	 */
	public $queryString = array();

	/**
	 * Constructor
	 *
	 * @param	string|NULL	$url		A valid URL as per our definition (see phpDoc on class) or NULL if being called by createFromComponents()
	 * @param	bool		$autoEncode	If true, any invalid components will be automatically encoded rather than an exception thrown - useful if the entire link is user-provided
	 * @return	void
	 * @throws	\IPS\Http\Url\Exception
	 *	@li	INVALID_URL			The URL did not start with // to indicate relative protocol or contain ://
	 *	@li	INVALID_SCHEME		The scheme was invalid
	 *	@li	INVALID_USERNAME	The username was invalid
	 *	@li	INVALID_PASSWORD	The password was invalid
	 *	@LI	INVALID_HOST		The host name was invalid
	 *	@LI	INVALID_PATH		The path was invalid
	 *	@LI	INVALID_QUERY		The query was invalid
	 *	@LI	INVALID_FRAGMENT	The fragment was invalid
	 */
	public function __construct( $url = NULL, $autoEncode = FALSE )
	{
		if ( $url )
		{
			/* Set the URL */
			$this->url = $url;

			/* Set the components */
			$this->data = static::componentsFromUrlString( $url, $autoEncode );
			$this->queryString = static::convertQueryAsStringToArray( $this->data['query'] );
		}
	}

	/**
	 * Adjust scheme
	 *
	 * @param	string|NULL		$scheme	Scheme (NULL for protocol-relative)
	 * @return	\IPS\Http\Url
	 */
	public function setScheme( $scheme )
	{
		$obj = clone $this;
		$obj->data[ static::COMPONENT_SCHEME ] = $scheme;
		$obj->reconstructUrlFromData();
		return $obj;
	}

	/**
	 * Adjust host
	 *
	 * @param	string	$host	Host
	 * @return	\IPS\Http\Url
	 */
	public function setHost( $host )
	{
		$obj = clone $this;
		$obj->data[ static::COMPONENT_HOST ] = $host;
		$obj->reconstructUrlFromData();
		return $obj;
	}

	/**
	 * Adjust path
	 *
	 * @param	string|NULL	$path Path
	 * @return	\IPS\Http\Url
	 */
	public function setPath( $path )
	{
		$obj = clone $this;
		$obj->data[ static::COMPONENT_PATH ] = $path;
		$obj->reconstructUrlFromData();
		return $obj;
	}

	/**
	 * Adjust Query String
	 *
	 * @param	string|array	$keyOrArray	Key, or array of key/value pairs
	 * @param	string|null		$value		Value, or NULL if $key is an array
	 * @return	\IPS\Http\Url
	 */
	public function setQueryString( $keyOrArray, $value=NULL )
	{
		$newQueryArray = $this->queryString;

		if ( is_array( $keyOrArray ) )
		{
			foreach ( $keyOrArray as $k => $v )
			{
				if ( $v === NULL )
				{
					unset( $newQueryArray[ $k ] );
				}
				else
				{
					$newQueryArray[ $k ] = $v;
				}
			}
		}
		else
		{
			if ( $value === NULL )
			{
				unset( $newQueryArray[ $keyOrArray ] );
			}
			else
			{
				$newQueryArray[ $keyOrArray ] = $value;
			}
		}

		$obj = clone $this;
		$obj->data[ static::COMPONENT_QUERY ] = static::convertQueryAsArrayToString( $newQueryArray );
		$obj->queryString = $newQueryArray;
		$obj->reconstructUrlFromData();
		return $obj;
	}

	/**
	 * Reset the $url property after changing data
	 *
	 * @return	void
	 */
	protected function reconstructUrlFromData()
	{
		/* Scheme */
		$scheme = '';
		if ( $this->data[ static::COMPONENT_SCHEME ] )
		{
			$scheme = $this->data[ static::COMPONENT_SCHEME ] . '://';
		}
		else
		{
			$scheme = '//';
		}

		/* Username and password */
		$usernameAndPassword = '';
		if ( $this->data[ static::COMPONENT_USERNAME ] )
		{
			$usernameAndPassword = static::encodeComponent( static::COMPONENT_USERNAME, $this->data[ static::COMPONENT_USERNAME ] );
			if ( $this->data[ static::COMPONENT_PASSWORD ] )
			{
				$usernameAndPassword .= ':' . static::encodeComponent( static::COMPONENT_PASSWORD, $this->data[ static::COMPONENT_PASSWORD ] );
			}
			$usernameAndPassword .= '@';
		}

		/* Host */
		$host = static::encodeComponent( static::COMPONENT_HOST, $this->data[ static::COMPONENT_HOST ] );

		/* Port */
		$port = '';
		if ( $this->data[ static::COMPONENT_PORT ] )
		{
			$port = ':' . intval( $this->data[ static::COMPONENT_PORT ] );
		}

		/* Path */
		$path = '';
		if ( $this->data[ static::COMPONENT_PATH ] )
		{
			$path = '/' . ltrim( static::encodeComponent( static::COMPONENT_PATH, $this->data[ static::COMPONENT_PATH ] ), '/' );
		}

		/* Query String */
		$queryString = '';
		if ( $this->data[ static::COMPONENT_QUERY ] )
		{
			$queryString = '?' . static::convertQueryAsArrayToString( $this->queryString, TRUE );
		}

		/* Fragment */
		$fragment = '';
		if ( $this->data[ static::COMPONENT_FRAGMENT ] )
		{
			$fragment = '#' . static::encodeComponent( static::COMPONENT_FRAGMENT, $this->data[ static::COMPONENT_FRAGMENT ] );
		}

		/* Put it all together */
		$this->url = $scheme . $usernameAndPassword . $host . $port . $path . $queryString . $fragment;
	}

	/**
	 * Strip Query String
	 *
	 * @param	string|array	$keys	The key(s) to strip - if omitted, entire query string is wiped
	 * @return	\IPS\Http\Url
	 */
	public function stripQueryString( $keys=NULL )
	{
		$newQueryArray = array();

		if( $keys !== NULL )
		{
			if( !is_array( $keys ) )
			{
				$keys = array( $keys => $keys );
			}

			$newQueryArray = array_diff_key( $this->queryString, array_combine( array_values( $keys ), array_values( $keys ) ) );
		}

		return static::createFromComponents( $this->data[ static::COMPONENT_HOST ], $this->data[ static::COMPONENT_SCHEME ], $this->data[ static::COMPONENT_PATH ], $newQueryArray, $this->data[ static::COMPONENT_PORT ], $this->data[ static::COMPONENT_USERNAME ], $this->data[ static::COMPONENT_PASSWORD ], $this->data[ static::COMPONENT_FRAGMENT ] );
	}

	/**
	 * Adjust Fragment
	 *
	 * @param	string	$fragment	Fragment
	 * @return	\IPS\Http\Url
	 */
	public function setFragment( $fragment )
	{
		return static::createFromComponents( $this->data[ static::COMPONENT_HOST ], $this->data[ static::COMPONENT_SCHEME ], $this->data[ static::COMPONENT_PATH ], $this->data[ static::COMPONENT_QUERY ], $this->data[ static::COMPONENT_PORT ], $this->data[ static::COMPONENT_USERNAME ], $this->data[ static::COMPONENT_PASSWORD ], $fragment );
	}

	/**
	 * Make safe for ACP
	 *
	 * @param	bool	$resource	If TRUE, will redirect silently
	 * @return	\IPS\Http\Url
	 */
	public function makeSafeForAcp( $resource=FALSE )
	{
		return static::internal( "app=core&module=system&controller=redirect", 'front' )->setQueryString( array(
			'url'		=> (string) $this,
			'key'		=> hash_hmac( "sha256", (string) $this, \IPS\SITE_SECRET_KEY ?: md5( \IPS\Settings::i()->sql_pass . \IPS\Settings::i()->board_url . \IPS\Settings::i()->sql_database ) ),
			'resource'	=> $resource
		) );
	}

	/**
	 * Is this URL pointing to the local server?
	 *
	 * @return	bool
	 */
	public function isLocalhost()
	{
		return ( isset( $this->data['host'] ) and ( in_array( $this->data['host'], array( 'localhost', static::internal('')->data['host'] ) )  or ( filter_var( $this->data['host'], FILTER_VALIDATE_IP ) and filter_var( $this->data['host'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === FALSE ) ) );
	}

	/**
	 * Make a HTTP Request
	 *
	 * @param	int|null	$timeout			Timeout
	 * @param	string		$httpVersion		HTTP Version
	 * @param	bool|int	$followRedirects	Automatically follow redirects? If a number is provided, will follow up to that number of redirects
	 * @return	\IPS\Http\Request
	 */
	public function request( $timeout=null, $httpVersion=null, $followRedirects=5 )
	{
		/* Check the scheme is valid. Some areas accept user-submitted information to create a Url object. To avoid
			security issues from using file:// telnet:// etc. We reject everything not used by the suite here */
		if( isset( $this->data['scheme'] ) AND !in_array( $this->data['scheme'], array( 'http', 'https', 'ftp', 'scp', 'sftp', 'ftps' ) ) )
		{
			throw new \RuntimeException( mb_strtoupper( $this->data['scheme'] ) . '_SCHEME_NOT_PERMITTED' );
		}

		/* Set a timeout */
		if( $timeout === null )
		{
			$timeout = \IPS\DEFAULT_REQUEST_TIMEOUT;
		}

		/* Use cURL if we can. BYPASS_CURL constant can be set to TRUE to force us to fallback to Sockets */
		if ( function_exists( 'curl_init' ) and function_exists( 'curl_exec' ) and \IPS\BYPASS_CURL === false )
		{
			/* We require 7.36 or higher because older versions can't handle chunked encoding properly - FORCE_CURL constant can be set to override this and use it anyway */
			$version = curl_version();
			if( \IPS\FORCE_CURL or version_compare( $version['version'], '7.36', '>=' ) )
			{
				$requestObj	= new \IPS\Http\Request\Curl( $this, $timeout, $httpVersion, $followRedirects );
			}
		}

		/* Fallback to Sockets if we can't use cURL */
		if( !isset( $requestObj ) )
		{
			$requestObj	= new \IPS\Http\Request\Sockets( $this, $timeout, $httpVersion, $followRedirects );
		}

		/* Set a default user-agent (some services, e.g. spotify, block requests without one but it's good to do so anyway) */
		$requestObj->setHeaders( array( 'User-Agent' => 'IPS Community Suite 4' ) );

		/* Return */
		return $requestObj;
	}

	/**
	 * Import as file
	 *
	 * @param	string	$storageExtension	The extension which specified the storage location to use
	 * @return	\IPS\File
	 * @throws	\RuntimeException
	 */
	public function import( $storageExtension )
	{
		$response = $this->request()->get();

		/* We should not attempt to "import" 404, 403, 500, etc. responses */
		if( (int) $response->httpResponseCode !== 200 )
		{
			throw new \RuntimeException( "COULD_NOT_IMPORT" );
		}

		return \IPS\File::create( $storageExtension, basename( $this->data[ static::COMPONENT_PATH ] ), $response );
	}

	/**
	 * To string
	 *
	 * @return	string
	 */
	public function __toString()
	{
		return (string) $this->url;
	}

	/* !Encoding and Decoding */

	/**
	 * @brief	Allowed characters for the different components, everything apart from schemes and ports can also contain percent-encoded characters
	 */
	protected static $allowedCharacters = array(
		/* A scheme must is allowed to contain letters, digits, plus ("+"), period ("."), or hyphen ("-"). */
		self::COMPONENT_SCHEME => 'A-Za-z0-9\+\.\-',
		/* A username is allowed to contain Unreserved Characters and Subcomponent Delimiters */
		self::COMPONENT_USERNAME => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=',
		/* A password is allowed to contain Unreserved Characters, Subcomponent Delimiters, and ":" */
		self::COMPONENT_PASSWORD => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=:',
		/* Hosts can be several different things (IP lireral, IPv4 address or registered name), but for the sake of validation it comes down to Unreserved Characters and Subcomponent delimiters */
		self::COMPONENT_HOST => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=',
		/* Ports must be numeric */
		self::COMPONENT_PORT => '0-9',
		/* A path is made up of path segments separated by a single /. A path segment is allowed to contain Unreserved Characters, Percent-Encoded Characters, Subcomponent Delimiters, plus ":", "@" */
		self::COMPONENT_PATH => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=:@\/',
		/* A query string can contain Unreserved Characters, Subcomponent Delimiters, plus ":", "@", "/" and "?".
			While "[" and "]" are not in the RFC, common convention is to use them for multi-dimensional key-value pairs, so they are also included which should be fine as square brackets are
			 only part of the general delimiters because of their use in the host for IPv6 characters - they have no special meaning in the query string or beyond
			While "{" and "}" are also not in the RFC, we need to allow them without throwing an error because older versions allowed them and otherwise the upgrader will throw an error half-way through
		*/
		self::COMPONENT_QUERY => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=:@\/\?\[\]\{\}',
		/* In a query string which is using the "k1=v1&k2=v2" convention, the keys  can contain anything a query string can contain except & and = */
		self::COMPONENT_QUERY_KEY => 'A-Za-z0-9\-\._~!\$\'\(\)\*\+,;:@\/\?\[\]',
		/* In a query string which is using the "k1=v1&k2=v2" convention, the value  can contain anything a query string can contain except & */
		self::COMPONENT_QUERY_VALUE => 'A-Za-z0-9\-\._~!\$\'\(\)\*\+,;=:@\/\?\[\]',
		/* A fragment can contain Unreserved Characters, Subcomponent Delimiters, plus ":", "@", "/" and "?" */
		self::COMPONENT_FRAGMENT => 'A-Za-z0-9\-\._~!\$&\'\(\)\*\+,;=:@\/\?',
	);

	/**
	 * Validate a component
	 *
	 * @param	string	$component	One of the COMPONENT_* constants
	 * @param	string	$value		The value
	 * @return	bool
	 */
	public static function validateComponent( $component, $value )
	{
		/* Get the allowed characters */
		$allowedCharacters = static::$allowedCharacters[ $component ];

		/* These ones can also include percent-encoded characters */
		if ( !in_array( $component, array( static::COMPONENT_SCHEME, static::COMPONENT_PORT ) ) )
		{
			$regex = '(' . '(%[A-Fa-z0-9]{2})|' . '[' . $allowedCharacters . ']*' . ')*';
		}
		else
		{
			$regex = '[' . $allowedCharacters . ']*';
		}

		/* Schemes must begin with a letter */
		if ( $component === static::COMPONENT_SCHEME )
		{
			$regex = '[A-Za-z]' . $regex;
		}

		/* Return */
		return (bool) preg_match( '/^' . $regex . '$/', $value );
	}

	/**
	 * Percent-Encode a component
	 *
	 * @param	string			$component			One of the COMPONENT_* constants
	 * @param	string			$value				The value
	 * @return	string
	 * @throws	\InvalidArgumentException
	 */
	public static function encodeComponent( $component, $value )
	{
		/* These ones cannot be percent-encoded */
		if ( in_array( $component, array( static::COMPONENT_SCHEME, static::COMPONENT_PORT ) ) )
		{
			throw new \InvalidArgumentException;
		}

		/* Get the allowed characters */
		$allowedCharacters = static::$allowedCharacters[ $component ];

		/* Do it */
		return preg_replace_callback( '/[^' . $allowedCharacters . ']/i', function( $matches )
		{
			return rawurlencode( $matches[0] );
		}, $value );
	}

	/**
	 * Un-Percent-Encode a component
	 *
	 * @param	string	$component	One of the COMPONENT_* constants
	 * @param	string	$value		The value
	 * @return	bool
	 * @throws	\InvalidArgumentException
	 */
	public static function decodeComponent( $component, $value )
	{
		return rawurldecode( $value );
	}

	/* !Utilities */

	/**
	 * Return the base URL
	 *
	 * @param	bool			$protocol		Protocol (one of the PROTOCOL_* constants)
	 * @return	string
	 */
	public static function baseUrl( $protocol = 0 )
	{
		/* Get the base URL */
		$url = \IPS\Settings::i()->base_url;

		/* Adjust the protocol */
		if ( $protocol )
		{
			switch ( $protocol )
			{
				case static::PROTOCOL_HTTPS:
					$url = 'https://' . mb_substr( $url, mb_strpos( $url, '://' ) + 3 );
					break;

				case static::PROTOCOL_HTTP:
					$url = 'http://' . mb_substr( $url, mb_strpos( $url, '://' ) + 3 );
					break;

				case static::PROTOCOL_RELATIVE:
					$url = '//' . mb_substr( $url, mb_strpos( $url, '://' ) + 3 );
					break;
			}
		}

		/* Add a trailing slash */
		if ( mb_substr( $url, -1 ) !== '/' )
		{
			$url .= '/';
		}

		/* Return */
		return $url;
	}

	/**
	 * @brief Punycode object
	 */
	protected static $punycode = NULL;

	/**
	 * Convert a full URL into it's components
	 *
	 * @param	string|NULL	$url		A valid URL as per our definition (see phpDoc on class) or NULL if being called by createFromComponents()
	 * @param	bool	$autoEncode		If true, any invalid components will be automatically encoded rather than an exception thrown - useful if the entire link is user-provided
	 * @return	array
	 * @throws	\IPS\Http\Url\Exception
	 *	@li	INVALID_URL			The URL did not start with // to indicate relative protocol or contain ://
	 *	@li	INVALID_SCHEME		The scheme was invalid
	 *	@li	INVALID_USERNAME	The username was invalid
	 *	@li	INVALID_PASSWORD	The password was invalid
	 *	@LI	INVALID_HOST		The host name was invalid
	 *	@LI	INVALID_PATH		The path was invalid
	 *	@LI	INVALID_QUERY		The query was invalid
	 *	@LI	INVALID_FRAGMENT	The fragment was invalid
	 */
	protected static function componentsFromUrlString( $url, $autoEncode = FALSE )
	{
		/* Init */
		$return = array(
			static::COMPONENT_SCHEME => NULL,
			static::COMPONENT_HOST => NULL,
			static::COMPONENT_PORT => NULL,
			static::COMPONENT_USERNAME => NULL,
			static::COMPONENT_PASSWORD => NULL,
			static::COMPONENT_PATH => NULL,
			static::COMPONENT_QUERY => NULL,
			static::COMPONENT_FRAGMENT => NULL,
		);

		/* If the URL doesn't start with the protocol-relative marker ("//"), it needs a scheme: */
		if ( mb_substr( $url, 0, 2 ) !== '//' )
		{
			/* Work out where the :// is */
			$colonAndDoubleForwardSlashPosition = mb_strpos( $url, '://' );
			if ( $colonAndDoubleForwardSlashPosition === FALSE )
			{
				if ( $autoEncode )
				{
					$scheme = 'http';
				}
				else
				{
					throw new \IPS\Http\Url\Exception('INVALID_URL');
				}
			}
			else
			{
				$scheme = mb_substr( $url, 0, $colonAndDoubleForwardSlashPosition );

				/* Take the scheme off the URL for the rest of of our processing */
				$url = mb_substr( $url, mb_strlen( $scheme ) + 3 );
			}

			/* Validate the scheme */
			if ( !static::validateComponent( static::COMPONENT_SCHEME, $scheme ) )
			{
				if ( $autoEncode )
				{
					$scheme = 'http';
				}
				else
				{
					throw new \IPS\Http\Url\Exception('INVALID_SCHEME');
				}
			}

			/* Set it. Though case-insensitve, we should only produce lowercase schemes */
			$return[ static::COMPONENT_SCHEME ] = mb_strtolower( $scheme );

		}
		/* If it's protocol relative, take the // off the URL for the rest of of our processing */
		else
		{
			$url = mb_substr( $url, 2 );
		}

		/* The authority component is preceded by a double slash ("//") and is  terminated by the next slash ("/"), question mark ("?"), or number
			sign ("#") character, or by the end of the URI */
		preg_match( '/^(.+?)(\/|\?|\#|$)/', $url, $matches );
		$authority = $matches[1];
		$url = mb_substr( $url, mb_strlen( $matches[1] ) );

		/* If there's an @ in the authority, everything before it is user info */
		$atSymbolPosition = mb_strpos( $authority, '@' );
		if ( $atSymbolPosition !== FALSE )
		{
			/* Take out the user information... */
			$userInfo = mb_substr( $authority, 0, $atSymbolPosition );
			$authority = mb_substr( $authority, $atSymbolPosition + 1 );

			/* If there's a : in the user information, we have a username and password */
			$colonPosition = mb_strpos( $userInfo, ':' );
			if ( $colonPosition !== FALSE )
			{
				$username = mb_substr( $userInfo, 0, $colonPosition );
				$password = mb_substr( $userInfo, $colonPosition + 1 );
			}
			/* Otherwise it's just a username */
			else
			{
				$username = $userInfo;
				$password = NULL;
			}

			/* Validate and set the username */
			if ( !static::validateComponent( static::COMPONENT_USERNAME, $username ) )
			{
				if ( $autoEncode )
				{
					$return[ static::COMPONENT_USERNAME ] = $username;
				}
				else
				{
					throw new \IPS\Http\Url\Exception('INVALID_USERNAME');
				}
			}
			else
			{
				$return[ static::COMPONENT_USERNAME ] = static::decodeComponent( static::COMPONENT_USERNAME, $username );
			}

			/* Validate and set the password if there is one */
			if ( $password !== NULL )
			{
				if ( !static::validateComponent( static::COMPONENT_PASSWORD, $password ) )
				{
					if ( $autoEncode )
					{
						$return[ static::COMPONENT_PASSWORD ] = $password;
					}
					else
					{
						throw new \IPS\Http\Url\Exception('INVALID_PASSWORD');
					}
				}
				else
				{
					$return[ static::COMPONENT_PASSWORD ] = static::decodeComponent( static::COMPONENT_PASSWORD, $password );
				}
			}
		}

		/* If the authority ends in a : followed by a number, that's the port */
		if ( preg_match( '/:(\d*)$/', $authority, $matches ) )
		{
			$return[ static::COMPONENT_PORT ] = intval( $matches[1] );
			$authority = mb_substr( $authority, 0, -mb_strlen( $matches[0] ) );
		}

		/* If the host contains non-ASCII characters, Puncody encode them */
		if ( !preg_match( '/^[\x00-\x7F]*$/', $authority ) )
		{
			if ( static::$punycode === NULL )
			{
				require_once \IPS\ROOT_PATH . "/system/3rd_party/php-punycode/Punycode.php";
				static::$punycode = new \TrueBV\Punycode();
			}
			$authority = static::$punycode->encode( $authority );
		}

		/* Set the host */
		if ( !static::validateComponent( static::COMPONENT_HOST, $authority ) )
		{
			if ( $autoEncode )
			{
				$return[ static::COMPONENT_HOST ] = $authority;
			}
			else
			{
				throw new \IPS\Http\Url\Exception('INVALID_HOST');
			}
		}
		else
		{
			$return[ static::COMPONENT_HOST ] = static::decodeComponent( static::COMPONENT_HOST, $authority );
		}

		/* There might be nothing left at this point, in which case we're done */
		if ( !$url )
		{
			return $return;
		}

		/* The path is terminated by the first question mark ("?") or number sign ("#") character, or by the end of the URI. */
		preg_match( '/^(.+?)(\?|\#|$)/', $url, $matches );
		if ( !static::validateComponent( static::COMPONENT_PATH, $matches[1] ) )
		{
			if ( $autoEncode )
			{
				$return[ static::COMPONENT_PATH ] = $matches[1];
			}
			else
			{
				throw new \IPS\Http\Url\Exception('INVALID_PATH');
			}
		}
		else
		{
			$return[ static::COMPONENT_PATH ] = static::decodeComponent( static::COMPONENT_PATH, $matches[1] );
		}
		$url = mb_substr( $url, mb_strlen( $matches[0] ) );

		/* There might be nothing left at this point, in which case we're done */
		if ( !$url )
		{
			return $return;
		}

		/* If the terminating character was a ? in $matches[2], then we have a query string */
		if ( $matches[2] === '?' )
		{
			/* The query component is terminated by a number sign ("#") character or by the end of the URI. */
			preg_match( '/^(.*?)(\#|$)/', $url, $matches );
			if ( !static::validateComponent( static::COMPONENT_QUERY, $matches[1] ) )
			{
				if ( $autoEncode )
				{
					$return[ static::COMPONENT_QUERY ] = $matches[1];
				}
				else
				{
					throw new \IPS\Http\Url\Exception('INVALID_QUERY');
				}
			}
			else
			{
				$return[ static::COMPONENT_QUERY ] = static::decodeComponent( static::COMPONENT_QUERY, $matches[1] );
			}
			$url = mb_substr( $url, mb_strlen( $matches[1] ) );
		}

		/* If there's anything left, it's the fragment */
		if ( $url )
		{
			$url = ltrim( $url, '#' );
			if ( !static::validateComponent( static::COMPONENT_FRAGMENT, $url ) )
			{
				if ( $autoEncode )
				{
					$return[ static::COMPONENT_FRAGMENT ] = $url;
				}
				else
				{
					throw new \IPS\Http\Url\Exception('INVALID_FRAGMENT');
				}
			}
			else
			{
				$return[ static::COMPONENT_FRAGMENT ] = static::decodeComponent( static::COMPONENT_FRAGMENT, $url );
			}
		}

		/* Return */
		return $return;
	}

	/**
	 * Convert an array of query parameters to a query string
	 *
	 * @param	array	$query	The query as an array (e.g. [ 'foo'=>'bar', 'moo'=>'baz' ])
	 * @param	bool	$encode	If true, will encode for output
	 * @return	string
	 */
	protected static function convertQueryAsArrayToString( $query, $encode = FALSE )
	{
		$return = array();
		foreach ( $query as $k => $v )
		{
			if ( $encode )
			{
				$k = static::encodeComponent( static::COMPONENT_QUERY_KEY, $k );
			}

			if ( is_array( $v ) )
			{
				$return[] = static::squashQueryStringArray( $k, $v );
			}
			elseif ( $v !== NULL )
			{
				if ( $encode )
				{
					$v = static::encodeComponent( static::COMPONENT_QUERY_VALUE, $v );
				}
				$return[] = "{$k}={$v}";
			}
			else
			{
				$return[] = "{$k}";
			}
		}
		return implode( '&', $return );
	}

	/**
	 * Convert an array within an array of query parameters to a query string
	 *
	 * @param	string	$key	The key for this query string parameter
	 * @param	array	$value	The query as an array (e.g. [ 'foo'=>'bar', 'moo'=>'baz' ])
	 * @return	string
	 */
	protected static function squashQueryStringArray( $key, $value )
	{
		$return = '';
		foreach ( $value as $k => $v )
		{
			if ( is_array( $v ) )
			{
				$return[] = static::squashQueryStringArray( "{$key}[{$k}]", $v );
			}
			else
			{
				$return[] = "{$key}[{$k}]={$v}";
			}
		}
		return is_array( $return ) ? implode( '&', $return ) : $return;
	}

	/**
	 * Convert a query string to an array of query parameters
	 *
	 * @param	array	$query	The query string as a string (e.g. "foo=bar&moo=baz")
	 * @return	array
	 */
	protected static function convertQueryAsStringToArray( $query )
	{
		$return = array();

		if ( $query !== NULL )
		{
			foreach ( explode( '&', $query ) as $part )
			{
				$keyAndValue = explode( '=', $part, 2 );
				if ( isset( $keyAndValue[1] ) )
				{
					if ( preg_match( '/^([^\[]*)(\[.*\])$/', $keyAndValue[0], $matches ) )
					{
						static::_pushQueryStringPartIntoArray( $return, $matches[1], $matches[2], $keyAndValue[1] );
					}
					else
					{
						$return[ $keyAndValue[0] ] = (string) $keyAndValue[1];
					}
				}
				else
				{
					$return[ $keyAndValue[0] ] = NULL;
				}
			}
		}

		return $return;
	}

	/**
	 * Utility function used by convertQueryAsStringToArray()
	 *
	 * @param	array	$return			The current $return value being worked on, passed by reference
	 * @param	string	$mainKey		The main key, for example, if parsing "foo[x][y]=bar", the value will be "foo"
	 * @param	string	$subKeyNames	The sub keys in square brackets, for example, if parsing "foo[x][y]=bar", the value will be "[x][y]"
	 * @param	string	$value			The value, for example, if parsing "foo[x][y]=bar", the value will be "bar"
	 */
	protected static function _pushQueryStringPartIntoArray( &$return, $mainKey, $subKeyNames, $value )
	{
		preg_match_all( '/\[([^\]]*)\]/', $subKeyNames, $matches );

		if ( !isset( $return[ $mainKey ] ) )
		{
	        $return[ $mainKey ] = array();
	    }
		$workingArray =& $return[ $mainKey ];

		$last = array_pop( $matches[1] );
		foreach ( $matches[1] as $k )
		{
			if ( $k === '' )
			{
				$workingArray[] = array();
				$workingArray =& $workingArray[ count( $workingArray ) - 1 ];
			}
			elseif ( !isset( $workingArray[ $k ] ) )
			{
				$workingArray[ $k ] = array();
				$workingArray =& $workingArray[ $k ];
			}
		}

		if ( $last === '' )
		{
	        $workingArray[] = $value;
	    }
	    else
	    {
	        $workingArray[ $last ] = $value;
	    }
	}

	/* !Deprecated */

	/**
	 * @brief		Is internal?
	 * @deprecated	Using this property is deprecated. Check if instance of \IPS\Http\Url\Internal
	 */
	public $isInternal = FALSE;

	/**
	 * @brief	Is friendly?
	 * @deprecated	Using this property is deprecated. Check if instance of \IPS\Http\Url\Friendly
	 */
	public $isFriendly = FALSE;

	/**
	 * Get FURL query
	 *
	 * @return		string
	 * @deprecated	Access $friendlyUrlComponent directly
	 */
	public function getFurlQuery()
	{
		if ( $this instanceof \IPS\Http\Url\Friendly )
		{
			return $this->friendlyUrlComponent;
		}
		else
		{
			return NULL;
		}
	}

	/**
	 * Get FURL Definition
	 *
	 * @param	bool	$revert	If TRUE, ignores all customisations and reloads from json
	 * @return	array
	 */
	public static function furlDefinition( $revert=FALSE )
	{
		return \IPS\Http\Url\Friendly::furlDefinition( $revert );
	}

	/**
	 * Add CSRF check to query string
	 *
	 * @return	\IPS\Http\Url
	 * @deprecated	This method is defined in \IPS\Http\Url\Internal which will be kept, while this method will be removed in a major version
	 */
	public function csrf()
	{
		return $this->setQueryString( 'csrfKey', \IPS\Session::i()->csrfKey );
	}

	/**
	 * Get ACP query string without adsess
	 *
	 * @return	string
	 * @deprecated	This method is defined in \IPS\Http\Url\Internal which will be kept, while this method will be removed in a major version
	 */
	public function acpQueryString()
	{
		$queryString = $this->queryString;
		unset( $queryString['adsess'] );
		unset( $queryString['csrf'] );
		return static::convertQueryAsArrayToString( $queryString );
	}

	/**
	 * Strip URL arguments
	 *
	 * @param	int		$position	Arguments from this position onward will be stripped. Value of 0 is equivalent to stripping the entire query string
	 * @return	\IPS\Http\Url
	 * @deprecated
	 */
	public function stripArguments( $position=0 )
	{
		if( $position === 0 )
		{
			return $this->stripQueryString();
		}

		$newQueryArray	= array();
		$_index			= 0;

		foreach( $this->queryString as $key => $value )
		{
			if( $_index >= $position )
			{
				break;
			}

			$newQueryArray[ $key ]	= $value;
			$_index++;
		}

		return static::createFromComponents( $this->data[ static::COMPONENT_HOST ], $this->data[ static::COMPONENT_SCHEME ], $this->data[ static::COMPONENT_PATH ], $newQueryArray, $this->data[ static::COMPONENT_PORT ], $this->data[ static::COMPONENT_USERNAME ], $this->data[ static::COMPONENT_PASSWORD ], $this->data[ static::COMPONENT_FRAGMENT ] );
	}

	/**
	 * Create a URL object from data array
	 *
	 * @param	array	$data	URL data pieces
	 * @return	\IPS\Http\Url
	 * @deprecated
	 */
	public static function createFromArray( $data )
	{
		return static::createFromComponents(
			$data[ static::COMPONENT_HOST ],
			isset( $data[ static::COMPONENT_SCHEME ] ) ? $data[ static::COMPONENT_SCHEME ] : NULL,
			isset( $data[ static::COMPONENT_PATH ] ) ? $data[ static::COMPONENT_PATH ] : NULL,
			isset( $data[ static::COMPONENT_QUERY ] ) ? $data[ static::COMPONENT_QUERY ] : NULL,
			isset( $data[ static::COMPONENT_PORT ] ) ? $data[ static::COMPONENT_PORT ] : NULL,
			isset( $data[ static::COMPONENT_USERNAME ] ) ? $data[ static::COMPONENT_USERNAME ] : NULL,
			isset( $data[ static::COMPONENT_PASSWORD ] ) ? $data[ static::COMPONENT_PASSWORD ] : NULL,
			isset( $data[ static::COMPONENT_FRAGMENT ] ) ? $data[ static::COMPONENT_FRAGMENT ] : NULL
		);
	}

	/**
	 * Return URL that conforms to RFC 3986
	 *
	 * @return	string
	 * @deprecated
	 */
	public function rfc3986()
	{
		return (string) $this;
	}

	/**
	 * Convert a value into an "SEO Title" for friendly URLs
	 *
	 * @param	string	$value	Value
	 * @return	string
	 * @note	Many places require an SEO title, so we always need to return something, so when no valid title is available we return a dash
	 */
	public static function seoTitle( $value )
	{
		return \IPS\Http\Url\Friendly::seoTitle( $value );
	}

	/**
	 * Get friendly URL data
	 *
	 * @return	array	Parameters
	 * @deprecared
	 */
	public function getFriendlyUrlData()
	{
		if ( $this instanceof \IPS\Http\Url\Friendly )
		{
			return $this->hiddenQueryString;
		}
		else
		{
			return array();
		}
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 19: 710 (1910)

#### Original name
Ganoderma flexipes Pat., 1907

### Remarks
null


text:
namespace device {

class BluetoothGattCharacteristic;

}  // namespace device

namespace bluez {

class BluetoothRemoteGattCharacteristicBlueZ;

// The BluetoothRemoteGattDescriptorBlueZ class implements
// BluetoothGattDescriptor for remote GATT characteristic descriptors for
// platforms that use BlueZ.
class BluetoothRemoteGattDescriptorBlueZ
    : public device::BluetoothGattDescriptor {
 public:
  // device::BluetoothGattDescriptor overrides.
  std::string GetIdentifier() const override;
  device::BluetoothUUID GetUUID() const override;
  bool IsLocal() const override;
  const std::vector<uint8_t>& GetValue() const override;
  device::BluetoothGattCharacteristic* GetCharacteristic() const override;
  device::BluetoothGattCharacteristic::Permissions GetPermissions()
      const override;
  void ReadRemoteDescriptor(const ValueCallback& callback,
                            const ErrorCallback& error_callback) override;
  void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value,
                             const base::Closure& callback,
                             const ErrorCallback& error_callback) override;

  // Object path of the underlying D-Bus characteristic.
  const dbus::ObjectPath& object_path() const { return object_path_; }

 private:
  friend class BluetoothRemoteGattCharacteristicBlueZ;

  BluetoothRemoteGattDescriptorBlueZ(
      BluetoothRemoteGattCharacteristicBlueZ* characteristic,
      const dbus::ObjectPath& object_path);
  ~BluetoothRemoteGattDescriptorBlueZ() override;

  // Called by dbus:: on unsuccessful completion of a request to read or write
  // the descriptor value.
  void OnError(const ErrorCallback& error_callback,
               const std::string& error_name,
               const std::string& error_message);

  // Object path of the D-Bus descriptor object.
  dbus::ObjectPath object_path_;

  // The GATT characteristic this descriptor belongs to.
  BluetoothRemoteGattCharacteristicBlueZ* characteristic_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<BluetoothRemoteGattDescriptorBlueZ> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothRemoteGattDescriptorBlueZ);
};

}  // namespace bluez

#endif  // DEVICE_BLUETOOTH_BLUETOOTH_REMOTE_GATT_DESCRIPTOR_BLUEZ_H_


text:
Example applications using [Syncro](https://github.com/mkopala/syncro) web application framework.

Examples
--------

* [Todos](todos)

Requirements
------------

* [MongoDB](http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/)
* Redis
* [node.js](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager)
* CoffeeScript

Quick setup
------------------

Add MongoDB source & key, adds node.js PPA repository, installs MongoDB, Redis, node.js, npm, and coffeescript & dependencies.  On ubuntu -

    make ubuntu-setup

On osx -

    make osx-setup


text:
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dir-watch-inotify.c  OS specific directory change notification for message bus
 *
 * Copyright (C) 2003 Red Hat, Inc.
 *           (c) 2006 Mandriva
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <config.h>

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/inotify.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>

#include <dbus/dbus-internals.h>
#include <dbus/dbus-list.h>
#include <dbus/dbus-watch.h>
#include "dir-watch.h"

#define MAX_DIRS_TO_WATCH 128
#define INOTIFY_EVENT_SIZE (sizeof(struct inotify_event))
#define INOTIFY_BUF_LEN (1024 * (INOTIFY_EVENT_SIZE + 16))

/* use a static array to avoid handling OOM */
static int wds[MAX_DIRS_TO_WATCH];
static char *dirs[MAX_DIRS_TO_WATCH];
static int num_wds = 0;
static int inotify_fd = -1;
static DBusWatch *watch = NULL;
static DBusLoop *loop = NULL;

static dbus_bool_t
_inotify_watch_callback (DBusWatch *watch, unsigned int condition, void *data)
{
  return dbus_watch_handle (watch, condition);
}

static dbus_bool_t
_handle_inotify_watch (DBusWatch *passed_watch, unsigned int flags, void *data)
{
  char buffer[INOTIFY_BUF_LEN];
  ssize_t ret = 0;
  int i = 0;
  pid_t pid;
  dbus_bool_t have_change = FALSE;

  ret = read (inotify_fd, buffer, INOTIFY_BUF_LEN);
  if (ret < 0)
    _dbus_verbose ("Error reading inotify event: '%s'\n", _dbus_strerror(errno));
  else if (!ret)
    _dbus_verbose ("Error reading inotify event: buffer too small\n");

  while (i < ret)
    {
      struct inotify_event *ev;
      pid = _dbus_getpid ();

      ev = (struct inotify_event *) &buffer[i];
      i += INOTIFY_EVENT_SIZE + ev->len;
#ifdef DBUS_ENABLE_VERBOSE_MODE
      if (ev->len)
        _dbus_verbose ("event name: '%s'\n", ev->name);
      _dbus_verbose ("inotify event: wd=%d mask=%u cookie=%u len=%u\n", ev->wd, ev->mask, ev->cookie, ev->len);
#endif
      _dbus_verbose ("Sending SIGHUP signal on reception of a inotify event\n");
      have_change = TRUE;
    }
  if (have_change)
    (void) kill (pid, SIGHUP);

  return TRUE;
}

#include <stdio.h>

static void
_set_watched_dirs_internal (DBusList **directories)
{
  int new_wds[MAX_DIRS_TO_WATCH];
  char *new_dirs[MAX_DIRS_TO_WATCH];
  DBusList *link;
  int i, j, wd;

  for (i = 0; i < MAX_DIRS_TO_WATCH; i++)
    {
      new_wds[i] = -1;
      new_dirs[i] = NULL;
    }

  i = 0;
  link = _dbus_list_get_first_link (directories);
  while (link != NULL)
    {
      new_dirs[i++] = (char *)link->data;
      link = _dbus_list_get_next_link (directories, link);
    }

  /* Look for directories in both the old and new sets, if
   * we find one, move its data into the new set.
   */
  for (i = 0; new_dirs[i]; i++)
    {
      for (j = 0; j < num_wds; j++)
        {
          if (dirs[j] && strcmp (new_dirs[i], dirs[j]) == 0)
            {
              new_wds[i] = wds[j];
              new_dirs[i] = dirs[j];
              wds[j] = -1;
              dirs[j] = NULL;
              break;
            }
        }
    }

  /* Any directories we find in "wds" with a nonzero fd must
   * not be in the new set, so perform cleanup now.
   */
  for (j = 0; j < num_wds; j++)
    {
      if (wds[j] != -1)
        {
          inotify_rm_watch (inotify_fd, wds[j]);
          dbus_free (dirs[j]);
          wds[j] = -1;
          dirs[j] = NULL;
        }
    }

  for (i = 0; new_dirs[i]; i++)
    {
      if (new_wds[i] == -1)
        {
          /* FIXME - less lame error handling for failing to add a watch; we may need to sleep. */
          wd = inotify_add_watch (inotify_fd, new_dirs[i], IN_CLOSE_WRITE | IN_DELETE | IN_MOVED_TO | IN_MOVED_FROM);
          if (wd < 0)
            {
              /* Not all service directories need to exist. */
              if (errno != ENOENT)
                {
                  _dbus_warn ("Cannot setup inotify for '%s'; error '%s'\n", new_dirs[i], _dbus_strerror (errno));
                  goto out;
                }
              else
                {
                  new_wds[i] = -1;
                  new_dirs[i] = NULL;
                  continue;
                }
            }
          new_wds[i] = wd;
          new_dirs[i] = _dbus_strdup (new_dirs[i]);
          if (!new_dirs[i])
            {
              /* FIXME have less lame handling for OOM, we just silently fail to
               * watch.  (In reality though, the whole OOM handling in dbus is stupid
               * but we won't go into that in this comment =) )
               */
              inotify_rm_watch (inotify_fd, wd);
              new_wds[i] = -1;
            }
        }
    }

  num_wds = i;

  for (i = 0; i < MAX_DIRS_TO_WATCH; i++)
    {
      wds[i] = new_wds[i];
      dirs[i] = new_dirs[i];
    }

 out:;
}

#include <stdio.h>
static void
_shutdown_inotify (void *data)
{
  DBusList *empty = NULL;

  if (inotify_fd == -1)
    return;

  _set_watched_dirs_internal (&empty);

  close (inotify_fd);
  inotify_fd = -1;
  if (watch != NULL)
    {
      _dbus_loop_remove_watch (loop, watch, _inotify_watch_callback, NULL);
      _dbus_watch_unref (watch);
      _dbus_loop_unref (loop);
    }
  watch = NULL;
  loop = NULL;
}

static int
_init_inotify (BusContext *context)
{
  int ret = 0;

  if (inotify_fd == -1)
    {
#ifdef HAVE_INOTIFY_INIT1
      inotify_fd = inotify_init1 (IN_CLOEXEC);
      /* This ensures we still run on older Linux kernels.
       * https://bugs.freedesktop.org/show_bug.cgi?id=23957
       */
      if (inotify_fd < 0)
        inotify_fd = inotify_init ();
#else
      inotify_fd = inotify_init ();
#endif
      if (inotify_fd <= 0)
        {
          _dbus_warn ("Cannot initialize inotify\n");
          goto out;
        }
      loop = bus_context_get_loop (context);
      _dbus_loop_ref (loop);

      watch = _dbus_watch_new (inotify_fd, DBUS_WATCH_READABLE, TRUE,
                               _handle_inotify_watch, NULL, NULL);

      if (watch == NULL)
        {
          _dbus_warn ("Unable to create inotify watch\n");
          goto out;
        }

      if (!_dbus_loop_add_watch (loop, watch, _inotify_watch_callback,
                                 NULL, NULL))
        {
          _dbus_warn ("Unable to add reload watch to main loop");
          _dbus_watch_unref (watch);
          watch = NULL;
          goto out;
        }

      _dbus_register_shutdown_func (_shutdown_inotify, NULL);
    }

  ret = 1;

out:
  return ret;
}

void
bus_set_watched_dirs (BusContext *context, DBusList **directories)
{
  if (!_init_inotify (context))
    return;

  _set_watched_dirs_internal (directories);
}


text:
namespace Twining.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Input;

    public class CommandBase : ICommand
    {
        public virtual bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }

            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public virtual void Execute(object parameter)
        {
        }
    }
}


text:
import Message from './Message'

test('it should increase message counter', () => {
  const msg1 = new Message('a', 'b')
  const msg2 = new Message('c', 'd')
  expect(msg1.id).toBe(0)
  expect(msg2.id).toBe(1)
})


text:
// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using LinkIt.ConfigBuilders;
using LinkIt.PublicApi;
using LinkIt.TestHelpers;
using Xunit;

namespace LinkIt.Tests.Core.Exploratory
{
    public class ImageWithRatiosCustomLoadLinkTests
    {
        public ImageWithRatiosCustomLoadLinkTests()
        {
            var loadLinkProtocolBuilder = new LoadLinkProtocolBuilder();
            loadLinkProtocolBuilder.For<WithImageLinkedSource>()
                .LoadLinkReferenceById(
                    linkedSource => linkedSource.Model.ImageUrl,
                    linkedSource => linkedSource.Image);

            _sut = loadLinkProtocolBuilder.Build(() =>
                new ReferenceLoaderStub(new ImageReferenceTypeConfigWorkAround())
            );
        }

        private readonly ILoadLinkProtocol _sut;

        [Fact]
        public async System.Threading.Tasks.Task LoadLink_ImagesFromDeclinaisonUrlAsync()
        {
            var actual = await _sut.LoadLink<WithImageLinkedSource>().FromModelAsync(
                new WithImage
                {
                    Id = "1",
                    ImageUrl = "a-1x1"
                }
            );

            Assert.Contains("a-1x1", actual.Image.Ratios.Select(r => r.Url));
        }

        [Fact]
        public async System.Threading.Tasks.Task LoadLink_ImagesFromDeclinaisonUrlCannotBeResolved_ShouldLinkNullAsync()
        {
            var actual = await _sut.LoadLink<WithImageLinkedSource>().FromModelAsync(
                new WithImage
                {
                    Id = "1",
                    ImageUrl = "cannot-be-resolved"
                }
            );

            Assert.Null(actual.Image);
        }

        [Fact]
        public async System.Threading.Tasks.Task LoadLink_ImagesFromDeclinaisonUrlWithoutReferenceId_ShouldLinkNullAsync()
        {
            var actual = await _sut.LoadLink<WithImageLinkedSource>().FromModelAsync(
                new WithImage
                {
                    Id = "1",
                    ImageUrl = null
                }
            );

            Assert.Null(actual.Image);
        }
    }

    public class WithImageLinkedSource : ILinkedSource<WithImage>
    {
        public ImageWithRatios Image { get; set; }
        public WithImage Model { get; set; }
    }

    public class WithImage
    {
        public string Id { get; set; }
        public string ImageUrl { get; set; }
    }

    public class ImageWithRatios
    {
        public string Alt { get; set; }
        public List<ImageRatio> Ratios { get; set; }
    }

    public class ImageRatio
    {
        public string Url { get; set; }
        public string Ratio { get; set; }
    }

    public class ImageWithRatioRepository
    {
        private static readonly Dictionary<string, ImageWithRatios> _imagesByRatioUrl;

        static ImageWithRatioRepository()
        {
            var images = new[]
            {
                new ImageWithRatios
                {
                    Alt = "alt-a",
                    Ratios = new List<ImageRatio>
                    {
                        new ImageRatio { Url = "a-16x9", Ratio = "16x9" },
                        new ImageRatio { Url = "a-1x1", Ratio = "1x1" }
                    }
                }
            };

            _imagesByRatioUrl = images.SelectMany(image => image.Ratios.Select(declinaison => new { declinaison.Url, Image = image })
                )
                .ToDictionary(
                    item => item.Url,
                    item => item.Image);
        }

        public List<ImageWithRatios> GetByDeclinaisonUrl(IEnumerable<string> declinaisonUrls)
        {
            return declinaisonUrls.Where(declinaisonUrl => _imagesByRatioUrl.ContainsKey(declinaisonUrl))
                .Select(declinaisonUrl => _imagesByRatioUrl[declinaisonUrl])
                .Distinct()
                .ToList();
        }
    }

    public class ImageReferenceTypeConfigWorkAround : IReferenceTypeConfig
    {
        public Type ReferenceType => typeof(ImageWithRatios);

        public void Load(ILoadingContext loadingContext)
        {
            var lookupIds = loadingContext.ReferenceIds<ImageWithRatios, string>();
            var repository = new ImageWithRatioRepository();
            var images = repository.GetByDeclinaisonUrl(lookupIds);

            var imagesByDeclinaisonUrl = images.SelectMany(
                    image => image.Ratios.Select(declinaison => new
                    {
                        DeclinaisonUrl = declinaison.Url,
                        Image = image
                    })
                )
                .ToDictionary(
                    imageByDeclinaisonUrl => imageByDeclinaisonUrl.DeclinaisonUrl,
                    imageByDeclinaisonUrl => imageByDeclinaisonUrl.Image);

            loadingContext.AddResults(imagesByDeclinaisonUrl);
        }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>4.1. Service, Function and State Declarations</title>
<link rel="stylesheet" type="text/css" href="docbook.css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<meta name="keywords" content="MASL, Action Language, Action Semantics, UML, Unified Modelling Language, Shlaer Mellor">
<link rel="home" href="index.html" title="MASL Reference Manual">
<link rel="up" href="section.Services.html" title="Chapter 4. Services, Functions and State Actions">
<link rel="prev" href="section.Services.html" title="Chapter 4. Services, Functions and State Actions">
<link rel="next" href="section.Services.Definition.html" title="4.2. Service, Function and State Action Definitions">
<link rel="chapter" href="section.LexicalStructure.html" title="Chapter 1. Lexical Structure">
<link rel="chapter" href="section.Types.html" title="Chapter 2. Type System">
<link rel="chapter" href="section.Domains.html" title="Chapter 3. Domains">
<link rel="chapter" href="section.Services.html" title="Chapter 4. Services, Functions and State Actions">
<link rel="chapter" href="section.Relationships.html" title="Chapter 5. Relationships">
<link rel="chapter" href="section.Exceptions.html" title="Chapter 6. Exceptions">
<link rel="chapter" href="section.Terminators.html" title="Chapter 7. Terminators">
<link rel="chapter" href="section.Objects.html" title="Chapter 8. Objects">
<link rel="chapter" href="section.Statements.html" title="Chapter 9. Statements">
<link rel="chapter" href="section.Expressions.html" title="Chapter 10. Expressions">
<link rel="chapter" href="section.Projects.html" title="Chapter 11. Projects">
<link rel="chapter" href="section.Pragmas.html" title="Chapter 12. Pragmas">
<link rel="appendix" href="AlphabeticalSyntaxReference.html" title="Appendix A. Alphabetical Syntax Reference">
<link rel="index" href="ix01.html" title="Index">

OFFICIAL

4.1. Service, Function and State Declarations

Prev
Chapter 4. Services, Functions and State Actions
 Next

4.1. Service, Function and State Declarations

to do

[65]
domain service declaration
=
[ service visibility ] , 'service' , service name ,
      parameter list , ';' , pragma list;

[66]
domain function declaration
=
[ service visibility ] , 'function' , service name ,
      parameter list , 'return' , return type , ';' , pragma list;

[96]
terminator service declaration
=
[ service visibility ] , 'service' , service name ,
      parameter list , ';' , pragma list;

[97]
terminator function declaration
=
[ service visibility ] , 'function' , service name ,
      parameter list , 'return' , return type , ';' , pragma list;

[111]
object service declaration
=
[ service visibility ] , [ service type ] , 'service' ,
      service name , parameter list , ';' , pragma list;

[112]
object function declaration
=
[ service visibility ] , [ service type ] , 'function' ,
      service name , parameter list , 'return' , return type , ';' , pragma list;

[116]
state declaration
=
[ state type ] , 'state' , state name , parameter list , ';' , pragma list;

[69]

service visibility
=
'private' | 'public';

[70]

service name
=

        identifier
      ;

[71]

state type
=
'assigner' | 'assigner' , 'start' | 'creation' | 'terminal';

[72]

state name
=

        identifier
      ;

[73]

parameter list
=
'(' , [ parameter definition ] , { ',' , parameter definition } , ')';

[74]

parameter definition
=

parameter name , ':' , parameter mode , parameter type;

[75]

parameter name
=

        identifier
      ;

[76]

parameter mode
=
'in' | 'out';

[77]

parameter type
=

        type ref
      ;

[78]

return type
=

        type ref
      ;

Prev
Up
 Next

Chapter 4. Services, Functions and State Actions

Home | ToC

 4.2. Service, Function and State Action Definitions

OFFICIAL


text:
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" />
    <meta name="description" content="Demo of various Shared Storage use-cases" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
    <title>Shared storage demo</title>

    <link rel="stylesheet" href="https://unpkg.com/open-props" />
    <link rel="stylesheet" href="https://unpkg.com/open-props/normalize.min.css" />
    <link rel="stylesheet" href="https://unpkg.com/open-props/buttons.min.css" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🙂</text></svg>"
    />
    <link rel="stylesheet" href="../demo.css" />

Demo control

        <button class="mdl-button mdl-js-button mdl-button--raised demo__button" onclick="resetSharedStorage()">
          Reset impression flag
        </button>


text:
<?php

class UsersController extends BaseController {

	public function __construct() {
		$this->beforeFilter('csrf', ['on' => 'post']);
	}

	public function getLogin()
	{
		return View::make('auth.login');
	}

	public function postLogin()
	{
		$input = ['username' => Input::get('username'), 'password' => Input::get('password')];
		if (Auth::attempt($input))
			return Redirect::intended()->with('message', 'Vous etes maintenant connecté!');
		else
			return Redirect::back()->with('message', 'Incorrect Username or Password');
	}

	public function getLogout()
	{
		Auth::logout();
		return Redirect::to('login')->with('message', 'Vous etes maintenant déconnecté!');
	}

	public function getRegister()
	{
		return View::make('auth.register');
	}

	public function postRegister()
	{
		$validator = Validator::make(Input::all(), User::$rules);

		if ($validator->passes()) {
			$user = new User;
			$user->username = Input::get('username');
			$user->name = Input::get('name');
			$user->lastname = Input::get('lastname');
			$user->birthdate = Input::get('birthdate');
			$user->email = Input::get('email');
			$user->password = Hash::make(Input::get('password'));
			$user->save();

			return Redirect::to('login')->with('message', 'Merci pour ton incription!');
		} else
			return Redirect::back()->with('message', 'Une erreur est apparue')->withErrors($validator)->withInput();
	}
}


text:
namespace Envoy {
namespace Extensions {
namespace ListenerFilters {
namespace OriginalDst {

Network::Address::InstanceConstSharedPtr OriginalDstFilter::getOriginalDst(Network::Socket& sock) {
  return Network::Utility::getOriginalDst(sock);
}

Network::FilterStatus OriginalDstFilter::onAccept(Network::ListenerFilterCallbacks& cb) {
  ENVOY_LOG(debug, "original_dst: New connection accepted");
  Network::ConnectionSocket& socket = cb.socket();

  if (socket.addressType() == Network::Address::Type::Ip) {
    Network::Address::InstanceConstSharedPtr original_local_address = getOriginalDst(socket);

    // A listener that has the use_original_dst flag set to true can still receive
    // connections that are NOT redirected using iptables. If a connection was not redirected,
    // the address returned by getOriginalDst() matches the local address of the new socket.
    // In this case the listener handles the connection directly and does not hand it off.
    if (original_local_address) {
      // Restore the local address to the original one.
      socket.restoreLocalAddress(original_local_address);
    }
  }

  return Network::FilterStatus::Continue;
}

} // namespace OriginalDst
} // namespace ListenerFilters
} // namespace Extensions
} // namespace Envoy


text:
package ca.uhn.fhir.rest.server;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.TokenAndListParam;
import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.util.TestUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.HumanName;
import org.hl7.fhir.r4.model.Patient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class MultitenancyR4Test {

	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MultitenancyR4Test.class);
	private static CloseableHttpClient ourClient;
	private static FhirContext ourCtx = FhirContext.forR4();
	private static TokenAndListParam ourIdentifiers;
	private static String ourLastMethod;
	private static int ourPort;
	private static Server ourServer;
	private static String ourLastTenantId;

	@BeforeEach
	public void before() {
		ourLastMethod = null;
		ourIdentifiers = null;
		ourLastTenantId = null;
	}

	@Test
	public void testUrlBaseStrategy() throws Exception {
		ourServer = new Server(0);

		DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();

		ServletHandler proxyHandler = new ServletHandler();
		RestfulServer servlet = new RestfulServer(ourCtx);
		servlet.setDefaultResponseEncoding(EncodingEnum.JSON);
		servlet.setPagingProvider(new FifoMemoryPagingProvider(10));
		servlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());

		servlet.setResourceProviders(patientProvider);
		ServletHolder servletHolder = new ServletHolder(servlet);
		proxyHandler.addServletWithMapping(servletHolder, "/*");
		ourServer.setHandler(proxyHandler);
		JettyUtil.startServer(ourServer);
        ourPort = JettyUtil.getPortForStartedServer(ourServer);

		HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANT2/Patient?identifier=foo%7Cbar");
		CloseableHttpResponse status = ourClient.execute(httpGet);
		try {
			String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
			assertEquals(200, status.getStatusLine().getStatusCode());
			assertEquals("search", ourLastMethod);
			assertEquals("TENANT2", ourLastTenantId);
			assertEquals("foo", ourIdentifiers.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getSystem());
			assertEquals("bar", ourIdentifiers.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue());

			Bundle resp = ourCtx.newJsonParser().parseResource(Bundle.class, responseContent);
			ourLog.debug(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp));

			assertEquals("http://localhost:" + ourPort + "/TENANT2/Patient?identifier=foo%7Cbar", resp.getLink("self").getUrl());
			assertEquals("http://localhost:" + ourPort + "/TENANT2/Patient/0", resp.getEntry().get(0).getFullUrl());
			assertEquals("http://localhost:"+ourPort+"/TENANT2/Patient/0", resp.getEntry().get(0).getResource().getId());
			assertThat(resp.getLink("next").getUrl(), startsWith("http://localhost:"+ourPort+"/TENANT2?_getpages="));

		} finally {
			IOUtils.closeQuietly(status.getEntity().getContent());
		}

		// GET the root
		httpGet = new HttpGet("http://localhost:" + ourPort + "/");
		status = ourClient.execute(httpGet);
		try {
			String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
			assertEquals(400, status.getStatusLine().getStatusCode());
			assertThat(responseContent, containsString("\"diagnostics\":\"This is the base URL of a multitenant FHIR server. Unable to handle this request, as it does not contain a tenant ID.\""));
		} finally {
			IOUtils.closeQuietly(status.getEntity().getContent());
		}
	}

	@AfterAll
	public static void afterClassClearContext() throws Exception {
		JettyUtil.closeServer(ourServer);
		TestUtil.randomizeLocaleAndTimezone();
	}

	@BeforeAll
	public static void beforeClass() {
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
		HttpClientBuilder builder = HttpClientBuilder.create();
		builder.setConnectionManager(connectionManager);
		ourClient = builder.build();

	}

	public static class DummyPatientResourceProvider implements IResourceProvider {

		@Override
		public Class<? extends IBaseResource> getResourceType() {
			return Patient.class;
		}

		@SuppressWarnings("rawtypes")
		@Search()
		public List search(
			RequestDetails theRequestDetails,
			@RequiredParam(name = Patient.SP_IDENTIFIER) TokenAndListParam theIdentifiers) {
			ourLastMethod = "search";
			ourIdentifiers = theIdentifiers;
			ourLastTenantId = theRequestDetails.getTenantId();
			ArrayList<Patient> retVal = new ArrayList<>();

			for (int i = 0; i < 200; i++) {
				Patient patient = new Patient();
				patient.addName(new HumanName().setFamily("FAMILY"));
				patient.setActive(true);
				patient.getIdElement().setValue("Patient/" + i);
				retVal.add(patient);
			}
			return retVal;
		}

	}

}


text:
@implementation UIFont (PTUIKitAddition)
+ (instancetype)fontWithCTFontRef:(CTFontRef)ctFont
{
   CFStringRef fontName = CTFontCopyFullName(ctFont);
   CGFloat fontSize = CTFontGetSize(ctFont);

   UIFont *ret = [UIFont fontWithName:(__bridge_transfer NSString *) fontName size:fontSize];
   return ret;
}

@end

CTFontRef CTFontFromUIFont(UIFont *font) {
   CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) font.fontName,
         font.pointSize,
         NULL);
   return ctFont;
}


text:
package org.elasticsoftware.elasticactors.spring;

import org.elasticsoftware.elasticactors.ServiceActor;
import org.elasticsoftware.elasticactors.runtime.ScannerHelper;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.core.type.filter.AnnotationTypeFilter;

/**
 * @author Joost van de Wijgerd
 */
public final class ActorSystemApplicationContextInitializer implements ApplicationContextInitializer<AnnotationConfigWebApplicationContext> {
    @Override
    public void initialize(AnnotationConfigWebApplicationContext applicationContext) {
        // ensure the EA annotations are scanned
        applicationContext.addIncludeFilters(new AnnotationTypeFilter(ServiceActor.class));
        // generate correct names for ServiceActor annotated actors
        applicationContext.setBeanNameGenerator(new ActorAnnotationBeanNameGenerator());
        // add all the elastic actors base packages to the scan configuration
        applicationContext.scan(ScannerHelper.findBasePackagesOnClasspath(applicationContext.getClassLoader()));
    }
}


text:
from .MidiOutStream import MidiOutStream

class MidiToText(MidiOutStream):

    """
    This class renders a midi file as text. It is mostly used for debugging
    """

    #############################
    # channel events

    def channel_message(self, message_type, channel, data):
        """The default event handler for channel messages"""
        print('message_type:%X, channel:%X, data size:%X' % (message_type, channel, len(data)))

    def note_on(self, channel=0, note=0x40, velocity=0x40):
        print('note_on  - ch:%02X,  note:%02X,  vel:%02X time:%s' % (channel, note, velocity, self.rel_time()))

    def note_off(self, channel=0, note=0x40, velocity=0x40):
        print('note_off - ch:%02X,  note:%02X,  vel:%02X time:%s' % (channel, note, velocity, self.rel_time()))

    def aftertouch(self, channel=0, note=0x40, velocity=0x40):
        print('aftertouch', channel, note, velocity)

    def continuous_controller(self, channel, controller, value):
        print('controller - ch: %02X, cont: #%02X, value: %02X' % (channel, controller, value))

    def patch_change(self, channel, patch):
        print('patch_change - ch:%02X, patch:%02X' % (channel, patch))

    def channel_pressure(self, channel, pressure):
        print('channel_pressure', channel, pressure)

    def pitch_bend(self, channel, value):
        print('pitch_bend ch:%s, value:%s' % (channel, value))

    #####################
    ## Common events

    def system_exclusive(self, data):
        print('system_exclusive - data size: %s' % len(date))

    def song_position_pointer(self, value):
        print('song_position_pointer: %s' % value)

    def song_select(self, songNumber):
        print('song_select: %s' % songNumber)

    def tuning_request(self):
        print('tuning_request')

    def midi_time_code(self, msg_type, values):
        print('midi_time_code - msg_type: %s, values: %s' % (msg_type, values))

    #########################
    # header does not really belong here. But anyhoo!!!

    def header(self, format=0, nTracks=1, division=96):
        print('format: %s, nTracks: %s, division: %s' % (format, nTracks, division))
        print('----------------------------------')
        print('')

    def eof(self):
        print('End of file')

    def start_of_track(self, n_track=0):
        print('Start - track #%s' % n_track)

    def end_of_track(self):
        print('End of track')
        print('')

    ###############
    # sysex event

    def sysex_event(self, data):
        print('sysex_event - datasize: %X' % len(data))

    #####################
    ## meta events

    def meta_event(self, meta_type, data):
        print('undefined_meta_event:', meta_type, len(data))

    def sequence_number(self, value):
        print('sequence_number', number)

    def text(self, text):
        print('text', text)

    def copyright(self, text):
        print('copyright', text)

    def sequence_name(self, text):
        print('sequence_name:', text)

    def instrument_name(self, text):
        print('instrument_name:', text)

    def lyric(self, text):
        print('lyric', text)

    def marker(self, text):
        print('marker', text)

    def cuepoint(self, text):
        print('cuepoint', text)

    def midi_ch_prefix(self, channel):
        print('midi_ch_prefix', channel)

    def midi_port(self, value):
        print('midi_port:', value)

    def tempo(self, value):
        print('tempo:', value)

    def smtp_offset(self, hour, minute, second, frame, framePart):
        print('smtp_offset', hour, minute, second, frame, framePart)

    def time_signature(self, nn, dd, cc, bb):
        print('time_signature:', nn, dd, cc, bb)

    def key_signature(self, sf, mi):
        print('key_signature', sf, mi)

    def sequencer_specific(self, data):
        print('sequencer_specific', len(data))

if __name__ == '__main__':

    # get data
    test_file = 'test/midifiles/minimal.mid'
    f = open(test_file, 'rb')

    # do parsing
    from .MidiInFile import MidiInFile
    midiIn = MidiInFile(MidiToText(), f)
    midiIn.read()
    f.close()