text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Tubaria venosa Henn.

### Remarks
null


text:
<f:layout name="Login" />

<f:section name="loginFormFields">

				<input type="text" id="t3-username" name="username" value="{presetUsername}" placeholder="{f:translate(key: 'login.username')}" class="form-control input-login t3js-clearable t3js-login-username-field" autofocus="autofocus" required="required" />

				<input type="password" id="t3-password" name="p_field" value="{presetPassword}" placeholder="{f:translate(key: 'login.password')}" class="form-control input-login t3js-clearable t3js-login-password-field" required="required" data-rsa-encryption="t3-field-userident" />

</f:section>

redpajama_set_name: RedPajamaGithub


text:
using System;
using ShinobiStockChart.Core.Model;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using ShinobiStockChart.Core.Presenter.Service;
using System.IO;

namespace ShinobiStockChart.Core.Presenter
{
    public class StockPriceListPresenter : BasePresenter
    {
        public interface View
        {
            void SetStockPrices (List<StockItem> prices);

            event EventHandler<StockSelectedEventArgs> StockSelected;
        }

        private string FTSE100 = "AAL.L,ABF.L,ADM.L,AGK.L,AMEC.L,ANTO.L,ARM.L,AU.L,AV.L,AZN.L,BA.L,BARC.L,BATS.L,BG.L,BLND.L,BLT.L,BP.L,BRBY.L,BSY.L,BT-A.L,CCL.L,CNA.L,CNE.L,CPG.L,CPI.L,CSCG.L,DGE.L,EMG.L,ENRC.L,ESSR.L,EXPN.L,FRES.L,GFS.L,GKN.L,GLEN.L,GSK.L,HL.L,HMSO.L,HSBA.L,IAG.L,IAP.L,IHG.L,III.L,IMI.L,IMT.L,INVP.L,IPR.L,ISAT.L,ITRK.L,ITV.L,JMAT.L,KAZ.L,KGF.L,LAND.L,LGEN.L,LLOY.L,LMI.L,MKS.L,MRW.L,NG.L,NXT.L,OML.L,PFC.L,PRU.L,PSON.L,RB.L,RBS.L,RDSA.L,RDSB.L,REX.L,RIO.L,RR.L,RRS.L,RSA.L,RSL.L,SAB.L,SBRY.L,SDR.L,SDRC.L,SGE.L,SHP.L,SL.L,SMIN.L,SN.L,SRP.L,SSE.L,STAN.L,SVT.L,TATE.L,TLW.L,TSCO.L,ULVR.L,UU.L,VED.L,VOD.L,WEIR.L,WG.L,WOS.L,WPP.L,WTB.L,XTA.L";

        private View _view;

        private IDataSource _dataSource = new WebDataSource();

        private IAppStatusService _statusService;

        private IMarshalInvokeService _marshalInvoke;

        private INavigationService _navigationService;

        private List<StockItem> _stocks = new List<StockItem> ();

        public StockPriceListPresenter (IAppStatusService statusService, IMarshalInvokeService marshalInvoke, INavigationService navigationService)
            : base("FTSE 100")
        {
            _statusService = statusService;
            _marshalInvoke = marshalInvoke;
            _navigationService = navigationService;

            // generate the stock data items from a CSV list
            var symbols = FTSE100.Split (',');
            foreach (var symbol in symbols) {
                _stocks.Add (new StockItem (symbol));
            }

            FetchQuotes ();
        }

        public void SetView(View view)
        {
            _view = view;
            _view.StockSelected += HandleStockSelected;
        }

        private void HandleStockSelected (object sender, StockSelectedEventArgs e)
        {
            _navigationService.PushPresenter (new StockChartPresenter (_statusService, _marshalInvoke, e.SelectedItem));
        }

        /// <summary>
        /// Fetches the current stock quote from Yahoo
        /// </summary>
        private void FetchQuotes ()
        {
            _statusService.NetworkActivityIndicatorVisible = true;

            _dataSource.FetchStockList (csv => ParseStockQuotes (csv));
        }

        private void ParseStockQuotes (string quotesCSV)
        {
            // split each line
            var lines = quotesCSV.Split (new char[] { '\n', '\r' });
            foreach (var line in lines) {
                // fail fast on any stocks that lack prices
                if (line.Contains ("N/A"))
                    continue;

                // split each item within the line
                var components = line.Split (',');
                if (components.Length > 1) {
                    try {
                        // extract the symbol, price and change
                        string symbol = components [0].Replace ("\"", "");
                        double quote = double.Parse (components [1]);
                        double change = double.Parse (components [2]);

                        // locate the respective data item and update its state
                        var stockItem = _stocks.SingleOrDefault (s => s.Symbol == symbol);
                        if (stockItem != null) {
                            stockItem.Price = quote;
                            stockItem.Change = change;
                        }
                    } catch {
                    }
                }
            }

            _marshalInvoke.Invoke (() => {
                _statusService.NetworkActivityIndicatorVisible = false;
                _view.SetStockPrices(_stocks);
            });
        }

    }
}


text:
from __future__ import with_statement
import setuptools

requires = [
    "flake8"
]

setuptools.setup(
    name='flake8_sklearn_rcheck',
    version='0.1',
    description="check if `random_state` argument is set, plugin for flake8",
    keywords='flake8 scikit-learn random_state',
    author='Erik C. Fredriksen',
    author_email='erik.fredriksen@phdstudent.hhs.se',
    url='https://github.com/nuffe/flake8-sklearn-rcheck',
    license='MIT',
    py_modules=['flake8_sklearn_rcheck'],
    zip_safe=False,
    install_requires=requires,
    entry_points={
        'flake8.extension': [
            'S = flake8_sklearn_rcheck:RandomStateCheck',
        ],
    },
    classifiers=[
        "Framework :: Flake8",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Software Development :: Quality Assurance",
    ],
)


text:
@implementation Counts
@end


text:
from cms.utils.moderator import get_cmsplugin_queryset
from cms.utils import get_language_from_request
from cms import settings
from django.conf import settings as django_settings
from cms.plugin_pool import plugin_pool
from cms.plugins.utils import get_plugins
from django.template.defaultfilters import title
from django.template.loader import render_to_string
import copy

def render_plugins_for_context(placeholder_name, page, context_to_copy, theme=None):
    """
    renders plugins for the given named placedholder and page using shallow copies of the
    given context
    """
    context = copy.copy(context_to_copy)
    l = get_language_from_request(context['request'])
    request = context['request']
    plugins = [plugin for plugin in get_plugins(request, page) if plugin.placeholder == placeholder_name]
    if settings.CMS_PLACEHOLDER_CONF and placeholder_name in settings.CMS_PLACEHOLDER_CONF:
        if "extra_context" in settings.CMS_PLACEHOLDER_CONF[placeholder_name]:
            context.update(settings.CMS_PLACEHOLDER_CONF[placeholder_name]["extra_context"])
    if theme:
        # this may overwrite previously defined key [theme] from settings.CMS_PLACEHOLDER_CONF
        context.update({'theme': theme,})
    c = []
    edit = False
    if ("edit" in request.GET or request.session.get("cms_edit", False)) and 'cms.middleware.toolbar.ToolbarMiddleware' in django_settings.MIDDLEWARE_CLASSES and request.user.is_staff and request.user.is_authenticated:
        edit = True
    if edit:
        installed_plugins = plugin_pool.get_all_plugins(placeholder_name, page)
        name = placeholder_name
        if settings.CMS_PLACEHOLDER_CONF and placeholder_name in settings.CMS_PLACEHOLDER_CONF:
            if "name" in settings.CMS_PLACEHOLDER_CONF[placeholder_name]:
                name = settings.CMS_PLACEHOLDER_CONF[placeholder_name]['name']
        name = title(name)
        c.append(render_to_string("cms/toolbar/add_plugins.html", {'installed_plugins':installed_plugins,
                                                               'language':request.LANGUAGE_CODE,
                                                               'placeholder_label':name,
                                                               'placeholder_name':placeholder_name,
                                                               'page':page,
                                                               }))
    for index, plugin in enumerate(plugins):
        context['plugin_index'] = index
        c.append(plugin.render_plugin(copy.copy(context), placeholder_name, edit=edit))
    return "".join(c)


text:
<!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script src="../../../resources/bluetooth/bluetooth-helpers.js"></script>
<script>
'use strict';
promise_test(() => {
  return setBluetoothFakeAdapter('HeartRateAdapter')
    .then(() => requestDeviceWithKeyDown({
      filters: [{services: ['heart_rate']}]}))
    .then(device => device.gatt.connect())
    .then(gattServer => gattServer.getPrimaryService('heart_rate'))
    .then(service => service.getCharacteristic('heart_rate_measurement'))
    .then(characteristic => {
      return characteristic.startNotifications()
        .then(start_characteristic => {
          assert_equals(start_characteristic, characteristic,
                  'Start characteristic should be the same as characteristic.');
        });
    });
  // TODO(ortuno): Assert that notifications are active.
  // http://crbug.com/600762
}, 'Single start notifications succeeds.');
</script>


text:
// Copyright 2011 Ernst Naezer, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

namespace ServerApp
{
    using System;
    using System.IO;
    using MassTransit.Transports.Stomp;
    using log4net.Config;
    using Magnum.Extensions;
    using MassTransit;
    using MassTransit.Saga;
    using MassTransit.Services.Subscriptions.Server;
    using Ultralight;
    using Ultralight.Listeners;

    internal class Program
    {
        private const string Host = "stomp://localhost:61614/queue";

        private static void Main(string[] args)
        {
            XmlConfigurator.Configure(new FileInfo("runner.log4net.xml"));

            // comment me to use an external stomp broker
            StartWebsocketServer();

            StartSubscriptionService();

            Console.Out.WriteLine("starting the servicebus");
            var serviceBus = ServiceBusFactory
                .New(sbc =>
                         {
                             sbc.ReceiveFrom("{0}/server".FormatWith(Host));
                             sbc.UseStomp();

                             sbc.UseSubscriptionService("{0}/mt_subscriptions".FormatWith(Host));
                             sbc.UseControlBus();

                             sbc.Subscribe(s => s.Handler<PongMessage>(x => Console.Out.WriteLine("x.Tag = {0}", x.Tag)));
                         });

            Console.WriteLine("ready... press enter to fire and 'exit' to stop");

            while (Console.ReadLine() != "exit")
            {
                serviceBus.Publish(
                    new PingMessage {Tag = DateTime.Now.ToString()},
                    contextCallback => contextCallback.IfNoSubscribers( () => Console.WriteLine("Make sure the browser is connected...")));
            }
        }

        private static void StartSubscriptionService()
        {
            Console.Out.WriteLine("starting the subscription service");

            var subscriptionSagaRepository = new InMemorySagaRepository<SubscriptionSaga>();
            var clientSagaRepository = new InMemorySagaRepository<SubscriptionClientSaga>();

            var serviceBus =
                ServiceBusFactory.New(sbc =>
                                          {
                                              sbc.UseStomp();

                                              sbc.ReceiveFrom("{0}/mt_subscriptions".FormatWith(Host));
                                              sbc.SetConcurrentConsumerLimit(1);
                                          });

            var subscriptionService = new SubscriptionService(serviceBus, subscriptionSagaRepository,
                                                              clientSagaRepository);
            subscriptionService.Start();
        }

        private static void StartWebsocketServer()
        {
            Console.Out.WriteLine("starting the websockets service");

            var wsListener = new StompWsListener(new Uri("ws://localhost:61614/"));
            var server = new StompServer(wsListener);
            server.Start();
        }
    }

    public class PingMessage
    {
        public string Tag { get; set; }
    }

    public class PongMessage
    {
        public string Tag { get; set; }
    }
}


text:
<?php

return array(
    'name'=>'Console - Maintenance',
    // application components
    'components'=>array(
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'logFile'=>'console-Maintenance.log',
                    'levels'=>'error, warning',
                ),
                array(
                    'class'=>'CFileLogRoute',
                    'logFile'=>'console-Maintenance-Trace.log',
                    'levels'=>'trace',
                ),
            ),
        ),
    ));


text:
<?php

namespace JiriNapravnik\Form\Controls;

use Nette\DateTime;
use Nette\Forms\Controls\BaseControl;
use Nette\Forms\Form;
use Nette\Forms\Helpers;
use Nette\Forms\IControl;
use Nette\Utils\Html;

class DateInput extends BaseControl
{

	private $day, $month, $year;

