text:
using log4net;
using Nini.Config;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using System;
using System.IO;
using System.Net;
using System.Reflection;

namespace OpenSim.Server.Handlers.Hypergrid
{
    public class HeloServerGetHandler : BaseStreamHandler
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private string m_HandlersType;

        public HeloServerGetHandler(string handlersType) :
            base("GET", "/helo")
        {
            m_HandlersType = handlersType;
        }

        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            return OKResponse(httpResponse);
        }

        private byte[] OKResponse(IOSHttpResponse httpResponse)
        {
            m_log.Debug("[HELO]: hi, GET was called");
            httpResponse.AddHeader("X-Handlers-Provided", m_HandlersType);
            httpResponse.StatusCode = (int)HttpStatusCode.OK;
            httpResponse.StatusDescription = "OK";
            return new byte[0];
        }
    }

    public class HeloServerHeadHandler : BaseStreamHandler
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private string m_HandlersType;

        public HeloServerHeadHandler(string handlersType) :
            base("HEAD", "/helo")
        {
            m_HandlersType = handlersType;
        }

        protected override byte[] ProcessRequest(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            return OKResponse(httpResponse);
        }

        private byte[] OKResponse(IOSHttpResponse httpResponse)
        {
            m_log.Debug("[HELO]: hi, HEAD was called");
            httpResponse.AddHeader("X-Handlers-Provided", m_HandlersType);
            httpResponse.StatusCode = (int)HttpStatusCode.OK;
            httpResponse.StatusDescription = "OK";
            return new byte[0];
        }
    }

    public class HeloServiceInConnector : ServiceConnector
    {
        public HeloServiceInConnector(IConfigSource config, IHttpServer server, string configName) :
            base(config, server, configName)
        {
            server.AddStreamHandler(new HeloServerGetHandler("opensim-robust"));
            server.AddStreamHandler(new HeloServerHeadHandler("opensim-robust"));
        }
    }
}


text:
source "src/cicd/k8s.sh"
source "src/cicd/docker.sh"
source "src/cicd/gke.sh"

hp_prePushVerification_help() { echo "validates that local code is ready for pull request"; }
hp_prePushVerification() {
    hp_minikubeBuildDeployTest
}

hp_onPullRequest() {
    hp_dockerBuildTagAndTest
}

hp_onMasterMerge() { export gcpCicdServiceAccountCredentialsJson
    cicdProductionBuildDeployTest
}

cicdProductionBuildDeployTest() {
    gcloud_cicdAccountLogin
    productionBuildDeployTest
}

productionBuildDeployTest() {
    #TODO: DRY up wrt: hp_minikubeBuildDeployTest
    local imageRepository="$(hp_gcr)"
    local shaToBuild="$(git_currentSha)"
    local taggedImageName="$(hp_taggedImageName ${imageRepository} ${shaToBuild})"
    hp_buildAndTagImage "${taggedImageName}" "${shaToBuild}"
    hp_dockerTestImage "${taggedImageName}"
    hp_docker push "${taggedImageName}"
    hp_deployToKubernetes "${taggedImageName}"
    hp_testUntilSuccess 120 15 hp_test "http://www.heartpoints.org/"
}

hp_manualDeploy_help() { echo "interactive interview to deploy to production"; }
hp_manualDeploy() { local gitSha=$1
    requiredParameter "gitSha" "${gitSha}"
    hp_deployToKubernetes "$(hp_taggedImageName $(hp_gcr) ${gitSha})"
}

hp_manualProductionBuildDeployTest() {
    gcloud_manualLogin
    productionBuildDeployTest
}

hp_buildAndPushCicdImage() {
    local imageURI="$(hp_gcr)/cicd:1.0.1"
    hp_docker build -t "$imageURI" -f cicd.Dockerfile .
    gcloud_manualLogin
    hp_docker push "$imageURI"
}

redpajama_set_name: RedPajamaGithub


text:
var assert = require('assert');

var index = 0;
var inputArray;
function readLine() {
  return inputArray[index++];
}

class Grid {
  constructor(len, max) {
    this.l = len;
    this.max = max;
    assert(max.length === len);
  }

  get length() {
    return this.l;
  }

  // +1 step
  neighbors(coord, step) {
    assert(coord.length === this.l);
    var newCoordinates = [];
    for (var i = 0; i < this.max.length; i++) {
      var newC = coord[i]+step;
      if (newC > 0 && newC <= this.max[i]) {
        var neighbor = new Array(coord.length);
        for (var k = 0; k < coord.length; k++) {
          neighbor[k] = coord[k];
        }
        neighbor[i] = coord[i]+step;
        newCoordinates.push(neighbor);
      }
    }
    //console.log(coord, step, newCoordinates);
    return newCoordinates;
  }

  process(start, M) {
    var frontier = [];
    frontier.push(start);
    var counts = [];

    for(var i = 0; i < M; i++) {
      var newFrontier = [];
      for(var j = 0; j < frontier.length; j++) {
        var c = frontier[j];
        var nodes = this.neighbors(c, 1);
        for(var k = 0; k < nodes.length; k++) {
          newFrontier.push(nodes[k]);
        }
        var nodes = this.neighbors(c, -1);
        for(var k = 0; k < nodes.length; k++) {
          newFrontier.push(nodes[k]);
        }
      }
      //console.log(newFrontier);
      counts.push(newFrontier.length);
      frontier = [];
      for(var k = 0; k < newFrontier.length; k++) {
        frontier.push(newFrontier[k]);
      }
    }
//console.log(counts);
    return counts[M-1];
  }
}

function processData(input) {
    //Enter your code here
    inputArray = input.split('\n');

    var tc = parseInt(readLine());
    for (var i = 0; i < tc; i++) {
      var line = readLine().split(' ').map(Number);
      var gridLen = line[0];
      var M = line[1];

      var start = readLine().split(' ').map(Number);
      var gridMax = readLine().split(' ').map(Number);

      assert(gridLen === gridMax.length);
      assert(gridLen === start.length);

      var g = new Grid(gridLen, gridMax);

      //console.log("+1", g.neighbors(start, 1));
      //console.log("-1", g.neighbors(start, -1));

      console.log(g.process(start, M));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});


text:
#include <aws/backup/model/GetBackupVaultNotificationsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Backup::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetBackupVaultNotificationsResult::GetBackupVaultNotificationsResult()
{
}

GetBackupVaultNotificationsResult::GetBackupVaultNotificationsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetBackupVaultNotificationsResult& GetBackupVaultNotificationsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("BackupVaultName"))
  {
    m_backupVaultName = jsonValue.GetString("BackupVaultName");

  }

  if(jsonValue.ValueExists("BackupVaultArn"))
  {
    m_backupVaultArn = jsonValue.GetString("BackupVaultArn");

  }

  if(jsonValue.ValueExists("SNSTopicArn"))
  {
    m_sNSTopicArn = jsonValue.GetString("SNSTopicArn");

  }

  if(jsonValue.ValueExists("BackupVaultEvents"))
  {
    Aws::Utils::Array<JsonView> backupVaultEventsJsonList = jsonValue.GetArray("BackupVaultEvents");
    for(unsigned backupVaultEventsIndex = 0; backupVaultEventsIndex < backupVaultEventsJsonList.GetLength(); ++backupVaultEventsIndex)
    {
      m_backupVaultEvents.push_back(BackupVaultEventMapper::GetBackupVaultEventForName(backupVaultEventsJsonList[backupVaultEventsIndex].AsString()));
    }
  }

  return *this;
}


text:
#pragma once

#include "envoy/init/manager.h"

#include "source/common/init/target_impl.h"
#include "source/common/init/watcher_impl.h"

#include "absl/container/flat_hash_map.h"
#include "gmock/gmock.h"

namespace Envoy {
namespace Init {

/**
 * ExpectableWatcherImpl is a real WatcherImpl, subclassed to add a mock `ready` method that you can
 * set expectations on in tests. Tests should never want a watcher with different behavior than the
 * real implementation.
 */
class ExpectableWatcherImpl : public WatcherImpl {
public:
  ExpectableWatcherImpl(absl::string_view name = "test");
  MOCK_METHOD(void, ready, (), (const));

  /**
   * Convenience method to provide a shorthand for EXPECT_CALL(watcher, ready()). Can be chained,
   * for example: watcher.expectReady().Times(0);
   */
  ::testing::internal::TypedExpectation<void()>& expectReady() const;
};

/**
 * ExpectableTargetImpl is a real TargetImpl, subclassed to add a mock `initialize` method that you
 * can set expectations on in tests. Tests should never want a target with a different behavior than
 * the real implementation.
 */
class ExpectableTargetImpl : public TargetImpl {
public:
  ExpectableTargetImpl(absl::string_view name = "test");
  MOCK_METHOD(void, initialize, ());

  /**
   * Convenience method to provide a shorthand for EXPECT_CALL(target, initialize()). Can be
   * chained, for example: target.expectInitialize().Times(0);
   */
  ::testing::internal::TypedExpectation<void()>& expectInitialize();

  /**
   * Convenience method to provide a shorthand for expectInitialize() with mocked behavior of
   * calling `ready` immediately.
   */
  ::testing::internal::TypedExpectation<void()>& expectInitializeWillCallReady();
};

/**
 * Borrow the idea from ExpectableTargetImpl. ExpectableSharedTargetImpl is a real SharedTargetImpl.
 */
class ExpectableSharedTargetImpl : public SharedTargetImpl {
public:
  ExpectableSharedTargetImpl(absl::string_view name = "test");
  ExpectableSharedTargetImpl(absl::string_view name, InitializeFn fn);
  MOCK_METHOD(void, initialize, ());

  ::testing::internal::TypedExpectation<void()>& expectInitialize();
};

/**
 * MockManager is a typical mock. In many cases, it won't be necessary to mock any of its methods.
 * In cases where its `add` and `initialize` methods are actually called in a test, it's usually
 * sufficient to mock `add` by saving the target argument locally, and to mock `initialize` by
 * invoking the saved target with the watcher argument.
 */
struct MockManager : Manager {
  MOCK_METHOD(Manager::State, state, (), (const));
  MOCK_METHOD(void, add, (const Target&));
  MOCK_METHOD(void, initialize, (const Watcher&));
  MOCK_METHOD((const absl::flat_hash_map<std::string, uint32_t>&), unreadyTargets, (), (const));
  MOCK_METHOD(void, dumpUnreadyTargets, (envoy::admin::v3::UnreadyTargetsDumps&));
};

} // namespace Init
} // namespace Envoy


text:
<?php

/**
 * sfComponents.
 *
 * @package    symfony
 * @subpackage action
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfComponents.class.php 20048 2009-07-09 09:53:03Z FabianLange $
 */
abstract class sfComponents extends sfComponent
{
  /**
   * @throws sfInitializationException
   *
   * @see sfComponent
   */
  public function execute($request)
  {
    throw new sfInitializationException('sfComponents initialization failed.');
  }
}


