text:
<?php

namespace BackQ\Adapter\Amazon\DynamoDb;

use function crc32;
use function json_decode;
use function json_encode;
use function uniqid;

class QueueTableRow
{
    private const DYNAMODB_TYPE_STRING = 'S';
    private const DYNAMODB_TYPE_NUMBER = 'N';

    protected $id;

    protected $payload;

    protected $metadata = [];

    protected $time_ready;

    public function __construct(string $body, int $timeReady, string $queueId = "")
    {
        $this->id         = uniqid($queueId . '.', false);
        $this->payload    = $body;
        $this->time_ready = (string) $timeReady;
        $this->metadata['payload_checksum'] = $this->calculateHMAC();
    }

    public static function fromArray(array $array): ?self
    {
        if (!isset($array['id'], $array['metadata'], $array['payload'], $array['time_ready'])) {
            return null;
        }

        $item     = new self($array['payload'], $array['time_ready']);
        $metadata = json_decode($array['metadata'], true);

        /**
         * Verify that the payload checksum corresponds to the payload
         */
        if ($metadata['payload_checksum'] !== $item->calculateHMAC()) {
            return null;
        }

        return $item;
    }

    public function toArray(): array
    {
        return ['id'         => [self::DYNAMODB_TYPE_STRING => $this->id],
            'metadata'   => [self::DYNAMODB_TYPE_STRING => json_encode($this->metadata)],
            'payload'    => [self::DYNAMODB_TYPE_STRING => $this->payload],
            'time_ready' => [self::DYNAMODB_TYPE_NUMBER => $this->time_ready],
        ];
    }

    public function getPayload(): string
    {
        return $this->payload;
    }

    private function calculateHMAC(): int
    {
        return crc32($this->payload);
    }
}


text:
// Copyright (c) 2014 MediaMiser Ltd. All rights reserved.
package com.mediamiser.test;

import javax.jms.Connection;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import com.mediamiser.test.rules.BrokerServer;

/**
 * Creates resources to test anything that requires a {@link java.jmx.Connection}
 * object.
 *
 * @author Chris Fournier <chris.fournier@mediamiser.com>
 */
public abstract class AbstractConnectionTests extends AbstractBrokerTests {

	protected static Connection	CONNECTION;

	@BeforeClass
	public static void startConnection() throws Exception {
		CONNECTION = new ActiveMQConnectionFactory(BrokerServer.CONNECTION_STRING).createConnection();
		CONNECTION.start();
	}

	@AfterClass
	public static void stopConnection() throws Exception {
		CONNECTION.stop();
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */

'use strict';

/**
 * Copyright 2017 Google Inc.
 *
 * 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.
 */
/**
 * This is the Array.prototype.findIndex polyfill from MDN
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
 * https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
 */
if (!Array.prototype.findIndex) {
    Object.defineProperty(Array.prototype, 'findIndex', {
        value: function value(predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            var o = Object(this);
            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;
            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];
            // 5. Let k be 0.
            var k = 0;
            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return k.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return k;
                }
                // e. Increase k by 1.
                k++;
            }
            // 7. Return -1.
            return -1;
        }
    });
}
/**
 * This is the Array.prototype.find polyfill from MDN
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
 * https://tc39.github.io/ecma262/#sec-array.prototype.find
 */
if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
        value: function value(predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            var o = Object(this);
            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;
            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];
            // 5. Let k be 0.
            var k = 0;
            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return kValue.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return kValue;
                }
                // e. Increase k by 1.
                k++;
            }
            // 7. Return undefined.
            return undefined;
        }
    });
}
//# sourceMappingURL=shims.js.map


text:
package com.jme3.gde.materialdefinition.editor;

import com.jme3.gde.core.editor.nodes.NodeToolBar;

/**
 * This class displays a small bar with an edit and remove icon.
 *
 * @author Nehon
 * @author MeFisto94
 */
public class ShaderNodeToolBar extends NodeToolBar {
    private final ShaderNodePanel node;

    /**
     * Creates new ShaderNodeToolBar
     */
    @SuppressWarnings("LeakingThisInConstructor")
    public ShaderNodeToolBar(ShaderNodePanel node) {
        super(node);
        this.node = node;
        if (node.getType() != ShaderNodePanel.NodeType.Fragment &&
                node.getType() != ShaderNodePanel.NodeType.Vertex) {
            // Only (Frag and Vert) Shaders can be edited, no params
            remove(codeButton);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     * Comment by MeFisto94: If you see a compile error here, code-gen has
     * changed the method signature. it should be protected void with
     * @Override since it implements NodeToolBar's initComponents actually
     */
    @SuppressWarnings("unchecked")
    @Override
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    protected void initComponents() {

        codeButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();

        setOpaque(false);
        java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
        layout.rowHeights = new int[] {16};
        setLayout(layout);

        codeButton.setBackground(new java.awt.Color(255, 255, 255));
        codeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/core/editor/icons/code.png"))); // NOI18N
        codeButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShaderNodeToolBar.class, "ShaderNodeToolBar.codeButton.toolTipText")); // NOI18N
        codeButton.setBorder(null);
        codeButton.setBorderPainted(false);
        codeButton.setContentAreaFilled(false);
        codeButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        codeButton.setFocusable(false);
        codeButton.setIconTextGap(0);
        codeButton.setMaximumSize(new java.awt.Dimension(24, 24));
        codeButton.setMinimumSize(new java.awt.Dimension(24, 24));
        codeButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/core/editor/icons/codeHover.png"))); // NOI18N
        codeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codeButtonActionPerformed(evt);
            }
        });
        add(codeButton, new java.awt.GridBagConstraints());

        deleteButton.setBackground(new java.awt.Color(255, 255, 255));
        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/core/editor/icons/deleteNode.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(ShaderNodeToolBar.class, "ShaderNodeToolBar.deleteButton.text")); // NOI18N
        deleteButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShaderNodeToolBar.class, "ShaderNodeToolBar.deleteButton.toolTipText")); // NOI18N
        deleteButton.setBorder(null);
        deleteButton.setBorderPainted(false);
        deleteButton.setContentAreaFilled(false);
        deleteButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        deleteButton.setFocusable(false);
        deleteButton.setIconTextGap(0);
        deleteButton.setMaximumSize(new java.awt.Dimension(24, 24));
        deleteButton.setMinimumSize(new java.awt.Dimension(24, 24));
        deleteButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jme3/gde/core/editor/icons/deleteNodeHover.png"))); // NOI18N
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });
        add(deleteButton, new java.awt.GridBagConstraints());
    }// </editor-fold>//GEN-END:initComponents

    private void codeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_codeButtonActionPerformed
        node.edit();
    }//GEN-LAST:event_codeButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        node.delete();
    }//GEN-LAST:event_deleteButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton codeButton;
    private javax.swing.JButton deleteButton;
    // End of variables declaration//GEN-END:variables

}


text:
package pl.com.softproject.utils.pivot;

import java.util.Map;

/**
 *
 * @author Adrian Lapierre <alapierre@softproject.com.pl>
 */
public class RowKey {

    private String[] columns;

    public RowKey(String ... columns) {
        this.columns = columns;
    }

}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/input_injector.h"

#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <stdint.h>

#include <algorithm>
#include <utility>

#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "remoting/host/clipboard.h"
#include "remoting/proto/internal.pb.h"
#include "remoting/protocol/message_decoder.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
#include "third_party/webrtc/modules/desktop_capture/mac/desktop_configuration.h"
#include "ui/events/keycodes/dom/keycode_converter.h"

namespace remoting {

namespace {

void SetOrClearBit(uint64_t &value, uint64_t bit, bool set_bit) {
  value = set_bit ? (value | bit) : (value & ~bit);
}

void CreateAndPostKeyEvent(int keycode,
                           bool pressed,
                           uint64_t flags,
                           const base::string16& unicode) {
  base::ScopedCFTypeRef<CGEventRef> eventRef(
      CGEventCreateKeyboardEvent(nullptr, keycode, pressed));
  if (eventRef) {
    CGEventSetFlags(eventRef, static_cast<CGEventFlags>(flags));
    if (!unicode.empty())
      CGEventKeyboardSetUnicodeString(eventRef, unicode.size(), &(unicode[0]));
    CGEventPost(kCGSessionEventTap, eventRef);
  }
}

// This value is not defined. Give it the obvious name so that if it is ever
// added there will be a handy compilation error to remind us to remove this
// definition.
const int kVK_RightCommand = 0x36;

// Determines the minimum amount of time between attempts to waken the display
// in response to an input event.
const int kWakeUpDisplayIntervalMs = 1000;

using protocol::ClipboardEvent;
using protocol::KeyEvent;
using protocol::TextEvent;
using protocol::MouseEvent;
using protocol::TouchEvent;

// A class to generate events on Mac.
class InputInjectorMac : public InputInjector {
 public:
  explicit InputInjectorMac(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner);
  ~InputInjectorMac() override;

  // ClipboardStub interface.
  void InjectClipboardEvent(const ClipboardEvent& event) override;

  // InputStub interface.
  void InjectKeyEvent(const KeyEvent& event) override;
  void InjectTextEvent(const TextEvent& event) override;
  void InjectMouseEvent(const MouseEvent& event) override;
  void InjectTouchEvent(const TouchEvent& event) override;

  // InputInjector interface.
  void Start(scoped_ptr<protocol::ClipboardStub> client_clipboard) override;

 private:
  // The actual implementation resides in InputInjectorMac::Core class.
  class Core : public base::RefCountedThreadSafe<Core> {
   public:
    explicit Core(scoped_refptr<base::SingleThreadTaskRunner> task_runner);

    // Mirrors the ClipboardStub interface.
    void InjectClipboardEvent(const ClipboardEvent& event);

    // Mirrors the InputStub interface.
    void InjectKeyEvent(const KeyEvent& event);
    void InjectTextEvent(const TextEvent& event);
    void InjectMouseEvent(const MouseEvent& event);

    // Mirrors the InputInjector interface.
    void Start(scoped_ptr<protocol::ClipboardStub> client_clipboard);

