text:
import datetime
import json
import os
import random
import re
import string
import unittest

from mock import patch, Mock

from six import string_types

import payjp

NOW = datetime.datetime.now()

DUMMY_CARD = {
    'number': '4242424242424242',
    'exp_month': NOW.month,
    'exp_year': NOW.year + 4
}

DUMMY_CHARGE = {
    'amount': 100,
    'currency': 'jpy',
    'card': DUMMY_CARD
}

DUMMY_PLAN = {
    'amount': 2000,
    'interval': 'month',
    'name': 'Amazing Gold Plan',
    'currency': 'jpy',
    'id': ('payjp-test-gold-' +
           ''.join(random.choice(string.ascii_lowercase) for x in range(10)))
}

DUMMY_TRANSFER = {
    'amount': 400,
    'currency': 'jpy',
    'recipient': 'self'
}

SAMPLE_INVOICE = json.loads("""
{
  "amount_due": 1305,
  "attempt_count": 0,
  "attempted": true,
  "charge": "ch_wajkQ5aDTzFs5v",
  "closed": true,
  "customer": "cus_osllUe2f1BzrRT",
  "date": 1338238728,
  "discount": null,
  "ending_balance": 0,
  "id": "in_t9mHb2hpK7mml1",
  "livemode": false,
  "next_payment_attempt": null,
  "object": "invoice",
  "paid": true,
  "period_end": 1338238728,
  "period_start": 1338238716,
  "starting_balance": -8695,
  "subtotal": 10000,
  "total": 10000,
  "lines": {
    "invoiceitems": [],
    "prorations": [],
    "subscriptions": [
      {
        "plan": {
          "interval": "month",
          "object": "plan",
          "identifier": "expensive",
          "currency": "jpy",
          "livemode": false,
          "amount": 10000,
          "name": "Expensive Plan",
          "trial_period_days": null,
          "id": "expensive"
        },
        "period": {
          "end": 1340917128,
          "start": 1338238728
        },
        "amount": 10000
      }
    ]
  }
}
""")

class PayjpTestCase(unittest.TestCase):
    RESTORE_ATTRIBUTES = ('api_version', 'api_key')

    def setUp(self):
        super(PayjpTestCase, self).setUp()

        self._payjp_original_attributes = {}

        for attr in self.RESTORE_ATTRIBUTES:
            self._payjp_original_attributes[attr] = getattr(payjp, attr)

        api_base = os.environ.get('PAYJP_API_BASE')
        if api_base:
            payjp.api_base = api_base
        payjp.api_key = os.environ.get(
            'PAYJP_API_KEY', 'sk_test_c62fade9d045b54cd76d7036')

    def tearDown(self):
        super(PayjpTestCase, self).tearDown()

        for attr in self.RESTORE_ATTRIBUTES:
            setattr(payjp, attr, self._payjp_original_attributes[attr])

    # Python < 2.7 compatibility
    def assertRaisesRegexp(self, exception, regexp, callable, *args, **kwargs):
        try:
            callable(*args, **kwargs)
        except exception as err:
            if regexp is None:
                return True

            if isinstance(regexp, string_types):
                regexp = re.compile(regexp)
            if not regexp.search(str(err)):
                raise self.failureException('"%s" does not match "%s"' %
                                            (regexp.pattern, str(err)))
        else:
            raise self.failureException(
                '%s was not raised' % (exception.__name__,))

class PayjpUnitTestCase(PayjpTestCase):
    REQUEST_LIBRARIES = ['requests']

    def setUp(self):
        super(PayjpUnitTestCase, self).setUp()

        self.request_patchers = {}
        self.request_mocks = {}
        for lib in self.REQUEST_LIBRARIES:
            patcher = patch("payjp.http_client.%s" % (lib,))

            self.request_mocks[lib] = patcher.start()
            self.request_patchers[lib] = patcher

    def tearDown(self):
        super(PayjpUnitTestCase, self).tearDown()

        for patcher in self.request_patchers.values():
            patcher.stop()

class PayjpApiTestCase(PayjpTestCase):

    def setUp(self):
        super(PayjpApiTestCase, self).setUp()

        self.requestor_patcher = patch('payjp.api_requestor.APIRequestor')
        requestor_class_mock = self.requestor_patcher.start()
        self.requestor_mock = requestor_class_mock.return_value

    def tearDown(self):
        super(PayjpApiTestCase, self).tearDown()

        self.requestor_patcher.stop()

    def mock_response(self, res):
        self.requestor_mock.request = Mock(return_value=(res, 'reskey'))

class MyResource(payjp.resource.APIResource):
    pass

class MyListable(payjp.resource.ListableAPIResource):
    pass

class MyCreatable(payjp.resource.CreateableAPIResource):
    pass

class MyUpdateable(payjp.resource.UpdateableAPIResource):
    pass

class MyDeletable(payjp.resource.DeletableAPIResource):
    pass

class MyComposite(payjp.resource.ListableAPIResource,
                  payjp.resource.CreateableAPIResource,
                  payjp.resource.UpdateableAPIResource,
                  payjp.resource.DeletableAPIResource):
    pass


text:
#ifndef MICROPY_INCLUDED_POWERPC_UNISTD_H
#define MICROPY_INCLUDED_POWERPC_UNISTD_H

// powerpc gcc compiler doesn't seem to have unistd.h file

#define SEEK_SET 0
#define SEEK_CUR 1

typedef int ssize_t;

#endif // MICROPY_INCLUDED_POWERPC_UNISTD_H

redpajama_set_name: RedPajamaGithub


text:
import enso.providers

__cairoImpl = enso.providers.getInterface( "cairo" )

globals().update( __cairoImpl.__dict__ )


text:
<!DOCTYPE html>

  <meta charset=utf-8>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="apple-touch-icon" sizes="57x57" href="/assets/favicons/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/assets/favicons/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/assets/favicons/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/assets/favicons/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/assets/favicons/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/assets/favicons/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/assets/favicons/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/assets/favicons/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/assets/favicons/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-194x194.png" sizes="194x194">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/assets/favicons/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/assets/favicons/manifest.json">
<link rel="mask-icon" href="/assets/favicons/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#3498db">
<meta name="msapplication-TileImage" content="/assets/favicons/mstile-144x144.png">
<meta name="theme-color" content="#3498db">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="description" content="You are likely to find at some point that you need to work on a department system remotely. In this tutorial, we'll explore connecting to Snowy, the departmental server.If you're familiar with SSH, here are the details you need:Snowy SSH details  Server: snowy.cs.bris.ac.uk  Username: your univer...">

  <meta property="og:type" content="website">
<meta property="og:title" content="SSH and Snowy - CSS Bristol">
<meta property="og:description" content="You are likely to find at some point that you need to work on a department system remotely. In this tutorial, we'll explore connecting to Snowy, the departmental server. If you're familiar with SSH, here are the details you need: Snowy SSH details Server: snowy.cs.bris.ac.uk Username: your university username, e.g....">
<meta property="og:image" content="https://cssbristol.co.uk/assets/images/core/og-image.png" />
<meta property="og:url" content="https://cssbristol.co.uk/tutorials/ssh-into-snowy/">

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="SSH and Snowy - CSS Bristol">
<meta name="twitter:description" content="You are likely to find at some point that you need to work on a department system remotely. In this tutorial, we'll explore connecting to Snowy, the departmental server. If you're familiar with SSH, here are the details you need: Snowy SSH details Server: snowy.cs.bris.ac.uk Username: your university username, e.g....">
<meta name="twitter:image" content="https://cssbristol.co.uk/assets/images/core/og-image.png">
<meta name="twitter:site" content="@cssbristol">

  <title>SSH and Snowy - CSS Bristol</title>

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400;0,700;0,800;1,400&display=swap" />

  <link rel="stylesheet" href="/assets/css/site.css" />
  <link rel="canonical" href="https://www.cssbristol.co.uk/tutorials/ssh-into-snowy/" />

  <link rel="prefetch" href="/assets/images/core/header-bg-01_70000.jpg">
  <link rel="prefetch" href="/assets/images/core/header-bg-02_70000.jpg">
  <link rel="prefetch" href="/assets/images/core/header-bg-03_70000.jpg">
  <link rel="prefetch" href="/assets/images/core/header-bg-04_70000.jpg">
  <link rel="prefetch" href="/assets/images/core/header-bg-05.jpg">

      University of Bristol Computer Science Society

About

Contact

Events

Freshers

Jobs

Sponsor us

Tutorials

Wellbeing

SSH and Snowy

        Ross Gardiner on
        <time datetime="2016-05-19T20:42:09+01:00">May 19, 2016</time>

You are likely to find at some point that you need to work on a department system remotely. In this tutorial, we'll explore connecting to Snowy, the departmental server.

If you're familiar with SSH, here are the details you need:

Snowy SSH details

Server: snowy.cs.bris.ac.uk

Username: your university username, e.g. ab12345

Password: your university password

SSH into lab machines

All the lab machines in MVB 2.11 are available when using snowy as
a jump box, this involves first connecting to snowy then to the lab machine in
a chain like fashion making use of SSH's ProxyCommand. This step can be
skipped if you are using the university VPN.

Lab machine addresses: it<ID>.wks.bris.ac.uk where ID is in the following range:

it075638.wks.bris.ac.uk – it075906.wks.bris.ac.uk

SSH

Mac/Linux

Open a Terminal/Console window, and type the following command:

ssh ab12345@snowy.cs.bris.ac.uk

(where ab12345 is replaced by your username)

Hit return, and wait for the password prompt. Type in your password and press return again. You are now logged in.

Windows

PuTTY is the easiest solution for SSH on Windows. You can either download the installer (putty-*.**-installer.msi) or putty.exe, which will run standalone.

Open PuTTY, and enter snowy.cs.bris.ac.uk in the 'Host Name (or IP address)' field. Make sure the 'Port' is set to 22. Click 'Open'. If you are asked to trust a signature, click yes. You will be greeted by a prompt that says:

login as:

Type your university username and press return. Then type your password and press return.

From a terminal

You will probably end up working in a terminal a lot of the time, even on Windows. Unfortunately, the set of text-based utilities that comes with Windows is rather lacking. Several efforts exist to make these available on Windows:

Bash on Windows on Ubuntu - an official Microsoft project that lets you run Linux binaries natively on Windows.

MSYS2

Babun

Cygwin

Figuring out how to get one of these to work is a good exercise for any first year CS student.

Getting a graphical environment

Snowy (like most current Linux systems) supports a feature called X Forwarding. This lets you run graphical applications remotely but use them as if they were running natively(-ish) on your desktop.

Mac/Linux

To enable X Forwarding, add the -X flag when running OpenSSH:

ssh ab12345@snowy.cs.bris.ac.uk -X

Once logged in, you will be able to launch utilities like nautilus (the GNOME file manager) and gedit (the GNOME text editor).

Windows

Windows requires additional steps for X Forwading. Firstly, you need to install Ximg, this allows graphical interface on server to be displayed. If you are using putty, all you should have to do tick the Enable X11 forewarding box under Connections\SSH\X11 in your putty connection.
As for Bash on Windows on Ubuntu, Cygwin… etc, you need to add -X  flag when running OpenSSH like in Mac/Linux:

ssh ab12345@snowy.cs.bris.ac.uk -X

Remote Desktop (NoMachine)