text:
package com.xlg.android;

import com.xlg.android.protocol.Header;
import com.xlg.android.protocol.Hello;
import com.xlg.android.protocol.LogonError;
import com.xlg.android.protocol.LogonRequest;
import com.xlg.android.protocol.LogonResponse;
import com.xlg.android.protocol.Message;
import com.xlg.android.protocol.RegisterRequest;
import com.xlg.android.utils.ByteBuffer;

public class LoginChannel  implements ClientSocketHandler {
	// 客户端回调
	private LoginHandler mHandler;
	// 新的socket对像
	private ClientSocket mSocket = new ClientSocket(this);
	// 接收缓冲区
	private ByteBuffer mBuffer = new ByteBuffer();

	public LoginChannel(LoginHandler handler) {
		mHandler = handler;
	}

	// 连接服务器
	public int Connect(String ip, int port) {
		return mSocket.Connect(ip, port);
	}

	// 关闭
	public void Close() {
		mSocket.Close();
	}

	@Override
	public void onConnected(int ret) {
		if(0 == ret) {
			mHandler.onConnectSuccessed();
		} else {
			mHandler.onConnectFailed();
		}
	}

	@Override
	public void onRecv(byte[] data, int size) {
//		System.out.println("接收数据"+data.length+"----size"+size);
		// 加入缓冲区
		mBuffer.addBytes(data, 0, size);
//		System.out.println("mBuffer"+mBuffer.size());
		// 解析数据
		Header head = new Header();
		int len;

		while(true)
		{
			len = Message.DecodeHeader(mBuffer, head);
//			System.out.println("len"+len);
			if(len <= 0) {
				break;
			}
			System.out.println("登录响应"+head.getCmd1());
			switch (head.getCmd1()) {

			case Header.MessageType_mxpLogonResponse:
			{
				LogonResponse obj = new LogonResponse();
				Message.DecodeObject(mBuffer, obj);
				mHandler.onLogonResponse(obj);
				break;
			}
			case Header.MessageType_mxpLogonError:
			{
				LogonError obj = new LogonError();
				Message.DecodeObject(mBuffer, obj);
				mHandler.onLogonError(obj);
				break;
			}
			default:
				break;
			}

			// 移除一个包
			mBuffer.rdarin(head.getLength());
		}
	}

	@Override
	public void onDisconnected() {
		mHandler.onDisconnected();
	}

	private void sendPack(Header head, Object obj) {
		ByteBuffer buf = new ByteBuffer();

		if( Message.EncodePack(buf, head, obj, true) ) {
			byte [] data = new byte[buf.size()];

			buf.getBytes(data, 0, buf.size());
			mSocket.Send(data);
		}
	}

	// 发送Hello
	public void SendHello() {
		Header head = new Header();
		Hello obj = new Hello();

		// 构建消息头
		head.setCmd1(Header.MessageType_mxpClientHelloCommand);
		// 构建消息体
		obj.setParam0((int)(Math.random() * 0xffff));
		obj.setParam1(obj.getParam0() + (obj.getParam0() & 0xffff));
		obj.setParam2(obj.getParam0() - 2 * (obj.getParam0() & 0xffff));

		sendPack(head, obj);
	}

	// 发送登录请求
	public void SendLogonRequest(int nUserId, int visitor, int nOnlineSate, String pszPwd,
								 String pszMacAddr, String pszDiskId, String cldcode, int flag) {
		Header head = new Header();
		LogonRequest obj = new LogonRequest();

		// 构建消息头
		head.setCmd1(Header.MessageType_mxpLogonRequest);
		// 构建消息体
		obj.setUserid(nUserId);
//		obj.setPort((short) 2);
		obj.setPort((short)2);
		obj.setVisitor((byte)visitor);
		obj.setOnline_stat((byte)nOnlineSate);
		if (flag == 0) {
			obj.setCuserpwd(pszPwd);
		}
		obj.setCmac(pszMacAddr);

		if (flag == 2 ){
			obj.setCldcode(cldcode);
		}
		sendPack(head, obj);
	}

	// 临时用户登录请求
	public void SendTempUserLogonRequest(String pszMacAddr, String pszDiskId) {
		Header head = new Header();
		LogonRequest obj = new LogonRequest();

		// 构建消息头
		head.setCmd1(Header.MessageType_mxpLogonRequest);
		// 构建消息体
		obj.setVisitor((byte)1);
		obj.setOnline_stat((byte)1);
		obj.setCmac(pszMacAddr);

		sendPack(head, obj);
	}
	//注册
	public void SendRegisterRequest(String psd,String cldcode){
		Header head = new Header();
		RegisterRequest obj = new RegisterRequest();
		head.setCmd1(Header.MessageType_mxpRegisterRequest);
		obj.setDeviceid((short) 2);
		obj.setVisitor((byte) 5);
		obj.setCldcode(cldcode);
		obj.setCuserpwd(psd);
		sendPack(head,obj);
	}
}


text:
"use strict";

let express = require('express'),
	app = express(),
	http = require('http').Server(app),
	io = require('socket.io')(http);

app.use(express.static(__dirname));

// var server = app.listen(8080, function(){
// 	console.log("Server ever started?");
// });

app.get('/', function(req, res){
	res.sendFile(__dirname+'/client/index.html');
})

io.on('connection', function(socket){
	console.log('a user connected');
	socket.on('chat message', function(msg){
		console.log("message is "+msg);
		io.emit('chat message', msg);
	});
});

http.listen(8080, function(){
	console.log("Server started at 8080");
})


text:
/**
 * \addtogroup stm32w-cpu
 *
 * @{
 */

/*
 * Copyright (c) 2010, STMicroelectronics.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/**
* \file
*					Machine dependent STM32W radio code.
* \author
*					Salvatore Pitrulli
*					Chi-Anh La la@imag.fr
*         Simon Duquennoy <simonduq@sics.se>
*/

#include PLATFORM_HEADER
#include "hal/error.h"
#include "hal/hal.h"

#include "contiki.h"

#include "net/mac/frame802154.h"

#include "dev/stm32w-radio.h"
#include "net/netstack.h"

#include "net/packetbuf.h"
#include "net/rime/rimestats.h"
#include "sys/rtimer.h"

#define DEBUG 0

#include "dev/leds.h"
#define LED_ACTIVITY 0

#ifdef ST_CONF_RADIO_AUTOACK
#define ST_RADIO_AUTOACK ST_CONF_RADIO_AUTOACK
#else
#define ST_RADIO_AUTOACK 0
#endif /* ST_CONF_RADIO_AUTOACK */

#if RDC_CONF_DEBUG_LED
#define LED_RDC RDC_CONF_DEBUG_LED
#undef LED_ACTIVITY
#define LED_ACTIVITY 1
#else
#define LED_RDC 0
#endif  /* RDC_CONF_DEBUG_LED */

#if DEBUG > 0
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...) do {} while (0)
#endif  /* DEBUG > 0 */

#if LED_ACTIVITY
#define LED_TX_ON() leds_on(LEDS_GREEN)
#define LED_TX_OFF() leds_off(LEDS_GREEN)
#define LED_RX_ON()     do {                                    \
                                if(LED_RDC == 0){               \
                                  leds_on(LEDS_RED);            \
                                }                               \
                        } while (0)
#define LED_RX_OFF()    do {                                    \
                                if(LED_RDC == 0){               \
                                  leds_off(LEDS_RED);           \
                                }                               \
                        } while (0)
#define LED_RDC_ON()    do {                                    \
                                if(LED_RDC == 1){               \
                                  leds_on(LEDS_RED);            \
                                }                               \
                        } while (0)
#define LED_RDC_OFF()   do {                                    \
                                if(LED_RDC == 1){               \
                                  leds_off(LEDS_RED);           \
                                }                               \
                        } while (0)
#else
#define LED_TX_ON()
#define LED_TX_OFF()
#define LED_RX_ON()
#define LED_RX_OFF()
#define LED_RDC_ON()
#define LED_RDC_OFF()
#endif  /* LED_ACTIVITY */

#if RDC_CONF_HARDWARE_CSMA
#undef MAC_RETRIES
#define MAC_RETRIES 0
#endif  /* RDC_CONF_HARDWARE_CSMA */

#ifndef MAC_RETRIES
#define MAC_RETRIES 1
#endif  /* MAC_RETRIES */

#if MAC_RETRIES
int8_t mac_retries_left;
#define INIT_RETRY_CNT() (mac_retries_left = packetbuf_attr(PACKETBUF_ATTR_MAX_MAC_TRANSMISSIONS))
#define DEC_RETRY_CNT() (mac_retries_left--)
#define RETRY_CNT_GTZ() (mac_retries_left > 0)
#else
#define INIT_RETRY_CNT()
#define DEC_RETRY_CNT()
#define RETRY_CNT_GTZ() 0
#endif /* MAC_RETRIES */

/* If set to 1, a send() returns only after the packet has been transmitted.
  This is necessary if you use the x-mac module, for example. */
#ifndef RADIO_WAIT_FOR_PACKET_SENT
#define RADIO_WAIT_FOR_PACKET_SENT 1
#endif  /* RADIO_WAIT_FOR_PACKET_SENT */

#define TO_PREV_STATE()       do {                                    \
                                if(onoroff == OFF){                   \
                                  ST_RadioSleep();                    \
                                  ENERGEST_OFF(ENERGEST_TYPE_LISTEN); \
                                }                                     \
                              } while(0)
#if RDC_CONF_HARDWARE_CSMA
#define ST_RADIO_CHECK_CCA FALSE
#define ST_RADIO_CCA_ATTEMPT_MAX 0
#define ST_BACKOFF_EXP_MIN 0
#define ST_BACKOFF_EXP_MAX 0
#else  /* RDC_CONF_HARDWARE_CSMA */
#define ST_RADIO_CHECK_CCA TRUE
#define ST_RADIO_CCA_ATTEMPT_MAX 4
#define ST_BACKOFF_EXP_MIN 2
#define ST_BACKOFF_EXP_MAX 6
#endif  /* RDC_CONF_HARDWARE_CSMA */

const RadioTransmitConfig radioTransmitConfig = {
  TRUE,                         /* waitForAck; */
  ST_RADIO_CHECK_CCA,           /* checkCca;Set to FALSE with low-power MACs. */
  ST_RADIO_CCA_ATTEMPT_MAX,     /* ccaAttemptMax; */
  ST_BACKOFF_EXP_MIN,           /* backoffExponentMin; */
  ST_BACKOFF_EXP_MAX,           /* backoffExponentMax; */
  TRUE                          /* appendCrc; */
};

#undef MAC_RETRIES
#define MAC_RETRIES 0

/*
 * The buffers which hold incoming data.
 */
