text:
describe("wrapper", function(){

  describe("#connect", function(){

    describe("open event", function(){

      it("should retrieve the session id from the connect.sid cookie");
      // We need a way to simulate the browser
      // We need to set a cookie on the browser
      // We need to load the javascript into that browser's page
      // We need to run the script which attempts to connect to the server

      it("should send a message back to the server with the session id, if a session id is present");

      it("should raise an error if if is not able to obtain a connect session id");

    });

  });

});


text:
"""Runs HPC Challenge.

Homepage: http://icl.cs.utk.edu/hpcc/

Most of the configuration of the HPC-Challenge revolves around HPL, the rest of
the HPCC piggybacks upon the HPL configration.

Homepage: http://www.netlib.org/benchmark/hpl/

HPL requires a BLAS library (Basic Linear Algebra Subprograms)
OpenBlas: http://www.openblas.net/

HPL also requires a MPI (Message Passing Interface) Library
OpenMPI: http://www.open-mpi.org/

MPI needs to be configured:
Configuring MPI:
http://techtinkering.com/2009/12/02/setting-up-a-beowulf-cluster-using-open-mpi-on-linux/

Once HPL is built the configuration file must be created:
Configuring HPL.dat:
http://www.advancedclustering.com/faq/how-do-i-tune-my-hpldat-file.html
http://www.netlib.org/benchmark/hpl/faqs.html
"""

import logging
import math
import re

from perfkitbenchmarker import configs
from perfkitbenchmarker import data
from perfkitbenchmarker import flags
from perfkitbenchmarker import regex_util
from perfkitbenchmarker import sample
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.linux_packages import hpcc

FLAGS = flags.FLAGS
HPCCINF_FILE = 'hpccinf.txt'
MACHINEFILE = 'machinefile'
BLOCK_SIZE = 192
STREAM_METRICS = ['Copy', 'Scale', 'Add', 'Triad']

BENCHMARK_NAME = 'hpcc'
BENCHMARK_CONFIG = """
hpcc:
  description: Runs HPCC. Specify the number of VMs with --num_vms
  vm_groups:
    default:
      vm_spec: *default_single_core
      vm_count: null
"""

flags.DEFINE_integer('memory_size_mb',
                     None,
                     'The amount of memory in MB on each machine to use. By '
                     'default it will use the entire system\'s memory.')

def GetConfig(user_config):
  return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)

def CheckPrerequisites():
  """Verifies that the required resources are present.

  Raises:
    perfkitbenchmarker.data.ResourceNotFound: On missing resource.
  """
  data.ResourcePath(HPCCINF_FILE)

def CreateMachineFile(vms):
  """Create a file with the IP of each machine in the cluster on its own line.

  Args:
    vms: The list of vms which will be in the cluster.
  """
  with vm_util.NamedTemporaryFile() as machine_file:
    master_vm = vms[0]
    machine_file.write('localhost slots=%d\n' % master_vm.num_cpus)
    for vm in vms[1:]:
      machine_file.write('%s slots=%d\n' % (vm.internal_ip,
                                            vm.num_cpus))
    machine_file.close()
    master_vm.PushFile(machine_file.name, MACHINEFILE)

def CreateHpccinf(vm, benchmark_spec):
  """Creates the HPCC input file."""
  num_vms = len(benchmark_spec.vms)
  if FLAGS.memory_size_mb:
    total_memory = FLAGS.memory_size_mb * 1024 * 1024 * num_vms
  else:
    stdout, _ = vm.RemoteCommand("free | sed -n 3p | awk {'print $4'}")
    available_memory = int(stdout)
    total_memory = available_memory * 1024 * num_vms
  total_cpus = vm.num_cpus * num_vms
  block_size = BLOCK_SIZE

  # Finds a problem size that will fit in memory and is a multiple of the
  # block size.
  base_problem_size = math.sqrt(total_memory * .1)
  blocks = int(base_problem_size / block_size)
  blocks = blocks if (blocks % 2) == 0 else blocks - 1
  problem_size = block_size * blocks

  # Makes the grid as 'square' as possible, with rows < columns
  sqrt_cpus = int(math.sqrt(total_cpus)) + 1
  num_rows = 0
  num_columns = 0
  for i in reversed(range(sqrt_cpus)):
    if total_cpus % i == 0:
      num_rows = i
      num_columns = total_cpus / i
      break

  file_path = data.ResourcePath(HPCCINF_FILE)
  vm.PushFile(file_path, HPCCINF_FILE)
  sed_cmd = (('sed -i -e "s/problem_size/%s/" -e "s/block_size/%s/" '
              '-e "s/rows/%s/" -e "s/columns/%s/" %s') %
             (problem_size, block_size, num_rows, num_columns, HPCCINF_FILE))
  vm.RemoteCommand(sed_cmd)

def PrepareHpcc(vm):
  """Builds HPCC on a single vm."""
  logging.info('Building HPCC on %s', vm)
  vm.Install('hpcc')

def Prepare(benchmark_spec):
  """Install HPCC on the target vms.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.
  """
  vms = benchmark_spec.vms
  master_vm = vms[0]

  PrepareHpcc(master_vm)
  CreateHpccinf(master_vm, benchmark_spec)
  CreateMachineFile(vms)
  master_vm.RemoteCommand('cp %s/hpcc hpcc' % hpcc.HPCC_DIR)

  for vm in vms[1:]:
    vm.Install('fortran')
    master_vm.MoveFile(vm, 'hpcc', 'hpcc')
    master_vm.MoveFile(vm, '/usr/bin/orted', 'orted')
    vm.RemoteCommand('sudo mv orted /usr/bin/orted')

def ParseOutput(hpcc_output, benchmark_spec):
  """Parses the output from HPCC.

  Args:
    hpcc_output: A string containing the text of hpccoutf.txt.
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.

  Returns:
    A list of samples to be published (in the same format as Run() returns).
  """
  results = []

  metadata = dict()
  match = re.search('HPLMaxProcs=([0-9]*)', hpcc_output)
  metadata['num_cpus'] = match.group(1)
  metadata['num_machines'] = len(benchmark_spec.vms)
  metadata['memory_size_mb'] = FLAGS.memory_size_mb
  value = regex_util.ExtractFloat('HPL_Tflops=([0-9]*\\.[0-9]*)', hpcc_output)
  results.append(sample.Sample('HPL Throughput', value, 'Tflops', metadata))

  value = regex_util.ExtractFloat('SingleRandomAccess_GUPs=([0-9]*\\.[0-9]*)',
                                  hpcc_output)
  results.append(sample.Sample('Random Access Throughput', value,
                               'GigaUpdates/sec'))

  for metric in STREAM_METRICS:
    regex = 'SingleSTREAM_%s=([0-9]*\\.[0-9]*)' % metric
    value = regex_util.ExtractFloat(regex, hpcc_output)
    results.append(sample.Sample('STREAM %s Throughput' % metric, value,
                                 'GB/s'))

  return results

def Run(benchmark_spec):
  """Run HPCC on the cluster.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.

  Returns:
    A list of sample.Sample objects.
  """
  vms = benchmark_spec.vms
  master_vm = vms[0]
  num_processes = len(vms) * master_vm.num_cpus

  mpi_cmd = ('mpirun -np %s -machinefile %s --mca orte_rsh_agent '
             '"ssh -o StrictHostKeyChecking=no" ./hpcc' %
             (num_processes, MACHINEFILE))
  master_vm.RobustRemoteCommand(mpi_cmd)
  logging.info('HPCC Results:')
  stdout, _ = master_vm.RemoteCommand('cat hpccoutf.txt', should_log=True)

  return ParseOutput(stdout, benchmark_spec)

def Cleanup(benchmark_spec):
  """Cleanup HPCC on the cluster.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.
  """
  vms = benchmark_spec.vms
  master_vm = vms[0]
  master_vm.RemoveFile('hpcc*')
  master_vm.RemoveFile(MACHINEFILE)

  for vm in vms[1:]:
    vm.RemoveFile('hpcc')
    vm.RemoveFile('/usr/bin/orted')

redpajama_set_name: RedPajamaGithub


text:
class LongDataRecord(object):

    def __init__(self):
        self.longData = None
        self.name = None
        self.dimension = None
        self.sizes = None
        self.maxSizes = None
        self.props = None
        self.minIndex = None
        self.group = None
        self.dataAttributes = None
        self.fillValue = None
        self.maxChunkSize = None

    def getLongData(self):
        return self.longData

    def setLongData(self, longData):
        self.longData = longData

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

    def getDimension(self):
        return self.dimension

    def setDimension(self, dimension):
        self.dimension = dimension

    def getSizes(self):
        return self.sizes

    def setSizes(self, sizes):
        self.sizes = sizes

    def getMaxSizes(self):
        return self.maxSizes

    def setMaxSizes(self, maxSizes):
        self.maxSizes = maxSizes

    def getProps(self):
        return self.props

    def setProps(self, props):
        self.props = props

    def getMinIndex(self):
        return self.minIndex

    def setMinIndex(self, minIndex):
        self.minIndex = minIndex

    def getGroup(self):
        return self.group

    def setGroup(self, group):
        self.group = group

    def getDataAttributes(self):
        return self.dataAttributes

    def setDataAttributes(self, dataAttributes):
        self.dataAttributes = dataAttributes

    def getFillValue(self):
        return self.fillValue

    def setFillValue(self, fillValue):
        self.fillValue = fillValue

    def getMaxChunkSize(self):
        return self.maxChunkSize

    def setMaxChunkSize(self, maxChunkSize):
        self.maxChunkSize = maxChunkSize

    def retrieveDataObject(self):
        return self.getLongData()

    def putDataObject(self, obj):
        self.setLongData(obj)


text:
package org.optaplanner.core.impl.exhaustivesearch.node.comparator;

import org.junit.Test;

public class OptimisticBoundFirstNodeComparatorTest extends AbstractNodeComparatorTest {

    @Test
    public void compare() {
        OptimisticBoundFirstNodeComparator comparator = new OptimisticBoundFirstNodeComparator(true);
        assertScoreCompareToOrder(comparator,
                buildNode(1, -110, 5, 40),
                buildNode(1, -110, 7, 40),
                buildNode(2, -110, 5, 40),
                buildNode(2, -110, 7, 40),
                buildNode(1, -90, 5, 40),
                buildNode(1, -90, 7, 40),
                buildNode(2, -90, 5, 40),
                buildNode(2, -90, 7, 40),
                buildNode(1, -95, 0, 5, 40),
                buildNode(2, -95, 0, 5, 40),
                buildNode(2, -95, 0, 7, 40));
    }

}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="author" content="Wesam Haboush" />
<meta name="description" content="Personal blog." />
<meta name="keywords" content="blog, tech" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<meta name="generator" content="Hugo 0.40.3" />

