text:
require 'set'

module Que
  Listener::MESSAGE_FORMATS[:job_available] =
    {
      queue:    String,
      id:       Integer,
      run_at:   TIME_REGEX,
      priority: Integer,
    }

  SQL[:clean_lockers] =
    %{
      DELETE FROM public.que_lockers
      WHERE pid = pg_backend_pid()
      OR NOT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = public.que_lockers.pid)
    }

  SQL[:register_locker] =
    %{
      INSERT INTO public.que_lockers (pid, worker_count, worker_priorities, ruby_pid, ruby_hostname, listening, queues)
      VALUES (pg_backend_pid(), $1::integer, $2::integer[], $3::integer, $4::text, $5::boolean, $6::text[])
    }

  class Locker
    attr_reader :thread, :workers, :job_buffer, :locks

    MESSAGE_RESOLVERS = {}
    RESULT_RESOLVERS  = {}

    MESSAGE_RESOLVERS[:job_available] =
      -> (messages) {
        metajobs = messages.map { |key| Metajob.new(key) }
        push_jobs(lock_jobs(job_buffer.accept?(metajobs)))
      }

    RESULT_RESOLVERS[:job_finished] =
      -> (messages) { finish_jobs(messages.map{|m| m.fetch(:metajob)}) }

    DEFAULT_POLL_INTERVAL       = 5.0
    DEFAULT_WAIT_PERIOD         = 50
    DEFAULT_MINIMUM_BUFFER_SIZE = 2
    DEFAULT_MAXIMUM_BUFFER_SIZE = 8
    DEFAULT_WORKER_PRIORITIES   = [10, 30, 50, nil, nil, nil].freeze

    def initialize(
      queues:              [Que.default_queue],
      connection_url:      nil,
      listen:              true,
      poll:                true,
      poll_interval:       DEFAULT_POLL_INTERVAL,
      wait_period:         DEFAULT_WAIT_PERIOD,
      maximum_buffer_size: DEFAULT_MAXIMUM_BUFFER_SIZE,
      minimum_buffer_size: DEFAULT_MINIMUM_BUFFER_SIZE,
      worker_priorities:   DEFAULT_WORKER_PRIORITIES,
      on_worker_start:     nil
    )

      # Sanity-check all our arguments, since some users may instantiate Locker
      # directly.
      Que.assert [TrueClass, FalseClass], listen
      Que.assert [TrueClass, FalseClass], poll

      Que.assert Numeric, poll_interval
      Que.assert Numeric, wait_period

      Que.assert Array, worker_priorities
      worker_priorities.each { |p| Que.assert([Integer, NilClass], p) }

      # We use a JobBuffer to track jobs and pass them to workers, and a
      # ResultQueue to receive messages from workers.
      @job_buffer = JobBuffer.new(
        maximum_size: maximum_buffer_size,
        minimum_size: minimum_buffer_size,
        priorities:   worker_priorities.uniq,
      )

      @result_queue = ResultQueue.new

      @stop = false

      Que.internal_log :locker_instantiate, self do
        {
          queues:              queues,
          listen:              listen,
          poll:                poll,
          poll_interval:       poll_interval,
          wait_period:         wait_period,
          maximum_buffer_size: maximum_buffer_size,
          minimum_buffer_size: minimum_buffer_size,
          worker_priorities:   worker_priorities,
        }
      end

      # Local cache of which advisory locks are held by this connection.
      @locks = Set.new

      @queue_names = queues.is_a?(Hash) ? queues.keys : queues
      @wait_period = wait_period.to_f / 1000 # Milliseconds to seconds.

      @workers =
        worker_priorities.map do |priority|
          Worker.new(
            priority:       priority,
            job_buffer:     @job_buffer,
            result_queue:   @result_queue,
            start_callback: on_worker_start,
          )
        end

      # To prevent race conditions, let every worker get into a ready state
      # before starting up the locker thread.
      loop do
        break if job_buffer.waiting_count == workers.count
        sleep 0.001
      end

      # If we weren't passed a specific connection_url, borrow a connection from
      # the pool and derive the connection string from it.
      connection_args =
        if connection_url
          uri = URI.parse(connection_url)

          opts =
            {
              host:     uri.host,
              user:     uri.user,
              password: uri.password,
              port:     uri.port || 5432,
              dbname:   uri.path[1..-1],
            }

          if uri.query
            opts.merge!(Hash[uri.query.split("&").map{|s| s.split('=')}.map{|a,b| [a.to_sym, b]}])
          end

          opts
        else
          Que.pool.checkout do |conn|
            c = conn.wrapped_connection

            {
              host:     c.host,
              user:     c.user,
              password: c.pass,
              port:     c.port,
              dbname:   c.db,
            }
          end
        end

      @connection = Que::Connection.wrap(PG::Connection.open(connection_args))

      @thread =
        Thread.new do
          # An error causing this thread to exit is a bug in Que, which we want
          # to know about ASAP, so propagate the error if it happens.
          Thread.current.abort_on_exception = true

          # Give this thread priority, so it can promptly respond to NOTIFYs.
          Thread.current.priority = 1

          begin
            unless connection_args.has_key?(:application_name)
              @connection.execute(
                "SELECT set_config('application_name', $1, false)",
                ["Que Locker: #{@connection.backend_pid}"]
              )
            end

            Poller.setup(@connection)

            @listener =
              if listen
                Listener.new(connection: @connection)
              end

            @pollers =
              if poll
                queues.map do |queue, interval|
                  Poller.new(
                    connection:    @connection,
                    queue:         queue,
                    poll_interval: interval || poll_interval,
                  )
                end
              end

            work_loop
          ensure
            @connection.wrapped_connection.close
          end
        end
    end

    def stop!
      stop; wait_for_stop
    end

    def stop
      @job_buffer.stop
      @stop = true
    end

    def stopping?
      @stop
    end

    def wait_for_stop
      @thread.join
    end

    private

    attr_reader :connection, :pollers

    def work_loop
      Que.log(
        level: :debug,
        event: :locker_start,
        queues: @queue_names,
      )

      Que.internal_log :locker_start, self do
        {
          backend_pid: connection.backend_pid,
          worker_priorities: workers.map(&:priority),
          pollers: pollers && pollers.map { |p| [p.queue, p.poll_interval] }
        }
      end

      begin
        @listener.listen if @listener

        startup

        {} while cycle

        Que.log(
          level: :debug,
          event: :locker_stop,
        )

        shutdown
      ensure
        connection.execute :clean_lockers

        @listener.unlisten if @listener
      end
    end

    def startup
      # A previous locker that didn't exit cleanly may have left behind
      # a bad locker record, so clean up before registering.
      connection.execute :clean_lockers
      connection.execute :register_locker, [
        @workers.count,
        "{#{@workers.map(&:priority).map{|p| p || 'NULL'}.join(',')}}",
        Process.pid,
        CURRENT_HOSTNAME,
        !!@listener,
        "{\"#{@queue_names.join('","')}\"}",
      ]
    end

    def cycle
      # Poll at the start of a cycle, so that when the worker starts up we can
      # load up the queue with jobs immediately.
      poll

      # If we got the stop call while we were polling, break before going to
      # sleep.
      return if @stop

      # The main sleeping part of the cycle. If this is a listening locker, this
      # is where we wait for notifications.
      wait

      # Manage any job output we got while we were sleeping.
      handle_results

      # If we haven't gotten the stop signal, cycle again.
      !@stop
    end

    def shutdown
      unlock_jobs(@job_buffer.clear)
      wait_for_shutdown
      handle_results
    end

    def wait_for_shutdown
      @workers.each(&:wait_until_stopped)
    end

    def poll
      # Only poll when there are pollers to use (that is, when polling is
      # enabled).
      return unless pollers

      # Figure out what job priorities we have to fill.
      priorities = job_buffer.available_priorities

      # Only poll when there are workers ready for jobs.
      return if priorities.empty?

      all_metajobs = []

      pollers.each do |poller|
        Que.internal_log(:locker_polling, self) {
          {
            priorities: priorities,
            held_locks: @locks.to_a,
            queue: poller.queue,
          }
        }

        if metajobs = poller.poll(priorities: priorities, held_locks: @locks)
          metajobs.sort!
          all_metajobs.concat(metajobs)

          # Update the desired priorities list to take the priorities that we
          # just retrieved into account.
          metajobs.each do |metajob|
            job_priority = metajob.job.fetch(:priority)

            priorities.each do |priority, count|
              if job_priority <= priority
                new_priority = count - 1

                if new_priority <= 0
                  priorities.delete(priority)
                else
                  priorities[priority] = new_priority
                end

                break
              end
            end
          end

          break if priorities.empty?
        end
      end

      all_metajobs.each { |metajob| mark_id_as_locked(metajob.id) }
      push_jobs(all_metajobs)
    end

    def wait
      if l = @listener
        l.wait_for_grouped_messages(@wait_period).each do |type, messages|
          if resolver = MESSAGE_RESOLVERS[type]
            instance_exec messages, &resolver
          else
            raise Error, "Unexpected message type: #{type.inspect}"
          end
        end
      else
        sleep(@wait_period)
      end
    end

    def handle_results
      messages_by_type =
        @result_queue.clear.group_by{|r| r.fetch(:message_type)}

      messages_by_type.each do |type, messages|
        if resolver = RESULT_RESOLVERS[type]
          instance_exec messages, &resolver
        else
          raise Error, "Unexpected result type: #{type.inspect}"
        end
      end
    end

    def lock_jobs(metajobs)
      metajobs.reject! { |m| @locks.include?(m.id) }
      return metajobs if metajobs.empty?

      ids = metajobs.map { |m| m.id.to_i }

      Que.internal_log :locker_locking, self do
        {
          backend_pid: connection.backend_pid,
          ids:         ids,
        }
      end

      jobs =
        connection.execute \
          <<-SQL
            WITH jobs AS (SELECT * FROM que_jobs WHERE id IN (#{ids.join(', ')}))
            SELECT * FROM jobs WHERE pg_try_advisory_lock(id)
          SQL

      jobs_by_id = {}

      jobs.each do |job|
        id = job.fetch(:id)
        mark_id_as_locked(id)
        jobs_by_id[id] = job
      end

      metajobs.keep_if do |metajob|
        if job = jobs_by_id[metajob.id]
          metajob.set_job(job)
          true
        else
          false
        end
      end
    end

    def push_jobs(metajobs)
      return if metajobs.empty?

      # First check that the jobs are all still visible/available in the DB.
      ids = metajobs.map(&:id)

      verified_ids =
        connection.execute(
          <<-SQL
            SELECT id
            FROM public.que_jobs
            WHERE finished_at IS NULL
              AND expired_at IS NULL
              AND id IN (#{ids.join(', ')})
          SQL
        ).map{|h| h[:id]}.to_set

      good, bad = metajobs.partition{|mj| verified_ids.include?(mj.id)}

      # Need to unlock any low-importance jobs the new ones may displace.
      if displaced = @job_buffer.push(*good)
        bad.concat(displaced)
      end

      unlock_jobs(bad)
    end

    def finish_jobs(metajobs)
      unlock_jobs(metajobs)
    end

    def unlock_jobs(metajobs)
      return if metajobs.empty?

      # Unclear how untrusted input would get passed to this method, but since
      # we need string interpolation here, make sure we only have integers.
      ids = metajobs.map { |job| job.id.to_i }

      Que.internal_log :locker_unlocking, self do
        {
          backend_pid: connection.backend_pid,
          ids:         ids,
        }
      end

      values = ids.join('), (')

      results =
        connection.execute \
          "SELECT pg_advisory_unlock(v.i) FROM (VALUES (#{values})) v (i)"

      results.each do |result|
        Que.assert(result.fetch(:pg_advisory_unlock)) do
          [
            "Tried to unlock a job we hadn't locked!",
            results.inspect,
            ids.inspect,
          ].join(' ')
        end
      end

      ids.each do |id|
        Que.assert(@locks.delete?(id)) do
          "Tried to remove a local lock that didn't exist!: #{id}"
        end
      end
    end

    def mark_id_as_locked(id)
      Que.assert(@locks.add?(id)) do
        "Tried to lock a job that was already locked: #{id}"
      end
    end
  end
end


text:
<?php

namespace PhpSsrs\ReportingService2006;

class SetCacheOptionsResponse
{

  /**
   *
   * @access public
   */
  public function __construct()
  {

  }

}

redpajama_set_name: RedPajamaGithub


text:
namespace gofxmath
{
	float Infinity()
	{
		return std::numeric_limits<float>::infinity();
	}

	float Epsilon()
	{
		return std::numeric_limits<float>::epsilon();
	}

	float FloatMax()
	{
		return std::numeric_limits<float>::max();
	}
}


text:
Before running the script, ensure that virt-install is available on the system.

`./build_bpf_demo.sh -n bpf-demo -k bpf_demo.ks.erb`

After setting up the initial VM, log in (the default password is 'iovisor')
and determine the DHCP IP. SSH to this IP as root.

To set up a kernel with the right options, run `bpf-kernel-setup`.

```
[root@bpf-demo ~]# bpf-kernel-setup
Cloning into 'net-next'...
```
After pulling the net-next branch, the kernel config menu should pop up. Ensure
that the below settings are proper.
```
General setup --->
  [*] Enable bpf() system call
Networking support --->
  Networking options --->
    QoS and/or fair queueing --->
      <M> BPF-based classifier
      <M> BPF based action
    [*] enable BPF Just In Time compiler
```
Once the .config is saved, the build will proceed and install the resulting
kernel. This kernel has updated userspace headers (e.g. the bpf() syscall) which
install into /usr/local/include...proper packaging for this will be
distro-dependent.

Next, run `bpf-llvm-setup` to pull and compile LLVM with BPF support enabled.
```
[root@bpf-demo ~]# bpf-llvm-setup
Cloning into 'llvm'...
```
The resulting libraries will be installed into /opt/local/llvm.

Next, reboot into the new kernel, either manually or by using the kexec helper.
```
[root@bpf-demo ~]# kexec-4.1.0-rc1+
Connection to 192.168.122.247 closed by remote host.
Connection to 192.168.122.247 closed.
```

Reconnect and run the final step, building and testing bcc.
```
[root@bpf-demo ~]# bcc-setup
Cloning into 'bcc'...
...
Linking CXX shared library libcc.so
[100%] Built target bcc
...
Running tests...
Test project /root/bcc/build
    Start 1: py_test1
1/4 Test #1: py_test1 .........................   Passed    0.24 sec
    Start 2: py_test2
2/4 Test #2: py_test2 .........................   Passed    0.53 sec
    Start 3: py_trace1
3/4 Test #3: py_trace1 ........................   Passed    0.09 sec
    Start 4: py_trace2
4/4 Test #4: py_trace2 ........................   Passed    1.06 sec

100% tests passed, 0 tests failed out of 4
```


text:
package testdata

import (
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"path"
	"runtime"
)

var certPath string

func init() {
	_, filename, _, ok := runtime.Caller(0)
	if !ok {
		panic("Failed to get current frame")
	}

	certPath = path.Dir(filename)
}

// GetCertificatePaths returns the paths to certificate and key
func GetCertificatePaths() (string, string) {
	return path.Join(certPath, "cert.pem"), path.Join(certPath, "priv.key")
}

// GetTLSConfig returns a tls config for quic.clemente.io
func GetTLSConfig() *tls.Config {
	cert, err := tls.LoadX509KeyPair(GetCertificatePaths())
	if err != nil {
		panic(err)
	}
	return &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
}

// AddRootCA adds the root CA certificate to a cert pool
func AddRootCA(certPool *x509.CertPool) {
	caCertPath := path.Join(certPath, "ca.pem")
	caCertRaw, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		panic(err)
	}
	if ok := certPool.AppendCertsFromPEM(caCertRaw); !ok {
		panic("Could not add root ceritificate to pool.")
	}
}

// GetRootCA returns an x509.CertPool containing (only) the CA certificate
func GetRootCA() *x509.CertPool {
	pool := x509.NewCertPool()
	AddRootCA(pool)
	return pool
}


text:
<?php

namespace app\controllers;

use Yii;
use app\models\PtypemoneySw;
use app\models\PtypemoneyswSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PtypemoneyswController implements the CRUD actions for PtypemoneySw model.
 */
class PtypemoneyswController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all PtypemoneySw models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PtypemoneyswSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PtypemoneySw model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new PtypemoneySw model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PtypemoneySw();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->code]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing PtypemoneySw model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->code]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PtypemoneySw model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PtypemoneySw model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return PtypemoneySw the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PtypemoneySw::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M24,26V8H36V26ZM16,36 L10,15.85V8H13V16.15L18.25,33H36V36ZM16,42V39H36V42Z"/>
</vector>


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Crud\Helper\Grid\Pug;