    void Stop();

   private:
    friend class base::RefCountedThreadSafe<Core>;
    virtual ~Core();

    void WakeUpDisplay();

    scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
    webrtc::DesktopVector mouse_pos_;
    uint32_t mouse_button_state_;
    scoped_ptr<Clipboard> clipboard_;
    uint64_t left_modifiers_;
    uint64_t right_modifiers_;
    base::TimeTicks last_time_display_woken_;

    DISALLOW_COPY_AND_ASSIGN(Core);
  };

  scoped_refptr<Core> core_;

  DISALLOW_COPY_AND_ASSIGN(InputInjectorMac);
};

InputInjectorMac::InputInjectorMac(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  core_ = new Core(task_runner);
}

InputInjectorMac::~InputInjectorMac() {
  core_->Stop();
}

void InputInjectorMac::InjectClipboardEvent(const ClipboardEvent& event) {
  core_->InjectClipboardEvent(event);
}

void InputInjectorMac::InjectKeyEvent(const KeyEvent& event) {
  core_->InjectKeyEvent(event);
}

void InputInjectorMac::InjectTextEvent(const TextEvent& event) {
  core_->InjectTextEvent(event);
}

void InputInjectorMac::InjectMouseEvent(const MouseEvent& event) {
  core_->InjectMouseEvent(event);
}

void InputInjectorMac::InjectTouchEvent(const TouchEvent& event) {
  NOTIMPLEMENTED() << "Raw touch event injection not implemented for Mac.";
}

void InputInjectorMac::Start(
    scoped_ptr<protocol::ClipboardStub> client_clipboard) {
  core_->Start(std::move(client_clipboard));
}

InputInjectorMac::Core::Core(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : task_runner_(task_runner),
      mouse_button_state_(0),
      clipboard_(Clipboard::Create()),
      left_modifiers_(0),
      right_modifiers_(0) {
  // Ensure that local hardware events are not suppressed after injecting
  // input events.  This allows LocalInputMonitor to detect if the local mouse
  // is being moved whilst a remote user is connected.
  // This API is deprecated, but it is needed when using the deprecated
  // injection APIs.
  // If the non-deprecated injection APIs were used instead, the equivalent of
  // this line would not be needed, as OS X defaults to _not_ suppressing local
  // inputs in that case.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  CGSetLocalEventsSuppressionInterval(0.0);
#pragma clang diagnostic pop
}

void InputInjectorMac::Core::InjectClipboardEvent(const ClipboardEvent& event) {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE, base::Bind(&Core::InjectClipboardEvent, this, event));
    return;
  }

  // |clipboard_| will ignore unknown MIME-types, and verify the data's format.
  clipboard_->InjectClipboardEvent(event);
}

void InputInjectorMac::Core::InjectKeyEvent(const KeyEvent& event) {
  // HostEventDispatcher should filter events missing the pressed field.
  if (!event.has_pressed() || !event.has_usb_keycode())
    return;

  WakeUpDisplay();

  int keycode =
      ui::KeycodeConverter::UsbKeycodeToNativeKeycode(event.usb_keycode());

  VLOG(3) << "Converting USB keycode: " << std::hex << event.usb_keycode()
          << " to keycode: " << keycode << std::dec;

  // If we couldn't determine the Mac virtual key code then ignore the event.
  if (keycode == ui::KeycodeConverter::InvalidNativeKeycode())
    return;

  // If this is a modifier key, remember its new state so that it can be
  // correctly applied to subsequent events.
  if (keycode == kVK_Command) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskCommand, event.pressed());
  } else if (keycode == kVK_Shift) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskShift, event.pressed());
  } else if (keycode == kVK_Control) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskControl, event.pressed());
  } else if (keycode == kVK_Option) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskAlternate, event.pressed());
  } else if (keycode == kVK_RightCommand) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskCommand, event.pressed());
  } else if (keycode == kVK_RightShift) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskShift, event.pressed());
  } else if (keycode == kVK_RightControl) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskControl, event.pressed());
  } else if (keycode == kVK_RightOption) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskAlternate, event.pressed());
  }

  // In addition to the modifier keys pressed right now, we also need to set
  // AlphaShift if caps lock was active at the client (Mac ignores NumLock).
  uint64_t flags = left_modifiers_ | right_modifiers_;
  if (event.lock_states() & protocol::KeyEvent::LOCK_STATES_CAPSLOCK)
    flags |= kCGEventFlagMaskAlphaShift;

  CreateAndPostKeyEvent(keycode, event.pressed(), flags, base::string16());
}

void InputInjectorMac::Core::InjectTextEvent(const TextEvent& event) {
  DCHECK(event.has_text());

  WakeUpDisplay();

  base::string16 text = base::UTF8ToUTF16(event.text());

  // Applications that ignore UnicodeString field will see the text event as
  // Space key.
  CreateAndPostKeyEvent(kVK_Space, /*pressed=*/true, 0, text);
  CreateAndPostKeyEvent(kVK_Space, /*pressed=*/false, 0, text);
}

void InputInjectorMac::Core::InjectMouseEvent(const MouseEvent& event) {
  WakeUpDisplay();

  if (event.has_x() && event.has_y()) {
    // On multi-monitor systems (0,0) refers to the top-left of the "main"
    // display, whereas our coordinate scheme places (0,0) at the top-left of
    // the bounding rectangle around all the displays, so we need to translate
    // accordingly.

    // Set the mouse position assuming single-monitor.
    mouse_pos_.set(event.x(), event.y());

    // Fetch the desktop configuration.
    // TODO(wez): Optimize this out, or at least only enumerate displays in
    // response to display-changed events. VideoFrameCapturer's VideoFrames
    // could be augmented to include native cursor coordinates for use by
    // MouseClampingFilter, removing the need for translation here.
    webrtc::MacDesktopConfiguration desktop_config =
        webrtc::MacDesktopConfiguration::GetCurrent(
            webrtc::MacDesktopConfiguration::TopLeftOrigin);

    // Translate the mouse position into desktop coordinates.
    mouse_pos_ = mouse_pos_.add(
        webrtc::DesktopVector(desktop_config.pixel_bounds.left(),
                              desktop_config.pixel_bounds.top()));

    // Constrain the mouse position to the desktop coordinates.
    mouse_pos_.set(
       std::max(desktop_config.pixel_bounds.left(),
           std::min(desktop_config.pixel_bounds.right(), mouse_pos_.x())),
       std::max(desktop_config.pixel_bounds.top(),
           std::min(desktop_config.pixel_bounds.bottom(), mouse_pos_.y())));

    // Convert from pixel to Density Independent Pixel coordinates.
    mouse_pos_.set(mouse_pos_.x() / desktop_config.dip_to_pixel_scale,
                   mouse_pos_.y() / desktop_config.dip_to_pixel_scale);

    VLOG(3) << "Moving mouse to " << mouse_pos_.x() << "," << mouse_pos_.y();
  }
  if (event.has_button() && event.has_button_down()) {
    if (event.button() >= 1 && event.button() <= 3) {
      VLOG(2) << "Button " << event.button()
              << (event.button_down() ? " down" : " up");
      int button_change = 1 << (event.button() - 1);
      if (event.button_down())
        mouse_button_state_ |= button_change;
      else
        mouse_button_state_ &= ~button_change;
    } else {
      VLOG(1) << "Unknown mouse button: " << event.button();
    }
  }
  // We use the deprecated CGPostMouseEvent API because we receive low-level
  // mouse events, whereas CGEventCreateMouseEvent is for injecting higher-level
  // events. For example, the deprecated APIs will detect double-clicks or drags
  // in a way that is consistent with how they would be generated using a local
  // mouse, whereas the new APIs expect us to inject these higher-level events
  // directly.
  CGPoint position = CGPointMake(mouse_pos_.x(), mouse_pos_.y());
  enum {
    LeftBit = 1 << (MouseEvent::BUTTON_LEFT - 1),
    MiddleBit = 1 << (MouseEvent::BUTTON_MIDDLE - 1),
    RightBit = 1 << (MouseEvent::BUTTON_RIGHT - 1)
  };
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  CGError error = CGPostMouseEvent(position, true, 3,
                                   (mouse_button_state_ & LeftBit) != 0,
                                   (mouse_button_state_ & RightBit) != 0,
                                   (mouse_button_state_ & MiddleBit) != 0);
#pragma clang diagnostic pop
  if (error != kCGErrorSuccess)
    LOG(WARNING) << "CGPostMouseEvent error " << error;

  if (event.has_wheel_delta_x() && event.has_wheel_delta_y()) {
    int delta_x = static_cast<int>(event.wheel_delta_x());
    int delta_y = static_cast<int>(event.wheel_delta_y());
    base::ScopedCFTypeRef<CGEventRef> event(CGEventCreateScrollWheelEvent(
        nullptr, kCGScrollEventUnitPixel, 2, delta_y, delta_x));
    if (event)
      CGEventPost(kCGSessionEventTap, event);
  }
}

void InputInjectorMac::Core::Start(
    scoped_ptr<protocol::ClipboardStub> client_clipboard) {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&Core::Start, this, base::Passed(&client_clipboard)));
    return;
  }

  clipboard_->Start(std::move(client_clipboard));
}

void InputInjectorMac::Core::Stop() {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE, base::Bind(&Core::Stop, this));
    return;
  }

  clipboard_.reset();
}

void InputInjectorMac::Core::WakeUpDisplay() {
  base::TimeTicks now = base::TimeTicks::Now();
  if (now - last_time_display_woken_ <
      base::TimeDelta::FromMilliseconds(kWakeUpDisplayIntervalMs)) {
    return;
  }

  last_time_display_woken_ = now;

  // TODO(dcaiafa): Consolidate power management with webrtc::ScreenCapturer
  // (crbug.com/535769)

  // Normally one would want to create a power assertion and hold it for the
  // duration of the session. An active power assertion prevents the display
  // from going to sleep automatically, but it doesn't prevent the user from
  // forcing it to sleep (e.g. by going to a hot corner). The display is only
  // re-awaken at the moment the assertion is created.
  IOPMAssertionID power_assertion_id = kIOPMNullAssertionID;
  IOReturn result = IOPMAssertionCreateWithName(
      CFSTR("UserIsActive"),
      kIOPMAssertionLevelOn,
      CFSTR("Chrome Remote Desktop connection active"),
      &power_assertion_id);
  if (result == kIOReturnSuccess) {
    IOPMAssertionRelease(power_assertion_id);
  }
}

