text:
    if (ret == -1) \
        return -1;

int _test_packet_1_deserialize(buffer_t data, struct test_packet_1* payload)
{
    TRY(buffer_pop_int32(data, &payload->data1));
    TRY(buffer_pop_char(data, &payload->data2));
    return 0;
}

int _test_packet_2_deserialize(buffer_t data, struct test_packet_2* payload)
{
    TRY(buffer_pop_int32(data, &payload->data1));
    TRY(buffer_pop_int16(data, &payload->data2));
    return 0;
}

int _handshake_deserialize(buffer_t data, struct handshake* payload)
{
    TRY(buffer_pop_int32(data, &payload->client_id));
    return 0;
}

int _plain_text_deserialize(buffer_t data, struct plain_text* payload)
{
    TRY(buffer_pop_string(data, &payload->text, 256));
    return 0;
}

int _ball_deserialize(buffer_t data, ball* payload)
{
    TRY(buffer_pop_int32(data, &payload->p_x));
    TRY(buffer_pop_int32(data, &payload->p_y));
    TRY(buffer_pop_int32(data, &payload->v_x));
    TRY(buffer_pop_int32(data, &payload->v_y));
    TRY(buffer_pop_int32(data, &payload->player));

    for (int i = 0; i < N_BUTTONS; i++) {
        TRY(buffer_pop_char(data, &payload->button_states[i]));
    }
    return 0;
}

int _state_deserialize(buffer_t data, state* payload)
{
    TRY(buffer_pop_char(data, &payload->paused));
    TRY(buffer_pop_int32(data, &payload->frame));
    for (int i = 0; i < MAX_PLAYERS; i++) {
        TRY(buffer_pop_int32(data, &payload->scores[i]));
    }
    for (int i = 0; i < N_BALLS; i++) {
        TRY(_ball_deserialize(data, &payload->balls[i]));
    }
    TRY(buffer_pop_int32(data, &payload->_lie));
    return 0;
}

int _event_deserialize(buffer_t data, event* payload)
{
    TRY(buffer_pop_int32(data, &payload->frame));
    TRY(buffer_pop_int32(data, &payload->summon_frame));
    TRY(buffer_pop_int32(data, &payload->player));
    TRY(buffer_pop_char(data, &payload->button));
    TRY(buffer_pop_char(data, &payload->pressed));
    return 0;
}

int packet_deserialize(buffer_t data, packet_t* packet, int parse_sender)
{
    TRY(buffer_pop_int16(data, &packet->size));

    if (parse_sender) {
        TRY(buffer_pop_int32(data, &packet->sender_id));
    }
    char ptype;
    TRY(buffer_pop_char(data, &ptype));
    packet->ptype = ptype;

    switch (ptype) {
    case TEST_PACKET_1:
        TRY(_test_packet_1_deserialize(data, &packet->payload.packet1));
        break;
    case TEST_PACKET_2:
        TRY(_test_packet_2_deserialize(data, &packet->payload.packet2));
        break;
    case HANDSHAKE:
        TRY(_handshake_deserialize(data, &packet->payload.handshake));
        break;
    case PLAIN_TEXT:
        TRY(_plain_text_deserialize(data, &packet->payload.plain_text));
        break;
    case DISCONNECTED:
        // No payload
        break;
    case CONNECTED:
        // No payload
        break;
    case BALL:
        TRY(_ball_deserialize(data, &packet->payload.ball));
        break;
    case STATE:
        TRY(_state_deserialize(data, &packet->payload.state));
        break;
    case EVENT:
        TRY(_event_deserialize(data, &packet->payload.event));
        break;
    }
    return 0;
}

buffer_t _header_serialize(int16_t psize, enum payload_type ptype)
{
    // size + type + payload_size
    buffer_t buffer = buffer_create(2 + 1 + psize);
    buffer_push_int16(buffer, 2 + 1 + psize);
    buffer_push_char(buffer, ptype);
    return buffer;
}

buffer_t _test_packet_1_serialize(const struct test_packet_1* payload)
{
    // int32 + char
    buffer_t buffer = _header_serialize(4 + 1, TEST_PACKET_1);
    buffer_push_int32(buffer, payload->data1);
    buffer_push_char(buffer, payload->data2);
    return buffer;
}

buffer_t _test_packet_2_serialize(const struct test_packet_2* payload)
{
    // int32 + int16
    buffer_t buffer = _header_serialize(4 + 2, TEST_PACKET_2);
    buffer_push_int32(buffer, payload->data1);
    buffer_push_int16(buffer, payload->data2);
    return buffer;
}

buffer_t _handshake_serialize(const struct handshake* payload)
{
    // int32
    buffer_t buffer = _header_serialize(4, HANDSHAKE);
    buffer_push_int32(buffer, payload->client_id);
    return buffer;
}

buffer_t _plain_text_serialize(const struct plain_text* payload)
{
    // string_size + var
    buffer_t buffer = _header_serialize(2 + strlen(payload->text), PLAIN_TEXT);
    buffer_push_string(buffer, payload->text);
    return buffer;
}

buffer_t _disconnected_serialize()
{
    // no payload
    buffer_t buffer = _header_serialize(0, DISCONNECTED);
    return buffer;
}

buffer_t _connected_serialize()
{
    // no payload
    buffer_t buffer = _header_serialize(0, CONNECTED);
    return buffer;
}

buffer_t _ball_serialize(const ball* payload, buffer_t buffer)
{
    // int32 * 5 + char * N_BUTTONS
    if (buffer == NULL) {
        buffer = _header_serialize(20 + N_BUTTONS, BALL);
    }

    buffer_push_int32(buffer, payload->p_x);
    buffer_push_int32(buffer, payload->p_y);
    buffer_push_int32(buffer, payload->v_x);
    buffer_push_int32(buffer, payload->v_y);
    buffer_push_int32(buffer, payload->player);

    for (int i = 0; i < N_BUTTONS; i++) {
        buffer_push_char(buffer, payload->button_states[i]);
    }

    return buffer;
}

buffer_t _state_serialize(const state* payload)
{
    // int32 + int32 * MAX_PLAYERS + (ball = 20 + N_BUTTONS) * N_BALLS + lie
    buffer_t buffer = _header_serialize(1 + 4 + (4 * MAX_PLAYERS) + ((20 + N_BUTTONS) * N_BALLS) + 4, STATE);
    buffer_push_char(buffer, payload->paused);
    buffer_push_int32(buffer, payload->frame);
    for (int i = 0; i < MAX_PLAYERS; i++) {
        buffer_push_int32(buffer, payload->scores[i]);
    }
    for (int i = 0; i < N_BALLS; i++) {
        _ball_serialize(&payload->balls[i], buffer);
    }
    buffer_push_int32(buffer, payload->_lie);
    return buffer;
}

buffer_t _event_serialize(const event* payload)
{
    // 3 * int32 + 2 * char
    buffer_t buffer = _header_serialize(12 + 2, EVENT);
    buffer_push_int32(buffer, payload->frame);
    buffer_push_int32(buffer, payload->summon_frame);
    buffer_push_int32(buffer, payload->player);
    buffer_push_char(buffer, payload->button);
    buffer_push_char(buffer, payload->pressed);
    return buffer;
}

buffer_t packet_serialize(const void* payload,
    enum payload_type ptype)
{
    switch (ptype) {
    case TEST_PACKET_1:
        return _test_packet_1_serialize(payload);
    case TEST_PACKET_2:
        return _test_packet_2_serialize(payload);
    case HANDSHAKE:
        return _handshake_serialize(payload);
    case PLAIN_TEXT:
        return _plain_text_serialize(payload);
    case DISCONNECTED:
        // Payload ignored
        return _disconnected_serialize();
    case CONNECTED:
        // Payload ignored
        return _connected_serialize();
    case BALL:
        return _ball_serialize(payload, NULL);
    case STATE:
        return _state_serialize(payload);
    case EVENT:
        return _event_serialize(payload);
    default:
        return NULL;
    }
}

void send_packet(int socket, const void* payload, enum payload_type ptype)
{
    auto_buffer_t data = packet_serialize(payload, ptype);
    send(socket, buffer_data(data), buffer_size(data), 0);
}

void print_packet(const packet_t* packet)
{
    packet_t child;

    switch (packet->ptype) {
    case NONE:
        printf("NONE\n");
        break;
    case TEST_PACKET_1:
        printf("test_packet_1 {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tdata1 = %d\n", packet->payload.packet1.data1);
        printf("\tdata2 = %c\n}\n", packet->payload.packet1.data2);
        break;
    case TEST_PACKET_2:
        printf("test_packet_2 {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tdata1 = %d\n", packet->payload.packet2.data1);
        printf("\tdata2 = %d\n}\n", packet->payload.packet2.data2);
        break;
    case HANDSHAKE:
        printf("handshake {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tclient_id = %d\n}\n", packet->payload.handshake.client_id);
        break;
    case PLAIN_TEXT:
        printf("plain_text {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\ttext = %s\n}\n", packet->payload.plain_text.text);
        break;
    case DISCONNECTED:
        printf("disconnected {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n}\n", packet->sender_id);
        break;
    case CONNECTED:
        printf("connected {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n}\n", packet->sender_id);
        break;
    case BALL:
        printf("ball {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tp_x = %d\n", packet->payload.ball.p_x);
        printf("\tp_y = %d\n", packet->payload.ball.p_y);
        printf("\tv_x = %d\n", packet->payload.ball.v_x);
        printf("\tv_y = %d\n", packet->payload.ball.v_y);
        printf("\tplayer = %d\n", packet->payload.ball.player);
        printf("\tbutton_states = [");
        for (int i = 0; i < N_BUTTONS - 1; i++) {
            printf("%c, ", packet->payload.ball.button_states[i]);
        }
        printf("%c]\n}\n", packet->payload.ball.button_states[N_BUTTONS - 1]);
        break;
    case STATE:
        printf("state {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tframe = %d\n", packet->payload.state.frame);
        printf("\tscores = [");
        for (int i = 0; i < MAX_PLAYERS - 1; i++) {
            printf("%d, ", packet->payload.state.scores[i]);
        }
        printf("%d]\n", packet->payload.state.scores[MAX_PLAYERS - 1]);
        printf("\tballs = [");
        for (int i = 0; i < N_BALLS - 1; i++) {
            child.size = 0;
            child.sender_id = packet->sender_id;
            child.ptype = BALL;
            child.payload.ball = packet->payload.state.balls[i];
            print_packet(&child);
            printf(", ");
        }
        child.size = 0;
        child.sender_id = packet->sender_id;
        child.ptype = BALL;
        child.payload.ball = packet->payload.state.balls[N_BALLS - 1];
        print_packet(&child);
        printf("]\n}\n");
        break;
    case EVENT:
        printf("event {\n");
        printf("\tsize = %d\n", packet->size);
        printf("\tsender_id = %d\n", packet->sender_id);
        printf("\tframe = %d\n", packet->payload.event.frame);
        printf("\tsummon_frame = %d\n", packet->payload.event.summon_frame);
        printf("\tplayer = %d\n", packet->payload.event.player);
        printf("\tbutton = %d\n", (int)packet->payload.event.button);
        printf("\tpressed = %d\n}\n", (int)packet->payload.event.pressed);
        break;
    default:
        printf("UNKNOWN\n");
    }
}