#ifndef RADIO_RXBUFS
#define RADIO_RXBUFS 1
#endif  /* RADIO_RXBUFS */

/* +1 because of the first byte, which will contain the length of the packet. */
static uint8_t stm32w_rxbufs[RADIO_RXBUFS][STM32W_MAX_PACKET_LEN + 1];

#if RADIO_RXBUFS > 1
static volatile int8_t first = -1, last = 0;
#else   /* RADIO_RXBUFS > 1 */
static const int8_t first = 0, last = 0;
#endif  /* RADIO_RXBUFS > 1 */

#if RADIO_RXBUFS > 1
#define CLEAN_RXBUFS() do{first = -1; last = 0;}while(0)
#define RXBUFS_EMPTY() (first == -1)
int
RXBUFS_FULL()
{
  int8_t first_tmp = first;
  return first_tmp == last;
}
#else /* RADIO_RXBUFS > 1 */
#define CLEAN_RXBUFS() (stm32w_rxbufs[0][0] = 0)
#define RXBUFS_EMPTY() (stm32w_rxbufs[0][0] == 0)
#define RXBUFS_FULL() (stm32w_rxbufs[0][0] != 0)
#endif /* RADIO_RXBUFS > 1 */

static uint8_t
  __attribute__ ((aligned(2))) stm32w_txbuf[STM32W_MAX_PACKET_LEN + 1];

#define CLEAN_TXBUF() (stm32w_txbuf[0] = 0)
#define TXBUF_EMPTY() (stm32w_txbuf[0] == 0)
#define CHECKSUM_LEN 2

/*
 * The transceiver state.
 */
#define ON     0
#define OFF    1

#define BUSYWAIT_UNTIL(cond, max_time)                                    \
    do {                                                                  \
      rtimer_clock_t t0;                                                  \
      t0 = RTIMER_NOW();                                                  \
      while(!(cond) && RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + (max_time)));   \
    } while(0)

#define GET_LOCK() locked++

static volatile uint8_t onoroff = OFF;
static uint8_t receiving_packet = 0;
static int8_t last_rssi;
static volatile StStatus last_tx_status;
static uint8_t locked;
static volatile uint8_t is_transmit_ack;
/*--------------------------------------------------------------------------*/
static void
RELEASE_LOCK(void)
{
  if(locked > 0)
    locked--;
}
/*---------------------------------------------------------------------------*/
PROCESS(stm32w_radio_process, "STM32W radio driver");
/*---------------------------------------------------------------------------*/
static int stm32w_radio_init(void);

static int stm32w_radio_prepare(const void *payload,
                                unsigned short payload_len);
static int stm32w_radio_transmit(unsigned short payload_len);

static int stm32w_radio_send(const void *data, unsigned short len);

static int stm32w_radio_read(void *buf, unsigned short bufsize);

static int stm32w_radio_channel_clear(void);

static int stm32w_radio_receiving_packet(void);

static int stm32w_radio_pending_packet(void);

static int stm32w_radio_on(void);

static int stm32w_radio_off(void);

static int add_to_rxbuf(uint8_t * src);

static int read_from_rxbuf(void *dest, unsigned short len);

