text:
package com.graphhopper.http.resources;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.graphhopper.config.CHProfile;
import com.graphhopper.http.GraphHopperApplication;
import com.graphhopper.http.GraphHopperServerConfiguration;
import com.graphhopper.http.util.GraphHopperServerTestConfiguration;
import com.graphhopper.routing.util.CustomModel;
import com.graphhopper.routing.weighting.custom.CustomProfile;
import com.graphhopper.util.Helper;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

import static com.graphhopper.http.util.TestUtils.clientTarget;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

@ExtendWith(DropwizardExtensionsSupport.class)
public class CustomWeightingRouteResourceTest {

    private static final String DIR = "./target/north-bayreuth-gh/";
    private static final DropwizardAppExtension<GraphHopperServerConfiguration> app = new DropwizardAppExtension<>(GraphHopperApplication.class, createConfig());

    private static GraphHopperServerConfiguration createConfig() {
        GraphHopperServerConfiguration config = new GraphHopperServerTestConfiguration();
        config.getGraphHopperConfiguration().
                putObject("graph.flag_encoders", "bike,car").
                putObject("routing.ch.disabling_allowed", true).
                putObject("prepare.min_network_size", 0).
                putObject("datareader.file", "../core/files/north-bayreuth.osm.gz").
                putObject("graph.location", DIR).
                putObject("graph.encoded_values", "max_height,max_weight,max_width,hazmat,toll,surface,track_type").
                setProfiles(Arrays.asList(
                        new CustomProfile("car").setCustomModel(new CustomModel()).setVehicle("car"),
                        new CustomProfile("bike").setCustomModel(new CustomModel()).setVehicle("bike"),
                        new CustomProfile("truck").setVehicle("car").
                                putHint("custom_model_file", "./src/test/resources/com/graphhopper/http/resources/truck.yml"),
                        new CustomProfile("cargo_bike").setVehicle("bike").
                                putHint("custom_model_file", "./src/test/resources/com/graphhopper/http/resources/cargo_bike.yml"),
                        new CustomProfile("json_bike").setVehicle("bike").
                                putHint("custom_model_file", "./src/test/resources/com/graphhopper/http/resources/json_bike.json"))).
                setCHProfiles(Collections.singletonList(new CHProfile("truck")));
        return config;
    }

    @BeforeAll
    @AfterAll
    public static void cleanUp() {
        Helper.removeDir(new File(DIR));
    }