If you would like to access lab machines or university softwares at home, then SSH with X11 forwarding might not be a good option. This is because X11
forwarding does not compress data, so the graphical interface will be very slow.  NoMachine client allows graphical remote desktop with less lag. The server snowy can be accessed with NoMachine, if you desire to use a lab machine, you can still SSH into them using snowy with or without X11 forwarding.

Copying files with scp

Mac/Linux

To copy from your computer to Snowy:

scp sourcefile ab12345@snowy.cs.bris.ac.uk:targetfile

For example, scp ~/main.c ab12345@snowy.cs.bris.ac.uk:~/main.c.

To copy from Snowy to your computer:

scp ab12345@snowy.cs.bris.ac.uk:sourcefile targetfile

For example, scp ab12345@snowy.cs.bris.ac.uk:~/main.c ~/main.c

Windows

On Windows, the easiest graphical method to transfer files is to use SFTP. There are many SFTP clients available. FileZilla is free and works nicely. Use the following settings:

Host: snowy.cs.bris.ac.uk

Username: university username

Password: university password

Port: 22

In a terminal

If you want to do this from the terminal, PuTTY comes with a utility called psftp. Alternatively, if you have something like cygwin installed, you probably have access to scp already.

Passwordless login

If you get tired of having to enter your password every time you connect to Snowy, don't worry! You can create an SSH keypair to verify your identity automatically: Snowy has a copy of your public key, and anyone with access to your private key (i.e. only you) can use it to automatically authenticate.

Mac/Linux

Open a terminal and enter the following:

ssh-keygen -t rsa

The tool will walk you through the process of creating a key. By default, the keypair is saved to the .ssh directory in your home directory - for example /home/myname/.ssh/. The private key is normally called id_rsa, the public key id_rsa.pub - though you can change these if you want. You will be asked to provide a passphrase. This protects your key from viruses, theft etc., so choose something strong.

Once your key is generated, create the .ssh folder on Snowy:

ssh ab12345@snowy.cs.bris.ac.uk 'mkdir -p .ssh'

Then append your public key to the list of authorised keys:

cat ~/.ssh/id_rsa.pub | ssh ab12345@snowy.cs.bris.ac.uk 'cat >> .ssh/authorized_keys'

Windows

PuTTY comes with a tool called PuTTYgen for creating new SSH keys. If you have something like cygwin installed, ssh-keygen is probably available in your shell.

You can copy the public key across using FileZilla, as described above.

Example SSH config

An example SSH config is given below:

# ~/.ssh/config

Host *
    ForwardAgent yes
    ForwardX11 yes
    ForwardX11Trusted yes

#######################################
#         University machines         #
#######################################
# University of Bristol machines
# See http://www.bristol.ac.uk/it-services/locations/zones/zonee/cosc/remote-access

Host snowy
    Hostname snowy.cs.bris.ac.uk
    Port 22
    User <USERNAME>
    IdentityFile ~/.ssh/id_rsa
    ForwardX11 no
    ForwardX11Trusted no

# To use only for Cadence tools
Host frosty
    Hostname frosty.fen.bris.ac.uk
    Port 22
    User <USERNAME>
    IdentityFile ~/.ssh/id_rsa
    ProxyCommand ssh snowy nc %h %p 2> /dev/null

# CS lab machines live on the follow ranges
#
#   - 075638--075906
#

Host cs-desktop-01
    HostName it075638.users.bris.ac.uk
    User <USERNAME>
    ProxyCommand ssh snowy nc %h %p 2> /dev/null

Host cs-desktop-02
    HostName it075639.users.bris.ac.uk
    User <USERNAME>
    ProxyCommand ssh snowy nc %h %p 2> /dev/null

Host cs-desktop-03
    HostName it075640.users.bris.ac.uk
    User <USERNAME>
    ProxyCommand ssh snowy nc %h %p 2> /dev/null

Resources

IT Services: Remote Access

Feedback

Any issues with this tutorial? Submit an issue or a pull request and we'll get it sorted out right away.

Proudly sponsored by

      Learn more about working with us.

  © University of Bristol Computer Science Society

        About

        Contact

        Events

        Freshers

        Jobs

        Sponsor us

        Tutorials

        Wellbeing


text:
self.addEventListener('message', function(e) {
    var data = e.data;
    var workerId = data.id;
    var start = data.start;
    var end = data.end;
    var sum = 0;
    var percent = 0;
    var current = 1;

    //console.log(workerId+":"+current)

    // Optimizing the algorithm

    for(var i=start; i < end; i++){
        sum += i;
        percent = Math.floor((i+1-start) / (end-start) * 100);

        if(percent == current){
            self.postMessage({"id":workerId,'percent': percent, 'msg':''});
            current++;
        }
    }
    self.postMessage({"id":workerId ,'sum': sum});
}, false);


text:
module Blogr
  module PostsHelper
  end
end


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';

import { setNavigationVisibility } from '../Navigation/reducer';
import './ViewInfo.scss';

// CRA does not support importing text files
// this is offered as a solution here
// (https://github.com/facebook/create-react-app/issues/3722)
const markdown = raw('./content_fi.md');

class InfoView extends Component {
  static propTypes = {
    setNavigationVisibility: PropTypes.func
  };

  static BODY_CLASS = 'helerm-info-view';

  componentDidMount() {
    if (document.body) {
      document.body.className = document.body.className + InfoView.BODY_CLASS;
    }
    this.props.setNavigationVisibility(true);
  }

  componentWillUnmount() {
    if (document.body) {
      document.body.className = document.body.className.replace(
        InfoView.BODY_CLASS,
        ''
      );
    }
  }

  render() {
    const classname =
      this.props.match.path === '/info' ? 'info-view-center' : 'info-view';
    return (
      <div className={classname}>
        <ReactMarkdown plugins={[gfm]} children={markdown} />
      </div>
    );
  }
}

InfoView.propTypes = {};

const mapStateToProps = null;

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(
    {
      setNavigationVisibility
    },
    dispatch
  );

export default withRouter(
  connect(mapStateToProps, mapDispatchToProps)(InfoView)
);


text:
package org.wildfly.swarm.health;

import org.junit.Assert;
import org.junit.Test;
import org.wildfly.swarm.microprofile.health.runtime.HealthAnnotationProcessor;
import org.wildfly.swarm.microprofile.health.runtime.HttpContexts;

/**
 * @author Heiko Braun
 */
public class ParserTest {

    // see https://issues.jboss.org/browse/SWARM-505
    @Test
    public void testAttributes() {

        HealthStatus healthStatus = HealthStatus.named("test")
                .up()
                .withAttribute("a", "b")
                .withAttribute("c", "d");

        String message = healthStatus.getMessage().get();
        Assert.assertTrue("Expected a", message.contains("a"));
        Assert.assertTrue("Expected c", message.contains("c"));
        System.out.println(message);
    }

    @Test
    public void testPathStructures() {
        StringBuilder sb = new StringBuilder();
        HealthAnnotationProcessor.safeAppend(sb, "jboss-web");
        HealthAnnotationProcessor.safeAppend(sb, "/webcontext");
        HealthAnnotationProcessor.safeAppend(sb, "/app");
        Assert.assertEquals("/jboss-web/webcontext/app", sb.toString());

        // --

        sb = new StringBuilder();
        HealthAnnotationProcessor.safeAppend(sb, "jboss-web/");
        HealthAnnotationProcessor.safeAppend(sb, "/webcontext");
        HealthAnnotationProcessor.safeAppend(sb, "app");
        Assert.assertEquals("/jboss-web/webcontext/app", sb.toString());

        // --

        sb = new StringBuilder();
        HealthAnnotationProcessor.safeAppend(sb, "jboss-web");
        HealthAnnotationProcessor.safeAppend(sb, "webcontext");
        HealthAnnotationProcessor.safeAppend(sb, "app");
        Assert.assertEquals("/jboss-web/webcontext/app", sb.toString());

        // --

        sb = new StringBuilder();
        HealthAnnotationProcessor.safeAppend(sb, "jboss-web/");
        HealthAnnotationProcessor.safeAppend(sb, "webcontext/");
        HealthAnnotationProcessor.safeAppend(sb, "app/");
        Assert.assertEquals("/jboss-web/webcontext/app", sb.toString());

        // --

        sb = new StringBuilder();
        HealthAnnotationProcessor.safeAppend(sb, "/jboss-web/");
        HealthAnnotationProcessor.safeAppend(sb, "/webcontext/");
        HealthAnnotationProcessor.safeAppend(sb, "/app/");
        Assert.assertEquals("/jboss-web/webcontext/app", sb.toString());

    }

    @Test
    public void testJsonEncoding() {
        org.eclipse.microprofile.health.HealthCheckResponse healthStatus = org.eclipse.microprofile.health.HealthCheckResponse
                .named("test")
                .withData("a", "b")
                .withData("c", "d")
                .up()
                .build();

        String s = HttpContexts.toJson(healthStatus);
        System.out.println(s);
    }
}


text:
<?php

// Call Zend_Dojo_View_Helper_BorderContainerTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Dojo_View_Helper_BorderContainerTest::main");
}

/** Zend_Dojo_View_Helper_BorderContainer */
require_once 'Zend/Dojo/View/Helper/BorderContainer.php';

/** Zend_View */
require_once 'Zend/View.php';

/** Zend_Registry */
require_once 'Zend/Registry.php';

/** Zend_Dojo_View_Helper_Dojo */
require_once 'Zend/Dojo/View/Helper/Dojo.php';

/**
 * Test class for Zend_Dojo_View_Helper_BorderContainer.
 *
 * @category   Zend
 * @package    Zend_Dojo
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Dojo
 * @group      Zend_Dojo_View
 */
class Zend_Dojo_View_Helper_BorderContainerTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Zend_Dojo_View_Helper_BorderContainerTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        Zend_Registry::_unsetInstance();
        Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

        $this->view   = $this->getView();
        $this->helper = new Zend_Dojo_View_Helper_BorderContainer();
        $this->helper->setView($this->view);
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }

    public function getView()
    {
        require_once 'Zend/View.php';
        $view = new Zend_View();
        $view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
        return $view;
    }

    public function getContainer()
    {
        $html = '';
        foreach (array('top', 'bottom', 'center', 'left', 'right') as $pane) {
            $id      = $pane . 'Pane';
            $content = 'This is the content of pane ' . $pane;
            $html   .= $this->view->contentPane($id, $content, array('region' => $pane));
        }
        return $this->helper->borderContainer('container', $html, array('design' => 'headline'));
    }

    public function testShouldAllowDeclarativeDijitCreation()
    {
        $html = $this->getContainer();
        $this->assertRegexp('/<div[^>]*(dojoType="dijit.layout.BorderContainer")/', $html, $html);
    }

    public function testShouldAllowProgrammaticDijitCreation()
    {
        Zend_Dojo_View_Helper_Dojo::setUseProgrammatic();
        $html = $this->getContainer();
        $this->assertNotRegexp('/<div[^>]*(dojoType="dijit.layout.BorderContainer")/', $html);
        $this->assertNotNull($this->view->dojo()->getDijit('container'));
    }

    /**
     * @group ZF-4664
     */
    public function testMultipleCallsToBorderContainerShouldNotCreateMultipleStyleEntries()
    {
        $this->getContainer();
        $this->getContainer();
        $style  = 'html, body { height: 100%; width: 100%; margin: 0; padding: 0; }';
        $styles = $this->helper->view->headStyle()->toString();
        $this->assertEquals(1, substr_count($styles, $style), $styles);
    }
}