	public function __construct($label = NULL)
	{
		parent::__construct($label);
		$this->setRequired(FALSE)
			->addRule(__CLASS__ . '::validateDate', 'Neexistující datum.');
	}

	public function setValue($value)
	{
		if ($value) {
			$date = DateTime::from($value);
			$this->day = $date->format('j');
			$this->month = $date->format('n');
			$this->year = $date->format('Y');
		} else {
			$this->day = $this->month = $this->year = NULL;
		}
	}

	/**
	 * @return DateTime|NULL
	 */
	public function getValue()
	{
		$year = $this->year;
		$month = $this->month;
		$day = $this->day;

		$validated = self::validateDate($this);

		if($validated && $year > 0 && $month > 0 && $day > 0){
			return date_create()->setDate($year, $month, $day);
		}
		return NULL;
	}

	public function loadHttpData()
	{
		$this->day = $this->getHttpData(Form::DATA_LINE, '[day]');
		$this->month = $this->getHttpData(Form::DATA_LINE, '[month]');
		$this->year = $this->getHttpData(Form::DATA_LINE, '[year]');
	}

	/**
	 * Generates control's HTML element.
	 */
	public function getControl()
	{

		parent::getControl();

		$days = array('' => 'Den') + array_combine(range(1, 31), range(1, 31));
		$yearsRange = range(date('Y'), date('Y') - 110);
		$years = array('' => 'Rok') + array_combine($yearsRange, $yearsRange);

		$monthsCzech = \JiriNapravnik\Common\DateCzech::getCzechMonthsNominativNumericKeys();
		$months = array('' => 'Měsíc');
		for ($i = 1; $i <= 12; $i++) {
			$months[$i] = $monthsCzech[$i];
		}

		$name = $this->getHtmlName();

		return Html::el()
				->addHtml(Helpers::createSelectBox(
						$days, array('selected?' => $this->day)
					)->name($name . '[day]')
					->class('form-control day')
				)
				->addHtml(Helpers::createSelectBox(
						$months, array('selected?' => $this->month)
					)->name($name . '[month]')
					->class('form-control month')
				)
				->addHtml(Helpers::createSelectBox(
						$years, array('selected?' => $this->year)
					)->name($name . '[year]')
					->class('form-control year')
		);
	}

	/**
	 * @return bool
	 */
	public static function validateDate(IControl $control)
	{
		$year = $control->year;
		$month = $control->month;
		$day = $control->day;

		if (!$control->isRequired() && $year === $month && $month === $day && $day === '') {
			return TRUE;
		} elseif ($year > 0 && $month > 0 && $day > 0) {
			return checkdate($month, $day, $year);
		} else {
			return FALSE;
		}
	}

}


text:
#include <rtai_sched.h>
#include <stdio.h>
#include <signal.h>
#include <rtai_shm.h>
#include <rtai.h>
#include <rtai_sem.h>
#include "m3rt/base/m3ec_def.h>
#include "m3rt/base/m3rt_def.h>
#include <rtai_nam2num.h>
#include <rtai_registry.h>
#include "m3/robots/humanoid_shm_sds.h"
#include "m3/hardware/joint_mode_ros.pb.h"
#include "m3/robots/chain_name.h"
#include <string>
#include <iomanip>
#include <locale>
#include <sstream>

// Needed for ROS
#include <ros/ros.h>
#include "m3ctrl_msgs/M3JointCmd.h"
#include <sensor_msgs/JointState.h>
#include <geometry_msgs/Wrench.h>

#include <tf/transform_broadcaster.h>

#define RT_TASK_FREQUENCY_MEKA_OMNI_SHM 100
#define RT_TIMER_TICKS_NS_MEKA_OMNI_SHM (1000000000 / RT_TASK_FREQUENCY_MEKA_OMNI_SHM)		//Period of rt-timer
#define MEKA_ODOM_SHM "TSHMM"
#define MEKA_ODOM_CMD_SEM "TSHMC"
#define MEKA_ODOM_STATUS_SEM "TSHMS"
#define MEKA_NDOF_HEAD 0
#define MEKA_NDOF_RIGHT_ARM 7
#define MEKA_NDOF_LEFT_ARM 7
#define MEKA_NDOF_TORSO 0
#define MEKA_NDOF_TOTAL MEKA_NDOF_HEAD + MEKA_NDOF_RIGHT_ARM + MEKA_NDOF_LEFT_ARM + MEKA_NDOF_TORSO

#define CYCLE_TIME_SEC 4

////////////////////////////////////////////////////////////////////////////////////
static int sys_thread_active = 0;
static int sys_thread_end=0;
static int end=0;
static int hst;
static M3HumanoidShmSdsCommand cmd;
static M3HumanoidShmSdsStatus status;
static int sds_status_size;
static int sds_cmd_size;
static long step_cnt = 0;
static void endme(int dummy) { std::cout << "END\n"; end=1; }
sensor_msgs::JointState joint_state_g;
m3ctrl_msgs::M3JointCmd joint_cmd_g;
geometry_msgs::Wrench right_wrench_g;
geometry_msgs::Wrench left_wrench_g;
ros::Publisher publisher_left_g;
ros::Publisher publisher_right_g;
ros::Subscriber cmd_sub_g;
//tf::TransformBroadcaster odom_broadcaster;
////////////////////////////////////////////////////////////////////////////////////

///////  Periodic Control Loop:
void StepShm();
void commandCallback(const m3ctrl_msgs::M3JointCmdConstPtr& msg);

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

void SetTimestamp(int64_t  timestamp)
{
  cmd.timestamp = timestamp;
    return;
}

int64_t GetTimestamp()
{
    return status.timestamp;
}

////////////////////////// MAIN COMPUTATION METHOD /////////////////////////////

void StepShm(int cntr)
{

    //SetTimestamp(GetTimestamp()); //Pass back timestamp as a heartbeat

    //right_wrench_g.header.stamp = ros::Time::now();
    //left_wrench_g.header.stamp = ros::Time::now();

     int j = 0;
  /*for (int i = 0; i < MEKA_NDOF_RIGHT_ARM; i++)
  {
    joint_state_g.position[j] = DEG2RAD(status.right_arm.theta[i]);
    joint_state_g.velocity[j] = DEG2RAD(status.right_arm.thetadot[i]);
    joint_state_g.effort[j] = status.right_arm.torque[i];
    j++;

  }

  for (int i = 0; i < MEKA_NDOF_LEFT_ARM; i++)
  {
    joint_state_g.position[j] = DEG2RAD(status.left_arm.theta[i]);
    joint_state_g.velocity[j] = DEG2RAD(status.left_arm.thetadot[i]);
    joint_state_g.effort[j] = status.left_arm.torque[i];
    j++;
  }

  for (int i = 0; i < MEKA_NDOF_HEAD; i++)
  {
    joint_state_g.position[j] = DEG2RAD(status.head.theta[i]);
    joint_state_g.velocity[j] = DEG2RAD(status.head.thetadot[i]);
    joint_state_g.effort[j] = status.head.torque[i];
      j++;
  }

  for (int i = 0; i < MEKA_NDOF_TORSO; i++)
  {
    joint_state_g.position[j] = DEG2RAD(status.torso.theta[i]);
    joint_state_g.velocity[j] = DEG2RAD(status.torso.thetadot[i]);
    joint_state_g.effort[j] = status.torso.torque[i];
      j++;
  }*/

  right_wrench_g.force.x = status.right_loadx6.wrench[0];
  right_wrench_g.force.y = status.right_loadx6.wrench[1];
  right_wrench_g.force.z = status.right_loadx6.wrench[2];
  right_wrench_g.torque.x = status.right_loadx6.wrench[3];
  right_wrench_g.torque.y = status.right_loadx6.wrench[4];
  right_wrench_g.torque.z = status.right_loadx6.wrench[5];

  left_wrench_g.force.x = status.left_loadx6.wrench[0];
  left_wrench_g.force.y = status.left_loadx6.wrench[1];
  left_wrench_g.force.z = status.left_loadx6.wrench[2];
  left_wrench_g.torque.x = status.left_loadx6.wrench[3];
  left_wrench_g.torque.y = status.left_loadx6.wrench[4];
  left_wrench_g.torque.z = status.left_loadx6.wrench[5];

    publisher_right_g.publish(right_wrench_g);
    publisher_left_g.publish(left_wrench_g);

     /*if (cntr % 100 == 0)
      {
	if (1)
	{
	  printf("********************************\n");
	  printf("timestamp: %ld\n", status.timestamp);
	  {
	    printf("------------------------------\n");
	    printf("force x: %f\n", status.right_loadx6.wrench[0]);
	     printf("------------------------------\n");
	    printf("\n");
	  }
	}
      }*/

     /*cmd.right_arm.q_desired[0] = 0;
      cmd.right_arm.slew_rate_q_desired[0] = 30;
      cmd.right_arm.q_stiffness[0] = 1.0;
      cmd.right_arm.ctrl_mode[0] = JOINT_ARRAY_MODE_THETA_GC;
      cmd.right_arm.smoothing_mode[0] = SMOOTHING_MODE_SLEW; */

}

void commandCallback(const m3ctrl_msgs::M3JointCmdConstPtr& msg)
{

  for (int i = 0; i < msg->chain.size(); i++)
  {
    int chain_idx = msg->chain_idx[i];
    if ((M3Chain)msg->chain[i] == RIGHT_ARM)
    {
      if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_OFF)
	cmd.right_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA)
	cmd.right_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA_GC)
	cmd.right_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA_GC;
      else
	cmd.right_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;

      cmd.right_arm.q_desired[chain_idx] = msg->position[i];
      cmd.right_arm.slew_rate_q_desired[chain_idx] = msg->velocity[i];
      cmd.right_arm.q_stiffness[chain_idx] = msg->stiffness[i];
      cmd.right_arm.smoothing_mode[chain_idx] = (SMOOTHING_MODE)msg->smoothing_mode[i];
    }
    else if ((M3Chain)msg->chain[i] == LEFT_ARM)
    {
      if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_OFF)
	cmd.left_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA)
	cmd.left_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA_GC)
	cmd.left_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA_GC;
      else
	cmd.left_arm.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;

      cmd.left_arm.q_desired[chain_idx] = msg->position[i];
      cmd.left_arm.slew_rate_q_desired[chain_idx] = msg->velocity[i];
      cmd.left_arm.q_stiffness[chain_idx] = msg->stiffness[i];
      cmd.left_arm.smoothing_mode[chain_idx] = (SMOOTHING_MODE)msg->smoothing_mode[i];
    }
    else if ((M3Chain)msg->chain[i] == HEAD)
    {
      if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_OFF)
	cmd.head.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA)
	cmd.head.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA_GC)
	cmd.head.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA_GC;
      else
	cmd.head.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      cmd.head.q_desired[chain_idx] = msg->position[i];
      cmd.head.slew_rate_q_desired[chain_idx] = msg->velocity[i];
      cmd.head.q_stiffness[chain_idx] = msg->stiffness[i];
      cmd.head.smoothing_mode[chain_idx] = (SMOOTHING_MODE)msg->smoothing_mode[i];
    }
    else if ((M3Chain)msg->chain[i] == TORSO)
    {
       if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_OFF)
	cmd.torso.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA)
	cmd.torso.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA;
      else if ((JOINT_MODE_ROS)msg->control_mode[i] == JOINT_MODE_ROS_THETA_GC)
	cmd.torso.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_THETA_GC;
      else
	cmd.torso.ctrl_mode[chain_idx] = JOINT_ARRAY_MODE_OFF;
      cmd.torso.q_desired[chain_idx] = msg->position[i];
      cmd.torso.slew_rate_q_desired[chain_idx] = msg->velocity[i];
      cmd.torso.q_stiffness[chain_idx] = msg->stiffness[i];
      cmd.torso.ctrl_mode[chain_idx] = (JOINT_ARRAY_MODE)msg->control_mode[i];
      cmd.torso.smoothing_mode[chain_idx] = (SMOOTHING_MODE)msg->smoothing_mode[i];
    }
  }

}

