text:
/*!
 * \file arg_binder.cc
 * \brief Helper utility to match and bind arguments.
 */
#include "arg_binder.h"

#include <tvm/runtime/device_api.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/op.h>

#include "ir_utils.h"

namespace tvm {
namespace tir {

void BinderAddAssert(arith::Analyzer* ana, PrimExpr cond, const std::string& arg_name,
                     std::vector<Stmt>* asserts) {
  PrimExpr scond = ana->Simplify(cond);
  if (is_zero(scond)) {
    LOG(FATAL) << "Bind have an unmet assertion: " << cond << ", "
               << " on argument " << arg_name;
  }
  if (!is_one(scond)) {
    std::ostringstream os;
    os << "Argument " << arg_name << " has an unsatisfied constraint: " << cond;
    asserts->emplace_back(AssertStmt(scond, tvm::tir::StringImm(os.str()), Evaluate(0)));
  }
}

bool ArgBinder::Bind_(const PrimExpr& arg, const PrimExpr& value, const std::string& arg_name,
                      bool with_lets) {
  ICHECK_EQ(arg.dtype(), value.dtype());
  if (const VarNode* v = arg.as<VarNode>()) {
    auto it = def_map_->find(v);
    if (it == def_map_->end()) {
      Var v_arg = Downcast<Var>(arg);
      defs_.emplace_back(v_arg);
      if (with_lets) {
        (*def_map_)[v] = arg;
        init_nest_.emplace_back(LetStmt(v_arg, value, Evaluate(0)));
      } else {
        (*def_map_)[v] = value;
      }
      return true;
    } else {
      BinderAddAssert(&analyzer_, it->second == value, arg_name, &asserts_);
    }
  } else {
    BinderAddAssert(&analyzer_, arg == value, arg_name, &asserts_);
  }
  return false;
}

void ArgBinder::Bind(const PrimExpr& arg, const PrimExpr& value, const std::string& arg_name,
                     bool with_let) {
  Bind_(arg, value, arg_name, with_let);
}

void ArgBinder::BindArray(const Array<PrimExpr>& arg, const Array<PrimExpr>& value,
                          const std::string& arg_name) {
  ICHECK_EQ(arg.size(), value.size()) << "Argument " << arg_name << " array size mismatch";
  for (size_t i = 0; i < arg.size(); ++i) {
    std::ostringstream os;
    os << arg_name << "[" << i << "]";
    this->Bind(arg[i], value[i], os.str());
  }
}

void ArgBinder::BindBuffer(const Buffer& arg, const Buffer& value, const std::string& arg_name,
                           bool fuzzy_match) {
  ICHECK_EQ(arg.scope(), value.scope()) << "Argument " << arg_name << " Buffer bind scope mismatch";
  ICHECK_EQ(arg->dtype, value->dtype)
      << "Argument " << arg_name << " Buffer bind data type mismatch";
  if (value->data_alignment % arg->data_alignment != 0) {
    LOG(WARNING) << "Trying to bind buffer to another one with lower alignment requirement "
                 << " required_alignment=" << arg->data_alignment
                 << ", provided_alignment=" << value->data_alignment;
  }
  // bind pointer and offset.
  if (is_zero(arg->elem_offset)) {
    ICHECK(is_zero(value->elem_offset))
        << "Trying to bind a Buffer with offset into one without offset "
        << " required elem_offset=" << arg->elem_offset
        << ", provided elem_offset=" << value->elem_offset;
  }

  this->Bind(arg->data, value->data, arg_name + ".data");
  if (Bind_(arg->elem_offset, value->elem_offset, arg_name + ".elem_offset", false)) {
    if (arg->offset_factor > 1) {
      PrimExpr offset = value->elem_offset;
      PrimExpr factor = make_const(offset.dtype(), arg->offset_factor);
      PrimExpr zero = make_zero(offset.dtype());
      BinderAddAssert(&analyzer_, truncmod(offset, factor) == zero, arg_name + ".elem_offset",
                      &asserts_);
    }
  }

  if (arg->shape.size() < value->shape.size()) {
    ICHECK(fuzzy_match) << "Argument " << arg_name << " size mismatch";
    size_t diff = value->shape.size() - arg->shape.size();
    for (size_t i = 0; i < diff; ++i) {
      ICHECK(is_one(analyzer_.Simplify(value->shape[i])))
          << "Argument " << arg_name << " shape mismatch" << arg->shape << " vs " << value->shape;
    }
    for (size_t i = 0; i < arg->shape.size(); ++i) {
      std::ostringstream os;
      os << arg_name << ".shape[" << i << "]";
      this->Bind(arg->shape[i], value->shape[i + diff], os.str());
    }
    if (value->strides.size() != 0) {
      ICHECK_EQ(arg->strides.size(), arg->shape.size());
      ICHECK_EQ(value->strides.size(), value->shape.size());
      for (size_t i = 0; i < arg->strides.size(); ++i) {
        std::ostringstream os;
        os << arg_name << ".strides[" << i << "]";
        this->Bind(arg->strides[i], value->strides[i + diff], os.str());
      }
    }
  } else {
    this->BindArray(arg->shape, value->shape, arg_name + ".shape");
    this->BindArray(arg->strides, value->strides, arg_name + ".strides");
  }
}

inline PrimExpr TVMArrayGet(DataType t, Var arr, builtin::TVMStructFieldKind kind) {
  return TVMStructGet(t, arr, 0, kind);
}

void ArgBinder::BindDLTensor(const Buffer& buffer, const PrimExpr& device_type,
                             const PrimExpr& device_id, const Var& handle,
                             const std::string& arg_name) {
  const DataType tvm_shape_type = DataType::ShapeIndex();
  const DataType tvm_ndim_type = DataType::Int(32);
  const Stmt nop = Evaluate(0);
  // dimension checks
  PrimExpr v_ndim = TVMArrayGet(tvm_ndim_type, handle, builtin::kArrNDim);
  PrimExpr a_ndim = make_const(tvm_ndim_type, static_cast<int64_t>(buffer->shape.size()));
  std::ostringstream ndim_err_msg;
  ndim_err_msg << arg_name << ".ndim is expected to equal " << buffer->shape.size();
  auto msg = tvm::tir::StringImm(ndim_err_msg.str());
  asserts_.emplace_back(AssertStmt(a_ndim == v_ndim, msg, nop));
  // type checks
  DataType dtype = buffer->dtype;
  std::ostringstream type_err_msg;
  type_err_msg << arg_name << ".dtype is expected to be " << dtype;
  PrimExpr cond = (TVMArrayGet(DataType::UInt(8), handle, builtin::kArrTypeCode) ==
                       IntImm(DataType::UInt(8), dtype.code()) &&
                   TVMArrayGet(DataType::UInt(8), handle, builtin::kArrTypeBits) ==
                       IntImm(DataType::UInt(8), dtype.bits()) &&
                   TVMArrayGet(DataType::UInt(16), handle, builtin::kArrTypeLanes) ==
                       IntImm(DataType::UInt(16), dtype.lanes()));
  if (!(dtype == DataType::Int(4) || dtype == DataType::UInt(4) || dtype == DataType::Int(1))) {
    auto type_msg = tvm::tir::StringImm(type_err_msg.str());
    asserts_.emplace_back(AssertStmt(a_ndim == v_ndim, msg, nop));
    asserts_.emplace_back(AssertStmt(cond, type_msg, nop));
  }
  // data field
  if (Bind_(buffer->data, TVMArrayGet(DataType::Handle(), handle, builtin::kArrData),
            arg_name + ".data", true)) {
    Var vptr(buffer->data);
    def_handle_dtype_.Set(vptr, tir::TypeAnnotation(buffer->dtype));
    // mark alignment of external bufs
    init_nest_.emplace_back(AttrStmt(vptr, tir::attr::storage_alignment,
                                     IntImm(DataType::Int(32), buffer->data_alignment), nop));
  }

  Var v_shape(arg_name + ".shape", DataType::Handle());
  def_handle_dtype_.Set(v_shape, make_const(tvm_shape_type, 0));
  init_nest_.emplace_back(
      LetStmt(v_shape, TVMArrayGet(DataType::Handle(), handle, builtin::kArrShape), nop));
  for (size_t k = 0; k < buffer->shape.size(); ++k) {
    if (dtype == DataType::Int(4) || dtype == DataType::UInt(4) || dtype == DataType::Int(1)) {
      break;
    }
    std::ostringstream field_name;
    field_name << v_shape->name_hint << '[' << k << ']';
    Bind_(buffer->shape[k],
          cast(buffer->shape[k].dtype(),
               Load(tvm_shape_type, v_shape, IntImm(DataType::Int(32), k), const_true(1))),
          field_name.str(), true);
  }
  // strides field
  Var v_strides(arg_name + ".strides", DataType::Handle());
  def_handle_dtype_.Set(v_strides, tir::TypeAnnotation(tvm_shape_type));
  init_nest_.emplace_back(
      LetStmt(v_strides, TVMArrayGet(DataType::Handle(), handle, builtin::kArrStrides), nop));
  PrimExpr v_strides_is_null = Call(DataType::Bool(1), builtin::isnullptr(), {v_strides});
  if (buffer->strides.size() == 0) {
    // Assert the buffer is compact
    DataType stype = buffer->DefaultIndexType();
    PrimExpr expect_stride = make_const(stype, 1);
    Array<PrimExpr> conds;
    for (size_t i = buffer->shape.size(); i != 0; --i) {
      size_t k = i - 1;
      PrimExpr svalue =
          cast(stype, Load(tvm_shape_type, v_strides, IntImm(DataType::Int(32), k), const_true(1)));
      conds.push_back(expect_stride == svalue);
      expect_stride = expect_stride * buffer->shape[k];
    }
    std::ostringstream stride_err_msg;
    stride_err_msg << arg_name << ".strides:"
                   << " expected to be compact array";
    if (conds.size() != 0) {
      auto stride_msg = tvm::tir::StringImm(stride_err_msg.str());
      Stmt check = AssertStmt(
          foldl([](PrimExpr a, PrimExpr b, Span span) { return logical_and(a, b, span); },
                const_true(1), conds),
          stride_msg, Evaluate(0));
      check = IfThenElse(Not(v_strides_is_null), check, Stmt());
      asserts_.emplace_back(SeqStmt({check, Evaluate(0)}));
    }
  } else if (buffer->buffer_type == kAutoBroadcast) {
    DataType stype = buffer->DefaultIndexType();
    PrimExpr stride = make_const(stype, 1);
    for (size_t i = buffer->shape.size(); i != 0; --i) {
      size_t k = i - 1;
      std::ostringstream field_name;
      field_name << v_strides->name_hint << '[' << k << ']';
      PrimExpr value =
          cast(buffer->shape[k].dtype(),
               Load(tvm_shape_type, v_strides, IntImm(DataType::Int(32), k), const_true(1)));
      value = tvm::if_then_else(v_strides_is_null, stride, value);
      value = tvm::if_then_else(buffer->shape[k] == 1, 0, value);
      Bind_(buffer->strides[k], value, field_name.str(), true);
      stride = analyzer_.Simplify(stride * buffer->shape[k]);
    }
  } else {
    PrimExpr stride_from_shape = 1;

    for (int k = buffer->strides.size() - 1; k >= 0; k--) {
      std::ostringstream field_name;
      field_name << v_strides->name_hint << '[' << k << ']';

      PrimExpr explicit_stride =
          cast(buffer->shape[k].dtype(),
               Load(tvm_shape_type, v_strides, IntImm(DataType::Int(32), k), const_true(1)));

      Bind_(buffer->strides[k],
            tvm::if_then_else(v_strides_is_null, stride_from_shape, explicit_stride),
            field_name.str(), true);

      stride_from_shape *=
          cast(buffer->shape[k].dtype(),
               Load(tvm_shape_type, v_shape, IntImm(DataType::Int(32), k), const_true(1)));
    }
  }
  // Byte_offset field.
  int data_bytes = GetVectorBytes(buffer->dtype);

  if (const auto* const_offset = buffer->elem_offset.as<IntImmNode>()) {
    Bind_(make_const(DataType::UInt(64), const_offset->value * data_bytes),
          TVMArrayGet(DataType::UInt(64), handle, builtin::kArrByteOffset),
          arg_name + ".byte_offset", true);
  } else {
    if (Bind_(buffer->elem_offset,
              cast(buffer->elem_offset.dtype(),
                   (TVMArrayGet(DataType::UInt(64), handle, builtin::kArrByteOffset) /
                    make_const(DataType::UInt(64), data_bytes))),
              arg_name + ".elem_offset", true)) {
      if (buffer->offset_factor > 1) {
        PrimExpr offset = buffer->elem_offset;
        PrimExpr factor = make_const(offset.dtype(), buffer->offset_factor);
        PrimExpr zero = make_zero(offset.dtype());
        BinderAddAssert(&analyzer_, truncmod(offset, factor) == zero, arg_name + ".elem_offset",
                        &asserts_);
      }
    }
  }
  // device info.
  Bind_(device_type, TVMArrayGet(DataType::Int(32), handle, builtin::kArrDeviceType),
        arg_name + ".device_type", true);
  Bind_(device_id, TVMArrayGet(DataType::Int(32), handle, builtin::kArrDeviceId),
        arg_name + ".device_id", true);
}

}  // namespace tir
}  // namespace tvm