text:
class VulkanTester
{
public:
	VulkanTester();
	virtual ~VulkanTester();

	// Call once after construction so that virtual functions may be called during init
	void initialize();

	const vk::DynamicLoader &dynamicLoader() const { return *dl; }
	vk::PhysicalDevice &getPhysicalDevice() { return physicalDevice; }
	vk::Device &getDevice() { return device; }
	vk::Queue &getQueue() { return queue; }
	uint32_t getQueueFamilyIndex() const { return queueFamilyIndex; }

private:
	std::unique_ptr<vk::DynamicLoader> loadDriver();

	std::unique_ptr<class ScopedSetIcdFilenames> setIcdFilenames;
	std::unique_ptr<vk::DynamicLoader> dl;
	vk::DebugUtilsMessengerEXT debugReport;

protected:
	const uint32_t queueFamilyIndex = 0;

	vk::Instance instance;  // Owning handle
	vk::PhysicalDevice physicalDevice;
	vk::Device device;  // Owning handle
	vk::Queue queue;
};

#endif  // VULKAN_TESTER_HPP_

redpajama_set_name: RedPajamaGithub


text:
package com.netflix.spinnaker.orca.kato.pipeline.strategy;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.orca.api.pipeline.RetryableTask;
import com.netflix.spinnaker.orca.api.pipeline.TaskResult;
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution;
import com.netflix.spinnaker.orca.kato.pipeline.support.SourceResolver;
import com.netflix.spinnaker.orca.kato.pipeline.support.StageData;
import groovy.util.logging.Slf4j;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CloudrunSourceServerGroupTask extends DetermineSourceServerGroupTask
    implements RetryableTask {

  public CloudrunSourceServerGroupTask() {}

  public CloudrunSourceServerGroupTask(SourceResolver sourceResolver) {
    super.setSourceResolver(sourceResolver);
  }

  @Override
  public TaskResult execute(StageExecution stage) {
    setRegionInContextFromPayload(stage);
    return super.execute(stage);
  }

  public StageData parseRegionAndSetInContext(StageExecution stage) {
    setRegionInContextFromPayload(stage);
    StageData stageData = stage.mapTo(StageData.class);
    return stageData;
  }

  private void setRegionInContextFromPayload(StageExecution stage) {

    ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
    if (stage.getContext() != null
        && stage.getContext().get("configFiles") != null
        && (!((List) stage.getContext().get("configFiles")).isEmpty())) {
      Map<String, Object> contextMap = stage.getContext();
      String configStr = (String) ((List) contextMap.get("configFiles")).get(0);
      Map<String, Object> yamlMap = null;
      try {
        yamlMap = yamlReader.readValue(configStr, Map.class);
        if (yamlMap.get("metadata") != null
            && ((Map<String, Object>) yamlMap.get("metadata")).get("labels") != null
            && ((Map<String, Object>) ((Map<String, Object>) yamlMap.get("metadata")).get("labels"))
                    .get("cloud.googleapis.com/location")
                != null) {
          stage
              .getContext()
              .put(
                  "region",
                  ((Map<String, Object>)
                          ((Map<String, Object>) yamlMap.get("metadata")).get("labels"))
                      .get("cloud.googleapis.com/location"));
        }
      } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
      }
    }
  }
}


text:
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, **options):
        self.stdout.write("simple_app")


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}
$editAccess = vc_user_access_check_shortcode_edit( $shortcode );
$allAccess = vc_user_access_check_shortcode_all( $shortcode );
?>
<div class="vc_controls<?php echo ! empty( $extended_css ) ? ' ' . $extended_css : '' ?>">
	<div class="vc_controls-<?php echo $position ?>">
		<a class="<?php echo esc_attr( $name_css_class ) ?>">
				<span class="vc_btn-content"
				      title="<?php if ( $allAccess ) : printf( __( 'Drag to move %s', 'js_composer' ), $name );
				      else : print( $name ); endif; ?>"><?php echo $name ?>

			<?php foreach ( $controls as $control ) : ?>
				<?php if ( 'add' === $control && $add_allowed ) : ?>
					<a class="vc_control-btn vc_control-btn-prepend vc_edit" href="#"
					   title="<?php printf( __( 'Prepend to %s', 'js_composer' ), $name ) ?>">
				<?php elseif ( $editAccess && 'edit' === $control ) :  ?>
					<a class="vc_control-btn vc_control-btn-edit" href="#"
					   title="<?php printf( __( 'Edit %s', 'js_composer' ), $name ) ?>">
				<?php elseif ( $allAccess && 'clone' === $control ) :  ?>
					<a class="vc_control-btn vc_control-btn-clone" href="#"
					   title="<?php printf( __( 'Clone %s', 'js_composer' ), $name ) ?>">
				<?php elseif ( $allAccess && 'delete' === $control ) :  ?>
					<a class="vc_control-btn vc_control-btn-delete" href="#"
					   title="<?php printf( __( 'Delete %s', 'js_composer' ), $name ) ?>">
				<?php endif ?>
			<?php endforeach ?>


text:
#pragma once
#include "global_data.h"
#include "parse_args.h"

namespace NN
{
  LEARNER::learner* setup(vw& all, po::variables_map& vm);
}


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

  angular.module('common')
    .controller('ProjectQuestionNewController', Controller);

  /** @ngInject */
  function Controller($state, ProjectQuestionService) {
    var ctrl = this;

    ctrl.$onChanges = onChanges;

    ctrl.onCreate = onCreate;
    ctrl.onCancel = onCancel;

    function onChanges(changes) {
      if (changes.projectQuestion) {
        ctrl.projectQuestion = angular.copy(ctrl.projectQuestion);
      }
    }

    function onCreate(event) {
      return ProjectQuestionService.create(event.projectQuestion)
        .then(function (projectQuestion) {
          $state.go('project-questions.edit', {id: projectQuestion.id});
        });
    }

    function onCancel() {
      $state.go('project-questions.list');
    }
  }
})();


text:
module Etsy4r
  class ServerCommands < Etsy4r::Commands

    def get_method_table
      @client.process('/')
    end

    def ping
      @client.process('/server/ping')
    end

    def get_server_epoch
      @client.process('/server/epoch')
    end

  end
end


text:
.operation-icon{
	width: 88px;
	height: 100px;
	background-color: #ebebeb;
	float: left;
	margin: 0px 10px 10px 0px;
	cursor: pointer;
	position: relative;
}

.operation-icon i{
    padding: 15px 0px 0px 0px;
    display: block;
    min-height: 65px;
		font-size: 3em !important;
    margin: 0px !important;
}

.operation-icon span{
	height: 35px;
    line-height: 15px;
    vertical-align: middle;
    display: table-cell;
    width: inherit;
}

.application{
	width: 250px;
	height: 100px;
	background-color: #ebebeb;
	float: left;
	margin: 0px 10px 10px 0px;
}

.application img{
    height: inherit;
    padding: 10px;
    float: left;
}

.app-info h4{
    margin-bottom: 0px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

.application i{
	float: right;
    margin: 0px 10px;
    position: relative;
    bottom: -20px;
	cursor: pointer;
}

.nav-tabs>li>a{
	color: #333;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover{
	border-bottom: 2px solid #37474f;
	border-right: none;
	border-top: none;
	border-left: none;
    font-weight: 400;
}
.nav-tabs-selector{
    margin: 0px;
    border: 1px solid #37474f;
}

.tab-pane{
	padding: 20px 0px;
}

.page-loader{
	position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: calc(100vh - 160px);
    z-index: 9999;
    background: url(images/page-loader.gif) 50% 50% no-repeat rgb(249,249,249);
}

.page-loader .loader{
    left: 43%;
    position: absolute;
    bottom: 50%;
    width: 13%;
}

.page-loader .loader span{
    padding: 9px;
    position: absolute;
    font-size: 18px;
}

.device-info-container{
    margin-bottom: 40px;
}
.device-type{
    font-size: 9em;
}
.device-info h1, .device-info h4:not(:last-child){
    margin: 0px 0px 9px 0px;
    position: relative;
    width: 100%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}
.device-id a{
    font-size: 0.4em;
    position: absolute;
    margin: 0px 5px;
    right: -5px;
}
.device-info h4:last-child{
	margin: 0px;
}
.tab-actions{
    position: relative;
}
.tab-actions .action-btn{
	padding: 10px 15px;
    background-color: #ebebeb;
    float: right;
    cursor: pointer;
    position: relative;
    margin-left: 10px;
    ma
}
.tab-actions .action{
    float: right;
    margin-left: 10px;
}
.tab-actions .action-btn.show a{
    margin: 0 0 10px;
}
.tab-actions .action-btn a{
    margin: 0px;
}
.tab-actions {
	margin: 0px;
}
.tab-actions .action-prop{
    padding: 10px;
    background: #ebebeb;
    width: 100%;
    margin-bottom: 10px;
}
.tab-action-active{
    padding-bottom: 15px !important;
}
.action-btn-container:after{
    content: '';
    display: block;
    clear:both;
}
.input-group .fw{
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 100;
}

.vital-strip{
    display: flex;
    flex-direction: row;
    background-color: #ebebeb;
    padding: 10px;
    margin-bottom: 40px;
}
.vital-strip p{
    flex-grow: 1;
    margin: 0px;
    display: inline-flex;
}
.vital-strip p i{
	margin: 0px 10px;
}
.vital-strip p span{
    padding: 5px 0px;
}
.memory-amt{
	font-size: 0.8em;
    position: relative;
    bottom: -3px;
    padding-left: 2px !important;
}

.policy-item{
	display: flex;
    flex-direction: row;
    padding: 10px;
    background-color: #ebebeb;
}
.policy-item .policy-status, .policy-item p{
	flex-grow: 1;
}
.policy-item .policy-status{
    flex-grow: 1;
    flex-basis: 0;
    margin-right: 10px;
    align-self: center;
    color: #5cb85c;
}
.policy-name{
    font-size: 1.5em;
    display: flex;
}
.policy-platform{
    display: flex;
}
.policy-item p:nth-child(2){
    margin: 0px;
}
.policy-item p:nth-child(3){
	flex-grow: 7;
    align-self: center;
    margin: 0px;
}
.policy-item p:nth-child(3) span{
    display: flex;
}
.policy-item .actions{
	flex-grow: 1;
    display: flex;
}
.policy-item .action-btn{
    flex-grow: 1;
    margin: 3px 5px;
    background-color: #ccc;
    display: flex;
    cursor: pointer;
    position: relative;
}
.policy-item .action-btn p{
    align-self: center;
    margin: 0px;
    display: flex;
    justify-content: center;
}
.policy-item .action-btn p i{
    padding: 0px 5px;
}
.policy-item .action-btn span{
    align-self: center;
}

#operation-log tr td{
    border-bottom: 15px solid #fff !important;
}
#operation-log tr.shown td{
    border-bottom: none !important;
}
.log-data-row td{
    padding: 0px !important;
    border-bottom: 15px solid #fff !important;
}
.log-data{
    background-color: #f6f6f6;
    padding: 0px 20px;
}
.log-data:after{
    content: '';
    width: 0;
    height: 100%;
    position: absolute;
    border: 1px solid #ced8db;
    top: 0;
    left: 50px;
}
.log-record-status{
    background-color: #4c4c4c !important;
    color: #fff;
    cursor: pointer;
    user-select: none;
}
.log-record-status i:first-child{
    float: left;
    line-height: 19px;
    padding: 0px 10px 0px 0px;
}
.log-record-status span{
    float: left;
    line-height: 17px;
}
.log-status{
    padding-left: 14px;
    z-index: 10;
    position: relative;
}
.log-status i{
    margin: 0px 10px;
    background-color: #f6f6f6;
    border-radius: 20px;
}
.log-entry{
   padding: 15px 0px;
}
.log-entry:not(:first-child){
    padding-top: 0px;
}

