text:
var Config = require('getconfig');
exports[Config.getconfig.env === 'dev' ? 'development' : Config.getconfig.env] = Config.db;

redpajama_set_name: RedPajamaGithub


text:
export const CHANNELS = 'CHANNELS';
export const FAVORITES = 'FAVORITES';

export function setHomeChannels(channel) {
  return {
    type: CHANNELS,
    home: channel
  };
}

export function setFavorites(favorites) {
  return {
    type: FAVORITES,
    favorites
  };
}


text:
ActiveRecord::Schema.define(:version => 1) do
  create_table :nodes, :force => true do |t|
    t.string :name
    t.string :breadcrumbs

    # nested_set
    t.integer :parent_id
    t.integer :lft
    t.integer :rgt
  end

  create_table :locations, :force => true do |t|
    t.string :name
    t.string :location_string

    # nested_set
    t.integer :parent_id
    t.integer :lft
    t.integer :rgt
  end

  create_table :soldiers, :force => true do |t|
    t.string :name
    t.string :chain_o_command

    # nested_set
    t.integer :parent_id
    t.integer :lft
    t.integer :rgt
  end

  create_table :web_pages, :force => true do |t|
    t.string :title
    t.string :slug
    t.string :url
    t.string :breadcrumbs

    # nested_set
    t.integer :parent_id
    t.integer :lft
    t.integer :rgt
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml;

using AlteryxRecordInfoNet;

using OmniBus.Framework.Attributes;
using OmniBus.Framework.Interfaces;

namespace OmniBus.Framework.TypeConverters
{
    /// <summary>
    ///     Provides a type converter to allow a user to select from a set of incoming fields.
    ///     Uses an <see cref="InputPropertyNameAttribute" /> to get list of fields and allows for type filtering.
    /// </summary>
    public class InputFieldTypeConverter : StringConverter
    {
        /// <summary>
        ///     Returns whether this object supports a standard set of values that can be picked from a list, using the
        ///     specified context.
        /// </summary>
        /// <returns>
        ///     true if <see cref="M:System.ComponentModel.TypeConverter.GetStandardValues" /> should be called to find a
        ///     common set of values the object supports; otherwise, false.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context. </param>
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;

        /// <summary>
        ///     Returns a collection of standard values for the data type this type converter is designed for when provided
        ///     with a format context.
        /// </summary>
        /// <returns>
        ///     A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection" /> that holds a standard set of
        ///     valid values, or null if the data type does not support a standard set of values.
        /// </returns>
        /// <param name="context">
        ///     An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context
        ///     that can be used to extract additional information about the environment from which this converter is invoked. This
        ///     parameter or properties of this parameter can be null.
        /// </param>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            if (context.PropertyDescriptor == null)
            {
                return base.GetStandardValues(context);
            }

            var attrib = context.PropertyDescriptor.Attributes.OfType<InputPropertyNameAttribute>().FirstOrDefault();
            if (attrib == null)
            {
                return base.GetStandardValues(context);
            }

            var instance = context.Instance as IConfigWithIncomingConnection;
            if (instance == null)
            {
                return base.GetStandardValues(context);
            }

            var names = GetFieldList(
                instance.IncomingMetaInfo,
                attrib.EngineType,
                attrib.InputConnectionName,
                attrib.FieldTypes);
            return new StandardValuesCollection(names);
        }

        private static ICollection GetFieldList(
            XmlElement[] incomingMetaData,
            Type engineType,
            string connectionName,
            IList<FieldType> fieldTypes)
        {
            var input =
                engineType.GetProperties<IIncomingConnectionInterface>()
                    .Select((kvp, i) => new { kvp.Key, i })
                    .FirstOrDefault(o => o.Key == connectionName);

            if (input == null || incomingMetaData == null || incomingMetaData.Length <= input.i)
            {
                return null;
            }

            var sourceElement = incomingMetaData[input.i]?.SelectNodes("RecordInfo/Field");
            if (sourceElement == null)
            {
                return null;
            }

            var names = new List<string>();
            foreach (XmlNode field in sourceElement)
            {
                var name = field.SelectSingleNode("@name")?.Value;
                var fieldTypeName = field.SelectSingleNode("@type")?.Value;
                if (name != null && fieldTypeName != null
                    && Enum.TryParse("E_FT_" + fieldTypeName, out FieldType fieldType) && fieldTypes.Contains(fieldType))
                {
                    names.Add(name);
                }
            }

            return names;
        }
    }
}


text:
#ifndef __sopmq__util__
#define __sopmq__util__

#include "uint128.h"

#include <string>
#include <boost/uuid/uuid.hpp>
#include <boost/multiprecision/cpp_int.hpp>

namespace sopmq {
    namespace shared {

        ///
        /// General utility functions
        ///
        class util
        {
        public:
            ///
            /// Takes a string of bytes and returns a human readable hex encoding
            ///
            static std::string hex_encode(const unsigned char* input, int inputSize);

            ///
            /// Generates a string of random bytes
            /// \param count The number of random bytes to generate
            ///
            static std::string random_bytes(int count);

            ///
            /// Generates a random uuid
            ///
            static boost::uuids::uuid random_uuid();

            ///
            /// Returns the murmur hash of the given value
            ///
            static uint128 murmur_hash3(const void * key, int len);

            ///
            /// Returns the murmur hash of the given value
            ///
            static uint128 murmur_hash3(const std::string& value);

            ///
            /// Extracts the raw bytes from a uuid. The string must be freed by the caller.
            /// Useful for inserting UUIDs into network messages
            ///
            static std::string* uuid_to_bytes(const boost::uuids::uuid& id);

            ///
            /// Constructs a uuid from a set of bytes
            ///
            static boost::uuids::uuid uuid_from_bytes(const std::string& bytes);

            ///
            /// Computes the sha256 of the given data and returns a human readable hex string
            /// result
            ///
            static std::string sha256_hex_string(const std::string& data);

        private:
            util();
            ~util();
        };
    }
}

#endif /* defined(__sopmq__util__) */


text:
package org.glassfish.jaxb.runtime.v2.runtime.reflect;

import org.glassfish.jaxb.core.v2.model.nav.Navigator;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utils class.
 *
 * WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
 *
 * Has *package private* access to avoid inappropriate usage.
 */
@SuppressWarnings({"unchecked"})
final class Utils {

    private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());

    /**
     * static ReflectionNavigator field to avoid usage of reflection every time we use it.
     */
    static final Navigator<Type, Class, Field, Method> REFLECTION_NAVIGATOR;

    static { // we statically initializing REFLECTION_NAVIGATOR property
        try {
            final Class<?> refNav = Class.forName("org.glassfish.jaxb.core.v2.model.nav.ReflectionNavigator");

            // requires accessClassInPackage privilege
            final Method getInstance = AccessController.doPrivileged(
                    new PrivilegedAction<>() {
                        @Override
                        public Method run() {
                            try {
                                Method getInstance = refNav.getDeclaredMethod("getInstance");
                                getInstance.setAccessible(true);
                                return getInstance;
                            } catch (NoSuchMethodException e) {
                                throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
                            }
                        }
                    }
            );

            //noinspection unchecked
            REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Can't find ReflectionNavigator class");
        } catch (InvocationTargetException e) {
            throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
        } catch (SecurityException e) {
            LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);
            throw e;
        }
    }

    /**
     * private constructor to avoid util class instantiating
     */
    private Utils() {
    }
}


text:
package aspguidp.controller.output.element;

import aspguidp.service.data.DataServicePool;
import aspguidp.service.data.manager.ValueDataManager;
import javafx.scene.control.Label;

/**
 * Base controller class for an value output component. This class implements functionality which is used by all value
 * output components of the application.
 */
public abstract class ValueOutputController extends OutputElementController {
    /**
     * Bind the text of the given label to value of the value data manager of the given data service pool.
     *
     * @param dataServicePool service pool which is used to access the value data manager which holds the value
     * @param outputLabel     label of which the text is bound to the value of the value data manager
     */
    protected void initializeValueLabel(DataServicePool dataServicePool, Label outputLabel) {
        // update label value on manager change
        ValueDataManager dataManager = dataServicePool.getValueDataManager();
        dataManager.getValue().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) outputLabel.setText("");
            else outputLabel.setText(newValue.getDisplayRepresentation());
        });
    }
}


text:
require 'mustermann/pattern'
require 'forwardable'