text:
  struct name##__;                       \
  typedef struct name##__* name;
#include "base/win/win_handle_types_list.inc"
#undef CHROME_WINDOWS_HANDLE_TYPE

#endif  // BASE_WIN_WIN_HANDLE_TYPES_H_

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-}

module Client (httpGet, httpPost) where

import Control.Monad
import Data.Maybe

import HttpTypes
import Data.HandleLike

import qualified Data.ByteString as BS

httpGet :: HandleLike h => h -> HandleMonad h BS.ByteString
httpGet sv = do
	hlPutStrLn sv request
	src <- hGetHeader sv
	let res = parseResponse src
	cnt <- hlGet sv (contentLength $ responseContentLength res)
	let res' = res { responseBody = cnt }
	mapM_ (hlDebug sv "critical" . (`BS.append` "\n"))
		. catMaybes $ showResponse res'
	return cnt

httpPost :: HandleLike h => h -> BS.ByteString -> HandleMonad h BS.ByteString
httpPost sv cnt = do
	hlPutStrLn sv . requestToString $ post cnt
	res <- parseResponse `liftM` hGetHeader sv
	cnt' <- hlGet sv (contentLength $ responseContentLength res)
	let res' = res { responseBody = cnt' }
	hlDebug sv "critical" . (`BS.append` "\n") $ responseToString res'
	return cnt'

hGetHeader :: HandleLike h => h -> HandleMonad h [BS.ByteString]
hGetHeader h = do
	l <- hlGetLine h
	if (BS.null l) then return [] else (l :) `liftM` hGetHeader h

crlf :: [BS.ByteString] -> BS.ByteString
crlf = BS.concat . map (+++ "\r\n")

request :: BS.ByteString
request = crlf . catMaybes . showRequest . RequestGet (Uri "/") (Version 1 1) $
	Get {
		getHost = Just . Host "localhost" $ Just 8080,
		getUserAgent = Just [Product "Mozilla" (Just "5.0")],
		getAccept = Just [Accept ("text", "plain") (Qvalue 1.0)],
		getAcceptLanguage = Just [AcceptLanguage "ja" (Qvalue 1.0)],
		getAcceptEncoding = Just [],
		getConnection = Just [Connection "close"],
		getCacheControl = Just [MaxAge 0],
		getOthers = []
	 }

requestToString :: Request -> BS.ByteString
requestToString = crlf . catMaybes . showRequest

responseToString :: Response -> BS.ByteString
responseToString = crlf . catMaybes . showResponse

post :: BS.ByteString -> Request
post cnt = RequestPost (Uri "/") (Version 1 1) $
	Post {
		postHost = Just . Host "localhost" $ Just 8080,
		postUserAgent = Just [Product "Mozilla" (Just "5.0")],
		postAccept = Just [Accept ("text", "plain") (Qvalue 1.0)],
		postAcceptLanguage = Just [AcceptLanguage "ja" (Qvalue 1.0)],
		postAcceptEncoding = Just [],
		postConnection = Just [Connection "close"],
		postCacheControl = Just [MaxAge 0],
		postContentType = Just $ ContentType ("text", "plain"),
		postContentLength = Just . ContentLength $ BS.length cnt,
		postOthers = [],
		postBody = cnt
	 }


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

using NUnit.Framework;

using Criteo.Memcache.Locator;
using Criteo.Memcache.Node;
using Criteo.Memcache.UTest.Mocks;

namespace Criteo.Memcache.UTest.Tests
{
    [TestFixture]
    public class LocatorTests
    {
        private IList<IMemcacheNode> _nodes;

        [TestFixtureSetUp]
        public void Setup()
        {
            _nodes = new List<IMemcacheNode>
            {
                new NodeMock {EndPoint = new IPEndPoint(new IPAddress(new byte[] {192, 168, 18, 1}), 11211)},
                new NodeMock {EndPoint = new IPEndPoint(new IPAddress(new byte[] {192, 168, 18, 2}), 11211)},
                new NodeMock {EndPoint = new IPEndPoint(new IPAddress(new byte[] {192, 168, 18, 3}), 11211)},
                new NodeMock {EndPoint = new IPEndPoint(new IPAddress(new byte[] {192, 168, 18, 4}), 11211)},
                new NodeMock {EndPoint = new IPEndPoint(new IPAddress(new byte[] {192, 168, 18, 5}), 11211)},
            };
        }

        [Test]
        public void RoundRobinTest()
        {
            var locator = new RoundRobinLocator();
            locator.Initialize(_nodes);

            var nodeSet = new HashSet<IMemcacheNode>();

            for (int i = 0; i < _nodes.Count; ++i)
            {
                var key = i.ToString().Select(c => (byte)c).ToArray();

                var locations = locator.Locate(new RequestKeyWrapper(key));
                Assert.IsNotEmpty(locations, "RoundRobinLocator found no node");

                var chosenNode = locations.First<IMemcacheNode>();
                Assert.IsNotNull(chosenNode, "RoundRobinLocator found no node");

                nodeSet.Add(chosenNode);
            }

            Assert.AreEqual(_nodes.Count, nodeSet.Count, "All nodes should have been chosen at least once");
        }

        [Test]
        public void KetamaTest()
        {
            var locator = new KetamaLocator();
            locator.Initialize(_nodes);

            // Test several keys, and iterate through each key several times
            for (int idx = 0; idx < _nodes.Count; ++idx)
            {
                var nodeSet = new HashSet<IMemcacheNode>();

                int nodeCount = 0;
                var keyAsBytes = idx.ToString().Select(c => (byte)c).ToArray();
                foreach (var chosenNode in locator.Locate(new RequestKeyWrapper(keyAsBytes)))
                {
                    Assert.IsNotNull(chosenNode, "KetamaLocator found no node");
                    nodeSet.Add(chosenNode);
                    nodeCount++;
                    Assert.AreEqual(nodeCount, nodeSet.Count, "For a given key, all nodes returned by the locator should be distinct");
                }
                Assert.AreEqual(_nodes.Count, nodeCount, "KetamaLocator did not return the maximum number of nodes available");
            }
        }

        [Test]
        public void RoundRobinDeadNodeDetectionTest()
        {
            var locator = new RoundRobinLocator();
            locator.Initialize(_nodes);

            for (int i = 1; i < _nodes.Count; ++i)
                (_nodes[i] as NodeMock).IsDead = true;

            for (int i = 0; i < _nodes.Count; ++i)
            {
                var keyAsBytes = i.ToString().Select(c => (byte)c).ToArray();

                var locations = locator.Locate(new RequestKeyWrapper(keyAsBytes));
                Assert.IsNotEmpty(locations, "RoundRobinLocator found no node, but at least 1 is alive");

                var chosenNode = locations.First();
                Assert.IsFalse(chosenNode.IsDead, "RoundRobinLocator returned a dead node");
            }

            (_nodes[0] as NodeMock).IsDead = true;

            for (int i = 0; i < _nodes.Count; ++i)
            {
                var keyAsBytes = i.ToString().Select(c => (byte)c).ToArray();
                CollectionAssert.IsEmpty(locator.Locate(new RequestKeyWrapper(keyAsBytes)), "RoundRobinLocator found a node when all are dead");
            }

            foreach (var node in _nodes)
                (node as NodeMock).IsDead = false;
        }

        [Test]
        public void KetamaDeadNodeDetectionTest1()
        {
            var locator = new KetamaLocator();
            locator.Initialize(_nodes);

            // All nodes but one are dead
            for (int i = 1; i < _nodes.Count; ++i)
                (_nodes[i] as NodeMock).IsDead = true;

            for (int i = 0; i < _nodes.Count; ++i)
            {
                var keyAsBytes = i.ToString().Select(c => (byte)c).ToArray();

                var locations = locator.Locate(new RequestKeyWrapper(keyAsBytes));
                Assert.IsNotEmpty(locations, "KetamaLocator found no node, but at least one is alive");

                var chosenNode = locations.First<IMemcacheNode>();
                Assert.IsFalse(chosenNode.IsDead, "KetamaLocator returned a dead node");
            }

            // Now all nodes are dead
            (_nodes[0] as NodeMock).IsDead = true;

            for (int i = 0; i < _nodes.Count; ++i)
            {
                var keyAsBytes = i.ToString().Select(c => (byte)c).ToArray();
                CollectionAssert.IsEmpty(locator.Locate(new RequestKeyWrapper(keyAsBytes)), "KetamaLocator found a node when all are dead");
            }

            foreach (var node in _nodes)
                (node as NodeMock).IsDead = false;
        }

        // Same test but killing the nodes after the enumeration has started. The Locator should still filter the dead nodes.
        [Test]
        public void KetamaDeadNodeDetectionTest2()
        {
            var locator = new KetamaLocator();
            locator.Initialize(_nodes);

            for (int i = 0; i < _nodes.Count; ++i)
            {
                foreach (IMemcacheNode node in _nodes)
                    (node as NodeMock).IsDead = false;

                var keyAsBytes = i.ToString().Select(c => (byte)c).ToArray();
                var locations = locator.Locate(new RequestKeyWrapper(keyAsBytes));

                var j = 0;
                var nodesSet = new HashSet<IMemcacheNode>();
                foreach (var chosenNode in locations)
                {
                    nodesSet.Add(chosenNode);
                    Assert.IsFalse(chosenNode.IsDead, "KetamaLocator returned a dead node");
                    // Kill one of the nodes
                    (_nodes[j++] as NodeMock).IsDead = true;
                }

                Assert.AreNotEqual(0, nodesSet.Count, "KetamaLocator returned no node");
            }

            foreach (var node in _nodes)
                (node as NodeMock).IsDead = false;
        }
    }
}