sensor_msgs::JointState GetInitialJointStateMessage()
{
//Hard-coded for now
/*std_msgs/Header header
  uint32 seq
  time stamp
  string frame_id
string[] name
float64[] position
float64[] velocity
float64[] effort
*/
  sensor_msgs::JointState joint_state;
  joint_state.header.stamp = ros::Time::now();
  joint_state.header.frame_id = "humanoid";

  joint_state.name.resize(MEKA_NDOF_TOTAL);
  joint_state.position.resize(MEKA_NDOF_TOTAL,0.0);
  joint_state.velocity.resize(MEKA_NDOF_TOTAL,0.0);
  joint_state.effort.resize(MEKA_NDOF_TOTAL,0.0);

  int j = 0;
  for (int i = 0; i < MEKA_NDOF_RIGHT_ARM; i++)
  {
    std::ostringstream convert;
    std::string int_str;
    convert << i;
    int_str = convert.str();
    joint_state.name[j] = std::string("right_arm_j") + int_str;
    j++;

  }

  for (int i = 0; i < MEKA_NDOF_LEFT_ARM; i++)
  {
    std::ostringstream convert;
    std::string int_str;
    convert << i;
    int_str = convert.str();
    joint_state.name[j] = std::string("left_arm_j") + int_str;
    j++;
  }

  for (int i = 0; i < MEKA_NDOF_HEAD; i++)
  {
    std::ostringstream convert;
    std::string int_str;
    convert << i;
    int_str = convert.str();
    joint_state.name[j] = std::string("head_j") + int_str;
      j++;
  }

  for (int i = 0; i < MEKA_NDOF_TORSO; i++)
  {
    std::ostringstream convert;
    std::string int_str;
    convert << i;
    int_str = convert.str();
    joint_state.name[j] = std::string("torso_j") + int_str;
      j++;
  }

  return joint_state;
}

////////////////////////// RTAI PROCESS BOILERPLATE /////////////////////////////

static void* rt_system_thread(void * arg)
{
	SEM * status_sem;
	SEM * command_sem;
	RT_TASK *task;
	int cntr=0;
	M3Sds * sds = (M3Sds *)arg;
	printf("Starting real-time thread\n");

	sds_status_size = sizeof(status);
	sds_cmd_size = sizeof(cmd);

	memset(&cmd, 0, sds_cmd_size);

	task = rt_task_init_schmod(nam2num("WSHMP"), 0, 0, 0, SCHED_FIFO, 0xF);
	rt_allow_nonroot_hrt();
	if (task==NULL)
	{
		printf("Failed to create RT-TASK TSHMP\n");
		return 0;
	}
	status_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_STATUS_SEM));
	command_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_CMD_SEM));
	if (!status_sem)
	{
		printf("Unable to find the %s semaphore.\n",MEKA_ODOM_STATUS_SEM);
		//rt_task_delete(task);
		return 0;
	}
	if (!command_sem)
	{
		printf("Unable to find the %s semaphore.\n",MEKA_ODOM_CMD_SEM);
		//rt_task_delete(task);
		return 0;
	}

	RTIME tick_period = nano2count(RT_TIMER_TICKS_NS_MEKA_OMNI_SHM);
	RTIME now = rt_get_time();
	rt_task_make_periodic(task, now + tick_period, tick_period);
	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();
	long long start_time, end_time, dt;
	long long step_cnt = 0;
	sys_thread_active=1;

	while(!sys_thread_end)
	{
		start_time = nano2count(rt_get_cpu_time_ns());
		rt_sem_wait(status_sem);
		memcpy(&status, sds->status, sds_status_size);
		rt_sem_signal(status_sem);

		StepShm(cntr);

		/*rt_sem_wait(command_sem);
		memcpy(sds->cmd, &cmd, sds_cmd_size);
		rt_sem_signal(command_sem);*/

		end_time = nano2count(rt_get_cpu_time_ns());
		dt=end_time-start_time;
		/*
		Check the time it takes to run components, and if it takes longer
		than our period, make us run slower. Otherwise this task locks
		up the CPU.*/
		if (dt > tick_period && step_cnt>10)
		{
			printf("Step %lld: Computation time of components is too long. Forcing all components to state SafeOp.\n",step_cnt);
			printf("Previous period: %f. New period: %f\n", (double)count2nano(tick_period),(double)count2nano(dt));
 			tick_period=dt;
			//rt_task_make_periodic(task, end + tick_period,tick_period);
		}
		step_cnt++;
		if (cntr++ == CYCLE_TIME_SEC * 2 * RT_TIMER_TICKS_NS_MEKA_OMNI_SHM)
		  cntr = 0;
		rt_task_wait_period();
	}
	printf("Exiting RealTime Thread...\n",0);
	rt_make_soft_real_time();
	rt_task_delete(task);
	sys_thread_active=0;
	return 0;
}

////////////////////////////////////////////////////////////////////////////////////
int main (int argc, char **argv)
{
	RT_TASK *task;
	M3Sds * sys;
	int cntr=0;

	rt_allow_nonroot_hrt();

	/*ros::init(argc, argv, "base_controller"); // initialize ROS node
  	ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing
  	spinner.start();
        ros::NodeHandle root_handle;*/

	ros::init(argc, argv, "loadx6_publisher", ros::init_options::NoSigintHandler); // initialize ROS node
	ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing
	spinner.start();
        ros::NodeHandle root_handle;
	ros::NodeHandle p_nh("~");

//	cmd_sub_g = root_handle.subscribe<m3ctrl_msgs::M3JointCmd>("humanoid_command", 1, &commandCallback);

	//joint_state_g = GetInitialJointStateMessage();
	publisher_right_g = root_handle.advertise<geometry_msgs::Wrench>("loadx6_right_state", 1, true);
	publisher_left_g = root_handle.advertise<geometry_msgs::Wrench>("loadx6_left_state", 1, true);

	signal(SIGINT, endme);

	if (sys = (M3Sds*)rt_shm_alloc(nam2num(MEKA_ODOM_SHM),sizeof(M3Sds),USE_VMALLOC))
		printf("Found shared memory starting shm_loadx6_controller.");
	else
	{
		printf("Rtai_malloc failure for %s\n",MEKA_ODOM_SHM);
		return 0;
	}

	rt_allow_nonroot_hrt();
	/*if (!(task = rt_task_init_schmod(nam2num("TSHM"), RT_TASK_PRIORITY, 0, 0, SCHED_FIFO, 0xF)))
	{
		rt_shm_free(nam2num(TORQUE_SHM));
		printf("Cannot init the RTAI task %s\n","TSHM");
		return 0;
	}*/
	hst=rt_thread_create((void*)rt_system_thread, sys, 10000);
	usleep(100000); //Let start up
	if (!sys_thread_active)
	{
		rt_task_delete(task);
		rt_shm_free(nam2num(MEKA_ODOM_SHM));
		printf("Startup of thread failed.\n",0);
		return 0;
	}
	while(!end)
	{
		usleep(250000);

	}
	printf("Removing RT thread...\n",0);
	sys_thread_end=1;
	//rt_thread_join(hst);
	usleep(1250000);
	if (sys_thread_active)printf("Real-time thread did not shutdown correctly\n");
	//rt_task_delete(task);
	rt_shm_free(nam2num(MEKA_ODOM_SHM));
	ros::shutdown();
	return 0;
}


text:
<?php

/*$I = new ApiGuyTester($scenario);

$I->wantTo('bind note 1');

$I->sendGET('/note/bind', [
    'tid' => 1,
    'reqs' => [
        [
            'UserID' => 'jksdadsasd',
            'NoteID' => 1,
            'NoteActionID' => 1,
        ],
    ],
]);

$I->seeResponseContains('qqqqq');
/*$I->amGoingTo('login without data');
$I->sendPOST('/user/login?_format=json', []);
$I->seeResponseCodeIs(400);
$I->seeResponseContains('Login');
$I->seeResponseContains('Password');
$I->seeResponseIsJson();

$I->amGoingTo('login with incorrect data');
$I->sendPOST('/user/login?_format=json', ['Login' => 'mmm', 'Password' => 'mmm']);
$I->seeResponseCodeIs(401);
$I->seeResponseIsJson();

$I->amGoingTo('login with correct data');
$I->sendPOST('/user/login?_format=json', ['Login' => 'ponor.ns', 'Password' => 'mkysyz']);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();*/


text:
/*********************************************************************
Arduino Library for the LinkSprite 2.04" E-Paper Display
Written by Michael Niemi / mvniemi  http://github.com/mvniemi
Implements the Adafruit GFX Class , Adapted from the Sharp Memory display library written by Limor Fried/Ladyada for Adafruit Industries.
*********************************************************************/

//#ifndef LINKSPRITE_EP2P04_H
//#define LINKSPRITE_EP2P04_H
//
//#endif //LINKSPRITE_EP2P04_H

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#include <Adafruit_GFX.h>

#if defined(ESP32)
  #include <pgmspace.h>
  #define _delay_ms(ms) delayMicroseconds((ms) * 1000)
#endif
#if defined(ESP8266)
  #include <pgmspace.h>
  #define _delay_ms(ms) delayMicroseconds((ms) * 1000)
#endif
//#include <util/delay.h>
#ifdef __avr__
  #include <util/delay.h>
#endif

// LCD Dimensions
#define EP2P04_LCDWIDTH       (172)
#define EP2P04_LCDHEIGHT      (72)

class Linksprite_EP2P04 : public Adafruit_GFX {
public:
    //Linsprite_EP2P04(uint8_t DC, uint8_t CS, uint8_t SDA, SCLK, RSR);
    Linksprite_EP2P04(uint8_t DC, uint8_t STAT, uint8_t CS, uint8_t DA, uint8_t RS, uint8_t SCK, uint8_t MODE);
    void
        begin(void),
        drawPixel(int16_t x, int16_t y, uint16_t color),
        clearDisplay(),
        entersleep(void),
        write_buffer_mono(char buffer[]),
        write_buffer_color(char buffer[]),
        image_display(char image[] = NULL),
        fillBlack(),
        setBounds(uint16_t w, uint16_t h),
        RESET(int delay = NULL), INIT();

    bool refresh(int timeout_thresh = NULL);
    //not implemented
    uint8_t getPixel(uint16_t x, uint16_t y);

    int buffsize;
    char* mem_buffer;
private:
    uint8_t _dc, _stat, _cs, _da, _rs, _sck, _mode;
//    volatile uint8_t *dataport, *clkport;
//    uint8_t _EP2P04_vcom, datapinmask, clkpinmask;

//    void sendbyte(uint8_t data);
//    void sendbyteLSB(uint8_t data);
    void
        SPI4W_WRITECOM(unsigned char INIT_COM),
        SPI4W_WRITEDATA(unsigned char INIT_DATA),
        SPI4W_WRITEDATA_MONO(unsigned char INIT_DATA),
        WRITE_LUT(),
        DELAY_mS(int delaytime);
    byte mem_type;
};


text:
package org.innovateuk.ifs.management.publiccontent.viewmodel.section;

import org.innovateuk.ifs.management.publiccontent.viewmodel.AbstractPublicContentGroupViewModel;

/**
 * View model for the scope section.
 */
public class ScopeViewModel extends AbstractPublicContentGroupViewModel {
}