use Vein\Core\Crud\Grid,
    Vein\Core\Crud\Grid\Column;

/**
 * Class grid columns helper
 *
 * @category   Vein\Core
 * @package    Crud
 * @subpackage Helper
 */
class ColumnsHead extends BaseHelper
{
	/**
	 * Generates grid table colums head
	 *
	 * @param \Vein\Core\Crud\Grid $grid
     *
     * @return string
	 */
	static public function _(Grid $grid)
	{
        $code = '
		        thead
		            tr';

        foreach ($grid->getColumns() as $column) {
            if ($column instanceof Column) {
                /*$columnCode = '
                            th(style=\'width: '.$column->getWidth().') ';*/
                $columnCode = '
		                th ';
                if ($column->isHidden()) {
                    $columnCode .= '';
                } else {
                    $columnCode .= $column->getTitle();
                }
            } else {
                $columnCode = '
		                th';
            }
            $code .= $columnCode;
        }

        return $code;
	}
}


text:
using System.Web.Mvc;

namespace CarService.Web.App_Start
{
    public static class ViewEnginesConfig
    {
        public static void RegisterViewEngines()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
        }
    }
}


text:
p_node_t detectLoop(const p_node_t& head) {
  if (head == nullptr || head->next == nullptr) return nullptr;
  if (head->next == head) return head;

  auto pFast = head->next->next, pSlow = head->next;

  while (pFast != nullptr && pFast->next != nullptr) {
    if (pFast == pSlow) {
      // found loop, start from head again
      pFast = head;
      while (pFast != pSlow) {
        pFast = pFast->next;
        pSlow = pSlow->next;
      }

      return pSlow;
    }

    pSlow = pSlow->next;
    pFast = pFast->next->next;
  }

  return nullptr;
}


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

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.flowable.app.domain.editor.AbstractModel;
import org.flowable.app.domain.editor.Model;
import org.flowable.app.domain.editor.ModelHistory;
import org.flowable.app.service.api.ModelService;
import org.flowable.app.service.exception.BadRequestException;
import org.flowable.app.service.exception.BaseModelerRestException;
import org.flowable.app.service.exception.InternalServerErrorException;
import org.flowable.bpmn.model.BpmnModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author jbarrez
 */
public class AbstractModelBpmnResource {

  private final Logger log = LoggerFactory.getLogger(AbstractModelBpmnResource.class);

  @Autowired
  protected ModelService modelService;

  public void getProcessModelBpmn20Xml(HttpServletResponse response, String processModelId) throws IOException {

    if (processModelId == null) {
      throw new BadRequestException("No process model id provided");
    }

    Model model = modelService.getModel(processModelId);
    generateBpmn20Xml(response, model);
  }

  public void getHistoricProcessModelBpmn20Xml(HttpServletResponse response, String processModelId, String processModelHistoryId) throws IOException {

    if (processModelId == null) {
      throw new BadRequestException("No process model id provided");
    }

    ModelHistory historicModel = modelService.getModelHistory(processModelId, processModelHistoryId);
    generateBpmn20Xml(response, historicModel);
  }

  protected void generateBpmn20Xml(HttpServletResponse response, AbstractModel model) {
    String name = model.getName().replaceAll(" ", "_");
    response.setHeader("Content-Disposition", "attachment; filename=" + name + ".bpmn20.xml");
    if (model.getModelEditorJson() != null) {
      try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("application/xml");

        BpmnModel bpmnModel = modelService.getBpmnModel(model);
        byte[] xmlBytes = modelService.getBpmnXML(bpmnModel);
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes));