// Call Zend_Dojo_View_Helper_BorderContainerTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Dojo_View_Helper_BorderContainerTest::main") {
    Zend_Dojo_View_Helper_BorderContainerTest::main();
}


text:
/*************************************************************************/
/*  editor_performance_profiler.cpp                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "editor_performance_profiler.h"

#include "editor/editor_property_name_processor.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "main/performance.h"

EditorPerformanceProfiler::Monitor::Monitor() {}

EditorPerformanceProfiler::Monitor::Monitor(String p_name, String p_base, int p_frame_index, Performance::MonitorType p_type, TreeItem *p_item) {
	type = p_type;
	item = p_item;
	frame_index = p_frame_index;
	name = p_name;
	base = p_base;
}

void EditorPerformanceProfiler::Monitor::update_value(float p_value) {
	ERR_FAIL_COND(!item);
	String label = EditorPerformanceProfiler::_create_label(p_value, type);
	String tooltip = label;
	switch (type) {
		case Performance::MONITOR_TYPE_MEMORY: {
			tooltip = label;
		} break;
		case Performance::MONITOR_TYPE_TIME: {
			tooltip = label;
		} break;
		default: {
			tooltip += " " + item->get_text(0);
		} break;
	}
	item->set_text(1, label);
	item->set_tooltip_text(1, tooltip);

	if (p_value > max) {
		max = p_value;
	}
}

void EditorPerformanceProfiler::Monitor::reset() {
	history.clear();
	max = 0.0f;
	if (item) {
		item->set_text(1, "");
		item->set_tooltip_text(1, "");
	}
}

String EditorPerformanceProfiler::_create_label(float p_value, Performance::MonitorType p_type) {
	switch (p_type) {
		case Performance::MONITOR_TYPE_MEMORY: {
			return String::humanize_size(p_value);
		}
		case Performance::MONITOR_TYPE_TIME: {
			return TS->format_number(rtos(p_value * 1000).pad_decimals(2)) + " " + RTR("ms");
		}
		default: {
			return TS->format_number(rtos(p_value));
		}
	}
}

void EditorPerformanceProfiler::_monitor_select() {
	monitor_draw->queue_redraw();
}

void EditorPerformanceProfiler::_monitor_draw() {
	Vector<StringName> active;
	for (const KeyValue<StringName, Monitor> &E : monitors) {
		if (E.value.item->is_checked(0)) {
			active.push_back(E.key);
		}
	}

	if (active.is_empty()) {
		info_message->show();
		return;
	}

	info_message->hide();

	Ref<StyleBox> graph_style_box = get_theme_stylebox(SNAME("normal"), SNAME("TextEdit"));
	Ref<Font> graph_font = get_theme_font(SNAME("font"), SNAME("TextEdit"));
	int font_size = get_theme_font_size(SNAME("font_size"), SNAME("TextEdit"));

	int columns = int(Math::ceil(Math::sqrt(float(active.size()))));
	int rows = int(Math::ceil(float(active.size()) / float(columns)));
	if (active.size() == 1) {
		rows = 1;
	}
	Size2i cell_size = Size2i(monitor_draw->get_size()) / Size2i(columns, rows);
	float spacing = float(POINT_SEPARATION) / float(columns);
	float value_multiplier = EditorSettings::get_singleton()->is_dark_theme() ? 1.4f : 0.55f;
	float hue_shift = 1.0f / float(monitors.size());

	for (int i = 0; i < active.size(); i++) {
		Monitor &current = monitors[active[i]];
		Rect2i rect(Point2i(i % columns, i / columns) * cell_size + Point2i(MARGIN, MARGIN), cell_size - Point2i(MARGIN, MARGIN) * 2);
		monitor_draw->draw_style_box(graph_style_box, rect);

		rect.position += graph_style_box->get_offset();
		rect.size -= graph_style_box->get_minimum_size();
		Color draw_color = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
		draw_color.set_hsv(Math::fmod(hue_shift * float(current.frame_index), 0.9f), draw_color.get_s() * 0.9f, draw_color.get_v() * value_multiplier, 0.6f);
		monitor_draw->draw_string(graph_font, rect.position + Point2(0, graph_font->get_ascent(font_size)), current.item->get_text(0), HORIZONTAL_ALIGNMENT_LEFT, rect.size.x, font_size, draw_color);

		draw_color.a = 0.9f;
		float value_position = rect.size.width - graph_font->get_string_size(current.item->get_text(1), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).width;
		if (value_position < 0) {
			value_position = 0;
		}
		monitor_draw->draw_string(graph_font, rect.position + Point2(value_position, graph_font->get_ascent(font_size)), current.item->get_text(1), HORIZONTAL_ALIGNMENT_LEFT, rect.size.x, font_size, draw_color);

		rect.position.y += graph_font->get_height(font_size);
		rect.size.height -= graph_font->get_height(font_size);

		int line_count = rect.size.height / (graph_font->get_height(font_size) * 2);
		if (line_count > 5) {
			line_count = 5;
		}
		if (line_count > 0) {
			Color horizontal_line_color;
			horizontal_line_color.set_hsv(draw_color.get_h(), draw_color.get_s() * 0.5f, draw_color.get_v() * 0.5f, 0.3f);
			monitor_draw->draw_line(rect.position, rect.position + Vector2(rect.size.width, 0), horizontal_line_color, Math::round(EDSCALE));
			monitor_draw->draw_string(graph_font, rect.position + Vector2(0, graph_font->get_ascent(font_size)), _create_label(current.max, current.type), HORIZONTAL_ALIGNMENT_LEFT, rect.size.width, font_size, horizontal_line_color);

			for (int j = 0; j < line_count; j++) {
				Vector2 y_offset = Vector2(0, rect.size.height * (1.0f - float(j) / float(line_count)));
				monitor_draw->draw_line(rect.position + y_offset, rect.position + Vector2(rect.size.width, 0) + y_offset, horizontal_line_color, Math::round(EDSCALE));
				monitor_draw->draw_string(graph_font, rect.position - Vector2(0, graph_font->get_descent(font_size)) + y_offset, _create_label(current.max * float(j) / float(line_count), current.type), HORIZONTAL_ALIGNMENT_LEFT, rect.size.width, font_size, horizontal_line_color);
			}
		}

		float from = rect.size.width;
		float prev = -1.0f;
		int count = 0;
		List<float>::Element *e = current.history.front();

		while (from >= 0 && e) {
			float m = current.max;
			float h2 = 0;
			if (m != 0) {
				h2 = (e->get() / m);
			}
			h2 = (1.0f - h2) * float(rect.size.y);
			if (e != current.history.front()) {
				monitor_draw->draw_line(rect.position + Point2(from, h2), rect.position + Point2(from + spacing, prev), draw_color, Math::round(EDSCALE));
			}

			if (marker_key == active[i] && count == marker_frame) {
				Color line_color;
				line_color.set_hsv(draw_color.get_h(), draw_color.get_s() * 0.8f, draw_color.get_v(), 0.5f);
				monitor_draw->draw_line(rect.position + Point2(from, 0), rect.position + Point2(from, rect.size.y), line_color, Math::round(EDSCALE));

				String label = _create_label(e->get(), current.type);
				Size2 size = graph_font->get_string_size(label, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size);
				Vector2 text_top_left_position = Vector2(from, h2) - (size + Vector2(MARKER_MARGIN, MARKER_MARGIN));
				if (text_top_left_position.x < 0) {
					text_top_left_position.x = from + MARKER_MARGIN;
				}
				if (text_top_left_position.y < 0) {
					text_top_left_position.y = h2 + MARKER_MARGIN;
				}
				monitor_draw->draw_string(graph_font, rect.position + text_top_left_position + Point2(0, graph_font->get_ascent(font_size)), label, HORIZONTAL_ALIGNMENT_LEFT, rect.size.x, font_size, line_color);
			}
			prev = h2;
			e = e->next();
			from -= spacing;
			count++;
		}
	}
}

void EditorPerformanceProfiler::_build_monitor_tree() {
	HashSet<StringName> monitor_checked;
	for (KeyValue<StringName, Monitor> &E : monitors) {
		if (E.value.item && E.value.item->is_checked(0)) {
			monitor_checked.insert(E.key);
		}
	}

	base_map.clear();
	monitor_tree->get_root()->clear_children();

	for (KeyValue<StringName, Monitor> &E : monitors) {
		TreeItem *base = _get_monitor_base(E.value.base);
		TreeItem *item = _create_monitor_item(E.value.name, base);
		item->set_checked(0, monitor_checked.has(E.key));
		E.value.item = item;
		if (!E.value.history.is_empty()) {
			E.value.update_value(E.value.history.front()->get());
		}
	}
}

TreeItem *EditorPerformanceProfiler::_get_monitor_base(const StringName &p_base_name) {
	if (base_map.has(p_base_name)) {
		return base_map[p_base_name];
	}

	TreeItem *base = monitor_tree->create_item(monitor_tree->get_root());
	base->set_text(0, p_base_name);
	base->set_editable(0, false);
	base->set_selectable(0, false);
	base->set_expand_right(0, true);
	base_map.insert(p_base_name, base);
	return base;
}

TreeItem *EditorPerformanceProfiler::_create_monitor_item(const StringName &p_monitor_name, TreeItem *p_base) {
	TreeItem *item = monitor_tree->create_item(p_base);
	item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
	item->set_editable(0, true);
	item->set_selectable(0, false);
	item->set_selectable(1, false);
	item->set_text(0, p_monitor_name);
	return item;
}

void EditorPerformanceProfiler::_marker_input(const Ref<InputEvent> &p_event) {
	Ref<InputEventMouseButton> mb = p_event;
	if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
		Vector<StringName> active;
		for (KeyValue<StringName, Monitor> &E : monitors) {
			if (E.value.item->is_checked(0)) {
				active.push_back(E.key);
			}
		}
		if (active.size() > 0) {
			int columns = int(Math::ceil(Math::sqrt(float(active.size()))));
			int rows = int(Math::ceil(float(active.size()) / float(columns)));
			if (active.size() == 1) {
				rows = 1;
			}
			Size2i cell_size = Size2i(monitor_draw->get_size()) / Size2i(columns, rows);
			Vector2i index = mb->get_position() / cell_size;
			Rect2i rect(index * cell_size + Point2i(MARGIN, MARGIN), cell_size - Point2i(MARGIN, MARGIN) * 2);
			if (rect.has_point(mb->get_position())) {
				if (index.x + index.y * columns < active.size()) {
					marker_key = active[index.x + index.y * columns];
				} else {
					marker_key = "";
				}
				Ref<StyleBox> graph_style_box = get_theme_stylebox(SNAME("normal"), SNAME("TextEdit"));
				rect.position += graph_style_box->get_offset();
				rect.size -= graph_style_box->get_minimum_size();
				Vector2 point = mb->get_position() - rect.position;
				if (point.x >= rect.size.x) {
					marker_frame = 0;
				} else {
					int point_sep = 5;
					float spacing = float(point_sep) / float(columns);
					marker_frame = (rect.size.x - point.x) / spacing;
				}
				monitor_draw->queue_redraw();
				return;
			}
		}
		marker_key = "";
		monitor_draw->queue_redraw();
	}
}

void EditorPerformanceProfiler::reset() {
	HashMap<StringName, Monitor>::Iterator E = monitors.begin();
	while (E != monitors.end()) {
		HashMap<StringName, Monitor>::Iterator N = E;
		++N;
		if (String(E->key).begins_with("custom:")) {
			monitors.remove(E);
		} else {
			E->value.reset();
		}
		E = N;
	}

	_build_monitor_tree();
	marker_key = "";
	marker_frame = 0;
	monitor_draw->queue_redraw();
}

void EditorPerformanceProfiler::update_monitors(const Vector<StringName> &p_names) {
	HashMap<StringName, int> names;
	for (int i = 0; i < p_names.size(); i++) {
		names.insert("custom:" + p_names[i], Performance::MONITOR_MAX + i);
	}

	{
		HashMap<StringName, Monitor>::Iterator E = monitors.begin();
		while (E != monitors.end()) {
			HashMap<StringName, Monitor>::Iterator N = E;
			++N;
			if (String(E->key).begins_with("custom:")) {
				if (!names.has(E->key)) {
					monitors.remove(E);
				} else {
					E->value.frame_index = names[E->key];
					names.erase(E->key);
				}
			}
			E = N;
		}
	}

	for (const KeyValue<StringName, int> &E : names) {
		String name = String(E.key).replace_first("custom:", "");
		String base = "Custom";
		if (name.get_slice_count("/") == 2) {
			base = name.get_slicec('/', 0);
			name = name.get_slicec('/', 1);
		}
		monitors.insert(E.key, Monitor(name, base, E.value, Performance::MONITOR_TYPE_QUANTITY, nullptr));
	}

	_build_monitor_tree();
}

void EditorPerformanceProfiler::add_profile_frame(const Vector<float> &p_values) {
	for (KeyValue<StringName, Monitor> &E : monitors) {
		float value = 0.0f;
		if (E.value.frame_index >= 0 && E.value.frame_index < p_values.size()) {
			value = p_values[E.value.frame_index];
		}
		E.value.history.push_front(value);
		E.value.update_value(value);
	}
	marker_frame++;
	monitor_draw->queue_redraw();
}

List<float> *EditorPerformanceProfiler::get_monitor_data(const StringName &p_name) {
	if (monitors.has(p_name)) {
		return &monitors[p_name].history;
	}
	return nullptr;
}

EditorPerformanceProfiler::EditorPerformanceProfiler() {
	set_name(TTR("Monitors"));
	set_split_offset(340 * EDSCALE);

	monitor_tree = memnew(Tree);
	monitor_tree->set_columns(2);
	monitor_tree->set_column_title(0, TTR("Monitor"));
	monitor_tree->set_column_title(1, TTR("Value"));
	monitor_tree->set_column_titles_visible(true);
	monitor_tree->connect("item_edited", callable_mp(this, &EditorPerformanceProfiler::_monitor_select));
	monitor_tree->create_item();
	monitor_tree->set_hide_root(true);
	add_child(monitor_tree);

	monitor_draw = memnew(Control);
	monitor_draw->set_clip_contents(true);
	monitor_draw->connect("draw", callable_mp(this, &EditorPerformanceProfiler::_monitor_draw));
	monitor_draw->connect("gui_input", callable_mp(this, &EditorPerformanceProfiler::_marker_input));
	add_child(monitor_draw);

	info_message = memnew(Label);
	info_message->set_text(TTR("Pick one or more items from the list to display the graph."));
	info_message->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
	info_message->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
	info_message->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
	info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
	info_message->set_anchors_and_offsets_preset(PRESET_FULL_RECT, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);
	monitor_draw->add_child(info_message);

	for (int i = 0; i < Performance::MONITOR_MAX; i++) {
		String base = EditorPropertyNameProcessor::get_singleton()->process_name(Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)).get_slicec('/', 0), EditorPropertyNameProcessor::STYLE_CAPITALIZED);
		String name = EditorPropertyNameProcessor::get_singleton()->process_name(Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)).get_slicec('/', 1), EditorPropertyNameProcessor::STYLE_CAPITALIZED);
		monitors.insert(Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)), Monitor(name, base, i, Performance::get_singleton()->get_monitor_type(Performance::Monitor(i)), nullptr));
	}

	_build_monitor_tree();
}


text:
package cn.tanziquan.produce.cole.gitdeploy.dto.github;

import java.sql.Timestamp;

/**
 * GitHubHeadCommitDto
 *
 * @author zhigang.tan
 * @version 0.0.1
 */