<link rel="canonical" href="http://wesamhaboush.github.io/posts/copy-paste-safe-loggers/">
<base href="http://wesamhaboush.github.io/" />
<meta property="og:title" content="Copy/Paste-safe Loggers" />
<meta property="og:description" content="Loggers Problem Developers commonly create loggers for classes by copying logger creation lines from other classes. The process is so repetitive and error-prone that often they forget to update the line to reflect the actual class where the statement was pasted. This is compounded by the fact that IDEs normally auto-import the foreign class. We all saw classes that had the wrong logger like this:
 public class X { private static final Logger LOG = Logger." />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://wesamhaboush.github.io/posts/copy-paste-safe-loggers/" />

<meta property="article:published_time" content="2015-10-06T00:00:00+00:00"/>

<meta property="article:modified_time" content="2015-10-06T00:00:00+00:00"/>

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Copy/Paste-safe Loggers"/>
<meta name="twitter:description" content="Loggers Problem Developers commonly create loggers for classes by copying logger creation lines from other classes. The process is so repetitive and error-prone that often they forget to update the line to reflect the actual class where the statement was pasted. This is compounded by the fact that IDEs normally auto-import the foreign class. We all saw classes that had the wrong logger like this:
 public class X { private static final Logger LOG = Logger."/>

<meta itemprop="name" content="Copy/Paste-safe Loggers">
<meta itemprop="description" content="Loggers Problem Developers commonly create loggers for classes by copying logger creation lines from other classes. The process is so repetitive and error-prone that often they forget to update the line to reflect the actual class where the statement was pasted. This is compounded by the fact that IDEs normally auto-import the foreign class. We all saw classes that had the wrong logger like this:
 public class X { private static final Logger LOG = Logger.">

<meta itemprop="datePublished" content="2015-10-06T00:00:00+00:00" />
<meta itemprop="dateModified" content="2015-10-06T00:00:00+00:00" />
<meta itemprop="wordCount" content="438">

<meta itemprop="keywords" content="" />

<link rel="stylesheet" href="css/layout.css" />

<title>

     Copy/Paste-safe Loggers

</title>

      The Art Of Computer Science

Posts

About Me

email

gh

in

 Copy/Paste-safe Loggers

Loggers Problem

Developers commonly create loggers for classes by copying logger creation lines from other classes. The process is so repetitive and error-prone that often they forget to update the line to reflect the actual class where the statement was pasted. This is compounded by the fact that IDEs normally auto-import the foreign class. We all saw classes that had the wrong logger like this:

public class X {
 private static final Logger LOG = Logger.getLogger(Y.class);
}

In this post, I offer a solution that worked for me.

Target Scheme For Obtaining Loggers

Ultimately, I would like to be able to do some thing like:

public class X {
 private static final Logger LOG = createLogger();
}

It is almost like we need an annotation or injected/configured service a la Spring. In the absence of these I came up with an implementation that relies on static loading of classes to obtain the class name. Have a look:

public class X {
 private static final Logger LOG = SLF4JLoggerFactory.INSTANCE.create();
}

copying the above code will simply work without needing to change anything on this line! it is essentially copy/paste safe!

Implementation Details

The main components of this implementation are:

The Factory interface is a simple interface that marks classes that make things.

The enum SLF4JLoggerFactory implements the above interface with an output product of type Logger. You can use it with Slf4j or log4j (and possibly others).

The Classes class has a couple of helper methods to find the class (or className) from the runtime static invocation of Logger creation invocation.

Here is the implementation of these components:

First the Factory:

package uk.co.codebreeze.commons.lang;

public interface Factory<T> {
    T create();
}

Then the enum implementing the Factory interface:

package uk.co.codebreeze.commons.lang;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum SLF4JLoggerFactory implements Factory<Logger> {

    INSTANCE;

    @Override
    public Logger create() {
        return LoggerFactory.getLogger(Classes.getInvokerClassOfCurrentMethod());
    }
}

Finally, the Classes helper class:

package uk.co.codebreeze.commons.lang;

import java.util.List;

public class Classes {
  private Classes() {
  }

  public static Class<?> getInvokerClassOfCurrentMethod() {
    final Class<?>[] classes = new ClassesHelper().getClassContext();
    return classes[3];
  }

  private static final class ClassesHelper extends SecurityManager {
    @Override
    protected Class<?>[] getClassContext() {
      return super.getClassContext();
    }
  }
}

Final Thoughts

I do not think this is the only or the best implementation. It is just an implementation that worked for me. I am sure many other engineers will be able to come up with other ideas.

I would recommend you put such implementation in a logger-extra module if you use maven, and make your projects pull it as a dependency, as opposed to embedding this code in every project.

As always, constructive feedback is welcome, and actually strongly appreciated.

 Oct 6, 2015

Email

GitHub

LinkedIn

  RSS

 Copyright (c) 2018, all rights reserved.

    Powered by Hugo.


text:
package com.silicon.rest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.gson.Gson;
import com.silicom.utils.PropUtil;
import com.silicon.entities.Restaurant;
import com.silicon.entities.User;
import com.silicon.dao.RestaurantDao;
import com.silicon.dao.UserDao;

public class GetRestaurants extends ServerResource {

	private static final Logger _logger = Logger
			.getLogger(GetRestaurants.class.getName());

	@SuppressWarnings("finally")
	@Post("json:json")
	public Representation acceptJson(JsonRepresentation represent)
			throws ResourceException {

		Representation rep = null;
		JSONStringer jsReply = null;
		String result;
		String jsonRestaurantList = null;
		try {
			ArrayList <Restaurant> restauranteList = RestaurantDao.fetch();
			if (!(restauranteList.size()>0)){
				jsReply = new JSONStringer();
				jsReply.object();
				jsReply.key("code").value(PropUtil.GR_I_EMP);
				jsReply.key("desc").value(PropUtil.getPropierties().get(PropUtil.GR_I_EMP));
				jsReply.endObject();
			}else {
				Gson gson = new Gson();
				jsonRestaurantList = gson.toJson(restauranteList);
			}
			getResponse().setStatus(Status.SUCCESS_OK);
		} catch (Exception e) {
			_logger.warning(e.toString());
			try {
				jsReply = new JSONStringer();
				jsReply.object();
				jsReply.key("code").value("ERROR");
				jsReply.key("desc").value(e.getMessage());
				jsReply.endObject();
			} catch (JSONException e1) {
				_logger.severe(e1.toString());
			}
			getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
		} finally {
			if (jsReply!=null){
				rep = new JsonRepresentation(jsReply);
			} else {
				rep = new JsonRepresentation(jsonRestaurantList);
			}
			return rep;
		}
	}
}


text:
package org.apache.shardingsphere.elasticjob.tracing.api;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.elasticjob.api.JobExtraConfiguration;
import org.apache.shardingsphere.elasticjob.tracing.exception.TracingStorageConverterNotFoundException;
import org.apache.shardingsphere.elasticjob.tracing.storage.TracingStorageConverterFactory;

/**
 * Tracing configuration.
 *
 * @param <T> type of tracing storage
 */
@Getter
@RequiredArgsConstructor
public final class TracingConfiguration<T> implements JobExtraConfiguration {

    private final String type;

    private final TracingStorageConfiguration<T> tracingStorageConfiguration;

    @SuppressWarnings("unchecked")
    public TracingConfiguration(final String type, final T storage) {
        this.type = type;
        this.tracingStorageConfiguration = TracingStorageConverterFactory.findConverter((Class<T>) storage.getClass())
                .orElseThrow(() -> new TracingStorageConverterNotFoundException(storage.getClass())).convertObjectToConfiguration(storage);
    }
}


text:
module Enum
  module Predicates
    def enumerize(field, enum)
      define_method("#{field}_is?") do |other|
        if (field_value = public_send(field)) && other
          enum.enum(field_value) == enum.enum(other)
        else
          false
        end
      end

      define_method("#{field}_any?") do |*others|
        others.each { |other| enum.enum(other) } # make sure that all others values are valid enums
        others.any? { |other| public_send("#{field}_is?", other) }
      end
    end
  end
end


text:
package sg.edu.cs2103aug2015_w13_2j.commands;

import java.util.ArrayList;
import java.util.logging.Logger;

import sg.edu.cs2103aug2015_w13_2j.LogicInterface;
import sg.edu.cs2103aug2015_w13_2j.Task;
import sg.edu.cs2103aug2015_w13_2j.exceptions.TaskNotFoundException;
import sg.edu.cs2103aug2015_w13_2j.parser.Command;
import sg.edu.cs2103aug2015_w13_2j.ui.FeedbackMessage;
import sg.edu.cs2103aug2015_w13_2j.ui.FeedbackMessage.FeedbackType;

// @@author A0130894B

/**
 * Toggles a Task specified by the user as "Important" or "Unimportant". An
 * index that refers to that task, or indexes that refer to the multiple tasks
 * to be marked is expected to be specified.
 *
 * A user feedback message will subsequently be returned upon marking the task.
 * If the Task index specified is out of range, or does not exist, a user error
 * message will be returned.
 *
 * @author Natasha Koh Sze Sze
 */
public class MarkImportantHandler extends CommandHandler {
    public static final String SET_IMPORTANT_SUCCESS = "Task has been set as important.";
    public static final String SET_UNIMPORTANT_SUCCESS = "Task has been set as unimportant.";
    private static final Logger LOGGER = Logger
            .getLogger(MarkImportantHandler.class.getName());
    private static final String NAME = "Mark Important";
    private static final String SYNTAX = "<TASK_ID>";
    private static final String[] FLAGS = {};
    private static final String[] OPTIONS = { OPTION_TASK_ID };
    private static final String[] RESERVED = { "i", "impt", "!" };
    private LogicInterface mLogic;

    public MarkImportantHandler() {
        super(NAME, SYNTAX, FLAGS, OPTIONS, RESERVED);
    }

    @Override
    public void execute(LogicInterface logic, Command command) {
        assert (logic != null);
        mLogic = logic;
        try {
            ArrayList<Integer> markIndexes = command.getAllIdTokenValues();
            assert (markIndexes != null);
            boolean noValidIndexFound = markIndexes.isEmpty();
            if (noValidIndexFound) {
                mLogic.feedback(FeedbackMessage.ERROR_INVALID_INDEX);
            } else {
                markAllSelectedTasks(markIndexes);
            }
        } catch (TaskNotFoundException e) {
            mLogic.feedback(FeedbackMessage.ERROR_TASK_NOT_FOUND);
        }
    }

    /**
     * Marks the list of {@link Task} objects associated with the list of
     * indexes specified by the user as important.
     *
     * @param markIndexes
     *            The list of indexes that represent the items to mark as
     *            completed.
     * @throws TaskNotFoundException
     *             Thrown when the provided index is out of bounds.
     */
    private void markAllSelectedTasks(ArrayList<Integer> markIndexes)
            throws TaskNotFoundException {
        for (Integer index : markIndexes) {
            Task task = mLogic.getTask(index);
            if (task.isImportant()) {
                task.setImportant(false);
                logImportantTask(task);
                mLogic.feedback(new FeedbackMessage(SET_UNIMPORTANT_SUCCESS,
                        FeedbackType.INFO));
            } else {
                task.setImportant(true);
                logImportantTask(task);
                mLogic.feedback(new FeedbackMessage(SET_IMPORTANT_SUCCESS,
                        FeedbackType.INFO));
            }
        }
        mLogic.clearRedoHistory();
        mLogic.storeCommandInHistory();
    }

    /**
     * Logs the name and date created of the Task object being processed.
     *
     * @param task
     *            Task object to be logged.
     */
    private void logImportantTask(Task task) {
        String nameOfTask = task.getName();
        LOGGER.info("[CommandHandler][MarkImportantHandler] '" + nameOfTask
                + "' importance status is: " + task.isImportant());
    }
}


text:
package org.dcm4chee.web.common.base;

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

import javax.servlet.http.Cookie;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;
import org.dcm4chee.web.common.secure.SecureAjaxTabbedPanel;

/**
 * @author Franz Willer <franz.willer@gmail.com>
 * @author Robert David <robert.david@agfa.com>
 * @version $Revision$ $Date$
 * @since July 12, 2009
 */

public class ModuleSelectorPanel extends SecureAjaxTabbedPanel {

    private static final long serialVersionUID = 1L;

    public boolean showLogout = true;

    public ModuleSelectorPanel(String id) {
        super(id);

        boolean found = false;
        Cookie[] cs = ((WebRequest) RequestCycle.get().getRequest()).getHttpServletRequest().getCookies();
        if (cs != null)
            for (Cookie c : cs) {
                if (c.getName().equals("WEB3LOCALE")) {
                    getSession().setLocale(new Locale(c.getValue()));
                    found = true;
                    break;
                }
            }

        if (!found) {
            ((WebResponse) RequestCycle.get().getResponse()).addCookie(new Cookie("WEB3LOCALE", "en"));
            getSession().setLocale(new Locale("en"));
        }

        add(new AjaxFallbackLink<Object>("logout") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(final AjaxRequestTarget target) {
                getSession().invalidate();
                setResponsePage(getApplication().getHomePage());
            }
            @Override
            public boolean isVisible() {
                return showLogout;
            }
        }.add(new Label("logoutLabel", new ResourceModel("logout"))));

        List<String> languages = new ArrayList<String>();
        languages.add("en");
        languages.add("de");
        languages.add("ja");

        final DropDownChoice<String> languageSelector =
            new DropDownChoice<String>("language", new Model<String>(), languages, new ChoiceRenderer<String>() {

            private static final long serialVersionUID = 1L;

            @Override
            public String getDisplayValue(String object) {
                Locale l = new Locale(object);
                return l.getDisplayName(l);
            }
        }) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSelectionChanged(String newSelection) {
                ((WebResponse) RequestCycle.get().getResponse()).addCookie(new Cookie("WEB3LOCALE", newSelection));
                getSession().setLocale(new Locale(newSelection));
            }
        };
        languageSelector.setDefaultModelObject(getSession().getLocale().getLanguage());
        languageSelector.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            private static final long serialVersionUID = 1L;

            protected void onUpdate(AjaxRequestTarget target) {
                languageSelector.onSelectionChanged();
                target.addComponent(getPage().setOutputMarkupId(true));
            }
        });
        add(languageSelector);

        add(new Image("img_logo", new ResourceReference(ModuleSelectorPanel.class,
                "images/logo.gif"))
        );
    }

    public void addModule(final Class<? extends Panel> clazz) {
        super.addModule(clazz, null);
        if (clazz.getResource("base-style.css") != null)
            add(CSSPackageResource.getHeaderContribution(clazz, "base-style.css"));
    }

    public void addInstance(Panel instance) {
        addInstance(instance, null);
    }

    public void addInstance(Panel instance, IModel<String> titleModel) {
        super.addModule(instance.getClass(), titleModel);
        if (instance.getClass().getResource("base-style.css") != null)
            add(CSSPackageResource.getHeaderContribution(instance.getClass(), "base-style.css"));
    }

    public ModuleSelectorPanel setShowLogoutLink(boolean show) {
        showLogout = show;
        return this;
    }
}