module Mustermann
  # Superclass for patterns that internally compile to a regular expression.
  # @see Mustermann::Pattern
  # @abstract
  class RegexpBased < Pattern
    # @return [Regexp] regular expression equivalent to the pattern.
    attr_reader :regexp
    alias_method :to_regexp, :regexp

    # @param (see Mustermann::Pattern#initialize)
    # @return (see Mustermann::Pattern#initialize)
    # @see (see Mustermann::Pattern#initialize)
    def initialize(string, **options)
      super
      regexp       = compile(**options)
      @peek_regexp = /\A#{regexp}/
      @regexp      = /\A#{regexp}\Z/
    end

    # @param (see Mustermann::Pattern#peek_size)
    # @return (see Mustermann::Pattern#peek_size)
    # @see (see Mustermann::Pattern#peek_size)
    def peek_size(string)
      return unless match = peek_match(string)
      match.to_s.size
    end

    # @param (see Mustermann::Pattern#peek_match)
    # @return (see Mustermann::Pattern#peek_match)
    # @see (see Mustermann::Pattern#peek_match)
    def peek_match(string)
      @peek_regexp.match(string)
    end

    extend Forwardable
    def_delegators :regexp, :===, :=~, :match, :names, :named_captures

    def compile(**options)
      raise NotImplementedError, 'subclass responsibility'
    end

    private :compile
  end
end


text:
module SeccompTools
end

require 'seccomp-tools/asm/asm'
require 'seccomp-tools/disasm/disasm'
require 'seccomp-tools/dumper'
require 'seccomp-tools/emulator'
require 'seccomp-tools/version'


text:
package com.github.justcoke.example.helloworld.resources;

import static org.assertj.core.api.Assertions.assertThat;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import com.github.justcoke.example.helloworld.HelloWorldApplication;
import com.github.justcoke.example.helloworld.HelloWorldConfiguration;

import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;

public class ApiIntegrationTest {
	@Rule
	public final DropwizardAppRule<HelloWorldConfiguration> RULE = new DropwizardAppRule<>(HelloWorldApplication.class,
			ResourceHelpers.resourceFilePath("integration-test.yml"));

	@Test
	@Ignore
	// FIXME
	public void setAndGetNode() {
		final String bodyText = "Hello world";

		Client client = ClientBuilder.newClient();

		Response saveResponse = client
				.target(String.format("http://localhost:%d/api/jcr/var?name=Test", RULE.getLocalPort())).request()
				.put(Entity.text(bodyText));

		Response getResponse = client
				.target(String.format("http://localhost:%d/api/jcr/var?name=Test", RULE.getLocalPort())).request()
				.get();

		String getBody = getResponse.readEntity(String.class);

		assertThat(saveResponse.getStatus()).isEqualTo(200);
		assertThat(getResponse.getStatus()).isEqualTo(200);
		assertThat(getBody).isEqualToIgnoringCase(bodyText);
	}
}


text:
using System.IO;
using Xunit;

namespace System.Net.WebSockets.Tests
{
    public sealed partial class WebSocketTests
    {
        [Fact]
        public static void DefaultKeepAliveInterval_ValidValue()
        {
            Assert.True(WebSocket.DefaultKeepAliveInterval > TimeSpan.Zero);
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(0)]
        public static void CreateClientBuffer_InvalidSendValues(int size)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => WebSocket.CreateClientBuffer(256, size));
        }

        [Theory]
        [InlineData(16)]
        [InlineData(64 * 1024)]
        public static void CreateClientBuffer_ValidSendValues(int size)
        {
            ArraySegment<byte> buffer = WebSocket.CreateClientBuffer(256, size);
            Assert.InRange(buffer.Count, size, int.MaxValue);
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(0)]
        public static void CreateClientBuffer_InvalidReceiveValues(int size)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => WebSocket.CreateClientBuffer(size, 16));
        }

        [Theory]
        [InlineData(256)]
        [InlineData(64 * 1024)]
        public static void CreateClientBuffer_ValidReceiveValues(int size)
        {
            ArraySegment<byte> buffer = WebSocket.CreateClientBuffer(size, 16);
            Assert.InRange(buffer.Count, size, int.MaxValue);
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(0)]
        public static void CreateServerBuffer_InvalidReceiveValues(int size)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => WebSocket.CreateServerBuffer(size));
        }

        [Theory]
        [InlineData(256)]
        [InlineData(64 * 1024)]
        public static void CreateServerBuffer_ValidReceiveValues(int size)
        {
            ArraySegment<byte> buffer = WebSocket.CreateServerBuffer(size);
            Assert.InRange(buffer.Count, size, int.MaxValue);
        }

        [Fact]
        public static void CreateClientWebSocket_InvalidArguments_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => WebSocket.CreateClientWebSocket(
                null, "subProtocol", 16480, 9856, TimeSpan.FromSeconds(30), false, WebSocket.CreateClientBuffer(16480, 9856)));

            Assert.Throws<ArgumentException>(() => WebSocket.CreateClientWebSocket(
                new MemoryStream(), "    ", 16480, 9856, TimeSpan.FromSeconds(30), false, WebSocket.CreateClientBuffer(16480, 9856)));
            Assert.Throws<ArgumentException>(() => WebSocket.CreateClientWebSocket(
                new MemoryStream(), "\xFF", 16480, 9856, TimeSpan.FromSeconds(30), false, WebSocket.CreateClientBuffer(16480, 9856)));

            Assert.Throws<ArgumentOutOfRangeException>(() => WebSocket.CreateClientWebSocket(
                new MemoryStream(), "subProtocol", 0, 9856, TimeSpan.FromSeconds(30), false, WebSocket.CreateClientBuffer(16480, 9856)));
            Assert.Throws<ArgumentOutOfRangeException>(() => WebSocket.CreateClientWebSocket(
                new MemoryStream(), "subProtocol", 16480, 0, TimeSpan.FromSeconds(30), false, WebSocket.CreateClientBuffer(16480, 9856)));
            Assert.Throws<ArgumentOutOfRangeException>(() => WebSocket.CreateClientWebSocket(
                new MemoryStream(), "subProtocol", 16480, 9856, TimeSpan.FromSeconds(-2), false, WebSocket.CreateClientBuffer(16480, 9856)));
        }

        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
        [Fact]
        public static void RegisterPrefixes_Unsupported()
        {
            Assert.Throws<PlatformNotSupportedException>(() => WebSocket.RegisterPrefixes());
        }

#if netcoreapp
        [Fact]
        public static void IsApplicationTargeting45_AlwaysTrue()
        {
#pragma warning disable 0618 // Obsolete API
            Assert.True(WebSocket.IsApplicationTargeting45());
#pragma warning restore 0618
        }
#endif // netcoreapp

        [Theory]
        [InlineData(WebSocketState.None)]
        [InlineData(WebSocketState.Connecting)]
        [InlineData(WebSocketState.Open)]
        [InlineData(WebSocketState.CloseSent)]
        [InlineData(WebSocketState.CloseReceived)]
        [InlineData((WebSocketState)(-1))]
        [InlineData((WebSocketState)(7))]
        public static void IsStateTerminal_NonTerminalReturnsFalse(WebSocketState state)
        {
            Assert.False(ExposeProtectedWebSocket.IsStateTerminal(state));
        }

        [Theory]
        [InlineData(WebSocketState.Closed)]
        [InlineData(WebSocketState.Aborted)]
        public static void IsStateTerminal_TerminalReturnsTrue(WebSocketState state)
        {
            Assert.True(ExposeProtectedWebSocket.IsStateTerminal(state));
        }

        [Theory]
        [InlineData(WebSocketState.Closed, new WebSocketState[] { })]
        [InlineData(WebSocketState.Closed, new WebSocketState[] { WebSocketState.Open })]
        [InlineData(WebSocketState.Open, new WebSocketState[] { WebSocketState.Aborted, WebSocketState.CloseSent })]
        public static void ThrowOnInvalidState_ThrowsIfNotInValidList(WebSocketState state, WebSocketState[] validStates)
        {
            Assert.Throws<WebSocketException>(() => ExposeProtectedWebSocket.ThrowOnInvalidState(state, validStates));
        }

        [Theory]
        [InlineData(WebSocketState.Open, new WebSocketState[] { WebSocketState.Open })]
        [InlineData(WebSocketState.Open, new WebSocketState[] { WebSocketState.Open, WebSocketState.Aborted, WebSocketState.Closed })]
        [InlineData(WebSocketState.Open, new WebSocketState[] { WebSocketState.Aborted, WebSocketState.Open, WebSocketState.Closed })]
        [InlineData(WebSocketState.Open, new WebSocketState[] { WebSocketState.Aborted, WebSocketState.CloseSent, WebSocketState.Open })]
        public static void ThrowOnInvalidState_SuccessIfInList(WebSocketState state, WebSocketState[] validStates)
        {
            ExposeProtectedWebSocket.ThrowOnInvalidState(state, validStates);
        }

        public abstract class ExposeProtectedWebSocket : WebSocket
        {
            public new static bool IsStateTerminal(WebSocketState state) =>
                WebSocket.IsStateTerminal(state);
            public new static void ThrowOnInvalidState(WebSocketState state, params WebSocketState[] validStates) =>
                WebSocket.ThrowOnInvalidState(state, validStates);
        }
    }
}