        byte[] buffer = new byte[8096];
        while (true) {
          int count = in.read(buffer);
          if (count == -1) {
            break;
          }
          servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();

      } catch (BaseModelerRestException e) {
        throw e;

      } catch (Exception e) {
        log.error("Could not generate BPMN 2.0 XML", e);
        throw new InternalServerErrorException("Could not generate BPMN 2.0 xml");
      }
    }
  }
}


text:
package org.apache.hyracks.storage.am.lsm.common.api;

import java.util.List;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.replication.IReplicationJob.ReplicationOperation;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.api.IIndex;
import org.apache.hyracks.storage.am.common.api.IIndexCursor;
import org.apache.hyracks.storage.am.common.api.IIndexOperationContext;
import org.apache.hyracks.storage.am.common.api.IModificationOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchPredicate;
import org.apache.hyracks.storage.am.common.api.IndexException;
import org.apache.hyracks.storage.am.lsm.common.impls.LSMHarness;

/**
 * Methods to be implemented by an LSM index, which are called from {@link LSMHarness}.
 * The implementations of the methods below should be thread agnostic.
 * Synchronization of LSM operations like updates/searches/flushes/merges are
 * done by the {@link LSMHarness}. For example, a flush() implementation should only
 * create and return the new on-disk component, ignoring the fact that
 * concurrent searches/updates/merges may be ongoing.
 */
public interface ILSMIndex extends IIndex {

    void deactivate(boolean flushOnExit) throws HyracksDataException;

    @Override
    ILSMIndexAccessor createAccessor(IModificationOperationCallback modificationCallback,
            ISearchOperationCallback searchCallback) throws HyracksDataException;

    ILSMOperationTracker getOperationTracker();

    ILSMIOOperationScheduler getIOScheduler();

    ILSMIOOperationCallback getIOOperationCallback();

    /**
     * components with lower indexes are newer than components with higher index
     */
    List<ILSMDiskComponent> getImmutableComponents();

    boolean isPrimaryIndex();

    void modify(IIndexOperationContext ictx, ITupleReference tuple) throws HyracksDataException, IndexException;

    void search(ILSMIndexOperationContext ictx, IIndexCursor cursor, ISearchPredicate pred)
            throws HyracksDataException, IndexException;

    void scheduleFlush(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback) throws HyracksDataException;

    ILSMDiskComponent flush(ILSMIOOperation operation) throws HyracksDataException, IndexException;

    void scheduleMerge(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
            throws HyracksDataException, IndexException;

    ILSMDiskComponent merge(ILSMIOOperation operation) throws HyracksDataException, IndexException;

    void addDiskComponent(ILSMDiskComponent index) throws HyracksDataException;

    void subsumeMergedComponents(ILSMDiskComponent newComponent, List<ILSMComponent> mergedComponents)
            throws HyracksDataException;

    void changeMutableComponent();

    void changeFlushStatusForCurrentMutableCompoent(boolean needsFlush);

    boolean hasFlushRequestForCurrentMutableComponent();

    /**
     * Populates the context's component holder with a snapshot of the components involved in the operation.
     *
     * @param ctx
     *            - the operation's context
     * @throws HyracksDataException
     */
    void getOperationalComponents(ILSMIndexOperationContext ctx) throws HyracksDataException;

    List<ILSMDiskComponent> getInactiveDiskComponents();

    void addInactiveDiskComponent(ILSMDiskComponent diskComponent);

    /**
     * Persist the LSM component
     *
     * @param lsmComponent
     *            , the component to be persistent
     * @throws HyracksDataException
     */
    void markAsValid(ILSMDiskComponent lsmComponent) throws HyracksDataException;

    boolean isCurrentMutableComponentEmpty() throws HyracksDataException;

    void scheduleReplication(ILSMIndexOperationContext ctx, List<ILSMDiskComponent> diskComponents, boolean bulkload,
            ReplicationOperation operation, LSMOperationType opType) throws HyracksDataException;

    boolean isMemoryComponentsAllocated();

    /**
     * Allocates the memory components of an LSM index in the buffer cache.
     *
     * @throws HyracksDataException
     */
    void allocateMemoryComponents() throws HyracksDataException;

    ILSMMemoryComponent getCurrentMemoryComponent();

    int getCurrentMemoryComponentIndex();

    List<ILSMMemoryComponent> getMemoryComponents();

    /**
     * @return true if the index is durable. Otherwise false.
     */
    boolean isDurable();
}


text:
void ParticleFilter::init(double x, double y, double theta, double std[])
{
	num_particles = 100;
	std::default_random_engine gen;
	std::normal_distribution<double> dist_x(x, std[0]);
	std::normal_distribution<double> dist_y(y, std[1]);
	std::normal_distribution<double> dist_theta(theta, std[2]);
	for (int i = 0; i < num_particles; ++i)
	{
		Particle p;
		p.id = i;
		p.x = dist_x(gen);
		p.y = dist_y(gen);
		p.theta = dist_theta(gen);
		p.weight = 1;
		particles.push_back(p);
	}
	is_initialized = true;
}

void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate)
{
	std::default_random_engine gen;
	// create gaissian noise
	std::normal_distribution<double> dist_x(0, std_pos[0]);
	std::normal_distribution<double> dist_y(0, std_pos[1]);
	std::normal_distribution<double> dist_theta(0, std_pos[2]);
	for (int i = 0; i < num_particles; ++i)
	{
		auto particle = &particles[i];
		double delta_x, delta_y, delta_theta;
		double theta = particle->theta;
		//check if yaw_rate is to be factored in
		if(fabs(yaw_rate) > 1.e-15)
		{
			// factor yaw_rate in
			double vel_over_yaw = (velocity / yaw_rate);
			double yaw_by_delta_t = (yaw_rate * delta_t);
			delta_x = vel_over_yaw * (sin(theta + yaw_by_delta_t) - sin(theta));
			delta_y = vel_over_yaw * (cos(theta) - cos(theta + yaw_by_delta_t));
			delta_theta = yaw_rate * delta_t;
		}
		else
		{
			// yaw_rate is zero
			double vel_by_delta_t = (velocity * delta_t);
			delta_x = vel_by_delta_t * cos(theta);
			delta_y = vel_by_delta_t * sin(theta);
			delta_theta = 0;
		}
		// assign
		particle->x += delta_x + dist_x(gen);
		particle->y += delta_y + dist_y(gen);
		particle->theta += delta_theta + dist_theta(gen);
	}
}

void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations)
{
	for (int i = 0; i < observations.size(); ++i)
	{
		auto o = &observations[i];
		int champ_index = -1;
		double smallest_distance = std::numeric_limits<double>::max();
		for (int j = 0; j < predicted.size(); ++j)
		{
			auto p = &predicted[j];
			double current_distance = dist(p->x, p->y, o->x, o->y);
			if (current_distance < smallest_distance)
			{
				smallest_distance = current_distance;
				champ_index = j;
			}
		}
		o->id = champ_index;
	}
}

void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
		std::vector<LandmarkObs> observations, Map map_landmarks)
{
	std::vector<LandmarkObs> map_landmarks_obs;
	for (int i = 0; i < map_landmarks.landmark_list.size(); ++i)
	{
		LandmarkObs obs;
		obs.id = map_landmarks.landmark_list[i].id_i;
		obs.x = map_landmarks.landmark_list[i].x_f;
		obs.y = map_landmarks.landmark_list[i].y_f;
		map_landmarks_obs.push_back(obs);
	}

	// we'll calculate the multivariate Gaussian probability density function, in its
	// bivariate case as described in https://en.wikipedia.org/wiki/Multivariate_normal_distribution
	double std_x = std_landmark[0];
	double std_y = std_landmark[1];
	double std_x2 = (std_x * std_x);
	double std_y2 = (std_y * std_y);
	// we assume rho to be zero, so we'll omit it in the next statement:
	long double bivariate_base = 1 / (2 * M_PI * std_x * std_y);

	for (int p = 0; p < particles.size(); ++p)
	{
		auto particle = &particles[p];
		// transform the observation as if it were seen from the particle's perspective
		// it is originally represented in the car's coordinate system
		std::vector<LandmarkObs> transformed_obs;
		for (int i = 0; i < observations.size(); ++i)
		{
			auto car_observation = observations[i];
			LandmarkObs obs;
			obs.id = -1; // no association
			obs.x = particle->x + (car_observation.x * cos(particle->theta)) - (car_observation.y * sin(particle->theta));
			obs.y = particle->y + (car_observation.x * sin(particle->theta)) + (car_observation.y * cos(particle->theta));
			// only add observation if it's within sensor range from the particle
			if (dist(particle->x, particle->y, obs.x, obs.y) <= sensor_range)
			{
				transformed_obs.push_back(obs);
			}
		}
		dataAssociation(map_landmarks_obs, transformed_obs);

		if (transformed_obs.size() > 0)
		{
			// implementation of bivariate case of the Gaussian probability density function
			// https://en.wikipedia.org/wiki/Multivariate_normal_distribution
			long double particle_weight = 1;
			for (int i = 0; i < transformed_obs.size(); ++i)
			{
				auto observation = &transformed_obs[i];
				auto associated_landmark = &map_landmarks_obs[observation->id];
				long double x = observation->x;
				long double mu_x = associated_landmark->x;
				long double y = observation->y;
				long double mu_y = associated_landmark->y;
				long double x_minus_mu_x = (x - mu_x);
				long double x_minus_mu_x2 = x_minus_mu_x * x_minus_mu_x;
				long double y_minus_mu_y = (y - mu_y);
				long double y_minus_mu_y2 = y_minus_mu_y * y_minus_mu_y;
				long double a = x_minus_mu_x2 / std_x2;
				long double b = y_minus_mu_y2 / std_y2;
				// we assume rho to be zero, so we'll omit it in the next statement:
				particle_weight *= bivariate_base * exp((-0.5) * (a + b));
			}
			//std::cout << "Particle " << p << " now has weight " << particle_weight << std::endl;
			particle->weight = particle_weight;
		}
		else
		{
			particle->weight = 1.e-150;
		}
	}
}