/*--------------------------------------------------------------------------*/
static radio_result_t
get_value(radio_param_t param, radio_value_t *value)
{
  if(!value) {
    return RADIO_RESULT_INVALID_VALUE;
  }
  switch(param) {
  case RADIO_PARAM_POWER_MODE:
    *value = onoroff == ON ? RADIO_POWER_MODE_ON : RADIO_POWER_MODE_OFF;
    return RADIO_RESULT_OK;
  case RADIO_PARAM_CHANNEL:
    *value = ST_RadioGetChannel();
    return RADIO_RESULT_OK;
  case RADIO_PARAM_PAN_ID:
    *value = ST_RadioGetPanId();
    return RADIO_RESULT_OK;
  case RADIO_PARAM_16BIT_ADDR:
    *value = ST_RadioGetNodeId();
    return RADIO_RESULT_OK;
  case RADIO_PARAM_RX_MODE:
    *value = 0;
    if(ST_RadioAddressFilteringEnabled()) {
      *value |= RADIO_RX_MODE_ADDRESS_FILTER;
    }
    if(ST_RadioAutoAckEnabled()) {
      *value |= RADIO_RX_MODE_AUTOACK;
    }
    return RADIO_RESULT_OK;
  case RADIO_PARAM_TXPOWER:
    *value = ST_RadioGetPower();
    return RADIO_RESULT_OK;
  case RADIO_PARAM_CCA_THRESHOLD:
    *value = ST_RadioGetEdCcaThreshold();
    return RADIO_RESULT_OK;
  case RADIO_PARAM_RSSI:
    *value = ST_RadioEnergyDetection();
    return RADIO_RESULT_OK;

  case RADIO_CONST_CHANNEL_MIN:
    *value = ST_MIN_802_15_4_CHANNEL_NUMBER;
    return RADIO_RESULT_OK;
  case RADIO_CONST_CHANNEL_MAX:
    *value = ST_MAX_802_15_4_CHANNEL_NUMBER;
    return RADIO_RESULT_OK;

  case RADIO_CONST_TXPOWER_MIN:
    *value = MIN_RADIO_POWER;
    return RADIO_RESULT_OK;
  case RADIO_CONST_TXPOWER_MAX:
    *value = MAX_RADIO_POWER;
    return RADIO_RESULT_OK;

  default:
    return RADIO_RESULT_NOT_SUPPORTED;
  }
}
/*--------------------------------------------------------------------------*/
static radio_result_t
set_value(radio_param_t param, radio_value_t value)
{
  switch(param) {
  case RADIO_PARAM_POWER_MODE:
    if(value == RADIO_POWER_MODE_ON) {
      stm32w_radio_on();
      return RADIO_RESULT_OK;
    }
    if(value == RADIO_POWER_MODE_OFF) {
      stm32w_radio_off();
      return RADIO_RESULT_OK;
    }
    return RADIO_RESULT_INVALID_VALUE;
  case RADIO_PARAM_CHANNEL:
    if(value < ST_MIN_802_15_4_CHANNEL_NUMBER ||
       value > ST_MAX_802_15_4_CHANNEL_NUMBER) {
      return RADIO_RESULT_INVALID_VALUE;
    }
    if(ST_RadioSetChannel(value) != ST_SUCCESS) {
      return RADIO_RESULT_ERROR;
    }
    return RADIO_RESULT_OK;
  case RADIO_PARAM_PAN_ID:
    ST_RadioSetPanId(value & 0xffff);
    return RADIO_RESULT_OK;
  case RADIO_PARAM_16BIT_ADDR:
    ST_RadioSetNodeId(value & 0xffff);
    return RADIO_RESULT_OK;
  case RADIO_PARAM_RX_MODE:
    if(value & ~(RADIO_RX_MODE_ADDRESS_FILTER |
                 RADIO_RX_MODE_AUTOACK)) {
      return RADIO_RESULT_INVALID_VALUE;
    }
    ST_RadioEnableAddressFiltering((value & RADIO_RX_MODE_ADDRESS_FILTER) != 0);
    ST_RadioEnableAutoAck((value & RADIO_RX_MODE_AUTOACK) != 0);
    return RADIO_RESULT_OK;
  case RADIO_PARAM_TXPOWER:
    if(value < MIN_RADIO_POWER || value > MAX_RADIO_POWER) {
      return RADIO_RESULT_INVALID_VALUE;
    }
    if(ST_RadioSetPower((int8_t)value) != ST_SUCCESS) {
      return RADIO_RESULT_INVALID_VALUE;
    }
    return RADIO_RESULT_OK;
  case RADIO_PARAM_CCA_THRESHOLD:
    ST_RadioSetEdCcaThreshold((int8_t)value);
    return RADIO_RESULT_OK;
  default:
    return RADIO_RESULT_NOT_SUPPORTED;
  }
}
/*--------------------------------------------------------------------------*/
static radio_result_t
get_object(radio_param_t param, void *dest, size_t size)
{
  const uint8_t *eui64;
  uint8_t *target;
  int i;

  if(param == RADIO_PARAM_64BIT_ADDR) {
    if(size < 8 || !dest) {
      return RADIO_RESULT_INVALID_VALUE;
    }
    eui64 = ST_RadioGetEui64();
    if(!eui64) {
      return RADIO_RESULT_ERROR;
    }
    target = dest;
    for(i = 0; i < 8; i++) {
      target[i] = eui64[7 - i];
    }
    return RADIO_RESULT_OK;
  }
  return RADIO_RESULT_NOT_SUPPORTED;
}
/*--------------------------------------------------------------------------*/
static radio_result_t
set_object(radio_param_t param, const void *src, size_t size)
{
  return RADIO_RESULT_NOT_SUPPORTED;
}
/*--------------------------------------------------------------------------*/
const struct radio_driver stm32w_radio_driver = {
  stm32w_radio_init,
  stm32w_radio_prepare,
  stm32w_radio_transmit,
  stm32w_radio_send,
  stm32w_radio_read,
  stm32w_radio_channel_clear,
  stm32w_radio_receiving_packet,
  stm32w_radio_pending_packet,
  stm32w_radio_on,
  stm32w_radio_off,
  get_value,
  set_value,
  get_object,
  set_object
};
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_init(void)
{
  /* A channel also needs to be set. */
  ST_RadioSetChannel(RF_CHANNEL);

  /* Initialize radio (analog section, digital baseband and MAC). */
  /* Leave radio powered up in non-promiscuous rx mode. */
  ST_RadioInit(ST_RADIO_POWER_MODE_OFF);

  onoroff = OFF;
  ST_RadioSetPanId(IEEE802154_PANID);

  CLEAN_RXBUFS();
  CLEAN_TXBUF();

#if ST_RADIO_AUTOACK && !(UIP_CONF_LL_802154 && LINKADDR_CONF_SIZE==8)
#error "Autoack and address filtering can only be used with EUI 64"
#endif
  ST_RadioEnableAutoAck(ST_RADIO_AUTOACK);
  ST_RadioEnableAddressFiltering(ST_RADIO_AUTOACK);

  locked = 0;
  process_start(&stm32w_radio_process, NULL);

  return 0;
}
/*---------------------------------------------------------------------------*/
void
stm32w_radio_set_promiscous(uint8_t on)
{
  if(on) {
    ST_RadioEnableAddressFiltering(0);
  } else {
    ST_RadioEnableAddressFiltering(ST_RADIO_AUTOACK);
  }
}
/*---------------------------------------------------------------------------*/
int
stm32w_radio_set_channel(uint8_t channel)
{
  if (ST_RadioSetChannel(channel) == ST_SUCCESS) {
    return 0;
  } else {
    return 1;
  }
}
/*---------------------------------------------------------------------------*/
static int
wait_for_tx(void)
{
  struct timer t;
  timer_set(&t, CLOCK_SECOND / 10);
  while(!TXBUF_EMPTY()) {
    if(timer_expired(&t)) {
      PRINTF("stm32w: tx buffer full.\r\n");
      return 1;
    }
    /* Put CPU in sleep mode. */
    halSleepWithOptions(SLEEPMODE_IDLE, 0);
  }
  return 0;
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_prepare(const void *payload, unsigned short payload_len)
{
  if(payload_len > STM32W_MAX_PACKET_LEN) {
    PRINTF("stm32w: payload length=%d is too long.\r\n", payload_len);
    return RADIO_TX_ERR;
  }
#if !RADIO_WAIT_FOR_PACKET_SENT
  /*
   * Check if the txbuf is empty. Wait for a finite time.
   * This should not occur if we wait for the end of transmission in
   * stm32w_radio_transmit().
   */
  if(wait_for_tx()) {
    PRINTF("stm32w: tx buffer full.\r\n");
    return RADIO_TX_ERR;
  }
#endif /* RADIO_WAIT_FOR_PACKET_SENT */

  /*
   * Copy to the txbuf.
   * The first byte must be the packet length.
   */
  CLEAN_TXBUF();
  memcpy(stm32w_txbuf + 1, payload, payload_len);

  return RADIO_TX_OK;
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_transmit(unsigned short payload_len)
{
  stm32w_txbuf[0] = payload_len + CHECKSUM_LEN;
  INIT_RETRY_CNT();

  if(onoroff == OFF) {
    PRINTF("stm32w: Radio is off, turning it on.\r\n");
    ST_RadioWake();
    ENERGEST_ON(ENERGEST_TYPE_LISTEN);
  }
#if RADIO_WAIT_FOR_PACKET_SENT
  GET_LOCK();
#endif /* RADIO_WAIT_FOR_PACKET_SENT */
  last_tx_status = -1;
  LED_TX_ON();
  if(ST_RadioTransmit(stm32w_txbuf) == ST_SUCCESS) {
    ENERGEST_OFF(ENERGEST_TYPE_LISTEN);
    ENERGEST_ON(ENERGEST_TYPE_TRANSMIT);
    PRINTF("stm32w: sending %d bytes\r\n", payload_len);

#if DEBUG > 1
    for(uint8_t c = 1; c <= stm32w_txbuf[0] - 2; c++) {
      PRINTF("%x:", stm32w_txbuf[c]);
    }
    PRINTF("\r\n");
#endif

#if RADIO_WAIT_FOR_PACKET_SENT

    if(wait_for_tx()) {
      PRINTF("stm32w: unknown tx error.\r\n");
      TO_PREV_STATE();
      LED_TX_OFF();
      RELEASE_LOCK();
      return RADIO_TX_ERR;
    }

    TO_PREV_STATE();
    if(last_tx_status == ST_SUCCESS || last_tx_status == ST_PHY_ACK_RECEIVED ||
          last_tx_status == ST_MAC_NO_ACK_RECEIVED) {
      RELEASE_LOCK();
      if(last_tx_status == ST_PHY_ACK_RECEIVED) {
        return RADIO_TX_OK;     /* ACK status */
      } else if(last_tx_status == ST_MAC_NO_ACK_RECEIVED ||
          last_tx_status == ST_SUCCESS) {
        return RADIO_TX_NOACK;
      }
    }
    LED_TX_OFF();
    RELEASE_LOCK();
    return RADIO_TX_ERR;

#else /* RADIO_WAIT_FOR_PACKET_SENT */
    TO_PREV_STATE();
    LED_TX_OFF();
    return RADIO_TX_OK;

#endif /* RADIO_WAIT_FOR_PACKET_SENT */
  }

#if RADIO_WAIT_FOR_PACKET_SENT
  RELEASE_LOCK();
#endif /* RADIO_WAIT_FOR_PACKET_SENT */
  TO_PREV_STATE();

  PRINTF("stm32w: transmission never started.\r\n");
  /* TODO: Do we have to retransmit? */

  CLEAN_TXBUF();
  LED_TX_OFF();
  return RADIO_TX_ERR;
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_send(const void *payload, unsigned short payload_len)
{
  if (stm32w_radio_prepare(payload, payload_len) == RADIO_TX_ERR) {
    return RADIO_TX_ERR;
  }
  return stm32w_radio_transmit(payload_len);
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_channel_clear(void)
{
  return ST_RadioChannelIsClear();
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_receiving_packet(void)
{
  return receiving_packet;
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_pending_packet(void)
{
  return !RXBUFS_EMPTY();
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_off(void)
{
  /* Any transmit or receive packets in progress are aborted.
   * Waiting for end of transmission or reception have to be done.
   */
  if(locked) {
    PRINTF("stm32w: try to off while sending/receiving (lock=%u).\r\n",
           locked);
    return 0;
  }
  /* off only if there is no transmission or reception of packet. */
  if(onoroff == ON && TXBUF_EMPTY() && !receiving_packet) {
    LED_RDC_OFF();
    ST_RadioSleep();
    onoroff = OFF;
    CLEAN_TXBUF();
    CLEAN_RXBUFS();

    ENERGEST_OFF(ENERGEST_TYPE_LISTEN);
  }

  return 1;
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_on(void)
{
  PRINTF("stm32w: turn radio on\n");
  if(onoroff == OFF) {
    LED_RDC_ON();
    ST_RadioWake();
    onoroff = ON;

    ENERGEST_ON(ENERGEST_TYPE_LISTEN);
  }

  return 1;
}
/*---------------------------------------------------------------------------*/
int
stm32w_radio_is_on(void)
{
  return onoroff == ON;
}
/*---------------------------------------------------------------------------*/
void
ST_RadioReceiveIsrCallback(uint8_t *packet,
                           boolean ackFramePendingSet,
                           uint32_t time, uint16_t errors, int8_t rssi)
{
  LED_RX_ON();
  PRINTF("stm32w: incomming packet received\n");
  receiving_packet = 0;

  /* Copy packet into the buffer. It is better to do this here. */
  if(add_to_rxbuf(packet)) {
    process_poll(&stm32w_radio_process);
    last_rssi = rssi;
  }
  LED_RX_OFF();
  GET_LOCK();
  is_transmit_ack = 1;
  /* Wait for sending ACK */
  BUSYWAIT_UNTIL(!is_transmit_ack, RTIMER_SECOND / 1500);
  RELEASE_LOCK();
}
/*--------------------------------------------------------------------------*/
void
ST_RadioTxAckIsrCallback(void)
{
  /*
   * This callback is for simplemac 1.1.0.
   * Till now we block (RTIMER_SECOND / 1500)
   * to prevent radio off during ACK transmission.
   */
  is_transmit_ack = 0;
  /* RELEASE_LOCK(); */
}
/*--------------------------------------------------------------------------*/
void
ST_RadioTransmitCompleteIsrCallback(StStatus status,
                                    uint32_t txSyncTime, boolean framePending)
{
  ENERGEST_OFF(ENERGEST_TYPE_TRANSMIT);
  ENERGEST_ON(ENERGEST_TYPE_LISTEN);
  LED_TX_OFF();

  last_tx_status = status;

  if(status == ST_SUCCESS || status == ST_PHY_ACK_RECEIVED) {
    CLEAN_TXBUF();
  } else {
    if(RETRY_CNT_GTZ()) {

      /* Retransmission */
      LED_TX_ON();
      if(ST_RadioTransmit(stm32w_txbuf) == ST_SUCCESS) {
        ENERGEST_OFF(ENERGEST_TYPE_LISTEN);
        ENERGEST_ON(ENERGEST_TYPE_TRANSMIT);
        PRINTF("stm32w: retransmission.\r\n");
        DEC_RETRY_CNT();
      } else {
        CLEAN_TXBUF();
        LED_TX_OFF();
        PRINTF("stm32w: retransmission failed.\r\n");
      }
    } else {
      CLEAN_TXBUF();
    }
  }

  /* Debug outputs. */
  if(status == ST_SUCCESS || status == ST_PHY_ACK_RECEIVED) {
    PRINTF("stm32w: return status TX_END\r\n");
  } else if(status == ST_MAC_NO_ACK_RECEIVED) {
    PRINTF("stm32w: return status TX_END_NOACK\r\n");
  } else if(status == ST_PHY_TX_CCA_FAIL) {
    PRINTF("stm32w: return status TX_END_CCA_FAIL\r\n");
  } else if(status == ST_PHY_TX_UNDERFLOW) {
    PRINTF("stm32w: return status TX_END_UNDERFLOW\r\n");
  } else {
    PRINTF("stm32w: return status TX_END_INCOMPLETE\r\n");
  }
}
/*--------------------------------------------------------------------------*/
boolean
ST_RadioDataPendingShortIdIsrCallback(uint16_t shortId)
{
  receiving_packet = 1;
  return FALSE;
}
/*--------------------------------------------------------------------------*/
boolean
ST_RadioDataPendingLongIdIsrCallback(uint8_t * longId)
{
  receiving_packet = 1;
  return FALSE;
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(stm32w_radio_process, ev, data)
{
  int len;
  PROCESS_BEGIN();
  PRINTF("stm32w_radio_process: started\r\n");

  while(1) {
    PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
    PRINTF("stm32w_radio_process: calling receiver callback\r\n");

#if DEBUG > 1
    for(uint8_t c = 1; c <= RCVD_PACKET_LEN; c++) {
      PRINTF("%x", stm32w_rxbuf[c]);
    }
    PRINTF("\r\n");
#endif

    packetbuf_clear();
    len = stm32w_radio_read(packetbuf_dataptr(), PACKETBUF_SIZE);
    if(len > 0) {
      packetbuf_set_datalen(len);
      NETSTACK_RDC.input();
    }
    if(!RXBUFS_EMPTY()) {
      /*
       * Some data packet still in rx buffer (this happens because process_poll
       * doesn't queue requests), so stm32w_radio_process needs to be called
       * again.
       */
      process_poll(&stm32w_radio_process);
    }
  }
  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
static int
stm32w_radio_read(void *buf, unsigned short bufsize)
{
  return read_from_rxbuf(buf, bufsize);
}
/*---------------------------------------------------------------------------*/
void
ST_RadioOverflowIsrCallback(void)
{
  PRINTF("stm32w: radio overflow\r\n");
}
/*---------------------------------------------------------------------------*/
void
ST_RadioSfdSentIsrCallback(uint32_t sfdSentTime)
{
}
/*---------------------------------------------------------------------------*/
void
ST_RadioMacTimerCompareIsrCallback(void)
{
}
/*---------------------------------------------------------------------------*/
static int
add_to_rxbuf(uint8_t *src)
{
  if(RXBUFS_FULL()) {
    return 0;
  }

  memcpy(stm32w_rxbufs[last], src, src[0] + 1);
#if RADIO_RXBUFS > 1
  last = (last + 1) % RADIO_RXBUFS;
  if(first == -1) {
    first = 0;
  }
#endif

  return 1;
}
/*---------------------------------------------------------------------------*/
static int
read_from_rxbuf(void *dest, unsigned short len)
{
  if(RXBUFS_EMPTY()) {          /* Buffers are all empty */
    return 0;
  }

  if(stm32w_rxbufs[first][0] > len) {   /* Too large packet for dest. */
    len = 0;
  } else {
    len = stm32w_rxbufs[first][0];
    memcpy(dest, stm32w_rxbufs[first] + 1, len);
    packetbuf_set_attr(PACKETBUF_ATTR_RSSI, last_rssi);
  }

#if RADIO_RXBUFS > 1
  ATOMIC(first = (first + 1) % RADIO_RXBUFS;
         int first_tmp = first; if(first_tmp == last) {
         CLEAN_RXBUFS();}
  )
#else
  CLEAN_RXBUFS();
#endif

  return len;
}
/*---------------------------------------------------------------------------*/
short
last_packet_rssi()
{
  return last_rssi;
}
/** @} */


text:
It's an hackable and thread safe c# logmanager for your project.

use it, enjoy it, hack it, improve it =)


text:
require "test_helper"
require "disposable/expose"
require "disposable/composition"

# Disposable::Expose.
class ExposeTest < MiniTest::Spec
  module Model
    Album = Struct.new(:id, :name)
  end

  module Twin
    class Album < Disposable::Twin
      property :id
      property :title, from: :name
    end
  end

  class AlbumExpose < Disposable::Expose
    from Twin::Album.definitions.values
  end

  let (:album) { Model::Album.new(1, "Dick Sandwich") }
  subject { AlbumExpose.new(album) }

  describe "readers" do
    it  do
      subject.id.must_equal 1
      subject.title.must_equal "Dick Sandwich"
    end
  end

  describe "writers" do
    it do
      subject.id = 3
      subject.title = "Eclipse"

      subject.id.must_equal 3
      subject.title.must_equal "Eclipse"
      album.id.must_equal 3
      album.name.must_equal "Eclipse"
    end
  end
end

# Disposable::Composition.
class ExposeCompositionTest < MiniTest::Spec
  module Model
    Band  = Struct.new(:id)
    Album = Struct.new(:id, :name)
  end

  module Twin
    class Album < Disposable::Twin
      property :id,                 on: :album
      property :name,               on: :album
      property :band_id, from: :id, on: :band
    end

    class AlbumComposition < Disposable::Composition
      from Twin::Album.definitions.values
    end
  end

  let (:band) { Model::Band.new(1) }
  let (:album) { Model::Album.new(2, "Dick Sandwich") }
  subject { Twin::AlbumComposition.new(album: album, band: band) }

  describe "readers" do
    it { subject.id.must_equal 2 }
    it { subject.band_id.must_equal 1 }
    it { subject.name.must_equal "Dick Sandwich" }
  end

  describe "writers" do
    it do
      subject.id = 3
      subject.band_id = 4
      subject.name = "Eclipse"

      subject.id.must_equal 3
      subject.band_id.must_equal 4
      subject.name.must_equal "Eclipse"
      band.id.must_equal 4
      album.id.must_equal 3
      album.name.must_equal "Eclipse"
    end
  end
end


text:
FileDownloader::FileDownloader(QUrl imageUrl, QObject *parent) :
 QObject(parent)
{
 connect(
  &m_WebCtrl, SIGNAL (finished(QNetworkReply*)),
  this, SLOT (fileDownloaded(QNetworkReply*))
  );

 QNetworkRequest request(imageUrl);
 m_WebCtrl.get(request);
}

FileDownloader::~FileDownloader() { }

void FileDownloader::fileDownloaded(QNetworkReply* pReply) {
 m_DownloadedData = pReply->readAll();
 //emit a signal
 pReply->deleteLater();
 emit downloaded();
}

QByteArray FileDownloader::downloadedData() const {
 return m_DownloadedData;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Access-Control-Allow-Origin" content="api.vanheemstrapictures.com, www.vanheemstrapictures.com, localhost">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Stateful Person Array Grid Example - MQL Single Person SIMPLE</title>
<link rel="stylesheet" type="text/css" href="/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="/resources/css/ext-example.css" />

Stateful Person Array Grid Example - MQL Single Person SIMPLE

This example shows how to create a person grid from Array data.

The grid is stateful so you can move or hide columns, reload the page, and come
back to the grid in the same state you left it in.

Note that the js is not minified so it is readable. See services-mql-single-person-grid-simple.js.


text:
require 'sinatra'
require 'json'
require 'sinatra/contrib'
require './lib/faxgeraet'

set :root, File.expand_path('../../', __FILE__)

before do
  @fax = Fax::Faxgeraet.new(nil)
end

get '/folders' do
   folders = @fax.fetch_folders
   json folders.map{|f| f.to_hash }
end

get '/:folder' do
  folder_name = params[:folder]
  folder_id = @fax.get_folder_id_by_name(folder_name)
  mails = @fax.show_folder_content(folder_id)
  json mails.map{ |m| m.to_hash }
end

get '/:folder/mail/:id' do
  folder_name = params[:folder]
  mail_id = params[:id]
  json @fax.get_mail_by_id(folder_name, mail_id)
end

post '/fetchmails' do

end

post '/sendmail' do
    # not implemented. Who actually wants to write mails?
end


text:
describe AmaLayout::Agent::Navigation do
  describe "#nav_file_path" do
    let(:file_path) { File.join(Gem.loaded_specs["ama_layout"].full_gem_path, "lib", "ama_layout", "agent_navigation.yml") }

    it "defaults to lib/ama_layout/agent_navigation.yml" do
      expect(subject.nav_file_path).to eq file_path
    end

    context "overridden file path" do
      let(:file_path) do
        File.join(Gem.loaded_specs["ama_layout"].full_gem_path, "spec", "ama_layout", "fixtures", "agent_navigation.yml")
      end
      let(:user) { double("user") }
      let(:subject) { described_class.new(user: user, nav_file_path: file_path, current_url: '/') }

      it "uses the overridden file path" do
        expect(subject.items.first.text).to eq "Waffles"
      end
    end
  end

  describe "#items" do
    it "does not remove nil #navigation_items" do
      expect(subject.items.collect(&:alt)).to include nil
    end

    it "displays links" do
      expect(subject.items.collect(&:link)).to eq subject.navigation_items.collect {|i| i["link"] }
    end

    it "contains text" do
      expect(subject.items.collect(&:text)).to eq subject.navigation_items.collect {|i| i["text"] }
    end

    it "contains icons" do
      expect(subject.items.collect(&:icon)).to eq subject.navigation_items.collect {|i| i["icon"] }
    end

    it "contains alt text" do
      expect(subject.items.collect(&:alt)).to eq subject.navigation_items.collect {|i| i["alt"] }
    end

    context "customer lookup" do
      context "main nav" do
        it "return the main nav items" do
          expect(subject.items[0].text).to eq "Customer Lookup"
          expect(subject.items[0].link).to eq ""
          expect(subject.items[0].icon).to eq ""
        end
      end
    end

    context "driver education" do
      context "main nav" do
        it "return the main nav items" do
          expect(subject.items[1].text).to eq "Driver Education"
          expect(subject.items[1].link).to eq ""
          expect(subject.items[1].icon).to eq "fa-car"
        end
      end

      context "subnavs" do
        let(:driver_education_subnav) { subject.items[1].sub_nav }

        it "return the subnav items" do
          expect(driver_education_subnav[0].text).to eq "Purchase Course"
          expect(driver_education_subnav[0].link).to eq ""

          expect(driver_education_subnav[1].text).to eq "Admin Tasks"
          expect(driver_education_subnav[1].link).to eq ""
        end
      end
    end

    context "cashout" do
      context "main nav" do
        it "return the main nav items" do
          expect(subject.items[2].text).to eq "Cashout"
          expect(subject.items[2].link).to eq ""
          expect(subject.items[2].icon).to eq ""
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="com.baseframework.example.pojo.Student" alias="Student" />
    </typeAliases>
    <!--数据源配置  这块用 mysql数据库 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="jdbc" />
             <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://192.168.0.211:3306/ptest" />
                <property name="username" value="root" />
                <property name="password" value="reallove" />
            </dataSource>

             <!-- <dataSource type="com.baseframework.example.db.MyDataSource">
            </dataSource> -->
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/baseframework/example/mybatis/mapper/StudentMapper.xml" />
    </mappers>
</configuration>


text:
using System;

/*
 * This program is based on zlib-1.1.3, so all credit should go authors
 * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
 * and contributors of zlib.
 */

namespace Raksha.Utilities.Zlib {

    internal sealed class Inflate{

        private const int MAX_WBITS=15; // 32K LZ77 window

        // preset dictionary flag in zlib header
        private const int PRESET_DICT=0x20;

        internal const int Z_NO_FLUSH=0;
        internal const int Z_PARTIAL_FLUSH=1;
        internal const int Z_SYNC_FLUSH=2;
        internal const int Z_FULL_FLUSH=3;
        internal const int Z_FINISH=4;

        private const int Z_DEFLATED=8;

        private const int Z_OK=0;
        private const int Z_STREAM_END=1;
        private const int Z_NEED_DICT=2;
        private const int Z_ERRNO=-1;
        private const int Z_STREAM_ERROR=-2;
        private const int Z_DATA_ERROR=-3;
        private const int Z_MEM_ERROR=-4;
        private const int Z_BUF_ERROR=-5;
        private const int Z_VERSION_ERROR=-6;

        private const int METHOD=0;   // waiting for method byte
        private const int FLAG=1;     // waiting for flag byte
        private const int DICT4=2;    // four dictionary check bytes to go
        private const int DICT3=3;    // three dictionary check bytes to go
        private const int DICT2=4;    // two dictionary check bytes to go
        private const int DICT1=5;    // one dictionary check byte to go
        private const int DICT0=6;    // waiting for inflateSetDictionary
        private const int BLOCKS=7;   // decompressing blocks
        private const int CHECK4=8;   // four check bytes to go
        private const int CHECK3=9;   // three check bytes to go
        private const int CHECK2=10;  // two check bytes to go
        private const int CHECK1=11;  // one check byte to go
        private const int DONE=12;    // finished check, done
        private const int BAD=13;     // got an error--stay here

        internal int mode;                            // current inflate mode

        // mode dependent information
        internal int method;        // if FLAGS, method byte

        // if CHECK, check values to compare
        internal long[] was=new long[1] ; // computed check value
        internal long need;               // stream check value

        // if BAD, inflateSync's marker bytes count
        internal int marker;

        // mode independent information
        internal int  nowrap;          // flag for no wrapper
        internal int wbits;            // log2(window size)  (8..15, defaults to 15)

        internal InfBlocks blocks;     // current inflate_blocks state

        internal int inflateReset(ZStream z){
            if(z == null || z.istate == null) return Z_STREAM_ERROR;

            z.total_in = z.total_out = 0;
            z.msg = null;
            z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD;
            z.istate.blocks.reset(z, null);
            return Z_OK;
        }

        internal int inflateEnd(ZStream z){
            if(blocks != null)
                blocks.free(z);
            blocks=null;
            //    ZFREE(z, z->state);
            return Z_OK;
        }

        internal int inflateInit(ZStream z, int w){
            z.msg = null;
            blocks = null;

            // handle undocumented nowrap option (no zlib header or check)
            nowrap = 0;
            if(w < 0){
                w = - w;
                nowrap = 1;
            }

            // set window size
            if(w<8 ||w>15){
                inflateEnd(z);
                return Z_STREAM_ERROR;
            }
            wbits=w;

            z.istate.blocks=new InfBlocks(z,
                z.istate.nowrap!=0 ? null : this,
                1<<w);

            // reset state
            inflateReset(z);
            return Z_OK;
        }

        internal int inflate(ZStream z, int f){
            int r;
            int b;

            if(z == null || z.istate == null || z.next_in == null)
                return Z_STREAM_ERROR;
            f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
            r = Z_BUF_ERROR;
            while (true){
                //System.out.println("mode: "+z.istate.mode);
                switch (z.istate.mode){
                    case METHOD:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        if(((z.istate.method = z.next_in[z.next_in_index++])&0xf)!=Z_DEFLATED){
                            z.istate.mode = BAD;
                            z.msg="unknown compression method";
                            z.istate.marker = 5;       // can't try inflateSync
                            break;
                        }
                        if((z.istate.method>>4)+8>z.istate.wbits){
                            z.istate.mode = BAD;
                            z.msg="invalid window size";
                            z.istate.marker = 5;       // can't try inflateSync
                            break;
                        }
                        z.istate.mode=FLAG;
                        goto case FLAG;
                    case FLAG:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        b = (z.next_in[z.next_in_index++])&0xff;

                        if((((z.istate.method << 8)+b) % 31)!=0){
                            z.istate.mode = BAD;
                            z.msg = "incorrect header check";
                            z.istate.marker = 5;       // can't try inflateSync
                            break;
                        }

                        if((b&PRESET_DICT)==0){
                            z.istate.mode = BLOCKS;
                            break;
                        }
                        z.istate.mode = DICT4;
                        goto case DICT4;
                    case DICT4:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
                        z.istate.mode=DICT3;
                        goto case DICT3;
                    case DICT3:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
                        z.istate.mode=DICT2;
                        goto case DICT2;
                    case DICT2:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
                        z.istate.mode=DICT1;
                        goto case DICT1;
                    case DICT1:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need += (z.next_in[z.next_in_index++]&0xffL);
                        z.adler = z.istate.need;
                        z.istate.mode = DICT0;
                        return Z_NEED_DICT;
                    case DICT0:
                        z.istate.mode = BAD;
                        z.msg = "need dictionary";
                        z.istate.marker = 0;       // can try inflateSync
                        return Z_STREAM_ERROR;
                    case BLOCKS:

                        r = z.istate.blocks.proc(z, r);
                        if(r == Z_DATA_ERROR){
                            z.istate.mode = BAD;
                            z.istate.marker = 0;     // can try inflateSync
                            break;
                        }
                        if(r == Z_OK){
                            r = f;
                        }
                        if(r != Z_STREAM_END){
                            return r;
                        }
                        r = f;
                        z.istate.blocks.reset(z, z.istate.was);
                        if(z.istate.nowrap!=0){
                            z.istate.mode=DONE;
                            break;
                        }
                        z.istate.mode=CHECK4;
                        goto case CHECK4;
                    case CHECK4:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
                        z.istate.mode=CHECK3;
                        goto case CHECK3;
                    case CHECK3:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
                        z.istate.mode = CHECK2;
                        goto case CHECK2;
                    case CHECK2:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
                        z.istate.mode = CHECK1;
                        goto case CHECK1;
                    case CHECK1:

                        if(z.avail_in==0)return r;r=f;

                        z.avail_in--; z.total_in++;
                        z.istate.need+=(z.next_in[z.next_in_index++]&0xffL);

                        if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){
                            z.istate.mode = BAD;
                            z.msg = "incorrect data check";
                            z.istate.marker = 5;       // can't try inflateSync
                            break;
                        }

                        z.istate.mode = DONE;
                        goto case DONE;
                    case DONE:
                        return Z_STREAM_END;
                    case BAD:
                        return Z_DATA_ERROR;
                    default:
                        return Z_STREAM_ERROR;
                }
            }
        }

        internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){
            int index=0;
            int length = dictLength;
            if(z==null || z.istate == null|| z.istate.mode != DICT0)
                return Z_STREAM_ERROR;

            if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){
                return Z_DATA_ERROR;
            }

            z.adler = z._adler.adler32(0, null, 0, 0);

            if(length >= (1<<z.istate.wbits)){
                length = (1<<z.istate.wbits)-1;
                index=dictLength - length;
            }
            z.istate.blocks.set_dictionary(dictionary, index, length);
            z.istate.mode = BLOCKS;
            return Z_OK;
        }

        private static readonly byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff};

        internal int inflateSync(ZStream z){
            int n;       // number of bytes to look at
            int p;       // pointer to bytes
            int m;       // number of marker bytes found in a row
            long r, w;   // temporaries to save total_in and total_out

            // set up
            if(z == null || z.istate == null)
                return Z_STREAM_ERROR;
            if(z.istate.mode != BAD){
                z.istate.mode = BAD;
                z.istate.marker = 0;
            }
            if((n=z.avail_in)==0)
                return Z_BUF_ERROR;
            p=z.next_in_index;
            m=z.istate.marker;

            // search
            while (n!=0 && m < 4){
                if(z.next_in[p] == mark[m]){
                    m++;
                }
                else if(z.next_in[p]!=0){
                    m = 0;
                }
                else{
                    m = 4 - m;
                }
                p++; n--;
            }

            // restore
            z.total_in += p-z.next_in_index;
            z.next_in_index = p;
            z.avail_in = n;
            z.istate.marker = m;

            // return no joy or set up to restart on a new block
            if(m != 4){
                return Z_DATA_ERROR;
            }
            r=z.total_in;  w=z.total_out;
            inflateReset(z);
            z.total_in=r;  z.total_out = w;
            z.istate.mode = BLOCKS;
            return Z_OK;
        }

        // Returns true if inflate is currently at the end of a block generated
        // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
        // implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
        // but removes the length bytes of the resulting empty stored block. When
        // decompressing, PPP checks that at the end of input packet, inflate is
        // waiting for these length bytes.
        internal int inflateSyncPoint(ZStream z){
            if(z == null || z.istate == null || z.istate.blocks == null)
                return Z_STREAM_ERROR;
            return z.istate.blocks.sync_point();
        }
    }
}


text:
package org.hawkular.bus.sample.client;

import java.util.HashMap;

import org.hawkular.bus.common.BasicMessageWithExtraData;
import org.hawkular.bus.common.ConnectionContextFactory;
import org.hawkular.bus.common.Endpoint;
import org.hawkular.bus.common.MessageProcessor;
import org.hawkular.bus.common.consumer.BasicMessageListener;
import org.hawkular.bus.common.consumer.ConsumerConnectionContext;
import org.hawkular.bus.common.producer.ProducerConnectionContext;
import org.hawkular.bus.sample.msg.Address;
import org.hawkular.bus.sample.msg.Person;
import org.hawkular.bus.sample.msg.Person.Title;
import org.hawkular.bus.sample.msg.PhoneNumber;

/**
 * A simple sample client used to show the API needed to consume and produce messages.
 *
 * @author John Mazzitelli
 */
public class Main {
    private static final String BROKER_URL = "vm://mybroker?broker.persistent=false";
    private static final Endpoint ENDPOINT = new Endpoint(Endpoint.Type.QUEUE, "myqueue");

    public static void main(String[] args) throws Exception {

        try (Consumer consumer = new Consumer(); Producer producer = new Producer()) {
            consumer.consume();
            producer.produce();
            Thread.sleep(1000); // give some time for message to flow before shutting down
        }
    }

    private static class Consumer implements AutoCloseable {
        ConnectionContextFactory cachedFactory;

        public void consume() throws Exception {
            ConnectionContextFactory factory = new ConnectionContextFactory(BROKER_URL);
            ConsumerConnectionContext context = factory.createConsumerConnectionContext(ENDPOINT);
            BasicMessageListener<Person> listener = new BasicMessageListener<Person>() {
                @Override
                protected void onBasicMessage(BasicMessageWithExtraData<Person> personWithExtraData) {
                    Person person = personWithExtraData.getBasicMessage();
                    System.out.println("\n========== RECEIVED MESSAGE START ==========");
                    System.out.println("Consumed Person:");
                    System.out.printf(
                            "title=[%s], firstN=[%s], lastN=[%s], age=[%d], address.street=[%s], hobbies=[%s]\n",
                            person.getTitle(),
                            person.getFirstName(),
                            person.getLastName(),
                            person.getAge(),
                            person.getAddress().getStreet(),
                            person.getHobbies());
                    System.out.println("Consumed Person.toString: " + person.toString());
                    System.out.println("Consumed Person.toJSON: " + person.toJSON());
                    System.out.println("Consumed Person.hashCode: " + person.hashCode());
                    System.out.println("========== RECEIVED MESSAGE END ==========\n");
                }
            };
            MessageProcessor processor = new MessageProcessor();
            processor.listen(context, listener);

            // remember this so we can clean up after ourselves later
            this.cachedFactory = factory;
        }

        public void close() throws Exception {
            this.cachedFactory.close();
        }
    }

    private static class Producer implements AutoCloseable {
        ConnectionContextFactory cachedFactory;

        public void produce() throws Exception {
            ConnectionContextFactory factory = new ConnectionContextFactory(BROKER_URL);
            ProducerConnectionContext pc = factory.createProducerConnectionContext(ENDPOINT);
            Person person = new Person();
            person.setAge(18);
            person.setFirstName("John");
            person.setLastName("Doe");
            person.setTitle(Title.DR);
            person.getFavoriteColors().add("blue");
            person.getFavoriteColors().add("yellow");
            Address address = new Address();
            address.setStreet("Main Street");
            address.setCity("Anyplace, Kansas");
            person.setAddress(address);
            PhoneNumber phone1 = new PhoneNumber();
            phone1.setKind("home");
            phone1.setDigits("555-1212");
            PhoneNumber phone2 = new PhoneNumber();
            phone2.setKind("cell");
            phone2.setDigits("800-WOT-GORILLA");
            person.getPhoneNumbers().add(phone1);
            person.getPhoneNumbers().add(phone2);
            person.setHobbies(new HashMap<String, Number>(3));
            person.getHobbies().put("golf", 6);
            person.getHobbies().put("cooking", 3);
            person.getHobbies().put("tennis", 4);
            MessageProcessor processor = new MessageProcessor();
            processor.send(pc, person);

            // remember this so we can clean up after ourselves later
            this.cachedFactory = factory;
        }

        public void close() throws Exception {
            this.cachedFactory.close();
        }
    }
}


text:
require "rubygems"
require "bundler/setup"
require "newrelic_plugin"

module NewRelicOpenvpnAgent
  class Agent < NewRelic::Plugin::Agent::Base
    agent_guid "com.kangacoders.openvpn"
    agent_version "0.0.1"
    agent_config_options :openvpn_status_path
    agent_human_labels("OpenVPN Agent") { ident }

    attr_reader :ident

    def poll_cycle
      [:total_users, :total_clients, :total_bytes_received, :total_bytes_sent, :average_bytes_received, :average_bytes_sent].each do |_type|
        name, unit, _output = metric(_type)
        report_metric name, unit, _output.call
      end
    end

    private

    def get_columns(_output, _c_index, _uniq = true, _total = true)
      result = _output.scan(/^([^,]+),(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d+,(\d+),(\d+).+$/).map{|_x| _x[_c_index] }
      result = result.uniq if _uniq
      result = result.length if _total
      result
    end

    def metric(_type)
      metrics = {
        :total_users => ["Total/Users", "Users", lambda{get_columns(ovpn_cmd, 0) }],
        :total_clients => ["Total/Clients", "Clients", lambda{get_columns(ovpn_cmd, 1) }],
        :total_bytes_received => ["Total/Bytes/Received", "bytes", lambda{ get_columns(ovpn_cmd, 2, false, false).inject(0){|_t, _b| (_t + _b.to_i) } }],
        :total_bytes_sent => ["Total/Bytes/Sent", "bytes", lambda{ get_columns(ovpn_cmd, 3, false, false).inject(0){|_t, _b| (_t + _b.to_i) } }],
        :average_bytes_received => ["Average/Bytes/Received", "bytes", lambda{ x = get_columns(ovpn_cmd, 2, false, false); x.inject(0){|_t, _b| (_t + _b.to_i) } / x.length }],
        :average_bytes_sent => ["Average/Bytes/Sent", "bytes", lambda{ x = get_columns(ovpn_cmd, 3, false, false); x.inject(0){|_t, _b| (_t + _b.to_i) } / x.length }]
      }
      metrics[_type]
    end

    def ovpn_cmd
      `cat #{openvpn_status_path}`
    end

  end

  def self.run
    NewRelic::Plugin::Config.config.agents.keys.each do |_agent|
      NewRelic::Plugin::Setup.install_agent _agent, NewRelicOpenvpnAgent
    end

    NewRelic::Plugin::Run.setup_and_run
  end
end


text:
/* See license.txt for terms of usage */

/**********************************************
Description: This file includes all the CSS
  variables used across firebug theme.

Usage: @import url("firebug-style-variables.css");

**********************************************/

:root {
  --theme-body-background: #fcfcfc;
  --theme-sidebar-background: #f7f7f7;
  --theme-contrast-background: #e6b064;

  --theme-tab-toolbar-background: #ebeced;
  --theme-toolbar-background: #f0f1f2;
  --theme-selection-background: #4c9ed9;
  --theme-selection-color: #f5f7fa;
  --theme-selection-background-semitransparent: rgba(76, 158, 217, .23);
  --theme-splitter-color: #aaaaaa;
  --theme-comment: hsl(90,2%,46%);

  --theme-body-color: #18191a;
  --theme-body-color-alt: #585959;
  --theme-content-color1: #292e33;
  --theme-content-color2: #8fa1b2;
  --theme-content-color3: #667380;

  --theme-highlight-green: hsl(72,100%,27%);
  --theme-highlight-blue: hsl(208,56%,40%);
  --theme-highlight-bluegrey: hsl(208,81%,21%);
  --theme-highlight-purple: #5b5fff;
  --theme-highlight-lightorange: #a18650;
  --theme-highlight-orange: hsl(24,85%,39%);
  --theme-highlight-red: #bf5656;
  --theme-highlight-pink: #b82ee5;

  --theme-firebug-object: #006400; /*Green*/
  --theme-firebug-string: #FF183C; /*Red*/
}


text:
require 'spec_helper.rb'
require 'smallcage'

describe "SmallCage::Commands::Export" do
  docroot = Pathname.new(File.join(SPEC_DATA_DIR, 'htdocs2'))
  outdir = Pathname.new(File.join(SPEC_DATA_DIR, 'out'))

  it "should export not smc files" do
    begin
      opts = { :command => "export",
               :path => docroot.to_s,
               :out => outdir.to_s,
               :quiet => true }
      SmallCage::Runner.run(opts)

      (outdir + "./a/test.html.smc").exist?.should be false
      (outdir + "./a/test.html").exist?.should be false
      (outdir + "./a/b/test.html").exist?.should be true
      (outdir + "./a/b/c/test.html").exist?.should be true
    ensure
      FileUtils.rm_r(outdir)
    end
  end

  it "should export project subdirectory" do
    begin
      path = docroot + "a/b/c"
      opts = { :command => "export",
               :path => path.to_s,
               :out => outdir.to_s,
               :quiet => true }
      SmallCage::Runner.run(opts)

      (outdir + "./a/test.html.smc").exist?.should be false
      (outdir + "./a/test.html").exist?.should be false
      (outdir + "./a/b/test.html").exist?.should be false

      (outdir + "./a/b/c/test.html").exist?.should be true
    ensure
      FileUtils.rm_r(outdir)
    end
  end
end


text:
require_relative "test_helper"

class QueryTest < Minitest::Test
  def test_basic
    store_names ["Milk", "Apple"]
    query = Product.search("milk", execute: false)
    # query.body = {query: {match_all: {}}}
    # query.body = {query: {match: {name: "Apple"}}}
    query.body[:query] = {match_all: {}}
    assert_equal ["Apple", "Milk"], query.map(&:name).sort
    assert_equal ["Apple", "Milk"], query.execute.map(&:name).sort
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Crocicreas giganteum Mont.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>group-id</groupId>
        <artifactId>parent-artifact-id</artifactId>
        <version>1.0</version>
    </parent>
    <groupId>group-id</groupId>
    <artifactId>child-artifact-id-2</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
</project>


text:
package com.microsoft.filediscovery.adapters;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.microsoft.assetmanagement.R;
import com.microsoft.filediscovery.viewmodel.ServiceViewItem;

// TODO: Auto-generated Javadoc
/**
 * The Class ServiceItemAdapter.
 */
public class ServiceItemAdapter extends BaseAdapter {

	/** The m activity. */
	private Activity mActivity;

	/** The m data. */
	private List<ServiceViewItem> mData;

	/** The inflater. */
	private static LayoutInflater inflater = null;

	/**
	 * Instantiates a new car item adapter.
	 *
	 * @param activity
	 *            the activity
	 * @param data
	 *            the data
	 */
	public ServiceItemAdapter(Activity activity, List<ServiceViewItem> data) {
		mActivity = activity;
		mData = data;
		inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.widget.Adapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (convertView == null)
			view = inflater.inflate(R.layout.activity_service_list_item, null);

		TextView serviceName = (TextView) view.findViewById(R.id.serviceName);
		TextView resourceId = (TextView) view.findViewById(R.id.resourceId);
		TextView capability = (TextView) view.findViewById(R.id.capability);

		ServiceViewItem item = mData.get(position);
		serviceName.setText(item.getName());
		resourceId.setText(item.getResourceId());
		capability.setText(item.getCapability());

		if (!item.getSelectable()) {
			view.findViewById(R.id.arrow).setVisibility(View.INVISIBLE);
		} else {
			view.findViewById(R.id.arrow).setVisibility(View.VISIBLE);
		}

		return view;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return mData.size();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Object getItem(int position) {
		return mData.get(position);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		return position;
	}
}


text:
package org.hocdoc.sandoc.processor

import java.io.OutputStream
import org.hocdoc.sandoc.OutputContentType
import org.apache.fop.apps.FopFactory
import org.apache.xmlgraphics.util.MimeConstants
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamSource
import java.io.StringReader
import java.io.File
import javax.xml.transform.sax.SAXResult
import java.net.URL
import grizzled.slf4j.Logging

abstract class MarkupProcessor extends Logging {

  protected val imagePath = "/xsl/docbook/images/"
  protected val calloutImagePath = imagePath + "callouts/"

  protected lazy val fopFactory = FopFactory.newInstance

  def render(inputText: String, outputContentType: OutputContentType.Value,
             stream: OutputStream, xsltPath: String): Unit

  /** Renders a DocBook as PDF with Apache FOP. */
  protected def docBookToPdf(docbookXml: String, stream: OutputStream, xsltPath: String): Unit = {
    val startTime = System.currentTimeMillis
    val fop = fopFactory.newFop(MimeConstants.MIME_PDF, stream)
    val transformerFactory = TransformerFactory.newInstance
    val xslt = new StreamSource(new File(xsltPath));

    val transformer = transformerFactory.newTransformer(xslt);
    transformer.setParameter("use.extensions", "1")
    transformer.setParameter("fop.extensions", "0")
    transformer.setParameter("fop1.extensions", "1")         // generate bookmark tree
    transformer.setParameter("admon.graphics", "1")
    transformer.setParameter("admon.graphics.path", resourceURL(imagePath))
    transformer.setParameter("admon.graphics.extension", ".svg")
    transformer.setParameter("callout.graphics.path", resourceURL(calloutImagePath))

    val src = new StreamSource(new StringReader(docbookXml))
    val result = new SAXResult(fop.getDefaultHandler)
    transformer.transform(src, result)

    val endTime = System.currentTimeMillis
    logger.info("FOP Time: " + (endTime - startTime))
  }

  /** Absolute URL of a file resource. */
  private def resourceURL(name: String): URL =
    getClass.getResource(name)

}


text:
package teststorage

import (
	"errors"

	"github.com/RangelReale/osin"
)

type Test struct {
	Clients       map[string]osin.Client
	AuthorizeData *osin.AuthorizeData
	Authorize     map[string]*osin.AuthorizeData
	AccessData    *osin.AccessData
	Access        map[string]*osin.AccessData
	Err           error
}

func New() *Test {
	return &Test{
		Clients:   make(map[string]osin.Client),
		Authorize: make(map[string]*osin.AuthorizeData),
		Access:    make(map[string]*osin.AccessData),
	}
}

func (t *Test) Clone() osin.Storage {
	return t
}

func (t *Test) Close() {
}

// GetClient loads the client by id (client_id)
func (t *Test) GetClient(id string) (osin.Client, error) {
	return t.Clients[id], t.Err
}

// SaveAuthorize saves authorize data.
func (t *Test) SaveAuthorize(data *osin.AuthorizeData) error {
	t.AuthorizeData = data
	t.Authorize[data.Code] = data
	return t.Err
}

// LoadAuthorize looks up AuthorizeData by a code.
// Client information MUST be loaded together.
// Optionally can return error if expired.
func (t *Test) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
	return t.Authorize[code], t.Err
}

// RemoveAuthorize revokes or deletes the authorization code.
func (t *Test) RemoveAuthorize(code string) error {
	delete(t.Authorize, code)
	return t.Err
}

// SaveAccess writes AccessData.
// If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.
func (t *Test) SaveAccess(data *osin.AccessData) error {
	t.AccessData = data
	t.Access[data.AccessToken] = data
	return t.Err
}

// LoadAccess retrieves access data by token. Client information MUST be loaded together.
// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (t *Test) LoadAccess(token string) (*osin.AccessData, error) {
	return t.Access[token], t.Err
}

// RemoveAccess revokes or deletes an AccessData.
func (t *Test) RemoveAccess(token string) error {
	delete(t.Access, token)
	return t.Err
}

// LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together.
// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (t *Test) LoadRefresh(token string) (*osin.AccessData, error) {
	for _, v := range t.Access {
		if v.RefreshToken == token {
			return v, t.Err
		}
	}
	return nil, errors.New("not found")
}

// RemoveRefresh revokes or deletes refresh AccessData.
func (t *Test) RemoveRefresh(token string) error {
	data, _ := t.LoadRefresh(token)
	if data != nil {
		delete(t.Access, data.AccessToken)
	}
	return t.Err
}


text:
<!DOCTYPE html>

    <title th:text="#{home.sideTitle}"></title>

    <link rel="stylesheet" th:href="@{/css/home.css}"/>

 <button id="showItemTreeBtn" th:text="#{home.treeBtn}" type="button" class="btn btn-primary">Alle anzeigen</button>


text:
using System;
using System.Data;
using System.Linq;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

using Rebus.Logging;
using Rebus.Serialization;
using Rebus.Serialization.Json;
using Rebus.AdoNet.Schema;
using Rebus.AdoNet.Dialects;

namespace Rebus.AdoNet
{
	/// <summary>
	/// Implements a saga persister for Rebus that stores sagas using an AdoNet provider.
	/// </summary>
	public abstract class AdoNetSagaPersister : IStoreSagaData, AdoNetSagaPersisterFluentConfigurer, ICanUpdateMultipleSagaDatasAtomically
	{
		private const int MaximumSagaDataTypeNameLength = 80;
		private static ILog log;
		private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings {
			TypeNameHandling = TypeNameHandling.All, // TODO: Make it configurable by adding a SagaTypeResolver feature.
			DateFormatHandling = DateFormatHandling.IsoDateFormat, // TODO: Make it configurable..
			Binder = new CustomSerializationBinder()
		};

		private readonly AdoNetUnitOfWorkManager manager;
		private readonly string idPropertyName;
		private Func<Type, string> sagaNameCustomizer;

		protected bool IndexNullProperties { get; private set; } = true;
		protected bool UseSqlArrays { get; private set; }
		protected bool UseSagaLocking { get; private set; }
		protected bool UseNoWaitSagaLocking { get; private set; }

		protected AdoNetUnitOfWorkManager Manager => manager;

		static AdoNetSagaPersister()
		{
			RebusLoggerFactory.Changed += f => log = f.GetCurrentClassLogger();
		}

		/// <summary>
		/// Constructs the persister with the ability to create connections to database using the specified connection string.
		/// This also means that the persister will manage the connection by itself, closing it when it has stopped using it.
		/// </summary>
		public AdoNetSagaPersister(AdoNetUnitOfWorkManager manager)
		{
			this.manager = manager;
			this.idPropertyName = Reflect.Path<ISagaData>(x => x.Id);
		}

		#region AdoNetSagaPersisterFluentConfigurer

		/// <summary>
		/// Configures the persister to ignore null-valued correlation properties and not add them to the saga index.
		/// </summary>
		public AdoNetSagaPersisterFluentConfigurer DoNotIndexNullProperties()
		{
			IndexNullProperties = false;
			return this;
		}

		public AdoNetSagaPersisterFluentConfigurer UseLockingOnSagaUpdates(bool waitForLocks)
		{
			UseSagaLocking = true;
			UseNoWaitSagaLocking = !waitForLocks;
			return this;
		}

		/// <summary>
		/// Creates the necessary saga storage tables if they haven't already been created. If a table already exists
		/// with a name that matches one of the desired table names, no action is performed (i.e. it is assumed that
		/// the tables already exist).
		/// </summary>
		public virtual AdoNetSagaPersisterFluentConfigurer EnsureTablesAreCreated()
		{
			throw new NotImplementedException("Creation of Saga tables not implemented.");
		}

		/// <summary>
		/// Customizes the saga names by invoking this customizer.
		/// </summary>
		/// <param name="customizer">The customizer.</param>
		/// <returns></returns>
		public AdoNetSagaPersisterFluentConfigurer CustomizeSagaNamesAs(Func<Type, string> customizer)
		{
			this.sagaNameCustomizer = customizer;
			return this;
		}

		/// <summary>
		/// Enables locking of sagas as to avoid two or more workers to update them concurrently.
		/// </summary>
		/// <returns>The saga locking.</returns>
		public AdoNetSagaPersisterFluentConfigurer EnableSagaLocking()
		{
			UseSagaLocking = true;
			return this;
		}

		/// <summary>
		/// Uses the use of sql array types for storing indexes related to correlation properties.
		/// </summary>
		/// <returns>The sql arrays.</returns>
		public AdoNetSagaPersisterFluentConfigurer UseSqlArraysForCorrelationIndexes()
		{
			UseSqlArrays = true;
			return this;
		}

		/// <summary>
		/// Allows customizing opened connections by passing a delegate/lambda to invoke for each new connection.
		/// </summary>
		/// <param name="customizer"></param>
		/// <returns></returns>
		public AdoNetSagaPersisterFluentConfigurer CustomizeOpenedConnections(Action<IDbConnection> customizer)
		{
			manager.ConnectionFactory.ConnectionCustomizer = customizer;
			return this;
		}

		/// <summary>
		/// Customizes type2name & name2type mapping logic used during serialization/deserialization.
		/// </summary>
		/// <param name="nameToTypeResolver">Delegate to invoke when resolving a name-to-type during deserialization.</param>
		/// <param name="typeToNameResolver">Delegate to invoke when resolving a type-to-name during serialization.</param>
		/// <returns></returns>
		public AdoNetSagaPersisterFluentConfigurer CustomizeSerializationTypeResolving(Func<TypeDescriptor, Type> nameToTypeResolver, Func<Type, TypeDescriptor> typeToNameResolver)
		{
			(Settings.Binder as CustomSerializationBinder).NameToTypeResolver = nameToTypeResolver;
			(Settings.Binder as CustomSerializationBinder).TypeToNameResolver = typeToNameResolver;
			return this;
		}

		#endregion

		#region Saga TypeName mangling

		private static string GetClassName(Type type)
		{
			var classNameRegex = new Regex("^[a-zA-Z0-9_]*[\\w]", RegexOptions.IgnoreCase);
			var match = classNameRegex.Match(type.Name);

			if (!match.Success) throw new Exception($"Error trying extract name class from type: {type.Name}");

			return match.Value;
		}

		private static IEnumerable<string> GetGenericArguments(Type type)
		{
			return type.GetGenericArguments()
				.Select(x => x.Name)
				.ToList();
		}

		private static string GetDefaultSagaName(Type type)
		{
			var declaringType = type.DeclaringType;

			if (type.IsNested && declaringType != null)
			{
				if (declaringType.IsGenericType)
				{
					var className = GetClassName(declaringType);
					var genericArguments = GetGenericArguments(type).ToList();

					return genericArguments.Any()
						? $"{className}<{string.Join(",", genericArguments)}>"
						: $"{className}";
				}

				return declaringType.Name;
			}

			return type.Name;
		}

		protected string GetSagaTypeName(Type sagaDataType)
		{
			var sagaTypeName = sagaNameCustomizer != null ? sagaNameCustomizer(sagaDataType) : GetDefaultSagaName(sagaDataType);

			if (sagaTypeName.Length > MaximumSagaDataTypeNameLength)
			{
				throw new InvalidOperationException(
					string.Format(
						@"Sorry, but the maximum length of the name of a saga data class is currently limited to {0} characters!

This is due to a limitation in SQL Server, where compound indexes have a 900 byte upper size limit - and
since the saga index needs to be able to efficiently query by saga type, key, and value at the same time,
there's room for only 200 characters as the key, 200 characters as the value, and 80 characters as the
saga type name.",
						MaximumSagaDataTypeNameLength));
			}

			return sagaTypeName;
		}

		#endregion

		protected string Serialize(ISagaData sagaData)
		{
			return JsonConvert.SerializeObject(sagaData, Formatting.Indented, Settings);
		}

		public abstract void Insert(ISagaData sagaData, string[] sagaDataPropertyPathsToIndex);

		public abstract void Update(ISagaData sagaData, string[] sagaDataPropertyPathsToIndex);

		public abstract void Delete(ISagaData sagaData);

		protected abstract string Fetch<TSagaData>(string sagaDataPropertyPath, object fieldFromMessage)
			where TSagaData : class, ISagaData;

		public TSagaData Find<TSagaData>(string sagaDataPropertyPath, object fieldFromMessage)
			where TSagaData : class, ISagaData
		{
			var sagaType = GetSagaTypeName(typeof(TSagaData));

			log.Debug("Finding saga of type {0} with {1} = {2}", sagaType, sagaDataPropertyPath, fieldFromMessage);

			var data = Fetch<TSagaData>(sagaDataPropertyPath, fieldFromMessage);

			if (data == null)
			{
				log.Debug("No saga found of type {0} with {1} = {2}", sagaType, sagaDataPropertyPath, fieldFromMessage);
				return null;
			}

			log.Debug("Found saga of type {0} with {1} = {2}", sagaType, sagaDataPropertyPath, fieldFromMessage);

			try
			{
				return JsonConvert.DeserializeObject<TSagaData>(data, Settings);
			}
			catch { }

			try
			{
				return (TSagaData)JsonConvert.DeserializeObject(data, Settings);
			}
			catch (Exception exception)
			{
				var message = string.Format("An error occurred while attempting to deserialize '{0}' into a {1}", data,
					typeof(TSagaData));

				throw new ApplicationException(message, exception);
			}
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Task1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}