text:
/**
 * Return a new copy of the polydom stack
 *
 * @private
 * @param {Object}
 * @returns {Object}
 */
function newStack(result) {
    // If a selector is passed in,
    // reset $dom.fn.selector
    if (!!result) {
        $dom.fn.selector = $dom.fn.$ = result;
    }
    // Use a non-looping copy method for increased performance
    return {
        version: $dom.fn.version,
        constructor: $dom.fn.constructor,
        context: $dom.fn.context,
        selector: $dom.fn.selector,
        $: $dom.fn.$,
        module: $dom.fn.module,
        //=require ../methods.js
    };
}


text:
#pragma once

#include <cstdint>
#include <vector>
#include <functional>
#include <utility>

#include "glm/glm.hpp"
#include "msgpack.hpp"

#include "types/linear_node.hpp"
#include "types/traversal_state.hpp"
#include "utils/tostring.hpp"

namespace fr {

struct Mesh;
struct SlimRay;
struct LinkedNode;
struct PrimitiveInfo;
struct HitRecord;

/**
 * The construction implementation is based on the one presented in Physically
 * Based Rendering, Section 4.4, pages 208-227, with some modifications to
 * support stackless traversal. The stackless traversal algorithm is as
 * described in Hapala et al [2011], with modifications for suspension on one
 * worker and resuming on another without a restart.
 */

class BVH {
public:
    /**
     * Constructs a BVH for traversing the given mesh.
     */
    explicit BVH(const Mesh* mesh);

    /**
     * Constructs a BVH for traversing a set of things, where those things
     * are pairs of resource IDs and their bounding boxes.
     */
    explicit BVH(const std::vector<std::pair<uint32_t, BoundingBox>>& things);

    /// MSGPACK ONLY!
    explicit BVH();

    /**
     * Traverses the BVH by testing the given SlimRay against the bounding
     * volumes. If a leaf node is hit, the passed primitive intersector
     * function will be called. Returns the current traversal state when the
     * function exits.
     */
    TraversalState Traverse(const SlimRay& ray, HitRecord* nearest,
     std::function<bool (uint32_t index, const SlimRay& ray, HitRecord* hit, bool* request_suspend)> intersector);

    /**
     * Also traverses the BVH, but resumes traversal where we left off using
     * the given TraversalState packet. Returns the current traversal state
     * when the function exits.
     */
    TraversalState Traverse(TraversalState state, const SlimRay& ray, HitRecord* nearest,
     std::function<bool (uint32_t index, const SlimRay& ray, HitRecord* hit, bool* request_suspend)> intersector, bool resume = true);

    /**
     * Returns the extents of the area contained by the BVH.
     */
    inline BoundingBox Extents() const {
        return _nodes[0].bounds;
    }

    inline uint64_t GetSizeInBytes() const { return _nodes.size() * sizeof(LinearNode); }
    inline float GetSizeInMB() const { return (_nodes.size() * sizeof(LinearNode)) / (1024.0f * 1024.0f); }

    MSGPACK_DEFINE(_nodes);

    TOSTRINGABLEBYPTR(BVH);

private:
    struct BucketInfo {
        uint32_t count;
        BoundingBox bounds;
    };

    static const uint32_t NUM_BUCKETS;

    std::vector<LinearNode> _nodes;

    /**
     * Constructs the BVH from the given initialized build data.
     */
    void Build(std::vector<PrimitiveInfo>& build_data);

    /**
     * Recursively partitions and builds the BVH for the given build data
     * between the start and end indexes. Returns the total nodes created
     * through the passed pointer.
     */
    LinkedNode* RecursiveBuild(std::vector<PrimitiveInfo>& build_data,
     size_t start, size_t end, size_t* total_nodes);

    /**
     * Computes the minimum cost split for the build_data given num_buckets
     * possible candidate splits and the centroid bounding box.
     */
    uint32_t ComputeSAH(std::vector<PrimitiveInfo>& build_data, size_t start,
     size_t end, float min, float max, float surface_area, BoundingBox::Axis axis);

    /**
     * Flattens the linked tree structure into a linear structure with offsets
     * for faster/portable traversal at runtime.
     */
    size_t FlattenTree(LinkedNode* current, size_t parent, size_t* offset);

    /**
     * Recursively deletes a LinkedNode tree structure rooted at node.
     */
    void DeleteLinked(LinkedNode* node);

    /// Special case constructor for building a tree with nothing in it.
    void ZeroThings();

    /// Special case constructor for building a tree with one thing in it.
    void OneThing(uint32_t id, const BoundingBox& bounds);

    /// Returns the index of the sibling of the current node.
    inline size_t Sibling(size_t current) {
        size_t parent = _nodes[current].parent;
        size_t right = _nodes[parent].right;
        return (right == current) ? parent + 1 : right;
    }

    /// The near child is defined to be the left-hand child.
    inline size_t NearChild(size_t current, glm::vec3 direction) {
        float axis_component = AxisComponent(direction, _nodes[current].axis);
        return axis_component < 0.0f ? _nodes[current].right : current + 1;
    }

    /// The far child is defined to be the right-hand child.
    inline size_t FarChild(size_t current, glm::vec3 direction) {
        float axis_component = AxisComponent(direction, _nodes[current].axis);
        return axis_component < 0.0f ? current + 1 : _nodes[current].right;
    }

    /// Performs a quick bounding box check against the given bounds and ray.
    inline bool BoundingHit(const BoundingBox& bounds, const SlimRay& ray,
     glm::vec3 inv_dir, float max) {
        if (!bounds.IsValid()) return false;
        float t = -1.0f;
        return bounds.Intersect(ray, inv_dir, &t) && t < max;
    }
};

std::string ToString(const BVH* bvh, const std::string& indent = "");

} // namespace fr


text:
// <copyright file="Constants.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;

namespace App.Metrics.Reporting.InfluxDB.Client
{
    internal static class Constants
    {
        public static readonly TimeSpan DefaultBackoffPeriod = TimeSpan.FromSeconds(30);
        public static readonly int DefaultFailuresBeforeBackoff = 3;
        public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30);
    }
}


text:
'use strict'

const fs = require('fs')
const util = require('util')
const chmod = util.promisify(fs.chmod)
const unlink = util.promisify(fs.unlink)
const stat = util.promisify(fs.stat)
const move = require('@npmcli/move-file')
const pinflight = require('promise-inflight')

module.exports = moveFile

function moveFile (src, dest) {
  const isWindows = global.__CACACHE_TEST_FAKE_WINDOWS__ ||
    process.platform === 'win32'

  // This isn't quite an fs.rename -- the assumption is that
  // if `dest` already exists, and we get certain errors while
  // trying to move it, we should just not bother.
  //
  // In the case of cache corruption, users will receive an
  // EINTEGRITY error elsewhere, and can remove the offending
  // content their own way.
  //
  // Note that, as the name suggests, this strictly only supports file moves.
  return new Promise((resolve, reject) => {
    fs.link(src, dest, (err) => {
      if (err) {
        if (isWindows && err.code === 'EPERM') {
          // XXX This is a really weird way to handle this situation, as it
          // results in the src file being deleted even though the dest
          // might not exist.  Since we pretty much always write files to
          // deterministic locations based on content hash, this is likely
          // ok (or at worst, just ends in a future cache miss).  But it would
          // be worth investigating at some time in the future if this is
          // really what we want to do here.
          return resolve()
        } else if (err.code === 'EEXIST' || err.code === 'EBUSY') {
          // file already exists, so whatever
          return resolve()
        } else {
          return reject(err)
        }
      } else {
        return resolve()
      }
    })
  })
    .then(() => {
      // content should never change for any reason, so make it read-only
      return Promise.all([
        unlink(src),
        !isWindows && chmod(dest, '0444')
      ])
    })
    .catch(() => {
      return pinflight('cacache-move-file:' + dest, () => {
        return stat(dest).catch((err) => {
          if (err.code !== 'ENOENT') {
            // Something else is wrong here. Bail bail bail
            throw err
          }
          // file doesn't already exist! let's try a rename -> copy fallback
          // only delete if it successfully copies
          return move(src, dest)
        })
      })
    })
}


text:
#import <Foundation/Foundation.h>
#import "OAIObject.h"

/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

#import "OAIFreeStyleProject.h"
@protocol OAIFreeStyleProject;
@class OAIFreeStyleProject;

@protocol OAIListView
@end

@interface OAIListView : OAIObject

@property(nonatomic) NSString* _class;