InputInjectorMac::Core::~Core() {}

}  // namespace

// static
scoped_ptr<InputInjector> InputInjector::Create(
    scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) {
  return make_scoped_ptr(new InputInjectorMac(main_task_runner));
}

// static
bool InputInjector::SupportsTouchEvents() {
  return false;
}

}  // namespace remoting


text:
                    <%=item.view%>

                文章

                评论

                        <%=item.desc%>

                        Show Detail

                    Nice

                    Comment

                <form class="comment-form">

                        <input class="nickname c-textarea" type="text" name="nickname" placeholder="Enter Your Nickname">

                            Submit

                        <textarea class="comment-val c-textarea" name="comment" placeholder="Say something...">
                        </textarea>

                    <input type="hidden" name="id" value="<%=item.id%>">
                </form>

        <form class="form">
            <input type="hidden" name="is-detail-show" value="0">
            <input type="hidden" name="blog-id" value="{{item.id}}">
            <input type="hidden" name="file" value="">
        </form>


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * LocalTimeUnserializer.java                             *
 *                                                        *
 * LocalTime unserializer class for Java.                 *
 *                                                        *
 * LastModified: Apr 17, 2016                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

package hprose.io.unserialize;

import static hprose.io.HproseTags.TagDate;
import static hprose.io.HproseTags.TagDouble;
import static hprose.io.HproseTags.TagEmpty;
import static hprose.io.HproseTags.TagInteger;
import static hprose.io.HproseTags.TagLong;
import static hprose.io.HproseTags.TagNull;
import static hprose.io.HproseTags.TagRef;
import static hprose.io.HproseTags.TagString;
import static hprose.io.HproseTags.TagTime;
import hprose.util.DateTime;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.time.LocalTime;

final class LocalTimeUnserializer implements Unserializer {

    public final static LocalTimeUnserializer instance = new LocalTimeUnserializer();

    private static LocalTime toLocalTime(DateTime dt) {
        return LocalTime.of(dt.hour, dt.minute, dt.second, dt.nanosecond);
    }

    private static LocalTime toLocalTime(Object obj) {
        if (obj instanceof DateTime) {
            return toLocalTime((DateTime)obj);
        }
        if (obj instanceof char[]) {
            return LocalTime.parse(new String((char[])obj));
        }
        return LocalTime.parse(obj.toString());
    }

    final static LocalTime read(Reader reader, ByteBuffer buffer) throws IOException {
        int tag = buffer.get();
        switch (tag) {
            case TagDate: return toLocalTime(DefaultUnserializer.readDateTime(reader, buffer));
            case TagTime: return toLocalTime(DefaultUnserializer.readTime(reader, buffer));
            case TagNull:
            case TagEmpty: return null;
            case TagString: return LocalTime.parse(StringUnserializer.readString(reader, buffer));
            case TagRef: return toLocalTime(reader.readRef(buffer));
        }
        if (tag >= '0' && tag <= '9') return LocalTime.ofNanoOfDay(tag - '0');
        switch (tag) {
            case TagInteger:
            case TagLong: return LocalTime.ofNanoOfDay(ValueReader.readLong(buffer));
            case TagDouble: return LocalTime.ofNanoOfDay(Double.valueOf(ValueReader.readDouble(buffer)).longValue());
            default: throw ValueReader.castError(reader.tagToString(tag), LocalTime.class);
        }
    }

    final static LocalTime read(Reader reader, InputStream stream) throws IOException {
        int tag = stream.read();
        switch (tag) {
            case TagDate: return toLocalTime(DefaultUnserializer.readDateTime(reader, stream));
            case TagTime: return toLocalTime(DefaultUnserializer.readTime(reader, stream));
            case TagNull:
            case TagEmpty: return null;
            case TagString: return LocalTime.parse(StringUnserializer.readString(reader, stream));
            case TagRef: return toLocalTime(reader.readRef(stream));
        }
        if (tag >= '0' && tag <= '9') return LocalTime.ofNanoOfDay(tag - '0');
        switch (tag) {
            case TagInteger:
            case TagLong: return LocalTime.ofNanoOfDay(ValueReader.readLong(stream));
            case TagDouble: return LocalTime.ofNanoOfDay(Double.valueOf(ValueReader.readDouble(stream)).longValue());
            default: throw ValueReader.castError(reader.tagToString(tag), LocalTime.class);
        }
    }

    public final Object read(Reader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException {
        return read(reader, buffer);
    }

    public final Object read(Reader reader, InputStream stream, Class<?> cls, Type type) throws IOException {
        return read(reader, stream);
    }

}


text:
<?php

namespace Magento\Developer\Console\Command;

use Magento\TestFramework\Helper\Bootstrap;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class SourceThemeDeployCommandTest
 *
 * @see \Magento\Developer\Console\Command\SourceThemeDeployCommand
 */
class SourceThemeDeployCommandTest extends \PHPUnit_Framework_TestCase
{
    const PUB_STATIC_DIRECTORY = 'pub/static';

    const AREA_TEST_VALUE = 'frontend';

    const LOCALE_TEST_VALUE = 'en_US';

    const THEME_TEST_VALUE = 'Magento/luma';

    const TYPE_TEST_VALUE = 'less';

    /**
     * @var SourceThemeDeployCommand
     */
    private $command;

    /**
     * @var string
     */
    private $pubStatic;

    /**
     * @var array
     */
    private $compiledFiles = ['css/styles-m', 'css/styles-l'];

    /**
     * Set up
     */
    protected function setUp()
    {
        global $installDir;

        $this->pubStatic = $installDir . DIRECTORY_SEPARATOR . self::PUB_STATIC_DIRECTORY;
        $this->command = Bootstrap::getObjectManager()->get(SourceThemeDeployCommand::class);
    }

    /**
     * Run test for execute method
     */
    public function testExecute()
    {
        $error = [];

        /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $outputMock */
        $outputMock = $this->getMockBuilder(OutputInterface::class)
            ->getMockForAbstractClass();

        $this->clearStaticDirectory();

        $this->command->run($this->getInputMock(), $outputMock);

        /** @var \SplFileInfo $file */
        foreach ($this->collectFiles($this->pubStatic) as $file) {
            $fileInfo = pathinfo($file->getFilename());
            if (!in_array('css/' . $fileInfo['filename'], $this->compiledFiles, true)
                && !$file->isLink()
            ) {
                $error[] = 'Bad file -> ' . $file->getFilename() . PHP_EOL;
            }
        }

        $this->clearStaticDirectory();

        self::assertEmpty($error, implode($error));
    }

    /**
     * @return void
     */
    private function clearStaticDirectory()
    {
        /** @var \SplFileInfo $file */
        foreach ($this->collectFiles($this->pubStatic) as $file) {
            @unlink($file->getPathname());
        }
    }

    /**
     * @param string $path
     * @return \RegexIterator
     */
    private function collectFiles($path)
    {
        $flags = \FilesystemIterator::CURRENT_AS_FILEINFO
            | \FilesystemIterator::SKIP_DOTS;
        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, $flags));