text:
Chrome App to advertise Eddystone packets.
Uses the Eddystone Advertising library available [here](https://github.com/google/eddystone/tree/master/libraries/javascript/eddystone-advertising).

# BLE Advertising Availability
BLE Advertising is only available in Single App Kiosk Mode.

For *development* you should turn on the `enable-ble-advertising-in-apps`
flag in `chrome://flags/#enable-ble-advertising-in-apps`. This will let
the app Advertise without being in Kiosk Mode. This only works in Chrome OS.

For *deployment* you should add the following to manifest.json:
```js
"kiosk_enabled": true,
"kiosk_only": true
```

![URL Advertising](url-advertising.png)
![UID Advertising](uid-advertising.png)


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin
 */

/**
 * Generates and displays the React root element for a metabox section.
 */
class WPSEO_Metabox_Section_React implements WPSEO_Metabox_Section {
	/**
	 * Name of the section, used as an identifier in the HTML.
	 *
	 * @var string
	 */
	public $name;

	/**
	 * Content to use before the React root node.
	 *
	 * @var string
	 */
	public $content;

	/**
	 * Content to use to display the button to open this content block.
	 *
	 * @var string
	 */
	private $link_content;

	/**
	 * Class to add to the link.
	 *
	 * @var string
	 */
	private $link_class;

	/**
	 * Aria label to use for the link.
	 *
	 * @var string
	 */
	private $link_aria_label;

	/**
	 * Constructor.
	 *
	 * @param string $name         The name of the section, used as an identifier in the html. Can only contain URL safe characters.
	 * @param string $link_content The text content of the section link.
	 * @param string $content      Optional. Content to use above the React root element.
	 * @param array  $options      Optional link attributes.
	 */
	public function __construct( $name, $link_content, $content = '', array $options = array() ) {
		$this->name    = $name;
		$this->content = $content;

		$default_options = array(
			'link_class'      => '',
			'link_aria_label' => '',
		);

		$options = wp_parse_args( $options, $default_options );

		$this->link_content    = $link_content;
		$this->link_class      = $options['link_class'];
		$this->link_aria_label = $options['link_aria_label'];
	}

	/**
	 * Outputs the section link.
	 *
	 * @return void
	 */
	public function display_link() {
		printf(
			'
%4$s
',
			esc_attr( $this->name ),
			esc_attr( $this->link_class ),
			( '' !== $this->link_aria_label ) ? ' aria-label="' . esc_attr( $this->link_aria_label ) . '"' : '',
			$this->link_content
		);
	}

	/**
	 * Outputs the section content.
	 *
	 * @return void
	 */
	public function display_content() {
		$html  = sprintf( '
', esc_attr( 'wpseo-meta-section-' . $this->name ) );
		$html .= $this->content;
		$html .= '

';
		$html .= '
';

		echo $html;
	}
}


text:
#ifndef __cuda_stdint_h__
#define __cuda_stdint_h__

// Compiler-specific treatment for C99's stdint.h
//
// By default, this header will use the standard headers (so it
// is your responsibility to make sure they are available), except
// on MSVC before Visual Studio 2010, when they were not provided.
// To support old MSVC, a few of the commonly-used definitions are
// provided here.  If more definitions are needed, add them here,
// or replace these definitions with a complete implementation,
// such as the ones available from Google, Boost, or MSVC10.  You
// can prevent the definition of any of these types (in order to
// use your own) by #defining CU_STDINT_TYPES_ALREADY_DEFINED.

#if !defined(CU_STDINT_TYPES_ALREADY_DEFINED)

// In VS including stdint.h forces the C++ runtime dep - provide an opt-out
// (CU_STDINT_VS_FORCE_NO_STDINT_H) for users that care (notably static
// cudart).
#if defined(_MSC_VER) && ((_MSC_VER < 1600) || defined(CU_STDINT_VS_FORCE_NO_STDINT_H))

// These definitions can be used with MSVC 8 and 9,
// which don't ship with stdint.h:

typedef            char    int8_t;
typedef unsigned   char   uint8_t;

typedef            short  int16_t;
typedef unsigned   short uint16_t;

typedef            long   int32_t;
typedef unsigned   long  uint32_t;

typedef          __int64  int64_t;
typedef unsigned __int64 uint64_t;

#elif defined(__DJGPP__)

// These definitions can be used when compiling
// C code with DJGPP, which only provides stdint.h
// when compiling C++ code with TR1 enabled.

typedef               char    int8_t;
typedef unsigned      char   uint8_t;

typedef               short  int16_t;
typedef unsigned      short uint16_t;

typedef               long   int32_t;
typedef unsigned      long  uint32_t;

typedef          long long   int64_t;
typedef unsigned long long  uint64_t;

#else

// Use standard headers, as specified by C99 and C++ TR1.
// Known to be provided by:
// - gcc/glibc, supported by all versions of glibc
// - djgpp, supported since 2001
// - MSVC, supported by Visual Studio 2010 and later

#include <stdint.h>

#endif

#endif // !defined(CU_STDINT_TYPES_ALREADY_DEFINED)

#endif // file guard


text:
package com.laticobsa.modelo;
// Generated 31-jul-2017 17:40:44 by Hibernate Tools 4.3.1

import java.util.Date;

/**
 * LcRecordatorios generated by hbm2java
 */
public class LcRecordatorios  implements java.io.Serializable {

     private int idRecordatorio;
     private LcAgencia lcAgencia;
     private LcClientes lcClientes;
     private LcDatosDeudores lcDatosDeudores;
     private LcEmpleados lcEmpleados;
     private LcEmpresa lcEmpresa;
     private Date fechaCompromiso;
     private String revisado;
     private Date fechaRegistro;
     private Date fechaActualizado;
     private String estado;

    public LcRecordatorios() {
    }

    public LcRecordatorios(int idRecordatorio) {
        this.idRecordatorio = idRecordatorio;
    }
    public LcRecordatorios(int idRecordatorio, LcAgencia lcAgencia, LcClientes lcClientes, LcDatosDeudores lcDatosDeudores, LcEmpleados lcEmpleados, LcEmpresa lcEmpresa, Date fechaCompromiso, String revisado, Date fechaRegistro, Date fechaActualizado, String estado) {
       this.idRecordatorio = idRecordatorio;
       this.lcAgencia = lcAgencia;
       this.lcClientes = lcClientes;
       this.lcDatosDeudores = lcDatosDeudores;
       this.lcEmpleados = lcEmpleados;
       this.lcEmpresa = lcEmpresa;
       this.fechaCompromiso = fechaCompromiso;
       this.revisado = revisado;
       this.fechaRegistro = fechaRegistro;
       this.fechaActualizado = fechaActualizado;
       this.estado = estado;
    }

    public int getIdRecordatorio() {
        return this.idRecordatorio;
    }

    public void setIdRecordatorio(int idRecordatorio) {
        this.idRecordatorio = idRecordatorio;
    }
    public LcAgencia getLcAgencia() {
        return this.lcAgencia;
    }

    public void setLcAgencia(LcAgencia lcAgencia) {
        this.lcAgencia = lcAgencia;
    }
    public LcClientes getLcClientes() {
        return this.lcClientes;
    }

    public void setLcClientes(LcClientes lcClientes) {
        this.lcClientes = lcClientes;
    }
    public LcDatosDeudores getLcDatosDeudores() {
        return this.lcDatosDeudores;
    }

    public void setLcDatosDeudores(LcDatosDeudores lcDatosDeudores) {
        this.lcDatosDeudores = lcDatosDeudores;
    }
    public LcEmpleados getLcEmpleados() {
        return this.lcEmpleados;
    }

    public void setLcEmpleados(LcEmpleados lcEmpleados) {
        this.lcEmpleados = lcEmpleados;
    }
    public LcEmpresa getLcEmpresa() {
        return this.lcEmpresa;
    }

    public void setLcEmpresa(LcEmpresa lcEmpresa) {
        this.lcEmpresa = lcEmpresa;
    }
    public Date getFechaCompromiso() {
        return this.fechaCompromiso;
    }

    public void setFechaCompromiso(Date fechaCompromiso) {
        this.fechaCompromiso = fechaCompromiso;
    }
    public String getRevisado() {
        return this.revisado;
    }

    public void setRevisado(String revisado) {
        this.revisado = revisado;
    }
    public Date getFechaRegistro() {
        return this.fechaRegistro;
    }

    public void setFechaRegistro(Date fechaRegistro) {
        this.fechaRegistro = fechaRegistro;
    }
    public Date getFechaActualizado() {
        return this.fechaActualizado;
    }

    public void setFechaActualizado(Date fechaActualizado) {
        this.fechaActualizado = fechaActualizado;
    }
    public String getEstado() {
        return this.estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

}


text:
import knex from "knex";

import config from "../config";

const client = knex({
  client: "pg",
  connection: config.db.client,
  pool: config.db.pooling,
  debug: false // Toggle this variable to log SQL queries
});

export const findOne = (table, fields, primaryKey = "id") => async identifier =>
  client
    .select(fields)
    .from(table)
    .where({ [primaryKey]: identifier })
    .first();

export const insertOne = (table, fields) => async row => {
  const results = await client(table)
    .insert(row)
    .returning(fields);

  return results[0]; // Cannot chain .first() on "insert" query
};

export const updateOne = (table, fields, primaryKey = "id") => async (
  identifier,
  row
) => {
  const results = await client(table)
    .where({ [primaryKey]: identifier })
    .update(row)
    .returning(fields);

  return results[0]; // Cannot chain .first() on "update" query
};

export default client;


text:
package main

import (
	"os"
	"path/filepath"
	"syscall"
	"time"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/spf13/cobra"
	"github.com/coreos/rkt/common"
	"github.com/coreos/rkt/stage0"
	"github.com/coreos/rkt/store"
)

const (
	defaultGracePeriod        = 30 * time.Minute
	defaultPreparedExpiration = 24 * time.Hour
)

var (
	cmdGC = &cobra.Command{
		Use:   "gc [--grace-period=duration] [--expire-prepared=duration]",
		Short: "Garbage-collect rkt pods no longer in use",
		Run:   runWrapper(runGC),
	}
	flagGracePeriod        time.Duration
	flagPreparedExpiration time.Duration
)

func init() {
	cmdRkt.AddCommand(cmdGC)
	cmdGC.Flags().DurationVar(&flagGracePeriod, "grace-period", defaultGracePeriod, "duration to wait before discarding inactive pods from garbage")
	cmdGC.Flags().DurationVar(&flagPreparedExpiration, "expire-prepared", defaultPreparedExpiration, "duration to wait before expiring prepared pods")
}

func runGC(cmd *cobra.Command, args []string) (exit int) {
	if err := renameExited(); err != nil {
		stderr("Failed to rename exited pods: %v", err)
		return 1
	}

	if err := renameAborted(); err != nil {
		stderr("Failed to rename aborted pods: %v", err)
		return 1
	}

	if err := renameExpired(flagPreparedExpiration); err != nil {
		stderr("Failed to rename expired prepared pods: %v", err)
		return 1
	}

	if err := emptyExitedGarbage(flagGracePeriod); err != nil {
		stderr("Failed to empty exitedGarbage: %v", err)
		return 1
	}

	if err := emptyGarbage(); err != nil {
		stderr("Failed to empty garbage: %v", err)
		return 1
	}

	return
}

// renameExited renames exited pods to the exitedGarbage directory
func renameExited() error {
	if err := walkPods(includeRunDir, func(p *pod) {
		if p.isExited {
			stderr("Moving pod %q to garbage", p.uuid)
			if err := p.xToExitedGarbage(); err != nil && err != os.ErrNotExist {
				stderr("Rename error: %v", err)
			}
		}
	}); err != nil {
		return err
	}

	return nil
}

// emptyExitedGarbage discards sufficiently aged pods from exitedGarbageDir()
func emptyExitedGarbage(gracePeriod time.Duration) error {
	if err := walkPods(includeExitedGarbageDir, func(p *pod) {
		gp := p.path()
		st := &syscall.Stat_t{}
		if err := syscall.Lstat(gp, st); err != nil {
			if err != syscall.ENOENT {
				stderr("Unable to stat %q, ignoring: %v", gp, err)
			}
			return
		}

		if expiration := time.Unix(st.Ctim.Unix()).Add(gracePeriod); time.Now().After(expiration) {
			if err := p.ExclusiveLock(); err != nil {
				return
			}
			stdout("Garbage collecting pod %q", p.uuid)

			deletePod(p)
		} else {
			stderr("Pod %q not removed: still within grace period (%s)", p.uuid, gracePeriod)
		}
	}); err != nil {
		return err
	}

	return nil
}

// renameAborted renames failed prepares to the garbage directory
func renameAborted() error {
	if err := walkPods(includePrepareDir, func(p *pod) {
		if p.isAbortedPrepare {
			stderr("Moving failed prepare %q to garbage", p.uuid)
			if err := p.xToGarbage(); err != nil && err != os.ErrNotExist {
				stderr("Rename error: %v", err)
			}
		}
	}); err != nil {
		return err
	}
	return nil
}

// renameExpired renames expired prepared pods to the garbage directory
func renameExpired(preparedExpiration time.Duration) error {
	if err := walkPods(includePreparedDir, func(p *pod) {
		st := &syscall.Stat_t{}
		pp := p.path()
		if err := syscall.Lstat(pp, st); err != nil {
			if err != syscall.ENOENT {
				stderr("Unable to stat %q, ignoring: %v", pp, err)
			}
			return
		}

		if expiration := time.Unix(st.Ctim.Unix()).Add(preparedExpiration); time.Now().After(expiration) {
			stderr("Moving expired prepared pod %q to garbage", p.uuid)
			if err := p.xToGarbage(); err != nil && err != os.ErrNotExist {
				stderr("Rename error: %v", err)
			}
		}
	}); err != nil {
		return err
	}
	return nil
}

// emptyGarbage discards everything from garbageDir()
func emptyGarbage() error {
	if err := walkPods(includeGarbageDir, func(p *pod) {
		if err := p.ExclusiveLock(); err != nil {
			return
		}
		stdout("Garbage collecting pod %q", p.uuid)

		deletePod(p)
	}); err != nil {
		return err
	}

	return nil
}

// deletePod cleans up files and resource associated with the pod
// pod must be under exclusive lock and be in either ExitedGarbage
// or Garbage state
func deletePod(p *pod) {
	if !p.isExitedGarbage && !p.isGarbage {
		panic("logic error: deletePod called with non-garbage pod")
	}

	if p.isExitedGarbage {
		s, err := store.NewStore(globalFlags.Dir)
		if err != nil {
			stderr("Cannot open store: %v", err)
			return
		}
		defer s.Close()
		stage1TreeStoreID, err := p.getStage1TreeStoreID()
		if err != nil {
			stderr("Error getting stage1 treeStoreID: %v", err)
			return
		}
		stage1RootFS := s.GetTreeStoreRootFS(stage1TreeStoreID)

		// execute stage1's GC
		if err := stage0.GC(p.path(), p.uuid, stage1RootFS, globalFlags.Debug); err != nil {
			stderr("Stage1 GC of pod %q failed: %v", p.uuid, err)
			return
		}

		if p.usesOverlay() {
			apps, err := p.getApps()
			if err != nil {
				stderr("Error retrieving app hashes from pod manifest: %v", err)
				return
			}
			for _, a := range apps {
				dest := filepath.Join(common.AppPath(p.path(), a.Name), "rootfs")
				if err := syscall.Unmount(dest, 0); err != nil {
					// machine could have been rebooted and mounts lost.
					// ignore "does not exist" and "not a mount point" errors
					if err != syscall.ENOENT && err != syscall.EINVAL {
						stderr("Error unmounting app at %v: %v", dest, err)
					}
				}
			}

			s1 := filepath.Join(common.Stage1ImagePath(p.path()), "rootfs")
			if err := syscall.Unmount(s1, 0); err != nil {
				// machine could have been rebooted and mounts lost.
				// ignore "does not exist" and "not a mount point" errors
				if err != syscall.ENOENT && err != syscall.EINVAL {
					stderr("Error unmounting stage1 at %v: %v", s1, err)
					return
				}
			}
		}
	}

	if err := os.RemoveAll(p.path()); err != nil {
		stderr("Unable to remove pod %q: %v", p.uuid, err)
	}
}


text:
npm start &
sleep 20s
./node_modules/.bin/jasmine test/functional/epic.js
EXIT_CODE=$?

FOREMAN_PID=$(pgrep foreman)
kill -s SIGINT $FOREMAN_PID

exit $EXIT_CODE


text:
package org.apache.hawq.pxf.service;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import org.apache.hawq.pxf.api.Fragment;

/**
 * Class for serializing fragments metadata in JSON format. The class implements
 * {@link StreamingOutput} so the serialization will be done in a stream and not
 * in one bulk, this in order to avoid running out of memory when processing a
 * lot of fragments.
 */
public class FragmentsResponse implements StreamingOutput {

    private static final Log Log = LogFactory.getLog(FragmentsResponse.class);

    private List<Fragment> fragments;

    /**
     * Constructs fragments response out of a list of fragments
     *
     * @param fragments fragment list
     */
    public FragmentsResponse(List<Fragment> fragments) {
        this.fragments = fragments;
    }

    /**
     * Serializes a fragments list in JSON, To be used as the result string for
     * HAWQ. An example result is as follows:
     * <code>{"PXFFragments":[{"replicas":
     * ["sdw1.corp.emc.com","sdw3.corp.emc.com","sdw8.corp.emc.com"],
     * "sourceName":"text2.csv", "index":"0","metadata":"<base64 metadata for fragment>",
     * "userData":"<data_specific_to_third_party_fragmenter>"
     * },{"replicas":["sdw2.corp.emc.com","sdw4.corp.emc.com","sdw5.corp.emc.com"
     * ],"sourceName":"text_data.csv","index":"0","metadata":
     * "<base64 metadata for fragment>"
     * ,"userData":"<data_specific_to_third_party_fragmenter>"
     * }]}</code>
     */
    @Override
    public void write(OutputStream output) throws IOException,
            WebApplicationException {
        DataOutputStream dos = new DataOutputStream(output);
        ObjectMapper mapper = new ObjectMapper();

        dos.write("{\"PXFFragments\":[".getBytes());

        String prefix = "";
        for (Fragment fragment : fragments) {
            StringBuilder result = new StringBuilder();
            /* metaData and userData are automatically converted to Base64 */
            result.append(prefix).append(mapper.writeValueAsString(fragment));
            prefix = ",";
            dos.write(result.toString().getBytes());
        }

        dos.write("]}".getBytes());
    }
}


text:
package im.connector.api.data;
import io.unequal.reuse.data.Constant;

public class FieldType extends Constant {

	// TYPE:
	public static FieldType EMAIL = new FieldType(100, "Email address");
	public static FieldType PHONE = new FieldType(200, "Phone number");
	public static FieldType ADDRESS = new FieldType(300, "Address");
	public static FieldType BIRTHDAY = new FieldType(400, "Birthday");
	public static FieldType DATE = new FieldType(500, "Date");

	// INSTANCE:
	private FieldType(int code, String description) {
		super(code, description);
	}
}


text:
using namespace SourceKit;
using namespace sourcekitd;

namespace {
class SKDObject;
typedef RefPtr<SKDObject> SKDObjectRef;

class SKDObject : public ThreadSafeRefCountedBaseVPTR {
public:
  enum class ObjectKind {
    Dictionary,
    Array,
    String,
    Int64,
    UID,
    Bool,
    CustomData,
    Error,
  };
private:
  ObjectKind Kind;
protected:
  SKDObject(ObjectKind K) : Kind(K) {}
public:
  SKDObject(SKDObject const&) = delete;
  SKDObject &operator=(SKDObject const&) = delete;

  ObjectKind getKind() const { return Kind; }

  virtual sourcekitd_variant_type_t getVariantType() const = 0;

  virtual void set(sourcekitd_uid_t Key, SKDObjectRef Value) {}
  virtual void set(size_t Index, SKDObjectRef Value) {}

  virtual SKDObjectRef get(sourcekitd_uid_t Key) const { return nullptr; }

  virtual SKDObjectRef get(size_t Index) const { return nullptr; }
  virtual size_t getCount() const { return 0; }

  virtual sourcekitd_uid_t getUID() const { return nullptr; }
  virtual Optional<int64_t> getInt64() const { return None; }
  virtual Optional<StringRef> getString() const { return None; }
  virtual const char *getCString() const { return nullptr; }
  virtual bool getBool() const { return false; }
  virtual const void *getDataPtr() const { return nullptr; }
  virtual size_t getDataSize() const { return 0; }
};

class SKDDictionary: public SKDObject {
public:
  SKDDictionary() : SKDObject(ObjectKind::Dictionary) {}
  SKDDictionary(SKDDictionary const&) = delete;
  SKDDictionary &operator=(SKDDictionary const&) = delete;

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_DICTIONARY;
  }

  void set(sourcekitd_uid_t Key, SKDObjectRef Value) override {
    Storage[Key] = Value;
  }

  SKDObjectRef get(sourcekitd_uid_t Key) const override {
    auto it = Storage.find(Key);
    return it != Storage.end() ? it->second : nullptr;
  }

  bool
  apply(llvm::function_ref<bool(sourcekitd_uid_t, SKDObjectRef)> Applier) const {
    for (const auto& kv : Storage) {
      if (!Applier(kv.first, kv.second))
        return false;
    }
    return true;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::Dictionary;
  }
private:
  std::map<sourcekitd_uid_t, SKDObjectRef> Storage;
};

class SKDArray: public SKDObject {
public:
  SKDArray() : SKDObject(ObjectKind::Array) {}
  SKDArray(SKDArray const&) = delete;
  SKDArray &operator=(SKDArray const&) = delete;

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_ARRAY;
  }

  void set(size_t Index, SKDObjectRef Value) override {
    if (Index == SOURCEKITD_ARRAY_APPEND) {
      Storage.push_back(Value);
    } else {
      Storage[Index] = Value;
    }
  }

  SKDObjectRef get(size_t Index) const override {
    return Storage[Index];
  }

  size_t getCount() const override {
    return Storage.size();
  }

  bool apply(llvm::function_ref<bool(size_t, SKDObjectRef)> Applier) const {
    for (size_t i = 0; i < Storage.size(); ++i) {
      if (!Applier(i, Storage[i]))
        return false;
    }
    return true;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::Array;
  }
private:
  std::vector<SKDObjectRef> Storage;
};

class SKDString: public SKDObject {
public:
  SKDString(std::string &&Value) : SKDObject(ObjectKind::String), Storage(Value) {}

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_STRING;
  }

  Optional<StringRef> getString() const override {
    return Optional<StringRef>(Storage);
  }

  const char *getCString() const override {
    return Storage.c_str();
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::String;
  }
private:
  std::string Storage;
};

class SKDInt64: public SKDObject {
public:
  SKDInt64(int64_t Value) : SKDObject(ObjectKind::Int64), Storage(Value) {}

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_INT64;
  }

  Optional<int64_t> getInt64() const override {
    return Storage;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::Int64;
  }
private:
  int64_t Storage;
};