@property(nonatomic) NSString* _description;

@property(nonatomic) NSArray<OAIFreeStyleProject>* jobs;

@property(nonatomic) NSString* name;

@property(nonatomic) NSString* url;

@end


text:
package io.gravitee.am.reporter.file.exception;

/**
 * @author Eric LELEU (eric.leleu at graviteesource.com)
 * @author GraviteeSource Team
 */
public class FileReporterInitializationException extends RuntimeException {
    public FileReporterInitializationException(String message) {
        super(message);
    }
}


text:
define(["lib-build/tpl!./MainMediaContainerMap",
		"lib-build/tpl!./MainMediaContainerImage",
		"lib-build/tpl!./MainMediaContainerEmbed",
		"lib-build/css!./MainStage",
		"../core/WebApplicationData",
		"dojo/has",
		"esri/arcgis/utils",
		"esri/renderers/UniqueValueRenderer",
		"esri/geometry/Point",
		"esri/geometry/Extent",
		"esri/config",
		"esri/geometry/webMercatorUtils",
		"esri/symbols/SimpleMarkerSymbol",
		//"esri/dijit/PopupMobile",
		"esri/tasks/query",
		"dojo/topic",
		"dojo/on",
		"dojo/aspect",
		"dojo/_base/lang"
	],
	function(
		mainMediaContainerMapTpl,
		mainMediaContainerImageTpl,
		mainMediaContainerEmbedTpl,
		viewCss,
		WebApplicationData,
		has,
		arcgisUtils,
		UniqueValueRenderer,
		Point,
		Extent,
		esriConfig,
		webMercatorUtils,
		SimpleMarkerSymbol,
		//PopupMobile,
		Query,
		topic,
		on,
		aspect,
		lang
	){
		return function MainStage(container, isInBuilder, mainView)
		{
			var _this = this;

			//
			// Media containers
			//

			function addTemporaryMainMediaContainer(webmap)
			{
				$("#mainStagePanel .medias").append(mainMediaContainerMapTpl({ webmapid: webmap, isTemporary: true }));
			}

			this.updateMainMediaContainers = function()
			{
				var webmaps = app.data.getWebmaps(),
					images = app.data.getImages(),
					embeds = app.data.getEmbeds();

				//
				// Map
				//

				// Add new container
				$.each(webmaps, function(i, webmap){
					var mapContainer = $('.mapContainer[data-webmapid="' + webmap + '"]');
					if ( ! mapContainer.length )
						$("#mainStagePanel .medias").append( mainMediaContainerMapTpl({ webmapid: webmap, isTemporary: false }) );
				});

				// Remove unused container
				$('.mapContainer').each(function(){
					if ( $.inArray($(this).data('webmapid'), webmaps) == -1 )
						$(this).parent().remove();
				});

				//
				// Image
				//

				// Add new container
				$.each(images, function(i, imageUrl){
					var imageContainer = $('.imgContainer[data-src="' + imageUrl + '"]');
					if ( ! imageContainer.length )
						$("#mainStagePanel .medias").append( mainMediaContainerImageTpl({ url: imageUrl }) );
				});

				// Remove unused containers
				$('.imgContainer').each(function(){
					if ( $.inArray($(this).data('src'), images) == -1 )
						$(this).parent().remove();
				});

				//
				// Embed (video and webpage)
				//

				// Add new container
				$.each(embeds, function(i, embedInfo) {
					// TODO this has to be reviewed to not allow content to be loaded too early? or give the same option for url?

					var embedUrl = embedInfo.url,
						embedhash = "";

					if ( embedUrl.lastIndexOf('#') > 0 ) {
						embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));
						embedhash = embedInfo.url.substring(embedInfo.url.lastIndexOf('#') + 1);

						embedInfo.hash = embedhash;
					}

					var embedContainer = $('.embedContainer[data-src="' + (embedUrl || embedInfo.ts) + '"]');
					if ( ! embedContainer.length ) {

						//
						// Frametag are added straight to the dom without any container
						//  a class and a data attribute are added below
						// Ideally there should be a container so that it's possible to do more funny stuff like adding
						//  multiple iframe but these makes it difficult to center the frame(s)
						//

						$("#mainStagePanel .medias").append(mainMediaContainerEmbedTpl({
							url: embedUrl,
							frameTag: embedInfo.frameTag,
							// Introduced in V1.1
							unload: !!(embedInfo.unload === undefined || embedInfo.unload)
						}));

						// If it's a frame tag
						if ( !! embedInfo.frameTag ) {
							// Find the Iframe
							var frameTag = $("#mainStagePanel .medias .mainMediaContainer").last().find('iframe').first();

							// Transform the src attribute into a data-src and Add the timestamp
							frameTag.addClass('embedContainer')
								.attr('data-src', frameTag.attr('src'))
								.removeAttr('src')
								.attr('data-ts', embedInfo.ts)
								// Introduced in V1.1
								.attr('data-unload', !!(embedInfo.unload === undefined || embedInfo.unload));
						}
					}
				});

				// Remove unused containers
				$('.embedContainer').each(function() {
					var embedSRC = $(this).data('ts') || $(this).data('src');
					var embedInUse = $.grep(embeds, function(embed){
						var embedUrl = embed.url;
						if ( embedUrl.lastIndexOf('#') > 0 )
							embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));

						return embedSRC == embedUrl || embedSRC == embed.ts;
					}).length > 0;

					if ( ! embedInUse )
						$(this).parent().remove();
				});

				setMapControlsColor();
			};

			//
			// Management of Main Stage: all media
			//

			this.updateMainMediaWithStoryMainMedia = function(index)
			{
				var section = app.data.getStoryByIndex(index);
				if ( section && section.media )
					updateMainMedia(section.media, section, index);

				topic.publish("story-load-section", index);
			};

			this.updateMainMediaWithStoryAction = function(media)
			{
				updateMainMedia(media, app.data.getCurrentSection(), null);
			};

			function updateMainMedia(media, section, index)
			{
				// Refresh any iframe that would be the current Main Stage Media
				// If it's a video player this will stop current video playback
				var activeFrame = $(".mainMediaContainer.active > iframe[data-unload=true]");
				if ( activeFrame.length ) {
					setTimeout(function(){
						activeFrame.attr('src', activeFrame.attr('src'));
					}, 500);
				}

				// Fade out active container
				$(".mainMediaContainer.active").fadeOut();
				// Stop loading Indicator if running
				// From now only the Map has a loading indicator
				stopMainStageLoadingIndicator();

				if ( media.type == "webmap" )
					updateMainMediaMaps(media.webmap.id, section, index, media);
				else if ( media.type == "image" )
					updateMainMediaPicture(media.image.url, media.image.display);
				else if ( media.type == "video" )
					updateMainMediaEmbed(media.video.url, media.video);
				else if ( media.type == "webpage" ){
					var embedUrl = media.webpage.url;

					if ( embedUrl.lastIndexOf('#') > 0 )
						embedUrl = embedUrl.substring(0, embedUrl.lastIndexOf('#'));

					updateMainMediaEmbed(embedUrl || media.webpage.ts, media.webpage);
				}
			}

			function startMainStageLoadingIndicator()
			{
				$('#mainStageLoadingIndicator').fadeIn();
			}

			function stopMainStageLoadingIndicator()
			{
				$('#mainStageLoadingIndicator').fadeOut();
			}

			//
			// Layout
			//

			this.updateMainStageWithLayoutSettings = function()
			{
				var appLayout = WebApplicationData.getLayoutId(),
					appColors = app.data.getWebAppData().getColors(),
					layoutCfg = WebApplicationData.getLayoutCfg(),
					bodyWidth = $("body").width();

				// Resize embed that are have display fit
				styleMainStageEmbed();

				container.css("background-color", appColors.media);

				setMapControlsColor();

				if ( appLayout == "float" ) {
					var mapWidth = $("#contentPanel").width(),
						panelPos = $("#floatingPanel").position(),
						panelWidth = $("#floatingPanel").width(),
						isLeft = layoutCfg.position == "left",
						mapArea = isLeft ? mapWidth - (panelPos.left + panelWidth) : panelPos.left;

					// Attribution
					if ( isLeft )
						$(".mainMediaContainer.active .esriControlsBR").css({
							left: panelPos.left + panelWidth + 5,
							right: 'inherit'
						});
					else
						$(".mainMediaContainer.active .esriControlsBR").css({
							left: 'inherit',
							right: mapWidth - panelPos.left + 5
						});

					// Map configuration, loading indicator and error
					if ( isLeft )
						$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", panelPos.left + panelWidth + mapArea / 2);
					else
						$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", mapArea / 2);

					if ( $("body").hasClass("mobile-view") )
						$("#mainStageLoadingIndicator, .mainStageErrorContainer").css("left", "50%");

					//
					// Center some components on the Main Stage space at the left or right of the panel
					//

					var panelIsRight =  $("body").hasClass("layout-float-right"),
						paddingDir = panelIsRight ? "padding-right" : "padding-left",
						posDir = panelIsRight ? "right" : "left",
						val = $("#floatingPanel").position().left;

					if ( panelIsRight )
						val = bodyWidth - val;
					else
						val += $("#floatingPanel").width();

					// Help, builder landing&quotes
					$(".centerAlignOnFloat")
						.css({ paddingRight: 0, paddingLeft: 0 })
						.css(paddingDir, val);

					// Back button
					$(".mediaBackContainer")
						.css({ left: 'inherit', right: 'inherit' })
						.css(posDir, val + mapArea / 2);

					// Help goes over the floating panel when screen too small
					if ( bodyWidth <= 1067 )
						$("#builderHelp").css(paddingDir, 0);

					// Main Stage Images that are centered
					$(".mainMediaContainer .imgContainer.center")
						.css({ left: 0, right: 0 })
						.css(posDir, val);

					// Main Stage video&embed that are centered
					$(".mainMediaContainer .embedContainer.center")
						.css({ left: 0, right: 0 })
						.css(posDir, val);

					// Main Stage video&embed that are custom
					$(".mainMediaContainer .embedContainer.custom")
						.css({ left: 0, right: 0 })
						.css(posDir, val);
				}
				// Side Panel
				else {
					// Attribution
					$(".mainMediaContainer.active .esriControlsBR").css({
						left: "",
						right: ""
					});

					// Map configuration, loading indicator and error
					$(".mapConfigOverlay.position, .mapConfigOverlay.popup, #mainStageLoadingIndicator, .mainStageErrorContainer").css("left", "50%");

					// Reset centering that may have been done if user has changed layouts
					$(".centerAlignOnFloat").css({ paddingRight: 0, paddingLeft: 0 });
					$(".mediaBackContainer").css({ left: '50%', right: 'inherit' });
					$(".mainMediaContainer .imgContainer.center").css({ left: 0, right: 0 });
					$(".mainMediaContainer .embedContainer.center").css({ left: 0, right: 0 });
					$(".mainMediaContainer .embedContainer.custom").css({ left: 0, right: 0 });
				}
			};

			//
			// Management of Main Stage: map
			//

			// TODO params of the next two function has to be cleanedup

			function updateMainMediaMaps(newWebmapId, section, index, media)
			{
				//var currentWebmapId = $('.mapContainer:visible').data('webmapid');

				var mapContainer = $('.mapContainer[data-webmapid="' + newWebmapId + '"]');
				$('.mainMediaContainer').removeClass("active has-error");
				mapContainer.parent().addClass("active");

				if ( newWebmapId ) {
					// The map has already been loaded
					if ( mapContainer.hasClass('map') ) {
						var extentBeforeUpdate = app.map ? app.map.extent : null;

						app.map = app.maps[newWebmapId].response.map;
						app.mapItem = app.maps[newWebmapId].response.itemInfo;
						app.mapConfig = app.maps[newWebmapId];

						updateMainMediaMapsStep2(
							mapContainer,
							section,
							extentBeforeUpdate,
							index,
							media,
							true
						);
					}
					// Need to load the map
					else {
						startMainStageLoadingIndicator();

						// Get the extent to be used to load the webmap
						var extent = media && media.webmap ? media.webmap.extent : null;
						if ( extent ) {
							try {
								extent = new Extent(extent);
							} catch (e) {
								extent = null;
							}
						}

						mainView.loadWebmap(newWebmapId, mapContainer[0], extent).then(
							lang.hitch(_this, function(response){
								var extentBeforeUpdate = app.map ? app.map.extent : null;

								app.maps[newWebmapId] = mainView.getMapConfig(response, mapContainer);
								app.map = response.map;
								app.mapItem = app.maps[newWebmapId].response.itemInfo;
								app.mapConfig = app.maps[newWebmapId];

								// Popup
								if ( app.map.infoWindow ) {
									$(app.map.infoWindow.domNode).addClass("light");
									app.map.infoWindow.markerSymbol = new SimpleMarkerSymbol().setSize(0);
								}

								updateMainMediaMapsStep2(
									mapContainer,
									section,
									extentBeforeUpdate,
									index,
									media,
									false
								);

								//
								// Register events for the builder
								//  because we need to know for Map Configuration what is the intended extent
								//  before the zoom when there is lods (the resulting extent will always be different)
								//
								if ( isInBuilder ) {
									// can't use update-end as it's not correct value for setExtent when lods
									app.ignoreNextEvent = false;
									aspect.before(app.map, "setExtent", function(extent) {
										console.log("Set extent:", extent);
										if ( ! app.ignoreNextEvent ) {
											app.lastExtentSet = extent;
											// A pan or zoom will also be triggered
											app.ignoreNextEvent = true;
										}
									});

									var handle = app.map.on("update-end", function(){
										handle.remove();
										app.lastExtentSet = app.map.extent;
										// store the initial extent in a new property
										// TODO is that necessary? to not mess with browser resize and init map extent?
										//app.map._params.extent = app.map.extent;
										app.map.mapJournalInitExtent = app.map.extent;
										app.ignoreNextEvent = true;
									});

									var onPanOrZoomEnd = function(e)
									{
										if ( ! app.ignoreNextEvent )
											app.lastExtentSet = e.extent;
										else
											app.ignoreNextEvent = false;
									};
									app.map.on("zoom-end", onPanOrZoomEnd);
									app.map.on("pan-end", onPanOrZoomEnd);
								}

								setTimeout(function(){
									stopMainStageLoadingIndicator();
								}, 50);

								mapContainer.parent().removeClass("has-error");
							}),
							lang.hitch(_this, function(){
								stopMainStageLoadingIndicator();
								mapContainer.parent().addClass("has-error");
								mapContainer.parent().find('.error').html(i18n.viewer.errors.mapLoadingFail);

								topic.publish("story-loaded-map", {
									id: newWebmapId,
									index: index
								});
								topic.publish("ADDEDIT_LOAD_WEBMAP_FAIL");
							})
						);

						// Publish an early loaded after two second in case the map is slow to load
						setTimeout(function(){
							topic.publish("story-section-map-timeout");
						}, 2000);
					}
				}
			}

			function updateMainMediaMapsStep2(mapContainer, section, oldExtent, index, media, notFirstLoad)
			{
				_this.updateMainStageWithLayoutSettings();
				setMapControlsColor();

				//app.data.debug();

				if( WebApplicationData.getLayoutId() == "float" )
					app.map.disableKeyboardNavigation();
				else
					app.map.enableKeyboardNavigation();

				try {
					app.map.resize();
					app.map.reposition();
				} catch(e) { }

				// If this is a story section
				if ( section || media ) {
					//
					// Layers
					//

					//  - Array of {id:'', visible:''} for the overrided layers (compared to the webmap initial state)
					//  - Only overrided layers are present there to allow the webmap to evolve outside of the app
					//     - If default visibility of layers are changed outside of the app, all view that didn't override the value will see the change
					//     - if the webmap evolve the array may reference deleted layers. That's cleaned anytime user open the Configure map View and Save
					var layerCfg = media && media.webmap ? media.webmap.layers : null,
						mapDefault = app.maps[media.webmap.id].response.itemInfo.itemData.operationalLayers;

					// Loop through webmap layers and set the visibility
					// The visibility is set to the section definition when defined or to the webmap initial visibility
					$.each(mapDefault, function(i, layer){
						var override;

						if ( layer.layerObject) {
							override = $(layerCfg).filter(function(i, l){ return l.id == layer.layerObject.id; });

							var updateVisibility = function()
							{
								layer.layerObject.setVisibility(override.length ? override[0].visibility : layer.visibility);
							};

							if ( layer.layerObject.loaded )
								updateVisibility();
							else {
								layer.layerObject.on("load", updateVisibility);
							}
						}
						else if ( layer.featureCollection && layer.featureCollection.layers ) {
							$.each(layer.featureCollection.layers, function(i, fcLayer){
								override = $(layerCfg).filter(function(i, l){
									// Because the configuration store the map layerObject id like "mapNotes_914_0" instead of "mapNotes_914"
									// Should change that and keep V1.0 compatibility
									return l.id.split('_').slice(0,-1).join('_') == fcLayer.layerObject.id.split('_').slice(0,-1).join('_');
								});
								fcLayer.layerObject.setVisibility(override.length ? override[0].visibility : fcLayer.visibility);
							});
						}
					});

					//
					// Extent
					//

					var extent = media && media.webmap ? media.webmap.extent : null;
					if ( extent ) {
						try {
							extent = new Extent(extent);
						} catch (e){
							//
						}
					}

					// Get back to the home section and section is configured to web map default
					if ( ! extent && notFirstLoad && index === 0 ) {
						extent = app.map._params.extent;
					}

					if ( extent )
						app.map.setExtent(extent/*, true*/).then(function(){
							applyPopupConfiguration(media.webmap.popup, index);
							topic.publish("story-loaded-map", {
								id: media.webmap.id,
								index: index
							});
						}); // TODO has at least to use _core.setExtent
					else
						topic.publish("story-loaded-map", {
							id: media.webmap.id,
							index: index
						});

					/*
					// Reuse the current extent
					else if( oldExtent )
						app.map.setExtent(oldExtent);
					*/

					//
					// Map Controls
					//

					var overviewSettings = media.webmap.overview || {},
						legendSettings = media.webmap.legend || {};

					// If it's a Main Stage Action, look to use the section Main Stage media
					//  configuration IF it's a webmap
					if ( index === null && section.media && section.media.webmap  ) {
						overviewSettings = section.media.webmap.overview || {},
						legendSettings = section.media.webmap.legend || {};
					}

					if ( overviewSettings.enable !== undefined ) {
						app.maps[media.webmap.id].overview.toggle(overviewSettings.enable, WebApplicationData.getColors());
						app.maps[media.webmap.id].overview.toggleExpanded(overviewSettings.openByDefault);
						app.maps[media.webmap.id].overview.setSettings(overviewSettings);
					}

					if ( legendSettings.enable !== undefined ) {
						app.maps[media.webmap.id].legend.toggle(legendSettings.enable);
						app.maps[media.webmap.id].legend.toggleExpanded(legendSettings.openByDefault);
						app.maps[media.webmap.id].legend.setSettings(legendSettings);
					}
					/*	*/
					//
					// Popup
					//

					if ( ! extent )
						applyPopupConfiguration(media.webmap.popup, index);
					// Otherwise called through extent change callback

				}
				else
					topic.publish("ADDEDIT_WEBMAP_DONE");
			}

			function applyPopupConfiguration(popupCfg, index)
			{
				// When an action is performed the popup will be closed
				// But features aren't cleared so it can be restored
				app.map.infoWindow.hide();

				if ( popupCfg ) {
					var layer = app.map.getLayer(popupCfg.layerId);

					app.map.infoWindow.clearFeatures();

					if ( layer )
						applyPopupConfigurationStep2(popupCfg, index);
					// On FS the layer will be null until loaded...
					else
						var handle = app.map.on("update-end", function(){
							applyPopupConfiguration(popupCfg, index);
							handle.remove();
						});
				}
			}

			function applyPopupConfigurationStep2(popupCfg, index)
			{
				var query = new Query(),
					layer = app.map.getLayer(popupCfg.layerId);

				if ( ! layer )
					return;

				query.objectIds = [popupCfg.fieldValue];

				// Feature Service
				if (!layer._collection) {
					query.returnGeometry = true;
					query.outFields = ["*"]; // popupCfg.fieldName ?
					query.outSpatialReference = app.map.spatialReference;
				}

				layer.queryFeatures(query).then(function(featureSet) {
					applyPopupConfigurationStep3(featureSet.features, index);
				});
			}

			function applyPopupConfigurationStep3(features, index)
			{
				if ( ! features || ! features.length )
					return;

				var geom = features[0].geometry,
					center = geom.getExtent() ? geom.getExtent().getCenter() : geom;

				app.map.infoWindow.setFeatures(features);
				app.map.infoWindow.show(center);

				// Center the map is the geometry isn't visible
				if ( ! app.map.extent.contains(center) ) {
					app.map.centerAt(center);
					// Show back btn only if it's a Main Stage action
					if ( index === null ) {
						$('.mediaBackContainer')
							.show()
							.css("marginLeft", - $(".mediaBackContainer .backButton").outerWidth() / 2)
							.css("marginRight", - $(".mediaBackContainer .backButton").outerWidth() / 2);
					}
				}
			}

			function setMapControlsColor()
			{
				if ( app.mapConfig ) {
					var appColors = app.data.getWebAppData().getColors();
					app.mapConfig.overview.setColors(appColors);
					app.mapConfig.legend.setColors(appColors);
				}
			}

			// Builder events

			this.showWebmapById = function(webmapId)
			{
				updateMainMediaMaps(webmapId, null, null, null);
			};

			this.loadTmpWebmap = function(webmapId)
			{
				if ( ! $('.mapContainer[data-webmapid="' + webmapId + '"]').length )
					addTemporaryMainMediaContainer(webmapId);

				updateMainMediaMaps(webmapId, null, null, null);
			};

			//
			// Management of Main Stage: picture
			//

			function updateMainMediaPicture(url, display)
			{
				$('.mainMediaContainer').removeClass('active');
				var pictureContainer = $('.imgContainer[data-src="' + url + '"]');
				if ( pictureContainer ) {
					pictureContainer
						.removeClass("center fit fill stretch")
						.addClass(display)
						.css({
							left: 0,
							right: 0
						})
						.css('background-image', 'url("' + pictureContainer.data('src') + '")');

					_this.updateMainStageWithLayoutSettings();

					pictureContainer.parent().addClass('active');
				}
			}

			//
			// Management of Main Stage: embed (video and webpage)
			//

			function updateMainMediaEmbed(url, cfg)
			{
				$('.mainMediaContainer').removeClass('active');

				// URL can be an URL or the timestamp in case of an iframe tag
				var embedContainer = $('.embedContainer[data-src="' + url + '"]');

				// Not found, must be an iframe tag
				if ( ! embedContainer.length ) {
					embedContainer = $('.embedContainer[data-ts="' + url + '"]');
					// The correct URL is in data-src
					url = embedContainer.data('src');
				}

				if ( embedContainer.length ) {
					embedContainer
						.removeClass("center fit fill stretch")
						.addClass(cfg.display)
						.attr("data-unload", cfg.unload === undefined || cfg.unload)
						.css({
							left: 0,
							right: 0
						});

					if ( cfg.hash ) {
						url = url + '#' + cfg.hash;
						embedContainer.attr('src', url);
					}

					// TODO this fail if no src attr is set on the iframe (srcdoc)
					//  as a workaround <iframe srcdoc="http://" src="about:blank></iframe>
					if ( ! embedContainer.attr('src') )
						// TODO youtube recommand an origin param "&origin=" + encodeURIComponent(document.location.origin)
						// https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
						embedContainer.attr('src', url);

					var width = cfg.width || '560',
						height = cfg.height || '315';

					// Done trough CSS and JS on resize
					if ( cfg.display == "fit" ) {
						width = "";
						height = "";
					}

					if ( width ) {
						if ( ! width.match(/[0-9]+%/) )
							width = width + 'px';
						embedContainer.attr('width', width);
					}
					if ( height ) {
						if ( ! height.match(/[0-9]+%/) )
							height = height + 'px';
						embedContainer.attr('height', height);
					}

					embedContainer.parent().addClass('active');
					_this.updateMainStageWithLayoutSettings();
				}
			}

			function styleMainStageEmbed()
			{
				$(".mainMediaContainer.active iframe.embedContainer.fit").attr(
					"height",
					$("#mainStagePanel").width() * 9 / 16
				);
			}
		};
	}
);