text:
package org.guvnor.ala.services.rest.factories;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import org.guvnor.ala.config.ProviderConfig;
import org.guvnor.ala.runtime.providers.Provider;
import org.guvnor.ala.runtime.providers.ProviderBuilder;

public class ProviderFactory {

    private final Collection<ProviderBuilder> builders = new ArrayList<>();

    public ProviderFactory() {
    }

    @Inject
    public ProviderFactory( final Instance<ProviderBuilder<?, ?>> builders ) {
        builders.forEach( this.builders::add );
    }

    public Optional<Provider> newProvider( ProviderConfig config ) {
        Optional<Provider> provider = builders.stream()
                .filter( pb -> pb.supports( config ) )
                .findFirst().flatMap( pb -> {
                    return ( Optional<Provider> ) pb.apply( config );
                } );
        return provider;
    }
}


text:
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

function readLine (file, opts){

   if (!(this instanceof readLine)) return new readLine(file);;

   EventEmitter.call(this);
   opts = opts || {};
   var self = this;
   var readStream = fs.createReadStream(file);
   var nl = require('os').EOL.charCodeAt(0);
   var line = [];

   readStream.on("open",function (fd){
      self.emit('open',fd);
   });

   readStream.on("data", function (data){
     for(var i=0; i < data.length; i++){
        if(data[i] === nl){
          var tmpBuf = new Buffer(line);
          self.emit("line",tmpBuf.toString());
          line = [];
        }else{
          line.push(data[i]);
        }
     }
   });
   readStream.on("error", function (err){
      self.emit("error",err);

   });

   readStream.on("end", function (){
    self.emit("end");
   });

   readStream.on("close", function (){
    self.emit("close");
   });
};

util.inherits(readLine, EventEmitter);
module.exports = readLine;


text:
package com.wci.umls.server.test.jpa;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.wci.umls.server.helpers.StringList;
import com.wci.umls.server.jpa.services.ContentServiceJpa;
import com.wci.umls.server.services.ContentService;
import com.wci.umls.server.test.helpers.IntegrationUnitSupport;

/**
 * Sample test to get auto complete working
 */
public class ContentServiceAutocompleteTest extends IntegrationUnitSupport {

  /** The service. */
  ContentService service = null;

  /**
   * Setup class.
   */
  @BeforeClass
  public static void setupClass() {
    // do nothing
  }

  /**
   * Setup.
   * @throws Exception
   */
  @Before
  public void setup() throws Exception {
    service = new ContentServiceJpa();
  }

  /**
   * Normal use of concept autocomplete.
   *
   * @throws Exception the exception
   */
  @Test
  public void testConceptAutocompleteNormalUse() throws Exception {
    Logger.getLogger(getClass()).info("TEST " + name.getMethodName());
    StringList results =
        service.autocompleteConcepts("SNOMEDCT_US", "2016_03_01", "lett");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteConcepts("SNOMEDCT_US", "2016_03_01", "let");
    assertTrue(results.getObjects().size()>10);

    results = service.autocompleteConcepts("MTH", "latest", "lett");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteConcepts("MTH", "latest", "let");
    assertTrue(results.getObjects().size()>10);
  }

  /**
   * Normal use of descriptor autocomplete.
   *
   * @throws Exception the exception
   */
  @Test
  public void testDescriptorAutocompleteNormalUse() throws Exception {
    Logger.getLogger(getClass()).info("TEST " + name.getMethodName());
    StringList results =
        service.autocompleteDescriptors("MSH", "2016_2016_02_26", "infr");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteDescriptors("MSH", "2016_2016_02_26", "inf");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteDescriptors("MSH", "2016_2016_02_26", "in");
    assertEquals(7, results.getObjects().size());
    results = service.autocompleteDescriptors("MSH", "2016_2016_02_26", "i");
    assertEquals(6, results.getObjects().size());

  }

  /**
   * Normal use of code autocomplete.
   *
   * @throws Exception the exception
   */
  @Test
  public void testCodeAutocompleteNormalUse() throws Exception {
    Logger.getLogger(getClass()).info("TEST " + name.getMethodName());
    StringList results =
        service.autocompleteCodes("SNOMEDCT_US", "2016_03_01", "lett");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteCodes("SNOMEDCT_US", "2016_03_01", "let");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteCodes("SNOMEDCT_US", "2016_03_01", "le");
    assertTrue(results.getObjects().isEmpty());
    results = service.autocompleteCodes("SNOMEDCT_US", "2016_03_01", "l");
    assertEquals(2, results.getObjects().size());

    results = service.autocompleteCodes("MTH", "latest", "lett");
    assertTrue(results.getObjects().isEmpty());
    results = service.autocompleteCodes("MTH", "latest", "let");
    assertTrue(results.getObjects().isEmpty());

    results = service.autocompleteCodes("MTH", "latest", "le");
    assertTrue(results.getObjects().isEmpty());
    results = service.autocompleteCodes("MTH", "latest", "l");
    assertTrue(results.getObjects().isEmpty());
  }

  /**
   * Edge cases of concept autocomplete.
   *
   * @throws Exception the exception
   */
  @Test
  public void testConceptAutocompleteEdgeCases() throws Exception {
    Logger.getLogger(getClass()).info("TEST " + name.getMethodName());
    StringList results =
        service.autocompleteConcepts("SNOMEDCT_US", "2016_03_01", "le");
    assertTrue(results.getObjects().isEmpty());
    results = service.autocompleteConcepts("SNOMEDCT_US", "2016_03_01", "l");
    assertEquals(2, results.getObjects().size());
    results = service.autocompleteConcepts("MTH", "latest", "le");
    assertTrue(results.getObjects().size()>10);
    results = service.autocompleteConcepts("MTH", "latest", "l");
    assertTrue(results.getObjects().size()>10);

  }

  /**
   * Degenerate use of concept autocomplete.
   *
   * @throws Exception the exception
   */
  @Test
  public void testConceptAutocompleteDegenerateUse() throws Exception {
    Logger.getLogger(getClass()).info("TEST " + name.getMethodName());
    StringList results = service.autocompleteConcepts(null, null, null);
    assertTrue(results.getObjects().isEmpty());
  }

  /**
   * Teardown.
   */
  @After
  public void teardown() {
    // do nothing
  }

  /**
   * Teardown class.
   */
  @AfterClass
  public static void teardownClass() {
    // do nothing
  }

}


text:
ACCEPTED

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

#### Published in
Nova Hedwigia 44(3-4): 519 (1987)

#### Original name
Ketubakia Kamat, Varghese & V.G. Rao

### Remarks
null


text:
@interface CANetworkAddress_Generated ()

@end

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

@implementation CANetworkAddress_Generated

-(CAJsonObject*)toJsonObject {
	CAJsonObject* answer = [[CAJsonObject alloc] init];
	[answer setInt:_port forKey:@"port"];
	return answer;

}

#pragma mark -
#pragma mark instance lifecycle

-(id)init {
	return [super init];
}

-(id)initWithJsonObject:(CAJsonObject*)jsonObject {

	CANetworkAddress_Generated* answer = [super init];

	[answer setPort:[jsonObject intForKey:@"port"]];

	return answer;

}

-(void)dealloc {

}

#pragma mark -
#pragma mark fields

//////////////////////////////////////////////////////
// port
//int _port;
//@property (nonatomic, assign) int port;
@synthesize port = _port;

@end


text:
import json
import os
import unittest

from monty.serialization import loadfn

from pymatgen.analysis.defects.core import DefectEntry
from pymatgen.analysis.defects.thermodynamics import DefectPhaseDiagram
from pymatgen.core import Element
from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.util.testing import PymatgenTest

class DefectsThermodynamicsTest(PymatgenTest):
    @classmethod
    def setUpClass(cls):
        cls.vbm_val = 2.6682
        cls.gap = 1.5
        cls.entries = list(loadfn(os.path.join(os.path.dirname(__file__), "GaAs_test_defentries.json")).values())
        for entry in cls.entries:
            entry.parameters.update({"vbm": cls.vbm_val})
        cls.pd = DefectPhaseDiagram(cls.entries, cls.vbm_val, cls.gap)
        cls.mu_elts = {Element("As"): -4.658070555, Element("Ga"): -3.7317319750000006}

        # make Vac_As (q= -2) only defect test single-stable-charge exceptions
        cls.extra_entry = DefectEntry(cls.entries[5].defect.copy(), 100.0)
        sep_entries = [
            ent for ent in cls.entries if not (ent.name == "Vac_As_mult4" and ent.charge in [-2, -1, 0, 1, 2])
        ]
        sep_entries.append(cls.extra_entry.copy())
        cls.sep_pd = DefectPhaseDiagram(sep_entries, cls.vbm_val, cls.gap)

        # make Vac_As (q= -2) is incompatible for larger supercell
        ls_entries = cls.entries[:]
        for entry in ls_entries:
            if entry.name == "Vac_As_mult4" and entry.charge == -2.0:
                entry.parameters["is_compatible"] = False
        cls.pd_ls_fcTrue = DefectPhaseDiagram(ls_entries, cls.vbm_val, cls.gap, filter_compatible=True)
        cls.pd_ls_fcFalse = DefectPhaseDiagram(ls_entries, cls.vbm_val, cls.gap, filter_compatible=False)

        # load complete dos for fermi energy solving
        with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "complete_dos.json")) as f:
            dos_dict = json.load(f)
        cls.dos = CompleteDos.from_dict(dos_dict)

    def test_good_test_data(self):
        self.assertEqual(len(self.entries), 48)

    def test_suggest_charges(self):
        suggested_charges = self.pd.suggest_charges()
        for k in [
            "Vac_As_mult4@0-1-2-3-4-5",
            "Sub_Ga_on_As_mult4@6-7-8-9-10-11",
            "Vac_Ga_mult4@12-13-14-15",
            "Sub_As_on_Ga_mult4@16-17-18-19-20-21",
            "Int_Ga_mult1@22-23-24-25",
            "Int_As_mult1@26-27-28-29-30-31-32-33-34",
            "Int_As_mult1@35-36-37-38-39-40-41-42-43",
            "Int_Ga_mult1@44-45-46-47",
        ]:
            self.assertTrue(
                len(suggested_charges[k]) > 0,
                f"Could not find any suggested charges for {k} with band_gap of {self.pd.band_gap}",
            )

        pd = DefectPhaseDiagram(self.entries, 2.6682, 1.0)
        suggested_charges = self.pd.suggest_charges()
        for k in ["Vac_As_mult4@0-1-2-3-4-5", "Vac_Ga_mult4@12-13-14-15"]:
            self.assertTrue(
                len(suggested_charges[k]) > 0,
                f"Could not find any suggested charges for {k} with band_gap of {pd.band_gap}",
            )

        # test again but with only one charge state stable for Vac_As
        suggested_charges = self.sep_pd.suggest_charges()
        self.assertEqual(set(suggested_charges["Vac_As_mult4@0-43"]), {-4})

    def test_suggest_larger_supercells(self):
        suggested_larger_cells = self.pd_ls_fcFalse.suggest_larger_supercells()
        self.assertEqual(suggested_larger_cells["Vac_As_mult4@0-1-2-3-4-5"], [-2])

        # raise error if filter_compatibile = True
        self.assertRaises(ValueError, self.pd_ls_fcTrue.suggest_larger_supercells)

    def test_entries(self):
        all_stable_entries = self.pd.all_stable_entries

        self.assertEqual(len(self.pd.defect_types), 8)
        self.assertEqual(
            len(all_stable_entries),
            sum(len(v) for v in self.pd.stable_charges.values()),
        )

        # test again but with only one charge state stable for Vac_As
        self.assertEqual(len(self.sep_pd.transition_level_map["Vac_As_mult4@0-43"]), 0)
        self.assertEqual(len(self.sep_pd.stable_entries["Vac_As_mult4@0-43"]), 1)
        self.assertEqual(len(self.sep_pd.finished_charges["Vac_As_mult4@0-43"]), 2)

    def test_solve_for_fermi_energy(self):
        fermi_energy = self.pd.solve_for_fermi_energy(100.0, self.mu_elts, self.dos)
        self.assertAlmostEqual(fermi_energy, 0.8334775317578078, 3)
        fermi_energy = self.pd.solve_for_fermi_energy(1000.0, self.mu_elts, self.dos)
        self.assertAlmostEqual(fermi_energy, 0.74139553, 3)

    def test_solve_for_non_equilibrium_fermi_energy(self):
        fermi_energy = self.pd.solve_for_non_equilibrium_fermi_energy(300.0, 1000.0, self.mu_elts, self.dos)
        self.assertAlmostEqual(fermi_energy, 0.29500637, 3)
        fermi_energy = self.pd.solve_for_non_equilibrium_fermi_energy(1000.0, 1000.0, self.mu_elts, self.dos)
        self.assertAlmostEqual(fermi_energy, 0.7413955908839398, 3)

    def test_get_dopability_limits(self):
        lower_lim, upper_lim = self.pd.get_dopability_limits(self.mu_elts)
        self.assertAlmostEqual(lower_lim, -0.39996272)
        self.assertAlmostEqual(upper_lim, 1.064193047)
        # raise error if defects are negative across gap
        bad_mu_elts = self.mu_elts.copy()
        bad_mu_elts[Element("Ga")] += 10.0
        lower_lim, upper_lim = self.pd.get_dopability_limits(bad_mu_elts)
        self.assertIsNone(lower_lim)
        self.assertIsNone(upper_lim)

    # def test_plot(self):
    #     # simple test that plot is produced
    #     p = self.pd.plot(saved=False)
    #     self.assertTrue(p)

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