class SKDUID: public SKDObject {
public:
  SKDUID(sourcekitd_uid_t Value) : SKDObject(ObjectKind::UID), Storage(Value) {}

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_UID;
  }

  sourcekitd_uid_t getUID() const override {
    return Storage;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::UID;
  }
private:
  sourcekitd_uid_t Storage;
};

class SKDBool: public SKDObject {
public:
  SKDBool(bool Value) : SKDObject(ObjectKind::Bool), Storage(Value) {}

  sourcekitd_variant_type_t getVariantType() const override {
    return SOURCEKITD_VARIANT_TYPE_BOOL;
  }

  bool getBool() const override {
    return Storage;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::Bool;
  }
private:
  bool Storage;
};

class SKDCustomData: public SKDObject {
public:
  SKDCustomData(CustomBufferKind BufferKind,
                std::unique_ptr<llvm::MemoryBuffer>& MemBuf)
  : SKDObject(ObjectKind::CustomData), BufferKind(BufferKind),
    BufferPtr(llvm::MemoryBuffer::getMemBufferCopy(
                                                MemBuf->getBuffer(),
                                                MemBuf->getBufferIdentifier()))
    {}

  SKDCustomData(SKDCustomData const&) = delete;
  SKDCustomData &operator=(SKDCustomData const&) = delete;

  sourcekitd_variant_type_t getVariantType() const override {
    switch (BufferKind) {
      case CustomBufferKind::TokenAnnotationsArray:
      case CustomBufferKind::DocSupportAnnotationArray:
      case CustomBufferKind::CodeCompletionResultsArray:
      case CustomBufferKind::DocStructureArray:
      case CustomBufferKind::InheritedTypesArray:
      case CustomBufferKind::DocStructureElementArray:
      case CustomBufferKind::AttributesArray:
        return SOURCEKITD_VARIANT_TYPE_ARRAY;
      case CustomBufferKind::RawData:
        return SOURCEKITD_VARIANT_TYPE_DATA;
    }
    llvm::report_fatal_error("sourcekitd object did not resolve to a known type");
  }

  CustomBufferKind getBufferKind() const {
    return BufferKind;
  }

  const void *getDataPtr() const override {
    return BufferPtr->getBuffer().data();
  }

  size_t getDataSize() const override {
    return BufferPtr->getBuffer().size();
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::CustomData;
  }
private:
  CustomBufferKind BufferKind;
  std::unique_ptr<llvm::MemoryBuffer> BufferPtr;
};

class SKDError: public SKDObject {
public:
  SKDError(sourcekitd_error_t ErrorKind, StringRef Description)
  : SKDObject(ObjectKind::Error), ErrorKind(ErrorKind), Description(Description) {}

  SKDError(SKDError const&) = delete;
  SKDError &operator=(SKDError const&) = delete;

  sourcekitd_variant_type_t getVariantType() const override {
    llvm::report_fatal_error("sourcekitd error object is not a variant type");
  }

  sourcekitd_error_t getErrorKind() const {
    return ErrorKind;
  }

  const std::string &getDescription() const {
    return Description;
  }

  static bool classof(const SKDObject *O) {
    return O->getKind() == ObjectKind::Error;
  }
private:
  sourcekitd_error_t ErrorKind;
  std::string Description;
};

template <typename ImplClass, typename RetTy = void>
class SKDObjectVisitor {
public:
  typedef std::vector<std::pair<UIdent, sourcekitd_object_t>> DictMap;