/*
 * custom css fixes
 */

.page-content-wrapper, .page-content-wrapper[data-container-behaviour=static]{
	min-height: calc(100vh - 123px);
}

.content{
	/*opacity: 0;*/
}

.content-wrapper{
	position: relative;
}

.dataTablesTop{
	display: none;
}

.table.list-table:not(.grid-view)>tbody>tr>td, .table.list-table:not(.grid-view)>tbody>tr>th{
    background-color: #eaeaea;
}
.table.table-hover>tbody>tr:hover td:not(.dataTables_empty){
    background-color: inherit !important;
}
.table-hover>tbody>tr:hover,{
    background-color:
}
.table.list-table>tbody>tr:nth-of-type(even), .table.list-table>tbody>tr:nth-of-type(odd){
    background-color: #eaeaea;
}
.table.table-hover>tbody>tr:hover td:not(.dataTables_empty){
    background-color: inherit !important;
}
.table.table-hover>tbody>tr:hover td.log-record-status{
    background-color: #4c4c4c !important;
}

.tab-content{
	border:none;
}


text:
package org.scalafmt.dynamic

import scala.util.Try

case class ScalafmtVersion(
    major: Int,
    minor: Int,
    patch: Int,
    rc: Int = 0,
    snapshot: String = ""
) extends Comparable[ScalafmtVersion] {
  private val integerRepr: Int = {
    val max = 100
    val rcval = (rc + max - 1) % max // 0 -> 99, everything else is less
    Seq(major, minor, patch, rcval).reduce(_ * max + _)
  }

  def <(other: ScalafmtVersion): Boolean = compareTo(other) < 0

  def >(other: ScalafmtVersion): Boolean = other < this

  override def toString: String =
    s"$major.$minor.$patch" +
      (if (rc > 0) s"-RC$rc" else "") +
      snapshot

  override def compareTo(o: ScalafmtVersion): Int = {
    val cmp = Integer.compare(integerRepr, o.integerRepr)
    if (cmp != 0) cmp
    else snapshot.compareTo(o.snapshot)
  }
}

object ScalafmtVersion {

  private val versionRegex =
    """(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?:-RC(\d{1,2}))?([+].*|-SNAPSHOT)?""".r

  def parse(version: String): Option[ScalafmtVersion] =
    version match {
      case versionRegex(major, minor, patch, rc, snapshot) =>
        Try {
          ScalafmtVersion(
            positiveInt(major),
            positiveInt(minor),
            positiveInt(patch),
            if (rc == null) 0 else positiveInt(rc),
            if (snapshot == null) "" else snapshot
          )
        }.toOption
      case _ => None
    }

  private def positiveInt(s: String): Int = {
    val i = s.toInt
    require(i >= 0)
    i
  }
}


text:
<?php
namespace AppBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
class UserConfigurationAdminController extends Controller
{
    public function myEditAction(Request $request = null)
    {
        $this->admin->checkAccess('edit');

        $id = 1;
        $object = $this->admin->getObject($id);

        $this->admin->setSubject($object);

        $form = $this->admin->getForm();
        $form->setData($object);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($config);
            $em->flush();
        }

        return $this->render($this->admin->getTemplate('myEdit'), array(
            'action'     => 'myEdit',
            'form'       => $form->createView(),
            'object' => $object,
        ), null, $request);
    }
}


text:
package org.drools.command.runtime.rule;

import org.drools.command.Context;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.impl.StatefulKnowledgeSessionImpl;
import org.drools.reteoo.ReteooWorkingMemoryInterface;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.rule.AgendaFilter;

public class FireUntilHaltCommand
    implements
    GenericCommand<Object> {
    private static final long serialVersionUID = 510l;

    private AgendaFilter agendaFilter = null;

    public FireUntilHaltCommand() {
    }

    public FireUntilHaltCommand(AgendaFilter agendaFilter) {
        this.agendaFilter = agendaFilter;
    }

    public Integer execute(Context context) {
        StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
        final ReteooWorkingMemoryInterface session = ((StatefulKnowledgeSessionImpl)ksession).session;

        new Thread(new Runnable() {
            public void run() {
                if ( agendaFilter != null ) {
                    session.fireUntilHalt( new StatefulKnowledgeSessionImpl.AgendaFilterWrapper( agendaFilter ) );
                } else {
                    session.fireUntilHalt();
                }
            }
        }).start();

        return null;
    }

    public String toString() {
        if ( agendaFilter != null ) {
            return "session.fireUntilHalt( " + agendaFilter + " );";
        } else {
            return "session.fireUntilHalt();";
        }
    }
}


text:
<!DOCTYPE html>

	<link href="styles/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="bower_components/angular-growl-v2/build/angular-growl.css"></link>
    <link rel="stylesheet" href="bower_components/ngActivityIndicator/css/ngActivityIndicator.css"></link>


text:
// Copyright (C) 2014 dot42
//
// Original filename: MulticastDelegate.cs
//
// 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.

using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Dot42;

namespace System
{
    abstract partial class MulticastDelegate : Delegate
    {
        // http://csharpindepth.com/Articles/Chapter2/Events.aspx
        //                                        in particular the table on removal
        //                                        and addition of delegates.

        // MulticastDelegate is immutable per specification.
        //
        // In our implementation, we always have a head (this), and possibly
        // a tail, stored in 'invocationList', its length defined by
        // 'invocationListLength'.
        // The invocation list will only contain delegates that
        // do not have an invocation list on their own, i.e. we always have
        // a flat invocation list.
        // We only create an invocation list when required. When required,
        // we try to minimize the number of new allocations by sharing the
        // invocation list between instances, if possible. Following typical
        // usage patterns, a newly combined delegate takes ownership of the
        // invocation list from the current delegate, if the current delegate
        // owns it.

        protected int InvocationListLength;
	    protected MulticastDelegate[] InvocationList;
        private int lostInvocationList;

        [Include]
        protected virtual bool EqualsWithoutInvocationList(MulticastDelegate other)
        {
            throw new NotImplementedException();
        }

        [Include]
        protected virtual int GetHashCodeWithoutInvocationList() { return GetType().GetHashCode(); }

        [Include, DexName("CloneWithNewInvocationList")]
        protected virtual MulticastDelegate CloneWithNewInvocationList(MulticastDelegate[] invocationList, int invocationListLength)
        {
            throw new NotImplementedException();
        }

        protected virtual object GetTargetImpl() { return null;}

        protected virtual MethodInfo GetMethodInfoImpl()
        {
            throw new NotImplementedException();
        }

        protected override sealed Delegate CombineImpl(Delegate other)
        {
            if (other == null)
                return this;

            MulticastDelegate o = (MulticastDelegate) other;

            var oInvList = o.InvocationList;
            var oInvLen  = o.InvocationListLength;

            o = o.WithoutInvocationList(); // we flatten the list.

            var newInvList = InvocationList;
            var curInvLen = InvocationListLength;
            int newInvLen = curInvLen + 1 + oInvLen;

            bool needNewList = newInvList == null || newInvList.Length < newInvLen;

            // try appending to the current list.
            if (!needNewList)
            {
                //if (Interlocked.CompareExchange(ref lostInvocationList, 1, 0) != 0 /*!TakeInvokationListOwnership()*/)
                // The locking might acually be faster than forcing a field of the class to be volatile,
                // but more measurements are needed.
                lock (InvocationList)
                {
                    if (lostInvocationList != 0)
                        needNewList = true;
                    else
                        lostInvocationList = 1;
                }

                if(!needNewList)
                {
                    newInvList[curInvLen] = o;
                    for (int i = 0; i < oInvLen; ++i)
                    {
                        newInvList[curInvLen + i + 1] = oInvList[i];
                    }
                }
            }

            if (needNewList)
            {
                // start by 4, duplicate size.
                int len = newInvList == null ? 4 : newInvList.Length;
                while (len < newInvLen)
                    len *= 2;

                MulticastDelegate[] list = new MulticastDelegate[len];

                var curInvList = InvocationList;
                for(int i = 0; i < curInvLen; ++i)
                    list[i] = curInvList[i];

                list[curInvLen] = o;

                for (int i = 0; i < oInvLen; ++i)
                    list[curInvLen + 1 + i] = oInvList[i];

                newInvList = list;
            }

            return this.CloneWithNewInvocationList(newInvList, newInvLen);
        }