text:
package com.kingtopgroup.activty;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kingtogroup.utils.RegxUtils;
import com.kingtopgroup.R;
import com.kingtopgroup.constant.ConstanceUtil;
import com.kingtopgroup.util.stevenhu.android.phone.bean.UserBean;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.stevenhu.android.phone.utils.AsyncHttpCilentUtil;

public class AddAddressActivity extends MainActionBarActivity implements
		OnClickListener {
	private static final String TAG = "AddAddressActivity";
	EditText et_name;
	EditText et_phone;
	EditText et_address;
	Button btn_ok;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addaddress);
		init();
	}

	void init() {
		et_name = (EditText) findViewById(R.id.et_name);
		et_address = (EditText) findViewById(R.id.et_address);
		et_phone = (EditText) findViewById(R.id.et_phone);
		btn_ok = (Button) findViewById(R.id.btn_ok);

		titleButton.setText("Ìí¼ÓµØÖ·");

		btn_ok.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_ok:
			String name = et_name.getText().toString();
			if (TextUtils.isEmpty(name)) {
				Toast.makeText(this, "ÐÕÃû²»ÄÜΪ¿Õ£¡", Toast.LENGTH_SHORT).show();
				return;
			}
			String phone = et_phone.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				Toast.makeText(this, "ÁªÏµµç»°²»ÄÜΪ¿Õ£¡", Toast.LENGTH_SHORT).show();
				return;
			}
			if (!RegxUtils.isPhone(phone)) {
				Toast.makeText(this, "ÇëÊäÈëÕýÈ·µÄÊÖ»úºÅÂ룡", Toast.LENGTH_SHORT).show();
				return;
			}
			String address = et_address.getText().toString();
			if (TextUtils.isEmpty(address)) {
				Toast.makeText(this, "ÏêϸµØÖ·²»ÄÜΪ¿Õ£¡", Toast.LENGTH_SHORT).show();
				return;
			}

			requestAdd(name, phone, address);

			break;

		default:
			break;
		}
	}

	void requestAdd(String name, String phone, String address) {
		UserBean userBean = UserBean.getUSerBean();
		String uid = userBean.getUid();
		if (TextUtils.isEmpty(uid))
			return;
		RequestParams params = AsyncHttpCilentUtil.getParams();
		params.put("consignee", name);
		params.put("uid", UserBean.getUSerBean().getUid());
		params.put("regionId", "2685");
		params.put("alias", name);
		params.put("mobile", phone);
		params.put("phone", phone);
		params.put("email", "1135741892@qqq.com");
		params.put("zipcode", "655002");
		params.put("address", address);
		params.put("isDefault", "1");

		AsyncHttpCilentUtil.getInstance().post(this,
				ConstanceUtil.add_adress_url, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						toastMsg("ÐÅÏ¢ÓÐÎó£¬ÇëÖØÊÔ");
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						Log.i(TAG, new String(arg2));
						if (arg0 == 200) {
							try {
								JSONObject obj = new JSONObject(
										new String(arg2));
								int returnValue = obj.getInt("ReturnValue");
								String msg = obj.getString("ActionMessage");
								toastMsg(msg);
								if (returnValue != -1) {
									finish();
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					}
				});
	}

	void toastMsg(final String msg) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(AddAddressActivity.this, msg, Toast.LENGTH_SHORT)
						.show();
			}
		});
	}

	@Override
	public void backButtonClick(View v) {
		finish();
	}

	@Override
	public void titleButtonClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public void rightButtonClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public Boolean showHeadView() {
		return true;
	}

}


text:
from __future__ import unicode_literals

from django.contrib import admin
from django.forms import widgets
from django.utils.translation import ugettext_lazy as _
from cms.extensions import PageExtensionAdmin
from cmsplugin_cascade.fields import PartialFormField
from cmsplugin_cascade.widgets import JSONMultiWidget
from cmsplugin_cascade.utils import rectify_partial_form_field
from .models import RevealExtension

@admin.register(RevealExtension)
class RevealExtensionAdmin(PageExtensionAdmin):
    TRANSITIONS = (('none', "None"), ('fade', "Fade"), ('slide', "Slide"), ('convex', "Convey"),
        ('concave', "Concave"), ('zoom', "Zoom"))

    option_fields = ((
        PartialFormField('controls',
            widgets.CheckboxInput(),
            label=_("Controls"),
            initial=True,
            help_text=_("Displays control arrows in the bottom right corner."),
        ),
        PartialFormField('progress',
            widgets.CheckboxInput(),
            label=_("Progress"),
            initial=True,
            help_text=_("Display a presentation progress bar on the bottom."),
        ),
        PartialFormField('history',
            widgets.CheckboxInput(),
            label=_("History"),
            initial=True,
            help_text=_("Push each slide change to the browser history."),
        ),
        PartialFormField('center',
            widgets.CheckboxInput(),
            label=_("Center"),
            initial=True,
            help_text=_("Vertical centering of slides."),
        ),
        PartialFormField('transition',
            widgets.Select(choices=TRANSITIONS),
            label=_("Transition"),
            help_text=_("Transitions style for changing slides."),
        ),
        PartialFormField('width',
            widgets.TextInput(),
            label=_("Width"),
            initial='960px',
            help_text=_("Slide width"),
        ),
        PartialFormField('height',
            widgets.TextInput(),
            label=_("Height"),
            initial='700px',
            help_text=_("Slide height"),
        ),
        PartialFormField('margin',
            widgets.NumberInput(attrs={'step': 0.02}),
            label=_("Margin"),
            initial=0.1,
            help_text=_("Slide's margin"),
        ),
        PartialFormField('minScale',
            widgets.NumberInput(attrs={'step': 0.1}),
            label=_("Min Scale"),
            initial=0.2,
        ),
        PartialFormField('maxScale',
            widgets.NumberInput(attrs={'step': 0.1}),
            label=_("Max Scale"),
            initial=1.5,
        ),
    ),)

    class Media:
        css = {'all': ('cascade/css/admin/partialfields.css',)}

    def get_form(self, request, obj=None, **kwargs):
        """
        Build the form used for changing the model.
        """
        kwargs.update(widgets={
            'options': JSONMultiWidget(self.option_fields),
        })
        form = super(RevealExtensionAdmin, self).get_form(request, obj, **kwargs)
        rectify_partial_form_field(form.base_fields['options'], self.option_fields)
        form.option_fields = self.option_fields
        return form


text:
// -----------------------------------------------------------------------
//  <copyright file="FlexArrayList.cs" company="Phoenix Game Studios, LLC">
//      Copyright (c) 2017 Phoenix Game Studios, LLC. All rights reserved.
//      Licensed under the MIT License.
//      See https://github.com/PhoenixGameStudios/DangrLib/blob/master/LICENSE for full license information.
//  </copyright>
// -----------------------------------------------------------------------

namespace Dangr.Core.FlexCollections.List
{
    /// <summary>
    /// Defines interfaces for a <see cref="FlexList"/> that uses an array as its internal data store.
    /// </summary>
    public static class FlexArrayList
    {
        /// <summary>
        /// The default capacity of a FlexArrayList.
        /// </summary>
        public const int DEFAULT_CAPACITY = 10;

        /// <summary>
        /// Provides read only covariant methods for the collection.
        /// </summary>
        /// <typeparam name="T">The type of object contained in the collection.</typeparam>
        public interface IReadOnlyCovariant<out T> : FlexList.IReadOnlyCovariant<T>
        {
            /// <summary>
            /// Gets the current capacity of the array list.
            /// </summary>
            int Capacity { get; }
        }

        /// <summary>
        /// Provides read only methods for the collection.
        /// </summary>
        /// <typeparam name="T">The type of object contained in the collection.</typeparam>
        public interface IReadOnly<T> : IReadOnlyCovariant<T>, FlexList.IReadOnly<T>
        {
        }

        /// <summary>
        /// Provides covariant methods for the collection.
        /// </summary>
        /// <typeparam name="T">The type of object contained in the collection.</typeparam>
        public interface ICovariant<out T> : IReadOnlyCovariant<T>, FlexList.ICovariant<T>
        {
        }

        /// <summary>
        /// Provides generic methods for the collection.
        /// </summary>
        /// <typeparam name="T">The type of object contained in the collection.</typeparam>
        public interface IGeneric<T> : IReadOnly<T>, ICovariant<T>, FlexList.IGeneric<T>
        {
        }
    }
}