    @Test
    public void testCHTruckQuery() {
        String jsonQuery = "{" +
                " \"points\": [[11.58199, 50.0141], [11.5865, 50.0095]]," +
                " \"profile\": \"truck\"" +
                "}";
        final Response response = clientTarget(app, "/route").request().post(Entity.json(jsonQuery));
        assertEquals(200, response.getStatus());
        JsonNode json = response.readEntity(JsonNode.class);
        JsonNode infoJson = json.get("info");
        assertFalse(infoJson.has("errors"));
        JsonNode path = json.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), 1500, 10);
        assertEquals(path.get("time").asLong(), 151_000, 1_000);
    }

    @ParameterizedTest
    @CsvSource(value = {"0.05,3073", "0.5,1498"})
    public void testAvoidArea(double priority, double expectedDistance) {
        String yamlQuery = "points: [[11.58199, 50.0141], [11.5865, 50.0095]]\n" +
                "profile: car\n";

        JsonNode yamlNode = clientTarget(app, "/route-custom").request().post(Entity.json(yamlToJson(yamlQuery))).readEntity(JsonNode.class);
        JsonNode path = yamlNode.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), 661, 10);

        // 'blocking' the area either leads to a route that still crosses it (but on a faster road) or to a road
        // going all the way around it depending on the priority, see #2021
        yamlQuery += "priority:\n" +
                // a faster road (see #2021)? or maybe do both?
                "  area_custom1: " + priority + "\n" +
                "areas:\n" +
                "  custom1:\n" +
                "    type: \"Feature\"\n" +
                "    geometry: { type: \"Polygon\", coordinates: [[[11.5818,50.0126], [11.5818,50.0119], [11.5861,50.0119], [11.5861,50.0126], [11.5818,50.0126]]] }";
        yamlNode = clientTarget(app, "/route-custom").request().post(Entity.json(yamlToJson(yamlQuery))).readEntity(JsonNode.class);
        path = yamlNode.get("paths").get(0);
        assertEquals(expectedDistance, path.get("distance").asDouble(), 10);
    }

    @Test
    public void testCargoBike() throws IOException {
        String yamlQuery = "points: [[11.58199, 50.0141], [11.5865, 50.0095]]\n" +
                "profile: bike\n";
        JsonNode yamlNode = clientTarget(app, "/route-custom").request().post(Entity.json(yamlToJson(yamlQuery))).readEntity(JsonNode.class);
        JsonNode path = yamlNode.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), 661, 5);

        String queryYamlFromFile = Helper.isToString(getClass().getResourceAsStream("cargo_bike.yml"));
        yamlQuery = "points: [[11.58199, 50.0141], [11.5865, 50.0095]]\n" +
                "profile: bike\n" +
                queryYamlFromFile;
        yamlNode = clientTarget(app, "/route-custom").request().post(Entity.json(yamlToJson(yamlQuery))).readEntity(JsonNode.class);
        path = yamlNode.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), 1007, 5);

        // results should be identical be it via server-side profile or query profile:
        yamlQuery = "points: [[11.58199, 50.0141], [11.5865, 50.0095]]\n" +
                "profile: cargo_bike";
        yamlNode = clientTarget(app, "/route-custom").request().post(Entity.json(yamlToJson(yamlQuery))).readEntity(JsonNode.class);
        JsonNode path2 = yamlNode.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), path2.get("distance").asDouble(), 1);
    }

    @Test
    public void testJsonBike() {
        String jsonQuery = "{" +
                " \"points\": [[11.58199, 50.0141], [11.5865, 50.0095]]," +
                " \"profile\": \"json_bike\"" +
                "}";
        final Response response = clientTarget(app, "/route-custom").request().post(Entity.json(jsonQuery));
        assertEquals(200, response.getStatus());
        JsonNode json = response.readEntity(JsonNode.class);
        JsonNode infoJson = json.get("info");
        assertFalse(infoJson.has("errors"));
        JsonNode path = json.get("paths").get(0);
        assertEquals(path.get("distance").asDouble(), 660, 10);
    }

    static String yamlToJson(String yaml) {
        try {
            ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
            Object obj = yamlReader.readValue(yaml, Object.class);

            ObjectMapper jsonWriter = new ObjectMapper();
            return jsonWriter.writeValueAsString(obj);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}


text:
package esride.opendatabridge.application;

/**
 * Created by IntelliJ IDEA.
 * User: sma
 * Date: 03.05.13
 * Time: 14:31
 * To change this template use File | Settings | File Templates.
 */
public class StartParameterException extends Exception {

    public StartParameterException() {
        super();    //To change body of overridden methods use File | Settings | File Templates.
    }

    public StartParameterException(String message) {
        super(message);    //To change body of overridden methods use File | Settings | File Templates.
    }

    public StartParameterException(String message, Throwable cause) {
        super(message, cause);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public String getMessage() {
        return super.getMessage();    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public String getLocalizedMessage() {
        return super.getLocalizedMessage();    //To change body of overridden methods use File | Settings | File Templates.
    }
}

redpajama_set_name: RedPajamaGithub


text:
package openshift

import (
	"errors"

	"github.com/golang/glog"

	"golang.org/x/net/context"

	"github.com/tangfeixiong/go-to-cloud-1/pkg/api/proto/paas/ci/osopb3"
	// "github.com/tangfeixiong/go-to-cloud-1/pkg/server"
)

var (
	errNotFound       error = errors.New("not found")
	errNotImplemented error = errors.New("not implemented")
	errUnexpected     error = errors.New("unexpected")
)

type Appliance struct {
}

func NewAppliance() *Appliance {
	return &Appliance{}
}

func (a *Appliance) EnterWorkspace(ctx context.Context,
	in *osopb3.EnterWorkspaceRequest) (*osopb3.EnterWorkspaceResponse, error) {
	glog.Info("grpc request")
	return nil, errNotImplemented
}


text:
@protocol PLActorProcess;

#ifdef ACTOR_PRIVATE_API
@protocol PLActorLocalProcess;
#endif

@interface PLActorKit : NSObject

+ (id<PLActorProcess>) spawnWithTarget: (id) target selector: (SEL) selector;

+ (id<PLActorProcess>) spawnWithTarget: (id) target selector: (SEL) selector object: (id) object;

+ (id) receive;
+ (BOOL) receive: (id *) message withTimeout: (PLActorTimeInterval) timeout;

#ifdef HAVE_NSPREDICATE
+ (id) receiveUsingPredicate: (NSPredicate *) predicate;
+ (BOOL) receive: (id *) message usingPredicate: (NSPredicate *) predicate withTimeout: (PLActorTimeInterval) timeout;
#endif /* HAVE_NSPREDICATE */

+ (BOOL) receive: (id *) message usingFilter: (plactor_receive_filter_t) filter filterContext: (void *) context withTimeout: (PLActorTimeInterval) timeout;

+ (PLActorTxId) createTransactionId;

+ (id<PLActorProcess>) process;

#ifdef ACTOR_PRIVATE_API

+ (void) setThreadProcess: (id<PLActorLocalProcess>) mailbox;
+ (id<PLActorLocalProcess>) threadProcess;

#endif /* ACTOR_PRIVATE_API */

@end


text:
#ifndef WriteBarrier_h
#define WriteBarrier_h

#include "JSValue.h"

namespace JSC {
class JSCell;
class JSGlobalData;

inline void writeBarrier(JSGlobalData&, const JSCell*, JSValue)
{
}

inline void writeBarrier(JSGlobalData&, const JSCell*, JSCell*)
{
}

typedef enum { } Unknown;
typedef JSValue* HandleSlot;

template <typename T> struct JSValueChecker {
    static const bool IsJSValue = false;
};

template <> struct JSValueChecker<JSValue> {
    static const bool IsJSValue = true;
};

// We have a separate base class with no constructors for use in Unions.
template <typename T> class WriteBarrierBase {
public:
    COMPILE_ASSERT(!JSValueChecker<T>::IsJSValue, WriteBarrier_JSValue_is_invalid__use_unknown);
    void set(JSGlobalData& globalData, const JSCell* owner, T* value)
    {
        this->m_cell = reinterpret_cast<JSCell*>(value);
        writeBarrier(globalData, owner, this->m_cell);
#if ENABLE(JSC_ZOMBIES)
        ASSERT(!isZombie(owner));
        ASSERT(!isZombie(m_cell));
#endif
    }

    T* get() const
    {
        return reinterpret_cast<T*>(m_cell);
    }

    T* operator*() const
    {
        ASSERT(m_cell);
#if ENABLE(JSC_ZOMBIES)
        ASSERT(!isZombie(m_cell));
#endif
        return static_cast<T*>(m_cell);
    }

    T* operator->() const
    {
        ASSERT(m_cell);
        return static_cast<T*>(m_cell);
    }

    void clear() { m_cell = 0; }

    JSCell** slot() { return &m_cell; }

    typedef T* (WriteBarrierBase::*UnspecifiedBoolType);
    operator UnspecifiedBoolType*() const { return m_cell ? reinterpret_cast<UnspecifiedBoolType*>(1) : 0; }

    bool operator!() const { return !m_cell; }

    void setWithoutWriteBarrier(T* value)
    {
        this->m_cell = reinterpret_cast<JSCell*>(value);
#if ENABLE(JSC_ZOMBIES)
        ASSERT(!m_cell || !isZombie(m_cell));
#endif
    }

private:
    JSCell* m_cell;
};

template <> class WriteBarrierBase<Unknown> {
public:
    void set(JSGlobalData& globalData, const JSCell* owner, JSValue value)
    {
#if ENABLE(JSC_ZOMBIES)
        ASSERT(!isZombie(owner));
        ASSERT(!value.isZombie());
#endif
        m_value = JSValue::encode(value);
        writeBarrier(globalData, owner, value);
    }
    void setWithoutWriteBarrier(JSValue value)
    {
#if ENABLE(JSC_ZOMBIES)
        ASSERT(!value.isZombie());
#endif
        m_value = JSValue::encode(value);
    }

    JSValue get() const
    {
        return JSValue::decode(m_value);
    }
    void clear() { m_value = JSValue::encode(JSValue()); }
    void setUndefined() { m_value = JSValue::encode(jsUndefined()); }
    bool isNumber() const { return get().isNumber(); }
    bool isObject() const { return get().isObject(); }
    bool isNull() const { return get().isNull(); }
    bool isGetterSetter() const { return get().isGetterSetter(); }

    JSValue* slot()
    {
        union {
            EncodedJSValue* v;
            JSValue* slot;
        } u;
        u.v = &m_value;
        return u.slot;
    }

    typedef JSValue (WriteBarrierBase::*UnspecifiedBoolType);
    operator UnspecifiedBoolType*() const { return get() ? reinterpret_cast<UnspecifiedBoolType*>(1) : 0; }
    bool operator!() const { return !get(); }

private:
    EncodedJSValue m_value;
};

template <typename T> class WriteBarrier : public WriteBarrierBase<T> {
public:
    WriteBarrier()
    {
        this->setWithoutWriteBarrier(0);
    }

    WriteBarrier(JSGlobalData& globalData, const JSCell* owner, T* value)
    {
        this->set(globalData, owner, value);
    }
};

template <> class WriteBarrier<Unknown> : public WriteBarrierBase<Unknown> {
public:
    WriteBarrier()
    {
        this->setWithoutWriteBarrier(JSValue());
    }

    WriteBarrier(JSGlobalData& globalData, const JSCell* owner, JSValue value)
    {
        this->set(globalData, owner, value);
    }
};

template <typename U, typename V> inline bool operator==(const WriteBarrierBase<U>& lhs, const WriteBarrierBase<V>& rhs)
{
    return lhs.get() == rhs.get();
}

} // namespace JSC

#endif // WriteBarrier_h


text:
package org.talend.sdk.component.runtime.manager.service;

import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toList;

import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;

import org.talend.sdk.component.api.service.Service;
import org.talend.sdk.component.api.service.configuration.Configuration;
import org.talend.sdk.component.api.service.injector.Injector;
import org.talend.sdk.component.runtime.manager.asm.ProxyGenerator;
import org.talend.sdk.component.runtime.manager.reflect.ReflectionService;
import org.talend.sdk.component.runtime.serialization.SerializableService;

import lombok.AllArgsConstructor;

// internal service for now, we can refactor it later to expose it if needed
@AllArgsConstructor
public class InjectorImpl implements Serializable, Injector {

    private final String plugin;

    private final ReflectionService reflectionService;

    private final ProxyGenerator proxyGenerator;

    private final Map<Class<?>, Object> services;

    @Override
    public <T> T inject(final T instance) {
        if (instance == null) {
            return null;
        }
        doInject(instance.getClass(), unwrap(instance));
        return instance;
    }

    private Object unwrap(final Object instance) {
        if (instance.getClass().getName().endsWith("$$TalendServiceProxy")) {
            try {
                return proxyGenerator.getHandler(instance).getDelegate();
            } catch (final IllegalStateException nsfe) {
                // no-op
            }
        }
        return instance;
    }

    private <T> void doInject(final Class<?> type, final T instance) {
        if (type == Object.class || type == null) {
            return;
        }
        final Field[] fields = type.getDeclaredFields();
        Stream
                .of(fields)
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .filter(field -> field.isAnnotationPresent(Service.class))
                .peek(f -> {
                    if (!f.isAccessible()) {
                        f.setAccessible(true);
                    }
                })
                .forEach(field -> {
                    Object value = services.get(field.getType());
                    if (value == null && ParameterizedType.class.isInstance(field.getGenericType())) {
                        final ParameterizedType pt = ParameterizedType.class.cast(field.getGenericType());
                        if (Class.class.isInstance(pt.getRawType())
                                && Collection.class.isAssignableFrom(Class.class.cast(pt.getRawType()))) {
                            final Type serviceType = pt.getActualTypeArguments()[0];
                            if (Class.class.isInstance(serviceType)) {
                                final Class<?> serviceClass = Class.class.cast(serviceType);
                                value = services
                                        .entrySet()
                                        .stream()
                                        .filter(e -> serviceClass.isAssignableFrom(e.getKey()))
                                        .collect(toList());
                            }
                        }
                    }
                    if (value != null) {
                        try {
                            field.set(instance, value);
                        } catch (final IllegalAccessException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                });
        Stream
                .of(fields)
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .filter(field -> field.isAnnotationPresent(Configuration.class))
                .peek(field -> {
                    if (Supplier.class != field.getType()
                            || !ParameterizedType.class.isInstance(field.getGenericType())) {
                        throw new IllegalArgumentException("Field " + field + " is not a Supplier<X>,\n"
                                + "it will not be injected otherwise it wouldn't be up to date,\n"
                                + "did you mean Supplier<" + field.getType() + "> ?");
                    }
                })
                .peek(f -> {
                    if (!f.isAccessible()) {
                        f.setAccessible(true);
                    }
                })
                .forEach(field -> {
                    try {
                        final Class<?> configClass = Class.class
                                .cast(ParameterizedType.class.cast(field.getGenericType()).getActualTypeArguments()[0]);
                        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
                        final Supplier<?> supplier = () -> {
                            try {
                                return reflectionService
                                        .createConfigFactory(services, loader,
                                                reflectionService.createContextualSupplier(loader), field.getName(),
                                                field.getAnnotation(Configuration.class), field.getAnnotations(),
                                                configClass)
                                        .apply(emptyMap());
                            } catch (final NoSuchMethodException e) {
                                throw new IllegalStateException(e);
                            }
                        };
                        field.set(instance, supplier);
                    } catch (final IllegalAccessException e) {
                        throw new IllegalArgumentException(e);
                    }
                });
        if (type.getSuperclass() != type) {
            doInject(type.getSuperclass(), instance);
        }
    }

    Object writeReplace() throws ObjectStreamException {
        return new SerializableService(plugin, Injector.class.getName());
    }
}


text:
package com.gs.fw.common.mithra;

import java.io.ObjectOutput;
import java.io.IOException;
import java.sql.Timestamp;

public interface MithraDatedObject extends MithraObject
{

    public void zSetCurrentData(MithraDataObject data);

    public MithraDataObject zGetCurrentDataWithCheck();

    public MithraDataObject zGetCurrentOrTransactionalData();

    public MithraDataObject zRefreshWithLock(boolean lock);

    public void zSerializePrimaryKey(ObjectOutput out) throws IOException;

    public boolean zDataMatches(Object data, Timestamp[] asOfDates);
}


text:
import '../../../test/common-test-setup';
import './gr-autocomplete-dropdown';
import {GrAutocompleteDropdown} from './gr-autocomplete-dropdown';
import {
  pressKey,
  queryAll,
  queryAndAssert,
  waitEventLoop,
  waitUntil,
} from '../../../test/test-utils';
import {assertIsDefined} from '../../../utils/common-util';
import {fixture, html, assert} from '@open-wc/testing';
import {Key} from '../../../utils/dom-util';

suite('gr-autocomplete-dropdown', () => {
  let element: GrAutocompleteDropdown;

  const suggestionsEl = () => queryAndAssert(element, '#suggestions');

  setup(async () => {
    element = await fixture(
      html`<gr-autocomplete-dropdown></gr-autocomplete-dropdown>`
    );
    element.open();
    element.suggestions = [
      {dataValue: 'test value 1', name: 'test name 1', text: '1', label: 'hi'},
      {dataValue: 'test value 2', name: 'test name 2', text: '2'},
    ];
    await waitEventLoop();
  });

  teardown(() => {
    element.close();
  });

  test('renders', () => {
    assert.shadowDom.equal(
      element,
      /* HTML */ `

               1
               hi

               2

      `
    );
  });

  test('shows labels', () => {
    const els = queryAll<HTMLElement>(suggestionsEl(), 'li');
    assert.equal(els[0].innerText.trim(), '1\nhi');
    assert.equal(els[1].innerText.trim(), '2');
  });

  test('escape key', async () => {
    const closeSpy = sinon.spy(element, 'close');
    pressKey(element, Key.ESC);
    await waitEventLoop();
    assert.isTrue(closeSpy.called);
  });

  test('tab key', () => {
    const handleTabSpy = sinon.spy(element, 'handleTab');
    const itemSelectedStub = sinon.stub();
    element.addEventListener('item-selected', itemSelectedStub);
    pressKey(element, Key.TAB);
    assert.isTrue(handleTabSpy.called);
    assert.equal(element.cursor.index, 0);
    assert.isTrue(itemSelectedStub.called);
    assert.deepEqual(itemSelectedStub.lastCall.args[0].detail, {
      trigger: 'tab',
      selected: element.getCursorTarget(),
    });
  });

  test('enter key', () => {
    const handleEnterSpy = sinon.spy(element, 'handleEnter');
    const itemSelectedStub = sinon.stub();
    element.addEventListener('item-selected', itemSelectedStub);
    pressKey(element, Key.ENTER);
    assert.isTrue(handleEnterSpy.called);
    assert.equal(element.cursor.index, 0);
    assert.deepEqual(itemSelectedStub.lastCall.args[0].detail, {
      trigger: 'enter',
      selected: element.getCursorTarget(),
    });
  });

  test('down key', () => {
    element.isHidden = true;
    const nextSpy = sinon.spy(element.cursor, 'next');
    pressKey(element, 'ArrowDown');
    assert.isFalse(nextSpy.called);
    assert.equal(element.cursor.index, 0);
    element.isHidden = false;
    pressKey(element, 'ArrowDown');
    assert.isTrue(nextSpy.called);
    assert.equal(element.cursor.index, 1);
  });

  test('up key', () => {
    element.isHidden = true;
    const prevSpy = sinon.spy(element.cursor, 'previous');
    pressKey(element, 'ArrowUp');
    assert.isFalse(prevSpy.called);
    assert.equal(element.cursor.index, 0);
    element.isHidden = false;
    element.cursor.setCursorAtIndex(1);
    assert.equal(element.cursor.index, 1);
    pressKey(element, 'ArrowUp');
    assert.isTrue(prevSpy.called);
    assert.equal(element.cursor.index, 0);
  });

  test('tapping selects item', async () => {
    const itemSelectedStub = sinon.stub();
    element.addEventListener('item-selected', itemSelectedStub);

    suggestionsEl().querySelectorAll('li')[1].click();
    await waitEventLoop();
    assert.deepEqual(itemSelectedStub.lastCall.args[0].detail, {
      trigger: 'click',
      selected: suggestionsEl().querySelectorAll('li')[1],
    });
  });

  test('tapping child still selects item', async () => {
    const itemSelectedStub = sinon.stub();
    element.addEventListener('item-selected', itemSelectedStub);
    const lastElChild = queryAll<HTMLLIElement>(suggestionsEl(), 'li')[0]
      ?.lastElementChild;
    assertIsDefined(lastElChild);
    (lastElChild as HTMLSpanElement).click();
    await waitEventLoop();
    assert.deepEqual(itemSelectedStub.lastCall.args[0].detail, {
      trigger: 'click',
      selected: queryAll<HTMLElement>(suggestionsEl(), 'li')[0],
    });
  });

  test('updated suggestions resets cursor stops', async () => {
    const resetStopsSpy = sinon.spy(element, 'computeCursorStopsAndRefit');
    element.suggestions = [];
    await waitUntil(() => resetStopsSpy.called);
  });
});


text:
#ifndef BONEFISH_NATIVE_ENDPOINT_HPP
#define BONEFISH_NATIVE_ENDPOINT_HPP

// http://stackoverflow.com/questions/22597948/using-boostfuture-with-then-continuations/
#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY

#include <boost/thread/future.hpp>
#include <functional>
#include <msgpack.hpp>
#include <vector>

namespace bonefish {

class native_endpoint;

/*!
 * Defines a convenience type for a future that is fulfilled with a server
 * endpoint.
 */
using native_endpoint_future = boost::future<std::shared_ptr<native_endpoint>>;

/*!
 * Defines a convenience type for a promise that fullfils a server
 * endpoint as its promise.
 */
using native_endpoint_promise = boost::promise<std::shared_ptr<native_endpoint>>;

/*!
 * A class that provides the concept of an endpoint for communicating natively
 * between a component and a server. Communication is message based and conducted
 * in a zero copy manner, as ownership of the message is passed via the endpoint.
 */
class native_endpoint
{
public:
    /*!
     * Defines a handler used by the endpoint for sending messages. The message
     * is represented as a set of fields and the zone used to allocate them.
     * Ownership of the fields is passed off to the recipient of the message.
     */
    using send_message_handler =
            std::function<void(
                    std::vector<msgpack::object>&& fields, msgpack::zone&& zone)>;

public:
    native_endpoint();

    const send_message_handler& get_send_message_handler() const;
    void set_send_message_handler(send_message_handler&& handler);

private:
    send_message_handler m_send_message_handler;
};

inline native_endpoint::native_endpoint()
    : m_send_message_handler()
{
}

inline const native_endpoint::send_message_handler&
native_endpoint::get_send_message_handler() const
{
    return m_send_message_handler;
}

inline void native_endpoint::set_send_message_handler(
        send_message_handler&& handler)
{
    m_send_message_handler = std::move(handler);
}

} // namespace bonefish

#endif // BONEFISH_NATIVE_ENDPOINT_HPP


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Microsoft Public License (MS-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
//
//   The terms "reproduce," "reproduction," "derivative works," and
//   "distribution" have the same meaning here as under U.S. copyright law. A
//   "contribution" is the original software, or any additions or changes to
//   the software. A "contributor" is any person that distributes its
//   contribution under this license. "Licensed patents" are a contributor's
//   patent claims that read directly on its contribution.
//
// 2. Grant of Rights
//
//   (A) Copyright Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free copyright license
//       to reproduce its contribution, prepare derivative works of its
//       contribution, and distribute its contribution or any derivative works
//       that you create.
//
//   (B) Patent Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free license under its
//       licensed patents to make, have made, use, sell, offer for sale,
//       import, and/or otherwise dispose of its contribution in the software
//       or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
//
//   (A) No Trademark License- This license does not grant you rights to use
//       any contributors' name, logo, or trademarks.
//
//   (B) If you bring a patent claim against any contributor over patents that
//       you claim are infringed by the software, your patent license from such
//       contributor to the software ends automatically.
//
//   (C) If you distribute any portion of the software, you must retain all
//       copyright, patent, trademark, and attribution notices that are present
//       in the software.
//
//   (D) If you distribute any portion of the software in source code form, you
//       may do so only under this license by including a complete copy of this
//       license with your distribution. If you distribute any portion of the
//       software in compiled or object code form, you may only do so under a
//       license that complies with this license.
//
//   (E) The software is licensed "as-is." You bear the risk of using it. The
//       contributors give no express warranties, guarantees or conditions. You
//       may have additional consumer rights under your local laws which this
//       license cannot change. To the extent permitted under your local laws,
//       the contributors exclude the implied warranties of merchantability,
//       fitness for a particular purpose and non-infringement.
//

using System;
using System.Collections.Generic;

namespace Microsoft.ClearScript.Util
{
    internal class ConcurrentWeakSet<T> where T : class
    {
        private readonly object dataLock = new object();
        private List<WeakReference> weakRefs = new List<WeakReference>();

        public int Count
        {
            get { return GetItems().Count; }
        }

        public bool Contains(T item)
        {
            MiscHelpers.VerifyNonNullArgument(item, "item");
            return GetItems().Contains(item);
        }

        public bool TryAdd(T item)
        {
            MiscHelpers.VerifyNonNullArgument(item, "item");
            lock (dataLock)
            {
                if (!GetItemsInternal().Contains(item))
                {
                    weakRefs.Add(new WeakReference(item));
                    return true;
                }

                return false;
            }
        }

        public void ForEach(Action<T> action)
        {
            MiscHelpers.VerifyNonNullArgument(action, "action");
            GetItems().ForEach(action);
        }

        private List<T> GetItems()
        {
            lock (dataLock)
            {
                return GetItemsInternal();
            }
        }

        private List<T> GetItemsInternal()
        {
            var items = new List<T>();
            var tempWeakRefs = new List<WeakReference>();
            foreach (var weakRef in weakRefs)
            {
                var item = weakRef.Target as T;
                if (item != null)
                {
                    items.Add(item);
                    tempWeakRefs.Add(weakRef);
                }
            }

            weakRefs = tempWeakRefs;
            return items;
        }
    }
}


text:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"

Describe "New-Archive" {

    # arrange
    $content="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor."
    $file = New-item "TestDrive:\one.txt" -Type File

    Set-Content $file -value $content

    It -skip "Should create a compressed file" {

        # act
        { $archive = New-Archive $file -Type ZIP } | Should Not Throw

        # archive should exist
        Test-Path $archive | Should Be $true

    }

}


text:
> Mock any executable binary

Useful for mocking tests that run executable binary, especially to fake edge cases and increase test coverage.

## Install

```
$ npm install --save-dev mock-bin
```

## Usage

```js
const mockBin = require('mock-bin');
const log = 'mocking git!';
const unmock = await mockBin('git', 'node', `console.log('${log}')`);
let actual = shell.exec('git').stdout;
t.is(log + '\n', actual);

unmock();
actual = shell.exec('git').stdout;
t.not(log + '\n', actual);
```

## API

### mockBin(bin, shebang, code)

Returns a promise which resolves with an unmock function.

#### bin

Type: `string`

EG: `'git'`.

#### shebang

Type: `string`

Shebang or environment

EG: `'#!/usr/bin/env node'` or `'bash'`

##### code

Type: `string`

The actual code you want to execute.

## Related

- [mock-git](https://github.com/stevemao/mock-git) - Mock any git command

## License

MIT © [Steve Mao](https://github.com/stevemao)


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

package org.flowable.engine.impl;

import java.util.List;

import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
import org.flowable.engine.history.HistoricDetailQuery;
import org.flowable.engine.history.HistoricIdentityLink;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.history.HistoricTaskInstanceQuery;
import org.flowable.engine.history.HistoricVariableInstanceQuery;
import org.flowable.engine.history.NativeHistoricActivityInstanceQuery;
import org.flowable.engine.history.NativeHistoricDetailQuery;
import org.flowable.engine.history.NativeHistoricProcessInstanceQuery;
import org.flowable.engine.history.NativeHistoricTaskInstanceQuery;
import org.flowable.engine.history.NativeHistoricVariableInstanceQuery;
import org.flowable.engine.history.ProcessInstanceHistoryLogQuery;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.cmd.DeleteHistoricProcessInstanceCmd;
import org.flowable.engine.impl.cmd.DeleteHistoricTaskInstanceCmd;
import org.flowable.engine.impl.cmd.GetHistoricIdentityLinksForTaskCmd;

/**
 * @author Tom Baeyens
 * @author Bernd Ruecker (camunda)
 * @author Christian Stettler
 */
public class HistoryServiceImpl extends ServiceImpl implements HistoryService {

  public HistoryServiceImpl() {

  }

  public HistoryServiceImpl(ProcessEngineConfigurationImpl processEngineConfiguration) {
    super(processEngineConfiguration);
  }

  public HistoricProcessInstanceQuery createHistoricProcessInstanceQuery() {
    return new HistoricProcessInstanceQueryImpl(commandExecutor);
  }

  public HistoricActivityInstanceQuery createHistoricActivityInstanceQuery() {
    return new HistoricActivityInstanceQueryImpl(commandExecutor);
  }

  public HistoricTaskInstanceQuery createHistoricTaskInstanceQuery() {
    return new HistoricTaskInstanceQueryImpl(commandExecutor, processEngineConfiguration.getDatabaseType());
  }

  public HistoricDetailQuery createHistoricDetailQuery() {
    return new HistoricDetailQueryImpl(commandExecutor);
  }

  @Override
  public NativeHistoricDetailQuery createNativeHistoricDetailQuery() {
    return new NativeHistoricDetailQueryImpl(commandExecutor);
  }

  public HistoricVariableInstanceQuery createHistoricVariableInstanceQuery() {
    return new HistoricVariableInstanceQueryImpl(commandExecutor);
  }

  @Override
  public NativeHistoricVariableInstanceQuery createNativeHistoricVariableInstanceQuery() {
    return new NativeHistoricVariableInstanceQueryImpl(commandExecutor);
  }

  public void deleteHistoricTaskInstance(String taskId) {
    commandExecutor.execute(new DeleteHistoricTaskInstanceCmd(taskId));
  }

  public void deleteHistoricProcessInstance(String processInstanceId) {
    commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId));
  }

  public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() {
    return new NativeHistoricProcessInstanceQueryImpl(commandExecutor);
  }

  public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() {
    return new NativeHistoricTaskInstanceQueryImpl(commandExecutor);
  }

  public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() {
    return new NativeHistoricActivityInstanceQueryImpl(commandExecutor);
  }

  @Override
  public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) {
    return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId));
  }

  @Override
  public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) {
    return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null));
  }

  @Override
  public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) {
    return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId);
  }

}