        protected override sealed Delegate RemoveImpl(Delegate other)
        {
            if (ReferenceEquals(other, this))
                return null;

            MulticastDelegate o = (MulticastDelegate)other;

            int idx = LastIndexOf(o);

            if (idx == -1)
                return this;

            var invListLen = InvocationListLength;
            var newNumDelegates = invListLen - o.InvocationListLength;

            if (newNumDelegates == 0)
                return null;

            if (newNumDelegates == 1)
            {
                if (idx == 0)
                    return InvocationList[invListLen - 1]; // keep the last delegate
                Debug.Assert(idx == 1);
                return WithoutInvocationList();            // keep the first delegate
            }

            int newInvListLen = newNumDelegates - 1;
            MulticastDelegate[] newInvList;
            MulticastDelegate head;

            var invList = InvocationList;

            if (idx == 0)
            {
                head = invList[o.InvocationListLength];
                newInvList = RemoveSliceFromInvocationList(invList, invListLen, 0, o.InvocationListLength + 1);
            }
            else
            {
                head = this;
                newInvList = RemoveSliceFromInvocationList(invList, invListLen, idx - 1, o.InvocationListLength + 1);
            }

            var ret = head.CloneWithNewInvocationList(newInvList, newInvListLen);

            if (newInvList != null && ReferenceEquals(newInvList, InvocationList))
            {
                // we cannot take ownerhip of the invocation list here as we
                // would overwrite existing extries at the next invocation of
                // CombineImpl
                ret.lostInvocationList = 1;
            }

            return ret;
        }

        public override Delegate[] GetInvocationList()
        {
            Delegate[] ret = new Delegate[1 + InvocationListLength];
            ret[0] = this.WithoutInvocationList();
            for (int i = 1; i <= InvocationListLength; ++i)
                ret[i] = InvocationList[i - 1];
            return ret;
        }

        /// <summary>
	    /// return the class instance or null, if this is a static delegate.
	    /// </summary>
	    public override object Target
	    {
	        get
	        {
                // we need to return the last Target from our invocation list.
                if (InvocationListLength > 0)
	            {
                    var del = InvocationList[InvocationListLength - 1];
	                return del.GetTargetImpl();
	            }

	            return GetTargetImpl();
            }
	    }

        internal override MethodInfo Method
        {
            get
            {
                // we need to return the last Method from our invocation list.
                if(InvocationListLength > 0)
                    return InvocationList[InvocationListLength - 1].GetMethodInfoImpl();
                return GetMethodInfoImpl();
            }
        }

        public override bool Equals(object other)
        {
            // we have to check for same type and same invocation list.
            var o = other as MulticastDelegate;

            if (o == null)
                return false;

            var invListLen = InvocationListLength;
            if (invListLen != o.InvocationListLength)
                return false;

            if (!EqualsWithoutInvocationList(o))
                return false;

            var oInvList = o.InvocationList;
            var invList = InvocationList;

            for (int i = 0; i < invListLen; ++i)
            {
                if(!invList[i].EqualsWithoutInvocationList(oInvList[i]))
                    return false;
            }
            return true;
        }

        public override int GetHashCode()
        {
            return GetHashCodeWithoutInvocationList() * 33 ^ InvocationListLength;
        }

        private static MulticastDelegate[] RemoveSliceFromInvocationList(MulticastDelegate[] invList, int invListLen, int idx, int length)
        {
            int newInvLen = invListLen - length;
            int trueInvListLen = invList.Length;

            bool canKeepList = newInvLen == idx && (trueInvListLen <= 4 || trueInvListLen/2 <= newInvLen);

            if(canKeepList)
                return invList;

            trueInvListLen = 4;
            while (trueInvListLen < newInvLen)
                trueInvListLen *= 2;

            MulticastDelegate[] newList = new MulticastDelegate[trueInvListLen];

            for (int i = 0; i < idx; ++i)
                newList[i] = invList[i];
            for (int i = idx + length, j = idx; j < newInvLen; ++i, ++j)
                newList[j] = invList[i];

            return newList;
        }

        /// <summary>
        /// Will return an index into [head] + tail, or -1 if not found
        /// </summary>
        private int LastIndexOf(MulticastDelegate o)
        {
            int oInvLen = o.InvocationListLength;
            var oInvList = o.InvocationList;
            var invList = InvocationList;

            // We need to start comparing from the end.

            // Mono's implementation uses the KMP algorithm, but at a first
            // glance this seems to be overkill for an invocation list. In the
            // typical usage scenario, 'o' will have no invocation list at all.
            // We stick to the naive implementation for now.
            int i = InvocationListLength - oInvLen;

            if (oInvLen == 0)
            {
                for(; i > 0; --i)
                {
                    if (o.EqualsWithoutInvocationList(invList[i - 1]))
                        return i;
                }
            }
            else
            {
                for (; i > 0; --i)
                {
                    if (!o.EqualsWithoutInvocationList(invList[i - 1]))
                        continue;

                    for (int j = 0; j < oInvLen; ++j)
                    {
                        if (!invList[i + j].EqualsWithoutInvocationList(oInvList[j]))
                            goto next_iteration;
                    }

                    // found it!
                    return i;

                    next_iteration:;
                }
            }

            // 0 = this
            return i < 0 || !o.EqualsWithoutInvocationList(this) ? -1 : 0;
        }

        [Inline, DexNative]
        private MulticastDelegate WithoutInvocationList()
        {
            if (InvocationListLength == 0) return this;
            return CloneWithNewInvocationList(null, 0);
        }
    }
}


text:
import {Component, Input, ViewEncapsulation} from "@angular/core";

@Component({
    moduleId: module.id,
    selector: "[path-item]",
    templateUrl: "path-item.component.html",
    encapsulation: ViewEncapsulation.None
})
export class PathItemComponent {

    @Input() path: string;

    public pathSegments(): string[] {
        let rval: string[] = this.path.split("/");
        if (rval[0] === "") {
            rval = rval.splice(1);
        }
        return rval;
    }

}


text:
@extends('layouts.admin')

@section('content')

        @include('ContentManager::partials.errormessage')

    @include('ContentManager::post.partials.form')

@endsection

@push('scripts')
@include('ContentManager::post.partials.scriptform')

@endpush


text:
/* =General
-------------------------------------------------------------- */
.cpac-divider {
  display: inline-block;
  width: 14px;
  height: 12px;
  background: transparent url(../images/square.png) no-repeat 50% 7px;
}
span.status-closed {
  color: red;
}
.actions #post-query-submit {
  float: left;
  vertical-align: middle;
  margin-bottom: 4px;
}
.tablenav.top .cpac-edit {
  top: 2px;
  display: inline-block;
  vertical-align: middle;
  float: left;
  margin-bottom: 4px;
}
body.edit-tags-php .tablenav.top .cpac-edit {
  float: none;
}
.cpac_status_yes {
  color: #46b450;
}
.cpac_status_no {
  color: #dc3232;
}
body.edit-php #delete_all {
  float: left;
  margin-right: 3px;
}
body.users-php .tablenav .actions a.add-new-h2 {
  float: none;
  vertical-align: middle !important;
  top: 2px !important;
}
@media screen and (max-width: 782px) {
  .tablenav.top .actions {
    display: block !important;
    margin-bottom: 4px;
  }
  .tablenav.top .actions * {
    display: none;
  }
  .tablenav.top .actions .cpac-edit {
    display: inline-block;
  }
}
body.upload-php .tablenav.top .cpac-edit {
  float: none;
}
/* =General Column
-------------------------------------------------------------- */
.cpac-inline-info {
  display: inline-block;
  border-radius: 3px;
  min-width: 8px;
  padding: 0 6px;
  min-height: 20px;
  background-color: #e9e9e9;
  text-align: center;
  margin-right: 7px;
  font-size: 11px;
  font-weight: bold;
}
.cpac-rounded {
  display: inline-block;
  border-radius: 10px;
  min-width: 8px;
  padding: 0 6px;
  height: 20px;
  background-color: #e0e0e0;
  text-align: center;
  margin-left: 7px;
  font-size: 12px;
}
.cpac-rounded.cpac-rounded-first {
  margin-left: 0;
}
.cpac-spacing {
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 4px;
}
.cpac-suffix {
  margin-left: 8px;
  color: #808080;
}
/* =Images Column
-------------------------------------------------------------- */
.cpac-column-value-image {
  display: inline-block;
  background: transparent;
  margin-right: 2px;
  overflow: hidden;
  max-width: 100%;
}
.rtl .cpac-column-value-image {
  margin-left: 2px;
  margin-right: 0;
}
.cpac-column-value-image img {
  display: block;
  margin: 0 auto;
}
.column-column-attachment img {
  padding-right: 5px;
  padding-bottom: 4px;
}
.rtl .column-column-attachment img {
  padding-left: 5px;
  padding-right: 0;
}
/* =Color Column
-------------------------------------------------------------- */
div.cpac-color {
  line-height: 26px;
}
div.cpac-color span {
  display: block;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  color: #ffffff;
  float: left;
  height: 16px;
  line-height: 16px;
  margin-right: 12px;
  min-width: 30px;
  overflow: hidden;
  padding: 4px 5px;
  font-size: 10px;
  font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
  min-width: 47px;
  text-align: center;
}
.rtl div.cpac-color span {
  float: right;
  margin-left: 12px;
  margin-right: 0;
}
/* =Available Sizes column
-------------------------------------------------------------- */
div.sizes span.not-available {
  color: #999;
}
/* =Actions column
-------------------------------------------------------------- */
.button.cpac-button-action {
  position: relative;
  text-indent: 9999px;
  margin-right: 4px;
  padding: 0 13px;
  overflow: hidden;
}
.button.cpac-button-action:before {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-indent: 0;
}
/* =qTip2
-------------------------------------------------------------- */
.cpac-tip {
  display: inline-block;
}
.qtip.qtip-tipsy {
  background: rgba(0, 0, 0, 0.75);
  font-weight: normal;
  min-width: 25px;
}


text:
//
// Created by Mark van der Broek on 08/03/2017.
//

/**
 * @brief Constructor
 *
 * @param [in] env          Environment pointer
 */

#include "solution.ih"

Solution::Solution(Env *env)
:
    d_env(env)
{}