        return new \RegexIterator(
            $iterator,
            '#\.less$#',
            \RegexIterator::MATCH,
            \RegexIterator::USE_KEY
        );
    }

    /**
     * @return InputInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getInputMock()
    {
        $inputMock = $this->getMockBuilder(InputInterface::class)
            ->getMockForAbstractClass();

        $inputMock->expects(self::exactly(4))
            ->method('getOption')
            ->willReturnMap(
                [
                    ['area', self::AREA_TEST_VALUE],
                    ['locale', self::LOCALE_TEST_VALUE],
                    ['theme', self::THEME_TEST_VALUE],
                    ['type', self::TYPE_TEST_VALUE]
                ]
            );
        $inputMock->expects(self::once())
            ->method('getArgument')
            ->with('file')
            ->willReturn($this->compiledFiles);

        return $inputMock;
    }
}


text:
import { it } from "flow-typed-test";
import { of } from "rxjs";
import { skipWhile } from "rxjs/operators";

it("should support a predicate", () => {
  const o = of("foo", "bar", "baz").pipe(skipWhile(value => value === "bar"));
});

it("should support a predicate with an index", () => {
  const o = of("foo", "bar", "baz").pipe(
    skipWhile((value, index) => index < 3)
  );
});

it("should enforce types", () => {
  // $ExpectError
  const o = of("foo", "bar", "baz").pipe(skipWhile());
});

it("should enforce predicate types", () => {
  // $ExpectError
  const o = of("foo", "bar", "baz").pipe(skipWhile(value => value < 3));
  // $ExpectError
  const p = of("foo", "bar", "baz").pipe(skipWhile((value, index) => index < "3"));
});

it("should enforce predicate return type", () => {
  // $ExpectError
  const o = of("foo", "bar", "baz").pipe(skipWhile(value => value));
});


text:
const express = require('express')
const User = require('mongoose').model('User')

const router = new express.Router()

router.get('/dashboard', (req, res) => {
  User.find({}).exec(
    (err, users) => {
      if (err) throw err
      res.status(200).json({
        'users': users
      })
    }
  )
})

module.exports = router


text:
PostgreSQL implementation of [JSON Web Tokens](https://jwt.io/)

## Dependencies

This code requires the pgcrypto extension, included in most
distribution's "postgresql-contrib" package.  The tests require the
pgtap extension to run.

## Install

You will require sudo privledges and the postgres development
libraries for your operating system in most cases.  For ubuntu on
postgres 9.5 for example, you can install them with:

    sudo apt-get install postgresql-server-dev-9.5

Clone the repository and then run:

    'make install'

This creates a new extension that can be installed with 'CREATE
EXTENSION pgjwt;'

To run the tests install pgtap and run 'pg_prove test/test.sql'.
Another approach is to use the docker based test runner, but running
'./test.sh'.  This will require you have docker installed.

## Usage

Create a token.  The first argument must be valid json, the second argument any text:

    => select sign('{"sub":"1234567890","name":"John Doe","admin":true}', 'secret');
                                                                            sign
    -------------------------------------------------------------------------------------------------------------------------------------------------------
     eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Verify a token:

    => select * from verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ', 'secret');
               header            |                       payload                       | valid
    -----------------------------+-----------------------------------------------------+-------
     {"alg":"HS256","typ":"JWT"} | {"sub":"1234567890","name":"John Doe","admin":true} | t

Algorithm
---------

sign() and verify() take an optional algorithm argument that can be
'HS256', 'HS384' or 'HS512'.  The default is 'HS256':

    => select sign('{"sub":"1234567890","name":"John Doe","admin":true}', 'secret', 'HS384'),

## TODO

* public/private keys when pgcrypto gets *_verify() functions

* SET ROLE and key lookup helper functions


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Funnel2Data</title>
<meta name="date" content="2015-09-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.xclcharts.chart

Class Funnel2Data

java.lang.Object

org.xclcharts.chart.Funnel2Data

All Implemented Interfaces:

java.lang.Comparable<Funnel2Data>

public class Funnel2Data
extends java.lang.Object
implements java.lang.Comparable<Funnel2Data>

Author:

XiongChuanLiang
(xcl_168@aliyun.com)

ClassName:

Funnel2Data

Description:

漏斗图数据类

Constructor Summary

Constructors

Constructor and Description

Funnel2Data()

Funnel2Data(java.lang.String label,
           float base,
           float percent,
           int color)

Method Summary

Methods

Modifier and Type
Method and Description

int
compareTo(Funnel2Data arg0)

int
getAlpha()

float
getBaseData()

返回基数集合

int
getColor()

java.lang.String
getLabel()

返回标签

float
getPercentData()

返回百分比数据

void
setAlpha(int alpha)

void
setBaseData(float data)

设置基数数据源

void
setColor(int value)

设置颜色

void
setLabel(java.lang.String value)

设置标签

void
setPercentData(float percent)

设置百分比数据源,即基数在最后所占的百分比

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Funnel2Data

public Funnel2Data()

Funnel2Data

public Funnel2Data(java.lang.String label,
           float base,
           float percent,
           int color)

Method Detail

setAlpha

public void setAlpha(int alpha)

getAlpha

public int getAlpha()

setLabel

public void setLabel(java.lang.String value)

设置标签

Parameters:

value - 标签内容

getLabel

public java.lang.String getLabel()

返回标签

Returns:

标签

setColor

public void setColor(int value)

设置颜色

Parameters:

value - 颜色

getColor

public int getColor()

setBaseData

public void setBaseData(float data)

设置基数数据源

Parameters:

data - 初始值

setPercentData

public void setPercentData(float percent)

设置百分比数据源,即基数在最后所占的百分比

Parameters:

percent - 所占百分比(0-1)

getBaseData

public float getBaseData()

返回基数集合

Returns:

基数

getPercentData

public float getPercentData()

返回百分比数据

Returns:

所占比数据(0-1)

compareTo

public int compareTo(Funnel2Data arg0)

Specified by:

compareTo in interface java.lang.Comparable<Funnel2Data>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php
namespace Home\Model;
use \Home\Model\CommonModel;
class FormModel extends CommonModel {
	// 自动验证设置
	protected $_validate	 =	 array(
		array('title','require','标题必须!',1),
		array('email','email','邮箱格式错误!',2),
		array('content','require','内容必须'),
		array('title','','标题已经存在',0,'unique',self::MODEL_INSERT),
		);
	// 自动填充设置
	protected $_auto	 =	 array(
		array('status','1',self::MODEL_INSERT),
		array('create_time','time',self::MODEL_INSERT,'function'),
		);

}


text:
require "google_drive/acl_entry"

module GoogleDrive

    # ACL (access control list) of a spreadsheet.
    #
    # Use GoogleDrive::Spreadsheet#acl to get GoogleDrive::Acl object.
    # See GoogleDrive::Spreadsheet#acl for usage example.
    #
    # This code is based on https://github.com/guyboertje/gdata-spreadsheet-ruby .
    class Acl

        include(Util)
        extend(Forwardable)

        def initialize(session, acls_feed_url) #:nodoc:
          @session = session
          @acls_feed_url = acls_feed_url
          header = {"GData-Version" => "3.0"}
          doc = @session.request(:get, @acls_feed_url, :header => header, :auth => :writely)
          @acls = doc.css("entry").map(){ |e| AclEntry.new(entry_to_params(e)) }
        end

        def_delegators(:@acls, :size, :[], :each)

        # Adds a new entry. +entry+ is either a GoogleDrive::AclEntry or a Hash with keys
        # :scope_type, :scope and :role. See GoogleDrive::AclEntry#scope_type and
        # GoogleDrive::AclEntry#role for the document of the fields.
        #
        # NOTE: This sends email to the new people.
        #
        # e.g.
        #   # A specific user can read or write.
        #   spreadsheet.acl.push(
        #       {:scope_type => "user", :scope => "example2@gmail.com", :role => "reader"})
        #   spreadsheet.acl.push(
        #       {:scope_type => "user", :scope => "example3@gmail.com", :role => "writer"})
        #   # Publish on the Web.
        #   spreadsheet.acl.push(
        #       {:scope_type => "default", :role => "reader"})
        #   # Anyone who knows the link can read.
        #   spreadsheet.acl.push(
        #       {:scope_type => "default", :with_key => true, :role => "reader"})
        def push(entry)

          entry = AclEntry.new(entry) if entry.is_a?(Hash)

          header = {"GData-Version" => "3.0", "Content-Type" => "application/atom+xml;charset=utf-8"}
          doc = @session.request(
              :post, @acls_feed_url, :data => entry.to_xml(), :header => header, :auth => :writely)

          entry.params = entry_to_params(doc.root)
          @acls.push(entry)
          return entry

        end

        # Deletes an ACL entry.
        #
        # e.g.
        #   spreadsheet.acl.delete(spreadsheet.acl[1])
        def delete(entry)
          header = {"GData-Version" => "3.0"}
          @session.request(:delete, entry.edit_url_internal, :header => header, :auth => :writely)
          @acls.delete(entry)
        end

        def update_role(entry) #:nodoc:

          header = {"GData-Version" => "3.0", "Content-Type" => "application/atom+xml;charset=utf-8"}
          doc = @session.request(
              :put, entry.edit_url_internal, :data => entry.to_xml(), :header => header, :auth => :writely)

          entry.params = entry_to_params(doc.root)
          return entry

        end

        def inspect
          return "\#<%p %p>" % [self.class, @acls]
        end

      private

        def entry_to_params(entry)

          if !entry.css("gAcl|withKey").empty?
            with_key = true
            role = entry.css("gAcl|withKey gAcl|role")[0]["value"]
          else
            with_key = false
            role = entry.css("gAcl|role")[0]["value"]
          end

          return {
            :acl => self,
            :scope_type => entry.css("gAcl|scope")[0]["type"],
            :scope => entry.css("gAcl|scope")[0]["value"],
            :with_key => with_key,
            :role => role,
            :title => entry.css("title").text,
            :edit_url => entry.css("link[rel='edit']")[0]["href"],
            :etag => entry["etag"],
          }

        end

    end

end


text:
export default async synchronizer => {
  await synchronizer.$store.dispatch('peer/updateCurrentPeerStatus')
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaymentEquipment.IDevice;
using PaymentEquipment.DLL;
using Model.General;
using System.Net;
using PaymentEquipment.Enum;
using PaymentEquipment.Entity;
using Model.HHZX.ComsumeAccount;
using BLL.IBLL.HHZX.ConsumeAccount;
using BLL.Factory.HHZX;
using BLL.IBLL.HHZX.ConsumerDevice;
using Model.HHZX.ConsumerDevice;

namespace PaymentEquipment.DeviceImplement
{
    public class EastRiverDevice : AbstractPayDevice
    {
        private EastRiverDevice_base _Device;

        public EastRiverDevice()
        {
            this._Device = new EastRiverDevice_base();
        }

        public override ReturnValueInfo Conn(IPAddress IPAddr, int iPort, int iMacID)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_ConnNet(IPAddr.ToString().ToCharArray(), iPort, iMacID);
                base.MacNo = iMacID;
                base.IP = IPAddr;
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo DisConn()
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_DisconnMac();
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo SetManagementCard(string strManageCardNo)
        {
            throw new NotImplementedException();
        }

        public override string GetManagementCard()
        {
            throw new NotImplementedException();
        }

        public override ReturnValueInfo SetDeviceNo(int iDeviceNewNo)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetMacID(iDeviceNewNo);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo SyncDeviceTime()
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetMacTime(DateTime.Now);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override DateTime? GetDeviceTime()
        {
            return this._Device.ER_GetMacTime();
        }

        public override ReturnValueInfo SetDeviceMode(EnumDeviceMode Mode)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetWorkModelState(Mode, EnumDeviceState.Common);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override EnumDeviceMode ReadDeviceMode()
        {
            try
            {
                EnumDeviceMode mode;
                EnumDeviceState state;

                bool res = this._Device.ER_GetWorkModelState(out mode, out state);
                return mode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public override ReturnValueInfo AddBlacklist(string strCardNo)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetSigleNameList(strCardNo, EastRiverDevice_base.ER_ListType.Blacklist);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo AddWhitelist(string strCardNo)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetSigleNameList(strCardNo, EastRiverDevice_base.ER_ListType.AttendanceWhiteList);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo RemoveBlacklist(string strCardNo)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_DelSigleList(EastRiverDevice_base.ER_ListType.Blacklist, strCardNo);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo RemoveWhitelist(string strCardNo)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_DelSigleList(EastRiverDevice_base.ER_ListType.AttendanceWhiteList, strCardNo);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo RemoveAllBlacklist()
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                //rvInfo.boolValue = this._Device.ER_ClearAllList();
                rvInfo.boolValue = this._Device.ER_DelBatchList(EastRiverDevice_base.ER_ListType.Blacklist);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo RemoveAllWhitelist()
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                //rvInfo.boolValue = this._Device.ER_ClearAllList();
                rvInfo.boolValue = this._Device.ER_DelBatchList(EastRiverDevice_base.ER_ListType.AttendanceWhiteList);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override Model.General.ReturnValueInfo SetDevicePwd(string strOldPwd, string strNewPwd)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();

            try
            {
                rvInfo.boolValue = _Device.ER_SetMacPwd(strOldPwd, strNewPwd);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }

            return rvInfo;
        }

        public override List<PosRecord> GetAllConsumptionRecords()
        {
            try
            {
                return this._Device.ER_GetAllRecord();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public override List<ConsumeRecord_csr_Info> GetAllProfileRecords()
        {
            List<ConsumeRecord_csr_Info> listReturn = null;
            try
            {
                IConsumeMachineBL MacBLL = MasterBLLFactory.GetBLL<IConsumeMachineBL>(MasterBLLFactory.ConsumeMachine);
                ConsumeMachineMaster_cmm_Info machineInfo = MacBLL.SearchRecords(new ConsumeMachineMaster_cmm_Info() { cmm_iMacNo = base.MacNo, cmm_cIPAddr = base.IP.ToString() }).FirstOrDefault();
                if (machineInfo == null)
                {
                    return listReturn;
                }

                bool isPingSucc = Common.General.Ping(base.IP.ToString());
                List<PosRecord> listRecord = this._Device.ER_GetAllRecord();
                if (listRecord != null && isPingSucc)
                {
                    if (listRecord.Count > 0)
                    {
                        //转换数据,保存到数据库
                        #region 转换原始数据

                        List<SourceConsumeRecord_scr_Info> listDBRecord = new List<SourceConsumeRecord_scr_Info>();
                        foreach (PosRecord payItem in listRecord)
                        {
                            try
                            {
                                SourceConsumeRecord_scr_Info sRecord = new SourceConsumeRecord_scr_Info();
                                sRecord.scr_cAdd = "sys";
                                sRecord.scr_cCardNo = payItem.CardNo;
                                sRecord.scr_cRecordID = Guid.NewGuid();
                                sRecord.scr_dAddDate = DateTime.Now;
                                sRecord.scr_dRecordTime = payItem.RecordTime;
                                sRecord.scr_fBalance = payItem.Balance;
                                sRecord.scr_fConsume = payItem.Consume;
                                sRecord.scr_iMacNo = base.MacNo;
                                listDBRecord.Add(sRecord);
                            }
                            catch (Exception exItem)
                            {
                                throw exItem;
                            }
                        }

                        #endregion

                        ISourceConsumeRecordBL BLL = MasterBLLFactory.GetBLL<ISourceConsumeRecordBL>(MasterBLLFactory.SourceConsumeRecord);
                        ReturnValueInfo rvInfo = BLL.BatchInsertRecord(listDBRecord);

                        if (rvInfo.boolValue && !rvInfo.isError)
                        {
                            machineInfo.cmm_lLastAccessRes = true;

                            this.RemoveAllConsumptionRecords();
                            listReturn = rvInfo.ValueObject as List<ConsumeRecord_csr_Info>;
                        }
                        else
                        {
                            machineInfo.cmm_lLastAccessRes = false;
                        }
                    }
                    else
                    {
                        machineInfo.cmm_lLastAccessRes = true;
                        listReturn = new List<ConsumeRecord_csr_Info>();
                    }
                }
                else
                {
                    machineInfo.cmm_lLastAccessRes = false;
                }

                machineInfo.cmm_dLastAccessTime = DateTime.Now;
                machineInfo.cmm_cLast = "sys";
                machineInfo.cmm_dLastDate = DateTime.Now;
                MacBLL.Save(machineInfo, Common.DefineConstantValue.EditStateEnum.OE_Update);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return listReturn;
        }

        public override ReturnValueInfo RemoveAllConsumptionRecords()
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_DeleteAllRecord();
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override ReturnValueInfo SetReadCardInterval(int iInterval)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetMacReadInterval(iInterval);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override int GetReadCardInterval()
        {
            return this._Device.ER_GetMacReadInterval();
        }

        public override decimal GetDayConsumeLimit()
        {
            try
            {
                return this._Device.ER_GetDayConsumeLimit();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public override ReturnValueInfo SetDayConsumeLimit(decimal dLimit)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetDayConsumeLimit(dLimit);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override decimal GetPerConsumeLimit()
        {
            try
            {
                return this._Device.ER_GetPerConsumeLimit();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public override ReturnValueInfo SetPerConsumeLimit(decimal dLimit)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetPerConsumeLimit(dLimit);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }

        public override IPAddress GetMachineIP()
        {
            IPAddress ipAddr = IPAddress.Parse("192.168.20.200");
            this._Device.ER_GetMachineNetworkInfo();
            return ipAddr;
        }

        public override int GetClientCode()
        {
            return this._Device.ER_GetClientCode();
        }

        public override bool SetClientCode()
        {
            return this._Device.ER_SetSectionNum(1);
        }

        public override ReturnValueInfo SetMacTimeSpan(List<ConsumeTimeSpan> listSpan)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                if (listSpan == null)
                {
                    rvInfo.isError = true;
                    return rvInfo;
                }
                List<PaymentEquipment.DLL.EastRiverDevice_base.TimepriceSpan> listBaseSpan = new List<EastRiverDevice_base.TimepriceSpan>();
                foreach (ConsumeTimeSpan item in listSpan)
                {
                    PaymentEquipment.DLL.EastRiverDevice_base.TimepriceSpan span = new EastRiverDevice_base.TimepriceSpan();
                    span.begintime = Convert.ToChar(item.BeginTime.Hours).ToString() + Convert.ToChar(item.BeginTime.Minutes).ToString();
                    span.endtime = Convert.ToChar(item.EndTime.Hours).ToString() + Convert.ToChar(item.EndTime.Minutes).ToString();
                    span.price = (int)(item.SetMoney * 100);
                    span.clockmodule = (int)item.DeviceMode;
                    span.times = 0;
                    listBaseSpan.Add(span);

                    this._Device.ER_SetSpanTimeofPrice(item.BeginTime.ToString(), item.EndTime.ToString(), item.LimitedTimes, (int)(item.SetMoney * 100));
                }
                //rvInfo.boolValue = this._Device.ER_SetConsumeSpan(listBaseSpan);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return rvInfo;
        }

        public override List<ConsumeTimeSpan> GetMacTimeSpan()
        {
            List<ConsumeTimeSpan> listSpan = new List<ConsumeTimeSpan>();
            try
            {
                PaymentEquipment.DLL.EastRiverDevice_base.TimepriceSpan[] times = this._Device.ER_GetConsumeSpan();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return listSpan;
        }

        public override ReturnValueInfo SetConsumetimeParam(int setcurmodel, int setcurallow)
        {
            ReturnValueInfo rvInfo = new ReturnValueInfo();
            try
            {
                rvInfo.boolValue = this._Device.ER_SetConsumetimeParam(setcurmodel, setcurallow);
            }
            catch (Exception ex)
            {
                rvInfo.isError = true;
                rvInfo.messageText = ex.Message;
            }
            return rvInfo;
        }
    }
}


text:
/**
 * Module: TYPO3/CMS/Filelist/FileSearch
 * JavaScript for file search
 * @exports TYPO3/CMS/Filelist/FileSearch
 */