text:
var randomString = require('random-string');
var mand = require('mandrill-api');

// Sends a password-reset request.
module.exports = function(app, config) {

	var mandrill = new mand.Mandrill(config.mandrill.key);

	app.post(config.endpoint + '/password-reset', function(req, res) {

		var service = app.service(config.endpoint);

		if (!req.body.email) {
			return res.json({
				error: 'email required',
				message: 'Please pass an email address to send a password reset request.'
			});
		} else {

			service.find({
				query: {
					email: req.body.email.toLowerCase()
				}
			}, function(err, users) {
				if (err) {
					return res.status(500).json(err);
				}

				// If a user was found, create a code and send a password change request.
				if (users[0]) {
					var user = users[0];

					var code;

					if (!user.code) {
						code = user.code = randomString();
					} else {
						code = user.code;
					}
					// Update the user with the code and send back the credentials.
					service.update(user[config.id], user, function(err, user) {

						// Resend verification email.
						var protocol = 'http';
						if (req.headers['x-forwarded-proto'] === 'https') {
							protocol = 'https';
						}
						var url = protocol + '://' + req.headers.host + '/#!passwordchange';

						var body = 'Click here to change your password: \n ' + url + '/' + code +
							'\n\n or go to this page: ' + url +
							'\n\n and enter this code: ' + code;

						var message = {
							'text': body,
							'subject': 'Password Change Request',
							'from_email': config.mandrill.from_email,
							'from_name': config.mandrill.from_name,
							'to': [{
								'email': user.email,
								'type': 'to'
							}],
							'important': true,
							'tags': [
								'change-password'
							],
							'subaccount': config.mandrill.subaccount,
							'metadata': {
								'website': config.mandrill.website
							},
							'recipient_metadata': [{
								'rcpt': user.email,
								'values': {
									'userID': user.userID
								}
							}]
						};

						mandrill.messages.send({
							'message': message,
							'async': true
						}, function() {
							return res.json({
								success: true
							});
						}, function(e) {
							// Mandrill returns the error as an object with name and message keys
							console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
							// A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
							return res.status(500).json(e);
						});

					});

					// No user was found.
				} else {
					return res.json({
						error: 'User Not Found',
						message: 'Could not find a user with that email address.'
					});
				}
			});
		}
	});
};