text:
namespace treeDiM.StackBuilder.Desktop
{
    partial class DockContentAnalysisCylinderCase
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DockContentAnalysisCylinderCase));
            ((System.ComponentModel.ISupportInitialize)(this.graphCtrlSolution)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainerHoriz)).BeginInit();
            this.splitContainerHoriz.Panel1.SuspendLayout();
            this.splitContainerHoriz.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainerVert)).BeginInit();
            this.splitContainerVert.Panel1.SuspendLayout();
            this.splitContainerVert.Panel2.SuspendLayout();
            this.splitContainerVert.SuspendLayout();
            this.SuspendLayout();
            //
            // graphCtrlSolution
            //
            resources.ApplyResources(this.graphCtrlSolution, "graphCtrlSolution");
            //
            // splitContainerHoriz
            //
            resources.ApplyResources(this.splitContainerHoriz, "splitContainerHoriz");
            //
            // splitContainerHoriz.Panel1
            //
            resources.ApplyResources(this.splitContainerHoriz.Panel1, "splitContainerHoriz.Panel1");
            //
            // splitContainerHoriz.Panel2
            //
            resources.ApplyResources(this.splitContainerHoriz.Panel2, "splitContainerHoriz.Panel2");
            //
            // splitContainerVert
            //
            resources.ApplyResources(this.splitContainerVert, "splitContainerVert");
            //
            // splitContainerVert.Panel1
            //
            resources.ApplyResources(this.splitContainerVert.Panel1, "splitContainerVert.Panel1");
            //
            // splitContainerVert.Panel2
            //
            resources.ApplyResources(this.splitContainerVert.Panel2, "splitContainerVert.Panel2");
            //
            // cbInterlayer
            //
            resources.ApplyResources(this.cbInterlayer, "cbInterlayer");
            //
            // gridSolutions
            //
            resources.ApplyResources(this.gridSolution, "gridSolutions");
            //
            // DockContentAnalysisCylinderCase
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "DockContentAnalysisCylinderCase";
            this.ShowInTaskbar = false;
            ((System.ComponentModel.ISupportInitialize)(this.graphCtrlSolution)).EndInit();
            this.splitContainerHoriz.Panel1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainerHoriz)).EndInit();
            this.splitContainerHoriz.ResumeLayout(false);
            this.splitContainerVert.Panel1.ResumeLayout(false);
            this.splitContainerVert.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainerVert)).EndInit();
            this.splitContainerVert.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
    }
}


text:
import * as THREE from "three";

import * as Geo from "../geo/Geo";

import { RenderMode } from "./RenderMode";
import { ViewportSize } from "./interfaces/ViewportSize";

import { Camera } from "../geo/Camera";
import { Spatial } from "../geo/Spatial";
import { Transform } from "../geo/Transform";
import { ViewportCoords } from "../geo/ViewportCoords";
import { State } from "../state/State";
import { AnimationFrame } from "../state/interfaces/AnimationFrame";
import { EulerRotation } from "../state/interfaces/EulerRotation";
import { isSpherical } from "../geo/Geo";
import { MathUtils, Matrix3, Quaternion, Vector2, Vector3 } from "three";

export class RenderCamera {
    private _spatial: Spatial;
    private _viewportCoords: ViewportCoords;

    private _alpha: number;
    private _stateTransitionAlpha: number;
    private _stateTransitionFov: number;
    private _renderMode: RenderMode;
    private _zoom: number;
    private _frameId: number;

    private _size: ViewportSize;

    private _camera: Camera;
    private _perspective: THREE.PerspectiveCamera;

    private _rotation: EulerRotation;

    private _changed: boolean;
    private _changedForFrame: number;

    private _currentImageId: string;
    private _previousImageId: string;

    private _currentSpherical: boolean;
    private _previousSpherical: boolean;

    private _state: State;

    private _currentProjectedPoints: number[][];
    private _previousProjectedPoints: number[][];

    private _currentFov: number;
    private _previousFov: number;

    private _currentCameraUp: Vector3;
    private _previousCameraUp: Vector3;

    private _currentTransformUp: Vector3;
    private _previousTransformUp: Vector3;

    private _currentTransformForward: Vector3;
    private _previousTransformForward: Vector3;

    private _initialFov: number;

    constructor(
        elementWidth: number,
        elementHeight: number,
        renderMode: RenderMode) {

        this._spatial = new Spatial();
        this._viewportCoords = new ViewportCoords();

        this._size = { width: elementWidth, height: elementHeight };

        this._initialFov = 60;

        this._alpha = -1;
        this._stateTransitionAlpha = -1;
        this._stateTransitionFov = -1;
        this._renderMode = renderMode;
        this._zoom = 0;

        this._frameId = -1;

        this._changed = false;
        this._changedForFrame = -1;

        this._currentImageId = null;
        this._previousImageId = null;

        this._currentSpherical = false;
        this._previousSpherical = false;

        this._state = null;

        this._currentProjectedPoints = [];
        this._previousProjectedPoints = [];

        this._currentFov = this._initialFov;
        this._previousFov = this._initialFov;

        this._camera = new Camera();

        this._currentCameraUp = new Vector3();
        this._previousCameraUp = new Vector3();

        this._currentTransformUp = new Vector3();
        this._previousTransformUp = new Vector3();

        this._currentTransformForward = new Vector3();
        this._previousTransformForward = new Vector3();

        this._perspective = new THREE.PerspectiveCamera(
            this._initialFov,
            this._computeAspect(elementWidth, elementHeight),
            0.1,
            10000);
        this._perspective.position.copy(this._camera.position);
        this._perspective.up.copy(this._camera.up);
        this._perspective.lookAt(this._camera.lookat);
        this._perspective.updateMatrixWorld(true);

        this._perspective.matrixAutoUpdate = false;

        this._rotation = { phi: 0, theta: 0 };
    }

    public get alpha(): number {
        return this._alpha;
    }

    public get camera(): Camera {
        return this._camera;
    }

    public get changed(): boolean {
        return this._frameId === this._changedForFrame;
    }

    public get frameId(): number {
        return this._frameId;
    }

    public get perspective(): THREE.PerspectiveCamera {
        return this._perspective;
    }

    public get renderMode(): RenderMode {
        return this._renderMode;
    }

    public get rotation(): EulerRotation {
        return this._rotation;
    }

    public get zoom(): number {
        return this._zoom;
    }

    public get size(): ViewportSize {
        return this._size;
    }

    public getTilt(): number {
        return 90 - this._spatial.radToDeg(this._rotation.theta);
    }

    public fovToZoom(fov: number): number {
        fov = Math.min(90, Math.max(0, fov));

        const currentFov = this._computeCurrentFov(0);
        const actualFov = this._alpha === 1 ?
            currentFov :
            this._interpolateFov(
                currentFov,
                this._computePreviousFov(0),
                this._alpha);

        const y0 = Math.tan(actualFov / 2 * Math.PI / 180);
        const y1 = Math.tan(fov / 2 * Math.PI / 180);

        const zoom = Math.log(y0 / y1) / Math.log(2);

        return zoom;
    }

    public setFrame(frame: AnimationFrame): void {
        const state = frame.state;

        if (state.state !== this._state) {
            this._state = state.state;
            if (this._state !== State.Custom) {
                this.setRenderMode(this._renderMode);
                this.setSize(this._size);
            }
            if (this._state === State.Earth) {
                const y = this._fovToY(this._perspective.fov, this._zoom);
                this._stateTransitionFov = this._yToFov(y, 0);
            }

            this._changed = true;
        }

        const currentImageId = state.currentImage.id;
        const previousImageId = !!state.previousImage ? state.previousImage.id : null;

        if (currentImageId !== this._currentImageId || this._changed) {
            this._currentImageId = currentImageId;
            this._currentSpherical = isSpherical(state.currentTransform.cameraType);
            this._currentProjectedPoints = this._computeProjectedPoints(state.currentTransform);
            this._currentCameraUp.copy(state.currentCamera.up);
            this._currentTransformUp.copy(state.currentTransform.upVector());
            this._currentTransformForward.copy(
                new Vector3().fromArray(
                    state.currentTransform.unprojectSfM([0, 0], 10))
                    .sub(
                        new Vector3().fromArray(
                            state.currentTransform.
                                unprojectSfM([0, 0], 0))));

            this._changed = true;
        }

        if (previousImageId !== this._previousImageId) {
            this._previousImageId = previousImageId;
            this._previousSpherical =
                isSpherical(state.previousTransform.cameraType);
            this._previousProjectedPoints = this._computeProjectedPoints(state.previousTransform);
            this._previousCameraUp.copy(state.previousCamera.up);
            this._previousTransformUp.copy(state.previousTransform.upVector());
            this._previousTransformForward.copy(
                new Vector3().fromArray(
                    state.previousTransform.unprojectSfM([0, 0], 10))
                    .sub(
                        new Vector3().fromArray(
                            state.previousTransform.
                                unprojectSfM([0, 0], 0))));

            this._changed = true;
        }

        const zoom = state.zoom;
        if (zoom !== this._zoom) {
            this._changed = true;
        }

        const camera = state.camera;

        if (this._changed) {
            this._currentFov = this._computeCurrentFov(zoom);
            this._previousFov = this._computePreviousFov(zoom);
        }

        const alpha = state.alpha;
        const sta = state.stateTransitionAlpha;
        if (this._changed ||
            alpha !== this._alpha ||
            sta !== this._stateTransitionAlpha) {

            this._alpha = alpha;
            this._stateTransitionAlpha = sta;

            switch (this._state) {
                case State.Earth: {
                    const startFov = this._stateTransitionFov;
                    const endFov = this._focalToFov(state.camera.focal);
                    const fov = MathUtils.lerp(startFov, endFov, sta);
                    const y = this._fovToY(fov, 0);
                    this._perspective.fov = this._yToFov(y, zoom);
                    break;
                }
                case State.Custom:
                    break;
                default:
                    this._perspective.fov =
                        this._interpolateFov(
                            this._currentFov,
                            this._previousFov,
                            this._alpha);
                    this._changed = true;
                    break;
            }

            this._zoom = zoom;

            if (this._state !== State.Custom) {
                this._perspective.updateProjectionMatrix();
            }
        }

        if (this._camera.diff(camera) > 1e-9) {
            this._camera.copy(camera);

            this._rotation = this._computeRotation(camera);

            this._perspective.up.copy(camera.up);
            this._perspective.position.copy(camera.position);

            // Workaround for shaking camera
            this._perspective.matrixAutoUpdate = true;
            this._perspective.lookAt(camera.lookat);
            this._perspective.matrixAutoUpdate = false;

            this._perspective.updateMatrix();
            this._perspective.updateMatrixWorld(false);

            this._changed = true;
        }

        this._setFrameId(frame.id);
    }

    public setProjectionMatrix(matrix: number[]): void {
        this._perspective.fov = this._focalToFov(matrix[5] / 2);
        this._perspective.projectionMatrix.fromArray(matrix);
        this._perspective.projectionMatrixInverse
            .copy(this._perspective.projectionMatrix)
            .invert();

        this._changed = true;
    }

    public setRenderMode(renderMode: RenderMode): void {
        this._renderMode = renderMode;

        if (this._state === State.Custom) {
            return;
        }

        this._perspective.fov = this._computeFov();
        this._perspective.updateProjectionMatrix();

        this._changed = true;
    }