  static bool compKeys(const std::pair<UIdent, sourcekitd_object_t> &LHS,
                       const std::pair<UIdent, sourcekitd_object_t> &RHS) {
    return sourcekitd::compareDictKeys(LHS.first, RHS.first);
  }

  RetTy visit(sourcekitd_object_t Obj) {
    auto Object = static_cast<SKDObject *>(Obj);

    if (auto DictionaryObject = dyn_cast<SKDDictionary>(Object)) {
      DictMap Dict;
      DictionaryObject->apply([&](sourcekitd_uid_t Key, SKDObjectRef Element){
        UIdent UID = UIdentFromSKDUID(Key);
        Dict.push_back({ UID, Element.get() });
        return true;
      });
      std::sort(Dict.begin(), Dict.end(), compKeys);
      return static_cast<ImplClass*>(this)->visitDictionary(Dict);
    }
    if (auto ArrayObject = dyn_cast<SKDArray>(Object)) {
      std::vector<sourcekitd_object_t> Vec;
      ArrayObject->apply([&](size_t Index, SKDObjectRef Element){
        Vec.push_back(Element.get());
        return true;
      });
      return static_cast<ImplClass*>(this)->visitArray(Vec);
    }
    if (auto SKDUID = Object->getUID()) {
      UIdent UID = UIdentFromSKDUID(SKDUID);
      return static_cast<ImplClass*>(this)->visitUID(UID.getName());
    }
    if (auto CString = Object->getCString()) {
      return static_cast<ImplClass*>(this)->visitString(CString);
    }
    auto OptInt = Object->getInt64();
    if (OptInt.hasValue()) {
      return static_cast<ImplClass*>(this)->visitInt64(OptInt.getValue());
    }
    llvm_unreachable("unknown sourcekitd_object_t");
  }
};

class SKDObjectPrinter : public SKDObjectVisitor<SKDObjectPrinter> {
  raw_ostream &OS;
  unsigned Indent;
public:
  SKDObjectPrinter(raw_ostream &OS, unsigned Indent = 0)
  : OS(OS), Indent(Indent) { }

  void visitDictionary(const DictMap &Map) {
    OS << "{\n";
    Indent += 2;
    for (unsigned i = 0, e = Map.size(); i != e; ++i) {
      auto &Pair = Map[i];
      OS.indent(Indent);
      OSColor(OS, DictKeyColor) << Pair.first.getName();
      OS << ": ";
      SKDObjectPrinter(OS, Indent).visit(Pair.second);
      if (i < e-1)
        OS << ',';
      OS << '\n';
    }
    Indent -= 2;
    OS.indent(Indent) << '}';
  }

  void visitArray(ArrayRef<sourcekitd_object_t> Arr) {
    OS << "[\n";
    Indent += 2;
    for (unsigned i = 0, e = Arr.size(); i != e; ++i) {
      auto Obj = Arr[i];
      OS.indent(Indent);
      SKDObjectPrinter(OS, Indent).visit(Obj);
      if (i < e-1)
        OS << ',';
      OS << '\n';
    }
    Indent -= 2;
    OS.indent(Indent) << ']';
  }

  void visitInt64(int64_t Val) {
    OS << Val;
  }

  void visitString(StringRef Str) {
    OS << '\"';
    // Avoid raw_ostream's write_escaped, we don't want to escape unicode
    // characters because it will be invalid JSON.
    writeEscaped(Str, OS);
    OS << '\"';
  }

  void visitUID(StringRef UID) {
    OSColor(OS, UIDColor) << UID;
  }
};

static SKDObject *retained(SKDObject *object) {
  object->Retain();
  return object;
}

} // anonymous namespace

//===----------------------------------------------------------------------===//
// Public Request API
//===----------------------------------------------------------------------===//

sourcekitd_object_t
sourcekitd_request_retain(sourcekitd_object_t object) {
  return retained(static_cast<SKDObject *>(object));
}

void sourcekitd_request_release(sourcekitd_object_t object) {
  static_cast<SKDObject *>(object)->Release();
}

sourcekitd_object_t
sourcekitd_request_dictionary_create(const sourcekitd_uid_t *keys,
                                     const sourcekitd_object_t *values,
                                     size_t count) {
  SKDDictionary *Dict = new SKDDictionary();
  for (size_t i = 0; i < count; ++i) {
    Dict->set(keys[i], static_cast<SKDObject *>(values[i]));
  }
  return retained(Dict);
}

void
sourcekitd_request_dictionary_set_value(sourcekitd_object_t dict,
                                        sourcekitd_uid_t key,
                                        sourcekitd_object_t value) {
  static_cast<SKDObject *>(dict)->set(key, static_cast<SKDObject *>(value));
}

void sourcekitd_request_dictionary_set_string(sourcekitd_object_t dict,
                                              sourcekitd_uid_t key,
                                              const char *string) {
  static_cast<SKDObject *>(dict)->set(key, new SKDString(std::string(string)));
}

void
sourcekitd_request_dictionary_set_stringbuf(sourcekitd_object_t dict,
                                            sourcekitd_uid_t key,
                                            const char *buf, size_t length) {
  static_cast<SKDObject *>(dict)->set(key,
                                      new SKDString(std::string(buf, length)));
}

void sourcekitd_request_dictionary_set_int64(sourcekitd_object_t dict,
                                             sourcekitd_uid_t key,
                                             int64_t val) {
  static_cast<SKDObject *>(dict)->set(key, new SKDInt64(val));
}

void
sourcekitd_request_dictionary_set_uid(sourcekitd_object_t dict,
                                      sourcekitd_uid_t key,
                                      sourcekitd_uid_t uid) {
  static_cast<SKDObject *>(dict)->set(key, new SKDUID(uid));
}

sourcekitd_object_t
sourcekitd_request_array_create(const sourcekitd_object_t *objects,
                                size_t count) {
  SKDArray *Array = new SKDArray();
  for (size_t i = 0; i < count; ++i) {
    Array->set(SOURCEKITD_ARRAY_APPEND, static_cast<SKDObject *>(objects[i]));
  }
  return retained(Array);
}

void
sourcekitd_request_array_set_value(sourcekitd_object_t array, size_t index,
                                   sourcekitd_object_t value) {
  static_cast<SKDObject *>(array)->set(index, static_cast<SKDObject *>(value));
}

void
sourcekitd_request_array_set_string(sourcekitd_object_t array, size_t index,
                                    const char *string) {
  static_cast<SKDObject *>(array)->set(index,
                                       new SKDString(std::string(string)));
}

void
sourcekitd_request_array_set_stringbuf(sourcekitd_object_t array, size_t index,
                                       const char *buf, size_t length) {
  static_cast<SKDObject *>(array)->set(index,
                                       new SKDString(std::string(buf, length)));
}

void
sourcekitd_request_array_set_int64(sourcekitd_object_t array, size_t index,
                                   int64_t val) {
  static_cast<SKDObject *>(array)->set(index, new SKDInt64(val));
}

void
sourcekitd_request_array_set_uid(sourcekitd_object_t array, size_t index,
                                 sourcekitd_uid_t uid) {
  static_cast<SKDObject *>(array)->set(index, new SKDUID(uid));
}

sourcekitd_object_t
sourcekitd_request_int64_create(int64_t val) {
  return retained(new SKDInt64(val));
}

sourcekitd_object_t
sourcekitd_request_string_create(const char *string) {
  return retained(new SKDString(std::string(string)));
}

sourcekitd_object_t
sourcekitd_request_uid_create(sourcekitd_uid_t uid) {
  return retained(new SKDUID(uid));
}

//===----------------------------------------------------------------------===//
// Public Response API
//===----------------------------------------------------------------------===//

void
sourcekitd_response_dispose(sourcekitd_response_t obj) {
  static_cast<SKDObject *>(obj)->Release();
}

bool
sourcekitd_response_is_error(sourcekitd_response_t obj) {
  return isa<SKDError>(static_cast<SKDObject *>(obj));
}

sourcekitd_error_t
sourcekitd_response_error_get_kind(sourcekitd_response_t obj) {
  if (auto *Error = dyn_cast<SKDError>(static_cast<SKDObject *>(obj)))
    return Error->getErrorKind();
  llvm::report_fatal_error("invalid sourcekitd error object");
}

const char *
sourcekitd_response_error_get_description(sourcekitd_response_t obj) {
  if (auto *Error = dyn_cast<SKDError>(static_cast<SKDObject *>(obj)))
    return Error->getDescription().c_str();
  llvm::report_fatal_error("invalid sourcekitd error object");
}

static sourcekitd_variant_t variantFromSKDObject(SKDObjectRef Object);

sourcekitd_variant_t
sourcekitd_response_get_value(sourcekitd_response_t resp) {
  if (sourcekitd_response_is_error(resp))
    return makeNullVariant();
  return variantFromSKDObject(static_cast<SKDObject *>(resp));
}

//===----------------------------------------------------------------------===//
// Internal Request API
//===----------------------------------------------------------------------===//

void sourcekitd::printRequestObject(sourcekitd_object_t Obj, raw_ostream &OS) {
  if (!Obj) {
    OS << "<<NULL>>";
    return;
  }

  SKDObjectPrinter(OS).visit(Obj);
}

//===----------------------------------------------------------------------===//
// Internal ResponseBuilder Implementation
//===----------------------------------------------------------------------===//

ResponseBuilder::ResponseBuilder() {
  Impl = retained(new SKDDictionary());
}

ResponseBuilder::~ResponseBuilder() {
  static_cast<SKDObject *>(Impl)->Release();
}

ResponseBuilder::ResponseBuilder(const ResponseBuilder &Other) {
  Impl = retained(static_cast<SKDObject *>(Other.Impl));
}

ResponseBuilder &ResponseBuilder::operator =(const ResponseBuilder &Other) {
  auto Tmp = retained(static_cast<SKDObject *>(Other.Impl));
  static_cast<SKDObject *>(Impl)->Release();
  Impl = Tmp;
  return *this;
}

ResponseBuilder::Dictionary ResponseBuilder::getDictionary() {
  return Dictionary(Impl);
}

sourcekitd_response_t ResponseBuilder::createResponse() {
  return retained(static_cast<SKDObject *>(Impl));
}

void ResponseBuilder::Dictionary::set(UIdent Key, SourceKit::UIdent UID) {
  set(Key, SKDUIDFromUIdent(UID));
}

void ResponseBuilder::Dictionary::set(UIdent Key, sourcekitd_uid_t UID) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), new SKDUID(UID));
}

void ResponseBuilder::Dictionary::set(UIdent Key, const char *Str) {
  set(Key, StringRef(Str));
}

void ResponseBuilder::Dictionary::set(UIdent Key, StringRef Str) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key),
                                      new SKDString(Str));
}

void ResponseBuilder::Dictionary::set(UIdent Key, const std::string &Str) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key),
                                      new SKDString(std::string(Str)));
}

void ResponseBuilder::Dictionary::set(UIdent Key, int64_t Val) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), new SKDInt64(Val));
}

void ResponseBuilder::Dictionary::set(SourceKit::UIdent Key,
                                      ArrayRef<StringRef> Strs) {
  auto ArrayObject = new SKDArray();
  for (auto Str : Strs) {
    ArrayObject->set(SOURCEKITD_ARRAY_APPEND, new SKDString(Str));
  }
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), ArrayObject);
}

void ResponseBuilder::Dictionary::set(SourceKit::UIdent Key,
                                      ArrayRef<std::string> Strs) {
  auto ArrayObject = new SKDArray();
  for (auto Str : Strs) {
    ArrayObject->set(SOURCEKITD_ARRAY_APPEND, new SKDString(std::string(Str)));
  }
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), ArrayObject);
}

void ResponseBuilder::Dictionary::setBool(UIdent Key, bool Val) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), new SKDBool(Val));
}

ResponseBuilder::Dictionary
ResponseBuilder::Dictionary::setDictionary(UIdent Key) {
  auto DictionaryObject = new SKDDictionary();
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), DictionaryObject);
  return Dictionary(DictionaryObject);
}

void ResponseBuilder::Dictionary::setCustomBuffer(
      SourceKit::UIdent Key,
      CustomBufferKind Kind, std::unique_ptr<llvm::MemoryBuffer> MemBuf) {
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key),
                                      new SKDCustomData(Kind, MemBuf));
}

ResponseBuilder::Array
ResponseBuilder::Dictionary::setArray(UIdent Key) {
  auto ArrayObject = new SKDArray();
  static_cast<SKDObject *>(Impl)->set(SKDUIDFromUIdent(Key), ArrayObject);
  return Array(ArrayObject);
}