text:
package jade.imtp.leap.JICP;

//#J2ME_EXCLUDE_FILE

import jade.util.leap.Properties;

import java.net.InetAddress;

import jade.security.JADESecurityException;

public interface PDPContextManager {
	public static final String MSISDN = "msisdn";
	public static final String USERNAME = "pdp-context-username";
	public static final String PASSWORD = "pdp-context-password";
	public static final String LOCATION = "location";

	public static interface Listener {
		void handlePDPContextClosed(String msisdn);
	}

  void init(Properties p) throws Exception;

  void registerListener(Listener l);

  Properties getPDPContextInfo(InetAddress addr, String owner) throws JADESecurityException;
}


text:
"use strict";

const expect = require("chai").expect;
const findEmoji = require("../../../../../../client/js/libs/handlebars/ircmessageparser/findEmoji");

describe("findEmoji", () => {
	it("should find default emoji presentation character", () => {
		const input = "test \u{231A} test";
		const expected = [{
			start: 5,
			end: 6,
			emoji: "\u{231A}",
		}];

		const actual = findEmoji(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find default text presentation character rendered as emoji", () => {
		const input = "test \u{2194}\u{FE0F} test";
		const expected = [{
			start: 5,
			end: 7,
			emoji: "\u{2194}\u{FE0F}",
		}];

		const actual = findEmoji(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find emoji modifier base", () => {
		const input = "test\u{1F469}test";
		const expected = [{
			start: 4,
			end: 6,
			emoji: "\u{1F469}",
		}];

		const actual = findEmoji(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find emoji modifier base followed by a modifier", () => {
		const input = "test\u{1F469}\u{1F3FF}test";
		const expected = [{
			start: 4,
			end: 8,
			emoji: "\u{1F469}\u{1F3FF}",
		}];

		const actual = findEmoji(input);

		expect(actual).to.deep.equal(expected);
	});
});


text:
(function (module) {

    var resultController = function (user) {
        this.user = user;
    };
    module.controller('resultController', resultController);
}(angular.module('forms')));


text:
/*
 * Created on Mar 6, 2004
 *
 * To change this generated comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package org.spongycastle.openpgp;

import java.io.IOException;

import org.spongycastle.bcpg.BCPGInputStream;
import org.spongycastle.bcpg.MarkerPacket;

/**
 * a PGP marker packet - in general these should be ignored other than where
 * the idea is to preserve the original input stream.
 */
public class PGPMarker
{
    private MarkerPacket p;

    /**
     * Default constructor.
     *
     * @param in
     * @throws IOException
     */
    public PGPMarker(
        BCPGInputStream in)
        throws IOException
    {
        p = (MarkerPacket)in.readPacket();
    }
}


text:
#include "MulticopterPositionControl.hpp"

using namespace time_literals;
using namespace matrix;

MulticopterPositionControl::MulticopterPositionControl(bool vtol) :
	SuperBlock(nullptr, "MPC"),
	ModuleParams(nullptr),
	WorkItem(MODULE_NAME, px4::wq_configurations::nav_and_controllers),
	_vehicle_attitude_setpoint_pub(vtol ? ORB_ID(mc_virtual_attitude_setpoint) : ORB_ID(vehicle_attitude_setpoint)),
	_vel_x_deriv(this, "VELD"),
	_vel_y_deriv(this, "VELD"),
	_vel_z_deriv(this, "VELD"),
	_cycle_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": cycle time"))
{
	if (vtol) {
		// if vehicle is a VTOL we want to enable weathervane capabilities
		_wv_controller = new WeatherVane();
	}

	// fetch initial parameter values
	parameters_update(true);

	// set failsafe hysteresis
	_failsafe_land_hysteresis.set_hysteresis_time_from(false, LOITER_TIME_BEFORE_DESCEND);
}

MulticopterPositionControl::~MulticopterPositionControl()
{
	delete _wv_controller;

	perf_free(_cycle_perf);
}

bool MulticopterPositionControl::init()
{
	if (!_local_pos_sub.registerCallback()) {
		PX4_ERR("vehicle_local_position callback registration failed!");
		return false;
	}

	// limit to every other vehicle_local_position update (50 Hz)
	_local_pos_sub.set_interval_us(20_ms);

	_time_stamp_last_loop = hrt_absolute_time();

	return true;
}

int MulticopterPositionControl::parameters_update(bool force)
{
	// check for parameter updates
	if (_parameter_update_sub.updated() || force) {
		// clear update
		parameter_update_s pupdate;
		_parameter_update_sub.copy(&pupdate);

		// update parameters from storage
		ModuleParams::updateParams();
		SuperBlock::updateParams();

		if (_param_mpc_tiltmax_air.get() > MAX_SAFE_TILT_DEG) {
			_param_mpc_tiltmax_air.set(MAX_SAFE_TILT_DEG);
			_param_mpc_tiltmax_air.commit();
			mavlink_log_critical(&_mavlink_log_pub, "Tilt constrained to safe value");
		}

		if (_param_mpc_tiltmax_lnd.get() > _param_mpc_tiltmax_air.get()) {
			_param_mpc_tiltmax_lnd.set(_param_mpc_tiltmax_air.get());
			_param_mpc_tiltmax_lnd.commit();
			mavlink_log_critical(&_mavlink_log_pub, "Land tilt has been constrained by max tilt");
		}

		_control.setPositionGains(Vector3f(_param_mpc_xy_p.get(), _param_mpc_xy_p.get(), _param_mpc_z_p.get()));
		_control.setVelocityGains(
			Vector3f(_param_mpc_xy_vel_p_acc.get(), _param_mpc_xy_vel_p_acc.get(), _param_mpc_z_vel_p_acc.get()),
			Vector3f(_param_mpc_xy_vel_i_acc.get(), _param_mpc_xy_vel_i_acc.get(), _param_mpc_z_vel_i_acc.get()),
			Vector3f(_param_mpc_xy_vel_d_acc.get(), _param_mpc_xy_vel_d_acc.get(), _param_mpc_z_vel_d_acc.get()));
		_control.setVelocityLimits(_param_mpc_xy_vel_max.get(), _param_mpc_z_vel_max_up.get(), _param_mpc_z_vel_max_dn.get());
		_control.setThrustLimits(_param_mpc_thr_min.get(), _param_mpc_thr_max.get());
		_control.setTiltLimit(M_DEG_TO_RAD_F * _param_mpc_tiltmax_air.get()); // convert to radians!

		// Check that the design parameters are inside the absolute maximum constraints
		if (_param_mpc_xy_cruise.get() > _param_mpc_xy_vel_max.get()) {
			_param_mpc_xy_cruise.set(_param_mpc_xy_vel_max.get());
			_param_mpc_xy_cruise.commit();
			mavlink_log_critical(&_mavlink_log_pub, "Cruise speed has been constrained by max speed");
		}

		if (_param_mpc_vel_manual.get() > _param_mpc_xy_vel_max.get()) {
			_param_mpc_vel_manual.set(_param_mpc_xy_vel_max.get());
			_param_mpc_vel_manual.commit();
			mavlink_log_critical(&_mavlink_log_pub, "Manual speed has been constrained by max speed");
		}

		if (_param_mpc_thr_hover.get() > _param_mpc_thr_max.get() ||
		    _param_mpc_thr_hover.get() < _param_mpc_thr_min.get()) {
			_param_mpc_thr_hover.set(math::constrain(_param_mpc_thr_hover.get(), _param_mpc_thr_min.get(),
						 _param_mpc_thr_max.get()));
			_param_mpc_thr_hover.commit();
			mavlink_log_critical(&_mavlink_log_pub, "Hover thrust has been constrained by min/max");
		}

		if (!_param_mpc_use_hte.get() || !_hover_thrust_initialized) {
			_control.setHoverThrust(_param_mpc_thr_hover.get());
			_hover_thrust_initialized = true;
		}

		_flight_tasks.handleParameterUpdate();

		// initialize vectors from params and enforce constraints
		_param_mpc_tko_speed.set(math::min(_param_mpc_tko_speed.get(), _param_mpc_z_vel_max_up.get()));
		_param_mpc_land_speed.set(math::min(_param_mpc_land_speed.get(), _param_mpc_z_vel_max_dn.get()));

		// set trigger time for takeoff delay
		_takeoff.setSpoolupTime(_param_mpc_spoolup_time.get());
		_takeoff.setTakeoffRampTime(_param_mpc_tko_ramp_t.get());
		_takeoff.generateInitialRampValue(_param_mpc_z_vel_p_acc.get());

		if (_wv_controller != nullptr) {
			_wv_controller->update_parameters();
		}
	}

	return OK;
}

void MulticopterPositionControl::poll_subscriptions()
{
	_vehicle_status_sub.update(&_vehicle_status);
	_vehicle_land_detected_sub.update(&_vehicle_land_detected);
	_control_mode_sub.update(&_control_mode);
	_home_pos_sub.update(&_home_pos);

	if (_param_mpc_use_hte.get()) {
		hover_thrust_estimate_s hte;

		if (_hover_thrust_estimate_sub.update(&hte)) {
			if (hte.valid) {
				_control.updateHoverThrust(hte.hover_thrust);
			}
		}
	}
}

void MulticopterPositionControl::limit_altitude(vehicle_local_position_setpoint_s &setpoint)
{
	if (_vehicle_land_detected.alt_max < 0.0f || !_home_pos.valid_alt || !_local_pos.v_z_valid) {
		// there is no altitude limitation present or the required information not available
		return;
	}

	// maximum altitude == minimal z-value (NED)
	const float min_z = _home_pos.z + (-_vehicle_land_detected.alt_max);

	if (_states.position(2) < min_z) {
		// above maximum altitude, only allow downwards flight == positive vz-setpoints (NED)
		setpoint.z = min_z;
		setpoint.vz = math::max(setpoint.vz, 0.f);
	}
}

void MulticopterPositionControl::set_vehicle_states(const float &vel_sp_z)
{
	// only set position states if valid and finite
	if (PX4_ISFINITE(_local_pos.x) && PX4_ISFINITE(_local_pos.y) && _local_pos.xy_valid) {
		_states.position(0) = _local_pos.x;
		_states.position(1) = _local_pos.y;

	} else {
		_states.position(0) = _states.position(1) = NAN;
	}

	if (PX4_ISFINITE(_local_pos.z) && _local_pos.z_valid) {
		_states.position(2) = _local_pos.z;

	} else {
		_states.position(2) = NAN;
	}

	if (PX4_ISFINITE(_local_pos.vx) && PX4_ISFINITE(_local_pos.vy) && _local_pos.v_xy_valid) {
		_states.velocity(0) = _local_pos.vx;
		_states.velocity(1) = _local_pos.vy;
		_states.acceleration(0) = _vel_x_deriv.update(_states.velocity(0));
		_states.acceleration(1) = _vel_y_deriv.update(_states.velocity(1));

	} else {
		_states.velocity(0) = _states.velocity(1) = NAN;
		_states.acceleration(0) = _states.acceleration(1) = NAN;
		// reset derivatives to prevent acceleration spikes when regaining velocity
		_vel_x_deriv.reset();
		_vel_y_deriv.reset();
	}

	if (PX4_ISFINITE(_local_pos.vz) && _local_pos.v_z_valid) {
		_states.velocity(2) = _local_pos.vz;

		if (PX4_ISFINITE(vel_sp_z) && fabsf(vel_sp_z) > FLT_EPSILON && PX4_ISFINITE(_local_pos.z_deriv)) {
			// A change in velocity is demanded. Set velocity to the derivative of position
			// because it has less bias but blend it in across the landing speed range
			float weighting = fminf(fabsf(vel_sp_z) / _param_mpc_land_speed.get(), 1.0f);
			_states.velocity(2) = _local_pos.z_deriv * weighting + _local_pos.vz * (1.0f - weighting);
		}

		_states.acceleration(2) = _vel_z_deriv.update(_states.velocity(2));

	} else {
		_states.velocity(2) = _states.acceleration(2) = NAN;
		// reset derivative to prevent acceleration spikes when regaining velocity
		_vel_z_deriv.reset();
	}

	if (PX4_ISFINITE(_local_pos.heading)) {
		_states.yaw = _local_pos.heading;
	}
}

int MulticopterPositionControl::print_status()
{
	if (_flight_tasks.isAnyTaskActive()) {
		PX4_INFO("Running, active flight task: %i", _flight_tasks.getActiveTask());

	} else {
		PX4_INFO("Running, no flight task active");
	}

	perf_print_counter(_cycle_perf);

	return 0;
}

void MulticopterPositionControl::Run()
{
	if (should_exit()) {
		_local_pos_sub.unregisterCallback();
		exit_and_cleanup();
		return;
	}

	perf_begin(_cycle_perf);

	if (_local_pos_sub.update(&_local_pos)) {

		poll_subscriptions();
		parameters_update(false);

		const hrt_abstime time_stamp_now = _local_pos.timestamp;
		const float dt = math::constrain(((time_stamp_now - _time_stamp_last_loop) * 1e-6f), 0.002f, 0.04f);
		_time_stamp_last_loop = time_stamp_now;

		// set _dt in controllib Block - the time difference since the last loop iteration in seconds
		setDt(dt);

		const bool was_in_failsafe = _in_failsafe;
		_in_failsafe = false;

		// activate the weathervane controller if required. If activated a flighttask can use it to implement a yaw-rate control strategy
		// that turns the nose of the vehicle into the wind
		if (_wv_controller != nullptr) {

			// in manual mode we just want to use weathervane if position is controlled as well
			// in mission, enabling wv is done in flight task
			if (_control_mode.flag_control_manual_enabled) {
				if (_control_mode.flag_control_position_enabled && _wv_controller->weathervane_enabled()) {
					_wv_controller->activate();

				} else {
					_wv_controller->deactivate();
				}
			}

			_wv_controller->update(_wv_dcm_z_sp_prev, _states.yaw);
		}

		// an update is necessary here because otherwise the takeoff state doesn't get skiped with non-altitude-controlled modes
		_takeoff.updateTakeoffState(_control_mode.flag_armed, _vehicle_land_detected.landed, false, 10.f,
					    !_control_mode.flag_control_climb_rate_enabled, time_stamp_now);

		// switch to the required flighttask
		start_flight_task();

		// check if any task is active
		if (_flight_tasks.isAnyTaskActive()) {
			// setpoints and constraints for the position controller from flighttask or failsafe
			vehicle_local_position_setpoint_s setpoint = FlightTask::empty_setpoint;
			vehicle_constraints_s constraints = FlightTask::empty_constraints;

			_flight_tasks.setYawHandler(_wv_controller);

			// update task
			if (!_flight_tasks.update()) {
				// FAILSAFE
				// Task was not able to update correctly. Do Failsafe.
				failsafe(time_stamp_now, setpoint, _states, false, !was_in_failsafe);

			} else {
				setpoint = _flight_tasks.getPositionSetpoint();
				constraints = _flight_tasks.getConstraints();

				_failsafe_land_hysteresis.set_state_and_update(false, time_stamp_now);
			}

			// publish trajectory setpoint
			_traj_sp_pub.publish(setpoint);

			landing_gear_s gear = _flight_tasks.getGear();

			// check if all local states are valid and map accordingly
			set_vehicle_states(setpoint.vz);

			// fix to prevent the takeoff ramp to ramp to a too high value or get stuck because of NAN
			// TODO: this should get obsolete once the takeoff limiting moves into the flight tasks
			if (!PX4_ISFINITE(constraints.speed_up) || (constraints.speed_up > _param_mpc_z_vel_max_up.get())) {
				constraints.speed_up = _param_mpc_z_vel_max_up.get();
			}

			// limit tilt during takeoff ramupup
			if (_takeoff.getTakeoffState() < TakeoffState::flight) {
				constraints.tilt = math::radians(_param_mpc_tiltmax_lnd.get());
				setpoint.acceleration[2] = NAN;
			}

			// limit altitude only if local position is valid
			if (PX4_ISFINITE(_states.position(2))) {
				limit_altitude(setpoint);
			}

			// handle smooth takeoff
			_takeoff.updateTakeoffState(_control_mode.flag_armed, _vehicle_land_detected.landed, constraints.want_takeoff,
						    constraints.speed_up, !_control_mode.flag_control_climb_rate_enabled, time_stamp_now);
			constraints.speed_up = _takeoff.updateRamp(dt, constraints.speed_up);

			const bool not_taken_off = _takeoff.getTakeoffState() < TakeoffState::rampup;
			const bool flying = _takeoff.getTakeoffState() >= TakeoffState::flight;
			const bool flying_but_ground_contact = flying && _vehicle_land_detected.ground_contact;

			if (flying) {
				_control.setThrustLimits(_param_mpc_thr_min.get(), _param_mpc_thr_max.get());

			} else {
				// allow zero thrust when taking off and landing
				_control.setThrustLimits(0.f, _param_mpc_thr_max.get());
			}

			if (not_taken_off || flying_but_ground_contact) {
				// we are not flying yet and need to avoid any corrections
				reset_setpoint_to_nan(setpoint);
				Vector3f(0.f, 0.f, 100.f).copyTo(setpoint.acceleration); // High downwards acceleration to make sure there's no thrust
				// set yaw-sp to current yaw
				// TODO: we need a clean way to disable yaw control
				setpoint.yaw = _states.yaw;
				setpoint.yawspeed = 0.f;
				// prevent any integrator windup
				_control.resetIntegral();
			}

			if (not_taken_off) {
				// reactivate the task which will reset the setpoint to current state
				_flight_tasks.reActivate();
			}

			// Run position control
			_control.setState(_states);
			_control.setConstraints(constraints);
			_control.setInputSetpoint(setpoint);

			if (!_control.update(dt)) {
				if ((time_stamp_now - _last_warn) > 1_s) {
					PX4_WARN("invalid setpoints");
					_last_warn = time_stamp_now;
				}

				failsafe(time_stamp_now, setpoint, _states, true, !was_in_failsafe);
				_control.setInputSetpoint(setpoint);
				constraints = FlightTask::empty_constraints;
				_control.update(dt);
			}

			// Fill local position, velocity and thrust setpoint.
			// This message contains setpoints where each type of setpoint is either the input to the PositionController
			// or was generated by the PositionController and therefore corresponds to the PositioControl internal states (states that were generated by P-PID).
			// Example:
			// If the desired setpoint is position-setpoint, _local_pos_sp will contain
			// position-, velocity- and thrust-setpoint where the velocity- and thrust-setpoint were generated by the PositionControlller.
			// If the desired setpoint has a velocity-setpoint only, then _local_pos_sp will contain valid velocity- and thrust-setpoint, but the position-setpoint
			// will remain NAN. Given that the PositionController cannot generate a position-setpoint, this type of setpoint is always equal to the input to the
			// PositionController.
			vehicle_local_position_setpoint_s local_pos_sp{};
			local_pos_sp.timestamp = time_stamp_now;
			_control.getLocalPositionSetpoint(local_pos_sp);

			// Publish local position setpoint
			// This message will be used by other modules (such as Landdetector) to determine vehicle intention.
			_local_pos_sp_pub.publish(local_pos_sp);

			// Inform FlightTask about the input and output of the velocity controller
			// This is used to properly initialize the velocity setpoint when onpening the position loop (position unlock)
			_flight_tasks.updateVelocityControllerIO(Vector3f(local_pos_sp.vx, local_pos_sp.vy, local_pos_sp.vz),
					Vector3f(local_pos_sp.acceleration));

			vehicle_attitude_setpoint_s attitude_setpoint{};
			attitude_setpoint.timestamp = time_stamp_now;
			_control.getAttitudeSetpoint(attitude_setpoint);

			// publish attitude setpoint
			// It's important to publish also when disarmed otheriwse the attitude setpoint stays uninitialized.
			// Not publishing when not running a flight task
			// in stabilized mode attitude setpoints get ignored
			// in offboard with attitude setpoints they come from MAVLink directly
			_vehicle_attitude_setpoint_pub.publish(attitude_setpoint);

			_wv_dcm_z_sp_prev = Quatf(attitude_setpoint.q_d).dcm_z();

			// if there's any change in landing gear setpoint publish it
			if (gear.landing_gear != _old_landing_gear_position
			    && gear.landing_gear != landing_gear_s::GEAR_KEEP) {
				_landing_gear.timestamp = time_stamp_now;
				_landing_gear.landing_gear = gear.landing_gear;
				_landing_gear_pub.publish(_landing_gear);
			}

			_old_landing_gear_position = gear.landing_gear;

		} else {
			// reset the numerical derivatives to not generate d term spikes when coming from non-position controlled operation
			_vel_x_deriv.reset();
			_vel_y_deriv.reset();
			_vel_z_deriv.reset();
		}
	}

	perf_end(_cycle_perf);
}

void MulticopterPositionControl::start_flight_task()
{
	bool task_failure = false;
	bool should_disable_task = true;
	int prev_failure_count = _task_failure_count;

	// Do not run any flight task for VTOLs in fixed-wing mode
	if (_vehicle_status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING) {
		_flight_tasks.switchTask(FlightTaskIndex::None);
		return;
	}

	if (_vehicle_status.in_transition_mode) {
		should_disable_task = false;
		FlightTaskError error = _flight_tasks.switchTask(FlightTaskIndex::Transition);

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Transition activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			// we want to be in this mode, reset the failure count
			_task_failure_count = 0;
		}

		return;
	}

	// offboard
	if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_OFFBOARD
	    && (_control_mode.flag_control_altitude_enabled ||
		_control_mode.flag_control_position_enabled ||
		_control_mode.flag_control_climb_rate_enabled ||
		_control_mode.flag_control_velocity_enabled ||
		_control_mode.flag_control_acceleration_enabled)) {

		should_disable_task = false;
		FlightTaskError error = _flight_tasks.switchTask(FlightTaskIndex::Offboard);

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Offboard activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			// we want to be in this mode, reset the failure count
			_task_failure_count = 0;
		}
	}

	// Auto-follow me
	if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_AUTO_FOLLOW_TARGET) {
		should_disable_task = false;
		FlightTaskError error = _flight_tasks.switchTask(FlightTaskIndex::AutoFollowMe);

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Follow-Me activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			// we want to be in this mode, reset the failure count
			_task_failure_count = 0;
		}

	} else if (_control_mode.flag_control_auto_enabled) {
		// Auto related maneuvers
		should_disable_task = false;
		FlightTaskError error = FlightTaskError::NoError;

		error =  _flight_tasks.switchTask(FlightTaskIndex::AutoLineSmoothVel);

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Auto activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			// we want to be in this mode, reset the failure count
			_task_failure_count = 0;
		}

	} else if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_DESCEND) {

		// Emergency descend
		should_disable_task = false;
		FlightTaskError error = FlightTaskError::NoError;

		error =  _flight_tasks.switchTask(FlightTaskIndex::Descend);

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Descend activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			// we want to be in this mode, reset the failure count
			_task_failure_count = 0;
		}

	}

	// manual position control
	if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_POSCTL || task_failure) {
		should_disable_task = false;
		FlightTaskError error = FlightTaskError::NoError;

		switch (_param_mpc_pos_mode.get()) {
		case 1:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualPositionSmooth);
			break;

		case 3:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualPositionSmoothVel);
			break;

		default:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualPosition);
			break;
		}

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Position-Ctrl activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			check_failure(task_failure, vehicle_status_s::NAVIGATION_STATE_POSCTL);
			task_failure = false;
		}
	}

	// manual altitude control
	if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_ALTCTL || task_failure) {
		should_disable_task = false;
		FlightTaskError error = FlightTaskError::NoError;

		switch (_param_mpc_pos_mode.get()) {
		case 1:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualAltitudeSmooth);
			break;

		case 3:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualAltitudeSmoothVel);
			break;

		default:
			error =  _flight_tasks.switchTask(FlightTaskIndex::ManualAltitude);
			break;
		}

		if (error != FlightTaskError::NoError) {
			if (prev_failure_count == 0) {
				PX4_WARN("Altitude-Ctrl activation failed with error: %s", _flight_tasks.errorToString(error));
			}

			task_failure = true;
			_task_failure_count++;

		} else {
			check_failure(task_failure, vehicle_status_s::NAVIGATION_STATE_ALTCTL);
			task_failure = false;
		}
	}

	if (_vehicle_status.nav_state == vehicle_status_s::NAVIGATION_STATE_ORBIT) {
		should_disable_task = false;
	}

	// check task failure
	if (task_failure) {

		// for some reason no flighttask was able to start.
		// go into failsafe flighttask
		FlightTaskError error = _flight_tasks.switchTask(FlightTaskIndex::Failsafe);

		if (error != FlightTaskError::NoError) {
			// No task was activated.
			_flight_tasks.switchTask(FlightTaskIndex::None);
		}

	} else if (should_disable_task) {
		_flight_tasks.switchTask(FlightTaskIndex::None);
	}
}