text:
What is YetiScript?
-------------------
YetiScript compiles [yeti](http://mth.github.io/yeti/) code to JavaScript.

Yeti is an ML-style functional programming language, with static type-inference  with tries to be clean and minimal expressive and to interface well with JavaScript code.

YetiScript tries to be as close to yeti as it can, however there are some [differences](https://github.com/chrisichris/yetiscript/wiki/Differences-to-Yeti).

TOC
---
* [Status](#status)
* [Get Started](#get-started)
* [Basic Usage](#basic-usage)
* [Questions, Feedback](#questions-feedback)
* [Documentation](#documentation)
* [Credits](#credits)

## Status

YetiScript is in early development and still very buggy, however it compiles nearly all of yeti-code.

#### Update Version 0.2.1
* 26-11-2014 Chrome Extension using the build in compileserver as seperat project [YetiScriptConsole](https://github.com/chrisichris/yetiscript-console)
* 26-11-2014 fixed bug in npm module logging jar which node did not understand
* 25-11-2014 added webserver to use compiler/repl as local rest-api
use the -server swith on yjs to start a NanoHTTPD server wich compiles yetiscript as rest-service.
* 21-11-2014 repl now works with rhino
* 21-11-2014 removed dependencie on lo-dash
The import was making trouble, so I went further to remove it all together

#### Updates Version 0.1.1
* 20-11-2014 Published to npm
YetiScript can be installed as a node.js module. The modulename is ``yetiscript`` the if installed globally it can be invoked with the ``yjs`` command.
* 20-11-2014 New Versioning Scheme and Version 0.1.1
Yetiscript uses the node.js versioning scheme. And starts all over new with Version 0.1.1. The version is in the std api ``yetiScriptVersion``. The version of yeti the current YetiScript is based on is in ``yetiVersion`` (0.9.9+)
* 18-11-2014 Scoping like in yeti
Before YetiScript used the same local scope as JavaScript (function-scope). Within the same function body a name could only be bound once. Now shadowing, structure and functions-scoping is like in yeti. Bindings with the same name in ohne function get translated to javascript with appending numbers ie
    fn x =
      (x = x + 2;
       x);
translates to
    var fn = function fn(x) {
      x1 = x + 2;
      return x1;
    }

## Get Started

Java JDK7 is required an ``java`` must be on the path.
YetiScript itself is distributed as a npm-module. To install it execute the
follwing commands

    //test jave version
    >java -version
    java version "1.7.0....."

    //install yetiscript
    >npm install yetiscript -g
    ....

    //use yjs to run the yetiscript compiler
    >yjs
    help msg ....

Alternatively (and to use the lates version) you can git clone it and build it
with ant

    > git clone git://github.com/chrisichris/yetiscript.git
    > cd yetiscript
    > ant

The resulting ``yjs.jar`` contains everything needed and can be use like the
npm ``yjs`` command:

## Basic Usage

Evaluate an expression with node:

    $yjs -e "1 + 1" | node

evaluate an expression with rhino (build into JDK7):

    $yjs -r -e "1 + 1"

run an example using node:

    yjs examples/fact.yjs | node

run an example using the build in rhino:

    yjs -r examples/fact.yjs

compile an example to `build` directory

    yjs -d build examples/fact.yjs

print help

    yjs yjs.jar -h

## Questions Feedback

Please point all your questions and feedback to the [yeti mailinglist](https://groups.google.com/forum/#!forum/yeti-lang).

## Documentation

 - [tutorial](http://dot.planet.ee/yeti/intro.html) - tutorial for the original yeti language (note the differences doc)
 - [differences to yeti]( https://github.com/chrisichris/yetiscript/wiki/Differences-to-Yeti) - differences of yetiscript to yeti
 - [yeti std api](http://dot.planet.ee/yeti/docs/latest/yeti.lang.std.html) - api docs for the std api of yeti which is nearly identical to yetiscripts std
   is mostly supported)
 - [std.yjs](https://github.com/chrisichris/yetiscript/blob/master/modules/std.yjs) : the source of the YetiScript std api
 - [yeti homepage](http://mth.github.io/yeti/) : the homepage of yeti with a lot more info
 - [YetiScript wiki](https://github.com/chrisichris/yetiscript/wiki): feel free to add

## Credits

YetiScript is a fork of [yeti](http://mth.github.io/yeti/) by Madis Janson.
YetiScript adds a JavaScript backend to the yeti compiler - which does the
bulk of the work.

Uses the following apis:
- [nanohttpd](https://github.com/NanoHttpd/nanohttpd) (modified BSD license)


text:
namespace Raven.Workshop.Web.Models
{
    using System.ComponentModel.DataAnnotations;

    public class Employee
	{
		public string Id { get; set; }

		[Required(ErrorMessage = "Imię jest wymagane.")]
		[Display(Name = "Imię")]
		public string FirstName { get; set; }

        [Required(ErrorMessage = "Nazwisko jest wymagane.")]
		[Display(Name = "Nazwisko")]
		public string LastName { get; set; }

        [Required(ErrorMessage = "Wiek jest wymagany.")]
		[Display(Name = "Wiek")]
		public uint Age { get; set; }
	}
}


text:
package v1beta1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// EgressSelectorConfiguration provides versioned configuration for egress selector clients.
type EgressSelectorConfiguration struct {
	metav1.TypeMeta `json:",inline"`

	// connectionServices contains a list of egress selection client configurations
	EgressSelections []EgressSelection `json:"egressSelections"`
}

// EgressSelection provides the configuration for a single egress selection client.
type EgressSelection struct {
	// name is the name of the egress selection.
	// Currently supported values are "Master", "Etcd" and "Cluster"
	Name string `json:"name"`

	// connection is the exact information used to configure the egress selection
	Connection Connection `json:"connection"`
}

// Connection provides the configuration for a single egress selection client.
type Connection struct {
	// Protocol is the protocol used to connect from client to the konnectivity server.
	ProxyProtocol ProtocolType `json:"proxyProtocol,omitempty"`

	// Transport defines the transport configurations we use to dial to the konnectivity server.
	// This is required if ProxyProtocol is HTTPConnect or GRPC.
	// +optional
	Transport *Transport `json:"transport,omitempty"`
}

// ProtocolType is a set of valid values for Connection.ProtocolType
type ProtocolType string

// Valid types for ProtocolType for konnectivity server
const (
	// Use HTTPConnect to connect to konnectivity server
	ProtocolHTTPConnect ProtocolType = "HTTPConnect"
	// Use grpc to connect to konnectivity server
	ProtocolGRPC ProtocolType = "GRPC"
	// Connect directly (skip konnectivity server)
	ProtocolDirect ProtocolType = "Direct"
)

// Transport defines the transport configurations we use to dial to the konnectivity server
type Transport struct {
	// TCP is the TCP configuration for communicating with the konnectivity server via TCP
	// ProxyProtocol of GRPC is not supported with TCP transport at the moment
	// Requires at least one of TCP or UDS to be set
	// +optional
	TCP *TCPTransport `json:"tcp,omitempty"`

	// UDS is the UDS configuration for communicating with the konnectivity server via UDS
	// Requires at least one of TCP or UDS to be set
	// +optional
	UDS *UDSTransport `json:"uds,omitempty"`
}

// TCPTransport provides the information to connect to konnectivity server via TCP
type TCPTransport struct {
	// URL is the location of the konnectivity server to connect to.
	// As an example it might be "https://127.0.0.1:8131"
	URL string `json:"url,omitempty"`

	// TLSConfig is the config needed to use TLS when connecting to konnectivity server
	// +optional
	TLSConfig *TLSConfig `json:"tlsConfig,omitempty"`
}

// UDSTransport provides the information to connect to konnectivity server via UDS
type UDSTransport struct {
	// UDSName is the name of the unix domain socket to connect to konnectivity server
	// This does not use a unix:// prefix. (Eg: /etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket)
	UDSName string `json:"udsName,omitempty"`
}

// TLSConfig provides the authentication information to connect to konnectivity server
// Only used with TCPTransport
type TLSConfig struct {
	// caBundle is the file location of the CA to be used to determine trust with the konnectivity server.
	// Must be absent/empty if TCPTransport.URL is prefixed with http://
	// If absent while TCPTransport.URL is prefixed with https://, default to system trust roots.
	// +optional
	CABundle string `json:"caBundle,omitempty"`

	// clientKey is the file location of the client key to be used in mtls handshakes with the konnectivity server.
	// Must be absent/empty if TCPTransport.URL is prefixed with http://
	// Must be configured if TCPTransport.URL is prefixed with https://
	// +optional
	ClientKey string `json:"clientKey,omitempty"`

	// clientCert is the file location of the client certificate to be used in mtls handshakes with the konnectivity server.
	// Must be absent/empty if TCPTransport.URL is prefixed with http://
	// Must be configured if TCPTransport.URL is prefixed with https://
	// +optional
	ClientCert string `json:"clientCert,omitempty"`
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
**
** Copyright 2016, The Android Open Source Project
**
** 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.
*/
-->

<!-- Layout for {@link com.android.systemui.tv.pip.PipControlsView}. -->
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <com.android.systemui.tv.pip.PipControlButtonView
        android:id="@+id/full_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_fullscreen_white_24dp"
        android:text="@string/pip_fullscreen" />

    <com.android.systemui.tv.pip.PipControlButtonView
        android:id="@+id/close_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="-50dp"
        android:src="@drawable/ic_close_white"
        android:text="@string/pip_close" />

    <com.android.systemui.tv.pip.PipControlButtonView
        android:id="@+id/play_pause_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="-50dp"
        android:src="@drawable/ic_pause_white_24dp"
        android:text="@string/pip_pause" />
</merge>


text:
package se.l4.dust.jaxrs.internal.asset;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.google.inject.Inject;
import com.google.inject.Stage;

import se.l4.dust.api.asset.Asset;
import se.l4.dust.api.resource.Resource;

/**
 * {@link MessageBodyWriter} for {@link Asset}.
 *
 * @author Andreas Holstenson
 */
@Provider
@Produces("*/*")
public class AssetWriter
	implements MessageBodyWriter<Asset>
{
	private final boolean development;
	private final long maxAge;

	@Inject
	public AssetWriter(Stage stage)
	{
		development = stage == Stage.DEVELOPMENT;

		long time = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, 1);
		c.add(Calendar.DAY_OF_MONTH, -1);

		maxAge = c.getTimeInMillis() - time;
	}

	@Override
	public long getSize(Asset t, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType)
	{
		Resource resource = t.getResource();
		return resource.getContentLength();
	}

	@Override
	public boolean isWriteable(Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType)
	{
		return Asset.class.isAssignableFrom(type);
	}

	@Override
	public void writeTo(Asset t, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders,
			OutputStream entityStream)
		throws IOException, WebApplicationException
	{
		Resource resource = t.getResource();

		if(false == development)
		{
			httpHeaders.putSingle("Cache-Control", "public, max-age=" + maxAge);
			httpHeaders.putSingle("Date", new Date());
			httpHeaders.putSingle("Expires", new Date(System.currentTimeMillis() + maxAge));
		}

		String contentType = getMimeType(t);
		httpHeaders.putSingle("Last-Modified", new Date(resource.getLastModified()));

		if(contentType != null)
		{
			httpHeaders.putSingle("Content-Type", contentType);
		}

		InputStream stream = null;
		try
		{
			stream = resource.openStream();

			byte[] buffer = new byte[1024];
			int l;
			while((l = stream.read(buffer)) != -1)
			{
				entityStream.write(buffer, 0, l);
			}
		}
		finally
		{
			if(stream != null)
			{
				stream.close();
			}
		}
	}

	public static String getMimeType(Asset asset)
	{
		String contentType = asset.getResource().getContentType();
		if(contentType == null || "".equals(contentType) || "content/unknown".equals(contentType) || "unknown".equals(contentType))
		{
			contentType = getLazyMimeType(asset);
		}

		return contentType;
	}

	private static String getLazyMimeType(Asset asset)
	{
		String name = asset.getName();
		if(name.endsWith(".css"))
		{
			return "text/css";
		}
		else if(name.endsWith(".js"))
		{
			return "text/javascript";
		}
		else if(name.endsWith(".woff"))
		{
			return "application/x-font-woff";
		}
		else
		{
			return "application/octet-stream";
		}
	}
}


text:
class UsersController < InheritedResources::Base
  access_control do
    allow logged_in
  end

  respond_to :html, :xml, :json
end


text:
#ifndef ALITRDDATADCS_H
#define ALITRDDATADCS_H

/* $Id$ */

////////////////////////////////////////////////////////////////////////////
//                                                                        //
// Extracts the DCS information                                           //
//                                                                        //
////////////////////////////////////////////////////////////////////////////

#include <TNamed.h>

class TObjArray;
class TString;

class TGraph;
class AliSplineFit;
class TMap;

class AliTRDDataDCS : public TNamed
{

 public :

  AliTRDDataDCS ();
  ~AliTRDDataDCS ();

  Bool_t ExtractDCS (TMap * aliDCS);
  Bool_t PerformFit ();
  void   ClearFits ();
  void   ClearGraphs ();

  UInt_t 	GetNAlias () const {return fNAlias;}
  TString       GetAmandaStr (UInt_t iAlias) const;
  UInt_t 	GetNChannel (UInt_t iAlias) const;

  TGraph * 		GetGraph (UInt_t iAlias, UInt_t iChannel = 0) const;
  AliSplineFit * 	GetFit (UInt_t iAlias, UInt_t iChannel = 0) const;

  // Get TGraph
  TGraph * GetGraphChamberByteStatus (UInt_t iSensor) const	        {return GetGraph (kChamberByteStatus, iSensor);}
  TGraph * GetGraphPreTrigger () const 					{return GetGraph (kPreTrigger);}
  TGraph * GetGraphGoofyHv () const			        	{return GetGraph (kGoofyHv);}
  TGraph * GetGraphGoofyPeakPos (UInt_t iSensor) const	                {return GetGraph (kGoofyPeakPos, iSensor);}
  TGraph * GetGraphGoofyPeakArea (UInt_t iSensor) const 	        {return GetGraph (kGoofyPeakArea, iSensor);}
  TGraph * GetGraphGoofyTemp (UInt_t iSensor) const		        {return GetGraph (kGoofyTemp, iSensor);}
  TGraph * GetGraphGoofyPressure () const 				{return GetGraph (kGoofyPressure);}
  TGraph * GetGraphGoofyVelocity () const 				{return GetGraph (kGoofyVelocity);}
  TGraph * GetGraphGoofyGain (UInt_t iSensor) const		        {return GetGraph (kGoofyGain, iSensor);}
  TGraph * GetGraphGoofyCO2 ()  const					{return GetGraph (kGoofyCO2);}
  TGraph * GetGraphGoofyN2 () const 					{return GetGraph (kGoofyN2);}
  TGraph * GetGraphGasO2 () const 					{return GetGraph (kGasO2);}
  TGraph * GetGraphGasOverpressure () const 				{return GetGraph (kGasOverpressure);}
  TGraph * GetGraphEnvTemp (UInt_t iSensor) const			{return GetGraph (kEnvTemp, iSensor);}
  TGraph * GetGraphHvAnodeImon (UInt_t iSensor) const		        {return GetGraph (kHvAnodeImon, iSensor);}
  TGraph * GetGraphHvDriftImon (UInt_t iSensor) const		        {return GetGraph (kHvDriftImon, iSensor);}
  TGraph * GetGraphHvAnodeUmon (UInt_t iSensor) const		        {return GetGraph (kHvAnodeUmon, iSensor);}
  TGraph * GetGraphHvDriftUmon (UInt_t iSensor) const		        {return GetGraph (kHvDriftUmon, iSensor);}
  TGraph * GetGraphAdcClkPhase () const 				{return GetGraph (kAdcClkPhase);}
  TGraph * GetGraphAtmPressure () const 				{return GetGraph (kAtmPressure);}
  TGraph * GetGraphLuminosity () const 					{return GetGraph (kLuminosity);}
  TGraph * GetGraphMagneticField () const				{return GetGraph (kMagneticField);}

  AliSplineFit * GetFitChamberByteStatus (UInt_t iSensor) const	        {return GetFit (kChamberByteStatus, iSensor);}
  AliSplineFit * GetFitPreTrigger () const 				{return GetFit (kPreTrigger);}
  AliSplineFit * GetFitGoofyHv () const					{return GetFit (kGoofyHv);}
  AliSplineFit * GetFitGoofyPeakPos (UInt_t iSensor) const	        {return GetFit (kGoofyPeakPos, iSensor);}
  AliSplineFit * GetFitGoofyPeakArea (UInt_t iSensor) const 	        {return GetFit (kGoofyPeakArea, iSensor);}
  AliSplineFit * GetFitGoofyTemp (UInt_t iSensor) const		        {return GetFit (kGoofyTemp, iSensor);}
  AliSplineFit * GetFitGoofyPressure () const 				{return GetFit (kGoofyPressure);}
  AliSplineFit * GetFitGoofyVelocity () const 				{return GetFit (kGoofyVelocity);}
  AliSplineFit * GetFitGoofyGain (UInt_t iSensor) const		        {return GetFit (kGoofyGain, iSensor);}
  AliSplineFit * GetFitGoofyCO2 ()  const				{return GetFit (kGoofyCO2);}
  AliSplineFit * GetFitGoofyN2 () const 				{return GetFit (kGoofyN2);}
  AliSplineFit * GetFitGasO2 () const 					{return GetFit (kGasO2);}
  AliSplineFit * GetFitGasOverpressure () const 			{return GetFit (kGasOverpressure);}
  AliSplineFit * GetFitEnvTemp (UInt_t iSensor) const			{return GetFit (kEnvTemp, iSensor);}
  AliSplineFit * GetFitHvAnodeImon (UInt_t iSensor) const		{return GetFit (kHvAnodeImon, iSensor);}
  AliSplineFit * GetFitHvDriftImon (UInt_t iSensor) const		{return GetFit (kHvDriftImon, iSensor);}
  AliSplineFit * GetFitHvAnodeUmon (UInt_t iSensor) const		{return GetFit (kHvAnodeUmon, iSensor);}
  AliSplineFit * GetFitHvDriftUmon (UInt_t iSensor) const		{return GetFit (kHvDriftUmon, iSensor);}
  AliSplineFit * GetFitAdcClkPhase () const 				{return GetFit (kAdcClkPhase);}
  AliSplineFit * GetFitAtmPressure () const 				{return GetFit (kAtmPressure);}
  AliSplineFit * GetFitLuminosity () const 				{return GetFit (kLuminosity);}
  AliSplineFit * GetFitMagneticField () const				{return GetFit (kMagneticField);}

  void Print (const Option_t * const option = "") const;

 protected :

    TGraph       * FindAndMakeGraph (TMap * const dcsMap
                                   , const char * amandaStr
				   , char dataType);
    AliSplineFit * Fit (const TGraph * const graph,
			Int_t  kMinPoints, Int_t  kIter,
			Double_t  kMaxDelta, Int_t  kFitReq);

    void Init ();
    void InitFits ();
    void InitGraphs ();

    void SetConf (UInt_t iAlias, const char * amanda, char dataType, UInt_t nChannel,
		  Bool_t enableGraph, Bool_t enableFit, Int_t kMinPoints,
		  Int_t kIter, Double_t kMaxDelta, Int_t kFitReq);

 private :

    enum { kChamberByteStatus = 0
         , kPreTrigger        = 1
         , kGoofyHv           = 2
         , kGoofyPeakPos      = 3
         , kGoofyPeakArea     = 4
         , kGoofyTemp         = 5
         , kGoofyPressure     = 6
         , kGoofyVelocity     = 7
         , kGoofyGain         = 8
         , kGoofyCO2          = 9
         , kGoofyN2           = 10
         , kGasO2             = 11
         , kGasOverpressure   = 12
         , kEnvTemp           = 13
         , kHvAnodeImon       = 14
         , kHvDriftImon       = 15
         , kHvAnodeUmon       = 16
         , kHvDriftUmon       = 17
         , kAdcClkPhase       = 18
         , kAtmPressure       = 19
         , kLuminosity        = 20
         , kMagneticField     = 21
    };

  Bool_t fGraphsAreIni;              // Check whether graphs are initialized
  Bool_t fFitsAreIni;                // Check whether firs are initialized
  UInt_t fNAlias;                    // Number of aliases

    class AliTRDDataDCSdata {
     public:
      AliTRDDataDCSdata()
	:fFit(0x0)
        ,fGraph(0x0) { };
      virtual ~AliTRDDataDCSdata() { };
      TObjArray GetFit() const          { return fFit;      }
      TObjArray GetGraph() const        { return fGraph;    }
      TObject*  GetFit(Int_t i) const   { return fFit[i];   }
      TObject*  GetGraph(Int_t i) const { return fGraph[i]; }
     protected:
      TObjArray fFit;			// array of AliSplineFit
      TObjArray fGraph;		        // array of TGraph
    };

    class AliTRDDataDCSconf {
     public:
      AliTRDDataDCSconf()
	:fAmanda(0)
	,fDataType(0)
	,fNChannel(0)
	,fEnableGraph(0)
	,fEnableFit(0)
	,fMinPoints(0)
	,fIter(0)
	,fMaxDelta(0)
	,fFitReq(0) { };
      virtual ~AliTRDDataDCSconf() { };
      TString  GetAmanda() const        { return fAmanda;      }
      Char_t   GetDataType() const      { return fDataType;    }
      UInt_t   GetNChannel() const      { return fNChannel;    }
      Bool_t   GetEnableGraph() const   { return fEnableGraph; }
      Bool_t   GetEnableFit() const     { return fEnableFit;   }
      Int_t    GetMinPoints() const     { return fMinPoints;   }
      Int_t    GetIter() const          { return fIter;        }
      Double_t GetMaxDelta() const      { return fMaxDelta;    }
      Int_t    GetFitReq() const        { return fFitReq;      }
      void     SetAmanda(TString s)     { fAmanda      = s;    }
      void     SetDataType(Char_t d)    { fDataType    = d;    }
      void     SetNChannel(UInt_t n)    { fNChannel    = n;    }
      void     SetEnableGraph(Bool_t e) { fEnableGraph = e;    }
      void     SetEnableFit(Bool_t e)   { fEnableFit   = e;    }
      void     SetMinPoints(Int_t m)    { fMinPoints   = m;    }
      void     SetIter(Int_t i)         { fIter        = i;    }
      void     SetMaxDelta(Double_t m)  { fMaxDelta    = m;    }
      void     SetFitReq(Int_t f)       { fFitReq      = f;    }
     protected:
        TString   fAmanda;	      	// amanda string
        Char_t    fDataType;		// 'c' for char, 'f' for float
        UInt_t    fNChannel;		// number of channel
        Bool_t    fEnableGraph;		// will be converted in TGraph
        Bool_t    fEnableFit;	        // will be converted in AliSplineFit
        Int_t     fMinPoints;		// minimum number of points per knot in fit
        Int_t     fIter;		// number of iterations for spline fit
        Double_t  fMaxDelta;	        // precision parameter for spline fit
        Int_t     fFitReq;	        // fit requirement, 2 = continuous 2nd derivative
      };

      AliTRDDataDCSdata fDatas [22];	// configurations
      AliTRDDataDCSconf fConfs [22];	// data arrays

      ClassDef(AliTRDDataDCS,1)         // TRD calibration class

};

#endif


text:
<?php

namespace Cpm\JovenesBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * EtapaRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EtapaRepository extends EntityRepository
{
	public function findAll($conditions = array()){
		return $this->findBy($conditions, array('numero' => 'ASC')	);
	}

	public function findOne($conditions = array()){
			$query = $this->createQueryBuilder('e');
		if($anteriores)
			$query->where('e.numero < :numero');
		else
			$query->where('e.numero > :numero');

		$query->orderBy('e.numero','DESC')
			->setParameter('numero', $etapa->getNumero())
			->setSize($count)
			->getQuery()
		;
		return $query->getResult();
	}

	public function findPrimerEtapa(){
		$etapaUno = $this->findOneBy(array(), array('numero' => 'ASC'));
		if (empty($etapaUno))
			throw new \OutOfRangeException("No existe una etapa UNO, esto no deberia suceder");
		return $etapaUno;
	}

	public function findEtapaAnteriorA($etapa){
		$proxEtapas = $this->findEtapasProximas($etapa, true,1);
		if (empty($proxEtapas))
			return null;
		else
			return array_pop($proxEtapas);
	}

	public function findEtapaSiguienteA($etapa){
		$proxEtapas = $this->findEtapasProximas($etapa, false,1);

		if (empty($proxEtapas))
			return null;
		else
			return array_pop($proxEtapas);
	}

	public function findEtapasProximas($etapa, $anteriores = true, $count = 1){
		$query = $this->createQueryBuilder('e');
		if($anteriores)
			$query->where('e.numero < :numero')->orderBy('e.numero', 'DESC');
		else
			$query->where('e.numero > :numero')->orderBy('e.numero', 'ASC');

		$query
			->setParameter('numero', $etapa->getNumero())
			->setMaxResults($count)
		;
		return $query->getQuery()->getResult();
	}

}


text:
INSERT INTO meta (meta_key, meta_value)
  VALUES ('schema_version', 73);

-- Patch identifier
INSERT INTO meta (meta_key, meta_value)
  VALUES ('patch', 'patch_72_73_a.sql|schema_version');


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

namespace Itinero.IO.Osm.Overpass
{
    /// <summary>
    /// Downloads data from overpass.
    /// </summary>
    public static class OverpassDownload
    {
        /// <summary>
        /// Downloads a file if it doesn't exist yet.
        /// </summary>
        public static Stream ToStream(string query)
        {
            Itinero.Logging.Logger.Log("Download", Itinero.Logging.TraceEventType.Information,
                "Downloading from overpass...");

            var client = new HttpClient();
            var content = new StringContent("data=" + query);
            var response = client.PostAsync(@"http://overpass-api.de/api/interpreter", content);
            return response.GetAwaiter().GetResult().Content.ReadAsStreamAsync().GetAwaiter().GetResult();
        }
    }
}


text:
#ifndef _SPIKEGEN_FROM_VECTOR_H_
#define _SPIKEGEN_FROM_VECTOR_H_

#include <callback.h>
#include <vector>

class CARLsim; // forward-declaration

/*!
 * \brief a SpikeGenerator that schedules spikes from a vector of spike times
 *
 * This class implements a SpikeGenerator that schedules spikes from a vector of spike times (ms).
 * \TODO change to vector of AER or 2D vector, so that each neuron can have their own spike times.
 */
class SpikeGeneratorFromVector : public SpikeGenerator {
public:
	/*!
	 * \brief SpikeGeneratorFromVector constructor
	 * \param[in] spkTimes a vector of all spike times
	 */
	SpikeGeneratorFromVector(std::vector<int> spkTimes);

	//! PeriodicSpikeGenerator destructor
	~SpikeGeneratorFromVector() {}

	/*!
	 * \brief schedules the next spike time
	 *
	 * This function schedules the next spike time, given the currentTime and the lastScheduledSpikeTime. It implements
	 * the virtual function of the base class.
	 * \param[in] sim pointer to a CARLsim object
	 * \param[in] grpId current group ID for which to schedule spikes
	 * \param[in] nid current neuron ID for which to schedule spikes
	 * \param[in] currentTime current time (ms) at which spike scheduler is called
	 * \param[in] lastScheduledSpikeTime the last time (ms) at which a spike was scheduled for this nid, grpId
	 * \returns the next spike time (ms)
	 */
	int nextSpikeTime(CARLsim* sim, int grpId, int nid, int currentTime, int lastScheduledSpikeTime, int endOfTimeSlice);

private:
	void checkSpikeVector();

	std::vector<int> spkTimes_;	//!< vector of spike times
	int currentIndex_;			//!< keeps track of current position in the vector
	int size_;					//!< size of vector for fast access
};

#endif


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.customerinsights.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of Interactions. */
public interface Interactions {
    /**
     * Gets information about the specified interaction.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @param interactionName The name of the interaction.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return information about the specified interaction.
     */
    InteractionResourceFormat get(String resourceGroupName, String hubName, String interactionName);

    /**
     * Gets information about the specified interaction.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @param interactionName The name of the interaction.
     * @param localeCode Locale of interaction to retrieve, default is en-us.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return information about the specified interaction.
     */
    Response<InteractionResourceFormat> getWithResponse(
        String resourceGroupName, String hubName, String interactionName, String localeCode, Context context);

    /**
     * Gets all interactions in the hub.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return all interactions in the hub.
     */
    PagedIterable<InteractionResourceFormat> listByHub(String resourceGroupName, String hubName);

    /**
     * Gets all interactions in the hub.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @param localeCode Locale of interaction to retrieve, default is en-us.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return all interactions in the hub.
     */
    PagedIterable<InteractionResourceFormat> listByHub(
        String resourceGroupName, String hubName, String localeCode, Context context);

    /**
     * Suggests relationships to create relationship links.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @param interactionName The name of the interaction.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response of suggest relationship links operation.
     */
    SuggestRelationshipLinksResponse suggestRelationshipLinks(
        String resourceGroupName, String hubName, String interactionName);

    /**
     * Suggests relationships to create relationship links.
     *
     * @param resourceGroupName The name of the resource group.
     * @param hubName The name of the hub.
     * @param interactionName The name of the interaction.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response of suggest relationship links operation.
     */
    Response<SuggestRelationshipLinksResponse> suggestRelationshipLinksWithResponse(
        String resourceGroupName, String hubName, String interactionName, Context context);

    /**
     * Gets information about the specified interaction.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return information about the specified interaction.
     */
    InteractionResourceFormat getById(String id);

    /**
     * Gets information about the specified interaction.
     *
     * @param id the resource ID.
     * @param localeCode Locale of interaction to retrieve, default is en-us.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return information about the specified interaction.
     */
    Response<InteractionResourceFormat> getByIdWithResponse(String id, String localeCode, Context context);

    /**
     * Begins definition for a new InteractionResourceFormat resource.
     *
     * @param name resource name.
     * @return the first stage of the new InteractionResourceFormat definition.
     */
    InteractionResourceFormat.DefinitionStages.Blank define(String name);
}


text:
FactoryBot.define do
  factory :suggestion do
    relative_order 0
    association :note, factory: :diff_note_on_merge_request
    from_content "    vars = {\n"
    to_content "    vars = [\n"

    trait :unappliable do
      from_content "foo"
      to_content "foo"
    end

    trait :applied do
      applied true
      commit_id { RepoHelpers.sample_commit.id }
    end
  end
end


text:
var COLLIDES = require('../COLLIDES');

/**
 * @callback CollideCallback
 *
 * @param {Phaser.Physics.Impact.Body} body - [description]
 * @param {Phaser.Physics.Impact.Body} other - [description]
 * @param {string} axis - [description]
 */

/**
 * [description]
 *
 * @name Phaser.Physics.Impact.Components.Collides
 * @since 3.0.0
 */
var Collides = {

    _collideCallback: null,
    _callbackScope: null,

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setCollideCallback
     * @since 3.0.0
     *
     * @param {CollideCallback} callback - [description]
     * @param {*} scope - [description]
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setCollideCallback: function (callback, scope)
    {
        this._collideCallback = callback;

        if (scope)
        {
            this._callbackScope = scope;
        }

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setCollidesNever
     * @since 3.0.0
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setCollidesNever: function ()
    {
        this.body.collides = COLLIDES.NEVER;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setLiteCollision
     * @since 3.6.0
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setLiteCollision: function ()
    {
        this.body.collides = COLLIDES.LITE;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setPassiveCollision
     * @since 3.6.0
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setPassiveCollision: function ()
    {
        this.body.collides = COLLIDES.PASSIVE;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setActiveCollision
     * @since 3.6.0
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setActiveCollision: function ()
    {
        this.body.collides = COLLIDES.ACTIVE;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.Physics.Impact.Components.Collides#setFixedCollision
     * @since 3.6.0
     *
     * @return {Phaser.GameObjects.GameObject} This Game Object.
     */
    setFixedCollision: function ()
    {
        this.body.collides = COLLIDES.FIXED;

        return this;
    },

    /**
     * [description]
     *
     * @name Phaser.Physics.Impact.Components.Collides#collides
     * @type {number}
     * @since 3.0.0
     */
    collides: {

        get: function ()
        {
            return this.body.collides;
        },

        set: function (value)
        {
            this.body.collides = value;
        }

    }

};

module.exports = Collides;


text:
#include <iostream>
#include <fstream>
using namespace std;

#include "ap_fixed.h"
#include <math.h>

// phase accumulator
typedef ap_fixed<32,1> incr_t;  // s.xxxx, +/- 1 = +/- pi = +fs/2 to -fs/2
typedef ap_fixed<32,1> acc_t;   // s.xxxx, +/- 1 = +/- pi = +fs/2 to -fs/2

// cos lut address, word size
const int NLUT     = 10;               // bitwidth for cos lut address, covers one quadrant
const int LUTSIZE  = 1024;             // 2^NLUT
typedef ap_uint<NLUT+2> lut_adr_t;     // covers 4 quadrant
typedef ap_uint<NLUT>   quad_adr_t;    // covers 1 quadrant

// rounding makes huge difference in the noise floor
typedef ap_fixed<18,1,AP_RND_CONV,AP_SAT_SYM> lut_word_t;
//typedef ap_fixed<18,1> lut_word_t;
//typedef double lut_word_t;

// fine lut address, word size
const int NFINE     = 9;               // bitwidth for fine lut address, covers one quadrant
const int FINESIZE  = 512;             // 2^NFINE
typedef ap_uint<NLUT+2> fine_adr_t;    // covers 4 quadrant
//typedef ap_fixed<18,1,AP_RND_INF,AP_SAT_SYM> fine_word_t;
//typedef ap_fixed<18,1> fine_word_t;
//typedef ap_fixed<18,-8> fine_word_t;
//typedef ap_fixed<18,-10> fine_word_t;
//typedef double fine_word_t;
typedef ap_fixed<18,-7> fine_word_t;

const double DELTA = M_PI/(2*LUTSIZE*FINESIZE); // fine lut resolution, range covers 0 to pi/(2*LUTSIZE)

// DDS output = f(cos lut, fine table)
//typedef ap_fixed<18,1,AP_RND_CONV,AP_SAT_SYM> dds_t;
typedef ap_fixed<16,1,AP_RND_CONV,AP_SAT_SYM> dds_t;

ap_uint<19> dither();
void init_cos_lut( lut_word_t cos_lut[LUTSIZE], const int LUTSIZE );
void read_cos_lut( lut_word_t cos_lut[LUTSIZE], const int LUTSIZE );
void read_sine_lut( lut_word_t cos_lut[LUTSIZE], const int LUTSIZE );
void init_fine_lut( fine_word_t fine_lut[FINESIZE], const int FINESIZE, const double DELTA );
void dds ( incr_t  incr,  dds_t*  cos_out,  dds_t* sin_out );

#endif


text:
<?php

namespace Codeages\Biz\Framework\Service\Exception;

class AccessDeniedException extends ServiceException
{
}


text:
CUI-Element
Inputblock
NumberInputblock

***

@@include(numberinputblock_p.md)


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

namespace HyperSlackers.Bootstrap.Demo.Models
{
    public class FormsModel
    {
        public string Email { get; set; }

        public string Password { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

        public bool IsHappy { get; set; }

        public DateTime SignUpDate { get; set; }

        public ColorType FavoriteColor { get; set; }

        public string Description { get; set; }
    }
}


text:
import logging
import inspect
from uliweb.utils.common import import_attr

__all__ = ['HIGH', 'MIDDLE', 'LOW', 'bind', 'call', 'get', 'unbind', 'call_once', 'get_once']

HIGH = 1    #plugin high
MIDDLE = 2
LOW = 3

_receivers = {}
_called = {}

def reset():
    global _receivers, _called

    _receivers.clear()
    _called.clear()

def bind(topic, signal=None, kind=MIDDLE, nice=-1):
    """
    This is a decorator function, so you should use it as:

        @bind('init')
        def process_init(a, b):
            ...
    """
    def f(func):
        if not topic in _receivers:
            receivers = _receivers[topic] = []
        else:
            receivers = _receivers[topic]

        if nice == -1:
            if kind == MIDDLE:
                n = 500
            elif kind == HIGH:
                n = 100
            else:
                n = 900
        else:
            n = nice
        if callable(func):
            func_name = func.__module__ + '.' + func.__name__
            func = func
        else:
            func_name = func
            func = None
        _f = (n, {'func':func, 'signal':signal, 'func_name':func_name})
        receivers.append(_f)
        return func
    return f

def unbind(topic, func):
    """
    Remove receiver function
    """
    if topic in _receivers:
        receivers = _receivers[topic]
        for i in range(len(receivers)-1, -1, -1):
            nice, f = receivers[i]
            if (callable(func) and f['func'] == func) or (f['func_name'] == func):
                del receivers[i]
                return

def _test(kwargs, receiver):
    signal = kwargs.get('signal', None)
    f = receiver['func']
    args = inspect.getargspec(f)[0]
    if 'signal' not in args:
        kwargs.pop('signal', None)
    _signal = receiver.get('signal')
    flag = True
    if _signal:
        if isinstance(_signal, (tuple, list)):
            if signal not in _signal:
                flag = False
        elif _signal!=signal:
            flag = False
    return flag

def call(sender, topic, *args, **kwargs):
    """
    Invoke receiver functions according topic, it'll invoke receiver functions one by one,
    and it'll not return anything, so if you want to return a value, you should
    use get function.
    """
    if not topic in _receivers:
        return
    items = _receivers[topic]
    def _cmp(x, y):
        return cmp(x[0], y[0])

    items.sort(_cmp)
    i = 0
    while i<len(items):
        nice, f = items[i]
        i = i + 1
        _f = f['func']
        if not _f:
            try:
                _f = import_attr(f['func_name'])
            except (ImportError, AttributeError) as e:
                logging.error("Can't import function %s" % f['func_name'])
                raise
            f['func'] = _f
        if callable(_f):
            kw = kwargs.copy()
            if not _test(kw, f):
                continue
            try:
                _f(sender, *args, **kw)
            except:
                func = _f.__module__ + '.' + _f.__name__
                logging.exception('Calling dispatch point [%s] %s(%r, %r) error!' % (topic, func, args, kw))
                raise
        else:
            raise Exception, "Dispatch point [%s] %r can't been invoked" % (topic, _f)

def call_once(sender, topic, *args, **kwargs):
    signal = kwargs.get('signal')
    if (topic, signal) in _called:
        return
    else:
        call(sender, topic, *args, **kwargs)
        _called[(topic, signal)] = True

def get(sender, topic, *args, **kwargs):
    """
    Invoke receiver functions according topic, it'll invoke receiver functions one by one,
    and if one receiver function return non-None value, it'll return it and break
    the loop.
    """
    if not topic in _receivers:
        return
    items = _receivers[topic]
    def _cmp(x, y):
        return cmp(x[0], y[0])

    items.sort(_cmp)
    for i in range(len(items)):
        nice, f = items[i]
        _f = f['func']
        if not _f:
            try:
                _f = import_attr(f['func_name'])
            except ImportError:
                logging.error("Can't import function %s" % f['func_name'])
                raise
            f['func'] = _f
        if callable(_f):
            if not _test(kwargs, f):
                continue
            try:
                v = _f(sender, *args, **kwargs)
            except:
                func = _f.__module__ + '.' + _f.__name__
                logging.exception('Calling dispatch point [%s] %s(%r,%r) error!' % (topic, func, args, kwargs))
                raise
            if v is not None:
                return v
        else:
            raise "Dispatch point [%s] %r can't been invoked" % (topic, _f)

def get_once(sender, topic, *args, **kwargs):
    signal = kwargs.get('signal')
    if (topic, signal) in _called:
        return _called[(topic, signal)]
    else:
        r = get(sender, topic, *args, **kwargs)
        _called[(topic, signal)] = r
        return r

def print_topics():
    import pprint

    pprint.pprint(_receivers)


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

module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ],
    entry: ["bootstrap-loader", "./src/index.tsx"],
    output: {
        filename: "./dist/bundle.js",
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
        moduleDirectories: [
            'node_modules'
        ]
    },

    module: {
        loaders: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            { test: /\.tsx?$/, loader: "ts-loader" },
            { test: /\.css$/, loaders: ['style', 'css'] },
            { test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'] },
            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url-loader?limit=10000&name=dist/fonts/[name].[ext]',
            },
            {
                test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
                loader: 'file-loader?name=dist/fonts/[name].[ext]',
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    'file?hash=sha512&digest=hex&name=dist/img/[name].[ext]',
                    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            },
            { test: /bootstrap-sass(\\|\/)assets(\\|\/)javascripts(\\|\/)/, loader: 'imports-loader?jQuery=jquery' }
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },
};


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jme3_bullet_joints_Point2PointJoint */

#ifndef _Included_com_jme3_bullet_joints_Point2PointJoint
#define _Included_com_jme3_bullet_joints_Point2PointJoint
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    setDamping
 * Signature: (JF)V
 */
JNIEXPORT void JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_setDamping
  (JNIEnv *, jobject, jlong, jfloat);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    setImpulseClamp
 * Signature: (JF)V
 */
JNIEXPORT void JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_setImpulseClamp
  (JNIEnv *, jobject, jlong, jfloat);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    setTau
 * Signature: (JF)V
 */
JNIEXPORT void JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_setTau
  (JNIEnv *, jobject, jlong, jfloat);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    getDamping
 * Signature: (J)F
 */
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_getDamping
  (JNIEnv *, jobject, jlong);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    getImpulseClamp
 * Signature: (J)F
 */
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_getImpulseClamp
  (JNIEnv *, jobject, jlong);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    getTau
 * Signature: (J)F
 */
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_getTau
  (JNIEnv *, jobject, jlong);

/*
 * Class:     com_jme3_bullet_joints_Point2PointJoint
 * Method:    createJoint
 * Signature: (JJLcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;)J
 */
JNIEXPORT jlong JNICALL Java_com_jme3_bullet_joints_Point2PointJoint_createJoint
  (JNIEnv *, jobject, jlong, jlong, jobject, jobject);

#ifdef __cplusplus
}
#endif
#endif


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
require 'linode'

describe Linode::Nodebalancer do
  before :each do
    @api_key = 'foo'
    @linode = Linode::Nodebalancer.new(:api_key => @api_key)
  end

  it 'should be a Linode instance' do
    @linode.class.should < Linode
  end

  %w(update create list delete).each do |action|
    it "should allow accessing the #{action} API" do
      @linode.should respond_to(action.to_sym)
    end

    describe "when accessing the #{action} API" do
      it 'should allow a data hash' do
        @linode.stubs(:send_request)
        lambda { @linode.send(action.to_sym, {}) }.should_not raise_error
      end

      it 'should not require arguments' do
        @linode.stubs(:send_request)
        lambda { @linode.send(action.to_sym) }.should_not raise_error
      end

      it "should request the nodebalancer.#{action} action" do
        @linode.expects(:send_request).with {|api_action, data| api_action == "nodebalancer.#{action}" }
        @linode.send(action.to_sym)
      end

      it 'should provide the data hash when making its request' do
        @linode.expects(:send_request).with {|api_action, data| data = { :foo => :bar } }
        @linode.send(action.to_sym, {:foo => :bar})
      end

      it 'should return the result of the request' do
        @linode.expects(:send_request).returns(:bar => :baz)
        @linode.send(action.to_sym).should == { :bar => :baz }
      end

      it "should consider the documentation to live at https://www.linode.com/api/nodebalancer/nodebalancer.#{action}" do
        @linode.documentation_path(Linode.action_path(@linode.class.name, action)).should == "https://www.linode.com/api/nodebalancer/nodebalancer.#{action}"
      end
    end
  end

  it 'should be able to provide access to the Linode Nodebalancer Config API' do
    @linode.should respond_to(:config)
  end

  describe 'when providing access to the Linode Nodebalancer Config API' do
    before :each do
      @api_key = 'foo'
      @api_url = 'https://fake.linode.com/'
      @linode = Linode::Nodebalancer.new(:api_key => @api_key, :api_url => @api_url)
    end

    it 'should allow no arguments' do
      lambda { @linode.config }.should_not raise_error
    end

    it 'should require no arguments' do
      lambda { @linode.config(:foo) }.should raise_error(ArgumentError)
    end

    it 'should return a Linode::Nodebalancer::Config instance' do
      @linode.config.class.should == Linode::Nodebalancer::Config
    end

    it 'should set the API key on the Linode::Nodebalancer::Config instance to be our API key' do
      @linode.config.api_key.should == @api_key
    end

    it 'should set the API url on the Linode::Nodebalancer::Config instance to be our API url' do
      @linode.config.api_url.should == @api_url
    end

    it 'should return the same Linode::Nodebalancer::Config instance when called again' do
      linode = Linode::Nodebalancer.new(:api_key => @api_key)
      result = linode.config
      linode.config.should == result
    end
  end

  it 'should be able to provide access to the Linode Nodebalancer Node API' do
    @linode.should respond_to(:node)
  end

  describe 'when providing access to the Linode Nodebalancer Node API' do
    before :each do
      @api_key = 'foo'
      @api_url = 'https://fake.linode.com/'
      @linode = Linode::Nodebalancer.new(:api_key => @api_key, :api_url => @api_url)
    end

    it 'should allow no arguments' do
      lambda { @linode.node }.should_not raise_error
    end

    it 'should require no arguments' do
      lambda { @linode.node(:foo) }.should raise_error(ArgumentError)
    end

    it 'should return a Linode::Nodebalancer::Node instance' do
      @linode.node.class.should == Linode::Nodebalancer::Node
    end

    it 'should set the API key on the Linode::Nodebalancer::Node instance to be our API key' do
      @linode.node.api_key.should == @api_key
    end

    it 'should set the API url on the Linode::Nodebalancer::Node instance to be our API url' do
      @linode.node.api_url.should == @api_url
    end

    it 'should return the same Linode::Nodebalancer::Node instance when called again' do
      linode = Linode::Nodebalancer.new(:api_key => @api_key)
      result = linode.node
      linode.node.should == result
    end
  end
end


text:
This playground is intended to create a [CD](http://guide.agilealliance.org/guide/cd.html) pipeline.

The following requirements the pipeline must address:

1. use [Concourse CI](https://concourse-ci.org/)
2. build a Java executable jar file
3. optional: include a version number in the final file to run
4. build a docker image
   * optional: tag docker image version (same as above)
5. publish a docker image

## Java, Maven, evtl. Spring Boot

## Usage

```
# build java project
mvn package

# prepare vagrant box
vagrant init concourse/lite
vagrant up

# upload pipeline
fly -t local set-pipeline -p concourse-java-maven-test-prj -c ./pipeline.yml
```

### Where do I get 'fly' from?

As stated in the official [fly documentation](https://concourse-ci.org/fly.html),
you can download or update your fly installation from any Concourse CI installation.

With your vagrant image running, your Concourse CI should be accessible via http://192.168.100.4:8080/.
Just download fly from there.

First, add your local running Concourse CI as target
```
fly -t local login -c "http://192.168.100.4:8080/"
```

Get a list of configured targets via
```
>>> fly targets

name   url                        expiry
local  http://192.168.100.4:8080  n/a
```


text:
.. _whatsnew_061:

Version 0.6.1 (December 13, 2011)
---------------------------------

New features
~~~~~~~~~~~~
- Can :ref:`append single rows <merging.append.row>` (as Series) to a DataFrame
- Add Spearman and Kendall rank :ref:`correlation <computation.correlation>`
  options to Series.corr and DataFrame.corr (:issue:`428`)
- :ref:`Added <indexing.basics.get_value>` ``get_value`` and ``set_value`` methods to
  Series, DataFrame, and Panel for very low-overhead access (>2x faster in many
  cases) to scalar elements (:issue:`437`, :issue:`438`). ``set_value`` is capable of
  producing an enlarged object.
- Add PyQt table widget to sandbox (:issue:`435`)
- DataFrame.align can :ref:`accept Series arguments <basics.align.frame.series>`
  and an :ref:`axis option <basics.df_join>` (:issue:`461`)
- Implement new :ref:`SparseArray <sparse.array>` and ``SparseList``
  data structures. SparseSeries now derives from SparseArray (:issue:`463`)
- :ref:`Better console printing options <basics.console_output>` (:issue:`453`)
- Implement fast :ref:`data ranking <computation.ranking>` for Series and
  DataFrame, fast versions of scipy.stats.rankdata (:issue:`428`)
- Implement ``DataFrame.from_items`` alternate
  constructor (:issue:`444`)
- DataFrame.convert_objects method for :ref:`inferring better dtypes <basics.cast>`
  for object columns (:issue:`302`)
- Add :ref:`rolling_corr_pairwise <window.corr_pairwise>` function for
  computing Panel of correlation matrices (:issue:`189`)
- Add :ref:`margins <reshaping.pivot.margins>` option to :ref:`pivot_table
  <reshaping.pivot>` for computing subgroup aggregates (:issue:`114`)
- Add ``Series.from_csv`` function (:issue:`482`)
- :ref:`Can pass <window.cov_corr>` DataFrame/DataFrame and
  DataFrame/Series to rolling_corr/rolling_cov (GH #462)
- MultiIndex.get_level_values can :ref:`accept the level name <advanced.get_level_values>`

Performance improvements
~~~~~~~~~~~~~~~~~~~~~~~~

- Improve memory usage of ``DataFrame.describe`` (do not copy data
  unnecessarily) (PR #425)

- Optimize scalar value lookups in the general case by 25% or more in Series
  and DataFrame

- Fix performance regression in cross-sectional count in DataFrame, affecting
  DataFrame.dropna speed
- Column deletion in DataFrame copies no data (computes views on blocks) (GH
  #158)

.. _whatsnew_0.6.1.contributors:

Contributors
~~~~~~~~~~~~

.. contributors:: v0.6.0..v0.6.1


text:
/*	$NetBSD: gdt.c,v 1.1 2004/03/11 21:44:08 cl Exp $	*/
/*	NetBSD: gdt.c,v 1.32 2004/02/13 11:36:13 wiz Exp 	*/

/*-
 * Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by John T. Kohl and Charles M. Hannum.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: gdt.c,v 1.1 2004/03/11 21:44:08 cl Exp $");

#include "opt_multiprocessor.h"
#include "opt_xen.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/lock.h>
#include <sys/user.h>

#include <uvm/uvm.h>

#include <machine/gdt.h>

int gdt_size[2];	/* total number of GDT entries */
int gdt_count[2];	/* number of GDT entries in use */
int gdt_next[2];	/* next available slot for sweeping */
int gdt_free[2];	/* next free slot; terminated with GNULL_SEL */

struct lock gdt_lock_store;

static __inline void gdt_lock(void);
static __inline void gdt_unlock(void);
void gdt_init(void);
void gdt_grow(int);
int gdt_get_slot(void);
int gdt_get_slot1(int);
void gdt_put_slot(int);
void gdt_put_slot1(int, int);

/*
 * Lock and unlock the GDT, to avoid races in case gdt_{ge,pu}t_slot() sleep
 * waiting for memory.
 *
 * Note that the locking done here is not sufficient for multiprocessor
 * systems.  A freshly allocated slot will still be of type SDT_SYSNULL for
 * some time after the GDT is unlocked, so gdt_compact() could attempt to
 * reclaim it.
 */
static __inline void
gdt_lock()
{

	(void) lockmgr(&gdt_lock_store, LK_EXCLUSIVE, NULL);
}

static __inline void
gdt_unlock()
{

	(void) lockmgr(&gdt_lock_store, LK_RELEASE, NULL);
}

void
setgdt(int sel, void *base, size_t limit,
    int type, int dpl, int def32, int gran)
{
	struct segment_descriptor sd;
	CPU_INFO_ITERATOR cii;
	struct cpu_info *ci;

	if (type == SDT_SYS386TSS) {
		/* printk("XXX TSS descriptor not supported in GDT\n"); */
		return;
	}

	setsegment(&sd, base, limit, type, dpl, def32, gran);
	for (CPU_INFO_FOREACH(cii, ci)) {
		if (ci->ci_gdt != NULL) {
#ifndef XEN
			ci->ci_gdt[sel].sd = sd;
#else
			xen_update_descriptor(&ci->ci_gdt[sel],
			    (union descriptor *)&sd);
#endif
		}
	}
}

/*
 * Initialize the GDT subsystem.  Called from autoconf().
 */
void
gdt_init()
{
	size_t max_len, min_len;
	union descriptor *old_gdt;
	struct vm_page *pg;
	vaddr_t va;
	struct cpu_info *ci = &cpu_info_primary;

	lockinit(&gdt_lock_store, PZERO, "gdtlck", 0, 0);

	max_len = MAXGDTSIZ * sizeof(gdt[0]);
	min_len = MINGDTSIZ * sizeof(gdt[0]);

	gdt_size[0] = MINGDTSIZ;
	gdt_count[0] = NGDT;
	gdt_next[0] = NGDT;
	gdt_free[0] = GNULL_SEL;

	gdt_size[1] = 0;
	gdt_count[1] = MAXGDTSIZ;
	gdt_next[1] = MAXGDTSIZ;
	gdt_free[1] = GNULL_SEL;

	old_gdt = gdt;
	gdt = (union descriptor *)uvm_km_valloc(kernel_map, max_len + max_len);
	for (va = (vaddr_t)gdt; va < (vaddr_t)gdt + min_len; va += PAGE_SIZE) {
		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO);
		if (pg == NULL) {
			panic("gdt_init: no pages");
		}
		pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg),
		    VM_PROT_READ | VM_PROT_WRITE);
	}
	memcpy(gdt, old_gdt, NGDT * sizeof(gdt[0]));
	ci->ci_gdt = gdt;
	setsegment(&ci->ci_gdt[GCPU_SEL].sd, ci, sizeof(struct cpu_info)-1,
	    SDT_MEMRWA, SEL_KPL, 1, 1);

	gdt_init_cpu(ci);
}

/*
 * Allocate shadow GDT for a slave CPU.
 */
void
gdt_alloc_cpu(struct cpu_info *ci)
{
	int max_len = MAXGDTSIZ * sizeof(gdt[0]);
	int min_len = MINGDTSIZ * sizeof(gdt[0]);
	struct vm_page *pg;
	vaddr_t va;

	ci->ci_gdt = (union descriptor *)uvm_km_valloc(kernel_map, max_len);
	for (va = (vaddr_t)ci->ci_gdt; va < (vaddr_t)ci->ci_gdt + min_len;
	    va += PAGE_SIZE) {
		while ((pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO))
		    == NULL) {
			uvm_wait("gdt_alloc_cpu");
		}
		pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg),
		    VM_PROT_READ | VM_PROT_WRITE);
	}
	memset(ci->ci_gdt, 0, min_len);
	memcpy(ci->ci_gdt, gdt, gdt_count[0] * sizeof(gdt[0]));
	setsegment(&ci->ci_gdt[GCPU_SEL].sd, ci, sizeof(struct cpu_info)-1,
	    SDT_MEMRWA, SEL_KPL, 1, 1);
}

/*
 * Load appropriate gdt descriptor; we better be running on *ci
 * (for the most part, this is how a CPU knows who it is).
 */
void
gdt_init_cpu(struct cpu_info *ci)
{
#ifndef XEN
	struct region_descriptor region;
	size_t max_len;

	max_len = MAXGDTSIZ * sizeof(gdt[0]);
	setregion(&region, ci->ci_gdt, max_len - 1);
	lgdt(&region);
#else
	size_t len = gdt_size[0] * sizeof(gdt[0]);
	unsigned long frames[len >> PAGE_SHIFT];
	vaddr_t va;
	pt_entry_t *ptp;
	int f;

	for (va = (vaddr_t)ci->ci_gdt, f = 0;
	     va < (vaddr_t)ci->ci_gdt + len;
	     va += PAGE_SIZE, f++) {
		KASSERT(va >= VM_MIN_KERNEL_ADDRESS);
		ptp = kvtopte(va);
		frames[f] = *ptp >> PAGE_SHIFT;
		PTE_CLEARBITS(ptp, PG_RW);
	}
	PTE_UPDATES_FLUSH();
	/* printk("loading gdt %x, %d entries, %d pages", */
	    /* frames[0] << PAGE_SHIFT, gdt_size[0], len >> PAGE_SHIFT); */
	if (HYPERVISOR_set_gdt(frames, gdt_size[0]))
		panic("HYPERVISOR_set_gdt failed!\n");
	lgdt_finish();
#endif
}

#ifdef MULTIPROCESSOR

void
gdt_reload_cpu(struct cpu_info *ci)
{
	struct region_descriptor region;
	size_t max_len;

	max_len = MAXGDTSIZ * sizeof(gdt[0]);
	setregion(&region, ci->ci_gdt, max_len - 1);
	lgdt(&region);
}
#endif

/*
 * Grow the GDT.
 */
void
gdt_grow(int which)
{
	size_t old_len, new_len, max_len;
	CPU_INFO_ITERATOR cii;
	struct cpu_info *ci;
	struct vm_page *pg;
	vaddr_t va;

	old_len = gdt_size[which] * sizeof(gdt[0]);
	gdt_size[which] <<= 1;
	new_len = old_len << 1;

	if (which != 0) {
		max_len = MAXGDTSIZ * sizeof(gdt[0]);
		if (old_len == 0) {
			gdt_size[which] = MINGDTSIZ;
			new_len = gdt_size[which] * sizeof(gdt[0]);
		}
		for (va = (vaddr_t)(cpu_info_primary.ci_gdt) + old_len + max_len;
		     va < (vaddr_t)(cpu_info_primary.ci_gdt) + new_len + max_len;
		     va += PAGE_SIZE) {
			while ((pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO)) ==
			    NULL) {
				uvm_wait("gdt_grow");
			}
			pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg),
			    VM_PROT_READ | VM_PROT_WRITE);
		}
		return;
	}

	for (CPU_INFO_FOREACH(cii, ci)) {
		for (va = (vaddr_t)(ci->ci_gdt) + old_len;
		     va < (vaddr_t)(ci->ci_gdt) + new_len;
		     va += PAGE_SIZE) {
			while ((pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO)) ==
			    NULL) {
				uvm_wait("gdt_grow");
			}
			pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg),
			    VM_PROT_READ | VM_PROT_WRITE);
		}
	}
}

/*
 * Allocate a GDT slot as follows:
 * 1) If there are entries on the free list, use those.
 * 2) If there are fewer than gdt_size entries in use, there are free slots
 *    near the end that we can sweep through.
 * 3) As a last resort, we increase the size of the GDT, and sweep through
 *    the new slots.
 */
int
gdt_get_slot()
{
	return gdt_get_slot1(0);
}

int
gdt_get_slot1(int which)
{
	size_t offset;
	int slot;

	gdt_lock();

	if (gdt_free[which] != GNULL_SEL) {
		slot = gdt_free[which];
		gdt_free[which] = gdt[slot].gd.gd_selector;
	} else {
		offset = which * MAXGDTSIZ * sizeof(gdt[0]);
		if (gdt_next[which] != gdt_count[which] + offset)
			panic("gdt_get_slot botch 1");
		if (gdt_next[which] - offset >= gdt_size[which]) {
			if (gdt_size[which] >= MAXGDTSIZ)
				panic("gdt_get_slot botch 2");
			gdt_grow(which);
		}
		slot = gdt_next[which]++;
	}

	gdt_count[which]++;
	gdt_unlock();
	return (slot);
}

/*
 * Deallocate a GDT slot, putting it on the free list.
 */
void
gdt_put_slot(int slot)
{
	gdt_put_slot1(slot, 0);
}

void
gdt_put_slot1(int slot, int which)
{

	gdt_lock();
	gdt_count[which]--;

	gdt[slot].gd.gd_type = SDT_SYSNULL;
	gdt[slot].gd.gd_selector = gdt_free[which];
	gdt_free[which] = slot;

	gdt_unlock();
}

int
tss_alloc(struct pcb *pcb)
{
	int slot;

	slot = gdt_get_slot();
	setgdt(slot, &pcb->pcb_tss, sizeof(struct pcb) - 1,
	    SDT_SYS386TSS, SEL_KPL, 0, 0);
	return GSEL(slot, SEL_KPL);
}

void
tss_free(int sel)
{

	gdt_put_slot(IDXSEL(sel));
}

/*
 * Caller must have pmap locked for both of these functions.
 */
void
ldt_alloc(struct pmap *pmap, union descriptor *ldt, size_t len)
{
	int slot;

	slot = gdt_get_slot1(1);
#ifndef XEN
	setgdt(slot, ldt, len - 1, SDT_SYSLDT, SEL_KPL, 0, 0);
#else
	cpu_info_primary.ci_gdt[slot].ld.ld_base = (uint32_t)ldt;
	cpu_info_primary.ci_gdt[slot].ld.ld_entries =
		len / sizeof(union descriptor);
#endif
	pmap->pm_ldt_sel = GSEL(slot, SEL_KPL);
}

void
ldt_free(struct pmap *pmap)
{
	int slot;

	slot = IDXSEL(pmap->pm_ldt_sel);

	gdt_put_slot1(slot, 1);
}


text:
package org.apache.jena.tdb2.store.tupletable;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses( {
    TestTupleIndexRecord.class,
    TestTupleIndexRecordDirect.class,
    TestTupleTable.class
} )

public class TS_TupleTable
{ }


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="panel">

        <roleset framnet="" id="panel.01" name="Cover with panels" vncls="9.9">
            <roles>
                <role descr="Agent, placer of panels" f="" n="0">
                    <vnrole vncls="9.9" vntheta="agent"/>
                    <vnrole vncls="9.8" vntheta="agent"/>
                </role>
                <role descr="Wall, entity being covered with panels" f="" n="1">
                    <vnrole vncls="9.9" vntheta="destination"/>
                    <vnrole vncls="9.8" vntheta="destination"/>
                </role>
                <note/>
                <role descr="Panels themselves, type of panel" f="" n="2">
                    <vnrole vncls="9.9" vntheta="theme"/>
                    <vnrole vncls="9.8" vntheta="theme"/>
                </role>
            </roles>
            <example name="All arguments" src="web usage" type="">
                <text>He paneled the wall with cedar planks from the floor to the rafters.</text>
                <note/>
                <arg f="" n="0">He</arg>
                <rel f="">paneled</rel>
                <arg f="" n="1">the wall</arg>
                <arg f="" n="2">with cedar planks</arg>
                <arg f="ext" n="m">from the floor to the rafters</arg>
            </example>
            <note>Hand-corrected by Claire.</note>
        </roleset>

        <note>Automatically created based on framefiles: feather (9.9), festoon (9.8)</note>
    </predicate>
    <note/>
</frameset>