void ParticleFilter::resample()
{
	std::vector<Particle> resample_bucket;

	int n = particles.size();
	int index = rand() % n;
	double beta = 0;
	double max_weight = std::numeric_limits<double>::min();
	for (int i = 0; i < n; ++i)
	{
		if (particles[i].weight > max_weight)
		{
			max_weight = particles[i].weight;
		}
	}
	double max_weight_2x = 2 * max_weight;
	for (int i = 0; i < n; ++i)
	{
		beta += ((double)rand() / RAND_MAX) * max_weight_2x;
		while (beta > particles[index].weight)
		{
			beta -= particles[index].weight;
			index = (index + 1) % n;
		}
		Particle particle;
		particle.id = i;
		particle.x = particles[index].x;
		particle.y = particles[index].y;
		particle.theta = particles[index].theta;
		particle.weight = particles[index].weight;
		resample_bucket.push_back(particle);
	}
	particles = resample_bucket;
}

void ParticleFilter::write(std::string filename)
{
	// You don't need to modify this file.
	std::ofstream dataFile;
	dataFile.open(filename, std::ios::app);
	for (int i = 0; i < num_particles; ++i)
	{
		dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
	}
	dataFile.close();
}


text:
title: Restart Detection
date: 20:50 2017-05-04
author: Marcel Fuhrmann
body_classes: header-lite fullwidth blogstyling
taxonomy:
    category: wiki
    tag: [threshold, wiki]
---
Most of today's servers run in virtual environments and Java applications in containers.
Sometimes these applications or servers unexpectedly restart and can often go unnoticed because a restart can be much faster then a polling cycle.

If SNMP is enabled, the hrSystemUptime can detect restarts from Windows or Linux machines.
Similarly, this concept can also be applied to Java application restart detection via JMX and the JVM uptime metric.
This article describes how to use the OpenNMS threshold features to detect server and Java application restarts and create events for alerting or logging.

Would you like to know more? -> [Restart Detection](https://wiki.opennms.org/wiki/Restart_Detection)


text:
// Generated Code for the Draw2D touch HTML5 lib
//
// http://www.draw2d.org
//
// Go to the Designer http://www.draw2d.org
// to design your own shape or download user generated
//
var draw2d_circuit_pulse_50hz = draw2d.SetFigure.extend({

   NAME: "draw2d_circuit_pulse_50hz",

   init:function(attr, setter, getter)
   {
     this._super( $.extend({stroke:0, bgColor:null, width:32,height:48.60950000000048},attr), setter, getter);
     var port;
     // circle
     port = this.createPort("output", new draw2d.layout.locator.XYRelPortLocator(102.0751953125, 69.8754358715884));
     port.setConnectionDirection(1);
     port.setBackgroundColor("#1C9BAB");
     port.setName("circle");
     port.setMaxFanOut(20);
     this.persistPorts=false;
   },

   createShapeElement : function()
   {
      var shape = this._super();
      this.originalWidth = 32;
      this.originalHeight= 48.60950000000048;
      return shape;
   },

   createSet: function()
   {
       this.canvas.paper.setStart();

        // BoundingBox
        shape = this.canvas.paper.path("M0,0 L32,0 L32,48.60950000000048 L0,48.60950000000048");
        shape.attr({"stroke":"none","stroke-width":0,"fill":"none"});
        shape.data("name","BoundingBox");

        // Rectangle
        shape = this.canvas.paper.path('M1.6640625 18.60950000000048L31.6640625 18.60950000000048L31.6640625 48.60950000000048L1.6640625 48.60950000000048Z');
        shape.attr({"stroke":"#303030","stroke-width":1,"fill":"#FFFFFF","dasharray":null,"opacity":1});
        shape.data("name","Rectangle");

        // Label
        shape = this.canvas.paper.text(0,0,'50Hz');
        shape.attr({"x":4,"y":11,"text-anchor":"start","text":"50Hz","font-family":"\"Arial\"","font-size":10,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
        shape.data("name","Label");

        // Line_shadow
        shape = this.canvas.paper.path('M3.5 41.5L10.5,41.5L10.5,30.5L22.5,30.5L22.5,40.5L28.5,40.5');
        shape.attr({"stroke-linecap":"round","stroke-linejoin":"round","stroke":"none","stroke-width":1,"stroke-dasharray":null,"opacity":1});
        shape.data("name","Line_shadow");

        // Line
        shape = this.canvas.paper.path('M3.5 41.5L10.5,41.5L10.5,30.5L22.5,30.5L22.5,40.5L28.5,40.5');
        shape.attr({"stroke-linecap":"round","stroke-linejoin":"round","stroke":"#000000","stroke-width":1,"stroke-dasharray":null,"opacity":1});
        shape.data("name","Line");

        return this.canvas.paper.setFinish();
   },

   applyAlpha: function()
   {
   },

   layerGet: function(name, attributes)
   {
      if(this.svgNodes===null) return null;

      var result=null;
      this.svgNodes.some(function(shape){
         if(shape.data("name")===name){
            result=shape;
         }
         return result!==null;
      });

      return result;
   },

   layerAttr: function(name, attributes)
   {
     if(this.svgNodes===null) return;

     this.svgNodes.forEach(function(shape){
             if(shape.data("name")===name){
                  shape.attr(attributes);
             }
     });
   },

   layerShow: function(name, flag, duration)
   {
      if(this.svgNodes===null) return;

      if(duration){
        this.svgNodes.forEach(function(node){
            if(node.data("name")===name){
                if(flag){
                    node.attr({ opacity : 0 }).show().animate({ opacity : 1 }, duration);
                }
                else{
                    node.animate({ opacity : 0 }, duration, function () { this.hide() });
                }
            }
        });
      }
      else{
          this.svgNodes.forEach(function(node){
              if(node.data("name")===name){
                   if(flag){node.show();}
                   else{node.hide();}
               }
           });
      }
   },

    calculate: function()
    {
    },

    onStart: function()
    {
    },

    onStop:function()
    {
    },

    getParameterSettings: function()
    {
        return [];
    },

    /**
     * @method
     */
    addPort: function(port, locator)
    {
        this._super(port, locator);
        return port;
    },

    /**
     * @method
     * Return an objects with all important attributes for XML or JSON serialization
     *
     * @returns {Object}
     */
    getPersistentAttributes : function()
    {
        var memento = this._super();

        // add all decorations to the memento
        //
        memento.labels = [];
        this.children.each(function(i,e){
            var labelJSON = e.figure.getPersistentAttributes();
            labelJSON.locator=e.locator.NAME;
            memento.labels.push(labelJSON);
        });

        return memento;
    },

    /**
     * @method
     * Read all attributes from the serialized properties and transfer them into the shape.
     *
     * @param {Object} memento
     * @returns
     */
    setPersistentAttributes : function(memento)
    {
        this._super(memento);

        // remove all decorations created in the constructor of this element
        //
        this.resetChildren();

        // and add all children of the JSON document.
        //
        $.each(memento.labels, $.proxy(function(i,json){
            // create the figure stored in the JSON
            var figure =  eval("new "+json.type+"()");

            // apply all attributes
            figure.attr(json);

            // instantiate the locator
            var locator =  eval("new "+json.locator+"()");

            // add the new figure as child to this figure
            this.add(figure, locator);
        },this));
    }
});

/**
 * by 'Draw2D Shape Designer'
 *
 * Custom JS code to tweak the standard behaviour of the generated
 * shape. add your custome code and event handler here.
 *
 *
 */
draw2d_circuit_pulse_50hz = draw2d_circuit_pulse_50hz.extend({

    init: function(attr, setter, getter){
        this._super(attr, setter, getter);

        this.attr({resizeable:false});
        this.installEditPolicy(new draw2d.policy.figure.AntSelectionFeedbackPolicy());

        this.currentTimer=0;
    },

    calculate:function()
    {
      // 2 ticks => 50Hz
       this.currentTimer = (this.currentTimer+1)%2;
       if(this.currentTimer===0){
           this.value = !this.value;
           this.getOutputPort(0).setValue(this.value);
       }
    },

    onStart:function()
    {
         this.currentTimer=0;
    },

    onStop:function()
    {
    }

});
draw2d_circuit_pulse_50hz.github="./shapes/org/draw2d/circuit/pulse/50hz.shape";


text:
package org.jboss.weld.junit5.initiator.discovery;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.junit5.WeldInitiator;
import org.jboss.weld.junit5.WeldSetup;
import org.jboss.weld.junit5.initiator.bean.Foo;

/**
 *
 * @author Matej Novotny
 */
public class SuperclassWithProtectedWeldInitiator {

    @WeldSetup
    protected WeldInitiator weld = WeldInitiator
        .of(new Weld()
            .addBeanClass(Foo.class));
}


text:
package org.elasticsearch.client;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import org.apache.http.HttpHost;
import org.elasticsearch.mocksocket.MockHttpServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * Integration test to validate the builder builds a client with the correct configuration
 */
public class RestClientBuilderIntegTests extends RestClientTestCase {

    private static HttpsServer httpsServer;

    @BeforeClass
    public static void startHttpServer() throws Exception {
        httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
        httpsServer.setHttpsConfigurator(new HttpsConfigurator(getSslContext()));
        httpsServer.createContext("/", new ResponseHandler());
        httpsServer.start();
    }

    private static class ResponseHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            httpExchange.sendResponseHeaders(200, -1);
            httpExchange.close();
        }
    }

    @AfterClass
    public static void stopHttpServers() throws IOException {
        httpsServer.stop(0);
        httpsServer = null;
    }

    public void testBuilderUsesDefaultSSLContext() throws Exception {
        final SSLContext defaultSSLContext = SSLContext.getDefault();
        try {
            try (RestClient client = buildRestClient()) {
                try {
                    client.performRequest(new Request("GET", "/"));
                    fail("connection should have been rejected due to SSL handshake");
                } catch (Exception e) {
                    assertThat(e, instanceOf(SSLHandshakeException.class));
                }
            }

            SSLContext.setDefault(getSslContext());
            try (RestClient client = buildRestClient()) {
                Response response = client.performRequest(new Request("GET", "/"));
                assertEquals(200, response.getStatusLine().getStatusCode());
            }
        } finally {
            SSLContext.setDefault(defaultSSLContext);
        }
    }

    private RestClient buildRestClient() {
        InetSocketAddress address = httpsServer.getAddress();
        return RestClient.builder(new HttpHost(address.getHostString(), address.getPort(), "https")).build();
    }

    private static SSLContext getSslContext() throws Exception {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        try (InputStream certFile = RestClientBuilderIntegTests.class.getResourceAsStream("/test.crt")) {
            // Build a keystore of default type programmatically since we can't use JKS keystores to
            // init a KeyManagerFactory in FIPS 140 JVMs.
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, "password".toCharArray());
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get(RestClientBuilderIntegTests.class
                .getResource("/test.der").toURI())));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            keyStore.setKeyEntry("mykey", keyFactory.generatePrivate(privateKeySpec), "password".toCharArray(),
                new Certificate[]{certFactory.generateCertificate(certFile)});
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keyStore, "password".toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        }
        return sslContext;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<!--

    Copyright (C) 2009 eXo Platform SAS.

    This is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation; either version 2.1 of
    the License, or (at your option) any later version.

    This software is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this software; if not, write to the Free
    Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
    02110-1301 USA, or see the FSF site: http://www.fsf.org.