void MulticopterPositionControl::failsafe(const hrt_abstime &now, vehicle_local_position_setpoint_s &setpoint,
		const PositionControlStates &states, const bool force, bool warn)
{
	// do not warn while we are disarmed, as we might not have valid setpoints yet
	if (!_control_mode.flag_armed) {
		warn = false;
	}

	_failsafe_land_hysteresis.set_state_and_update(true, now);

	if (!_failsafe_land_hysteresis.get_state() && !force) {
		// just keep current setpoint and don't do anything.

	} else {
		reset_setpoint_to_nan(setpoint);

		if (PX4_ISFINITE(_states.velocity(0)) && PX4_ISFINITE(_states.velocity(1))) {
			// don't move along xy
			setpoint.vx = setpoint.vy = 0.f;

			if (warn) {
				PX4_WARN("Failsafe: stop and wait");
			}

		} else {
			// descend with land speed since we can't stop
			setpoint.acceleration[0] = setpoint.acceleration[1] = 0.f;
			setpoint.vz = _param_mpc_land_speed.get();

			if (warn) {
				PX4_WARN("Failsafe: blind land");
			}
		}

		if (PX4_ISFINITE(_states.velocity(2))) {
			// don't move along z if we can stop in all dimensions
			if (!PX4_ISFINITE(setpoint.vz)) {
				setpoint.vz = 0.f;
			}

		} else {
			// emergency descend with a bit below hover thrust
			setpoint.vz = NAN;
			setpoint.acceleration[2] = .3f;

			if (warn) {
				PX4_WARN("Failsafe: blind descend");
			}
		}

		_in_failsafe = true;
	}
}