    public setSize(size: ViewportSize): void {
        this._size = size;

        if (this._state === State.Custom) {
            return;
        }

        this._perspective.aspect = this._computeAspect(size.width, size.height);
        this._perspective.fov = this._computeFov();
        this._perspective.updateProjectionMatrix();

        this._changed = true;
    }

    private _computeAspect(elementWidth: number, elementHeight: number): number {
        return elementWidth === 0 ? 0 : elementWidth / elementHeight;
    }

    private _computeUpRotation(up: Vector3, refForward: Vector3, refUp: Vector3): number {
        const right = new Vector3().crossVectors(refForward, refUp).normalize();
        const normal = new Vector3().crossVectors(refUp, right).normalize();

        const xzFromNormal = new Quaternion()
            .setFromUnitVectors(normal, new Vector3(0, 1, 0));
        const upXz = up.clone().applyQuaternion(xzFromNormal);
        const refUpXz = refUp.clone().applyQuaternion(xzFromNormal);

        const upRad = Math.acos(new Vector2(upXz.x, upXz.z).normalize().x);
        const refUpRad = Math.acos(new Vector2(refUpXz.x, refUpXz.z).normalize().x);

        return refUpRad - upRad;
    }

    private _computeCurrentFov(zoom: number): number {
        if (this._perspective.aspect === 0) {
            return 0;
        }

        if (!this._currentImageId) {
            return this._initialFov;
        }

        return this._currentSpherical ?
            this._yToFov(1, zoom) :
            this._computeVerticalFov(
                this._currentProjectedPoints,
                this._renderMode,
                zoom,
                this.perspective.aspect,
                this._computeUpRotation(
                    this._currentTransformUp,
                    this._currentTransformForward,
                    this._currentCameraUp));
    }

    private _computeFov(): number {
        this._currentFov = this._computeCurrentFov(this._zoom);
        this._previousFov = this._computePreviousFov(this._zoom);

        return this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
    }

    private _computePreviousFov(zoom: number): number {
        if (this._perspective.aspect === 0) {
            return 0;
        }

        if (!this._currentImageId) {
            return this._initialFov;
        }

        return !this._previousImageId ?
            this._currentFov :
            this._previousSpherical ?
                this._yToFov(1, zoom) :
                this._computeVerticalFov(
                    this._previousProjectedPoints,
                    this._renderMode,
                    zoom,
                    this.perspective.aspect,
                    this._computeUpRotation(
                        this._previousTransformUp,
                        this._previousTransformForward,
                        this._previousCameraUp));
    }

    private _computeProjectedPoints(transform: Transform): number[][] {
        const vertices = [[0, 0], [1, 0]];
        const directions = [[1, 0], [0, 1]];
        const pointsPerLine = 50;

        return Geo.computeProjectedPoints(
            transform,
            vertices,
            directions,
            pointsPerLine,
            this._viewportCoords);
    }

    private _computeRequiredVerticalFov(
        projectedPoint: number[],
        zoom: number,
        aspect: number): number {
        const maxY = Math.max(
            Math.abs(projectedPoint[0]) / aspect,
            Math.abs(projectedPoint[1]));

        return this._yToFov(maxY, zoom);
    }

    private _computeRotation(camera: Camera): EulerRotation {
        let direction: THREE.Vector3 = camera.lookat.clone().sub(camera.position);
        let up: THREE.Vector3 = camera.up.clone();

        let phi = this._spatial.azimuthal(direction.toArray(), up.toArray());
        let theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);

        return { phi: phi, theta: theta };
    }

    private _computeVerticalFov(
        projectedPoints: number[][],
        renderMode: RenderMode,
        zoom: number,
        aspect: number,
        theta: number): number {

        const sinTheta = Math.sin(theta);
        const cosTheta = Math.cos(theta);

        const fovs = projectedPoints
            .map(
                ([x, y]: number[]): number => {
                    const rotatedPoint = [
                        cosTheta * x - sinTheta * y,
                        sinTheta * x + cosTheta * y,
                    ];
                    return this._computeRequiredVerticalFov(
                        rotatedPoint,
                        zoom,
                        aspect);
                });

        const vFovFill = Math.min(...fovs) * 0.995;
        if (renderMode === RenderMode.Fill) {
            return vFovFill;
        }

        const vFovLetterbox = Math.max(...fovs);
        const hFovLetterbox = aspect * vFovLetterbox;

        const fovCoeff = 1.25;
        const hFovFill = aspect * vFovFill;
        const hFovMax = fovCoeff * hFovFill;

        let vFov = vFovLetterbox;
        if (hFovLetterbox > hFovMax) {
            vFov *= hFovMax / hFovLetterbox;
        }

        const fovMax = 135;
        const vFovMax = aspect > 2 ? vFovFill : fovCoeff * vFovFill;
        vFov = Math.min(vFov, vFovMax, fovMax);
        vFov = Math.max(vFov, vFovFill);

        return vFov;
    }

    private _yToFov(y: number, zoom: number): number {
        return 2 * Math.atan(y / Math.pow(2, zoom)) * 180 / Math.PI;
    }

    private _focalToFov(focal: number): number {
        return 2 * Math.atan2(1, 2 * focal) * 180 / Math.PI;
    }

    private _fovToY(fov: number, zoom: number): number {
        return Math.pow(2, zoom) * Math.tan(Math.PI * fov / 360);
    }

    private _interpolateFov(v1: number, v2: number, alpha: number): number {
        return alpha * v1 + (1 - alpha) * v2;
    }

    private _setFrameId(frameId: number): void {
        this._frameId = frameId;

        if (this._changed) {
            this._changed = false;
            this._changedForFrame = frameId;
        }
    }
}


text:
package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal"

import (
	"context"
	"errors"
	"fmt"
	"net"

	"github.com/jaegertracing/jaeger/cmd/collector/app/sampling"
	"github.com/jaegertracing/jaeger/cmd/collector/app/sampling/strategystore"
	"github.com/jaegertracing/jaeger/proto-gen/api_v2"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/config/configgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/reflection"
)

var _ component.Component = (*SamplingGRPCServer)(nil)

var errGRPCServerNotRunning = errors.New("gRPC server is not running")

type grpcServer interface {
	Serve(lis net.Listener) error
	GracefulStop()
	Stop()
}

// NewGRPC returns a new sampling gRPC Server.
func NewGRPC(
	telemetry component.TelemetrySettings,
	settings configgrpc.GRPCServerSettings,
	strategyStore strategystore.StrategyStore,
) (*SamplingGRPCServer, error) {
	if strategyStore == nil {
		return nil, errMissingStrategyStore
	}

	return &SamplingGRPCServer{
		telemetry:     telemetry,
		settings:      settings,
		strategyStore: strategyStore,
	}, nil
}

// SamplingGRPCServer implements component.Component to make the life cycle easy to manage.
type SamplingGRPCServer struct {
	telemetry     component.TelemetrySettings
	settings      configgrpc.GRPCServerSettings
	strategyStore strategystore.StrategyStore

	grpcServer grpcServer
}

func (s *SamplingGRPCServer) Start(_ context.Context, host component.Host) error {
	server, err := s.settings.ToServer(host, s.telemetry)
	if err != nil {
		return err
	}
	reflection.Register(server)
	s.grpcServer = server

	api_v2.RegisterSamplingManagerServer(server, sampling.NewGRPCHandler(s.strategyStore))

	healthServer := health.NewServer()
	healthServer.SetServingStatus("jaeger.api_v2.SamplingManager", grpc_health_v1.HealthCheckResponse_SERVING)
	grpc_health_v1.RegisterHealthServer(server, healthServer)

	listener, err := s.settings.ToListener()
	if err != nil {
		return fmt.Errorf("failed to listen on gRPC port: %w", err)
	}

	go func() {
		if err := s.grpcServer.Serve(listener); err != nil {
			s.telemetry.Logger.Error("could not launch gRPC service", zap.Error(err))
		}
	}()

	return nil
}

// Shutdown tries to terminate connections gracefully as long as the passed context is valid.
func (s *SamplingGRPCServer) Shutdown(ctx context.Context) error {
	if s.grpcServer == nil {
		return errGRPCServerNotRunning
	}

	ch := make(chan struct{})
	go func() {
		s.grpcServer.GracefulStop()
		ch <- struct{}{}
	}()

	select {
	case <-ctx.Done():
		s.grpcServer.Stop()
	case <-ch:
	}

	return nil
}


text:
"""
Views which allow users to create and activate accounts.

"""

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from registration.models import RegistrationProfile
from . import forms
from apocalypse.my_notes import models as my_notes_models
from apocalypse.highlights import models as highlights_models

import logging
logger = logging.getLogger('registration')

def activate(request, activation_key,
             template_name='registration/activate.html',
             extra_context=None):
    """
    Activate a ``User``'s account from an activation key, if their key
    is valid and hasn't expired.

    By default, use the template ``registration/activate.html``; to
    change this, pass the name of a template as the keyword argument
    ``template_name``.

    **Required arguments**

    ``activation_key``
       The activation key to validate and use for activating the
       ``User``.

    **Optional arguments**

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``template_name``
        A custom template to use.

    **Context:**

    ``account``
        The ``User`` object corresponding to the account, if the
        activation was successful. ``False`` if the activation was not
        successful.

    ``expiration_days``
        The number of days for which activation keys stay valid after
        registration.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/activate.html or ``template_name`` keyword argument.

    """
    activation_key = activation_key.lower() # Normalize before trying anything with it.
    account = RegistrationProfile.objects.activate_user(activation_key)
    if account:
        # Move the anonymous user's stuff over to the new activated account.
        user = request.user
        user.get_profile().user = account
        logger.info('Old user: %s', user)
        logger.info('New user: %s', account)
        for note in my_notes_models.PassageNote.objects.filter(user=user):
            logger.info("Found note: %s", note)
            note.user = account
            note.save()
        for hl in highlights_models.Highlight.objects.filter(user=user):
            logger.info("Found highlight: %s", hl)
            hl.user = account
            hl.save()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'account': account,
                                'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
                              context_instance=context)

def register(request, success_url=None,
             form_class=forms.RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**

    None.

    **Optional arguments**

    ``form_class``
        The form class to use for registration.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.

    ``success_url``
        The URL to redirect to on successful registration.

    ``template_name``
        A custom template to use.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    context = RequestContext(request)
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        form.request = request
        if form.is_valid():
            new_user = form.save(profile_callback=profile_callback)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return render_to_response('registration/registration_complete.html',
                                      {'email': form.cleaned_data['email'],},
                                      context_instance=context)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)


text:
namespace NServiceBus.AcceptanceTests.DelayedDelivery
{
    using System;
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using Extensibility;
    using Features;
    using NServiceBus;
    using NServiceBus.Pipeline;
    using NUnit.Framework;
    using Persistence;
    using ScenarioDescriptors;
    using Timeout.Core;
    using Conventions = AcceptanceTesting.Customization.Conventions;