text:
package mat.client.measure.service;

import mat.client.measure.ManageMeasureDetailModel;
import mat.client.measure.ManageMeasureSearchModel;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * The Interface MeasureCloningServiceAsync.
 */
public interface MeasureCloningServiceAsync {

	/**
	 * Clone.
	 *
	 * @param currentDetails
	 *            the current details
	 * @param loggedinUserId
	 *            the loggedin user id
	 * @param isDraftCreation
	 *            the is draft creation
	 * @param callback
	 *            the callback
	 */
	void clone(ManageMeasureDetailModel currentDetails, String loggedinUserId, boolean isDraftCreation,
			AsyncCallback<ManageMeasureSearchModel.Result> callback);
}


text:
'use strict'

const BaseController = require('../../..')

module.exports = class MyController extends BaseController {
  constructor (app, ctx, next) {
    super(app, ctx, next)

    this.path = '/2'
  }

  post (req, res) {
    req.headers.host = null;
    res.send(String(req.hostname));
  }
}


text:
from collections import namedtuple
import copy
import shm
from shm.watchers import watcher
from mission.framework.task import Task
from mission.framework.targeting import PIDLoop, ForwardTarget
from mission.framework.combinators import (
    Sequential,
    Concurrent,
    MasterConcurrent,
    Retry,
    Conditional,
    Defer,
)
from mission.framework.timing import Timeout
from mission.framework.movement import (
    RelativeToInitialDepth,
    RelativeToCurrentDepth,
    VelocityX,
    VelocityY,
    Depth,
)
from mission.framework.primitive import (
    Zero,
    Log,
    Succeed,
    Fail,
    FunctionTask,
    NoOp,
)
from mission.framework.actuators import FireActuator
from mission.framework.position import (
    GoToPositionRough,
    MoveX,
    MoveY,
    MoveXRough,
    WithPositionalControl,
    NavigationSpeed,
)
from mission.framework.track import ConsistentObject
from mission.framework.helpers import call_if_function
from mission.missions.ozer_common import (
    ConsistentTask,
    Except,
    GlobalTimeoutError,
    StillHeadingSearch,
    GradualHeading,
    PrintDone,
    Infinite,
)
from mission.constants.config import torpedoes as constants