public class GitHubHeadCommitDto {

    private String message;

    private GitHubCommitterDto committer;

    private Timestamp timestamp;

    public GitHubCommitterDto getCommitter() {
        return committer;
    }

    public void setCommitter(GitHubCommitterDto committer) {
        this.committer = committer;
    }

    public Timestamp getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Timestamp timestamp) {
        this.timestamp = timestamp;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


text:
using System;

namespace Azure.Communication.Chat
{
    /// <summary> Result of the send message operation. </summary>
    internal partial class SendChatMessageResult
    {
        /// <summary> Initializes a new instance of SendChatMessageResult. </summary>
        /// <param name="id"> A server-generated message id. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception>
        internal SendChatMessageResult(string id)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            Id = id;
        }

        /// <summary> A server-generated message id. </summary>
        public string Id { get; }
    }
}


text:
package com.vaadin.v7.ui.components.colorpicker;

import com.vaadin.ui.Component;
import com.vaadin.ui.Component.Event;
import com.vaadin.v7.shared.ui.colorpicker.Color;

/**
 * The color changed event which is passed to the listeners when a color change
 * occurs.
 *
 * @since 7.0.0
 */
@Deprecated
public class ColorChangeEvent extends Event {
    private final Color color;

    public ColorChangeEvent(Component source, Color color) {
        super(source);

        this.color = color;
    }

    /**
     * Returns the new color.
     */
    public Color getColor() {
        return color;
    }
}


text:
FactoryGirl.define do
  factory :sitemap do
    url "MyString"
    valid false
  end
end


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @class Ext.toolbar.Paging
 */

/**
 * @var {boolean}
 * True to include different icons when the paging toolbar buttons are disabled.
 */
$grid-paging-toolbar-include-disabled-icons: true !default;


text:
This guide explains how to install Quilt, and also serves as a
brief, hands-on introduction to some Quilt basics.

## Install Go
Quilt supports Go version 1.5 or later.