ResponseBuilder::Dictionary ResponseBuilder::Array::appendDictionary() {
  auto DictionaryObject = new SKDDictionary();
  static_cast<SKDObject *>(Impl)->set(SOURCEKITD_ARRAY_APPEND, DictionaryObject);
  return Dictionary(DictionaryObject);
}

//===----------------------------------------------------------------------===//
// Internal RequestDict Implementation
//===----------------------------------------------------------------------===//

sourcekitd_uid_t RequestDict::getUID(UIdent Key) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  return Object ? Object->getUID() : nullptr;
}

Optional<StringRef> RequestDict::getString(UIdent Key) {
  if (auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key))) {
    return Object->getString();
  }
  return None;
}

Optional<RequestDict> RequestDict::getDictionary(SourceKit::UIdent Key) {
  SKDDictionary *DictObject = nullptr;
  if (auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key))) {
    DictObject = dyn_cast<SKDDictionary>(Object);
  }
  return DictObject ? Optional<RequestDict>(RequestDict(DictObject)) : None;
}

bool RequestDict::getStringArray(SourceKit::UIdent Key,
                                 llvm::SmallVectorImpl<const char *> &Arr,
                                 bool isOptional) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  if (!Object)
    return !isOptional;
  auto Array = dyn_cast<SKDArray>(Object);
  if (!Array)
    return true;
  size_t count = Array->getCount();
  Arr.reserve(count);
  for (size_t i = 0; i != count; ++i) {
    auto Str = Array->get(i)->getCString();
    if (!Str)
      return true;
    Arr.push_back(Str);
  }
  return false;
}

bool RequestDict::getUIDArray(SourceKit::UIdent Key,
                              llvm::SmallVectorImpl<sourcekitd_uid_t> &Arr,
                              bool isOptional) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  if (!Object)
    return !isOptional;
  auto Array = dyn_cast<SKDArray>(Object);
  if (!Array)
    return true;
  size_t count = Array->getCount();
  Arr.reserve(count);
  for (size_t i = 0; i != count; ++i) {
    auto UID = Array->get(i)->getUID();
    if (!UID)
      return true;
    Arr.push_back(UID);
  }
  return false;
}

bool RequestDict::dictionaryArrayApply(
    SourceKit::UIdent Key, llvm::function_ref<bool(RequestDict)> Applier) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  if (!Object)
    return true;
  auto Array = dyn_cast<SKDArray>(Object);
  if (!Array)
    return true;

  return !Array->apply([&](size_t index, SKDObjectRef object){
    auto Dict = dyn_cast<SKDDictionary>(object);
    if (!Dict)
      return false;
    return !Applier(RequestDict(Dict));
  });
}

bool RequestDict::getInt64(SourceKit::UIdent Key, int64_t &Val,
                           bool isOptional) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  if (!Object)
    return !isOptional;
  Val = Object->getInt64().getValueOr(0);
  return false;
}

Optional<int64_t> RequestDict::getOptionalInt64(SourceKit::UIdent Key) {
  auto Object = static_cast<SKDObject *>(Dict)->get(SKDUIDFromUIdent(Key));
  if (!Object)
    return None;
  return Object->getInt64().getValueOr(0);
}

sourcekitd_response_t
sourcekitd::createErrorRequestInvalid(const char *Description) {
  return retained(new SKDError(SOURCEKITD_ERROR_REQUEST_INVALID,
                               StringRef(Description)));
}

sourcekitd_response_t
sourcekitd::createErrorRequestFailed(const char *Description) {
  return retained(new SKDError(SOURCEKITD_ERROR_REQUEST_FAILED,
                      StringRef(Description)));
}

sourcekitd_response_t
sourcekitd::createErrorRequestCancelled() {
  return retained(new SKDError(SOURCEKITD_ERROR_REQUEST_CANCELLED,
                               StringRef("")));
}

//===----------------------------------------------------------------------===//
// Variant functions
//===----------------------------------------------------------------------===//

#define SKD_OBJ(var) ((SKDObject *)(var).data[1])

static sourcekitd_variant_type_t SKDVar_get_type(sourcekitd_variant_t var) {
  if (auto Object = SKD_OBJ(var)) {
    return Object->getVariantType();
  }
  llvm::report_fatal_error("sourcekitd object did not resolve to a known type");
}

static bool SKDVar_array_apply(
    sourcekitd_variant_t array,
    llvm::function_ref<bool(size_t, sourcekitd_variant_t)> applier) {
  return dyn_cast<SKDArray>(SKD_OBJ(array))->apply([&](size_t Index,
                                                       SKDObjectRef Object){
    return applier(Index, variantFromSKDObject(Object));
  });
}

static bool SKDVar_array_get_bool(sourcekitd_variant_t array, size_t index) {
  return SKD_OBJ(array)->get(index)->getBool();
}

static size_t SKDVar_array_get_count(sourcekitd_variant_t array) {
  return SKD_OBJ(array)->getCount();
}

static int64_t SKDVar_array_get_int64(sourcekitd_variant_t array, size_t index) {
  return SKD_OBJ(array)->get(index)->getInt64().getValueOr(0);
}

static const char *
SKDVar_array_get_string(sourcekitd_variant_t array, size_t index) {
  return SKD_OBJ(array)->get(index)->getCString();
}

static sourcekitd_uid_t SKDVar_array_get_uid(sourcekitd_variant_t array,
                                             size_t index) {
  return SKD_OBJ(array)->get(index)->getUID();
}

static sourcekitd_variant_t
SKDVar_array_get_value(sourcekitd_variant_t array, size_t index) {
  return variantFromSKDObject(SKD_OBJ(array)->get(index));
}

static bool SKDVar_bool_get_value(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getBool();
}

static bool SKDVar_dictionary_apply(
    sourcekitd_variant_t dict,
    llvm::function_ref<bool(sourcekitd_uid_t, sourcekitd_variant_t)> applier) {
  return dyn_cast<SKDDictionary>(SKD_OBJ(dict))->apply([&](sourcekitd_uid_t Key,
                                                           SKDObjectRef Object){
    return applier(Key, variantFromSKDObject(Object));
  });
}

static bool
SKDVar_dictionary_get_bool(sourcekitd_variant_t dict, sourcekitd_uid_t key) {
  if (auto Object = SKD_OBJ(dict)->get(key)) {
    return Object->getBool();
  }
  return false;
}

static int64_t
SKDVar_dictionary_get_int64(sourcekitd_variant_t dict, sourcekitd_uid_t key) {
  if (auto Object = SKD_OBJ(dict)->get(key)) {
    return Object->getInt64().getValueOr(0);
  }
  return 0;
}

static const char *
SKDVar_dictionary_get_string(sourcekitd_variant_t dict, sourcekitd_uid_t key) {
  if (auto Object = SKD_OBJ(dict)->get(key)) {
    return Object->getCString();
  }
  return nullptr;
}

static sourcekitd_variant_t
SKDVar_dictionary_get_value(sourcekitd_variant_t dict, sourcekitd_uid_t key) {
  return variantFromSKDObject(SKD_OBJ(dict)->get(key));
}

static sourcekitd_uid_t
SKDVar_dictionary_get_uid(sourcekitd_variant_t dict, sourcekitd_uid_t key) {
  if (auto Object = SKD_OBJ(dict)->get(key)) {
    return Object->getUID();
  }
  return nullptr;
}

static size_t SKDVar_string_get_length(sourcekitd_variant_t obj) {
  auto String = SKD_OBJ(obj)->getString();
  return String.hasValue() ? String->size() : 0;
}

static const char *SKDVar_string_get_ptr(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getCString();
}

static int64_t SKDVar_int64_get_value(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getInt64().getValueOr(0);
}

static sourcekitd_uid_t SKDVar_uid_get_value(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getUID();
}

static const void *SKDVar_data_get_ptr(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getDataPtr();
}

static size_t SKDVar_data_get_size(sourcekitd_variant_t obj) {
  return SKD_OBJ(obj)->getDataSize();
}

static VariantFunctions SKDVariantFuncs = {
  SKDVar_get_type,
  SKDVar_array_apply,
  SKDVar_array_get_bool,
  SKDVar_array_get_count,
  SKDVar_array_get_int64,
  SKDVar_array_get_string,
  SKDVar_array_get_uid,
  SKDVar_array_get_value,
  SKDVar_bool_get_value,
  SKDVar_dictionary_apply,
  SKDVar_dictionary_get_bool,
  SKDVar_dictionary_get_int64,
  SKDVar_dictionary_get_string,
  SKDVar_dictionary_get_value,
  SKDVar_dictionary_get_uid,
  SKDVar_string_get_length,
  SKDVar_string_get_ptr,
  SKDVar_int64_get_value,
  SKDVar_uid_get_value,
  SKDVar_data_get_size,
  SKDVar_data_get_ptr,
};