text:
// -----------------------------------------------------------------------
// <copyright file="SqlClauseBuilderTests.cs">
// Copyright (c) 2013-2015 Andrey Veselov. All rights reserved.
// License: Apache License 2.0
// Contacts: http://andrey.moveax.com andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace LoreKeeper.EF6.Tests
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using LoreKeeper.EF6.AdvancedFeatures;
    using LoreKeeper.Tests.Core.Models;
    using Xunit;

    public class SqlClauseBuilderTests
    {
        [Fact]
        public void SqlClauseBuilderSimpleWithConst()
        {
            // Arrange
            const string expectedSql = "(Id = '5')";
            Expression<Func<User, bool>> clause = u => u.Id == 5;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderSimpleWithVaue()
        {
            // Arrange
            string name = "some Name";
            string expectedSql = $"(Name = '{name}')";

            Expression<Func<User, bool>> clause = u => u.Name == name;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderSimpleWithConvertFromByte()
        {
            // Arrange
            byte id = 5;
            const string expectedSql = "(Id = '5')";

            Expression<Func<User, bool>> clause = u => u.Id == id;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderSimpleWithConvertFromEnum()
        {
            // Arrange
            var userType = UserType.Reader;
            string expectedSql = $"(Type = {(byte)UserType.Reader})";

            Expression<Func<User, bool>> clause = u => u.Type == userType;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderPropertyIsNullConst()
        {
            // Arrange
            string expectedSql = "(Name IS NULL)";

            Expression<Func<User, bool>> clause = u => u.Name == null;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderPropertyNotNullConst()
        {
            // Arrange
            string expectedSql = "(Name IS NOT NULL)";

            Expression<Func<User, bool>> clause = u => u.Name != null;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderAndClause()
        {
            // Arrange
            string name = "some Name";
            string expectedSql = $"((Id = '5') AND (Name = '{name}'))";

            Expression<Func<User, bool>> clause = u => u.Id == 5 && u.Name == name;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderNotClause()
        {
            // Arrange
            int id = 42;
            string expectedSql = $"(Id != '{id}')";

            Expression<Func<User, bool>> clause = u => u.Id != id;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderBooleanClauseWithConst()
        {
            // Arrange
            const string expectedSql = "(IsDisabled != 1)";

            Expression<Func<User, bool>> clause = u => u.IsDisabled != true;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderBooleanClauseWithValue()
        {
            // Arrange
            const bool isDisabled = false;
            string expectedSql = $"(IsDisabled != {(isDisabled ? "1" : "0")})";

            Expression<Func<User, bool>> clause = u => u.IsDisabled != isDisabled;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderBooleanProperty()
        {
            // Arrange
            const string expectedSql = "(IsDisabled = 1)";

            Expression<Func<User, bool>> clause = u => u.IsDisabled;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderNotProperty()
        {
            // Arrange
            const string expectedSql = "(IsDisabled = 0)";

            Expression<Func<User, bool>> clause = u => !u.IsDisabled;

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderNotExpression()
        {
            // Arrange
            const int id = 42;
            string expectedSql = $"(NOT (Id > '{id}'))";

            Expression<Func<User, bool>> clause = u => !(u.Id > id);

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderOrClause()
        {
            // Arrange
            const int id = 42;
            string expectedSql = $"((Id = '{id}') OR (Name = 'some Value'))";

            Expression<Func<User, bool>> clause = u => u.Id == id || u.Name == "some Value";

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderAndOrClause()
        {
            // Arrange
            const int id = 42;
            var now = DateTime.Now;
            string expectedSql = $"((Id = '{id}') OR ((Name = 'some Value') AND (Created < '{now.ToString("yyyy.MM.dd HH:mm:ss")}')))";

            Expression<Func<User, bool>> clause = u => u.Id == id || (u.Name == "some Value" && u.Created < now);

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        [Fact]
        public void SqlClauseBuilderWithBuilderExpression()
        {
            // Arrange
            const int id = 42;
            var now = DateTime.Now;
            string expectedSql = $"(((Id = '{id}') AND (Created < '{now.ToString("yyyy.MM.dd HH:mm:ss")}')) AND (Name = 'some Value'))";

            Expression<Func<User, bool>> clause = u => u.Id == id;
            clause = this.Combine(clause, u => u.Created < now);
            clause = this.Combine(clause, u => u.Name == "some Value");

            var sqlClauseBuilder = new SqlClauseBuilder();

            // Act
            string actualSql = sqlClauseBuilder.Build(clause.Body);

            // Assert
            Assert.Equal(expectedSql, actualSql);
        }

        private Expression<Func<TParam, TResult>> Combine<TParam, TResult>(Expression<Func<TParam, TResult>> a, Expression<Func<TParam, TResult>> b)
        {
            if (a == null)
                return b;

            ParameterExpression firstParameter = a.Parameters.First();
            Expression<Func<TParam, TResult>> b1 = Expression.Lambda<Func<TParam, TResult>>(Expression.Invoke(b, firstParameter), firstParameter);
            return Expression.Lambda<Func<TParam, TResult>>(Expression.And(a.Body, b1.Body), firstParameter);
        }
    }
}


text:
<?php
namespace Migration\Tests\Base;

use Migration\Tests\Base\AbstractProject;
use RuntimeException;

class AbstractProjectWithDb extends AbstractProject
{

    public function buildDb($platform = 'mysql')
    {

        if($platform === 'mysql') {
            exec('/usr/bin/mysql -u '. DEMO_DATABASE_USER . ' -p'.DEMO_DATABASE_PASSWORD .' < '.__DIR__ .'/sakila-schema.sql');
            exec('/usr/bin/mysql -u '. DEMO_DATABASE_USER . ' -p'.DEMO_DATABASE_PASSWORD .' < '.__DIR__ .'/sakila-data.sql');
        } else if($platform === 'sqlite') {

            if(is_file('/var/tmp/example.sqlite')) {
                unlink('/var/tmp/example.sqlite');
            }
            exec('/usr/bin/sqlite3 /var/tmp/example.sqlite < '.realpath(__DIR__ .'/Database/chinook_sqlite.sql'));
        } else {
            throw new RuntimeException(sprintf('Database platform %s has no database fixture to apply',$platform));
        }

    }

    //  -------------------------------------------------------------------------
    # Gets Doctine connection for the test database

    static $doctrine_connection;

    /**
      *  Gets a db connection to the test database
      *
      *  @access public
      *  @return \Doctrine\DBAL\Connection
      */
    public function getDoctrineConnection($platform = 'mysql')
    {

        $config = new \Doctrine\DBAL\Configuration();

        if($platform === 'mysql') {

            $connectionParams = array(
                'dbname'   => DEMO_DATABASE_SCHEMA,
                'user'     => DEMO_DATABASE_USER,
                'password' => DEMO_DATABASE_PASSWORD,
                'host'     => DEMO_DATABASE_HOST,
                'driver'   => DEMO_DATABASE_TYPE,
            );

        } else if($platform === 'sqlite') {
                $connectionParams = array(
                'path' => '/var/tmp/example.sqlite',
                'driver'   => 'pdo_sqlite',
            );

        } else {
            throw new RuntimeException(sprintf('Database platform %s has no database fixture to apply',$platform));
        }

        return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

    }

    //  -------------------------------------------------------------------------
    # Get Builder

    protected function getTable()
    {
        $connection = $this->getDoctrineConnection();
        $log    = $this->getMockLog();

        return new \Migration\Components\Migration\Driver\Mysql\TableManager($connection,$log,'migration_migrate');

    }

}
/* End of File */


text:
package org.apache.myfaces.trinidadinternal.skin.parse;

import org.apache.myfaces.trinidad.logging.TrinidadLogger;

/**
 * Object which represents a single <skin> element in trinidad-skins.xml.
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/ui/laf/xml/parse/SkinPropertyNode.java#0 $) $Date: 10-nov-2005.18:50:45 $
 */
public class SkinNode
{
  /**
   *
   */
  public SkinNode (
    String id,
    String family,
    String renderKitId,
    String skinExtends,
    String styleSheetName,
    String bundleName,
    String translationSourceExpression)
  {

    if (id==null)
    {
      throw new NullPointerException(_LOG.getMessage(
        "NULL_ID"));
    }
    if (family==null)
    {
      throw new NullPointerException(_LOG.getMessage(
        "NULL_FAMILY"));
    }

    _id = id;
    _family = family;
    _renderKitId = renderKitId;
    _skinExtends = skinExtends;
    _styleSheetName = styleSheetName;
    _bundleName = bundleName;
    _translationSourceExpression = translationSourceExpression;

  }

  /**
   * Returns the skin id for this node
   */
  public String getId()
  {
    return _id ;
  }

  /**
   * Returns the skin family for this node
   */
  public String getFamily()
  {
    return _family;
  }

  /**
   * Returns the renderKitId for this node.
   */
  public String getRenderKitId()
  {
    return _renderKitId;
  }

  /**
   * Returns the skinExtends for this node.
   */
  public String getSkinExtends()
  {
    return _skinExtends;
  }

  /**
   * Returns the styleSheetName for this node.
   */
  public String getStyleSheetName()
  {
    return _styleSheetName;
  }

  /**
   * Returns the bundleName for this node.
   */
  public String getBundleName()
  {
    return _bundleName;
  }

  /**
   * Returns the translationSource value expression String. This could
   * resolve to a Map or a ResourceBundle.
   */
  public String getTranslationSourceExpression()
  {
    return _translationSourceExpression;
  }

  private String _id;
  private String _family;
  private String _renderKitId;
  private String _skinExtends;
  private String _styleSheetName;
  private String _bundleName;
  private String _translationSourceExpression;

  private static final TrinidadLogger _LOG =
    TrinidadLogger.createTrinidadLogger( SkinNode.class);
}


text:
package com.gmail.socraticphoenix.nebula.io.jlsc.metadata;

import java.util.ArrayList;
import java.util.List;

public class JLSCValueProperty {
    private String name;
    private List<String> args;

    public JLSCValueProperty(String name) {
        this.name = name;
        this.args = new ArrayList<>();
    }

    public List<String> getArguments() {
        return this.args;
    }

    public String getName() {
        return this.name;
    }
}


text:
package elasticsearch_test

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/arsham/expipe/datatype"
	"github.com/arsham/expipe/recorder"
	"github.com/arsham/expipe/recorder/elasticsearch"
	rt "github.com/arsham/expipe/recorder/testing"
	"github.com/arsham/expipe/tools/token"
	"github.com/pkg/errors"
)

var (
	sniffer = `{
  "_nodes": {
    "total": 1,
    "successful": 1,
    "failed": 0
  },
  "cluster_name": "elasticsearch",
  "nodes": {
    "P2CLuttqTw-UaiqMYwEkeA": {
      "name": "P2CLutt",
      "transport_address": "%s:9300",
      "host": "%s",
      "ip": "%s",
      "version": "5.0.1",
      "build_hash": "080bb47",
      "roles": [
        "master",
        "data",
        "ingest"
      ],
      "http": {
        "bound_address": [
          "[::]:%s"
        ],
        "publish_address": "%s",
        "max_content_length_in_bytes": 104857600
      }
    }
  }
}`

	recording = `{"_index":"my_index","_type":"my type","_id":"AVlzOSs-sx0uWYTCQCzC","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"created":true}`
	pinging   = `{"name" : "P2CLutt", "cluster_name" : "elasticsearch", "cluster_uuid" : "MEhShuk2R9aUgnnX_Qk2bw", "version" : {"number" : "5.0.1", "build_hash" : "080bb47", "build_date" : "2016-11-11T22:08:49.812Z", "build_snapshot" : false, "lucene_version" : "6.2.1"}, "tagline" : "You Know, for Search"}`
)

func getTestServer() *httptest.Server {
	var host, url, port string
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/_nodes/http":
			// sniffing
			w.Write([]byte(fmt.Sprintf(sniffer, host, host, host, port, url)))
		case len(r.URL.Path) > 5:
			// recording
			w.Write([]byte(recording))
		case r.URL.Path == "/":
			// pinging
			w.Write([]byte(pinging))
		}
	})

	testServer := httptest.NewServer(handler)
	url = strings.Split(testServer.URL, "//")[1]
	host, port = strings.Split(url, ":")[0], strings.Split(url, ":")[1]
	return testServer
}

type Construct struct {
	*rt.BaseConstruct
	testServer *httptest.Server
}

func (c *Construct) TestServer() *httptest.Server {
	c.testServer = getTestServer()
	return c.testServer
}

func (c *Construct) Object() (recorder.DataRecorder, error) {
	return elasticsearch.New(c.Setters()...)
}

func (c *Construct) ValidEndpoints() []string {
	return []string{
		"http://192.168.1.1:9200",
		"http://127.0.0.1:9200",
		"http://localhost:9200",
		"http://localhost.localdomain:9200",
	}
}

func (c *Construct) InvalidEndpoints() []string {
	return []string{
		"http://192.168 .1.1:9200",
		"http ://127.0.0.1:9200",
		"http://:9200",
		":9200",
		"",
	}
}

func TestElasticsearchRecorder(t *testing.T) {
	rt.TestSuites(t, func() (rt.Constructor, func()) {
		c := &Construct{
			testServer:    getTestServer(),
			BaseConstruct: rt.NewBaseConstruct(),
		}
		return c, func() { c.testServer.Close() }
	})
}

func TestElasticsearchRecordURLError(t *testing.T) {
	t.Parallel()
	ctx := context.Background()
	ts := getTestServer()
	defer ts.Close()
	rec, err := elasticsearch.New(
		recorder.WithEndpoint(ts.URL),
		recorder.WithName("name"),
	)
	rec.SetTimeout(100 * time.Millisecond)
	if errors.Cause(err) != nil {
		t.Fatalf("err = (%#v); want (nil)", err)
	}

	payload := recorder.Job{
		ID:        token.NewUID(),
		Payload:   datatype.New([]datatype.DataType{}),
		IndexName: "my index",
		TypeName:  "my type",
		Time:      time.Now(),
	}
	err = rec.Ping()
	if errors.Cause(err) != nil {
		t.Fatalf("err = (%#v); want (nil)", err)
	}
	ts.Close()
	err = rec.Record(ctx, payload)
	if _, ok := errors.Cause(err).(recorder.EndpointNotAvailableError); !ok {
		t.Errorf("err = (%#v); want (recorder.EndpointNotAvailableError)", err)
	}
}

func TestElasticsearchIndexExists(t *testing.T) {
	t.Parallel()
	var host, url, port string
	indexName := "my_index"
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/_nodes/http":
			w.Write([]byte(fmt.Sprintf(sniffer, host, host, host, port, url)))
		case r.URL.Path == ("/" + indexName):
			// index exists check
			w.WriteHeader(http.StatusInternalServerError)
		case len(r.URL.Path) > 5:
			// recording
			w.Write([]byte(recording))
		case r.URL.Path == "/":
			// pinging
			w.Write([]byte(pinging))
		}
	})

	ts := httptest.NewServer(handler)
	defer ts.Close()
	url = strings.Split(ts.URL, "//")[1]
	host, port = strings.Split(url, ":")[0], strings.Split(url, ":")[1]

	rec, err := elasticsearch.New(
		recorder.WithEndpoint(ts.URL),
		recorder.WithName("name"),
		recorder.WithIndexName(indexName),
	)
	rec.SetTimeout(10 * time.Millisecond)
	if errors.Cause(err) != nil {
		t.Fatalf("err = (%#v); want (nil)", err)
	}

	err = rec.Ping()
	if errors.Cause(err) == nil {
		t.Error("err = (nil); want (error)")
	}
}

func TestElasticsearchCreateIndex(t *testing.T) {
	t.Parallel()
	var host, url, port string
	indexName := "my_index"
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/_nodes/http":
			w.Write([]byte(fmt.Sprintf(sniffer, host, host, host, port, url)))
		case r.URL.Path == ("/"+indexName) && r.Method == "HEAD":
			// index exists check
			w.WriteHeader(http.StatusNotFound)
		case r.URL.Path == ("/"+indexName) && r.Method == "PUT":
			// index creation
			w.WriteHeader(http.StatusInternalServerError)
		case len(r.URL.Path) > 5:
			// recording
			w.Write([]byte(recording))
		case r.URL.Path == "/":
			// pinging
			w.Write([]byte(pinging))
		}
	})

	ts := httptest.NewServer(handler)
	defer ts.Close()
	url = strings.Split(ts.URL, "//")[1]
	host, port = strings.Split(url, ":")[0], strings.Split(url, ":")[1]

	rec, err := elasticsearch.New(
		recorder.WithEndpoint(ts.URL),
		recorder.WithName("name"),
		recorder.WithIndexName(indexName),
	)
	rec.SetTimeout(100 * time.Millisecond)
	if errors.Cause(err) != nil {
		t.Fatalf("err = (%#v); want (nil)", err)
	}

	err = rec.Ping()
	if errors.Cause(err) == nil {
		t.Fatalf("err = (%#v); want (nil)", err)
	}
}


text:
def main(args):
    print("start dashboard", args)


text:
<input class="form-control" name="{{field.name}}-dev" id="{{field.name}}-dev" ng-model="field.value"
       ng-model-options="{ debounce: 1000 }" type="{{field.type}}" placeholder="{{field.placeholder}}"
       ng-required="{{field.required}}" title="{{field.tooltip}}" ng-readonly="field.readonly"/>


text:
package net

import (
	"sync"
	"syscall"
	"time"
)

// runtimeNano returns the current value of the runtime clock in nanoseconds.
func runtimeNano() int64

func runtime_pollServerInit()
func runtime_pollOpen(fd uintptr) (uintptr, int)
func runtime_pollClose(ctx uintptr)
func runtime_pollWait(ctx uintptr, mode int) int
func runtime_pollWaitCanceled(ctx uintptr, mode int) int
func runtime_pollReset(ctx uintptr, mode int) int
func runtime_pollSetDeadline(ctx uintptr, d int64, mode int)
func runtime_pollUnblock(ctx uintptr)

type pollDesc struct {
	runtimeCtx uintptr
}

var serverInit sync.Once

func (pd *pollDesc) Init(fd *netFD) error {
	serverInit.Do(runtime_pollServerInit)
	ctx, errno := runtime_pollOpen(uintptr(fd.sysfd))
	if errno != 0 {
		return syscall.Errno(errno)
	}
	pd.runtimeCtx = ctx
	return nil
}

func (pd *pollDesc) Close() {
	if pd.runtimeCtx == 0 {
		return
	}
	runtime_pollClose(pd.runtimeCtx)
	pd.runtimeCtx = 0
}

// Evict evicts fd from the pending list, unblocking any I/O running on fd.
func (pd *pollDesc) Evict() {
	if pd.runtimeCtx == 0 {
		return
	}
	runtime_pollUnblock(pd.runtimeCtx)
}

func (pd *pollDesc) Prepare(mode int) error {
	res := runtime_pollReset(pd.runtimeCtx, mode)
	return convertErr(res)
}

func (pd *pollDesc) PrepareRead() error {
	return pd.Prepare('r')
}

func (pd *pollDesc) PrepareWrite() error {
	return pd.Prepare('w')
}

func (pd *pollDesc) Wait(mode int) error {
	res := runtime_pollWait(pd.runtimeCtx, mode)
	return convertErr(res)
}

func (pd *pollDesc) WaitRead() error {
	return pd.Wait('r')
}

func (pd *pollDesc) WaitWrite() error {
	return pd.Wait('w')
}

func (pd *pollDesc) WaitCanceled(mode int) {
	runtime_pollWaitCanceled(pd.runtimeCtx, mode)
}

func (pd *pollDesc) WaitCanceledRead() {
	pd.WaitCanceled('r')
}

func (pd *pollDesc) WaitCanceledWrite() {
	pd.WaitCanceled('w')
}

func convertErr(res int) error {
	switch res {
	case 0:
		return nil
	case 1:
		return errClosing
	case 2:
		return errTimeout
	}
	println("unreachable: ", res)
	panic("unreachable")
}

func (fd *netFD) setDeadline(t time.Time) error {
	return setDeadlineImpl(fd, t, 'r'+'w')
}

func (fd *netFD) setReadDeadline(t time.Time) error {
	return setDeadlineImpl(fd, t, 'r')
}

func (fd *netFD) setWriteDeadline(t time.Time) error {
	return setDeadlineImpl(fd, t, 'w')
}

func setDeadlineImpl(fd *netFD, t time.Time, mode int) error {
	diff := int64(t.Sub(time.Now()))
	d := runtimeNano() + diff
	if d <= 0 && diff > 0 {
		// If the user has a deadline in the future, but the delay calculation
		// overflows, then set the deadline to the maximum possible value.
		d = 1<<63 - 1
	}
	if t.IsZero() {
		d = 0
	}
	if err := fd.incref(); err != nil {
		return err
	}
	runtime_pollSetDeadline(fd.pd.runtimeCtx, d, mode)
	fd.decref()
	return nil
}


text:
package org.avmframework;

import org.avmframework.objective.ObjectiveValue;

/**
 * A Monitor instance is used by an AVM object to keep track of the candidate solution with the best
 * objective value, the number of objective function evaluations that have taken place, and other
 * information. It is also responsible for triggering a {@link
 * org.avmframework.TerminationException} when the conditions of the search's {@link
 * org.avmframework.TerminationPolicy} have been satisfied.
 *
 * @author Phil McMinn
 */
public class Monitor {

  /** The termination policy being used by the search. */
  protected TerminationPolicy tp;

  /** The best objective value observed so far during hte search. */
  protected ObjectiveValue bestObjVal;

  /** The vector with the best objective value observed so far by the search. */
  protected Vector bestVector;

  /**
   * The number of objective function evaluations that have taken place so far. The count includes
   * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded
   * by this counter.
   */
  protected int numEvaluations;

  /**
   * The number of unique objective function evaluations that have taken place so far. If a vector
   * is evaluated more than once, this count should not increase.
   */
  protected int numUniqueEvaluations;

  /** The number of times the AVM search has been restarted. */
  protected int numRestarts;

  /** The system time (in milliseconds) that the search was started. */
  protected long startTime;

  /** The system time (in milliseconds) that the search was ended. */
  protected long endTime;

  /**
   * Constructs a Monitor instance.
   *
   * @param tp The termination policy being used by the search.
   */
  public Monitor(TerminationPolicy tp) {
    this.tp = tp;
    bestObjVal = null;
    bestVector = null;
    numEvaluations = 0;
    numUniqueEvaluations = 0;
    numRestarts = 0;
    startTime = System.currentTimeMillis();
  }

  /**
   * Gets the best objective value observed by the search so far.
   *
   * @return THe best objective value.
   */
  public ObjectiveValue getBestObjVal() {
    return bestObjVal;
  }

  /**
   * Gets the vector with the best objective value observed by the search so far.
   *
   * @return The best vector.
   */
  public Vector getBestVector() {
    return bestVector;
  }

  /**
   * Gets the number of objective function evaluations that have taken place so far. The count
   * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be
   * recorded by this counter.
   *
   * @return The number of objective function evaluations.
   */
  public int getNumEvaluations() {
    return numEvaluations;
  }

  /**
   * Gets the number of unique objective function evaluations that have taken place so far. If a
   * vector is evaluated more than once, this count should not increase.
   *
   * @return The number of unique objective function evaluations.
   */
  public int getNumUniqueEvaluations() {
    return numUniqueEvaluations;
  }

  /**
   * Get the number of times the AVM search has been restarted (following hitting a local optimum).
   *
   * @return The number of times the AVM search has been restarted.
   */
  public int getNumRestarts() {
    return numRestarts;
  }

  /**
   * Gets the running time (in milliseconds) of the search from start to finish. If the search has
   * not terminated, the value is undefined.
   *
   * @return The run time of the search.
   */
  // TODO: should this return the running time also.
  public long getRunningTime() {
    return endTime - startTime;
  }

  // TODO: Better name? No parameter.
  public void observeVector() throws TerminationException {
    tp.checkExhaustedEvaluations(this);
    tp.checkExhaustedTime(this);
    numEvaluations++;
  }

  public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal)
      throws TerminationException {
    if (bestObjVal == null || objVal.betterThan(bestObjVal)) {
      bestObjVal = objVal;
      bestVector = vector.deepCopy();
    }
    numUniqueEvaluations++;

    tp.checkFoundOptimal(this);
  }

  public void observeRestart() throws TerminationException {
    tp.checkExhaustedRestarts(this);
    tp.checkExhaustedTime(this);
    numRestarts++;
  }

  public void observeTermination() {
    endTime = System.currentTimeMillis();
  }
}


text:
import React from 'react';
import './button.css';

interface ButtonProps {
  /**
   * Is this the principal call to action on the page?
   */
  primary?: boolean;
  /**
   * What background color to use
   */
  backgroundColor?: string;
  /**
   * How large should the button be?
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Button contents
   */
  label: string;
  /**
   * Optional click handler
   */
  onClick?: () => void;
}

/**
 * Primary UI component for user interaction
 */
export const Button = ({
  primary = false,
  size = 'medium',
  backgroundColor,
  label,
  ...props
}: ButtonProps) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
      style={{ backgroundColor }}
      {...props}
    >
      {label}
    </button>
  );
};


text:
(function () {
    'use strict';

    angular.module('app').controller('SettingsCtrl', ['$scope', '$http', '$state', 'user', 'printers', function ($scope, $http, $state, user, printers) {
        $scope.cancelAll = function () {
            // TODO make request to google print API to cancel all print jobs
        };

        $scope.reset = function () {
            // TODO make request to NEW web server running on raspberry pi to restart the raspberry pi
        };

        $scope.settingsChanged = function () {
            $http.post('/api/google/settings', $scope.settings);
        };

        $scope.printers = printers;
        $scope.settings = {
            isOn: user.isOn,
            tag: user.tag,
            printerId: user.printerId
        };

        $scope.logout = function () {
            window.localStorage.clear();
            $state.go('info');
        };
    }]);

})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea coacervata Tav.

### Remarks
null


text:
class CreateImports < ActiveRecord::Migration
  def change
    create_table :imports do |t|
      t.integer :organization_id
      t.integer :user_id
      t.string :description
      t.integer :our_reference_id
      t.integer :to_warehouse_id
      t.integer :batch_id
      t.integer :quantity
      t.integer :amount
      t.integer :cost_price

      t.integer :importing_id
      t.integer :shipping_id
      t.integer :customs_id

      t.string :state
      t.timestamp :started_at
      t.timestamp :completed_at

      t.timestamps
    end
  end
end


text:
//
//  ConsumerEvaluationsModel.h
//  JianGuo
//
//  Created by apple on 17/8/11.
//  Copyright © 2017年 ningcol. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ConsumerEvaluationsModel : NSObject

/** 评价分数 */
@property (nonatomic, assign) CGFloat  score;

/** 用户id */
@property (nonatomic, assign) NSInteger  uid;

/** 用户昵称 */
@property (nonatomic, copy) NSString* nickname;

/** 评价内容 */
@property (nonatomic, copy) NSString* content;

/** 用户学校名称 */
@property (nonatomic, copy) NSString* schoolName;

/** 评价时间字符串 */
@property (nonatomic, copy) NSString* createTimeStr;

/** 头像 */
@property (nonatomic, copy) NSString* headImg;

/** 评价时间戳 */
@property (nonatomic, assign) NSInteger  createTime;

@end


text:
package cz.zcu.kiv.eeg.owlimport.gui;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import cz.zcu.kiv.eeg.owlimport.gui.dialog.FileOpenDialog;
import cz.zcu.kiv.eeg.owlimport.gui.dialog.FileSaveDialog;
import cz.zcu.kiv.eeg.owlimport.gui.model.RuleListModel;
import cz.zcu.kiv.eeg.owlimport.gui.model.SourceListModel;
import cz.zcu.kiv.eeg.owlimport.model.RuleManager;
import cz.zcu.kiv.eeg.owlimport.model.SourceManager;
import cz.zcu.kiv.eeg.owlimport.model.rules.AbstractRule;
import cz.zcu.kiv.eeg.owlimport.model.sources.AbstractSource;
import cz.zcu.kiv.eeg.owlimport.model.sources.SourceImportException;
import cz.zcu.kiv.eeg.owlimport.project.*;
import cz.zcu.kiv.eeg.owlimport.repository.RepositoryManager;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Main window of the program.
 *
 * @author Jan Smitka <jan@smitka.org>
 */
public class MainDialog {
	private JList sourceList;
	private JList ruleList;
	private JPanel rootPanel;
	private JToolBar mainToolbar;
	private JButton importOWLButton;
	private JButton exportButton;
	private JButton addRuleButton;
	private JPanel ruleOptionsPanel;
	private JButton saveProjectButton;
	private JButton loadProjectButton;
	private JButton generateVisibilityButton;
	private JButton removeRuleButton;

	private RepositoryManager repositoryManager;

	private SourceManager sourceManager;

	private RuleManager ruleManager;

	private SourceListModel sourcesModel;

	private AbstractSource selectedSource;

	private RuleListModel rulesModel;

	private AbstractRule selectedRule;

	/**
	 * Initializes the window.
	 *
	 * @param repoManager Repository manager.
	 * @param srcManager  Source manager.
	 * @param rlManager   Rule manager.
	 */
	public MainDialog(RepositoryManager repoManager, SourceManager srcManager, RuleManager rlManager) {
		sourceManager = srcManager;
		repositoryManager = repoManager;
		ruleManager = rlManager;

		initSourceList();

		initializeSourceComponentsListeners();
		initializeRuleComponentsListeners();
		initializeProjectButtonsListeners();
	}

	/**
	 * Initializes the listeners for ontology source management components.
	 */
	private void initializeSourceComponentsListeners() {
		importOWLButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				importSource();
			}
		});
		sourceList.addListSelectionListener(new ListSingleSelectionAdapter(sourceList) {
			@Override
			public void selectionSelected(int selectedIndex, ListSelectionEvent e) {
				refreshRuleList(selectedIndex);
			}

			@Override
			public void selectionCanceled(ListSelectionEvent e) {
				clearRuleList();
			}
		});
	}

	/**
	 * Initializes listeners for rule management components.
	 */
	private void initializeRuleComponentsListeners() {
		addRuleButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				addRule();
			}
		});

		removeRuleButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				removeSelectedRule();
			}
		});

		ruleList.addListSelectionListener(new ListSingleSelectionAdapter(ruleList) {
			@Override
			public void selectionSelected(int selectedIndex, ListSelectionEvent e) {
				createRuleOptionsPanel(selectedIndex);
			}

			@Override
			public void selectionCanceled(ListSelectionEvent e) {
				removeRuleOptionsPanel();
			}
		});
	}

	/**
	 * Initializes listeners for project management buttons.
	 */
	private void initializeProjectButtonsListeners() {
		exportButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				exportSources();
			}
		});

		saveProjectButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveProject();
			}
		});

		loadProjectButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				loadProject();
			}
		});

		generateVisibilityButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				generateVisibility();
			}
		});
	}

	/**
	 * Shows import source dialog and imports the source to repository.
	 */
	private void importSource() {
		ImportSourceDialog dialog = new ImportSourceDialog(this.sourceManager);
		dialog.showInCenterOf($$$getRootComponent$$$());

		if (dialog.getDialogResult() == DialogResult.OK) {
			AbstractSource source = dialog.createSource();
			try {
				repositoryManager.importSource(source);
				sourceManager.addSource(source);
			} catch (SourceImportException ex) {
				handleError(ex);
			}
		}
	}

	/**
	 * Clears the rule list.
	 */
	private void clearRuleList() {
		selectedSource = null;
		setRuleListModel(null);
	}

	/**
	 * Populates the rule list from currently selected source.
	 *
	 * @param selectedIndex Selected index.
	 */
	private void refreshRuleList(int selectedIndex) {
		if (rulesModel != null) {
			rulesModel.detach();
		}

		selectedSource = sourcesModel.getElementAt(selectedIndex);
		rulesModel = new RuleListModel(selectedSource);
		setRuleListModel(rulesModel);
	}

	/**
	 * Shows add rule dialog and adds the new rule to the currently selected source.
	 */
	private void addRule() {
		if (selectedSource == null) {
			return;
		}

		AddRuleDialog dialog = new AddRuleDialog(ruleManager);
		dialog.showInCenterOf($$$getRootComponent$$$());

		if (dialog.getDialogResult() == DialogResult.OK) {
			AbstractRule rule = dialog.createRule();
			selectedSource.addRule(rule);
		}
	}

	/**
	 * Creates rule options panel for rule at specified index.
	 *
	 * @param selectedIndex Selected index.
	 */
	private void createRuleOptionsPanel(int selectedIndex) {
		ruleOptionsPanel.removeAll();

		selectedRule = rulesModel.getElementAt(selectedIndex);
		IRuleParamsComponent opt = selectedRule.getGuiComponent();
		JLabel title = new JLabel(selectedRule.getTitle());
		title.setBorder(new EmptyBorder(0, 0, 10, 0));
		ruleOptionsPanel.add(title, BorderLayout.NORTH);
		ruleOptionsPanel.add(opt.getPanel(), BorderLayout.CENTER);
		opt.refresh();
		ruleOptionsPanel.revalidate();
		getFrame().pack();
		getFrame().repaint();

		removeRuleButton.setEnabled(true);
	}

	/**
	 * Removes the rule options panel.
	 */
	private void removeRuleOptionsPanel() {
		ruleOptionsPanel.removeAll();
		ruleOptionsPanel.revalidate();
		getFrame().repaint();

		selectedRule = null;
		removeRuleButton.setEnabled(false);
	}

	/**
	 * Exports currently defined sources and their rules.
	 */
	private void exportSources() {
		FileSaveDialog dialog = new FileSaveDialog("export");
		dialog.addExtensionFilter("Turtle Files", new String[]{"ttl"}, true);

		if (dialog.showDialog($$$getRootComponent$$$()) == FileSaveDialog.CONFIRM_OPTION) {
			Exporter export = new Exporter(dialog.getSelectedFile());
			try {
				export.writeSources(sourceManager.getSources());
			} catch (ExportException ex) {
				handleError(ex);
			}
		}
	}

	/**
	 * Saves project.
	 */
	private void saveProject() {
		FileSaveDialog dialog = new FileSaveDialog("export");
		dialog.addExtensionFilter("XML Files", new String[]{"xml"}, true);

		if (dialog.showDialog($$$getRootComponent$$$()) == FileSaveDialog.CONFIRM_OPTION) {
			try {
				sourceManager.saveProject(dialog.getSelectedFile());
			} catch (ProjectWriteException ex) {
				handleError(ex);
			}
		}
	}

	/**
	 * Loads previously saved projects.
	 */
	private void loadProject() {
		FileOpenDialog dialog = new FileOpenDialog("open");
		dialog.addExtensionFilter("XML Files", new String[]{"xml"}, true);

		if (dialog.showDialog($$$getRootComponent$$$()) == FileOpenDialog.CONFIRM_OPTION) {
			try {
				sourceManager.loadProject(dialog.getSelectedFile(), ruleManager);
				repositoryManager.importSources(sourceManager.getSources());
			} catch (ProjectReadException | SourceImportException ex) {
				handleError(ex);
			}
		}
	}

	/**
	 * Asks user for file path and generates visibility file.
	 */
	private void generateVisibility() {
		FileSaveDialog dialog = new FileSaveDialog("save");
		dialog.addExtensionFilter("N-Triples Files", new String[]{"nt"}, true);

		if (dialog.showDialog($$$getRootComponent$$$()) == FileSaveDialog.CONFIRM_OPTION) {
			VisibilityGenerator visibilityGenerator = new VisibilityGenerator(dialog.getSelectedFile());
			try {
				visibilityGenerator.generateVisibility(sourceManager.getSources());
			} catch (ExportException ex) {
				handleError(ex);
			}
		}
	}

	/**
	 * Removes the currently selected rule.
	 */
	private void removeSelectedRule() {
		if (selectedRule != null) {
			selectedSource.removeRule(selectedRule);
		}
	}

	/**
	 * Handles error and shows an error message to user.
	 *
	 * @param e Exception.
	 */
	private void handleError(Exception e) {
		JOptionPane.showMessageDialog($$$getRootComponent$$$(), formatErrorMessage(e), "Error", JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Formats the exception message.
	 *
	 * @param e Exception.
	 * @return String containing exception message and messages of all exception causes.
	 */
	private String formatErrorMessage(Exception e) {
		StringBuilder str = new StringBuilder(e.getMessage());
		Throwable cause = e.getCause();
		while (cause != null) {
			str.append(System.getProperty("line.separator"));
			str.append("Caused by: ");
			str.append(cause.getMessage());
			cause = cause.getCause();
		}

		return str.toString();
	}

	/**
	 * Gets the window frame.
	 *
	 * @return Window frame.
	 */
	private JFrame getFrame() {
		return (JFrame) rootPanel.getTopLevelAncestor();
	}

	/**
	 * Sets the rule list model and enables/disables addRuleButton and removeRuleButton.
	 *
	 * @param model
	 */
	private void setRuleListModel(ListModel<AbstractRule> model) {
		if (model == null) {
			ruleList.setModel(new DefaultListModel());
		} else {
			ruleList.setModel(model);
		}
		addRuleButton.setEnabled(model != null);
		removeRuleButton.setEnabled(model != null);
	}

	/**
	 * Initializes the source list.
	 */
	private void initSourceList() {
		sourcesModel = new SourceListModel(sourceManager);
		sourceList.setModel(sourcesModel);
	}

	/**
	 * Runs the application.
	 *
	 * @param repoManager Repository manager.
	 * @param srcManager  Source manager.
	 * @param rlManager   Rule manager.
	 */
	public static void run(final RepositoryManager repoManager, final SourceManager srcManager, final RuleManager rlManager) {
		initLookAndFeel();

		JFrame frame = new JFrame("KIM-OWLImport");
		ImageIcon icon = new ImageIcon(MainDialog.class.getResource("icons/kim-owlimport.png"));
		frame.setIconImage(icon.getImage());
		frame.setContentPane(new MainDialog(repoManager, srcManager, rlManager).rootPanel);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);

		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				repoManager.close();
			}
		});
	}

	/**
	 * Initializes the application system look and feel.
	 */
	private static void initLookAndFeel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception ex) {
			// ignore the missing system look and feel - it's just the look and feel, nothing groundbreaking
		}
	}

	{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
		$$$setupUI$$$();
	}

	/**
	 * Method generated by IntelliJ IDEA GUI Designer
	 * >>> IMPORTANT!! <<<
	 * DO NOT edit this method OR call it in your code!
	 *
	 * @noinspection ALL
	 */
	private void $$$setupUI$$$() {
		rootPanel = new JPanel();
		rootPanel.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1));
		mainToolbar = new JToolBar();
		mainToolbar.setFloatable(false);
		mainToolbar.setMargin(new Insets(0, 3, 0, 0));
		mainToolbar.setRollover(true);
		mainToolbar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);
		rootPanel.add(mainToolbar, new GridConstraints(0, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 20), null, 0, false));
		loadProjectButton = new JButton();
		loadProjectButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/open.png")));
		loadProjectButton.setText("Load Project");
		mainToolbar.add(loadProjectButton);
		final JToolBar.Separator toolBar$Separator1 = new JToolBar.Separator();
		mainToolbar.add(toolBar$Separator1);
		exportButton = new JButton();
		exportButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/export.png")));
		exportButton.setText("Export");
		mainToolbar.add(exportButton);
		generateVisibilityButton = new JButton();
		generateVisibilityButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/visibility.png")));
		generateVisibilityButton.setText("Generate Visibility");
		mainToolbar.add(generateVisibilityButton);
		final JToolBar.Separator toolBar$Separator2 = new JToolBar.Separator();
		mainToolbar.add(toolBar$Separator2);
		saveProjectButton = new JButton();
		saveProjectButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/save.png")));
		saveProjectButton.setText("Save Project");
		mainToolbar.add(saveProjectButton);
		final JScrollPane scrollPane1 = new JScrollPane();
		rootPanel.add(scrollPane1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(177, 128), null, 0, false));
		sourceList = new JList();
		sourceList.setSelectionMode(0);
		scrollPane1.setViewportView(sourceList);
		final JScrollPane scrollPane2 = new JScrollPane();
		rootPanel.add(scrollPane2, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(199, 128), null, 0, false));
		ruleList = new JList();
		ruleList.setSelectionMode(0);
		scrollPane2.setViewportView(ruleList);
		final JScrollPane scrollPane3 = new JScrollPane();
		rootPanel.add(scrollPane3, new GridConstraints(1, 2, 2, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(500, 300), null, 0, false));
		ruleOptionsPanel = new JPanel();
		ruleOptionsPanel.setLayout(new BorderLayout(0, 0));
		scrollPane3.setViewportView(ruleOptionsPanel);
		ruleOptionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), null));
		final JToolBar toolBar1 = new JToolBar();
		toolBar1.setFloatable(false);
		rootPanel.add(toolBar1, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 20), null, 0, false));
		addRuleButton = new JButton();
		addRuleButton.setEnabled(false);
		addRuleButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/add.png")));
		addRuleButton.setText("Add Rule");
		toolBar1.add(addRuleButton);
		removeRuleButton = new JButton();
		removeRuleButton.setEnabled(false);
		removeRuleButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/remove.png")));
		removeRuleButton.setText("Remove Rule");
		toolBar1.add(removeRuleButton);
		final JToolBar toolBar2 = new JToolBar();
		toolBar2.setFloatable(false);
		rootPanel.add(toolBar2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 20), null, 0, false));
		importOWLButton = new JButton();
		importOWLButton.setIcon(new ImageIcon(getClass().getResource("/cz/zcu/kiv/eeg/owlimport/gui/icons/add.png")));
		importOWLButton.setText("Import OWL");
		toolBar2.add(importOWLButton);
	}

	/**
	 * @noinspection ALL
	 */
	public JComponent $$$getRootComponent$$$() {
		return rootPanel;
	}
}