define(['jquery', 'TYPO3/CMS/Backend/jquery.clearable'], function($) {

	var $searchFields = $('input[name="tx_filelist_file_filelistlist[searchWord]"]');
	var searchResultShown = ('' !== $searchFields.first().val());

	// make search field clearable
	$searchFields.clearable({
		onClear: function() {
			if (searchResultShown) {
				$(this).closest('form').submit();
			}
		}
	});

});


text:
<?php

namespace Twig\Node\Expression;

class_exists('Twig_Node_Expression_Test');

if (\false) {
    class TestExpression extends \Twig_Node_Expression_Test
    {
    }
}


text:
Fireball::Fireball(const std::string& p_Keyname) : Projectile(p_Keyname)
{
  m_Speed = c_FireballSpeed;
  m_Health = c_FireballHealth;
  m_LifeTimeRemaining = c_FireballFadeoutTime;
}

void Fireball::Update(float p_DeltaTime)
{
  Projectile::Update(p_DeltaTime);

  m_LifeTimeRemaining -= p_DeltaTime;

  if (m_LifeTimeRemaining < 0)
  {
    Remove();
  }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function (_ref) {
  var showButtons = _ref.showButtons;
  var onSendResponse = _ref.onSendResponse;
  var onHideEditor = _ref.onHideEditor;
  var messages = _ref.messages;
  var hasHideEditorButton = _ref.hasHideEditorButton;

  if (!showButtons) return null;
  return _react2.default.createElement(
    "div",
    { className: "RichEditor-actions" },
    _react2.default.createElement(
      "button",
      {
        className: "RichEditor-actionsButton btn-Sky",
        onClick: onSendResponse
      },
      messages.buttons.send || 'send'
    ),
    hasHideEditorButton ? _react2.default.createElement(
      "p",
      {
        className: "RichEditor-actionsButtonCancel",
        onClick: onHideEditor
      },
      messages.buttons.cancel || 'cancel'
    ) : null
  );
};


text:
([
  function(module, exports, __webpack_require__) {

  __webpack_require__(1);
  (function(angular) {
    (module.exports['main'] = angular.module('main', ['ngRoute']));
  }.call(exports, __webpack_require__(2)))
},
function(module, exports, __webpack_require__) {
  (function(angular) {
    (function(window, angular, undefined){
      // stub
    }(window, window.angular));
  }.call(exports, __webpack_require__(2)))
},
function(module, exports, __webpack_require__) {
  (function(angular) {
  // angular.js stub
  module.exports = window.angular
  }.call(exports, __webpack_require__(2)))
}
])


text:
import type {
  ConfigFileSearch,
  BabelrcSearch,
  IgnoreList,
  IgnoreItem,
  PluginList,
  PluginItem,
  PluginTarget,
  ConfigApplicableTest,
  SourceMapsOption,
  SourceTypeOption,
  CompactOption,
  RootInputSourceMapOption,
} from "./options";

export type ValidatorSet = {
  [string]: Validator<any>,
};

export type Validator<T> = (string, mixed) => T;

export function assertSourceMaps(
  key: string,
  value: mixed,
): SourceMapsOption | void {
  if (
    value !== undefined &&
    typeof value !== "boolean" &&
    value !== "inline" &&
    value !== "both"
  ) {
    throw new Error(
      `.${key} must be a boolean, "inline", "both", or undefined`,
    );
  }
  return value;
}

export function assertCompact(key: string, value: mixed): CompactOption | void {
  if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
    throw new Error(`.${key} must be a boolean, "auto", or undefined`);
  }
  return value;
}