Find Go using your package manager or on the [Golang website](https://golang.org/doc/install).

### Setup GOPATH
We recommend reading the overview to Go workplaces [here](https://golang.org/doc/code.html).

Before installing Quilt, you'll need to set up your GOPATH. Assuming the root of
your Go workspace will be `~/gowork`, execute the following `export` commands in
your terminal to set up your GOPATH.
```bash
export GOPATH=~/gowork
export PATH=$PATH:$GOPATH/bin
```
It would be a good idea to add these commands to your `.bashrc` so that they do
not have to be run again.

## Download and Install Quilt
Clone the repository into your Go workspace: `go get github.com/quilt/quilt`.

This command also automatically installs Quilt. If the installation was
successful, then the `quilt` command should execute successfully in your shell.

## QUILT_PATH
Your `QUILT_PATH` will be where Quilt looks for imported specs, and where
specs you download with `quilt get` get placed.  By default, your `QUILT_PATH`
is `~/.quilt`. You can set a custom `QUILT_PATH` when invoking `quilt`:

```bash
QUILT_PATH="~/.my_quilt_directory" quilt run my_quilt_spec.js
```

Or you can `export` a custom path into your environment.

## Configure A Cloud Provider

Below we discuss how to setup Quilt for Amazon EC2. Google Compute Engine is
also supported. Since Quilt deploys systems consistently across providers, the
details of the rest of this document will apply no matter what provider you
choose.

For Amazon EC2, you'll first need to create an account with [Amazon Web
Services](https://aws.amazon.com/ec2/) and then find your
[access credentials](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html#cli-signup).
That done, you simply need to populate the file `~/.aws/credentials`, with your
Amazon credentials:
```
[default]
aws_access_key_id = <YOUR_ID>
aws_secret_access_key = <YOUR_SECRET_KEY>
```

## Your First Quilt-managed Infrastructure
We suggest you read
[`quilt/nginx/main.js`](https://github.com/quilt/nginx/blob/master/main.js)
to understand the infrastructure defined by this Quilt.js spec.

### Import Nginx Spec
Before we can run the Nginx spec, we need to import it into our `QUILT_PATH`.
To do that, execute the following command from your shell:
```bash
quilt get github.com/quilt/nginx
```

### Configure `quilt/nginx/main.js`
#### Set Up Your SSH Authentication
Quilt-managed Machines use public key authentication to control SSH access.
SSH authentication is configured with the `sshKeys` Machine attribute.
Currently,  the easiest way to set up your SSH access, is by using the
`githubKeys()` function. Given your GitHub username, the function grabs your
public keys from GitHub, so they can be used to configure SSH authentication.
If you can access GitHub repositories through SSH, then you can also SSH into a
`githubKey`-configured Machine.

If you would like to use `githubKey` authentication, open your spec in
`$QUILT_PATH/github.com/quilt/nginx/main.js` and set the `sshKeys` appropriately.
```javascript
var baseMachine = new Machine({
    ...
    sshKeys: githubKeys("CHANGE_ME"),
    ...
});
```

### Deploying `quilt/nginx/main.js`
In one shell, start the Quilt daemon with `quilt daemon`. In another shell,
execute `quilt run github.com/quilt/nginx/main.js`. Quilt will set up several
Ubuntu VMs on your cloud provider as Workers, and these Workers will host Nginx
Docker containers as specified in
[`quilt/nginx/app.js`](https://github.com/quilt/nginx/blob/master/app.js)
(you do not have to understand or edit this file).

### Accessing the Worker VM
It will take a while for the VMs to boot up, for Quilt to configure the network,
and for Docker containers to be initialized. When a machine is marked
`Connected` in the console output, the corresponding VM is fully booted and has
begun communicating with Quilt.

The public IP of the Worker VM can be deduced from the console output. The
following output shows the Worker VM's public IP to be 52.53.177.110:
```
INFO [Nov 11 13:23:10.266] db.Machine:
	Machine-2{Master, Amazon us-west-1 m4.large, sir-3sngfxdh, PublicIP=54.183.169.245, PrivateIP=172.31.2.178, Disk=32GB, Connected}
	Machine-4{Worker, Amazon us-west-1 m4.large, sir-19bid86g, PublicIP=52.53.177.110, PrivateIP=172.31.0.87, Disk=32GB, Connected}
...
```

Run `ssh quilt@<WORKER_PUBLIC_IP>` to access a privileged shell on the Worker VM.

### Inspecting Docker Containers on the Worker VM
You can run `docker ps` to list the containers running on your Worker VM.

```
quilt@ip-172-31-0-87:~$ docker ps
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS              PORTS               NAMES
a2ac27cfd313        quay.io/coreos/etcd:v3.0.2   "/usr/local/bin/etcd "   11 minutes ago      Up 11 minutes                           etcd
0f407bd0d5c4        quilt/ovs                    "run ovs-vswitchd"       11 minutes ago      Up 11 minutes                           ovs-vswitchd
7b65a447fe54        quilt/ovs                    "run ovsdb-server"       11 minutes ago      Up 11 minutes                           ovsdb-server
deb4f98db8eb        quilt/quilt:latest           "quilt minion"           11 minutes ago      Up 11 minutes                           minion
```

Any docker containers defined in a Stitch specification are placed on one of
your Worker VMs.  In addition to these user-defined containers, Quilt also
places several support containers on each VM. Among these support containers is
`minion`, which locally manages Docker and allows Quilt VMs to talk to each
other and your local computer.

### Loading the Nginx Webpage
By default, Quilt-managed containers are disconnected from the public internet
and isolated from one another. In order to make the Nginx container accessible
from the public internet,
[`quilt/nginx/app.js`](https://github.com/quilt/nginx/blob/master/app.js)
explicitly opens port 80 on the Nginx container to the outside world:

```javascript
publicInternet.connect(port, webTier);
```

From your browser via `http://<WORKER_PUBLIC_IP>`, or on the command-line via
`curl <WORKER_PUBLIC_IP>`, you can load the Nginx welcome page served by your
Quilt cluster.

### Cleaning up

If you'd like to destroy the infrastructure you just deployed, you can either
modify the specification to remove all of the Machines, or use the command,
`quilt stop`. Both options will cause Quilt to destroy all of the
Machines in the deployment.

## Next Steps: Downloading Other Specs
You can download specs into your `QUILT_PATH` by executing
`quilt get <IMPORT_PATH>`, where `<IMPORT_PATH>` is a path to a repository
containing specs (e.g. `github.com/quilt/nginx`). You can read more about this
functionality [here](https://github.com/quilt/quilt/blob/master/docs/Stitch.md#quilt_path).

## Next Steps: Writing your own Quilt Spec

This guide illustrated how to use Quilt to run an application that already had a
spec written.  Next, you can try writing your own Quilt specs for new applications
that don't yet have specs written; to do that, check out the
[guide to writing Quilt specs](https://github.com/quilt/quilt/blob/master/docs/spec-writers-guide.md).


text:
#include "precomp.hpp"

#ifdef HAVE_ANDROID_NATIVE_CAMERA

#include <opencv2/imgproc.hpp>
#include <pthread.h>
#include <android/log.h>
#include <camera_activity.hpp>

#undef LOG_TAG
#undef LOGD
#undef LOGE
#undef LOGI
#define LOG_TAG "OpenCV::camera"
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))

class VideoIOAndroidCameraActivity;

class CvCapture_Android : public CvCapture
{
public:
    CvCapture_Android(int);
    virtual ~CvCapture_Android();

    virtual double getProperty(int propIdx) const;
    virtual bool setProperty(int probIdx, double propVal);
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int outputType);
    virtual int getCaptureDomain() { return CV_CAP_ANDROID; }

    bool isOpened() const;

protected:
    struct OutputMap
    {
    public:
        cv::Mat mat;
        IplImage* getIplImagePtr();
    private:
        IplImage iplHeader;
    };

    CameraActivity* m_activity;

    //raw from camera
    int m_width;
    int m_height;
    cv::Mat m_frameYUV420;
    cv::Mat m_frameYUV420next;

    enum YUVformat
    {
        noformat = 0,
        yuv420sp,
        yvu420sp,
        yuvUnknown
    };

    YUVformat m_frameFormat;

    void setFrame(const void* buffer, int bufferSize);

private:
    bool m_isOpened;
    bool m_CameraParamsChanged;

    //frames counter for statistics
    int m_framesGrabbed;

    //cached converted frames
    OutputMap m_frameGray;
    OutputMap m_frameColor;
    bool m_hasGray;
    bool m_hasColor;

    enum CvCapture_Android_DataState {
        CVCAPTURE_ANDROID_STATE_NO_FRAME=0,
        CVCAPTURE_ANDROID_STATE_HAS_NEW_FRAME_UNGRABBED,
        CVCAPTURE_ANDROID_STATE_HAS_FRAME_GRABBED
    };
    volatile CvCapture_Android_DataState m_dataState;

    //synchronization
    pthread_mutex_t m_nextFrameMutex;
    pthread_cond_t m_nextFrameCond;
    volatile bool m_waitingNextFrame;
    volatile bool m_shouldAutoGrab;

    void prepareCacheForYUV(int width, int height);
    bool convertYUV2Grey(int width, int height, const unsigned char* yuv, cv::Mat& resmat);
    bool convertYUV2BGR(int width, int height, const unsigned char* yuv, cv::Mat& resmat, bool inRGBorder, bool withAlpha);

    friend class VideoIOAndroidCameraActivity;
};

class VideoIOAndroidCameraActivity : public CameraActivity
{
public:
    VideoIOAndroidCameraActivity(CvCapture_Android* capture)
    {
        m_capture = capture;
        m_framesReceived = 0;
    }

    virtual bool onFrameBuffer(void* buffer, int bufferSize)
    {
        if(isConnected() && buffer != 0 && bufferSize > 0)
        {
            m_framesReceived++;
            if (m_capture->m_waitingNextFrame || m_capture->m_shouldAutoGrab)
            {
                pthread_mutex_lock(&m_capture->m_nextFrameMutex);

                m_capture->setFrame(buffer, bufferSize);

                pthread_cond_broadcast(&m_capture->m_nextFrameCond);
                pthread_mutex_unlock(&m_capture->m_nextFrameMutex);
            }
            return true;
        }
        return false;
    }

    void LogFramesRate()
    {
        LOGI("FRAMES received: %d  grabbed: %d", m_framesReceived, m_capture->m_framesGrabbed);
    }

private:
    CvCapture_Android* m_capture;
    int m_framesReceived;
};

IplImage* CvCapture_Android::OutputMap::getIplImagePtr()
{
    if( mat.empty() )
        return 0;

    iplHeader = IplImage(mat);
    return &iplHeader;
}

CvCapture_Android::CvCapture_Android(int cameraId)
{
    //defaults
    m_width               = 0;
    m_height              = 0;
    m_activity            = 0;
    m_isOpened            = false;
    // m_frameYUV420        = 0;
    // m_frameYUV420next    = 0;
    m_hasGray             = false;
    m_hasColor            = false;
    m_dataState           = CVCAPTURE_ANDROID_STATE_NO_FRAME;
    m_waitingNextFrame    = false;
    m_shouldAutoGrab      = false;
    m_framesGrabbed       = 0;
    m_CameraParamsChanged = false;
    m_frameFormat         = noformat;

    //try connect to camera
    LOGD("CvCapture_Android::CvCapture_Android(%i)", cameraId);
    m_activity = new VideoIOAndroidCameraActivity(this);

    if (m_activity == 0) return;

    pthread_mutex_init(&m_nextFrameMutex, NULL);
    pthread_cond_init (&m_nextFrameCond,  NULL);

    CameraActivity::ErrorCode errcode = m_activity->connect(cameraId);

    if(errcode == CameraActivity::NO_ERROR)
        m_isOpened = true;
    else
    {
        LOGE("Native_camera returned opening error: %d", errcode);
        delete m_activity;
        m_activity = 0;
    }
}

bool CvCapture_Android::isOpened() const
{
    return m_isOpened;
}

CvCapture_Android::~CvCapture_Android()
{
    if (m_activity)
    {
        ((VideoIOAndroidCameraActivity*)m_activity)->LogFramesRate();

        pthread_mutex_lock(&m_nextFrameMutex);

        // unsigned char *tmp1=m_frameYUV420;
        // unsigned char *tmp2=m_frameYUV420next;
        // m_frameYUV420 = 0;
        // m_frameYUV420next = 0;
        // delete tmp1;
        // delete tmp2;

        m_dataState=CVCAPTURE_ANDROID_STATE_NO_FRAME;
        pthread_cond_broadcast(&m_nextFrameCond);

        pthread_mutex_unlock(&m_nextFrameMutex);

        //m_activity->disconnect() will be automatically called inside destructor;
        delete m_activity;
        m_activity = 0;

        pthread_mutex_destroy(&m_nextFrameMutex);
        pthread_cond_destroy(&m_nextFrameCond);
    }
}

double CvCapture_Android::getProperty( int propIdx ) const
{
    switch ( propIdx )
    {
    case CV_CAP_PROP_FRAME_WIDTH:
        return (double)m_activity->getFrameWidth();
    case CV_CAP_PROP_FRAME_HEIGHT:
        return (double)m_activity->getFrameHeight();
    case CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING:
    return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_SUPPORTED_PREVIEW_SIZES_STRING);
    case CV_CAP_PROP_PREVIEW_FORMAT:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_PREVIEW_FORMAT_STRING);
    case CV_CAP_PROP_FPS:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FPS);
    case CV_CAP_PROP_EXPOSURE:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_EXPOSURE);
    case CV_CAP_PROP_ANDROID_FLASH_MODE:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FLASH_MODE);
    case CV_CAP_PROP_ANDROID_FOCUS_MODE:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_MODE);
    case CV_CAP_PROP_ANDROID_WHITE_BALANCE:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_WHITE_BALANCE);
    case CV_CAP_PROP_ANDROID_ANTIBANDING:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_ANTIBANDING);
    case CV_CAP_PROP_ANDROID_FOCAL_LENGTH:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCAL_LENGTH);
    case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_NEAR);
    case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_OPTIMAL);
    case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_FAR);
    case CV_CAP_PROP_ANDROID_EXPOSE_LOCK:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_EXPOSE_LOCK);
    case CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK:
        return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_WHITEBALANCE_LOCK);
    default:
        CV_Error( CV_StsOutOfRange, "Failed attempt to GET unsupported camera property." );
        break;
    }
    return -1.0;
}

bool CvCapture_Android::setProperty( int propIdx, double propValue )
{
    bool res = false;
    if( isOpened() )
    {
        switch ( propIdx )
        {
        case CV_CAP_PROP_FRAME_WIDTH:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH, propValue);
            break;
        case CV_CAP_PROP_FRAME_HEIGHT:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT, propValue);
            break;
        case CV_CAP_PROP_AUTOGRAB:
        m_shouldAutoGrab=(propValue != 0);
            break;
        case CV_CAP_PROP_EXPOSURE:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_EXPOSURE, propValue);
            break;
        case CV_CAP_PROP_ANDROID_FLASH_MODE:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FLASH_MODE, propValue);
            break;
        case CV_CAP_PROP_ANDROID_FOCUS_MODE:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FOCUS_MODE, propValue);
            break;
        case CV_CAP_PROP_ANDROID_WHITE_BALANCE:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_WHITE_BALANCE, propValue);
            break;
        case CV_CAP_PROP_ANDROID_ANTIBANDING:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_ANTIBANDING, propValue);
            break;
        case CV_CAP_PROP_ANDROID_EXPOSE_LOCK:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_EXPOSE_LOCK, propValue);
            break;
        case CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK:
            m_activity->setProperty(ANDROID_CAMERA_PROPERTY_WHITEBALANCE_LOCK, propValue);
            break;
        default:
            CV_Error( CV_StsOutOfRange, "Failed attempt to SET unsupported camera property." );
            return false;
        }

        // Only changes in frame size require camera restart
        if ((propIdx == CV_CAP_PROP_FRAME_WIDTH) || (propIdx == CV_CAP_PROP_FRAME_HEIGHT))
        {   // property for videoio class CvCapture_Android only
            m_CameraParamsChanged = true;
        }

        res = true;
    }

    return res;
}