"""
Torpedoes 2017!
"""

class Vision(Task):
    # Board/cutout IDs are indices
    TENT_ID = 0
    SQUID_ID = 1

    def __init__(self, *args, **kwargs):
        super().__init__()
        # Vision object needs to be ready for rest of mission to access, so must
        # initialize before on_first_run()

        self.trackers = [ConsistentObject() for i in range(2)]

        self.watcher = watcher()
        self.watcher.watch(shm.torpedoes_vision)
        self.pull()

    def pull(self):
        shm_boards = [shm.torpedoes_tentacle.get(), shm.torpedoes_squid.get()]

        def noneify(g): return g if g.visible else None
        self.boards = [t.map(noneify(b)) for t, b in zip(self.trackers, shm_boards)]

    def on_run(self, *args, **kwargs):
        if self.watcher.has_changed():
            self.pull()

# Forecam offsets may be incorrect to compensate for inaccurate DVL-less control
class Torp:
    FIRE_TIME = 0.5

    def __init__(self, forecam_offset, actuator):
        self.forecam_offset = forecam_offset
        self.actuator = actuator

    def AlignFromForecam(self):
        return ConsistentTask(Concurrent(
            RelativeToInitialDepth(-self.forecam_offset[1]),
            MoveY(-self.forecam_offset[0], deadband=0.025),
            finite=False,
        ), success=2, total=3)

    def Fire(self):
        return Sequential(
            Log('Firing {} (!!)'.format(self.actuator)),
            FireActuator(self.actuator, self.FIRE_TIME),
        )