export function assertSourceType(
  key: string,
  value: mixed,
): SourceTypeOption | void {
  if (
    value !== undefined &&
    value !== "module" &&
    value !== "script" &&
    value !== "unambiguous"
  ) {
    throw new Error(
      `.${key} must be "module", "script", "unambiguous", or undefined`,
    );
  }
  return value;
}

export function assertInputSourceMap(
  key: string,
  value: mixed,
): RootInputSourceMapOption | void {
  if (
    value !== undefined &&
    typeof value !== "boolean" &&
    (typeof value !== "object" || !value)
  ) {
    throw new Error(".inputSourceMap must be a boolean, object, or undefined");
  }
  return value;
}

export function assertString(key: string, value: mixed): string | void {
  if (value !== undefined && typeof value !== "string") {
    throw new Error(`.${key} must be a string, or undefined`);
  }
  return value;
}

export function assertFunction(key: string, value: mixed): Function | void {
  if (value !== undefined && typeof value !== "function") {
    throw new Error(`.${key} must be a function, or undefined`);
  }
  return value;
}

export function assertBoolean(key: string, value: mixed): boolean | void {
  if (value !== undefined && typeof value !== "boolean") {
    throw new Error(`.${key} must be a boolean, or undefined`);
  }
  return value;
}

export function assertObject(key: string, value: mixed): {} | void {
  if (
    value !== undefined &&
    (typeof value !== "object" || Array.isArray(value) || !value)
  ) {
    throw new Error(`.${key} must be an object, or undefined`);
  }
  return value;
}

export function assertArray(key: string, value: mixed): ?$ReadOnlyArray<mixed> {
  if (value != null && !Array.isArray(value)) {
    throw new Error(`.${key} must be an array, or undefined`);
  }
  return value;
}

export function assertIgnoreList(key: string, value: mixed): IgnoreList | void {
  const arr = assertArray(key, value);
  if (arr) {
    arr.forEach((item, i) => assertIgnoreItem(key, i, item));
  }
  return (arr: any);
}
function assertIgnoreItem(
  key: string,
  index: number,
  value: mixed,
): IgnoreItem {
  if (
    typeof value !== "string" &&
    typeof value !== "function" &&
    !(value instanceof RegExp)
  ) {
    throw new Error(
      `.${key}[${index}] must be an array of string/Funtion/RegExp values, or undefined`,
    );
  }
  return value;
}

export function assertConfigApplicableTest(
  key: string,
  value: mixed,
): ConfigApplicableTest | void {
  if (value === undefined) return value;

  if (Array.isArray(value)) {
    value.forEach((item, i) => {
      if (!checkValidTest(item)) {
        throw new Error(`.${key}[${i}] must be a string/Function/RegExp.`);
      }
    });
  } else if (!checkValidTest(value)) {
    throw new Error(
      `.${key} must be a string/Function/RegExp, or an array of those`,
    );
  }
  return (value: any);
}

function checkValidTest(value: mixed): boolean {
  return (
    typeof value === "string" ||
    typeof value === "function" ||
    value instanceof RegExp
  );
}

export function assertConfigFileSearch(
  key: string,
  value: mixed,
): ConfigFileSearch | void {
  if (
    value !== undefined &&
    typeof value !== "boolean" &&
    typeof value !== "string"
  ) {
    throw new Error(
      `.${key} must be a undefined, a boolean, a string, ` +
        `got ${JSON.stringify(value)}`,
    );
  }

  return value;
}

export function assertBabelrcSearch(
  key: string,
  value: mixed,
): BabelrcSearch | void {
  if (value === undefined || typeof value === "boolean") return value;

  if (Array.isArray(value)) {
    value.forEach((item, i) => {
      if (typeof item !== "string") {
        throw new Error(`.${key}[${i}] must be a string.`);
      }
    });
  } else if (typeof value !== "string") {
    throw new Error(
      `.${key} must be a undefined, a boolean, a string, ` +
        `or an array of strings, got ${JSON.stringify(value)}`,
    );
  }
  return (value: any);
}

export function assertPluginList(key: string, value: mixed): PluginList | void {
  const arr = assertArray(key, value);
  if (arr) {
    // Loop instead of using `.map` in order to preserve object identity
    // for plugin array for use during config chain processing.
    arr.forEach((item, i) => assertPluginItem(key, i, item));
  }
  return (arr: any);
}
function assertPluginItem(
  key: string,
  index: number,
  value: mixed,
): PluginItem {
  if (Array.isArray(value)) {
    if (value.length === 0) {
      throw new Error(`.${key}[${index}] must include an object`);
    }

    if (value.length > 3) {
      throw new Error(
        `.${key}[${index}] may only be a two-tuple or three-tuple`,
      );
    }

    assertPluginTarget(key, index, true, value[0]);

    if (value.length > 1) {
      const opts = value[1];
      if (
        opts !== undefined &&
        opts !== false &&
        (typeof opts !== "object" || Array.isArray(opts))
      ) {
        throw new Error(
          `.${key}[${index}][1] must be an object, false, or undefined`,
        );
      }
    }
    if (value.length === 3) {
      const name = value[2];
      if (name !== undefined && typeof name !== "string") {
        throw new Error(`.${key}[${index}][2] must be a string, or undefined`);
      }
    }
  } else {
    assertPluginTarget(key, index, false, value);
  }

  return (value: any);
}
function assertPluginTarget(
  key: string,
  index: number,
  inArray: boolean,
  value: mixed,
): PluginTarget {
  if (
    (typeof value !== "object" || !value) &&
    typeof value !== "string" &&
    typeof value !== "function"
  ) {
    throw new Error(
      `.${key}[${index}]${
        inArray ? `[0]` : ""
      } must be a string, object, function`,
    );
  }
  return value;
}


text:
Migration Guide
===============

Laika has not reached the 1.0 status yet and as a consequence, minor API changes can still be expected on the road
towards 1.0.

Most of the content in this guide is not relevant if you either use the integrated sbt plugin or the library API
without any lower-level customizations.

The only major change of the top-level library API in 8 years had been the 0.12.0 release, which has very detailed
migration instructions below.

Versions older than 0.18.0
--------------------------

Version 0.18 is based on cats-effect 3, and the API changes in that library had to surface in API changes in Laika
in some places.
If you either use the sbt plugin or just the pure `laika-core` module, you are not affected.

But users of the library API in either `laika-io` or `laika-pdf` need to make an easy, minor change:

Before:

```scala
implicit val cs: ContextShift[IO] =
  IO.contextShift(ExecutionContext.global)

val blocker = Blocker.liftExecutionContext(
  ExecutionContext.fromExecutor(Executors.newCachedThreadPool())

)

val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)
  .io(blocker)
  .parallel[IO]
  .build
```

After:

```scala
val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)
  .parallel[IO]
  .build
```

The manual creation of `ContextShift` and `Blocker` instances is no longer needed,
and consequently the `.io(blocker)` builder step is gone, too.

If required, control over the thread pool configuration is still available centrally, e.g. in `IOApp`.

Versions older than 0.16.0
--------------------------

The 0.16 release introduced theme support and as a consequence all parsers, renderers and transformers are now
provided as a cat-effect `Resource`.

If you are using the sbt plugin, you are not affected by this API change.
When using the library API the necessary code changes are quite trivial. Change:

```scala
val transformer = ??? // build your transformer like before

transformer
  .fromDirectory("docs")
  .toDirectory("target")
  .transform
```

to

```scala
val transformer = ??? // build your transformer like before

transformer.use {
  _.fromDirectory("docs")
   .toDirectory("target")
   .transform
}
```

Ensure that you create the transformer only once at application start to avoid unnecessary overhead and memory usage
for repeated use.

Finally, the legacy directive syntax which had been deprecated in the 0.12 release, has now been removed.

Versions older than 0.15.0
--------------------------

If you plan to migrate to 0.15 it is recommended to address all deprecation warnings the compiler admits
as this is the last release where they'll be supported.

This version introduces namespaces for the built-in substitution variables to avoid name clashes with
user-defined variables.
If you use them in your markup files or templates you need to adjust them for this release:

* `document.*` becomes `cursor.currentDocument.*`

* All configuration variables are now prefixed with `laika`, e.g. `laika.title`, `laika.navigationOrder`.

* `cursor.*` and `laika.*` are the only reserved namespaces, any other prefix can be freely chosen.

If you upgrade from a version older than 0.12.0 it is also recommended to switch to the new directive syntax
described below as this is a functional area that unfortunately does not emit any compiler warnings.

Versions older than 0.14.0
--------------------------

* If you use the document AST: the `Path` API had been split into `Path` for absolute paths only and `RelativePath`
  for pointing from one document to another.

* If you developed parser extensions there are new entry points for defining a span or block parser.
  You can address all deprecation warnings you might get for your parser definitions by following the new
  guide for [Writing Parser Extensions].

Versions older than 0.12.0
--------------------------

The 0.12 release contains the most significant number of breaking changes
of any release since the 0.1 version in 2012.

**Using Laika's sbt plugin**

* If you do not use any of the customization hooks you can safely skip this guide.
* If you define custom rewrite rules, render functions or directives,
  please see the corresponding sections below.