text:
<?php
INCLUDE_ONCE('__module_init.php');
INCLUDE_ONCE('source/phenegade_functions.php');
$module_path	= 'modules/phenewall/';

$dropfile_path	= $argv[1];
$dropfile_payload	= unserialize(file_get_contents($dropfile_path));
$master_controller_process_id = $dropfile_payload['master_controller_process_id'];
phenegadeLog('Phenewall Begin');

$user_name		= $dropfile_payload['user_name'];
$user_id		= $dropfile_payload['user_id'];
$terminal_echo	= $dropfile_payload['terminal_echo'];

showWall();

phenSay('Do you want to write on the wall? [y/N]');
$input 	= phenReadInput();
phenegadeLog('Do you want to write on the wall = ' . $input);
if( strtolower($input) == 'y'  )
{
	phenSay("Tag it up! [ ");
	$my_input	= phenReadInput();
	$my_input	= "\n\r--- [ " . $user_name . " ] - " . $my_input . "\n\r";
	if( phenFileAppend($module_path . 'wall.asc', $my_input) )
	{
		phenSay('Done!');
		showWall();
	}
}
phenPressAnyKey();

function showWall()
{
	global $module_path;

	clearScreen();

	phenShowView($module_path . 'pre.ans', true);
	phenShowView($module_path . 'wall.asc', true);
	NextLine();
	nextLine();
}
?>