-->

<web-app version="3.0" metadata-complete="true"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>estudyExtension</display-name>

  <context-param>
    <description>Binary assets workspace name</description>
    <param-name>org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsWorkspace</param-name>
    <param-value>collaboration</param-value>
  </context-param>

  <context-param>
    <description>Binary assets path</description>
    <param-name>org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath</param-name>
    <param-value>/Digital Assets/</param-value>
  </context-param>

  <context-param>
    <description>Binary assets workspace name</description>
    <param-name>CurrentFolder</param-name>
    <param-value>/Digital Assets/</param-value>
  </context-param>

  <!-- ================================================================== -->
  <!--   RESOURCE FILTER TO CACHE MERGED JAVASCRIPT AND CSS               -->
  <!-- ================================================================== -->
  <filter>
    <filter-name>ResourceRequestFilter</filter-name>
    <filter-class>org.exoplatform.portal.application.ResourceRequestFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>ResourceRequestFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- ================================================================== -->
  <!--           LISTENER                                                 -->
  <!-- ================================================================== -->
  <listener>
    <listener-class>org.exoplatform.container.web.PortalContainerConfigOwner</listener-class>
  </listener>
  <!-- ================================================================== -->
  <!--           SERVLET                                                  -->
  <!-- ================================================================== -->
  <servlet>
    <servlet-name>GateInServlet</servlet-name>
    <servlet-class>org.gatein.wci.api.GateInServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <!--  =================================================================  -->
  <servlet-mapping>
    <servlet-name>GateInServlet</servlet-name>
    <url-pattern>/gateinservlet</url-pattern>
  </servlet-mapping>
</web-app>


text:
package com.kubrynski.data.repository.generic;

import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryMetadata;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @author jkubrynski@gmail.com
 * @since 2013-10-22
 */
public class GenericRepositoryFactory extends JpaRepositoryFactory {

  /**
   * Creates a new {@link org.springframework.data.jpa.repository.support.JpaRepositoryFactory}.
   *
   * @param entityManager must not be {@literal null}
   */
  public GenericRepositoryFactory(EntityManager entityManager) {
    super(entityManager);
  }

  @Override
  protected <T, ID extends Serializable> GenericRepository<T> getTargetRepository(RepositoryMetadata metadata, EntityManager entityManager) {
    return new GenericRepositoryImpl<T>(getEntityInformation((Class<T>) metadata.getDomainType()), entityManager);
  }

  @Override
  protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
    return GenericRepositoryImpl.class;
  }
}


text:
/**
 *
 */
package org.openflow.protocol.action;

import java.lang.reflect.Constructor;

import org.openflow.protocol.Instantiable;

/**
 * List of OpenFlow Action types and mappings to wire protocol value and
 * derived classes
 *
 * @author David Erickson (daviderickson@cs.stanford.edu)
 */
public enum OFActionType {
    OUTPUT              (0, OFActionOutput.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionOutput();
                            }}),
    SET_VLAN_ID        (1, OFActionVirtualLanIdentifier.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionVirtualLanIdentifier();
                            }}),
    SET_VLAN_PCP        (2, OFActionVirtualLanPriorityCodePoint.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionVirtualLanPriorityCodePoint();
                            }}),
    STRIP_VLAN          (3, OFActionStripVirtualLan.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionStripVirtualLan();
                            }}),
    SET_DL_SRC          (4, OFActionDataLayerSource.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionDataLayerSource();
                            }}),
    SET_DL_DST          (5, OFActionDataLayerDestination.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionDataLayerDestination();
                            }}),
    SET_NW_SRC          (6, OFActionNetworkLayerSource.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionNetworkLayerSource();
                            }}),
    SET_NW_DST          (7, OFActionNetworkLayerDestination.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionNetworkLayerDestination();
                            }}),
    SET_NW_TOS          (8, OFActionNetworkTypeOfService.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionNetworkTypeOfService();
                            }}),
    SET_TP_SRC          (9, OFActionTransportLayerSource.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionTransportLayerSource();
                            }}),
    SET_TP_DST          (10, OFActionTransportLayerDestination.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionTransportLayerDestination();
                            }}),
    OPAQUE_ENQUEUE      (11, OFActionEnqueue.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionEnqueue();
                            }}),
    REMOTE              (12, OFActionRemote.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionRemote();
                            }}),
    VENDOR              (0xffff, OFActionVendor.class, new Instantiable<OFAction>() {
                            @Override
                            public OFAction instantiate() {
                                return new OFActionVendor();
                            }});

    protected static OFActionType[] mapping;

    protected Class<? extends OFAction> clazz;
    protected Constructor<? extends OFAction> constructor;
    protected Instantiable<OFAction> instantiable;
    protected int minLen;
    protected short type;

    /**
     * Store some information about the OpenFlow Action type, including wire
     * protocol type number, length, and derrived class
     *
     * @param type Wire protocol number associated with this OFType
     * @param clazz The Java class corresponding to this type of OpenFlow Action
     * @param instantiable the instantiable for the OFAction this type represents
     */
    OFActionType(int type, Class<? extends OFAction> clazz, Instantiable<OFAction> instantiable) {
        this.type = (short) type;
        this.clazz = clazz;
        this.instantiable = instantiable;
        try {
            this.constructor = clazz.getConstructor(new Class[]{});
        } catch (Exception e) {
            throw new RuntimeException(
                    "Failure getting constructor for class: " + clazz, e);
        }
        OFActionType.addMapping(this.type, this);
    }

    /**
     * Adds a mapping from type value to OFActionType enum
     *
     * @param i OpenFlow wire protocol Action type value
     * @param t type
     */
    static public void addMapping(short i, OFActionType t) {
        if (mapping == null)
            mapping = new OFActionType[16];
        // bring higher mappings down to the edge of our array
        if (i < 0)
            i = (short) (16 + i);
        OFActionType.mapping[i] = t;
    }

    /**
     * Given a wire protocol OpenFlow type number, return the OFType associated
     * with it
     *
     * @param i wire protocol number
     * @return OFType enum type
     */

    static public OFActionType valueOf(short i) {
        if (i < 0)
            i = (short) (16+i);
        return OFActionType.mapping[i];
    }

    /**
     * @return Returns the wire protocol value corresponding to this
     *         OFActionType
     */
    public short getTypeValue() {
        return this.type;
    }

    /**
     * @return return the OFAction subclass corresponding to this OFActionType
     */
    public Class<? extends OFAction> toClass() {
        return clazz;
    }

    /**
     * Returns the no-argument Constructor of the implementation class for
     * this OFActionType
     * @return the constructor
     */
    public Constructor<? extends OFAction> getConstructor() {
        return constructor;
    }

    /**
     * Returns a new instance of the OFAction represented by this OFActionType
     * @return the new object
     */
    public OFAction newInstance() {
        return instantiable.instantiate();
    }

    /**
     * @return the instantiable
     */
    public Instantiable<OFAction> getInstantiable() {
        return instantiable;
    }

    /**
     * @param instantiable the instantiable to set
     */
    public void setInstantiable(Instantiable<OFAction> instantiable) {
        this.instantiable = instantiable;
    }
}


text:
'use strict'

// var distance = require('./centimeter')

// distance.set('angstrom', 'centimeter', 1 / 100000000)

// module.exports = distance

module.exports = ['angstrom', 'centimeter', 1 / 100000000]


text:
(function( $ ) {

module( "droppable: events" );

test( "droppable destruction/recreation on drop event", function() {
	expect( 1 );

	var config = {
			activeClass: "active",
			drop: function() {
				var element = $( this ),
					newDroppable = $( "<div>" )
						.css({ width: 100, height: 100 })
						.text( "Droppable" );
				element.after( newDroppable );
				element.remove();
				newDroppable.droppable( config );
			}
		},

		draggable = $( "#draggable1" ).draggable(),
		droppable1 = $( "#droppable1" ).droppable( config ),
		droppable2 = $( "#droppable2" ).droppable( config ),

		droppableOffset = droppable1.offset(),
		draggableOffset = draggable.offset(),
		dx = droppableOffset.left - draggableOffset.left,
		dy = droppableOffset.top - draggableOffset.top;

	draggable.simulate( "drag", {
		dx: dx,
		dy: dy
	});

	ok( !droppable2.hasClass( "active" ), "subsequent droppable no longer active" );
});

// todo: comment the following in when ready to actually test
/*
test("activate", function() {
	ok(false, 'missing test - untested code is broken code');
});

test("deactivate", function() {
	ok(false, 'missing test - untested code is broken code');
});

test("over", function() {
	ok(false, 'missing test - untested code is broken code');
});

test("out", function() {
	ok(false, 'missing test - untested code is broken code');
});

test("drop", function() {
	ok(false, 'missing test - untested code is broken code');
});
*/

})( jQuery );