**Using Laika's Library API**

* It's probably safest you read all the sections of this guide as even the
  high level APIs had changed.
* You can of course simply skip features you do not use.

This section is written for users of the 0.9, 0.10 and 0.11 releases which had been compatible with each other.

If you migrate from an even earlier version, please start with the
[release notes for 0.9](https://github.com/planet42/Laika/releases/tag/0.9.0) first.

**Motivation**

The following design goals led to the partial rewrite:

* Make the library a good citizen in a pure FP setup
* Stop throwing any exceptions in public APIs
* Stop hiding the side-effecting nature of some operations in blocking, synchronous APIs
* Build on top of cats-effect so that users get the familiar Bring-Your-Own Effect setup
* Avoid any kind of runtime reflection
* Make the feature set which had grown organically over the years more consistent and convenient
  to use
* Do many changes in one big, breaking release so that the road towards
  a final 1.0 release will be less bumpy from now on

**New Separate laika-io Module**

A subset of the existing `laika-core` module has been extracted into its own module,
`laika-io`. You need to add this new dependency if you use:

* File/Stream IO
* EPUB output
* Parallel transformations

The existing PDF support already had its own, separate artifact `laika-pdf` which
is also still available.

If you mostly do in-memory transformations from Markdown or reStructuredText to HTML
you can continue using the `laika-core` module.

The reasons for the split were:

* Keep features that depend on cats-effect separate so that the core module
  does not need this dependency
* Narrow the feature set of the core module to a point where it can realistically
  be fully supported for Scala.js in a later release (most likely 0.13)

**Referential Transparency**

Laika is now supposed to be a good citizen in a pure FP setup when using its
library API. The following changes had been implemented for this purpose:

* No method in the public API throws any Exceptions anymore.
* The result of pure operations is provided by instances of `Either`.
* The result of side-effecting operations is provided by a return type of `F[A]`
  where `F[_]` is the standard Bring-Your-Own-Effect pattern, so that any effect implementing
  the cats-effect typeclasses (`Sync` or `Async`, depending on use case) can be used.
* The dependency on the Typesafe Config library and its impure Java API has
  been removed in favor of a new lightweight and pure HOCON parser provided
  by Laika, supporting the full spec.

**Parser, Renderer and Transformer APIs**

The changes were necessary for the following reasons:

* The reduced core module does no longer offer any IO-related functionality.
* The return types of many methods had to change as Laika does no longer throw any Exceptions.
* The new IO module has its own builder APIs for constructing instances that work with
  the cats-effect type classes.

It's probably easiest to just show a few before/after examples below:

**Transforming from Markdown to HTML in-memory**

Before

```scala
val input = "some *text* example"

val transformer = Transform
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)

val res: String = transformer
  .fromString(input)
  .toString
```

After

```scala
val input = "some *text* example"

val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)
  .build

val res: Either[ParserError, String] = transformer
  .transform(input)
```

@:pageBreak

**Transforming a directory of files from Markdown to HTML**

Before

```scala
val transformer = Transform
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)
  .build

val res: Unit = transformer
  .fromDirectory("src")
  .toDirectory("target")
```

After (ensure you added the new `laika-io` dependency):

```scala
import laika.io.implicits._

val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .using(GitHubFlavor)
  .parallel[IO]
  .build

val res: IO[Unit] = transformer.use {
  _.fromDirectory("src")
   .toDirectory("target")
   .transform
}
```

Note that while the new code sample looks more verbose, it now gives you full
control over where your effects are run.

@:pageBreak

**Customizing Renderers**

The renderer API had changed from a side-effecting API to a pure API.
Renderers now take AST elements and produce a string and will be invoked
recursively as before. This model allows for easier testing and pure code
at a minimal performance hit over the old design (< 10%).

Before

```scala
val transformer = Transform
  .from(Markdown)
  .to(HTML)
  .rendering { out =>
    { case Emphasized(content, _) =>
      out << """<em class="big">""" << content << "</em>" }
  }
```

After

```scala
val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .rendering {
    case (fmt, Emphasized(content, opt)) =>
      fmt.element("em", opt, content, "class" -> "big")
    }.build
```

The engine passes the following instances to the partial function:

* The formatter (`fmt`) which has a different API for each supported output format,
  in this case it will be an `HTMLFormatter`
* The current element of the rendered document AST which you can pattern match on

**Rewrite Rules**

Here most of the changes are in the implementation which had been rewritten to avoid
any kind of runtime reflection.

On the API surface, there are only two changes:

* The return type is more explicit (e.g. `Replace(newElement)` instead of `Some(newElement)`)
* Rules for rewriting spans and blocks get registered separately for increased
  type-safety, as it is invalid to replace a span with a block element.

@:pageBreak

Before

```scala
val transformer = Transform
  .from(Markdown)
  .to(HTML)
  .usingRule {
    case Emphasized(content, opts) => Some(Strong(content, opts))
  }
```

After

```scala
val transformer = Transformer
  .from(Markdown)
  .to(HTML)
  .usingSpanRule {
    case Emphasized(content, opts) => Replace(Strong(content, opts))
  }
  .build
```

**Templating**

Variable substitutions now use HOCON syntax in line with the general deeper integration
with HOCON throughout Laika's feature set.

The old syntax is still supported,
but will be removed at some point before the 1.0 release.

The old reference style `{{some.ref}}` now becomes either `${some.ref}` for a required
reference or `${?some.ref}` for an optional one.

**Directives**

Directives in 0.12 come with changes in both, the DSL for creating custom directives
and the supported syntax in markup and template files.

If you are not implementing your own directives, but only use the built-in ones
provided by Laika, you can skip the section on the DSL.

**Directive Syntax**

* The separators for the attribute and body sections have changed
* HOCON syntax is now used for named attributes between curly braces or a plain string for an
  unnamed attribute in parenthesis
* The old syntax is still supported, but will be removed at some point before the 1.0 release

@:pageBreak

Before

```laika-html
@:if "layout.showSidebar":
  <div class="sidebar">...</div>

~else:
  <p>Something else</p>
```

After

```laika-html
@:if(layout.showSidebar)
<div class="sidebar">...</div>

@:else
<p>Something else</p>

@:@
```

**Directive DSL**

The building blocks for creating your own directives have also changed significantly:

* `attribute(Default)` is now `attribute(0)`
* `body` is now either `parsedBody` or `rawBody`
* Type conversions happen with the new `as` method: `attribute("title").as[String]`,
  based on the `ConfigDecoder` type class that is also used for the new Config API
* Named body parts have been replaced by the more flexible [Separator Directives].
* The built-in helper for mapping directive parts with different arity has
  been replaced by cats `mapN`

Before

```scala
import laika.ast._
import Spans.dsl._

case class Note (title: String,
                 content: Seq[Span],
                 options: Options = NoOpt) extends Span
                                           with SpanContainer[Note]

val spanDirective = Spans.create("note") {
  (attribute(Default) ~ body(Default)) (Note(_,_))
}
```

@:pageBreak

After

```scala
import cats.implicits._
import laika.ast._
import Spans.dsl._

case class Note (title: String,
                 content: Seq[Span],
                 options: Options = NoOpt) extends Span
                                           with SpanContainer[Note]

val spanDirective = Spans.create("note") {
  (attribute(0).as[String], parsedBody).mapN(Note(_,_))
}
```

Note the additional import of cats implicits in the new version.

**Config API**

Laika's support for HOCON configuration, originating either from configuration headers
in markup or template documents or separate configuration files had previously been
based on the Typesafe Config library and its Java API. Instances of `Config` were
available in the `Document` and `DocumentTree` types.

This type is now Laika's own Config API, based on its own lightweight HOCON parser.
See the API docs for [laika.config.Config] for details.

[laika.config.Config]: http://planet42.github.com/Laika/api/laika/config/Config.html

**Document Tree Model**

The model had been enhanced to better cater for Laika's support for e-book generation.

* The result of a tree parsing operation is now a new type called `DocumentTreeRoot`
* It has a `coverDocument` property and contains the recursive tree structure of the parsed content.
* Each `DocumentTree` in the structure now has an explicit `titleDocument: Option[Document]` property
  for more explicit content organization in e-books.
* Properties that previously held references to streams and other impure data had been
  removed from the pure content model (e.g. `DocumentTree.staticDocuments`).


text:
/* eslint max-nested-callbacks: ["error", 8] */
/* eslint-env mocha */
'use strict'

const crypto = require('crypto')
const expect = require('chai').expect
const FormData = require('form-data')
const streamToPromise = require('stream-to-promise')
const multibase = require('multibase')

module.exports = (http) => {
  describe('/files', () => {
    let api

    before(() => {
      api = http.api._httpApi._apiServers[0]
    })

    describe('/add', () => {
      it('should add buffer bigger than Hapi default max bytes (1024 * 1024)', async () => {
        const payload = Buffer.from([
          '',
          '------------287032381131322',
          'Content-Disposition: form-data; name="test"; filename="test.txt"',
          'Content-Type: text/plain',
          '',
          crypto.randomBytes(1024 * 1024 * 2).toString('hex'),
          '------------287032381131322--'
        ].join('\r\n'))

        const res = await api.inject({
          method: 'POST',
          url: '/api/v0/add',
          headers: {
            'Content-Type': 'multipart/form-data; boundary=----------287032381131322'
          },
          payload
        })

        expect(res.statusCode).to.not.equal(413) // Payload too large
        expect(res.statusCode).to.equal(200)
      })

      // TODO: unskip when we can retrieve data from the repo with a different
      // version CID then it was added with.
      it.skip('should add data and return a base64 encoded CID', async () => {
        const form = new FormData()
        form.append('data', Buffer.from('TEST' + Date.now()))
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        const res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?cid-base=base64',
          headers,
          payload
        })

        expect(res.statusCode).to.equal(200)
        expect(multibase.isEncoded(JSON.parse(res.result).Hash)).to.deep.equal('base64')
      })

      it('should add data without pinning and return a base64 encoded CID', async () => {
        const form = new FormData()
        form.append('data', Buffer.from('TEST' + Date.now()))
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        const res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?cid-base=base64&pin=false',
          headers,
          payload
        })

        expect(res.statusCode).to.equal(200)
        expect(multibase.isEncoded(JSON.parse(res.result).Hash)).to.deep.equal('base64')
      })

      it('should add data using the trickle importer', async () => {
        const form = new FormData()
        form.append('data', Buffer.from('TEST\n'))
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        const res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?trickle=true&pin=false',
          headers,
          payload
        })

        expect(res.statusCode).to.equal(200)
        expect(JSON.parse(res.result).Hash).to.equal('QmRJTAvvv1UNgCXxK9grf6u2pCT2ZQ2wCwsojpC1sTjkp9')
      })

      it('should add data using the balanced importer', async () => {
        const form = new FormData()
        form.append('data', Buffer.from('TEST\n'))
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        const res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?pin=false',
          headers,
          payload
        })

        expect(res.statusCode).to.equal(200)
        expect(JSON.parse(res.result).Hash).to.equal('Qmdudp5XvJr7KrqK6fQ7m2ACStoRxuwfovNHnY6dAAeUis')
      })
    })

    describe('/cat', () => {
      it('returns 400 for request without argument', async () => {
        const res = await api.inject({
          method: 'GET',
          url: '/api/v0/cat'
        })

        expect(res.statusCode).to.equal(400)
        expect(res.result.Message).to.be.a('string')
      })

      it('returns 400 for request with invalid argument', async () => {
        const res = await api.inject({
          method: 'GET',
          url: '/api/v0/cat?arg=invalid'
        })

        expect(res.statusCode).to.equal(400)
        expect(res.result.Message).to.be.a('string')
      })

      it('should cat a valid hash', async function () {
        this.timeout(30 * 1000)

        const data = Buffer.from('TEST' + Date.now())
        const form = new FormData()
        form.append('data', data)
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        let res = await api.inject({
          method: 'POST',
          url: '/api/v0/add',
          headers,
          payload
        })

        expect(res.statusCode).to.equal(200)
        const cid = JSON.parse(res.result).Hash

        res = await api.inject({
          method: 'GET',
          url: '/api/v0/cat?arg=' + cid
        })

        expect(res.statusCode).to.equal(200)
        expect(res.rawPayload).to.deep.equal(data)
        expect(res.payload).to.equal(data.toString())
      })
    })

    describe('/get', () => {}) // TODO

    describe('/ls', () => {
      it('should list directory contents and return a base64 encoded CIDs', async () => {
        const form = new FormData()
        form.append('file', Buffer.from('TEST' + Date.now()), { filename: 'data.txt' })
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        let res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?wrap-with-directory=true',
          headers,
          payload
        })
        expect(res.statusCode).to.equal(200)

        const files = res.result.trim().split('\n').map(r => JSON.parse(r))
        const dir = files[files.length - 1]

        res = await api.inject({
          method: 'POST',
          url: '/api/v0/ls?cid-base=base64&arg=' + dir.Hash
        })
        expect(res.statusCode).to.equal(200)
        res.result.Objects[0].Links.forEach(item => {
          expect(multibase.isEncoded(item.Hash)).to.deep.equal('base64')
        })
      })
    })

    describe('/refs', () => {
      it('should list refs', async () => {
        const form = new FormData()
        form.append('file', Buffer.from('TEST' + Date.now()), { filename: 'data.txt' })
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        let res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?wrap-with-directory=true',
          headers,
          payload
        })
        expect(res.statusCode).to.equal(200)

        const files = res.result.trim().split('\n').map(r => JSON.parse(r))
        const dir = files[files.length - 1]

        res = await api.inject({
          method: 'POST',
          url: '/api/v0/refs?format=<linkname>&arg=' + dir.Hash
        })
        expect(res.statusCode).to.equal(200)
        expect(JSON.parse(res.result).Ref).to.equal('data.txt')
      })
    })

    describe('/refs/local', () => {
      it('should list local refs', async () => {
        const form = new FormData()
        form.append('file', Buffer.from('TEST' + Date.now()), { filename: 'data.txt' })
        const headers = form.getHeaders()

        const payload = await streamToPromise(form)
        let res = await api.inject({
          method: 'POST',
          url: '/api/v0/add?wrap-with-directory=true',
          headers,
          payload
        })
        expect(res.statusCode).to.equal(200)

        res = await api.inject({
          method: 'POST',
          url: '/api/v0/refs/local'
        })
        expect(res.statusCode).to.equal(200)
        const refs = res.result.trim().split('\n').map(JSON.parse).map(r => r.Ref)
        expect(refs.length).to.be.gt(0)
      })
    })
  })
}