bool CvCapture_Android::grabFrame()
{
    if( !isOpened() ) {
        LOGE("CvCapture_Android::grabFrame(): camera is not opened");
        return false;
    }

    bool res=false;
    pthread_mutex_lock(&m_nextFrameMutex);
    if (m_CameraParamsChanged)
    {
        m_activity->applyProperties();
        m_CameraParamsChanged = false;
        m_dataState = CVCAPTURE_ANDROID_STATE_NO_FRAME;//we will wait new frame
    }

    if (m_dataState != CVCAPTURE_ANDROID_STATE_HAS_NEW_FRAME_UNGRABBED)
    {
        m_waitingNextFrame = true;
        pthread_cond_wait(&m_nextFrameCond, &m_nextFrameMutex);
    }

    if (m_dataState == CVCAPTURE_ANDROID_STATE_HAS_NEW_FRAME_UNGRABBED)
    {
        //LOGD("CvCapture_Android::grabFrame: get new frame");
        //swap current and new frames
        cv::swap(m_frameYUV420, m_frameYUV420next);

        //discard cached frames
        m_hasGray = false;
        m_hasColor = false;

        m_dataState=CVCAPTURE_ANDROID_STATE_HAS_FRAME_GRABBED;
        m_framesGrabbed++;

        res=true;
    } else {
        LOGE("CvCapture_Android::grabFrame: NO new frame");
    }

    int res_unlock=pthread_mutex_unlock(&m_nextFrameMutex);
    if (res_unlock) {
        LOGE("Error in CvCapture_Android::grabFrame: pthread_mutex_unlock returned %d --- probably, this object has been destroyed", res_unlock);
        return false;
    }

    return res;
}

IplImage* CvCapture_Android::retrieveFrame( int outputType )
{
    IplImage* image = NULL;

    cv::Mat m_frameYUV420_ref = m_frameYUV420;
    unsigned char *current_frameYUV420=m_frameYUV420_ref.ptr();
    //Attention! all the operations in this function below should occupy less time than the period between two frames from camera
    if (NULL != current_frameYUV420)
    {
        if (m_frameFormat == noformat)
        {
            union {double prop; const char* name;} u;
            u.prop = getProperty(CV_CAP_PROP_PREVIEW_FORMAT);
            if (0 == strcmp(u.name, "yuv420sp"))
                m_frameFormat = yuv420sp;
            else if (0 == strcmp(u.name, "yvu420sp"))
                m_frameFormat = yvu420sp;
            else
                m_frameFormat = yuvUnknown;
        }

        switch(outputType)
        {
        case CV_CAP_ANDROID_GREY_FRAME:
            if (!m_hasGray)
                if (!(m_hasGray = convertYUV2Grey(m_width, m_height, current_frameYUV420, m_frameGray.mat)))
                    return NULL;
            image = m_frameGray.getIplImagePtr();
            break;
        case CV_CAP_ANDROID_COLOR_FRAME_BGR: case CV_CAP_ANDROID_COLOR_FRAME_RGB:
            if (!m_hasColor)
                if (!(m_hasColor = convertYUV2BGR(m_width, m_height, current_frameYUV420, m_frameColor.mat, outputType == CV_CAP_ANDROID_COLOR_FRAME_RGB, false)))
                    return NULL;
            image = m_frameColor.getIplImagePtr();
            break;
        case CV_CAP_ANDROID_COLOR_FRAME_BGRA: case CV_CAP_ANDROID_COLOR_FRAME_RGBA:
            if (!m_hasColor)
                if (!(m_hasColor = convertYUV2BGR(m_width, m_height, current_frameYUV420, m_frameColor.mat, outputType == CV_CAP_ANDROID_COLOR_FRAME_RGBA, true)))
                    return NULL;
            image = m_frameColor.getIplImagePtr();
            break;
        default:
            LOGE("Unsupported frame output format: %d", outputType);
            CV_Error( CV_StsOutOfRange, "Output frame format is not supported." );
            image = NULL;
            break;
        }
    }
    return image;
}

//Attention: this method should be called inside pthread_mutex_lock(m_nextFrameMutex) only
void CvCapture_Android::setFrame(const void* buffer, int bufferSize)
{
    int width = m_activity->getFrameWidth();
    int height = m_activity->getFrameHeight();
    int expectedSize = (width * height * 3) >> 1;

    if ( expectedSize != bufferSize)
    {
        LOGE("ERROR reading YUV buffer: width=%d, height=%d, size=%d, receivedSize=%d", width, height, expectedSize, bufferSize);
        return;
    }

    //allocate memory if needed
    prepareCacheForYUV(width, height);

    //copy data
    cv::Mat m_frameYUV420next_ref = m_frameYUV420next;
    memcpy(m_frameYUV420next_ref.ptr(), buffer, bufferSize);
    // LOGD("CvCapture_Android::setFrame -- memcpy is done");
    // ((VideoIOAndroidCameraActivity*)m_activity)->LogFramesRate();

    m_dataState = CVCAPTURE_ANDROID_STATE_HAS_NEW_FRAME_UNGRABBED;
    m_waitingNextFrame = false;//set flag that no more frames required at this moment
}

//Attention: this method should be called inside pthread_mutex_lock(m_nextFrameMutex) only
void CvCapture_Android::prepareCacheForYUV(int width, int height)
{
    if (width != m_width || height != m_height)
    {
        LOGD("CvCapture_Android::prepareCacheForYUV: Changing size of buffers: from width=%d height=%d to width=%d height=%d", m_width, m_height, width, height);
        m_width = width;
        m_height = height;
        /*
        unsigned char *tmp = m_frameYUV420next;
        m_frameYUV420next = new unsigned char [width * height * 3 / 2];
        if (tmp != NULL)
        {
            delete[] tmp;
        }

        tmp = m_frameYUV420;
        m_frameYUV420 = new unsigned char [width * height * 3 / 2];
        if (tmp != NULL)
        {
            delete[] tmp;
        }*/
        m_frameYUV420.create(height * 3 / 2, width, CV_8UC1);
        m_frameYUV420next.create(height * 3 / 2, width, CV_8UC1);
    }
}

bool CvCapture_Android::convertYUV2Grey(int width, int height, const unsigned char* yuv, cv::Mat& resmat)
{
    if (yuv == 0) return false;
    if (m_frameFormat != yuv420sp && m_frameFormat != yvu420sp) return false;
#define ALWAYS_COPY_GRAY 0
#if ALWAYS_COPY_GRAY
    resmat.create(height, width, CV_8UC1);
    unsigned char* matBuff = resmat.ptr<unsigned char> (0);
    memcpy(matBuff, yuv, width * height);
#else
    resmat = cv::Mat(height, width, CV_8UC1, (void*)yuv);
#endif
    return !resmat.empty();
}

bool CvCapture_Android::convertYUV2BGR(int width, int height, const unsigned char* yuv, cv::Mat& resmat, bool inRGBorder, bool withAlpha)
{
    if (yuv == 0) return false;
    if (m_frameFormat != yuv420sp && m_frameFormat != yvu420sp) return false;

    CV_Assert(width % 2 == 0 && height % 2 == 0);

    cv::Mat src(height*3/2, width, CV_8UC1, (void*)yuv);

    if (m_frameFormat == yuv420sp)
        cv::cvtColor(src, resmat, inRGBorder ? CV_YUV420sp2RGB : CV_YUV420sp2BGR, withAlpha ? 4 : 3);
    else if (m_frameFormat == yvu420sp)
        cv::cvtColor(src, resmat, inRGBorder ? CV_YUV2RGB_NV21 : CV_YUV2BGR_NV12, withAlpha ? 4 : 3);

    return !resmat.empty();
}

CvCapture* cvCreateCameraCapture_Android( int cameraId )
{
    CvCapture_Android* capture = new CvCapture_Android(cameraId);

    if( capture->isOpened() )
        return capture;

    delete capture;
    return 0;
}

#endif


text:
module Database.HXournal.IDMap.Client.Command where

import Database.HXournal.IDMap.Client.ProgType hiding (test,get)
import Database.HXournal.IDMap.Client.Job
import Database.HXournal.IDMap.Client.Config
import Data.Configurator

commandLineProcess :: HXournalIDMapClient -> IO ()
commandLineProcess (Test cfg) = do
  putStrLn "test called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") test mc
commandLineProcess (Get cfg n) = do
  putStrLn "get called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (flip get n) mc
commandLineProcess (GetList cfg) = do
  putStrLn "getlist called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") getList mc
commandLineProcess (CreateWithFile cfg fn) = do
  putStrLn "create called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (\x -> createWithFile x fn) mc
commandLineProcess (GetListWithTime cfg t1 t2) = do
  putStrLn "getlist called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (\x -> getListWithTime x t1 t2) mc

{-
commandLineProcess (Create cfg mn) = do
  putStrLn "create called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (\x -> startCreate x mn Nothing) mc
-}
{-
commandLineProcess (Put cfg n mn) = do
  putStrLn "put called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (\c-> startPut c n mn) mc
commandLineProcess (Delete cfg n) = do
  putStrLn "delete called"
  mc <- getHXournalIDMapClientConfiguration =<< load [Required cfg]
  maybe (error "cannot parse config") (flip startDelete n) mc
-}


text:
import { GitHubSetting, GitHubSettingJSON } from "../../domain/GitHubSetting/GitHubSetting";
import { Identifier } from "../../domain/Entity";
import { createStorageInstance } from "./Storage";
import { NullableBaseRepository } from "./NullableBaseRepository";
import { GitHubUser } from "../../domain/GitHubUser/GitHubUser";

const debug = require("debug")("faao:GitHubSettingRepository");

export class GitHubSettingRepository extends NullableBaseRepository<GitHubSetting> {
    storage!: LocalForage;

    /**
     * Please call this before find* API
     * @returns {Promise<any>}
     */
    async ready(): Promise<this> {
        if (this.map.size > 0) {
            return Promise.resolve(this);
        }
        this.storage = createStorageInstance({
            name: "GitHubSettingRepository"
        });
        await this.storage.ready();
        const values: GitHubSettingJSON[] = [];
        await this.storage.iterate<GitHubSettingJSON, void>(value => {
            values.push(value);
        });
        values
            .map(json => {
                return GitHubSetting.fromJSON(json);
            })
            .forEach(gitHubSetting => {
                this.map.set(gitHubSetting.id.toValue(), gitHubSetting);
            });
        return this;
    }

    findGitHubSettingById(id: Identifier<GitHubSetting>): GitHubSetting | undefined {
        return this.findById(id);
    }

    save(entity: GitHubSetting): Promise<void> {
        super.save(entity);
        return this.storage.setItem(entity.id.toValue(), entity.toJSON()).then(() => {
            debug("Save entity");
        });
    }

    replace(prevSetting: GitHubSetting, newSetting: GitHubSetting): Promise<void> {
        newSetting.id = prevSetting.id;
        return this.save(newSetting);
    }

    delete(setting: GitHubSetting): Promise<void> {
        super.delete(setting);
        return this.storage.removeItem(setting.id.toValue());
    }

    clear() {
        super.clear();
        return this.storage.clear();
    }

    findByGitHubUserId(openedUserId: Identifier<GitHubUser>) {
        return this.map.values().find(setting => {
            return openedUserId.equals(setting.gitHubUserId);
        });
    }
}

export const gitHubSettingRepository = new GitHubSettingRepository();


text:
#pragma once

#ifndef _QI_TYPE_PROXYSIGNAL_HPP_
#define _QI_TYPE_PROXYSIGNAL_HPP_

#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/bind.hpp>
#undef BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <qi/signal.hpp>
#include <qi/anyfunction.hpp>
#include <qi/anyobject.hpp>

namespace qi
{
  namespace details_proxysignal
  {
    constexpr inline const char* objectExpiredError()
    {
      return "The object that the proxy signal represents has expired.";
    }

    inline void metaPostSignal(AnyWeakObject object,
                               const std::string& signalName,
                               const GenericFunctionParameters& params)
    {
      if (auto sharedObject = object.lock())
        sharedObject.metaPost(signalName, params);
    }