    public class When_timeout_dispatch_fails : NServiceBusAcceptanceTest
    {
        [Test]
        public Task Should_retry_and_move_to_error()
        {
            return Scenario.Define<Context>()
                .WithEndpoint<Endpoint>(b =>
                    b.DoNotFailOnErrorMessages()
                        .When((bus, c) =>
                        {
                            var options = new SendOptions();
                            options.DelayDeliveryWith(VeryLongTimeSpan);
                            options.RouteToThisEndpoint();
                            options.SetMessageId(c.TestRunId.ToString());

                            return bus.Send(new MyMessage(), options);
                        }))
                .Done(c => c.FailedTimeoutMovedToError)
                .Repeat(r => r.For<AllTransportsWithoutNativeDeferral>())
                .Should(c =>
                {
                    Assert.IsFalse(c.DelayedMessageDeliveredToHandler, "Message was unexpectedly delivered to the handler");
                    Assert.IsTrue(c.FailedTimeoutMovedToError, "Message should have been moved to the error queue");
                })
                .Run();
        }

        static readonly TimeSpan VeryLongTimeSpan = TimeSpan.FromMinutes(10);
        public class Context : ScenarioContext
        {
            public bool FailedTimeoutMovedToError { get; set; }
            public bool DelayedMessageDeliveredToHandler { get; set; }
        }

        public class Endpoint : EndpointConfigurationBuilder
        {
            public Endpoint()
            {
                EndpointSetup<DefaultServer>(config =>
                {
                    config.EnableFeature<TimeoutManager>();
                    config.UsePersistence<FakeTimeoutPersistence>();
                    config.SendFailedMessagesTo(Conventions.EndpointNamingConvention(typeof(Endpoint)));
                    config.RegisterComponents(c => c.ConfigureComponent<FakeTimeoutStorage>(DependencyLifecycle.SingleInstance));
                    config.Pipeline.Register<BehaviorThatLogsControlMessageDelivery.Registration>();
                });
            }

            class Handler : IHandleMessages<MyMessage>
            {
                public Context TestContext { get; set; }

                public Task Handle(MyMessage message, IMessageHandlerContext context)
                {
                    TestContext.DelayedMessageDeliveredToHandler = true;
                    return Task.FromResult(0);
                }
            }

            class FakeTimeoutPersistence : PersistenceDefinition
            {
                public FakeTimeoutPersistence()
                {
                    Supports<StorageType.Timeouts>(s => { });
                }
            }

            class FakeTimeoutStorage : IQueryTimeouts, IPersistTimeouts
            {
                public Context TestContext { get; set; }

                public Task Add(TimeoutData timeout, ContextBag context)
                {
                    if (TestContext.TestRunId.ToString() == timeout.Headers[Headers.MessageId])
                    {
                        timeout.Id = TestContext.TestRunId.ToString();
                        timeout.Time = DateTime.UtcNow;

                        timeoutData = timeout;
                    }

                    return Task.FromResult(0);
                }

                public Task<bool> TryRemove(string timeoutId, ContextBag context)
                {
                    throw new NotImplementedException();
                }

                public Task<TimeoutData> Peek(string timeoutId, ContextBag context)
                {
                    if (timeoutId != TestContext.TestRunId.ToString())
                    {
                        throw new ArgumentException("The timeoutId is different from one registered in the test context", "timeoutId");
                    }

                    throw new Exception("Ooops. Timeout storage went bust");
                }

                public Task RemoveTimeoutBy(Guid sagaId, ContextBag context)
                {
                    throw new NotImplementedException();
                }

                public Task<TimeoutsChunk> GetNextChunk(DateTime startSlice)
                {
                    var timeouts = timeoutData != null
                        ? new[]
                        {
                            new TimeoutsChunk.Timeout(timeoutData.Id, timeoutData.Time)
                        }
                        : new TimeoutsChunk.Timeout[0];

                    return Task.FromResult(new TimeoutsChunk(timeouts, DateTime.UtcNow + TimeSpan.FromSeconds(10)));
                }

                TimeoutData timeoutData;
            }

            class BehaviorThatLogsControlMessageDelivery : IBehavior<ITransportReceiveContext, ITransportReceiveContext>
            {
                public Context TestContext { get; set; }

                public Task Invoke(ITransportReceiveContext context, Func<ITransportReceiveContext, Task> next)
                {
                    if (context.Message.Headers.ContainsKey(Headers.ControlMessageHeader) &&
                        context.Message.Headers["Timeout.Id"] == TestContext.TestRunId.ToString())
                    {
                        TestContext.FailedTimeoutMovedToError = true;
                        return Task.FromResult(0);
                    }

                    return next(context);
                }

                public class Registration : RegisterStep
                {
                    public Registration() : base("BehaviorThatLogsControlMessageDelivery", typeof(BehaviorThatLogsControlMessageDelivery), "BehaviorThatLogsControlMessageDelivery")
                    {
                    }
                }
            }
        }

        public class MyMessage : IMessage
        {
        }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/talent/v4/event_service.proto

namespace GPBMetadata\Google\Cloud\Talent\V4;

class EventService
{
    public static $is_initialized = false;

    public static function initOnce() {
        $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();

        if (static::$is_initialized == true) {
          return;
        }
        \GPBMetadata\Google\Api\Annotations::initOnce();
        \GPBMetadata\Google\Api\Client::initOnce();
        \GPBMetadata\Google\Api\FieldBehavior::initOnce();
        \GPBMetadata\Google\Api\Resource::initOnce();
        \GPBMetadata\Google\Cloud\Talent\V4\Event::initOnce();
        $pool->internalAddGeneratedFile(
            '
•
*google/cloud/talent/v4/event_service.protogoogle.cloud.talent.v4google/api/client.protogoogle/api/field_behavior.protogoogle/api/resource.proto"google/cloud/talent/v4/event.proto"Ž
CreateClientEventRequest2
parent (	B"àAúA
jobs.googleapis.com/Tenant>
client_event (2#.google.cloud.talent.v4.ClientEventBàA2Å
EventServiceÆ
CreateClientEvent0.google.cloud.talent.v4.CreateClientEventRequest#.google.cloud.talent.v4.ClientEvent"Z'Óä">"./v4/{parent=projects/*/tenants/*}/clientEvents:client_eventÚAparent,client_eventlÊAjobs.googleapis.comÒAShttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/jobsBu
com.google.cloud.talent.v4BEventServiceProtoPZ<google.golang.org/genproto/googleapis/cloud/talent/v4;talent¢CTSbproto3'
        , true);

        static::$is_initialized = true;
    }
}


text:
Simple Ruby wrapper for the docker compose cli

## Installation

You need to have the docker compose cli installed.

Add this line to your application's Gemfile:

```ruby
gem 'docker_compose_ruby'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install docker_compose_ruby

## Usage

Set the path to your docker file.

    $ DockerCompose.set_yaml_path('/path/to/docker-compose.yml')

Set the project name (if no name is set it will be tthe name of the compose file's directory).

    $ DockerCompose.set_project_name('test_project')

Up the compose project containers.

    $ DockerCompose.up

Delete the compose project containers.

    $ DockerCompose.delete

Stop the compose project containers.

    $ DockerCompose.stop

Start the compose project containers.

    $ DockerCompose.start

## Development

I wanted something to use in a project I'm building, and there really wasn't anything out there that gives me the simplicity of the cli, but without having to repeat myself.

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/docker_compose_ruby.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
require 'brainstem/api_docs/formatters/abstract_formatter'

#
# Responsible for formatting each endpoint.
#
module Brainstem
  module ApiDocs
    module Formatters
      module OpenApiSpecification
        module Version2
          class EndpointCollectionFormatter < AbstractFormatter

            attr_accessor :endpoint_collection,
                          :output

            def initialize(endpoint_collection, options = {})
              self.endpoint_collection = endpoint_collection
              self.output              = {}

              super options
            end

            def call
              format_endpoints!
            end

            #####################################################################
            private
            #####################################################################

            def documentable_endpoints
              endpoint_collection
                .only_documentable
            end

            def format_endpoints!
              documentable_endpoints.each do |endpoint|
                formatted_endpoint = endpoint.formatted_as(:oas_v2)
                next if formatted_endpoint.blank?

                if (common_keys = output.keys & formatted_endpoint.keys).present?
                  common_keys.each do |key|
                    output[key].merge!(formatted_endpoint[key])
                  end
                else
                  output.merge!(formatted_endpoint)
                end
              end

              output
            end
          end
        end
      end
    end
  end
end

Brainstem::ApiDocs::FORMATTERS[:endpoint_collection][:oas_v2] =
  Brainstem::ApiDocs::Formatters::OpenApiSpecification::Version2::EndpointCollectionFormatter.method(:call)


text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * $Id$
 *
 */

/**
 * This class generates form components for Location Type
 *
 */
class CRM_Admin_Form_PreferencesDate extends CRM_Admin_Form {

  /**
   * Build the form object.
   *
   * @return void
   */
  public function buildQuickForm() {

    parent::buildQuickForm();

    if ($this->_action & CRM_Core_Action::DELETE) {
      return;
    }

    $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_PreferencesDate');

    $this->applyFilter('__ALL__', 'trim');
    $name = &$this->add('text',
      'name',
      ts('Name'),
      $attributes['name'],
      TRUE
    );
    $name->freeze();

    $this->add('text', 'description', ts('Description'), $attributes['description'], FALSE);
    $this->add('text', 'start', ts('Start Offset'), $attributes['start'], TRUE);
    $this->add('text', 'end', ts('End Offset'), $attributes['end'], TRUE);

    $formatType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate', $this->_id, 'name');

    if ($formatType == 'creditCard') {
      $this->add('text', 'date_format', ts('Format'), $attributes['date_format'], TRUE);
    }
    else {
      $this->add('select', 'date_format', ts('Format'),
        array('' => ts('- default input format -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
      );
      $this->add('select', 'time_format', ts('Time'),
        array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
      );
    }
    $this->addRule('start', ts('Value must be an integer.'), 'integer');
    $this->addRule('end', ts('Value must be an integer.'), 'integer');

    // add a form rule
    $this->addFormRule(array('CRM_Admin_Form_PreferencesDate', 'formRule'));
  }

  /**
   * Global validation rules for the form.
   *
   * @param array $fields
   *   Posted values of the form.
   *
   * @return array
   *   if errors then list of errors to be posted back to the form,
   *                  true otherwise
   */
  public static function formRule($fields) {
    $errors = array();

    if ($fields['name'] == 'activityDateTime' && !$fields['time_format']) {
      $errors['time_format'] = ts('Time is required for this format.');
    }

    return empty($errors) ? TRUE : $errors;
  }

  /**
   * Process the form submission.
   *
   *
   * @return void
   */
  public function postProcess() {
    if (!($this->_action & CRM_Core_Action::UPDATE)) {
      CRM_Core_Session::setStatus(ts('Preferences Date Options can only be updated'), ts('Sorry'), 'error');
      return;
    }

    // store the submitted values in an array
    $params = $this->controller->exportValues($this->_name);

    // action is taken depending upon the mode
    $dao = new CRM_Core_DAO_PreferencesDate();
    $dao->id = $this->_id;
    $dao->description = $params['description'];
    $dao->start = $params['start'];
    $dao->end = $params['end'];
    $dao->date_format = $params['date_format'];
    $dao->time_format = $params['time_format'];

    $dao->save();

    // Update dynamic js to reflect new date settings
    CRM_Core_Resources::singleton()->resetCacheCode();

    CRM_Core_Session::setStatus(ts("The date type '%1' has been saved.",
      array(1 => $params['name'])
    ), ts('Saved'), 'success');
  }

}


text:
const Playlist = require('./playlist');
const axios = require('axios');
const auth = require('../auth.json');
const YtSong = require('./ytsong');

module.exports = class YtPlayList extends Playlist {

    constructor(requester, type) {
        super(requester, type);
    }

    getSongs(link) {
        this.link = link;
        try{
            let regex = /list=([\d\w]+)/;
            this.playlistId = this.link.match(regex)[1];
        } catch(err) {
            return Promise.reject(err);
        }
        return new Promise((resolve, reject) => {
            let options = {
                url: '/youtube/v3/playlistItems',
                baseURL: 'https://www.googleapis.com',
                params: {
                    key: auth.yt_key,
                    part: 'contentDetails',
                    playlistId: this.playlistId,
                    maxResults: 10
                },
                responseType: 'json',
                validateStatus: (status) => {
                    if(status !== 200) console.log(`received ${status} from soundcloud resolve`);
                    return status >= 200 && status < 300;
                }
            };

            axios(options).then(resp => {
                let tracks = resp.data.items;
                tracks = tracks.map(item => new YtSong(`https://www.youtube.com/watch?v=${item.contentDetails.videoId}`, this.requester, this.type));
                return resolve(tracks);
            }).catch(err => {
                return reject(err);
            });
        });
    }
};