text:
#include "object.h"
#include <assert.h>

#include "dia-object.h"

dia::ObjectType::ObjectType (DiaObjectType* ot) : self(ot), version(ot ? ot->version : -1)
{
    assert (self);
    // read-only which also wont change
    name = self->name;
}
/*! Factory function to create Object of a given type.
 *
 * \return not only the new Object* but also two 'appropriate' Handle to e.g. connect
 * to some other Object
 */
dia::Object*
dia::ObjectType::create(double x, double y, dia::Handle** h1, dia::Handle** h2) const
{
    ::_Handle *_h1, *_h2;
    dia::Object* o;
    Point p = {x, y};
    void* user_data = 0; //TODO: as parameter ???
    if (!self)
        return 0;
    o = new dia::Object (self->ops->create(&p, user_data ? user_data : self->default_user_data, &_h1, &_h2));
    if (h1) *h1 = new dia::Handle (_h1, o->Self());
    if (h2) *h2 = new dia::Handle (_h2, o->Self());
    return o;
}
/*!
 * Allows to load an object from storage. Not sure if this becomes useful for language bindings.
 */
dia::Object*
dia::ObjectType::load (ObjectNode node, int version, const char* filename) const
{
    assert (self);
    return new dia::Object (self->ops->load (node, version, filename));
}
/*! Allows to save an Object to ObjectNode file filename.
 * . Not sure if this becomes useful for language bindings.
 */
void
dia::ObjectType::save (Object* o, ObjectNode node, const char* filename) const
{
    assert (self);
    self->ops->save (o->Self(), node, filename);
}
//! OPTIONAL: opens the defaults dialog
GtkWidget*
dia::ObjectType::get_defaults () const
{
    assert (self);
    if (!self->ops->get_defaults)
        return 0;
    return self->ops->get_defaults ();
}
//! OPTIONAL: apply changed defaults
void
dia::ObjectType::apply_defaults ()
{
    assert (self);
    if (!self->ops->apply_defaults)
	return;
    self->ops->apply_defaults ();
}

//! create an object wrapper - object previously registered from a plug-in
dia::Object::Object (DiaObject* o) : self(o), properties(o), connections(o), handles(o), type(o->type)
{
}
//! destroy the right thing - usually not the underlying object
dia::Object::~Object ()
{
}
//! accessor to deliver the objects bounding box
::_Rectangle*
dia::Object::bbox () const
{
    return &self->bounding_box;
}
//! real destruction
void
dia::Object::destroy ()
{
    assert (self);
    self->ops->destroy (self);
}
//! drawing the object on the renderer
void
dia::Object::draw (Renderer* r) const
{
    assert (self);
#if 0 //FIXME: need to think about delegation
    self->ops->draw (self, r);
#endif
}
//! calculate the distance betwenn the object and the point
double
dia::Object::distance_from (Point* p) const
{
    assert (self);
    return self->ops->distance_from (self, p);
}
//! react on selection (e.g. may change the drawing state)
void
dia::Object::select (Point* clicked_point, DiaRenderer* interactive_renderer)
{
    assert (self);
    self->ops->selectf (self, clicked_point, interactive_renderer);
}
//! create a deep copy
dia::Object* dia::Object::copy () const
{
    assert (self);
    return new dia::Object (self->ops->copy (self));
}
//! change position of the whole object
ObjectChange*
dia::Object::move (double x, double y)
{
    assert (self);
    Point p = {x, y};
    return self->ops->move (self, &p);
}
//! change position of an object handle - this is usually  a resize (Attention: does *not* match the C prototype)
ObjectChange*
dia::Object::move_handle (dia::Handle* h, double x, double y, HandleMoveReason reason, ModifierKeys modifiers)
{
    assert (self);
    Point p = {x, y};
    return self->ops->move_handle (self, h->Self(), &p, NULL, reason, modifiers);
}
//! OPTIONAL: provide a property dialog to change the object proeprties
GtkWidget*
dia::Object::get_properties (bool is_default) const
{
    assert (self);
    if (!self->ops->get_properties)
	return 0;
    return self->ops->get_properties (self, is_default);
}
//! OPTIONAL: apply the properties changed in the dialog
ObjectChange*
dia::Object::apply_properties (GtkWidget* w)
{
    assert (self);
    if (!self->ops->apply_properties_from_dialog)
	return NULL;
    return self->ops->apply_properties_from_dialog (self, w);
}
//! OPTIONAL: provide a context menu to change the object states
DiaMenu*
dia::Object::get_object_menu (Point* pos) const
{
    assert (self);
    if (!self->ops->get_object_menu)
	return 0;
    return self->ops->get_object_menu (self, pos);
}

//! StdProps: descibe properties accessible via standard properties API
const PropDescription*
dia::Object::describe_props () const
{
    assert (self);
    return self->ops->describe_props (self);
}
//! StdProps: return a list of properties describing the object state
void
dia::Object::get_props (GPtrArray *props) const
{
    assert (self);
    self->ops->get_props (self, props);
}
//! StdProps: apply a list of object properties to change the objects state
void
dia::Object::set_props (GPtrArray *props)
{
    assert (self);
    self->ops->set_props (self, props);
}

/*!
 * \brief factory function for ObjectType (Object factories)
 *
 * Before this function can return anything useful the ObjectType registry needs to be filled,
 * e.g. by dia::register_plugins()
 */
dia::ObjectType*
dia::get_object_type (const char* name)
{
    ::DiaObjectType* ot = object_get_type(const_cast<char*>(name));
    if (ot)
        return new dia::ObjectType (ot);
    return 0;
}