text:
void bga_writeregister(uint16_t index, uint16_t value);
///Reads a value from the bga
uint16_t bga_readregister(uint16_t index);
///Sets video mode
void bga_setmode(unsigned int width, unsigned int height, unsigned int bitdepth, int linearframebuffer, int clearvideomemory);
///Can we use the BGA?
int bga_isavalable();
///Initialises the BGA
int bga_init();
///Gets the Framebuffer
framebuffer_t bga_getFramebuffer();
#endif


text:
#include "App.h"
#include <signal.h>
/*#include <sys/wait.h>*/

Application::Application(int arg, char ** args) : AbstractApp(arg, args)
{

    if (!processArguments())
        _exit(1);

    startIdesk();
}

Application::~Application()
{
    delete container;
}

bool Application::processArguments()
{
    bool returnBool = true;
    string tmpStr;

    for (int i = 0; i < argc; i++)
    {
        tmpStr = argv[i];
        if (tmpStr == "-h" || tmpStr == "-v" || tmpStr == "--help" || tmpStr == "--usage")
        {
            cerr << "Idesk " << VERSION << endl << "==============\n"
                 << "Default Prefix " << DEFAULT_PREFIX << endl << "==============\n"
                 << "Further documentation available at:"
                 << " http://idesk.sourceforge.net\n"
                 << "\nRemember to create your ~/.config/idesktop/ideskrc file,"
                 << " and put .lnk icons in the ~/.config/idesktop\ndirectory.\n";
            returnBool = false;
        }
    }
    return returnBool;
}

void signalhandler(int sig){
	if(sig == SIGCHLD){
	  int status;
	  waitpid(-1, &status, WNOHANG|WUNTRACED);
	}else{
	  _exit(1);
	}
}

void Application::startIdesk()
{
    // setup signals
    signal(SIGSEGV, signalhandler);
    signal(SIGFPE, signalhandler);
    signal(SIGTERM, signalhandler);
    signal(SIGINT, signalhandler);
    signal(SIGUSR1, signalhandler);
    signal(SIGUSR2, signalhandler);
    signal(SIGHUP, signalhandler);
    signal(SIGCHLD, signalhandler);

    container = new XDesktopContainer(this);
    if (!container)
                cerr << "container is NULL\n";
    container->run();
}

void Application::restartIdesk()
{
    container->saveState();
    cerr << "restarting idesk\n";
    delete container;

    //startIdesk();
    //container->create();
    //container->run();

    execvp( argv[0], argv );
}