void MulticopterPositionControl::reset_setpoint_to_nan(vehicle_local_position_setpoint_s &setpoint)
{
	setpoint.x = setpoint.y = setpoint.z = NAN;
	setpoint.vx = setpoint.vy = setpoint.vz = NAN;
	setpoint.yaw = setpoint.yawspeed = NAN;
	setpoint.acceleration[0] = setpoint.acceleration[1] = setpoint.acceleration[2] = NAN;
	setpoint.thrust[0] = setpoint.thrust[1] = setpoint.thrust[2] = NAN;
}

void MulticopterPositionControl::check_failure(bool task_failure, uint8_t nav_state)
{
	if (!task_failure) {
		// we want to be in this mode, reset the failure count
		_task_failure_count = 0;

	} else if (_task_failure_count > NUM_FAILURE_TRIES) {
		// tell commander to switch mode
		PX4_WARN("Previous flight task failed, switching to mode %d", nav_state);
		send_vehicle_cmd_do(nav_state);
		_task_failure_count = 0; // avoid immediate resending of a vehicle command in the next iteration
	}
}

void MulticopterPositionControl::send_vehicle_cmd_do(uint8_t nav_state)
{
	vehicle_command_s command{};
	command.timestamp = hrt_absolute_time();
	command.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
	command.param1 = (float)1; // base mode
	command.param3 = (float)0; // sub mode
	command.target_system = 1;
	command.target_component = 1;
	command.source_system = 1;
	command.source_component = 1;
	command.confirmation = false;
	command.from_external = false;

	// set the main mode
	switch (nav_state) {
	case vehicle_status_s::NAVIGATION_STATE_STAB:
		command.param2 = (float)PX4_CUSTOM_MAIN_MODE_STABILIZED;
		break;

	case vehicle_status_s::NAVIGATION_STATE_ALTCTL:
		command.param2 = (float)PX4_CUSTOM_MAIN_MODE_ALTCTL;
		break;

	case vehicle_status_s::NAVIGATION_STATE_AUTO_LOITER:
		command.param2 = (float)PX4_CUSTOM_MAIN_MODE_AUTO;
		command.param3 = (float)PX4_CUSTOM_SUB_MODE_AUTO_LOITER;
		break;

	default: //vehicle_status_s::NAVIGATION_STATE_POSCTL
		command.param2 = (float)PX4_CUSTOM_MAIN_MODE_POSCTL;
		break;
	}

	// publish the vehicle command
	_pub_vehicle_command.publish(command);
}