TORPS = [Torp((-0.02, -0.12), 'left_torpedo'), Torp((0.15, -0.12), 'right_torpedo')]

Cutout = namedtuple('Cutout', ['name', 'board_func', 'coord_func', 'is_noodle'])

class Torpedoes(Task):
    def on_first_run(self, vision, *args, **kwargs):

        def small_cutout_coord(board):
            return (board.small_cutout_x, board.small_cutout_y)
        def large_cutout_coord(board):
            return (board.large_cutout_x, board.large_cutout_y)

        small_tent_cutout = Cutout(
            'small tentacle',
            lambda: vision.boards[vision.TENT_ID],
            lambda: small_cutout_coord(vision.boards[vision.TENT_ID]),
            False,
        )
        # large_tent_cutout = Cutout(
            # 'large tentacle',
            # lambda: vision.boards[vision.TENT_ID],
            # lambda: large_cutout_coord(vision.boards[vision.TENT_ID]),
            # False,
        # )
        small_squid_cutout = Cutout(
            'small squid',
            lambda: vision.boards[vision.SQUID_ID],
            lambda: small_cutout_coord(vision.boards[vision.SQUID_ID]),
            True,
        )
        # large_squid_cutout = Cutout(
            # 'large squid',
            # lambda: vision.boards[vision.SQUID_ID],
            # lambda: large_cutout_coord(vision.boards[vision.SQUID_ID]),
            # False,
        # )

        self.use_task(Except(
            Sequential(
                Log('Starting torpedoes!'),
                Succeed(TryCompleteCutout(vision, small_tent_cutout, TORPS[0])),
                Succeed(TryCompleteCutout(vision, small_squid_cutout, TORPS[1])),
            ),

            Fail(Log('Global timeout, aborting torpedoes')),
            GlobalTimeoutError,
        )),

class TryCompleteCutout(Task):
    def on_first_run(self, vision, cutout, torp, *args, **kwargs):
        self.use_task(Conditional(
            Sequential(
                Log('Starting to attempt {} cutout'.format(cutout.name)),
                Retry(lambda: CompleteCutout(vision, cutout, torp), 3),
            ),

            on_fail=Fail(Sequential(
                Log('Failed to ever complete {} cutout, firing torpedo anyway'.format(cutout.name)),
                torp.Fire(),
            )),
        ))

class CompleteCutout(Task):
    MOVE_BOARD_TIMEOUT = 30
    ALIGN_CUTOUT_TIMEOUT = 60

    def on_first_run(self, vision, cutout, torp, *args, **kwargs):
        self.use_task(Sequential(
            Log('Attempting {} cutout'.format(cutout.name)),

            Conditional(
                Retry(lambda: Timeout(
                    MoveInFrontOfBoards(vision),
                    self.MOVE_BOARD_TIMEOUT,
                ), 3),
                on_fail=Fail(Log('Failed to ever move in front of boards')),
            ),

            RestorePos(WithPositionalControl(Sequential(
                Timeout(AlignCutout(cutout, torp), self.ALIGN_CUTOUT_TIMEOUT),
                torp.Fire(),
            ))),
        ))

class MoveInFrontOfBoards(Task):
    def on_first_run(self, vision, *args, **kwargs):
        self.use_task(Sequential(
            Log('Moving to torpedoes depth'),
            Depth(constants.depth),

            Log('Searching for boards'),
            MasterConcurrent(IdentifyBoard(vision), StillHeadingSearch()),

            AlignBoards(lambda: vision.boards, min_boards=2),
        ))

class IdentifyBoard(Task):
    def on_run(self, vision, *args, **kwargs):
        if sum(b is not None for b in vision.boards) > 0:
            self.finish()

class AlignBoards(Task):
    """
    Imprecisely align to both torpedoes boards.

    Pre: at least one board in sight
    Post: both boards centered in front of sub
    """

    TARGET_WIDTH = 0.8
    FOV = 30

    def board_count(self, boards_func):
        return sum(b is not None for b in boards_func())

    def on_first_run(self, boards_func, min_boards=0, *args, **kwargs):
        def avg_board(boards):
            if len(boards) == 1:
                return boards[0]

            for i, b in enumerate(boards):
                if b is not None:
                    avg_i = i
                    avg_b = copy.copy(b)
                    break

            other_b = boards[1]
            if avg_i == 0 and other_b is not None:
                for attr in ['x', 'y', 'skew', 'width', 'height']:
                    setattr(
                        avg_b,
                        attr,
                        (getattr(avg_b, attr) + getattr(other_b, attr)) / 2,
                    )

            return avg_b

        def assert_boards():
            return self.board_count(boards_func) >= min_boards

        self.task = Retry(lambda: Sequential(
            Log('Aligning boards'),
            Concurrent(
                AlignSurge(lambda: avg_board(boards_func()), self.TARGET_WIDTH),
                AlignSkew(lambda: avg_board(boards_func())),

                # Align heading
                GradualHeading(lambda: shm.kalman.heading.get() + avg_board(boards_func()).x * self.FOV),

                finite=False,
            ),
            Zero(),

            Conditional(
                FunctionTask(assert_boards),

                on_fail=Fail(Sequential(
                    Log('Less than {} boards aligned, backing up and retrying'.format(min_boards)),
                    MoveXRough(-0.25),
                )),
            ),
        ), 2)

    def on_run(self, boards_func, *args, **kwargs):
        if self.board_count(boards_func) == 0:
            self.loge('No boards visible, aborting align')
            self.finish(success=False)
        else:
            self.task()
            if self.task.finished:
                self.finish(success=self.task.success)

class AlignSurge(Task):
    DEADBAND = 0.03
    P = 0.5
    D = 0.2
    MAX_OUT = 0.3

    def on_first_run(self, board_func, width, *args, **kwargs):
        """ PID our distance instead of the raw width since it's linear """
        self.use_task(PIDLoop(
            input_value=lambda: 1 / board_func().width,
            output_function=VelocityX(),
            target=lambda: 1 / call_if_function(width),
            deadband=self.DEADBAND,
            p=self.P,
            d=self.D,
            negate=True,
            max_out=self.MAX_OUT,
        ))

class AlignSkew(Task):
    def on_first_run(self, board_func, *args, **kwargs):
        self.use_task(PIDLoop(
            input_value=lambda: board_func().skew,
            output_function=VelocityY(),
            target=0,
            deadband=0.1,
            p=1.5,
            d=0.5,
            max_out=0.2,
        ))