text:
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['q'], function(Q) {
      return factory(XMLHttpRequest, Q)
    })
  } else if (typeof exports === 'object' && typeof module === 'object') {
    // CommonJS, mainly for testing
    module.exports = factory
  } else {
    if (typeof Q !== 'undefined') {
      factory(XMLHttpRequest, Q)
    }
  }
})(function(XHR, Q) {
  // shallow extend with varargs
  function extend(dst) {
    Array.prototype.forEach.call(arguments, function(obj) {
      if (obj && obj !== dst) {
        Object.keys(obj).forEach(function(key) {
          dst[key] = obj[key]
        })
      }
    })

    return dst
  }

  function lowercase(str) {
    return (str || '').toLowerCase()
  }

  function parseHeaders(headers) {
    var parsed = {}, key, val, i

    if (!headers) return parsed

    headers.split('\n').forEach(function(line) {
      i = line.indexOf(':')
      key = lowercase(line.substr(0, i).trim())
      val = line.substr(i + 1).trim()

      if (key) {
        if (parsed[key]) {
          parsed[key] += ', ' + val
        } else {
          parsed[key] = val
        }
      }
    })

    return parsed
  }

  function headersGetter(headers) {
    var headersObj = typeof headers === 'object' ? headers : undefined;

    return function(name) {
      if (!headersObj) headersObj = parseHeaders(headers)

      if (name) {
        return headersObj[lowercase(name)]
      }

      return headersObj
    }
  }

  function transformData(data, headers, fns) {
    if (typeof fns === 'function') {
      return fns(data, headers)
    }

    fns.forEach(function(fn) {
      data = fn(data, headers)
    })

    return data
  }

  function isSuccess(status) {
    return 200 <= status && status < 300
  }

  function forEach(obj, iterator, context) {
    var keys = Object.keys(obj)
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function forEachSorted(obj, iterator, context) {
    var keys = Object.keys(obj).sort()
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function buildUrl(url, params) {
    if (!params) return url
    var parts = []
    forEachSorted(params, function(value, key) {
      if (value == null) return
      if (!Array.isArray(value)) value = [value]

      value.forEach(function(v) {
        if (typeof v === 'object') {
          v = JSON.stringify(v)
        }
        parts.push(encodeURIComponent(key) + '=' +
                   encodeURIComponent(v))
      })
    })
    return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&')
  }

  Q.xhr = function (requestConfig) {
    var defaults = Q.xhr.defaults,
    config = {
      transformRequest: defaults.transformRequest,
      transformResponse: defaults.transformResponse
    },
    mergeHeaders = function(config) {
      var defHeaders = defaults.headers,
          reqHeaders = extend({}, config.headers),
          defHeaderName, lowercaseDefHeaderName, reqHeaderName,

      execHeaders = function(headers) {
        forEach(headers, function(headerFn, header) {
          if (typeof headerFn === 'function') {
            var headerContent = headerFn()
            if (headerContent != null) {
              headers[header] = headerContent
            } else {
              delete headers[header]
            }
          }
        })
      }

      defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);

      // execute if header value is function
      execHeaders(defHeaders);
      execHeaders(reqHeaders);

      // using for-in instead of forEach to avoid unecessary iteration after header has been found
      defaultHeadersIteration:
      for (defHeaderName in defHeaders) {
        lowercaseDefHeaderName = lowercase(defHeaderName);

        for (reqHeaderName in reqHeaders) {
          if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
            continue defaultHeadersIteration;
          }
        }

        reqHeaders[defHeaderName] = defHeaders[defHeaderName];
      }

      return reqHeaders;
    },
    headers = mergeHeaders(requestConfig)

    extend(config, requestConfig)
    config.headers = headers
    config.method = (config.method || 'GET').toUpperCase()

    var serverRequest = function(config) {
      headers = config.headers
      var reqData = transformData(config.data, headersGetter(headers), config.transformRequest)

      // strip content-type if data is undefined TODO does it really matter?
      if (config.data == null) {
        forEach(headers, function(value, header) {
          if (lowercase(header) === 'content-type') {
              delete headers[header]
          }
        })
      }

      if (config.withCredentials == null && defaults.withCredentials != null) {
        config.withCredentials = defaults.withCredentials
      }

      // send request
      return sendReq(config, reqData, headers).then(transformResponse, transformResponse)
    },

    transformResponse = function(response) {
      response.data = transformData(response.data, response.headers, config.transformResponse)
      return isSuccess(response.status) ? response : Q.reject(response)
    },

    promise = Q.when(config)

    // build a promise chain with request interceptors first, then the request, and response interceptors
    Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.request || !!interceptor.requestError
      }).map(function(interceptor) {
        return { success: interceptor.request, failure: interceptor.requestError }
      })
    .concat({ success: serverRequest })
    .concat(Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.response || !!interceptor.responseError
      }).map(function(interceptor) {
        return { success: interceptor.response, failure: interceptor.responseError }
      })
    ).forEach(function(then) {
      promise = promise.then(then.success, then.failure)
    })

    return promise
  }

  var contentTypeJson = { 'Content-Type': 'application/json;charset=utf-8' }

  Q.xhr.defaults = {
    transformResponse: [function(data, headers) {
      if (typeof data === 'string' && data.length && (headers('content-type') || '').indexOf('json') >= 0) {
        data = JSON.parse(data);
      }
      return data
    }],

    transformRequest: [function(data) {
      return !!data && typeof data === 'object' && data.toString() !== '[object File]' ?
        JSON.stringify(data) : data
    }],

    headers: {
      common: {
        'Accept': 'application/json, text/plain, */*'
      },
      post:   contentTypeJson,
      put:    contentTypeJson,
      patch:  contentTypeJson
    },
  }

  Q.xhr.interceptors = []
  Q.xhr.pendingRequests = []

  function sendReq(config, reqData, reqHeaders) {
    var deferred = Q.defer(),
        promise = deferred.promise,
        url = buildUrl(config.url, config.params),
        xhr = new XHR(),
        aborted = -1,
        status,
        timeoutId

    Q.xhr.pendingRequests.push(config)

    xhr.open(config.method, url, true)
    forEach(config.headers, function(value, key) {
      if (value) {
        xhr.setRequestHeader(key, value)
      }
    })

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var response, responseHeaders
        if (status !== aborted) {
          responseHeaders = xhr.getAllResponseHeaders()
          // responseText is the old-school way of retrieving response (supported by IE8 & 9)
          // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
          response = xhr.responseType ? xhr.response : xhr.responseText
        }

        // cancel timeout and subsequent timeout promise resolution
        timeoutId && clearTimeout(timeoutId)
        status = status || xhr.status
        xhr = null

        // normalize status, including accounting for IE bug (http://bugs.jquery.com/ticket/1450)
        status = Math.max(status == 1223 ? 204 : status, 0)

        var idx = Q.xhr.pendingRequests.indexOf(config)
        if (idx !== -1) Q.xhr.pendingRequests.splice(idx, 1)

        ;(isSuccess(status) ? deferred.resolve : deferred.reject)({
          data: response,
          status: status,
          headers: headersGetter(responseHeaders),
          config: config
        })
      }
    }

    xhr.onprogress = function (progress) {
      deferred.notify(progress)
    }

    if (config.withCredentials) {
      xhr.withCredentials = true
    }

    if (config.responseType) {
      xhr.responseType = config.responseType;
    }

    xhr.send(reqData || null)

    if (config.timeout > 0) {
      timeoutId = setTimeout(function() {
        status = aborted;
        xhr && xhr.abort()
      }, config.timeout)
    }

    return promise
  }

  ['get', 'delete', 'head'].forEach(function(name) {
    Q.xhr[name] = function(url, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url
      }))
    }
  });

  ['post', 'put', 'patch'].forEach(function(name) {
    Q.xhr[name] = function(url, data, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url,
        data: data
      }))
    }
  })

  return Q
})


text:
<?php

namespace BespokeSupport\OSImporter\Command;

use PHPCoord\OSRef;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\TableGateway;

class CpoConvertCommand extends Command
{
    public function configure()
    {
        $this->setName('postcode:convert');
        $this->setDescription('CodePoint-Open: Convert');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('<info>Starting Convert</info>');

        $question = $this->getHelper('question');

        $databaseHost = trim($question->ask($input, $output, new Question('<info>Database Host : </info>', '127.0.0.1')));
        $databaseUser = trim($question->ask($input, $output, new Question('<info>Database User : </info>')));
        $databasePass = trim($question->ask($input, $output, new Question('<info>Database Pass : </info>')));
        $databaseName = trim($question->ask($input, $output, new Question('<info>Database Name : </info>')));

        $databaseAdapter = new Adapter([
            'driver' => 'Pdo_Mysql',
            'host' => $databaseHost,
            'dbname' => $databaseName,
            'username' => $databaseUser,
            'password' => $databasePass,
        ]);

        $table = new TableGateway('postcodes', $databaseAdapter);

        $rows = $table->select();

        $count = 1;
        $databaseAdapter->getDriver()->getConnection()->beginTransaction();
        foreach ($rows as $row) {

            $gb = new OSRef($row->eastings, $row->northings);
            $latLng = $gb->toLatLng();
            $latLng->OSGB36ToWGS84();

            if ($latLng && $latLng->lat) {
                $table->update([
                    'latitude' => $latLng->lat,
                    'longitude' => $latLng->lng
                ],[
                    'postcode' => $row->postcode
                ]);
            }

            if ($count % 5000 == 0) {
                $output->writeln("\t $count");
                $databaseAdapter->getDriver()->getConnection()->commit();
                $databaseAdapter->getDriver()->getConnection()->beginTransaction();
            }

            $count++;
        }

        $databaseAdapter->getDriver()->getConnection()->commit();

        $output->writeln('<info>Convert End</info>');
    }
}


text:
<?php

namespace Blogger\BlogBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class CommentType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('user')
            ->add('comment')
        ;
    }

    public function getName()
    {
        return 'blogger_blogbundle_commenttype';
    }
}


text:
using System.Net.Http;
using System.Text;

namespace NContract
{
    public class RestApiClientConfiguration
    {
        public string BaseUri { get; set; }

        public StringContent Content { get; set; }

        public object Model { get; set; }

        public RequestHeadersContainer Headers { get; set; }

        public string RequestUri { get; set; }

        public string ContentType { get; set; }

        public ResponseContentType ResponseContentType { get; set; }

        public Encoding Encoding { get; set; }

        public HttpMethod HttpMethod { get; set; }
    }
}


text:
layout: full
menu_item: guides
title: From source
description: How to build NodeGit from source
---

[Return to all guides](../../)

* * *

Building from source
--------------------

If you wish to help contribute to NodeGit it is useful to build locally.