text:
package jp.bizreach.twitter.app.action;

import org.seasar.struts.annotation.Execute;

public class FooAction {
    public Integer id;

    //    @Execute(validator = false)
    //    public String index() {
    //        if (id == null) {
    //            id = 9999;
    //        }
    //        return "/index.jsp";
    //    }

    @Execute(validator = false, urlPattern = "{id}")
    public String bar() {
        if (id == null) {
            id = 9999;
        }
        return "/index.jsp";
    }
}


text:
    <title>Event</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 Delegate tests

Open the console, and verify that interacting with the elements logs output as expected by their descriptions.

Basic binding

I can be clicked unlimited times

I can be clicked unlimited times

I don't have a <a> so am unclickable

I can be clicked 5 times

Multiple events

Bind two events, one to "li a" and one to "li.foo a", give one element the foo class, but not the other.

Bound to li, triggers 1 event

Bound to li.foo, triggers both events

Blur/Focus events

This triggers on focus: <input placeholder='focus me'>

This triggers on blur: <input placeholder='blur me'>


text:
#ifndef ORC_RLEV2UTIL_HH
#define ORC_RLEV2UTIL_HH

#include "RLEv2.hh"

namespace orc {
  extern const uint8_t FBSToBitWidthMap[FixedBitSizes::SIZE];
  extern const uint8_t ClosestFixedBitsMap[65];
  extern const uint8_t ClosestAlignedFixedBitsMap[65];
  extern const uint8_t BitWidthToFBSMap[65];

  // The input n must be less than FixedBitSizes::SIZE.
  inline uint32_t decodeBitWidth(uint32_t n) {
    return FBSToBitWidthMap[n];
  }

  inline uint32_t getClosestFixedBits(uint32_t n) {
    if (n <= 64) {
      return ClosestFixedBitsMap[n];
    } else {
      return 64;
    }
  }

  inline uint32_t getClosestAlignedFixedBits(uint32_t n) {
    if (n <= 64) {
      return ClosestAlignedFixedBitsMap[n];
    } else {
      return 64;
    }
  }

  inline uint32_t encodeBitWidth(uint32_t n) {
    if (n <= 64) {
      return BitWidthToFBSMap[n];
    } else {
      return FixedBitSizes::SIXTYFOUR;
    }
  }

  inline uint32_t findClosestNumBits(int64_t value) {
    if (value < 0) {
      return getClosestFixedBits(64);
    }

    uint32_t count = 0;
    while (value != 0) {
      count++;
      value = value >> 1;
    }
    return getClosestFixedBits(count);
  }

  inline bool isSafeSubtract(int64_t left, int64_t right) {
    return ((left ^ right) >= 0) || ((left ^ (left - right)) >= 0);
  }

  inline uint32_t RleEncoderV2::getOpCode(EncodingType encoding) {
    return static_cast<uint32_t >(encoding << 6);
  }
}

#endif //ORC_RLEV2UTIL_HH


text:
#import <OfficeImport/ESDContainer.h>

@interface ESDContainer (EBAdditions)
- (id)ebInitWithType:(unsigned short)arg1 version:(unsigned short)arg2 state:(id)arg3;
@end


text:
from sys import version_info

if version_info[0] <= 2:
    int2oct = chr
    # noinspection PyPep8
    ints2octs = lambda s: ''.join([int2oct(x) for x in s])
    null = ''
    oct2int = ord
    # TODO: refactor to return a sequence of ints
    # noinspection PyPep8
    octs2ints = lambda s: [oct2int(x) for x in s]
    # noinspection PyPep8
    str2octs = lambda x: x
    # noinspection PyPep8
    octs2str = lambda x: x
    # noinspection PyPep8
    isOctetsType = lambda s: isinstance(s, str)
    # noinspection PyPep8
    isStringType = lambda s: isinstance(s, str)
    # noinspection PyPep8
    ensureString = str
else:
    ints2octs = bytes
    # noinspection PyPep8
    int2oct = lambda x: ints2octs((x,))
    null = ints2octs()
    # noinspection PyPep8
    oct2int = lambda x: x
    # noinspection PyPep8
    octs2ints = lambda x: x
    # noinspection PyPep8
    str2octs = lambda x: x.encode('iso-8859-1')
    # noinspection PyPep8
    octs2str = lambda x: x.decode('iso-8859-1')
    # noinspection PyPep8
    isOctetsType = lambda s: isinstance(s, bytes)
    # noinspection PyPep8
    isStringType = lambda s: isinstance(s, str)
    # noinspection PyPep8
    ensureString = bytes


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `src/git.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>git.rs.html -- source</title>

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

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

use std::fmt;

/// The struct representation of a `Commit`
#[derive(Clone)]
pub struct Commit {
    /// The 40 char hash
    pub hash: String,
    /// The commit subject
    pub subject: String,
    /// The component (if any)
    pub component: String,
    /// Any issues this commit closes
    pub closes: Vec<String>,
    /// Any issues this commit breaks
    pub breaks: Vec<String>,
    /// The commit type (or alias)
    pub commit_type: String
}

/// A convienience type for multiple commits
pub type Commits = Vec<Commit>;

impl fmt::Debug for Commit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{
            hash:{:?},
            subject: {:?},
            commit_type: {:?},
            component: {:?},
            closes: {:?},
            breaks: {:?}
        }}", self.hash, self.subject, self.commit_type, self.component, self.closes, self.breaks)
    }
}

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
import ExpandedPair from './ExpandedPair';

export default class ExpandedRow {
  private readonly pairs: Array<ExpandedPair>;
  private readonly rowNumber: number;
  private readonly wasReversed: boolean;

  constructor(pairs: Array<ExpandedPair>, rowNumber: number, wasReversed: boolean) {
    this.pairs = pairs;
    this.rowNumber = rowNumber;
    this.wasReversed = wasReversed;
  }

  getPairs(): Array<ExpandedPair> {
    return this.pairs;
  }

  getRowNumber(): number {
    return this.rowNumber;
  }

  isReversed(): boolean {
    return this.wasReversed;
  }
  // check implementation

  isEquivalent(otherPairs: Array<ExpandedPair>): boolean {
    return this.checkEqualitity(this, otherPairs);
  }
  // @Override

  public toString(): String {
    return '{ ' + this.pairs + ' }';
  }

  /**
   * Two rows are equal if they contain the same pairs in the same order.
   */
  // @Override
  // check implementation
  public equals(o1: ExpandedRow, o2: ExpandedRow): boolean {
    if (!(o1 instanceof ExpandedRow)) {
      return false;
    }
    return this.checkEqualitity(o1, o2) && o1.wasReversed === o2.wasReversed;
  }
  checkEqualitity(pair1: any, pair2: any): boolean {
    if (!pair1 || !pair2) return;
    let result;
    pair1.forEach((e1, i) => {
      pair2.forEach(e2 => {
        if (e1.getLeftChar().getValue() === e2.getLeftChar().getValue() && e1.getRightChar().getValue() === e2.getRightChar().getValue() && e1.getFinderPatter().getValue() === e2.getFinderPatter().getValue()) {
          result = true;
        }
      });
    });
    return result;
  }

  // @Override
  // check implementation
  // public int hashCode(): number {
  //   let hash = this.pairs.values ^ this.wasReversed
  //   //return pairs.hashCode() ^ Boolean.valueOf(wasReversed).hashCode();
  // }

}


text:
layout: page
title: Java Blogs
subtitle:    Take notes about everything new
menu: java-blog
css: ['blog-page.css']
---
{% include java-blog-page.html %}


text:
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SUNRUSE.Influx.Web.Services;

namespace SUNRUSE.Influx.Web.Unit.ServicesUnit
{
	[TestClass]
	public sealed class TimingUnit : ComposedTestClassBase
	{
		[TestMethod]
		public void NowReturnsCurrentDateTimeInUTC()
		{
			var now = Container.GetExportedValue<ITiming>().Now;
			Assert.AreEqual(DateTimeKind.Utc, now.Kind);
			Assert.IsTrue(now > DateTime.Now.ToUniversalTime().AddSeconds(-10));
			Assert.IsTrue(now < DateTime.Now.ToUniversalTime().AddSeconds(10));
		}
	}
}