class RestorePos(Task):
    """
    Restore the position of the sub from before the given task started.
    """
    def on_first_run(self, task, *args, **kwargs):
        k = shm.kalman.get()

        self.use_task(Defer(task, Sequential(
            Log('Restoring position'),
            NavigationSpeed(GoToPositionRough(
                north=k.north,
                east=k.east,
                heading=k.heading,
                depth=k.depth,
            ), 0.3),
            Zero(),
        )))

class AlignCutout(Task):
    NORMAL_TARGET_BOARD_WIDTH = 2
    NORMAL_TARGET_BOARD_HALF_WIDTH = 1 / ((
        1 / NORMAL_TARGET_BOARD_WIDTH + 1 / AlignBoards.TARGET_WIDTH
    ) / 2)
    SEAWEED_TARGET_BOARD_WIDTH = 1

    ALIGN_POKER_DISTANCE = 0.63

    def on_first_run(self, cutout, torp, *args, **kwargs):
        def unsee_cutout():
            self.must_see_cutout = False

        self.must_see_cutout = True

        def TargetCutout(deadband):
            return ForwardTarget(
                lambda: cutout.coord_func(),
                (0, 0),
                deadband=(deadband, deadband),
                px=0.7,
                py=0.5,
                max_out=0.3,
            )

        def MoveClose(width, deadband):
            return ConsistentTask(Concurrent(
                TargetCutout(deadband),
                AlignSurge(cutout.board_func, width),
                finite=False,
            ), success=6, total=8)

        if cutout.is_noodle:
            target_cutout = Sequential(
                Log('Aligning in front of covered cutout'),
                MoveClose(self.SEAWEED_TARGET_BOARD_WIDTH, 0.04),
            )

        else:
            target_cutout = Sequential(
                Log('Aligning halfway to uncovered cutout'),
                MoveClose(self.NORMAL_TARGET_BOARD_HALF_WIDTH, 0.07),
                Log('Aligning close to uncovered cutout'),
                MoveClose(self.NORMAL_TARGET_BOARD_WIDTH, 0.07),
            )

        self.task = Sequential(
            Log('Aligning board containing cutout'),
            AlignBoards(lambda: [cutout.board_func()]),

            Log('Centering cutout'),
            TargetCutout(0.15),
            target_cutout,

            Zero(),
            FunctionTask(unsee_cutout),

            Sequential(
                Log('Moving poker beside seaweed'),
                NavigationSpeed(
                    MoveX(self.ALIGN_POKER_DISTANCE, deadband=0.02),
                    0.3,
                ),
            ) if cutout.is_noodle else NoOp(),

            Log('Aligning torpedo tube'),
            torp.AlignFromForecam(),
        )

    def on_run(self, cutout, torp, *args, **kwargs):
        if self.must_see_cutout and cutout.board_func() is None:
            self.loge('Cutout lost, cannot align')
            self.finish(success=False)

        else:
            self.task()
            if self.task.finished:
                self.finish(success=self.task.success)

class VisionTask(Task):
    def on_first_run(self, task_func, *args, **kwargs):
        vision = Vision()
        self.use_task(MasterConcurrent(task_func(vision, *args, **kwargs), vision))

def Full(): return VisionTask(Torpedoes)


text:
package io.druid.query.spec;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.MoreExecutors;
import com.metamx.common.guava.Accumulator;
import com.metamx.common.guava.Sequence;
import com.metamx.common.guava.Sequences;
import com.metamx.common.guava.Yielder;
import com.metamx.common.guava.YieldingAccumulator;
import io.druid.granularity.QueryGranularities;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.query.Druids;
import io.druid.query.Query;
import io.druid.query.QueryRunner;
import io.druid.query.Result;
import io.druid.query.SegmentDescriptor;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.CountAggregator;
import io.druid.query.aggregation.CountAggregatorFactory;
import io.druid.query.timeseries.TimeseriesQuery;
import io.druid.query.timeseries.TimeseriesResultBuilder;
import io.druid.query.timeseries.TimeseriesResultValue;
import io.druid.segment.SegmentMissingException;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SpecificSegmentQueryRunnerTest
{
  @Test
  public void testRetry() throws Exception
  {
    final ObjectMapper mapper = new DefaultObjectMapper();
    SegmentDescriptor descriptor = new SegmentDescriptor(
        new Interval("2012-01-01T00:00:00Z/P1D"),
        "version",
        0
    );

    final SpecificSegmentQueryRunner queryRunner = new SpecificSegmentQueryRunner(
        new QueryRunner()
        {
          @Override
          public Sequence run(Query query, Map responseContext)
          {
            return new Sequence()
            {
              @Override
              public Object accumulate(Object initValue, Accumulator accumulator)
              {
                throw new SegmentMissingException("FAILSAUCE");
              }

              @Override
              public Yielder<Object> toYielder(
                  Object initValue, YieldingAccumulator accumulator
              )
              {
                return null;
              }
            };

          }
        },
        new SpecificSegmentSpec(
            descriptor
        )
    );

    final Map<String, Object> responseContext = Maps.newHashMap();
    TimeseriesQuery query = Druids.newTimeseriesQueryBuilder()
                                  .dataSource("foo")
                                  .granularity(QueryGranularities.ALL)
                                  .intervals(ImmutableList.of(new Interval("2012-01-01T00:00:00Z/P1D")))
                                  .aggregators(
                                      ImmutableList.<AggregatorFactory>of(
                                          new CountAggregatorFactory("rows")
                                      )
                                  )
                                  .build();
    Sequence results = queryRunner.run(
        query,
        responseContext
    );
    Sequences.toList(results, Lists.newArrayList());

    Object missingSegments = responseContext.get(Result.MISSING_SEGMENTS_KEY);

    Assert.assertTrue(missingSegments != null);
    Assert.assertTrue(missingSegments instanceof List);

    Object segmentDesc = ((List) missingSegments).get(0);

    Assert.assertTrue(segmentDesc instanceof SegmentDescriptor);

    SegmentDescriptor newDesc = mapper.readValue(mapper.writeValueAsString(segmentDesc), SegmentDescriptor.class);

    Assert.assertEquals(descriptor, newDesc);
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testRetry2() throws Exception
  {
    final ObjectMapper mapper = new DefaultObjectMapper();
    SegmentDescriptor descriptor = new SegmentDescriptor(
        new Interval("2012-01-01T00:00:00Z/P1D"),
        "version",
        0
    );

    TimeseriesResultBuilder builder = new TimeseriesResultBuilder(
        new DateTime("2012-01-01T00:00:00Z")
    );
    CountAggregator rows = new CountAggregator("rows");
    rows.aggregate();
    builder.addMetric(rows);
    final Result<TimeseriesResultValue> value = builder.build();

    final SpecificSegmentQueryRunner queryRunner = new SpecificSegmentQueryRunner(
        new QueryRunner()
        {
          @Override
          public Sequence run(Query query, Map responseContext)
          {
            return Sequences.withEffect(
                Sequences.simple(Arrays.asList(value)),
                new Runnable()
                {
                  @Override
                  public void run()
                  {
                    throw new SegmentMissingException("FAILSAUCE");
                  }
                },
                MoreExecutors.sameThreadExecutor()
            );
          }
        },
        new SpecificSegmentSpec(
            descriptor
        )
    );

    final Map<String, Object> responseContext = Maps.newHashMap();
    TimeseriesQuery query = Druids.newTimeseriesQueryBuilder()
                                  .dataSource("foo")
                                  .granularity(QueryGranularities.ALL)
                                  .intervals(ImmutableList.of(new Interval("2012-01-01T00:00:00Z/P1D")))
                                  .aggregators(
                                      ImmutableList.<AggregatorFactory>of(
                                          new CountAggregatorFactory("rows")
                                      )
                                  )
                                  .build();
    Sequence results = queryRunner.run(
        query,
        responseContext
    );
    List<Result<TimeseriesResultValue>> res = Sequences.toList(
        results,
        Lists.<Result<TimeseriesResultValue>>newArrayList()
    );

    Assert.assertEquals(1, res.size());

    Result<TimeseriesResultValue> theVal = res.get(0);

    Assert.assertTrue(1L == theVal.getValue().getLongMetric("rows"));

    Object missingSegments = responseContext.get(Result.MISSING_SEGMENTS_KEY);

    Assert.assertTrue(missingSegments != null);
    Assert.assertTrue(missingSegments instanceof List);

    Object segmentDesc = ((List) missingSegments).get(0);

    Assert.assertTrue(segmentDesc instanceof SegmentDescriptor);

    SegmentDescriptor newDesc = mapper.readValue(mapper.writeValueAsString(segmentDesc), SegmentDescriptor.class);

    Assert.assertEquals(descriptor, newDesc);
  }
}