``` bash
# Fetch this project.
git clone git://github.com/nodegit/nodegit.git

# Enter the repository.
cd nodegit

# Install all dependencies, run the code generation scripts, and build.
npm install
```

If you encounter errors, you most likely have not configured the dependencies correctly.

### Installing dependencies: ###

####  Mac OS X ####

- [Install XCode Command Line Tools](http://railsapps.github.io/xcode-command-line-tools.html)

#### Linux ####

Using APT in Ubuntu:

``` bash
sudo apt-get install build-essential
```

Using Pacman in Arch Linux:

``` bash
sudo pacman -S base-devel
```

Note that GCC/G++ 4.7+ are required, as the library makes use of some c++11 std calls.

#### Windows ####

- [Download and install Python 2](https://www.python.org/download/windows).
- [Download and install VS Community](https://www.visualstudio.com/products/visual-studio-community-vs).

You may have to add a build flag to the installation process to successfully install.
Try first without, if the build fails, try again with the flag.

*Allegedly the order in which you install Visual Studio could trigger this error.*

``` bash
npm install nodegit --msvs_version=2013
# Or whatever version you've installed.
```

### Electron and OpenSSL ###
A local version of OpenSSL is required when building for Electron on Windows and macOS. This is due to Electron using BoringSSL, as we are not able to link to it like we are OpenSSL in Node. Additionally, OpenSSL can be statically linked on Linux by setting the `NODEGIT_OPENSSL_STATIC_LINK` environment variable to `1`.

`acquireOpenSSL.js` will attempt to download OpenSSL prebuilts from S3. If preferred, it can also be built locally by setting the environment variable `npm_config_openssl_bin_url=skip`. On macOS, this should Just Work(tm). On Windows, things are a little trickier.

- We rely on the Visual Studio dev tools to be installed, specifically `vcvarsall.bat` to provide access to the tools. If this is not in the default location for VS2017, you'll need to `npm config set vcvarsall_path <path>` or set the environment variable `npm_config_vcvarsall_path` pointing to it.
- See [Compilation and Installation](https://wiki.openssl.org/index.php/Compilation_and_Installation#Windows) regarding required dependencies, specifically `Perl` (Strawberry Perl is known to work) and `NASM`. Make sure they're on the PATH.

Alternatively, you can provide your own OpenSSL binaries and headers. These can either go in `vendor/openssl` (e.g. `<nodegit_root>/vendor/openssl/{lib,bin,include}` should exist) or in an external directory located by `npm config set openssl_dir <path>` or the environment variable `npm_config_openssl_dir`. Additionally, you can `npm config set openssl_bin_url <url>` or the environment variable `npm_config_openssl_bin_url` to download and extract prebuilt binaries (only supports tar.gz files). `npm config set openssl_bin_sha256 <sha256>` or the environment variable `npm_config_openssl_bin_sha256` can be set to verify the download.

##### A note on environment variables in Windows #####
In many of the npm scripts (and examples above), things are run like
`BUILD_ONLY=true npm install`. This sets the `BUILD_ONLY` environment variable
to true for the duration of that command. This doesn't work in windows, however
there is a solution. You can use cmd to call a command inside of cmd (very meta)
with the variable set, and it only lasts for the duration of the inner call to cmd.
So for the above example, you would run `cmd /C "set BUILD_ONLY=true && npm install"`.
See here for more details:
[SuperUser](http://superuser.com/questions/223104/setting-environment-variable-for-just-one-command-in-windows-cmd-exe).

### Debug build: ###

In order to track down possible bugs, you will need a debug build so you
can get a backtrace with [gdb](http://www.gnu.org/software/gdb/) or
[lldb](http://lldb.llvm.org/).

If you're building for the first time, run `npm run installDebug` (or `BUILD_ONLY=true npm link`)

Note that you should run `rm -rf build/Release` (or `rd /s /q build/Release` in Windows) to make sure a release build doesn't get loaded instead of the debug build.

If you're doing a subsequent rebuild of NodeGit in debug, the clean function will cause a lot of extraneous recompilation of things you probably didn't change (like the vendor dependencies). If you need to regenerate the C++ files and recompile you can run `npm run rebuildDebug`, or `npm run recompileDebug` if you've manually updated the C++ files and don't want them to regenerate.


text:
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.ReminderService;
using Orleans.TestingHost;
using UnitTests.StorageTests;
using Xunit;

namespace UnitTests.RemindersTest
{
    /// <summary>
    /// Tests for operation of Orleans Reminders Table using Azure
    /// </summary>
    public class AzureRemindersTableTests : ReminderTableTestsBase, IClassFixture<AzureStorageBasicTestFixture>
    {
        public AzureRemindersTableTests(ConnectionStringFixture fixture) : base(fixture)
        {
            TraceLogger.AddTraceLevelOverride("AzureTableDataManager", Severity.Verbose3);
            TraceLogger.AddTraceLevelOverride("OrleansSiloInstanceManager", Severity.Verbose3);
            TraceLogger.AddTraceLevelOverride("Storage", Severity.Verbose3);
        }

        protected override IReminderTable CreateRemindersTable()
        {
            return new AzureBasedReminderTable();
        }

        protected override string GetConnectionString()
        {
            return StorageTestConstants.DataConnectionString;
        }

        [Fact, TestCategory("Reminders"), TestCategory("Azure")]
        public void RemindersTable_Azure_Init()
        {
        }

        [Fact, TestCategory("Reminders"), TestCategory("Azure")]
        public async Task RemindersTable_Azure_RemindersRange()
        {
            await RemindersRange(50);
        }

        [Fact, TestCategory("Reminders"), TestCategory("Azure")]
        public async Task RemindersTable_Azure_RemindersParallelUpsert()
        {
            await RemindersParallelUpsert();
        }

        [Fact, TestCategory("Reminders"), TestCategory("Azure")]
        public async Task RemindersTable_Azure_ReminderSimple()
        {
            await ReminderSimple();
        }
    }
}


text:
// Type definitions for redux-actions 2.6
// Project: https://github.com/redux-utilities/redux-actions
// Definitions by: Jack Hsu <https://github.com/jaysoo>,
//                 Alex Gorbatchev <https://github.com/alexgorbatchev>,
//                 Alec Hill <https://github.com/alechill>
//                 Alexey Pelykh <https://github.com/alexey-pelykh>
//                 Thiago de Andrade <https://github.com/7hi4g0>
//                 Ziyu <https://github.com/oddui>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2

export as namespace ReduxActions;

// FSA-compliant action.
// See: https://github.com/acdlite/flux-standard-action
export interface BaseAction {
    type: string;
}

export interface Action<Payload> extends BaseAction {
    payload: Payload;
    error?: boolean;
}

export interface ActionMeta<Payload, Meta> extends Action<Payload> {
    meta: Meta;
}

// https://github.com/redux-utilities/redux-actions/blob/v2.3.0/src/combineActions.js#L27
export interface CombinedActionType {
    _dummy: undefined;
}

export type ReducerMapValue<State, Payload> = Reducer<State, Payload> | ReducerNextThrow<State, Payload> | ReducerMap<State, Payload>;

export interface ReducerMap<State, Payload> {
    [actionType: string]: ReducerMapValue<State, Payload>;
}

export interface ReducerMapMeta<State, Payload, Meta> {
    [actionType: string]: ReducerMeta<State, Payload, Meta> | ReducerNextThrowMeta<State, Payload, Meta> | ReducerMapMeta<State, Payload, Meta>;
}

export interface ReducerNextThrow<State, Payload> {
    next?(state: State, action: Action<Payload>): State;
    throw?(state: State, action: Action<Payload>): State;
}

export interface ReducerNextThrowMeta<State, Payload, Meta> {
    next?(state: State, action: ActionMeta<Payload, Meta>): State;
    throw?(state: State, action: ActionMeta<Payload, Meta>): State;
}

export type BaseActionFunctions<TAction> =
    ActionFunction0<TAction> |
    ActionFunction1<any, TAction> |
    ActionFunction2<any, any, TAction> |
    ActionFunction3<any, any, any, TAction> |
    ActionFunction4<any, any, any, any, TAction> |
    ActionFunctionAny<TAction>;

export type ActionFunctions<Payload> = BaseActionFunctions<Action<Payload>>;

export type ActionWithMetaFunctions<Payload, Meta> = BaseActionFunctions<ActionMeta<Payload, Meta>>;

export type Reducer<State, Payload> = (state: State, action: Action<Payload>) => State;

export type ReducerMeta<State, Payload, Meta> = (state: State, action: ActionMeta<Payload, Meta>) => State;

export type ReduxCompatibleReducer<State, Payload> = (state: State | undefined, action: Action<Payload>) => State;

export type ReduxCompatibleReducerMeta<State, Payload, Meta> = (state: State | undefined, action: ActionMeta<Payload, Meta>) => State;

/** argument inferring borrowed from lodash definitions */
export type ActionFunction0<R> = () => R;
export type ActionFunction1<T1, R> = (t1: T1) => R;
export type ActionFunction2<T1, T2, R> = (t1: T1, t2: T2) => R;
export type ActionFunction3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
export type ActionFunction4<T1, T2, T3, T4, R> = (t1: T1, t2: T2, t3: T3, t4: T4) => R;
export type ActionFunctionAny<R> = (...args: any[]) => R;

// https://github.com/redux-utilities/redux-actions/blob/v2.3.0/src/createAction.js#L6
export function createAction(
    actionType: string
): ActionFunctionAny<Action<any>>;

export function createAction<Payload>(
    actionType: string,
    payloadCreator: ActionFunction0<Payload>
): ActionFunction0<Action<Payload>>;

export function createAction<Payload, Arg1>(
    actionType: string,
    payloadCreator: ActionFunction1<Arg1, Payload>
): ActionFunction1<Arg1, Action<Payload>>;

export function createAction<Payload, Arg1, Arg2>(
    actionType: string,
    payloadCreator: ActionFunction2<Arg1, Arg2, Payload>
): ActionFunction2<Arg1, Arg2, Action<Payload>>;

export function createAction<Payload, Arg1, Arg2, Arg3>(
    actionType: string,
    payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>
): ActionFunction3<Arg1, Arg2, Arg3, Action<Payload>>;

export function createAction<Payload, Arg1, Arg2, Arg3, Arg4>(
    actionType: string,
    payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>
): ActionFunction4<Arg1, Arg2, Arg3, Arg4, Action<Payload>>;

export function createAction<Payload>(
    actionType: string
): ActionFunction1<Payload, Action<Payload>>;

export function createAction<Meta>(
    actionType: string,
    payloadCreator: null | undefined,
    metaCreator: ActionFunctionAny<Meta>
): ActionFunctionAny<ActionMeta<any, Meta>>;

export function createAction<Payload, Meta>(
    actionType: string,
    payloadCreator: ActionFunctionAny<Payload>,
    metaCreator: ActionFunctionAny<Meta>
): ActionFunctionAny<ActionMeta<Payload, Meta>>;

export function createAction<Payload, Meta, Arg1>(
    actionType: string,
    payloadCreator: ActionFunction1<Arg1, Payload>,
    metaCreator: ActionFunction1<Arg1, Meta>
): ActionFunction1<Arg1, ActionMeta<Payload, Meta>>;

export function createAction<Payload, Meta, Arg1, Arg2>(
    actionType: string,
    payloadCreator: ActionFunction2<Arg1, Arg2, Payload>,
    metaCreator: ActionFunction2<Arg1, Arg2, Meta>
): ActionFunction2<Arg1, Arg2, ActionMeta<Payload, Meta>>;

export function createAction<Payload, Meta, Arg1, Arg2, Arg3>(
    actionType: string,
    payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>,
    metaCreator: ActionFunction3<Arg1, Arg2, Arg3, Meta>
): ActionFunction3<Arg1, Arg2, Arg3, ActionMeta<Payload, Meta>>;

export function createAction<Payload, Meta, Arg1, Arg2, Arg3, Arg4>(
    actionType: string,
    payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>,
    metaCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Meta>
): ActionFunction4<Arg1, Arg2, Arg3, Arg4, ActionMeta<Payload, Meta>>;

export function handleAction<State, Payload>(
    actionType: string | ActionFunctions<Payload> | CombinedActionType,
    reducer: Reducer<State, Payload> | ReducerNextThrow<State, Payload>,
    initialState: State
): ReduxCompatibleReducer<State, Payload>;

export function handleAction<State, Payload, Meta>(
    actionType: string | ActionWithMetaFunctions<Payload, Meta> | CombinedActionType,
    reducer: ReducerMeta<State, Payload, Meta> | ReducerNextThrowMeta<State, Payload, Meta>,
    initialState: State
): ReduxCompatibleReducerMeta<State, Payload, Meta>;

export interface Options {
    prefix?: string;
    namespace?: string;
}

export function handleActions<StateAndPayload>(
    reducerMap: ReducerMap<StateAndPayload, StateAndPayload>,
    initialState: StateAndPayload,
    options?: Options
): ReduxCompatibleReducer<StateAndPayload, StateAndPayload>;

export function handleActions<State, Payload>(
    reducerMap: ReducerMap<State, Payload>,
    initialState: State,
    options?: Options
): ReduxCompatibleReducer<State, Payload>;

export function handleActions<State, Payload, Meta>(
    reducerMap: ReducerMapMeta<State, Payload, Meta>,
    initialState: State,
    options?: Options
): ReduxCompatibleReducerMeta<State, Payload, Meta>;

// https://github.com/redux-utilities/redux-actions/blob/v2.3.0/src/combineActions.js#L21
export function combineActions(...actionTypes: Array<ActionFunctions<any> | string | symbol>): CombinedActionType;

export interface ActionMap<Payload, Meta> {
    [actionType: string]:
    ActionMap<Payload, Meta> |
    ActionFunctionAny<Payload> |
    [ActionFunctionAny<Payload>, ActionFunctionAny<Meta>] |
    undefined;
}

export function createActions<Payload>(
    actionMapOrIdentityAction: ActionMap<Payload, any> | string,
    ...identityActions: Array<string | Options>
): {
    [actionName: string]: ActionFunctionAny<Action<Payload>>
};

export function createActions(
    actionMapOrIdentityAction: ActionMap<any, any> | string,
    ...identityActions: Array<string | Options>
): {
    [actionName: string]: ActionFunctionAny<Action<any>>
};


text:
<?php

namespace BenGorUser\User\Infrastructure\CommandBus;

/**
 * User command bus class.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 */
interface UserCommandBus
{
    /**
     * Executes the given command.
     *
     * @param mixed $aCommand The command given
     */
    public function handle($aCommand);
}


text:
package org.apache.spark.sql.execution

import org.apache.spark.SparkConf
import org.apache.spark.sql.catalyst.util.DateTimeTestUtils
import org.apache.spark.sql.connector.InMemoryTableCatalog
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.{ExamplePoint, ExamplePointUDT, SharedSparkSession}

class HiveResultSuite extends SharedSparkSession {
  import testImplicits._

  override def sparkConf: SparkConf =
    super.sparkConf
      .setAppName("test")
      .set("spark.sql.parquet.columnarReaderBatchSize", "4096")
      .set("spark.sql.sources.useV1SourceList", "avro")
      .set("spark.sql.extensions", "com.intel.oap.ColumnarPlugin")
      .set("spark.sql.execution.arrow.maxRecordsPerBatch", "4096")
      //.set("spark.shuffle.manager", "org.apache.spark.shuffle.sort.ColumnarShuffleManager")
      .set("spark.memory.offHeap.enabled", "true")
      .set("spark.memory.offHeap.size", "50m")
      .set("spark.sql.join.preferSortMergeJoin", "false")
      .set("spark.sql.columnar.codegen.hashAggregate", "false")
      .set("spark.oap.sql.columnar.wholestagecodegen", "false")
      .set("spark.sql.columnar.window", "false")
      .set("spark.unsafe.exceptionOnMemoryLeak", "false")
      //.set("spark.sql.columnar.tmp_dir", "/codegen/nativesql/")
      .set("spark.sql.columnar.sort.broadcastJoin", "true")
      .set("spark.oap.sql.columnar.preferColumnar", "true")

  ignore("date formatting in hive result") {
    DateTimeTestUtils.outstandingTimezonesIds.foreach { zoneId =>
      withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> zoneId) {
        val dates = Seq("2018-12-28", "1582-10-03", "1582-10-04", "1582-10-15")
        val df = dates.toDF("a").selectExpr("cast(a as date) as b")
        val executedPlan1 = df.queryExecution.executedPlan
        val result = HiveResult.hiveResultString(executedPlan1)
        assert(result == dates)
        val executedPlan2 = df.selectExpr("array(b)").queryExecution.executedPlan
        val result2 = HiveResult.hiveResultString(executedPlan2)
        assert(result2 == dates.map(x => s"[$x]"))
      }
    }
  }

  ignore("timestamp formatting in hive result") {
    val timestamps = Seq(
      "2018-12-28 01:02:03",
      "1582-10-03 01:02:03",
      "1582-10-04 01:02:03",
      "1582-10-15 01:02:03")
    val df = timestamps.toDF("a").selectExpr("cast(a as timestamp) as b")
    val executedPlan1 = df.queryExecution.executedPlan
    val result = HiveResult.hiveResultString(executedPlan1)
    assert(result == timestamps)
    val executedPlan2 = df.selectExpr("array(b)").queryExecution.executedPlan
    val result2 = HiveResult.hiveResultString(executedPlan2)
    assert(result2 == timestamps.map(x => s"[$x]"))
  }

  test("toHiveString correctly handles UDTs") {
    val point = new ExamplePoint(50.0, 50.0)
    val tpe = new ExamplePointUDT()
    assert(HiveResult.toHiveString((point, tpe)) === "(50.0, 50.0)")
  }

  test("decimal formatting in hive result") {
    val df = Seq(new java.math.BigDecimal("1")).toDS()
    Seq(2, 6, 18).foreach { scala =>
      val executedPlan =
        df.selectExpr(s"CAST(value AS decimal(38, $scala))").queryExecution.executedPlan
      val result = HiveResult.hiveResultString(executedPlan)
      assert(result.head.split("\\.").last.length === scala)
    }

    val executedPlan = Seq(java.math.BigDecimal.ZERO).toDS()
      .selectExpr(s"CAST(value AS decimal(38, 8))").queryExecution.executedPlan
    val result = HiveResult.hiveResultString(executedPlan)
    assert(result.head === "0.00000000")
  }

  test("SHOW TABLES in hive result") {
    withSQLConf("spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName) {
      Seq(("testcat.ns", "tbl", "foo"), ("spark_catalog.default", "tbl", "csv")).foreach {
        case (ns, tbl, source) =>
          withTable(s"$ns.$tbl") {
            spark.sql(s"CREATE TABLE $ns.$tbl (id bigint) USING $source")
            val df = spark.sql(s"SHOW TABLES FROM $ns")
            val executedPlan = df.queryExecution.executedPlan
            assert(HiveResult.hiveResultString(executedPlan).head == tbl)
          }
      }
    }
  }

  test("DESCRIBE TABLE in hive result") {
    withSQLConf("spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName) {
      Seq(("testcat.ns", "tbl", "foo"), ("spark_catalog.default", "tbl", "csv")).foreach {
        case (ns, tbl, source) =>
          withTable(s"$ns.$tbl") {
            spark.sql(s"CREATE TABLE $ns.$tbl (id bigint COMMENT 'col1') USING $source")
            val df = spark.sql(s"DESCRIBE $ns.$tbl")
            val executedPlan = df.queryExecution.executedPlan
            val expected = "id                  " +
              "\tbigint              " +
              "\tcol1                "
            assert(HiveResult.hiveResultString(executedPlan).head == expected)
          }
      }
    }
  }
}


text:
 - Make ETCD connection more Resilient
 - Make ETCD request timeout configurable
 - Support TLS Plugin
 - Optimize Governance API for Searching Schema
 - Optimize Find Instance API
 - Use glide for dependency management
 - Add release binaries for MacOS
 - Add Toplogy View and Instance View in UI

#### Bug-Fix:
 - Fix connection leak in etcd
 - Fix Lose of events in some scenarios
 - Fix Cache mismatch.

###### For more details please [click here](https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12321626&version=12342427)