    /// Resets the bounce event callback on the signal, depending on the `enable` boolean and the
    /// existence of local subscribers.
    ///
    /// If enabled, the `callSubs` callback is called when the remote signal is triggered. If
    /// disabled, the callback is disconnected instead.
    ///
    /// Procedure<void(GenericFunctionParameters)> CallSubs
    template<typename CallSubs>
    Future<SignalLink> resetBounceEventCallback(CallSubs callSubs,
                                                bool enable,
                                                AnyWeakObject weakObject,
                                                std::string signalName,
                                                SignalLink link)
    {
      using namespace ka::functional_ops;

      auto object = weakObject.lock();
      if (!object)
        return makeFutureError<SignalLink>(objectExpiredError());

      Future<SignalLink> newLinkFut;
      if (enable)
      {
        // Bounce the event back to the local subscribers by calling `_callSubscribers` on the
        // signal instead of triggering it, which with our trigger override would re-post the event
        // back to the back-end and would lead to an infinite loop.
        SignalSubscriber bounceEvent(AnyFunction::fromDynamicFunction(
          ka::mv(callSubs) | ka::constant_function(AnyReference(typeOf<void>()))));
        return object.connect(signalName, std::move(bounceEvent)).async();
      }
      else
      {
        return object.disconnect(link).async()
          .then([](Future<void> discFut) {
            if (!discFut.hasValue())
            {
              qiLogVerbose("qitype.proxysignal")
                << "Failed to disconnect from parent signal: "
                << (discFut.hasError() ? discFut.error() : "promise was cancelled");
            }
            return SignalBase::invalidSignalLink;
          });
      }
    }

    /// If non-empty, returns the value of the optional given to it. Otherwise calls some procedure.
    ///
    /// If the procedure is not non-returning, then the behavior is undefined.
    ///
    /// Procedure<void()> Proc
    template<typename Proc>
    struct SrcOptOrInvoke
    {
      Proc proc;
    // Regular:
      KA_GENERATE_FRIEND_REGULAR_OPS_1(SrcOptOrInvoke, proc)

    // ka::opt_t<T> -> T:
      template<typename T>
      T operator()(const ka::opt_t<T>& o) const
      {
        if (o.empty())
          proc();
        return *o;
      }
    };

    /// Helper-function to deduce types for `SrcOptOrInvoke`.
    template<typename Proc>
    SrcOptOrInvoke<Proc> srcOptOrInvoke(Proc proc) { return { ka::mv(proc) }; }

    /// Resets the bounce event callback on an object, and then sets the `OnSubscribers` callback
    /// to a copy of itself with the new signal link, continuously. Once called, an instance of
    /// this type is not meant to be called again.
    ///
    /// The signal pointer must be valid for the duration of this function call.
    ///
    /// Transformation<Procedure> LifeSignal
    /// Procedure<void(GenericFunctionParameters)> CallSubs
    template<typename LifeSignal, typename CallSubs>
    struct ResetBounceEventCallbackOnSubscribersContinuous
    {
      SignalBase* signal;
      LifeSignal lifeSignal;
      CallSubs callSubs;
      AnyWeakObject weakObject;
      std::string signalName;

      using result_type = Future<void>;

    // Procedure:
      result_type operator()(SignalLink link, bool enable) const
      {
        auto self = *this;
        return resetBounceEventCallback(callSubs, enable, weakObject, signalName, link)
           // link changed, rebind ourselves if we're still alive
          .andThen(lifeSignal(
            // Copy self instead of using `this` to avoid lifetime issues.
            [self](SignalLink newLink) {
              self.signal->setOnSubscribers(self.lifeSignal(boost::bind(self, newLink, std::placeholders::_1)));
            }));
      }
    };

    /// Helper-function to deduce types for `ResetBounceEventCallbackOnSubscribersContinuous`.
    template <typename LifeSignal, typename CallSubs>
    ResetBounceEventCallbackOnSubscribersContinuous<LifeSignal, CallSubs>
    resetBounceEventCallbackOnSubscribersContinuous(SignalBase& signal,
                                                    LifeSignal lifeSignal,
                                                    CallSubs callSubs,
                                                    AnyWeakObject weakObject,
                                                    std::string signalName)
    {
      return { &signal, ka::mv(lifeSignal), ka::mv(callSubs), ka::mv(weakObject),
               ka::mv(signalName) };
    }

    inline void setUpProxy(SignalBase& signal, AnyWeakObject object, const std::string& signalName)
    {
      using namespace ka;
      namespace ph = std::placeholders;

      // lockTransfo: (A... → B) → (A... → ka::opt_t<B>)
      // p ↦ (x... ↦ | ka::opt(p(x...))  if the weak_ptr could be locked,
      //             | ka::opt_t<B>()    otherwise, i.e. an empty ka::opt_t)
      auto lockTransfo = scope_lock_transfo(mutable_store(weak_ptr(signal._p)));

      // srcOrThrow: (A... → ka::opt_t<B>) → (A... → B)
      // p ↦ (x... ↦ | *p(x...)  if !p(x...).empty(),
      //             | throw     otherwise)
      auto srcOrThrow =
        std::bind(compose_t{},
                  srcOptOrInvoke([] { throw std::runtime_error("the signal has expired"); }),
                  ph::_1);

      // lifeSignal: (A... → B) → (A... → B)
      // Transforms a procedure p to one that first checks if the signal is
      // still alive, then calls p if alive, and throws otherwise.
      auto lifeSignal = compose(mv(srcOrThrow), mv(lockTransfo));

      auto callSubs = lifeSignal(std::bind(&SignalBase::callSubscribers, std::ref(signal),
                                           ph::_1, MetaCallType_Auto));

      signal.setOnSubscribers(lifeSignal(
        boost::bind(resetBounceEventCallbackOnSubscribersContinuous(signal, lifeSignal, callSubs,
                                                                    object, signalName),
                    SignalBase::invalidSignalLink, ph::_1)));

      // On signal trigger, just forward the trigger to the back-end. When the back-end gets
      // triggered, we get notified back, because we connect to the back-end by the 'bounce event'
      // callback, in which we can notify back our local subscribers.
      signal.setTriggerOverride(
        boost::bind(&details_proxysignal::metaPostSignal, object, signalName, ph::_1));
    }

    inline void tearDownProxy(SignalBase& sig)
    {
      sig.disconnectAll();
    }
  } // namespace details_proxysignal

  /// Signal proxy, using an AnyObject and signal id as back-end.
  template<typename T>
  class ProxySignal: public SignalF<T>
  {
  public:
    using SignalType = SignalF<T>;

    ProxySignal()
    {
    }

    ProxySignal(AnyObject object, const std::string& signalName)
      : SignalType()
    {
      details_proxysignal::setUpProxy(*this, object, signalName);
    }

    ~ProxySignal()
    {
      details_proxysignal::tearDownProxy(*this);
    }

    QI_API_DEPRECATED_MSG(Use qi::makeProxySignal instead)
    void setup(AnyObject object, const std::string& signalName)
    {
      details_proxysignal::setUpProxy(*this, object, signalName);
    }

    QI_API_DEPRECATED_MSG(This function might be removed in the future with no replacement)
    Future<void> onSubscribe(bool enable,
                             GenericObject* object,
                             std::string signalName,
                             SignalLink link)
    {
      return details_proxysignal::resetBounceEventCallback(*this, this->_p, enable,
                                                           AnyObject(object, &AnyObject::noDelete),
                                                           signalName, link);
    }

    QI_API_DEPRECATED_MSG(This function might be removed in the future with no replacement)
    AnyReference bounceEvent(const AnyReferenceVector args)
    {
      this->callSubscribers(args);
      return AnyReference(typeOf<void>());
    }

    QI_API_DEPRECATED_MSG(This function might be removed in the future with no replacement)
    void triggerOverride(const GenericFunctionParameters& params,
                         MetaCallType,
                         GenericObject* object,
                         std::string signalName)
    {
      return details_proxysignal::metaPostSignal(AnyObject(object, &AnyObject::noDelete),
                                                 signalName, params);
    }
  };

  inline void makeProxySignal(SignalBase& target, AnyObject object, const std::string& signalName)
  {
    details_proxysignal::setUpProxy(target, object, signalName);
  }

  template<typename T>
  void makeProxySignal(ProxySignal<T>& target, AnyObject object, const std::string& signalName)
  {
    details_proxysignal::setUpProxy(target, object, signalName);
  }
} // namespace qi

#endif  // _QITYPE_PROXYSIGNAL_HPP_


text:
package com.thebluealliance.androidclient.adapters;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.thebluealliance.androidclient.fragments.district.DistrictEventsFragment;
import com.thebluealliance.androidclient.fragments.district.DistrictRankingsFragment;

public class ViewDistrictFragmentPagerAdapter extends FragmentPagerAdapter {

    public static final String[] TITLES = {"Events", "Rankings"};

    private String mDistrictKey;

    public ViewDistrictFragmentPagerAdapter(FragmentManager fm, String districtKey) {
        super(fm);
        mDistrictKey = districtKey;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment f;
        switch (position) {
            default:
            case 0:
                f = DistrictEventsFragment.newInstance(mDistrictKey);
                break;
            case 1:
                f = DistrictRankingsFragment.newInstance(mDistrictKey);
                break;
        }
        return f;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }

    @Override
    public int getCount() {
        return TITLES.length;
    }
}


text:
[Disqus]: http://disqus.com/
[elf+js]: http://elfjs.com/
[ER]: http://www.errorrik.com/er/
[Express]: http://expressjs.com/
[GitHub]: https://github.com/
[Google Custom Search]: http://www.google.com/cse/
[Google Picasa]: https://picasaweb.google.com/
[Gravatar]: http://gravatar.com/
[handlebars]: http://handlebarsjs.com/
[HighlightJS]: http://softwaremaniacs.org/soft/highlight/en/
[Hogan.js]: http://twitter.github.io/hogan.js/
[jekyll]: https://github.com/mojombo/jekyll
[JSDuck]: https://github.com/senchalabs/jsduck
[jslib]: https://github.com/elfjs/jslib/
[jslib-builder]: http://github.com/elfjs/jslib-builder/
[Markdown]: http://daringfireball.net/projects/markdown/
[mustache]: http://mustache.github.io/
[node.js]: http://nodejs.org/
[SimpleGray]: https://github.com/mytharcher/SimpleGray
[SublimeLinter]: https://github.com/SublimeLinter/SublimeLinter
[Tangram]: http://tangram.baidu.com/
[WordPress]: http://wordpress.org/


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Terrain Engine 2D: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Terrain Engine 2D
    1.21

A 2D Block Engine

TerrainEngine2D.Chunk Member List

This is the complete list of members for TerrainEngine2D.Chunk, including all inherited members.

ChunkSize	TerrainEngine2D.Chunk

ChunkX	TerrainEngine2D.Chunk

ChunkY	TerrainEngine2D.Chunk

FluidChunk	TerrainEngine2D.Chunk

InitializeChunk(int chunkSize, int chunkX, int chunkY)	TerrainEngine2D.Chunk

ReGenerate(int chunkX, int chunkY)	TerrainEngine2D.Chunk

Update	TerrainEngine2D.Chunk

Generated on Thu Apr 30 2020 23:39:32 for Terrain Engine 2D by

     1.8.14


text:
module Comparisons.Sussed where

import Control.Category hiding ((>>>), (<<<))
import Control.Applicative
import Prelude hiding ((.), id)