int MulticopterPositionControl::task_spawn(int argc, char *argv[])
{
	bool vtol = false;

	if (argc > 1) {
		if (strcmp(argv[1], "vtol") == 0) {
			vtol = true;
		}
	}

	MulticopterPositionControl *instance = new MulticopterPositionControl(vtol);

	if (instance) {
		_object.store(instance);
		_task_id = task_id_is_work_queue;

		if (instance->init()) {
			return PX4_OK;
		}

	} else {
		PX4_ERR("alloc failed");
	}

	delete instance;
	_object.store(nullptr);
	_task_id = -1;

	return PX4_ERROR;
}

int MulticopterPositionControl::custom_command(int argc, char *argv[])
{
	return print_usage("unknown command");
}

int MulticopterPositionControl::print_usage(const char *reason)
{
	if (reason) {
		PX4_WARN("%s\n", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### Description
The controller has two loops: a P loop for position error and a PID loop for velocity error.
Output of the velocity controller is thrust vector that is split to thrust direction
(i.e. rotation matrix for multicopter orientation) and thrust scalar (i.e. multicopter thrust itself).

The controller doesn't use Euler angles for its work, they are generated only for more human-friendly control and
logging.
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("mc_pos_control", "controller");
	PRINT_MODULE_USAGE_COMMAND("start");
	PRINT_MODULE_USAGE_ARG("vtol", "VTOL mode", true);
	PRINT_MODULE_USAGE_DEFAULT_COMMANDS();

	return 0;
}

extern "C" __EXPORT int mc_pos_control_main(int argc, char *argv[])
{
	return MulticopterPositionControl::main(argc, argv);
}


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

<title>Uses of Package ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter</title>
<meta name="date" content="2017-01-25">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter

Packages that use ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter

Package
Description

ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter

Classes in ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter used by ee.ria.dhx.server.types.ee.riik.schemas.dhl.rkel_letter

Class and Description

AccessRightsType

 Java class for AccessRightsType complex type.

Addressee

 Java class for Addressee complex type.

Compilator

 Java class for Compilator complex type.

Enclosure

 Java class for Enclosure complex type.

IntellectualPropertyRightsType

 Java class for IntellectualPropertyRightsType complex type.

Letter

 Java class for Letter complex type.

LetterType

 Java class for LetterType complex type.

OrganisationType

 Java class for OrganisationType complex type.

PartyType

 Java class for PartyType complex type.

PersonType

 Java class for PersonType complex type.

Signature

 Java class for Signature complex type.

SignatureDataType

 Java class for SignatureDataType complex type.

SignatureType

 Java class for SignatureType complex type.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-firefox-launcher'),
      require('karma-firefox-launcher'),
      require('./jasmine-seed-reporter')
    ],
    client: {
      jasmine: {
        // seed: '56124',  // Specify if you need to re-run the same seed
      },
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [

    ],
    preprocessors: {

    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul', 'jasmine-seed']
      : ['progress', 'kjhtml', 'jasmine-seed'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Firefox'],
    singleRun: false,
    browserNoActivityTimeout: 30000
  });
};


text:
<?xml version="1.0"?>

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>

    <title>Batik Glossary</title>

      <title>Bridge</title>

        A bridge is a class that handles an element in an SVG document, either
        by constructing a corresponding node in the GVT tree, or by informing
        the user agent that it has encountered the element.

      <title>GVT (Graphic Vector Toolkit)</title>

        GVT (Graphic Vector Toolkit) is an object oriented framework that
        describes complex 2D graphics in terms of a tree of Java objects. GVT
        is used in Batik to represent how SVG images are to be rendered.

      <title>SVG DOM</title>

        The SVG DOM (Document Object Model) defines the API that programming
        languages use to interact with SVG documents. There are different "bindings"
        of the DOM API for different languages. For example, there is an ECMAScript
        binding that allows SVG scripts to access or modify SVG documents, for example
        in reaction to events. There is also a Java binding which allows Java
        programs to dynamically interact with SVG documents. The Java binding
        and the ECMAScript binding are both available in Batik.

      <title>SVG Generator</title>

        The SVG Generator is a module of Batik that allows Java applications
        to create SVG content without needing specific knowledge of SVG. Applications
        doing graphics in Java use an API, embodied by the
        Graphics2D class, to do all their rendering operations.
        They use the same code, but different implementations of that API, to
        render to various outputs such as a screen or a printer. The SVG
        Generator is another implementation of that API that, instead of
        drawing to a screen or a printer, generates SVG content. Because it
        implements the same API as for printing or drawing to the screen, the
        same code that does screen rendering and printing can be used with the
        generator to generate SVG content.

</document>


text:
from rest_framework.filters import (
    FilterSet
)
from csacompendium.csa_practice.models import CsaTheme

class CsaThemeListFilter(FilterSet):
    """
    Filter query list from CSA theme database
    """
    class Meta:
        model = CsaTheme
        fields = {
            'csa_theme': ['iexact', 'icontains'],
        }
        order_by = ['csa_theme']


text:
"use strict";

// TODO: This is a temp solution that will
// be eventually replaced by the restrictions table.

const URI = require('hyperswitch').URI;
const mwUtil = require('./mwUtil');
const P = require('bluebird');

function redirect(content, location, options) {
    const vary = content.headers.vary ? `${content.headers.vary}, origin` : 'origin';
    return {
        status: 302,
        headers: Object.assign(content.headers, {
            location,
            'cache-control': options.redirect_cache_control || 'no-cache',
            vary
        }),
        body: content.body
    };
}

module.exports = (hyper, req, next, options, specInfo) => {
    const rp = req.params;
    const titleParamName = options.title ? options.title : 'title';
    const checkURIParts = [rp.domain, 'sys', 'page_revisions', 'page', rp[titleParamName]];
    if (rp.revision) {
        checkURIParts.push(`${rp.revision}`);
    }

    return hyper.get({ uri: new URI(checkURIParts) })
    .then((res) => {
        const revision = res.body.items[0];

        if (revision.redirect
                && req.query.redirect !== false
                && !mwUtil.isNoCacheRequest(req)) {
            const htmlPath = [rp.domain, 'sys', 'parsoid', 'html', rp[titleParamName]];
            if (rp.revision) {
                htmlPath.push(`${rp.revision}`);
                if (rp.tid) {
                    htmlPath.push(`${rp.tid}`);
                }
            }
            return hyper.get({
                uri: new URI(htmlPath),
            })
            .then((html) => {
                const redirectTitle = mwUtil.extractRedirect(html.body)
                    // Redirect detected while saving new HTML.
                    || html.headers.location;
                if (redirectTitle) {
                    const newParams = Object.assign({}, rp);
                    newParams[titleParamName] = redirectTitle;
                    const location = mwUtil.createRelativeTitleRedirect(specInfo.path, req, {
                        newReqParams: newParams,
                        titleParamName,
                        dropPathAfterTitle: true,
                    });

                    let contentPromise;
                    if (options.attach_body_to_redirect) {
                        if (specInfo.path.indexOf('html') !== -1) {
                            contentPromise = P.resolve(html);
                        } else {
                            contentPromise = next(hyper, req);
                        }
                    } else {
                        contentPromise = P.resolve({
                            headers: {
                                etag: html.headers.etag
                            }
                        });
                    }

                    return contentPromise.then(content => redirect(content, location, options));
                } else {
                    return next(hyper, req);
                }
            });
        }
        return next(hyper, req)
        .then((res) => {
            if (res.status === 302
                    && (req.query.redirect === false || mwUtil.isNoCacheRequest(req))) {
                res.status = 200;
                delete res.headers.location;
            }
            return res;
        });
    });
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>LIIS - Laboratory Information Indexing System: Culture_model Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

LIIS - Laboratory Information Indexing System
    0.10.2

Main Page

Related Pages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Files Functions Variables Pages

Public Member Functions |
Private Member Functions |
List of all members

Culture_model Class Reference

Inheritance diagram for Culture_model:

  <map id="Culture_model_map" name="Culture_model_map">
</map>

Public Member Functions

 	__construct ()

 	createRow ($data)

 	createRow  More...

 	create_culture ($data)

 	create_culture  More...

 	create_tax ($data)

 	create_tax  More...

 	create_vial ($data)

 	create_vial  More...

 	create_dnarna ($data)

 	create_dnarna  More...

 	import ($array, $table= 'CULTURE')

 	import  More...

 	search ($keywords, $fields, $table= 'CULTURE', $key= 'CULT_ID', $type= 'like', $custom=NULL)

 	search  More...

 	selectOne ($id)

 	selectOne  More...

 	get_culture ($id)

 	get_culture  More...

 	get_tax ($id)

 	get_tax  More...

 	get_vials ($id)

 	get_vials  More...

 	get_dnarna ($id)

 	get_vials  More...

 	editRow ($id, $data)

 	editRow  More...

 	update_culture ($id, $fields)

 	update_culture  More...

 	update_tax ($id, $fields)

 	update_tax  More...

 	update_vial ($id, $fields)

 	update_vial  More...

 	update_dnarna ($id, $fields)

 	update_dnarna  More...

 	delete_culture ($id)

 	delete_culture  More...

 	delete_tax ($id)

 	delete_tax  More...

 	delete_dnarna ($id)

 	delete_dnarna  More...

 	delete_vial ($id)

 	delete_vial  More...

Private Member Functions

 	select ($id=NULL, $table= 'CULTURE', $key= 'CULT_ID', $custom=NULL)

 	select  More...

 	selectLike ($conditions, $table= 'CULTURE', $key= 'CULT_ID', $custom=NULL, $type= 'or')

 	selectLike  More...

 	selectRange ($range, $field= 'CULT_DATE', $table= 'CULTURE', $key= 'CULT_ID', $custom=NULL)

 	selectRange  More...

 	update ($id, $data, $table= 'CULTURE', $key= 'CULT_ID', $custom=NULL)

 	update  More...

 	create ($data, $table= 'CULTURE')

 	create  More...

 	create_batch ($data, $table= 'CULTURE')

 	create_batch  More...

 	delete ($id, $table= 'CULTURE', $key= 'CULT_ID')

 	delete  More...

Constructor & Destructor Documentation

          Culture_model::__construct
          (
          )

Member Function Documentation

          Culture_model::create
          (

          $data,

          $table = 'CULTURE'

          )

private

create

Create a record within the table specified fields are passed through the associative array: array( field => value, field => value, ...)

private

Parameters

data	array associative array of field => value pairs used to create the record

table	string the table to create the record in

Returns

if successful can return the ID of the record created (if not available, then TRUE), false if not.

          Culture_model::create_batch
          (

          $data,

          $table = 'CULTURE'

          )

private

create_batch

Create multiple records within the table specified fields are passed through the associative data array: array( array(field => value, field => value, ...), array(...), ...)

private

Parameters

data	array associative array of field => value pairs used to create the record

table	string table which to create the records in

Returns

Returns true successful, false if not.

          Culture_model::create_culture
          (

          $data)

create_culture

Create a record in the culture table. Requires an associative array arranged as: array(field => value, field => value, ...) See database schema for valid field names and types

public

Parameters

data	array an associative array holding the field names and values of the data to insert.

Returns

Returns the record ID if successful, false if not.

          Culture_model::create_dnarna
          (

          $data)

create_dnarna

Create a record in the dnarna table. Requires an associative array arranged as: array(field => value, field => value, ...) See database schema for valid field names and types

public

Parameters

data	array an associative array holding the field name and values of the data to insert.

Returns

Returns true if successful, false if not.

          Culture_model::create_tax
          (

          $data)

create_tax

Create a record in the taxomomy table. Requires an associative array arranged as: array(field => value, field => value, ...) See database schema for valid field names and types

public

Parameters

data	array an associative array holding the field names and values of the data to insert.

Returns

Returns the record ID if successful, false if not.

          Culture_model::create_vial
          (

          $data)

create_vial

Create a record in the vial table. Requires an associative array arranged as: array(field => value, field => value, ...) See database schema for valid field names and types

public

Parameters

data	array an associative array holding the field names and values of the data to insert.

Returns

Returns true if successful, false if not.

          Culture_model::createRow
          (

          $data)

createRow

Required an associative array arranged as: array(table => array(field => value, field => value, ...), table => array(...), ...) Valid tables are: CULTURE, TAXONOMY, DNARNA, VIAL See database schema for valid fields.

public

Parameters

data	array The array that holds the record data.

Returns

1 if succesful, negative number if not. -1 taxonomy fail, -2 culture fail, -3 dnarna fail, -4 vial fail.

          Culture_model::delete
          (

          $id,

          $table = 'CULTURE',

          $key = 'CULT_ID'

          )

private

delete

delete a record from the table specified

private

Parameters

id	string the id of the record to be deleted

table	string table which to delete from

key	string the field which the id belongs to

Returns

Returns true if successful, false if not.

          Culture_model::delete_culture
          (

          $id)

delete_culture

Deletes a culture record and the records associated with it (cascading delete in mysql)

public

Parameters

id	int (string) the ID of the culture you want to delete

Returns

Returns true if successful, false if not.

          Culture_model::delete_dnarna
          (

          $id)

delete_dnarna

Deletes a dnarna record

public

Parameters

id	int (string) the ID of the dnarna record you want to delete

Returns

Returns true if successful, false if not.

          Culture_model::delete_tax
          (

          $id)

delete_tax

Deletes a taxonomy record

public

Parameters

id	int (string) the ID of the taxonomy you want to delete

Returns

Returns true if successful, false if not.

          Culture_model::delete_vial
          (

          $id)

delete_vial

Deletes a vial record

public

Parameters

id	int (string) the ID of the vial you want to delete

Returns

Returns true if successful, false if not.

          Culture_model::editRow
          (

          $id,

          $data

          )

editRow

Updates the row id specified with the data that is passed. The data should be an associative array arranged like: array(table => array(field => name, field => name, ...), table => array(...), ...) valid tables are: CULTURE, TAXONOMY, VIAL, DNARNA See database schema for valid field names and types.

public

Parameters

id	int (string) the ID of the culture record you want to edit

data	array an array holding the data you want to update the record with

Returns

an array of booleans, where true entries are successful updates and false entries are not.

          Culture_model::get_culture
          (

          $id)

get_culture

Selects and returns the a culture record without any resolved foreign keys

public

Parameters

id	int (string) the ID of the culture to select

Returns

Returns an array of results if successful, a message string if not.

          Culture_model::get_dnarna
          (

          $id)

get_vials

Selects and returns an array of all the dna/rna associated with the culture id passed

public

Parameters

id	int (string) the ID of the culture record you want to resolve the dnarna from

Returns

Returns an array of results if successful, a message string if not.

          Culture_model::get_tax
          (

          $id)

get_tax

Selects and returns the taxonomy record associated with the culture id passed

public

Parameters

id	int (string) the ID of the culture record you want to resolve the taxonomy from.

Returns

Returns an array of results if successful, false if not.

          Culture_model::get_vials
          (

          $id)

get_vials

Selects and returns an array of all the vials associated with the culture id passed

public

Parameters

id	int (string) the ID of the culture record you want to resolve the vials from

Returns

Returns an array of results if successful, a message string if not.

          Culture_model::import
          (

          $array,

          $table = 'CULTURE'

          )

import

Create multiple culture records. Requires a multidimensional associative array arranged as: array( array(field => value, field => value, ...), array(...), ...) See database schema for valid field names and types

public

Parameters

data	array an associative array holding the field name and values of the data to insert.

table	string the primary table to import into

Returns

Returns true if successful, false if not.

          Culture_model::search
          (

          $keywords,

          $fields,

          $table = 'CULTURE',

          $key = 'CULT_ID',

          $type = 'like',

          $custom = NULL

          )

search

Searches the specified table for the keywords against the fields. Returns the fields specified under the keys parameter. Has two types, 'like' and 'range', where like is a basic search against fields and range is a search between two points (like dates) Can be passed a custom string that will execute any custom where clauses you may want.

public

Parameters

keywords	array or string an array or comma delimited string holding the keywords to search for. eg. array('1', 'two') or '1, two'

fields	array or string an array or comma delimited string holding the fields to search against. eg. array('field1', 'field2') or 'field1, field2'

table	string the name of the table you want to search

key	string a comma delimited string that specifies which fields to return. eg. 'field1, field2'

type	string which type of search to perform. valid types are 'like' and 'range'

custom	string A custom where clause to add the the query. Must be a valid MySQL comparison. eg. 'field1 is NULL'

Returns

Returns the array of search results if successful, false if not.

          Culture_model::select
          (

          $id = NULL,

          $table = 'CULTURE',

          $key = 'CULT_ID',

          $custom = NULL

          )

private

select

selects records based on the id, but can be used to select other fields as well

private

Parameters

id	string the value of the field you want to select

table	string the table you wish to select from

key	string the field you wish to return (select)

custom	string a custom where clause if needed

Returns

Returns an array of results if successful , false if not.

          Culture_model::selectLike
          (

          $conditions,

          $table = 'CULTURE',

          $key = 'CULT_ID',

          $custom = NULL,

          $type = 'or'

          )

private

selectLike

selects records based on keywords, can be set to use OR or AND clauses $conditions is an associative array containing field => value pairs constructed like 'Field' => 'word' Field IS LIKE word

private

Parameters

conditions	array array of field => value pairs

table	string the table you wish to select from

key	string the field you wish to return (select)

custom	string a custom where clause if needed

type	string either 'or' or 'and' to select different clauses

Returns

Returns an array of results if successful , false if not.

          Culture_model::selectOne
          (

          $id)

selectOne

Selects and returns one fully resolved culture record (includes all lookup tables and other related records)

public

Parameters

id	int (string) the ID of the culture to select

Returns

Returns an array of results. (Can be elements will be false if record does not exist)

          Culture_model::selectRange
          (

          $range,

          $field = 'CULT_DATE',

          $table = 'CULTURE',

          $key = 'CULT_ID',

          $custom = NULL

          )

private

selectRange

For dates and other values selects records between two points $conditions is an associative array containing two specific keys: 'before' and 'after' constructed like 'before' => '1', 'after' => '2' where field > 1 where field < 2

private

Parameters

range	array array of two elements, 'before' and 'after'

field	string the field you wish to select the range from

table	string the table you wish to select from

key	string the field you wish to return (select)

custom	string a custom where clause if needed

Returns

Returns an array of results if successful, false if not.

          Culture_model::update
          (

          $id,

          $data,

          $table = 'CULTURE',

          $key = 'CULT_ID',

          $custom = NULL

          )

private

update

updates the record specified with the fields given within $data $data should be constructed like: array(field => value, field => value, ...)

private

Parameters

id	string the id of the record you with to update

data	string the assocative array holding field => value pairs

table	string the table which holds the record to be updated

key	string the field which the id matches

custom	string a custom where clause if needed

Returns

Returns true if successful, false if not.

          Culture_model::update_culture
          (

          $id,

          $fields

          )

update_culture

Updates a culture record with the fields given Fields to update should be specified in the fields array: array( field => value, field => value, ...)

public

Parameters

id	int (string) the id of the culture you want to update.

fields	array associative array holding the field => value pairs to update the record with

Returns

Returns true if successful, false if not.

          Culture_model::update_dnarna
          (

          $id,

          $fields

          )

update_dnarna

Updates a single dnarna record with the fields passed Fields to update should be specified in the fields array: array( field => value, field => value, ...)

public

Parameters

id	int (string) the ID of the dnarna record you want to update

fields	array associative array holding the field => value pairs to update the record with

Returns

Returns true if successful, false if not.

          Culture_model::update_tax
          (

          $id,

          $fields

          )

update_tax

Updates a taxonomy record associated with the culture ID passed Fields to update should be specified in the fields array: array( field => value, field => value, ...)

public

Parameters

id	int (string) the ID of the culture record you want update the taxonomy for

fields	array associative array holding the field => value pairs to update the record with

Returns

Returns true if successful, false if not.

          Culture_model::update_vial
          (

          $id,

          $fields

          )

update_vial

Updates a single vial record with the fields passed Fields to update should be specified in the fields array: array( field => value, field => value, ...)

public

Parameters

id	int (string) the ID of the vial you want to update

fields	array associative array holding the field => value pairs to update the record with

Returns

Returns true if successful, false if not.

The documentation for this class was generated from the following file:

application/models/culture_model.php

<address class="footer">
Generated on Mon Mar 17 2014 19:50:05 for LIIS - Laboratory Information Indexing System by

 1.8.4
</address>


text:
gopath=/usr/bin/go
filepath=$(cd "$(dirname "$0")"; pwd)
$gopath build ${filepath}"/server/LiveGoServer.go"
./LiveGoServer &