static sourcekitd_variant_t variantFromSKDObject(SKDObjectRef Object) {
  if (!Object)
    return makeNullVariant();

  if (auto DataObject = dyn_cast<SKDCustomData>(Object)) {
    switch(DataObject->getBufferKind()) {
      case CustomBufferKind::TokenAnnotationsArray:
        return {{ (uintptr_t)getVariantFunctionsForTokenAnnotationsArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::DocSupportAnnotationArray:
        return {{ (uintptr_t)getVariantFunctionsForDocSupportAnnotationArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::CodeCompletionResultsArray:
        return {{ (uintptr_t)getVariantFunctionsForCodeCompletionResultsArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::DocStructureArray:
        return {{ (uintptr_t)getVariantFunctionsForDocStructureArray(),
          (uintptr_t)DataObject->getDataPtr(), ~size_t(0) }};
      case CustomBufferKind::InheritedTypesArray:
        return {{ (uintptr_t)getVariantFunctionsForInheritedTypesArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::DocStructureElementArray:
        return {{ (uintptr_t)getVariantFunctionsForDocStructureElementArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::AttributesArray:
        return {{ (uintptr_t)getVariantFunctionsForAttributesArray(),
          (uintptr_t)DataObject->getDataPtr(), 0 }};
      case CustomBufferKind::RawData:
        return {{ (uintptr_t)getVariantFunctionsForRawData(),
                  (uintptr_t)DataObject->getDataPtr(),
                  (uintptr_t)DataObject->getDataSize() }};
    }
  }

  return {{ (uintptr_t)&SKDVariantFuncs, (uintptr_t)Object.get(), 0 }};
}


text:
<?php

/**
 * @task  routing URI Routing
 * @group aphront
 */
abstract class AphrontApplicationConfiguration {

  private $request;
  private $host;
  private $path;
  private $console;

  abstract public function getApplicationName();
  abstract public function getURIMap();
  abstract public function buildRequest();
  abstract public function build404Controller();
  abstract public function buildRedirectController($uri);

  final public function setRequest(AphrontRequest $request) {
    $this->request = $request;
    return $this;
  }

  final public function getRequest() {
    return $this->request;
  }

  final public function getConsole() {
    return $this->console;
  }

  final public function setConsole($console) {
    $this->console = $console;
    return $this;
  }

  final public function setHost($host) {
    $this->host = $host;
    return $this;
  }

  final public function getHost() {
    return $this->host;
  }

  final public function setPath($path) {
    $this->path = $path;
    return $this;
  }

  final public function getPath() {
    return $this->path;
  }

  public function willBuildRequest() {
  }

  /**
   * Hook for synchronizing account information from OAuth workflows.
   *
   * @task hook
   */
  public function willAuthenticateUserWithOAuth(
    PhabricatorUser $user,
    PhabricatorUserOAuthInfo $oauth_info,
    PhabricatorOAuthProvider $provider) {
    return;
  }

/* -(  URI Routing  )-------------------------------------------------------- */

  /**
   * Using builtin and application routes, build the appropriate
   * @{class:AphrontController} class for the request. To route a request, we
   * first test if the HTTP_HOST is configured as a valid Phabricator URI. If
   * it isn't, we do a special check to see if it's a custom domain for a blog
   * in the Phame application and if that fails we error. Otherwise, we test
   * the URI against all builtin routes from @{method:getURIMap}, then against
   * all application routes from installed @{class:PhabricatorApplication}s.
   *
   * If we match a route, we construct the controller it points at, build it,
   * and return it.
   *
   * If we fail to match a route, but the current path is missing a trailing
   * "/", we try routing the same path with a trailing "/" and do a redirect
   * if that has a valid route. The idea is to canoncalize URIs for consistency,
   * but avoid breaking noncanonical URIs that we can easily salvage.
   *
   * NOTE: We only redirect on GET. On POST, we'd drop parameters and most
   * likely mutate the request implicitly, and a bad POST usually indicates a
   * programming error rather than a sloppy typist.
   *
   * If the failing path already has a trailing "/", or we can't route the
   * version with a "/", we call @{method:build404Controller}, which build a
   * fallback @{class:AphrontController}.
   *
   * @return pair<AphrontController,dict> Controller and dictionary of request
   *                                      parameters.
   * @task routing
   */
  final public function buildController() {
    $request = $this->getRequest();

    if (PhabricatorEnv::getEnvConfig('security.require-https')) {
      if (!$request->isHTTPS()) {
        $uri = $request->getRequestURI();
        $uri->setDomain($request->getHost());
        $uri->setProtocol('https');
        return $this->buildRedirectController($uri);
      }
    }

    $path     = $request->getPath();
    $host     = $request->getHost();
    $base_uri = PhabricatorEnv::getEnvConfig('phabricator.base-uri');
    $prod_uri = PhabricatorEnv::getEnvConfig('phabricator.production-uri');
    $file_uri = PhabricatorEnv::getEnvConfig('security.alternate-file-domain');

    // NOTE: If the base URI isn't defined yet, don't activate alternate
    // domains.
    if ($base_uri &&
        $host != id(new PhutilURI($base_uri))->getDomain() &&
        $host != id(new PhutilURI($prod_uri))->getDomain() &&
        $host != id(new PhutilURI($file_uri))->getDomain()) {

      try {
        $blog = id(new PhameBlogQuery())
          ->setViewer(new PhabricatorUser())
          ->withDomain($host)
          ->executeOne();
      } catch (PhabricatorPolicyException $ex) {
        throw new Exception(
          "This blog is not visible to logged out users, so it can not be ".
          "visited from a custom domain.");
      }

      if (!$blog) {
        if ($prod_uri && $prod_uri != $base_uri) {
          $prod_str = ' or '.$prod_uri;
        } else {
          $prod_str = '';
        }
        throw new Exception(
          'Specified domain '.$host.' is not configured for Phabricator '.
          'requests. Please use '.$base_uri.$prod_str.' to visit this instance.'
        );
      }

      // TODO: Make this more flexible and modular so any application can
      // do crazy stuff here if it wants.

      $path = '/phame/live/'.$blog->getID().'/'.$path;
    }

    list($controller, $uri_data) = $this->buildControllerForPath($path);
    if (!$controller) {
      if (!preg_match('@/$@', $path)) {
        // If we failed to match anything but don't have a trailing slash, try
        // to add a trailing slash and issue a redirect if that resolves.
        list($controller, $uri_data) = $this->buildControllerForPath($path.'/');

        // NOTE: For POST, just 404 instead of redirecting, since the redirect
        // will be a GET without parameters.

        if ($controller && !$request->isHTTPPost()) {
          $uri = $request->getRequestURI()->setPath($path.'/');
          return $this->buildRedirectController($uri);
        }
      }
      return $this->build404Controller();
    }

    return array($controller, $uri_data);
  }

  /**
   * Map a specific path to the corresponding controller. For a description
   * of routing, see @{method:buildController}.
   *
   * @return pair<AphrontController,dict> Controller and dictionary of request
   *                                      parameters.
   * @task routing
   */
  final public function buildControllerForPath($path) {
    $maps = array();
    $maps[] = array(null, $this->getURIMap());

    $applications = PhabricatorApplication::getAllInstalledApplications();
    foreach ($applications as $application) {
      $maps[] = array($application, $application->getRoutes());
    }

    $current_application = null;
    $controller_class = null;
    foreach ($maps as $map_info) {
      list($application, $map) = $map_info;

      $mapper = new AphrontURIMapper($map);
      list($controller_class, $uri_data) = $mapper->mapPath($path);

      if ($controller_class) {
        if ($application) {
          $current_application = $application;
        }
        break;
      }
    }

    if (!$controller_class) {
      return array(null, null);
    }

    $request = $this->getRequest();

    $controller = newv($controller_class, array($request));
    if ($current_application) {
      $controller->setCurrentApplication($current_application);
    }

    return array($controller, $uri_data);
  }
}


text:
// Copyright (c) 2009-2019 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Starwels developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef STARWELS_STARWELSCONSENSUS_H
#define STARWELS_STARWELSCONSENSUS_H

#include <stdint.h>

#if defined(BUILD_STARWELS_INTERNAL) && defined(HAVE_CONFIG_H)
#include <config/starwels-config.h>
  #if defined(_WIN32)
    #if defined(DLL_EXPORT)
      #if defined(HAVE_FUNC_ATTRIBUTE_DLLEXPORT)
        #define EXPORT_SYMBOL __declspec(dllexport)
      #else
        #define EXPORT_SYMBOL
      #endif
    #endif
  #elif defined(HAVE_FUNC_ATTRIBUTE_VISIBILITY)
    #define EXPORT_SYMBOL __attribute__ ((visibility ("default")))
  #endif
#elif defined(MSC_VER) && !defined(STATIC_LIBSTARWELSCONSENSUS)
  #define EXPORT_SYMBOL __declspec(dllimport)
#endif

#ifndef EXPORT_SYMBOL
  #define EXPORT_SYMBOL
#endif

#ifdef __cplusplus
extern "C" {
#endif

#define STARWELSCONSENSUS_API_VER 1

typedef enum starwelsconsensus_error_t
{
    starwelsconsensus_ERR_OK = 0,
    starwelsconsensus_ERR_TX_INDEX,
    starwelsconsensus_ERR_TX_SIZE_MISMATCH,
    starwelsconsensus_ERR_TX_DESERIALIZE,
    starwelsconsensus_ERR_AMOUNT_REQUIRED,
    starwelsconsensus_ERR_INVALID_FLAGS,
} starwelsconsensus_error;

/** Script verification flags */
enum
{
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_NONE                = 0,
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_P2SH                = (1U << 0), // evaluate P2SH (BIP16) subscripts
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_DERSIG              = (1U << 2), // enforce strict DER (BIP66) compliance
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_NULLDUMMY           = (1U << 4), // enforce NULLDUMMY (BIP147)
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9), // enable CHECKLOCKTIMEVERIFY (BIP65)
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_CHECKSEQUENCEVERIFY = (1U << 10), // enable CHECKSEQUENCEVERIFY (BIP112)
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_WITNESS             = (1U << 11), // enable WITNESS (BIP141)
    starwelsconsensus_SCRIPT_FLAGS_VERIFY_ALL                 = starwelsconsensus_SCRIPT_FLAGS_VERIFY_P2SH | starwelsconsensus_SCRIPT_FLAGS_VERIFY_DERSIG |
                                                               starwelsconsensus_SCRIPT_FLAGS_VERIFY_NULLDUMMY | starwelsconsensus_SCRIPT_FLAGS_VERIFY_CHECKLOCKTIMEVERIFY |
                                                               starwelsconsensus_SCRIPT_FLAGS_VERIFY_CHECKSEQUENCEVERIFY | starwelsconsensus_SCRIPT_FLAGS_VERIFY_WITNESS
};

/// Returns 1 if the input nIn of the serialized transaction pointed to by
/// txTo correctly spends the scriptPubKey pointed to by scriptPubKey under
/// the additional constraints specified by flags.
/// If not nullptr, err will contain an error/success code for the operation
EXPORT_SYMBOL int starwelsconsensus_verify_script(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen,
                                                 const unsigned char *txTo        , unsigned int txToLen,
                                                 unsigned int nIn, unsigned int flags, starwelsconsensus_error* err);

EXPORT_SYMBOL int starwelsconsensus_verify_script_with_amount(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, int64_t amount,
                                    const unsigned char *txTo        , unsigned int txToLen,
                                    unsigned int nIn, unsigned int flags, starwelsconsensus_error* err);

EXPORT_SYMBOL unsigned int starwelsconsensus_version();

#ifdef __cplusplus
} // extern "C"
#endif

#undef EXPORT_SYMBOL

#endif // STARWELS_STARWELSCONSENSUS_H


text:
"""
test_yadi
----------------------------------

Tests for `yadi` module.
"""

import unittest

from yadi import yadi

class TestYadi(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
module.exports = function(config) {
  config.set({
    basePath: '',
//    autoWatch: true,
    frameworks: ['mocha', 'chai'],
    files: [
      // src
      'src/skins/Skin.js',

      'src/entry-exit.js',

      'src/utils/PathUtil.js',
      'src/utils/StringUtil.js',
      'src/utils/LiteralUtil.js',

      'src/share/constants.js',
      'src/share/functions.js',
      'src/share/RES.js',

      'src/base/Watcher.js',
      'src/base/Accessor.js',
      'src/base/Schedule.js',
      'src/base/Validator.js',
      'src/base/Evaluator.js',
      'src/base/Expression.js',
      'src/base/DirtyMarker.js',

      'src/core/models/Store.js',
      'src/core/models/Container.js',
      'src/core/models/Collection.js',

      'src/core/shadows/Shadow.js',
      'src/core/shadows/Text.js',
      'src/core/shadows/Element.js',
      'src/core/shadows/Component.js',

      'src/core/bindings/Binding.js',
      'src/core/bindings/DataBinding.js',
      'src/core/bindings/TextBinding.js',
      'src/core/bindings/EventBinding.js',

      'src/core/template/HTMXEngine.js',
      'src/core/template/HTMXTemplate.js',

      'src/core/template/parsers/EvaluatorParser.js',
      'src/core/template/parsers/DataBindingParser.js',
      'src/core/template/parsers/EventBindingParser.js',
      'src/core/template/parsers/TextBindingParser.js',
      'src/core/template/parsers/HTMLParser.js',
      'src/core/template/parsers/HTMXParser.js',

      'src/exit.js',

      // test
      'test/share/functions.test.js',
      'test/share/RES.test.js',

      'test/utils/PathUtil.test.js',
      'test/utils/StringUtil.test.js',
      'test/utils/LiteralUtil.test.js',

      'test/base/Watcher.test.js',
      'test/base/Accessor.test.js',
      'test/base/Schedule.test.js',
      'test/base/Validator.test.js',
      'test/base/Evaluator.test.js',
      'test/base/Expression.test.js',
      'test/base/DirtyMarker.test.js',

      'test/core/bindings/Binding.test.js',

      'test/core/models/Store.test.js',
      'test/core/models/Container.test.js',
      'test/core/models/Collection.test.js',

      'test/core/shadows/Text.test.js',
      'test/core/shadows/Shadow.test.js',
      'test/core/shadows/Element.test.js',

      'test/core/template/HTMXTemplate.test.js',
      'test/core/template/parsers/HTMLParser.test.js',
      'test/core/template/parsers/HTMXParser.test.js',
      'test/core/template/parsers/EvaluatorParser.test.js',
      'test/core/template/parsers/DataBindingParser.test.js',
      'test/core/template/parsers/EventBindingParser.test.js',
      'test/core/template/parsers/TextBindingParser.test.js'
    ],
    plugins: [
        'karma-coverage',
        'karma-chai',
        'karma-mocha',
        'karma-mocha-reporter',
        'karma-chrome-launcher',
        'karma-phantomjs-launcher'
    ],

    browsers: ['PhantomJS'/*, 'Chrome'*/], // , 'Firefox'],

    reporters: [/*'progress', */'coverage', 'mocha'],
    preprocessors: { './src/**/*.js': ['coverage'] },

    singleRun: true,
    logLevel: config.LOG_INFO,
    colors: true,

//    mochaReporter: {
//      output: 'full'
//    },

    coverageReporter: {
        dir : 'reporters/coverage/',
        reporters: [
            { type: 'html', subdir: 'html' }//,
//            { type: 'lcovonly', subdir: 'lcov' },
//            { type: 'cobertura', subdir: 'cobertura' }
        ]
    }
  });
};


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('food', '0006_auto_20150927_1837'),
    ]

    operations = [
        migrations.AddField(
            model_name='expectedattendance',
            name='date',
            field=models.DateField(default=datetime.date(2015, 9, 27)),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='expectedconsumption',
            name='date',
            field=models.DateField(default=datetime.date(2015, 9, 27)),
            preserve_default=False,
        ),
    ]


text:
module WSO2

  module WSF

    class WSSecurityToken

       def initialize(policy)
	     return unless policy.kind_of? Hash
	     @policy = policy
       end

       def option(option_name)
		  return @policy.has_key?(option_name) ? @policy[option_name] : nil
       end

    end

  end

end