import Melchior.Control
import Melchior.Data.String
import Melchior.Dom
import Melchior.Dom.Events
import Melchior.EventSources.Mouse
import Melchior.Dom.Selectors
import Melchior.Remote.XHR
import Melchior.Remote.Internal.ParserUtils
import Melchior.Sink
import Melchior.Time

main :: IO ()
main = runDom setupSorting

setupSorting :: [Element] -> Dom ()
setupSorting html = do
  inp <- Dom $ assuredly $ select (inputs . byId "inp" . from) html
  fetch <- Dom $ assuredly $ select (byId "remote" . from) html
  manualSorting html inp $ pure qsort
  setValue (toInput inp) $ stringify (remote GET "/numbers" (click fetch))

stringify :: Signal JSString -> Signal String
stringify s = (\x -> jsStringToString x) <$> s

manualSorting :: [Element] -> Input -> Signal ([Int] -> [Int]) -> Dom ()
manualSorting html inp sorter = do
  qout <- Dom $ assuredly $ select (byId "quick" . from) html
  mout <- Dom $ assuredly $ select (byId "merge" . from) html
  hout <- Dom $ assuredly $ select (byId "heap" . from) html
  appl <- Dom $ assuredly $ select (byId "applicative" . from) html
  let input = createEventedSignal (Of "string") inp (ElementEvt InputEvt)
  put appl $ sorter <*> ((\_ -> parseToNumbers $ value $ inp) <$> input)
  put qout ((\_ -> qsort $ parseToNumbers $ value $ inp) <$> input)
  put mout ((\_ -> msort $ parseToNumbers $ value $ inp) <$> input)
  put hout ((\_ -> hsort $ parseToNumbers $ value $ inp) <$> input)

merger :: [Signal JSString] -> Signal JSString
merger (x:[]) = x
merger (x:xs) = Melchior.Control.merge x $ merger xs

stringListToNumbers :: String -> [Int]
stringListToNumbers s = case parse numbers s of
  [] -> []
  (x:xs) -> map (\x -> read x) (fst x)

numbers = many1 numberAndDelim
numberAndDelim = do { n <- many1 digit; space; symb "," +++ return []; return n }

parseToNumbers :: JSString -> [Int]
parseToNumbers s = stringListToNumbers $ jsStringToString s

qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (pivot:rest) = (qsort lesser) ++ [pivot] ++ (qsort greater)
  where
    lesser = filter (< pivot) rest
    greater = filter (>= pivot) rest

msort :: Ord a => [a] -> [a]
msort []  = []
msort [x] = [x]
msort x   = merge (msort one) (msort two)
            where
              one = take half x
              two = drop half x
              half = div (length x) 2

merge :: Ord a => [a] -> [a] -> [a]
merge [] x = x
merge y [] = y
merge (x:xs) (y:ys) = case x < y of
  True -> x : merge xs (y:ys)
  False -> y : merge ys (x:xs)

data Heap a = Nil | Node a [Heap a]
heapify x = Node x []

hsort :: Ord a =>  [a] -> [a]
hsort h = flattenHeap $ mergeHeaps $ map heapify h
          where
            mergeHeaps = treeFold mergeHeap Nil
            flattenHeap Nil = []
            flattenHeap (Node x heaps) = x:flattenHeap (mergeHeaps heaps)
            mergeHeap h Nil = h
            mergeHeap a@(Node x heaps) b@(Node y heapd)
              | x < y = Node x (b:heaps)
              | otherwise = Node y (a:heapd)

treeFold _ x [] = x
treeFold _ _ [x] = x
treeFold f x (a:b:c) = treeFold f x (f a b : pairFold c)
                       where
                         pairFold (x:y:rest) = f x y : pairFold rest
                         pairFold a = a


text:
module LittleTranslator
  class Writer
    attr_accessor :translations

    def translations=(hash)
      @translations = hash
      write_translations
    end

    def write_translations
      self.translations.each do |locale, sections|
        locale_dir = File.join(Settings.locale_path, locale)
        File.send(:makedirs, locale_dir) unless File.exist?(locale_dir)
        sections.each do |section, translations|
          section_file = File.join(locale_dir, "#{section}.yml")
          File.open(section_file, 'w'){|file| file.write(translations.to_yaml) }
          logger.info(section_file.sub(%r{^#{Settings.locale_path}#{File::SEPARATOR}}, ''))
        end
      end
    end

    def logger
      Base.logger
    end

  end
end


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
MedicaidEligibilityApi::Application.initialize!


text:
package com.example.blue.myapplication.widget.thread;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;

public class ThreadManager {
    private static Handler uiHandler = null;
    private static ScheduledExecutorService pool = null;
    private static ScheduledExecutorService poolHigh = null;

    public ThreadManager() {
    }

    private static void checkInited() {
        if (uiHandler == null) {
            throw new IllegalStateException("ThreadManager.init NOT inited, you must call ThreadManager.init first");
        }
    }

    public static Handler getUIHandler() {
        checkInited();
        return uiHandler;
    }

    public static ScheduledExecutorService getPool() {
        checkInited();
        return pool;
    }

    public static ScheduledExecutorService getPoolHigh() {
        checkInited();
        return poolHigh;
    }

    public static synchronized void shutdown() {
        uiHandler.removeCallbacksAndMessages(null);
        uiHandler = null;
        if (pool != null) {
            pool.shutdown();
        }

        if (poolHigh != null) {
            poolHigh.shutdown();
        }

    }

    public static synchronized void shutdownNow() {
        uiHandler.removeCallbacksAndMessages(null);
        uiHandler = null;
        if (pool != null) {
            pool.shutdownNow();
        }

        if (poolHigh != null) {
            poolHigh.shutdownNow();
        }

    }

    public static synchronized void init(int poolSize, int highPoolSize) {
        if (uiHandler != null) {
            throw new IllegalStateException("ThreadManager.init already inited");
        } else {
            uiHandler = new Handler(Looper.getMainLooper());
            if (poolSize > 0) {
                pool = Executors.newScheduledThreadPool(poolSize, new ThreadFactory() {
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setPriority(Thread.NORM_PRIORITY);
                        t.setDaemon(true);
                        return t;
                    }
                });
            }

            if (highPoolSize > 0) {
                poolHigh = Executors.newScheduledThreadPool(highPoolSize, new ThreadFactory() {
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setPriority(Thread.MAX_PRIORITY);
                        t.setDaemon(true);
                        return t;
                    }
                });
            }

        }
    }
}


text:
class SafeTopWidget : public QWidget
{
    Q_OBJECT
public:
    explicit SafeTopWidget(QWidget *parent = 0);

signals:

public slots:

};

#endif // SAFETOPWIDGET_H


text:
layout: page
---

One of the projects I work on is a fairly sizeable Symfony2 application, and while it's always been deployed on Linux, until fairly recently I'd been developing it on OSX. This seems to be a fairly standard setup these days.

But I've always thought it would be nicer to be closer to the target environment. Especially when developing against and integrating with the various components the application uses. Examples of these things would be email proxies, metrics and logging backends, and search infrastructure. So I've made the move to using Vagrant, provisioned as our servers are with Ansible - and it's great!

The first downside I hit though was trying to use the Assetic --watch switch to dynamically rebuild my Js/CSS assets as I modified them. The problem I was seeing was that changes to files were regularly taking up to 30 seconds to get picked up and rebuilt, obviously too slow. This is an essential part of my workflow, I change and save very frequently so updating these manually is simply not an option.

I hunted around online for some suggestions to see if I was missing something, found a few good articles, but was already using the techniques they listed as speedups. Those being...

Use NFS for shared folders
Use opcache
Disable xdebug
Mount cache/logs to tmpfs

The next thing I tried was the new rsync support in Vagrant 1.5, but wasn't massively hopefully after reading that it didn't scale particularly well to large projects. And my problems here were twofold...

Vagrant was a little slow to sync
Permissions

The first problem was a bit off putting, but with some suggestions I thought maybe I could optimise my way around it. The permissions issue though was that the Vagrant rsync support copies files to the guest owned by the user vagrant:vagrant, and doesn't seem to be configurable. I already have a mix of users going on with my Ansible provisioning and my applications running under php-fpm. Adding another into this seemed to be quite clumsy, and when coupled to the fact that the rsync support wasn't that fast anyway, I didn't want to pursue this any further.

While I was gnashing and wrangling over all this my pal and top clever boy @BenjaminDavies had taken a look into alternative scanning/dumping solutions, with one of the top options being fswatch. It looked simple so I cloned, compiled and using an example from Stackoverflow gave it a try...

```
fswatch src/My/Bundle/Resources/public "app/console assetic:dump"
```

Turns out this is from an older version of the tool, and the current version doesn't support executing a command when changes are detected. Instead, it prints the path to the changed file to stdout. Ben sends me an updated one-liner and I paste it without blinking (my eyes beginning to bulge at this stage of rage)

```
fswatch src/my/Bundle/Resources/public | while read line; \
  do app/console assetic:dump; done
```

But editing files does nothing.  FML. The problem this time was that I was running this on the host not the guest, and the database configuration details wouldn't work from here. "Database?" I hear you say, but I thought you were dumping assets? It would seem booting a Symfony application which has Doctrine configured will connect to the database on boot.

So...  what now?  Well I'm already a few hours of wasted time in here, so decide to create a new config environment especially for Assetic, which doesn't have any database configuration, saving this in app/config/config_assetic.yml. Even this turned out to be a lot more painful than I'd hoped, but I got there in the end.

```
fswatch src/My/Bundle/Resources/public | while read line; \
  do app/console assetic:dump --env=assetic; done
```

It was a long ride any many thanks to Ben for sticking by me during my dark moments of despair.

Using this with my NFS mounted folder in Vagrant is now acceptably fast. Though not perfect. I may have to visit a better, simpler, solution when my blood pressure returns to normal.

I'm sure there are a million better solutions to this, and I'd love to hear how other people are solving this problem. So please let me know!


text:
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

/**
 * @description
 * Wraps an Express application so prioritized middleware can be added.
 * @param app The Express app.
 * @constructor
 */
var ExpressApp = function(app, scope) {
  this.app = app;
  this.scope = scope;
  this.registrations = [];
  this.locked = false;
};

/**
 * @description
 * Adds a prioritized registration function.
 * Registration functions will be added in order of growing priority.
 * @param {Number} priority The priority of the registration.
 * @param {Function} registration
 * The function that does the registration. Takes the Express app as its parameter.
 */
ExpressApp.prototype.register = function(priority, registration) {
  if (this.locked) {
    var t = this.scope.require('localization');
    throw new Error(t('Can\'t register middleware on a locked application.'));
  }
  registration.routePriority = priority;
  this.registrations.push(registration);
};

/**
 * @description
 * Locks the application so no new registration can be done.
 * Executes all the registration functions in priority order.
 */
ExpressApp.prototype.lock = function() {
  var self = this;
  self.registrations
    .sort(function orderByRoutePriority(registrationA, registrationB) {
      return registrationA.routePriority - registrationB.routePriority;
    })
    .forEach(function registerWithApp(registration) {
      registration(self.app);
    });
  var log = self.scope.require('log');
  if (log ) log.verbose('Registered Express middleware.');
  self.locked = true;
};

module.exports = ExpressApp;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SAF.SM.Api
{
    /// <summary>
    /// 店铺分类
    /// </summary>
    [RoutePrefix("api/sm/category")]
    public class CategoryController : ApiController
    {
    }
}