text:
import { h, Component } from 'preact'
import { bind } from 'decko'
import _ from 'lodash'
import nodeStore from '../../redux/store'
import {ACTION} from '../../redux/actions'
import getNodeTypeComponent from './../../constants/node-type-components'
import NodeResize from './node-resize'
import Attributes from './attributes'
import Portal from 'preact-portal'
import NODE_TYPE from '../../constants/node-type'

class Node extends Component {
    constructor({nodeId, nodeName, x, y}) {
        super()

        this.nodeId = nodeId

        this.state = {
            shouldMove: false,
            contentEditable: 'false',
            nodeName: nodeName,
            x: x, // top left corner
            y: y, // top left corner
            dragX: x,
            dragY: y,
            width: 100,
            height: 50
        }
    }

    @bind
    onMouseDown(event) {
        if (nodeStore.getState().settings.shouldConnectNodes) {
            let sourceNode = nodeStore.getState()
                .nodes
                .find(node => node.nodeId === this.nodeId)

            this.props.onDrawConnectionStart(sourceNode)

            nodeStore.dispatch({type: ACTION.START_DRAWING})

            window.addEventListener('mousemove', this.drawConnection)
            window.addEventListener('mouseup', this.drawConnectionFinished)
        } else {
            this.setState({
                shouldMove: true,
                startDragX: event.clientX,
                startDragY: event.clientY
            })

            window.addEventListener('mousemove', this.moveNode)
            window.addEventListener('mouseup', this.moveNodeFinished)
        }
    }

    @bind
    moveNode(event) {
        if (this.state.shouldMove) {
            let newPositionX = this.state.x + event.clientX - this.state.startDragX
            let newPositionY = this.state.y + event.clientY - this.state.startDragY

            this.setState({
                contentEditable: 'false',
                dragX: newPositionX,
                dragY: newPositionY
            })

            nodeStore.dispatch({
                type: ACTION.UPDATE_CONNECTIONS,
                value: {
                    nodeId: this.nodeId,
                    x: newPositionX,
                    y: newPositionY,
                    width: this.state.width,
                    height: this.state.height
                }
            })
        }
    }

    @bind
    moveNodeFinished() {
        window.removeEventListener('mousemove', this.moveNode)
        window.removeEventListener('mouseup', this.moveNodeFinished)

        if (this.state.x !== this.state.dragX || this.state.y !== this.state.dragY) {
            nodeStore.dispatch({
                type: ACTION.UPDATE_NODE,
                value: {
                    nodeId: this.nodeId,
                    x: this.state.dragX,
                    y: this.state.dragY,
                    width: this.state.width,
                    height: this.state.height
                }
            })

            this.setState({
                shouldMove: false,
                x: this.state.dragX,
                y: this.state.dragY
            })
        } else {
            this.setState({ shouldMove: false })
        }
    }

    @bind
    removeNode() {
        nodeStore.dispatch({
            type: ACTION.DELETE_NODE,
            value: {nodeId: this.nodeId}
        })
    }

    @bind
    drawConnection(event) {
        this.props.onDrawConnectionMove(event)
        this.setState({ contentEditable: 'false' })
    }

    @bind
    drawConnectionFinished() {
        window.removeEventListener('mousemove', this.drawConnection)
        window.removeEventListener('mouseup', this.drawConnectionFinished)

        this.props.onDrawConnectionEnd()
        nodeStore.dispatch({type: ACTION.STOP_DRAWING})
    }

    @bind
    onConnectionEnterDestination() {
        if (nodeStore.getState().settings.isDrawingConnection && nodeStore.getState().settings.shouldConnectNodes) {
            let destinationNode = nodeStore.getState()
                                           .nodes
                                           .find(node => node.nodeId === this.nodeId)

            if (destinationNode) {
                this.props.onNodeEnter(destinationNode)
            }
        }
    }

    @bind
    onConnectionLeaveDestination() {
        if (nodeStore.getState().settings.isDrawingConnection && nodeStore.getState().settings.shouldConnectNodes) {
            let destinationNode = nodeStore.getState()
                .nodes
                .find(node => node.nodeId === this.nodeId)

            if (destinationNode) {
                this.props.onNodeLeave(destinationNode)
            }
        }
    }

    componentWillReceiveProps({nodeName, x, y}) {
        if ((nodeName && this.state.nodeName !== nodeName) || this.state.x !== x || this.state.y !== y) {
            this.setState({
                ...this.state,
                nodeName: nodeName,
                x: x,
                y: y,
                dragX: x,
                dragY: y
            })
        }
    }

    @bind
    disableEnterKey(e) {
        let pressedKey = e.which
        let ENTER = 13
        if (pressedKey === ENTER) {
            e.preventDefault()
        }
    }

    @bind
    makeNameChange(e) {
        let pressedKey = e.which
        let ENTER = 13
        let ESCAPE = 27

        this.tempName = e.target.textContent

        if (pressedKey === ENTER) {
            this.saveName(e.target.textContent)
        }
        if (pressedKey === ENTER || pressedKey === ESCAPE) {
            this.tempName = null
            this.setState({ contentEditable: 'false' })
        }
    }

    @bind
    enableEdit() {
        this.setState({ contentEditable: 'true' })
    }

    @bind
    onBlur() {
        if (this.tempName) {
            this.saveName(this.tempName)
        }

        this.tempName = null

        this.setState({ contentEditable: 'false' })
    }

    saveName(name) {
        if (this.state.nodeName === name) {
            return
        }

        nodeStore.dispatch({
            type: ACTION.NODE_CHANGE_NAME,
            value: {
                nodeId: this.nodeId,
                nodeName: name
            }
        })
    }

    @bind
    startNodeResize(event, direction) {
        window.addEventListener('mousemove', this.moveNodeResize)
        window.addEventListener('mouseup', this.finishNodeResize)

        this.direction = direction
        this.startWidth = this.state.width
        this.startHeight = this.state.height
    }

    @bind
    moveNodeResize(event) {
        let newWidth
        let newHeight
        let x = this.state.x
        let y = this.state.y

        switch (this.direction) {
            case 'NW':
                newWidth = this.startWidth + this.state.x - event.clientX
                newHeight = this.startHeight + this.state.y - event.clientY
                x = event.clientX
                y = event.clientY
                break
            case 'NE':
                newWidth = event.clientX - this.state.x
                newHeight = this.startHeight + this.state.y - event.clientY
                y = event.clientY
                break
            case 'SW':
                newWidth = this.startWidth + this.state.x - event.clientX
                newHeight = event.clientY - this.state.y
                x = event.clientX
                break
            case 'SE':
                newWidth = event.clientX - this.state.x
                newHeight = event.clientY - this.state.y
                break
            default:
        }

        if (newWidth < 20) {
            newWidth = 20
            x = this.state.dragX
        }

        if (newHeight < 20) {
            newHeight = 20
            y = this.state.dragY
        }

        this.setState({
            dragX: x,
            dragY: y,
            width: newWidth,
            height: newHeight
        })
    }

    @bind
    finishNodeResize() {
        window.removeEventListener('mousemove', this.moveNodeResize)
        window.removeEventListener('mouseup', this.finishNodeResize)

        nodeStore.dispatch({
            type: ACTION.NODE_RESIZE_DONE,
            value: {
                nodeId: this.nodeId,
                x: this.state.dragX,
                y: this.state.dragY,
                width: this.state.width,
                height: this.state.height
            }
        })
    }

    @bind
    selectNode() {
        nodeStore.dispatch({
            type: ACTION.NODE_SELECT,
            value: {nodeId: this.nodeId}
        })
    }

    @bind
    preventDefault(event) {
        event.preventDefault()
    }

    @bind
    open() {
        this.setState({ open: true })
    }

    @bind
    close() {
        this.setState({ open: false })
    }

    @bind
    submit(event) {
        event.preventDefault()

        let attributeName = event.target[0].value
        let attributeType = event.target[1].value
        let attributeIsPrimary = event.target[2].checked

        if (_.isEmpty(attributeName)) {
            this.close()
            return
        }

        nodeStore.dispatch({type: ACTION.ADD_ATTRIBUTE,
            value: {
                nodeId: this.nodeId,
                attribute: {
                    name: attributeName,
                    type: attributeType,
                    isPrimary: attributeIsPrimary
                }
            }
        })

        this.close()
    }

    render(props, state) {
        let rootStyle = {
            transform: `translate(${state.dragX}px, ${state.dragY}px) scale(${props.zoom})`
        }

        return (

                    {/* <circle cx='0' cy='0' r='14' fill='#ebebeb' stroke='#c8c8c8' style='-webkit-tap-highlight-color: rgba(0, 0, 0, 0);' /> */}
                    {/* <circle cx='0' cy='0' r='10' fill='#ef4836' stroke='none' style='-webkit-tap-highlight-color: rgba(0, 0, 0, 0);' onClick={this.removeNode} /> */}

                { props.selected && <NodeResize onStartNodeResize={this.startNodeResize} /> }

                    { getNodeTypeComponent(props.type, {width: state.width, height: state.height, color: props.color}) }

                    {
                        props.type !== 'inheritance' &&

                            { state.nodeName }

                    }

                    <Attributes attributes={props.attributes} nodeId={this.nodeId} />

                    { props.selected && props.type !== NODE_TYPE.INHERITANCE && <button class='button-add-attribute' onClick={this.open}>Add property</button> }

                {
                    state.open &&
                    <Portal into='body'>

                            <form class='modal-form' name='attributeForm' onSubmit={this.submit} style='z-index: 101'>
                                <input type='text' value='' name='attributeName' onChange={this.preventDefault} placeholder='type name...' />

                                <select name='attributeType'>
                                    <option value='CHAR'>CHAR</option>
                                    <option value='INTEGER'>INTEGER</option>
                                    <option value='FLOAT'>FLOAT</option>
                                    <option value='TIMESTAMP'>TIMESTAMP</option>
                                </select>

                                    <input type='checkbox' class='checkbox' name='attributeIsKey' />
                                    Is primary key

                                    <input type='submit' value='Submit' />
                                    <input type='button' value='Cancel' onClick={this.close} />

                            </form>

                    </Portal>
                }

        )
    }
}

export default Node


text:
package cz.tomkren.typewars.basicgen;

import cz.tomkren.helpers.Comb0;
import cz.tomkren.helpers.AB;
import cz.tomkren.helpers.ABC;
import cz.tomkren.helpers.F;
import cz.tomkren.typewars.*;

import java.util.*;

public class Car {

    private final CreationLog log;
    private int nextVarId;
    private final Deque<Type> goalsQueue;
    private Sub sub;
    private int treeSize;

    public Car(Type goal) {
        log = CreationLog.START;

        AB<Type,Integer> fresheningResult = goal.freshenVars(0, new Sub());
        goal = fresheningResult._1();
        nextVarId = fresheningResult._2();

        goalsQueue = new ArrayDeque<>();
        goalsQueue.offer(goal);

        sub = new Sub();

        treeSize = 1; // góly počítáme taky
    }

    private Car(Car dad, ProtoNode newNode, Sub mgu, int nextVarId) {
        log = new CreationLog.Step(dad.log, newNode);
        this.nextVarId = nextVarId;

        // todo dyštak nějak taky udělat sdílený ve stylu podobném CreationLogu
        goalsQueue = new ArrayDeque<>(dad.goalsQueue);
        List<Type> inputTypes = newNode.getIns();
        inputTypes.forEach(goalsQueue::offer);

        mgu.dot(dad.sub);
        sub = mgu;

        treeSize = dad.treeSize + inputTypes.size(); // + 1 - 1
    }

    public List<Car> step(NodeLib lib) {
        Type goal = goalsQueue.poll();
        if (goal == null) {return null;} // hurá, hotovo
        goal = sub.apply(goal);

        List<Car> successors = new ArrayList<>();
        for (ProtoNode node : lib.getNodeList()) {
            ABC<ProtoNode,Sub,Integer> matchRes = node.matchOut(goal,nextVarId);
            if (matchRes != null) {
                successors.add(new Car(this, matchRes._1(), matchRes._2(), matchRes._3()));
            }
        }
        return successors;
    }

    public PolyTree mkPolyTree(NodeLib nodeLib) {
        if (!goalsQueue.isEmpty()) {throw new Error("Unfinished car cannot be transformed to a PolyTree.");}
        CodeLib codeLib = nodeLib instanceof CodeLib ? (CodeLib)nodeLib : null;
        return mkPolyTree(0, log.toRowList(), codeLib);
    }

    private PolyTree mkPolyTree(int i, List<CreationLog.Row> rows, CodeLib lib) {
        CreationLog.Row row = rows.get(i);
        ProtoNode node = row.getNode();
        List<PolyTree> sons = F.map(row.getSuccIs(), j -> mkPolyTree(j, rows, lib));

        String name = node.getName();
        CodeNode codeNode = lib == null ? null : lib.getCodeNode(name);

        return new PolyTree(codeNode, sub.apply(node.getOut()) , sons);
    }

    @Override
    public String toString() {
        return "Car{" +
                "\n log:\n" + log +
                "\n nextVarId: " + nextVarId +
                "\n goalsQueue: " + goalsQueue +
                "\n sub: " + sub +
                "\n treeSize: " + treeSize +
                "\n}\n";
    }

    public static class MinTreeSizeComparator implements Comparator<Car> {
        public int compare(Car c1, Car c2) {
            return Integer.compare(c1.treeSize, c2.treeSize);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
module TombstonePresenter
  extend ActiveSupport::Concern

  delegate :tombstone, to: :solr_document

  def tombstone?
    /^yes$/i.match?(tombstone)
  end

  def tombstone_message
    Sighrax.from_solr_document(solr_document).tombstone_message
  end

  def tombstone_thumbnail?
    return true unless respond_to?(:representative_id)
    Sighrax.from_noid(representative_id).tombstone?
  end

  def tombstone_thumbnail_tag(width, options = {})
    options[:style] = "max-width: #{width}px"
    ActionController::Base.helpers.image_tag('tombstone.svg', options)
  end
end


text:
namespace System.Diagnostics.CodeAnalysis
{
    using global::System;

#if DEBUG
    /// <summary>
    ///     Specifies that when a method returns <see cref="ReturnValue"/>,
    ///     the parameter will not be <see langword="null"/> even if the corresponding type allows it.
    /// </summary>
#endif
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if !NULLABLE_ATTRIBUTES_INCLUDE_IN_CODE_COVERAGE
    [DebuggerNonUserCode]
#endif
    internal sealed class NotNullWhenAttribute : Attribute
    {
#if DEBUG
        /// <summary>
        ///     Gets the return value condition.
        ///     If the method returns this value, the associated parameter will not be <see langword="null"/>.
        /// </summary>
#endif
        public bool ReturnValue { get; }

#if DEBUG
        /// <summary>
        ///     Initializes the attribute with the specified return value condition.
        /// </summary>
        /// <param name="returnValue">
        ///     The return value condition.
        ///     If the method returns this value, the associated parameter will not be <see langword="null"/>.
        /// </param>
#endif
        public NotNullWhenAttribute(bool returnValue)
        {
            ReturnValue = returnValue;
        }
    }
}

#pragma warning restore
#nullable restore
#endif // NULLABLE_ATTRIBUTES_DISABLE


text:
export const ACTION_STORAGE_LOCAL_DESTROYED     = 'STORAGE_LOCAL_DESTROYED';
export const ACTION_STORAGE_LOCAL_INDEXED       = 'STORAGE_LOCAL_INDEXED';
export const ACTION_STORAGE_LOCAL_STORED        = 'STORAGE_LOCAL_STORED';
export const ACTION_STORAGE_LOCAL_UPDATED       = 'STORAGE_LOCAL_UPDATED';
export const ACTION_STORAGE_LOCAL_VIEWED        = 'STORAGE_LOCAL_VIEWED';

// server
export const ACTION_STORAGE_SERVER_DESTROYED    = 'STORAGE_SERVER_DESTROYED';
export const ACTION_STORAGE_SERVER_INDEXED      = 'STORAGE_SERVER_INDEXED';
export const ACTION_STORAGE_SERVER_STORED       = 'STORAGE_SERVER_STORED';
export const ACTION_STORAGE_SERVER_UPDATED      = 'STORAGE_SERVER_UPDATED';
export const ACTION_STORAGE_SERVER_VIEWED       = 'STORAGE_SERVER_VIEWED';

export const ACTION_STORAGE_ERROR_CONNECTION        = 'STORAGE_ERROR_CONNECTION';
export const ACTION_STORAGE_ERROR_STORAGE_SERVER_INTERNAL   = 'ACTION_STORAGE_ERROR_STORAGE_SERVER_INTERNAL';
export const ACTION_STORAGE_ERROR_BAD_REQUEST       = 'STORAGE_ERROR_BAD_REQUEST';
export const ACTION_STORAGE_ERROR_UNKNOWN           = 'STORAGE_ERROR_UNKNOWN';

// misc
export const ACTION_STORAGE_WILL_SYNC               = 'STORAGE_WILL_SYNC';
export const ACTION_STORAGE_SYNCED                  = 'STORAGE_SYNCED';


text:
mkdir temp
mkdir temp/epub_source
mkdir data
mkdir data/paper
mkdir data/image
mkdir data/FormatA
mkdir data/FormatB
mkdir data/FormatATablet
mkdir data/FormatBTablet
mkdir data/FormatAMobile
mkdir data/FormatBMobile
mkdir data/pubmed
mkdir data/raw
mkdir data/attachment
mkdir data/gscholar


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Usnea hondoensis subsp. lacunosula Asahina

### Remarks
null


text:
#if!defined __TCPTRANSPORT_H__
#define __TCPTRANSPORT_H__

#include <map>
#include <string>
#include <list>
#include "Mutex.h"
#include "SocketUtil.h"

const int CLIENT_STATE_UNINIT = 0;
const int CLIENT_STATE_INITED = 1;
const int CLIENT_STATE_DISCONNECT = 2;
const int CLIENT_STATE_CONNECTED = 3;

const int CLIENT_ERROR_SUCCESS=0;
const int CLIENT_ERROR_INIT=1;
const int CLIENT_ERROR_INVALID_URL=2;
const int CLIENT_ERROR_CONNECT=3;
const int CLIENT_ERROR_OOM=4;

class TcpTransport
{
public:
	TcpTransport(std::map<std::string, std::string>& config);
	~TcpTransport();

	int Connect(const std::string &strServerURL);
	bool IsConnected();
	void Close();

	int SendData(const char* pBuffer, int len, int nTimeOut = -1);
	int RecvData(std::list<std::string*>& outDataList);
	void Run();
	SOCKET GetSocket();

private:
	int SendOneMsg(const char* pBuffer, int len, int nTimeout);
	int RecvMsg();
	void ProcessData(std::list<std::string*>& outDataList);
	bool ResizeBuf(int nNewSize);
	void TryShrink(int nMsgLen);
	static int GetMsgSize(const char * pBuf);

private:
	int m_sfd;
	int m_state;
	int m_recvBufSize;
	int m_recvBufUsed;
	int m_shrinkMax;
	int m_shrinkCheckCnt;
	kpr::Mutex m_sendLock;
	kpr::Mutex m_recvLock;
	std::string m_serverURL;
	char * m_pRecvBuf;
};

#endif


text:
package org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpressionList;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner;

/**
 * @author ilyas
 * Plain Argumanet list with parentheses. Cannot contain closure arguments, they are placed outside.
 */
public interface GrArgumentList extends GroovyPsiElement, GrNamedArgumentsOwner, PsiExpressionList {
  @NotNull GrExpression[] getExpressionArguments();

  @NotNull GroovyPsiElement[] getAllArguments();

  GrArgumentList replaceWithArgumentList(GrArgumentList newArgList) throws IncorrectOperationException;

  @Nullable
  PsiElement getLeftParen();

  @Nullable
  PsiElement getRightParen();

  int getExpressionArgumentIndex(GrExpression arg);

  GrNamedArgument addNamedArgument(GrNamedArgument namedArgument);
}


text:
class Array
  def pick
    at Kernel.rand(size)
  end
end


text:
#ifndef MODULES_RTP_RTCP_SOURCE_RTP_VIDEO_HEADER_H_
#define MODULES_RTP_RTCP_SOURCE_RTP_VIDEO_HEADER_H_

#include <cstdint>

#include "absl/container/inlined_vector.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "api/transport/rtp/dependency_descriptor.h"
#include "api/video/color_space.h"
#include "api/video/video_codec_type.h"
#include "api/video/video_content_type.h"
#include "api/video/video_frame_marking.h"
#include "api/video/video_frame_type.h"
#include "api/video/video_rotation.h"
#include "api/video/video_timing.h"
#include "common_types.h"  // NOLINT(build/include)
#include "modules/video_coding/codecs/h264/include/h264_globals.h"
#include "modules/video_coding/codecs/vp8/include/vp8_globals.h"
#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"

namespace webrtc {
// Details passed in the rtp payload for legacy generic rtp packetizer.
// TODO(bugs.webrtc.org/9772): Deprecate in favor of passing generic video
// details in an rtp header extension.
struct RTPVideoHeaderLegacyGeneric {
  uint16_t picture_id;
};

using RTPVideoTypeHeader = absl::variant<absl::monostate,
                                         RTPVideoHeaderVP8,
                                         RTPVideoHeaderVP9,
                                         RTPVideoHeaderH264,
                                         RTPVideoHeaderLegacyGeneric>;

struct RTPVideoHeader {
  struct GenericDescriptorInfo {
    GenericDescriptorInfo();
    GenericDescriptorInfo(const GenericDescriptorInfo& other);
    ~GenericDescriptorInfo();

    int64_t frame_id = 0;
    int spatial_index = 0;
    int temporal_index = 0;
    absl::InlinedVector<DecodeTargetIndication, 10> decode_target_indications;
    absl::InlinedVector<int64_t, 5> dependencies;
  };

  RTPVideoHeader();
  RTPVideoHeader(const RTPVideoHeader& other);

  ~RTPVideoHeader();

  absl::optional<GenericDescriptorInfo> generic;

  VideoFrameType frame_type = VideoFrameType::kEmptyFrame;
  uint16_t width = 0;
  uint16_t height = 0;
  VideoRotation rotation = VideoRotation::kVideoRotation_0;
  VideoContentType content_type = VideoContentType::UNSPECIFIED;
  bool is_first_packet_in_frame = false;
  bool is_last_packet_in_frame = false;
  uint8_t simulcastIdx = 0;
  VideoCodecType codec = VideoCodecType::kVideoCodecGeneric;

  PlayoutDelay playout_delay = {-1, -1};
  VideoSendTiming video_timing;
  FrameMarking frame_marking = {false, false, false, false, false, 0xFF, 0, 0};
  absl::optional<ColorSpace> color_space;
  RTPVideoTypeHeader video_type_header;
};

}  // namespace webrtc

#endif  // MODULES_RTP_RTCP_SOURCE_RTP_VIDEO_HEADER_H_


text:
<?php
namespace TYPO3\CMS\Fluid\Tests\Unit\ViewHelpers;

/*                                                                        *
 * This script is backported from the FLOW3 package "TYPO3.Fluid".        *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 *  of the License, or (at your option) any later version.                *
 *                                                                        *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * Testcase for RenderChildren ViewHelper
 */
class RenderChildrenViewHelperTest extends \TYPO3\CMS\Fluid\Tests\Unit\ViewHelpers\ViewHelperBaseTestcase
{
    /**
     * @var \TYPO3\CMS\Fluid\ViewHelpers\RenderChildrenViewHelper
     */
    protected $viewHelper;

    /**

     */
    protected function setUp()
    {
        $this->controllerContext = $this->getMock(\TYPO3\CMS\Extbase\Mvc\Controller\ControllerContext::class, [], [], '', false);
        $this->viewHelper = $this->getAccessibleMock(\TYPO3\CMS\Fluid\ViewHelpers\RenderChildrenViewHelper::class, ['renderChildren']);
        $this->viewHelper->_set('controllerContext', $this->controllerContext);
    }

    /**
     * @test
     */
    public function renderCallsEvaluateOnTheRootNodeAndRegistersTheArguments()
    {
        $this->request = $this->getMock(\TYPO3\CMS\Fluid\Core\Widget\WidgetRequest::class);
        $this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($this->request));
        $this->viewHelper->initializeArguments();
        $templateVariableContainer = $this->getMock(\TYPO3\CMS\Fluid\Core\ViewHelper\TemplateVariableContainer::class);
        $templateVariableContainer->expects($this->at(0))->method('add')->with('k1', 'v1');
        $templateVariableContainer->expects($this->at(1))->method('add')->with('k2', 'v2');
        $templateVariableContainer->expects($this->at(2))->method('remove')->with('k1');
        $templateVariableContainer->expects($this->at(3))->method('remove')->with('k2');
        $renderingContext = $this->getMock(\TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface::class);
        $renderingContext->expects($this->any())->method('getTemplateVariableContainer')->will($this->returnValue($templateVariableContainer));
        $rootNode = $this->getMock(\TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\RootNode::class);
        $widgetContext = $this->getMock(\TYPO3\CMS\Fluid\Core\Widget\WidgetContext::class);
        $this->request->expects($this->any())->method('getWidgetContext')->will($this->returnValue($widgetContext));
        $widgetContext->expects($this->any())->method('getViewHelperChildNodeRenderingContext')->will($this->returnValue($renderingContext));
        $widgetContext->expects($this->any())->method('getViewHelperChildNodes')->will($this->returnValue($rootNode));
        $rootNode->expects($this->any())->method('evaluate')->with($renderingContext)->will($this->returnValue('Rendered Results'));
        $output = $this->viewHelper->render(['k1' => 'v1', 'k2' => 'v2']);
        $this->assertEquals('Rendered Results', $output);
    }

    /**
     * @test
     * @expectedException \TYPO3\CMS\Fluid\Core\Widget\Exception\WidgetRequestNotFoundException
     */
    public function renderThrowsExceptionIfTheRequestIsNotAWidgetRequest()
    {
        $this->request = $this->getMock('Tx_Fluid_MVC_Request');
        $this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($this->request));
        $this->viewHelper->initializeArguments();
        $this->viewHelper->render();
    }

    /**
     * @test
     * @expectedException \TYPO3\CMS\Fluid\Core\Widget\Exception\RenderingContextNotFoundException
     */
    public function renderThrowsExceptionIfTheChildNodeRenderingContextIsNotThere()
    {
        $this->request = $this->getMock(\TYPO3\CMS\Fluid\Core\Widget\WidgetRequest::class);
        $this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($this->request));
        $this->viewHelper->initializeArguments();
        $widgetContext = $this->getMock(\TYPO3\CMS\Fluid\Core\Widget\WidgetContext::class);
        $this->request->expects($this->any())->method('getWidgetContext')->will($this->returnValue($widgetContext));
        $widgetContext->expects($this->any())->method('getViewHelperChildNodeRenderingContext')->will($this->returnValue(null));
        $widgetContext->expects($this->any())->method('getViewHelperChildNodes')->will($this->returnValue(null));
        $this->viewHelper->render();
    }
}


text:
package org.kuali.rice.core.framework.resourceloader;

import java.util.Collections;
import java.util.List;

import javax.servlet.ServletContext;
import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.config.ConfigurationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * A simple {@link org.kuali.rice.core.api.resourceloader.ResourceLoader} which wraps a Spring {@link ConfigurableApplicationContext}.
 *
 * Starts and stops the {@link ConfigurableApplicationContext}.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class SpringResourceLoader extends BaseResourceLoader {

	private SpringResourceLoader parentSpringResourceLoader;

	private ApplicationContext parentContext;
	private ConfigurableApplicationContext context;
	private ServletContext servletContextcontext;

	private final List<String> fileLocs;

	public SpringResourceLoader(QName name, String fileLoc, ServletContext context) {
	    this(name, Collections.singletonList(fileLoc), context);
	}

	public SpringResourceLoader(QName name, List<String> fileLocs, ServletContext servletContextcontext) {
		super(name);
		this.fileLocs = fileLocs;
		this.servletContextcontext = servletContextcontext;
	}

	@Override
	public Object getService(QName serviceName) {
	    	if (!isStarted()) {
	    	    return null;
	    	}
		if (this.getContext().containsBean(serviceName.toString())) {
			Object service = this.getContext().getBean(serviceName.toString());
			return postProcessService(serviceName, service);
		}
		return super.getService(serviceName);
	}

	@Override
	public void start() throws Exception {
		if(!isStarted()){
			LOG.info("Creating Spring context " + StringUtils.join(this.fileLocs, ","));
			if (parentSpringResourceLoader != null && parentContext != null) {
				throw new ConfigurationException("Both a parentSpringResourceLoader and parentContext were defined.  Only one can be defined!");
			}
			if (parentSpringResourceLoader != null) {
				parentContext = parentSpringResourceLoader.getContext();
			}

			if (servletContextcontext != null) {
				XmlWebApplicationContext lContext = new XmlWebApplicationContext();
				lContext.setServletContext(servletContextcontext);
				lContext.setParent(parentContext);
				lContext.setConfigLocations(this.fileLocs.toArray(new String[] {}));
				lContext.refresh();
				context = lContext;
			} else {
				this.context = new ClassPathXmlApplicationContext(this.fileLocs.toArray(new String[] {}), parentContext);
			}

			super.start();
		}
	}

	@Override
	public void stop() throws Exception {
		if (this.context != null) {
	        LOG.info("Stopping Spring context " + StringUtils.join(this.fileLocs, ","));
		    this.context.close();
		}
		super.stop();
	}

	public ConfigurableApplicationContext getContext() {
		return this.context;
	}

	public void setParentContext(ApplicationContext parentContext) {
		this.parentContext = parentContext;
	}

	public void setParentSpringResourceLoader(
			SpringResourceLoader parentSpringResourceLoader) {
		this.parentSpringResourceLoader = parentSpringResourceLoader;
	}

	@Override
	public String getContents(String indent, boolean servicePerLine) {
		String contents = "";
		for (String name : context.getBeanDefinitionNames()) {
			if (servicePerLine) {
				contents += indent + "+++" + name + "\n";
			} else {
				contents += name + ", ";
			}
		}
		return contents;
	}

}


text:
/**
 * Main Application class.
 *
 * @export
 * @class App
 */
import "@polymer/app-route/app-location";
import "@polymer/app-route/app-route";
import "@polymer/iron-pages/iron-pages";
import {customElement} from "@polymer/decorators";
import {PolymerElement} from "@polymer/polymer/polymer-element";
import template from "./app.html";
import "./child/child";

@customElement("unite-app")
export class App extends PolymerElement {
    /**
     * Get the template.
     * @readonly
     * @static
     * @returns {HTMLTemplateElement}
     */
    static get template() {
        const temp = document.createElement("template");
        temp.innerHTML = template.trim();
        return temp;
    }
}

/* Generated by UniteJS */


text:
<?php

namespace Content\Models;

interface DomainEntityInterface {

}


text:
# $ vtkpython TestImagePlaneWidget.py --help
# provides more details on other options.

import os
import os.path
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

class TestImagePlaneWidget(Testing.vtkTest):
    def testBug(self):
        # Uncomment the next line if you want to run this via
        # `gdb python`.
        #raw_input('Hit Ctrl-C')

        # Load some data.
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(os.path.join(VTK_DATA_ROOT,
                                       "Data", "headsq", "quarter"))
        v16.SetImageRange(1, 93)
        v16.SetDataSpacing(3.2, 3.2, 1.5)
        v16.Update()

        xMin, xMax, yMin, yMax, zMin, zMax = v16.GetExecutive().GetWholeExtent(v16.GetOutputInformation(0))
        img_data = v16.GetOutput()

        # **************************************************
        # Look here for wierdness.

        # Lets create this data using the data from the reader.
        my_img_data = vtk.vtkImageData()
        my_img_data.SetDimensions(img_data.GetDimensions())
#        my_img_data.SetWholeExtent(img_data.GetWholeExtent())
        my_img_data.SetExtent(img_data.GetExtent())
#        my_img_data.SetUpdateExtent(img_data.GetUpdateExtent())
        my_img_data.SetSpacing(img_data.GetSpacing())
        my_img_data.SetOrigin(img_data.GetOrigin())
        my_img_data.SetScalarType(img_data.GetScalarType(), my_img_data.GetInformation())
        my_img_data.GetPointData().SetScalars(img_data.GetPointData().GetScalars())
        # hang on to original image data.
        orig_img_data = img_data

        # hijack img_data with our own.  If you comment this out everything is
        # fine.
        img_data = my_img_data
        # **************************************************

        spacing = img_data.GetSpacing()
        sx, sy, sz = spacing

        origin = img_data.GetOrigin()
        ox, oy, oz = origin

        # An outline is shown for context.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputData(img_data)

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # The shared picker enables us to use 3 planes at one time
        # and gets the picking order right
        picker = vtk.vtkCellPicker()
        picker.SetTolerance(0.005)

        # The 3 image plane widgets are used to probe the dataset.
        planeWidgetX = vtk.vtkImagePlaneWidget()
        planeWidgetX.DisplayTextOn()
        planeWidgetX.SetInputData(img_data)
        planeWidgetX.SetPlaneOrientationToXAxes()
        planeWidgetX.SetSliceIndex(32)
        planeWidgetX.SetPicker(picker)
        planeWidgetX.SetKeyPressActivationValue("x")
        prop1 = planeWidgetX.GetPlaneProperty()
        prop1.SetColor(1, 0, 0)

        planeWidgetY = vtk.vtkImagePlaneWidget()
        planeWidgetY.DisplayTextOn()
        planeWidgetY.SetInputData(img_data)
        planeWidgetY.SetPlaneOrientationToYAxes()
        planeWidgetY.SetSliceIndex(32)
        planeWidgetY.SetPicker(picker)
        planeWidgetY.SetKeyPressActivationValue("y")
        prop2 = planeWidgetY.GetPlaneProperty()
        prop2.SetColor(1, 1, 0)
        planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())

        # for the z-slice, turn off texture interpolation:
        # interpolation is now nearest neighbour, to demonstrate
        # cross-hair cursor snapping to pixel centers
        planeWidgetZ = vtk.vtkImagePlaneWidget()
        planeWidgetZ.DisplayTextOn()
        planeWidgetZ.SetInputData(img_data)
        planeWidgetZ.SetPlaneOrientationToZAxes()
        planeWidgetZ.SetSliceIndex(46)
        planeWidgetZ.SetPicker(picker)
        planeWidgetZ.SetKeyPressActivationValue("z")
        prop3 = planeWidgetZ.GetPlaneProperty()
        prop3.SetColor(0, 0, 1)
        planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())

        # Create the RenderWindow and Renderer
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # Add the outline actor to the renderer, set the background
        # color and size
        ren.AddActor(outlineActor)
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()

if __name__ == "__main__":
    Testing.main([(TestImagePlaneWidget, 'test')])


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>facebook-overflow example</title>

I jump up and down

I don't


text:
		<title>Radiologie Trainer</title>
		<link rel="stylesheet" href="css/style.css" type="text/css">


text:
from django.conf.urls import patterns, url

from subdomains.tests.urls.default import urlpatterns as default_patterns
from subdomains.tests.views import view

urlpatterns = default_patterns + patterns(
    '',  # prefix
    url(regex=r'^$', view=view, name='home'),
    url(regex=r'^view/$', view=view, name='view'),
)


text:
<!DOCTYPE html>

		<title>Cadastro de pessoas</title>

		<form class="form-horizontal" method="POST" th:action="@{/pessoas}" th:object="${pessoa}">

Novo cadastro

						Voltar para pesquisa

	    			<input type="hidden" th:field="*{codigo}" />

							( * ) Campo obrigatório

						Nome

							<input type="text" class="form-control" id="nome" th:field="*{nome}"
								autofocus="autofocus" />

						CPF

							<input type="text" class="form-control" id="cpf" th:field="*{cpf}" />

						Telefone

							<input type="text" class="form-control" id="telefone" th:field="*{telefone}" />

						RG

							<input type="text" class="form-control" id="rg" th:field="*{rg}" />

						Pai

							<input type="text" class="form-control" id="pai" th:field="*{pai}" />

						Mãe

							<input type="text" class="form-control" id="mae" th:field="*{mae}" />

						UF de nascimento

							<select class="form-control" id="uf" th:field="*{uf}">
								<option th:each="uf : ${todosUfPessoa}" th:value="${uf}"
									th:text="${uf}"></option>
	                    	</select>

						Município de nascimento

							<input type="text" class="form-control" id="municipio" th:field="*{municipio}" />

						Data de nascimento

							<input type="text" class="form-control"	id="dataNascimento" th:field="*{dataNascimento}"
								data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-language="pt-BR" data-date-autoclose="true"
								data-date-today-highlight="true" data-date-orientation="bottom" />

						Status

							<select class="form-control" id="status" th:field="*{status}">
								<option th:each="status : ${todosStatusPessoa}" th:value="${status}"
									th:text="${status.descricao}"></option>
	                    	</select>

							<button type="submit" class="btn btn-primary">Salvar</button>

	    </form>


text:
package it.pkg.test.runner;

import static org.junit.Assert.assertNotNull;

import it.pkg.runner.AppRunner;
import org.junit.Test;

public class AppRunnerTest {

	@Test
	public void appRunnerTest1(){
		assertNotNull(new AppRunner());
	}
}


text:
package org.lewis.guava.qs.base;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.google.common.base.Strings;

/**
 * Test for Strings.
 *
 * @author lewis007
 * @since 0.1.0
 * @see com.google.common.base.Strings
 */
public class StringsTest {
	@Rule
	public ExpectedException exception = ExpectedException.none();

	@Test
	public void nullToEmpty() {
		Assert.assertEquals(Strings.nullToEmpty(null), "");
		Assert.assertEquals(Strings.nullToEmpty(""), "");
		Assert.assertEquals(Strings.nullToEmpty(" "), " ");
		Assert.assertEquals(Strings.nullToEmpty("test"), "test");
		Assert.assertEquals(Strings.nullToEmpty(" test "), " test ");

		Assert.assertNotEquals(Strings.nullToEmpty(" "), "");
		Assert.assertNotEquals(Strings.nullToEmpty(" test"), "test");
		Assert.assertNotEquals(Strings.nullToEmpty("test "), "test");
		Assert.assertNotEquals(Strings.nullToEmpty(" test "), "test");
	}

	@Test
	public void emptyToNull() {
		Assert.assertNull(Strings.emptyToNull(""));

		Assert.assertNotNull(Strings.emptyToNull(" "));
		Assert.assertNotNull(Strings.emptyToNull("test"));
	}

	@Test
	public void isNullOrEmpty() {
		Assert.assertEquals(Strings.isNullOrEmpty(null), true);
		Assert.assertEquals(Strings.isNullOrEmpty(""), true);

		Assert.assertEquals(Strings.isNullOrEmpty(" "), false);
		Assert.assertEquals(Strings.isNullOrEmpty("test"), false);
	}

	@Test
	public void padStart() {
		Assert.assertEquals(Strings.padStart("", 5, '-'), "-----");

		Assert.assertEquals(Strings.padStart("test", 5, '-'), "-test");
		Assert.assertNotEquals(Strings.padStart("test", 5, '-'), "-----test");

		Assert.assertEquals(Strings.padStart("test", 3, '-'), "test");
		Assert.assertNotEquals(Strings.padStart("test", 3, '-'), "tes");
		Assert.assertNotEquals(Strings.padStart("test", 3, '-'), "est");

		// 参数异常
		Assert.assertEquals(Strings.padStart("", 0, '-'), "");
		Assert.assertEquals(Strings.padStart("", -1, '-'), "");
		Assert.assertEquals(Strings.padStart("test", 5, ' '), " test");
	}

	@Test(expected = NullPointerException.class)
	public void padStartException() {
		Strings.padStart(null, 5, '-');
	}

	@Test
	public void padStartRule() {
		exception.expect(NullPointerException.class);
		Strings.padStart(null, 5, '-');
	}

	@Test
	public void padEnd() {
		Assert.assertEquals(Strings.padEnd("", 5, '-'), "-----");

		Assert.assertEquals(Strings.padEnd("test", 5, '-'), "test-");
		Assert.assertNotEquals(Strings.padEnd("test", 5, '-'), "test-----");

		Assert.assertEquals(Strings.padEnd("test", 3, '-'), "test");
		Assert.assertNotEquals(Strings.padEnd("test", 3, '-'), "tes");
		Assert.assertNotEquals(Strings.padEnd("test", 3, '-'), "est");

		// 参数异常
		Assert.assertEquals(Strings.padEnd("", 0, '-'), "");
		Assert.assertEquals(Strings.padEnd("", -1, '-'), "");
		Assert.assertEquals(Strings.padEnd("test", 5, ' '), "test ");
	}

	@Test(expected = NullPointerException.class)
	public void padEndException() {
		Strings.padEnd(null, 5, '-');
	}

	@Test
	public void padEndRule() {
		exception.expect(NullPointerException.class);
		Strings.padEnd(null, 5, '-');
	}

	@Test
	public void repeat() {
		Assert.assertEquals(Strings.repeat("test,", 6), "test,test,test,test,test,test,");

		Assert.assertEquals(Strings.repeat("", 6), "");
		Assert.assertEquals(Strings.repeat("test,", 0), "");
	}

	@Test(expected = NullPointerException.class)
	public void repeatException() {
		Strings.repeat(null, 6);
		Strings.repeat(null, -1);
	}

	@Test
	public void repeatRule() {
		exception.expect(IllegalArgumentException.class);
		Strings.repeat("test,", -1);
	}

	@Test
	public void commonPrefix() {
		Assert.assertEquals(Strings.commonPrefix("sfa-abcdefg", "sfa-hijklmn"), "sfa-");

		Assert.assertEquals(Strings.commonPrefix("x sfa-abcdefg", "- sfa-hijklmn"), "");
	}

	@Test
	public void commonSuffix() {
		Assert.assertEquals(Strings.commonSuffix("somebook.pdf", "others.pdf"), ".pdf");

		Assert.assertEquals(Strings.commonSuffix("somebook.pdf -", "others.pdf +"), "");
	}
}


text:
%% Small demonstration on how to use XLWRITE

%% Initialisation of POI Libs
% Add Java POI Libs to matlab javapath
javaaddpath('poi_library/dom4j-1.6.1.jar');
javaaddpath('poi_library/poi-3.8-20120326.jar');
javaaddpath('poi_library/poi-ooxml-3.8-20120326.jar');
javaaddpath('poi_library/poi-ooxml-schemas-3.8-20120326.jar');
javaaddpath('poi_library/stax-api-1.0.1.jar');
javaaddpath('poi_library/xmlbeans-2.3.0.jar');

%% Data Generation for XLSX
% Define an xls name
fileName = 'test_xlwrite.xlsx';
sheetName = 'this_is_sheetname';
startRange = 'B3';

% Generate some data
xlsData = {'A Number' 'Boolean Data' 'Empty Cells' 'Strings';...
    1 true [] 'String Text';...
    5 false [] 'Another very descriptive text';...
    -6.26 false 'This should have been an empty cell but I made an error' 'This is text';...
    1e8 true [] 'Last cell with text';...
    1e3 false NaN NaN;...
    1e2 true [] 'test'}

%% Generate XLSX file
xlwrite(fileName, xlsData, sheetName, startRange);


text:
#include <mitkTestingMacros.h>
#include <mitkImageGenerator.h>
#include <mitkOclBinaryThresholdImageFilter.h>

using namespace mitk;

/**
  This function is testing the OclFilter class and the
  OpenCL resource service. To prevent segmentation faults
  a mutexed reference counter is implemented in the resource service.
  It tracks the number of opencl program references for the corresponding filter
  and delete only the opencl programm if the reference count reaches 0.
  Every new instance of a filter increases the reference count by 1.
  This test runs successfull if the 2 filters are initialized, run
  and deleted without any crash.
  */
int mitkOclReferenceCountTest( int /*argc*/, char* /*argv*/[] )
{
  MITK_TEST_BEGIN("mitkOclReferenceCountTest");

  us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
  OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
  resources->GetContext(); //todo why do i need to call this before GetMaximumImageSize()?
  if(resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0)
  {
    //GPU device does not support 3D images. Skip this test.
    MITK_INFO << "Skipping test.";
    return 0;
  }

  mitk::Image::Pointer inputImage = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 52, 1, // dimension
                                                                                1.0f, 1.0f, 1.0f, // spacing
                                                                                255, 0); // max, min
  int upperThr = 255;
  int lowerThr = 60;
  int outsideVal = 0;
  int insideVal = 100;

  mitk::OclBinaryThresholdImageFilter::Pointer oclFilter1 = mitk::OclBinaryThresholdImageFilter::New();
  oclFilter1->SetInput( inputImage );
  oclFilter1->SetUpperThreshold( upperThr );
  oclFilter1->SetLowerThreshold( lowerThr );
  oclFilter1->SetOutsideValue( outsideVal );
  oclFilter1->SetInsideValue( insideVal );
  oclFilter1->Update();

  mitk::Image::Pointer outputImage1 = mitk::Image::New();
  outputImage1 = oclFilter1->GetOutput();

  mitk::OclBinaryThresholdImageFilter::Pointer oclFilter2 = mitk::OclBinaryThresholdImageFilter::New();

  oclFilter2->SetInput( inputImage );
  oclFilter2->SetUpperThreshold( upperThr );
  oclFilter2->SetLowerThreshold( lowerThr );
  oclFilter2->SetOutsideValue( outsideVal );
  oclFilter2->SetInsideValue( insideVal );
  oclFilter2->Update();

  mitk::Image::Pointer outputImage2 = mitk::Image::New();
  outputImage2 = oclFilter2->GetOutput();

  // delete filters
  oclFilter1 = NULL;
  oclFilter2 = NULL;

  // this is only visible if the delete did not cause a segmentation fault
  // it is always true and successfull if the program reaches this state
  MITK_TEST_CONDITION_REQUIRED( true, "2 Filters deleted without a crash -> success ");

  MITK_TEST_END();
}


text:
var assert = require("assert");

var generate_bsd_url = require("./index");

var api_id = "bsd-api-auth";
var api_timestamp = 1416856860;
var api_url = "https://sendto.mozilla.org/page/api/cons/get_constituents_by_id";
var api_version = "2"
var params = { cons_ids: 25730 };
var api_secret = "secret";
var api_signed_url = generate_bsd_url(api_id, api_timestamp, api_url, api_version, params, api_secret);

assert.equal(api_signed_url, "https://sendto.mozilla.org/page/api/cons/get_constituents_by_id?api_id=bsd-api-auth&api_ts=1416856860&api_ver=2&cons_ids=25730&api_mac=dc6aead204c9cdc8ce6683d8898cc9d8f3d041cb");


text:
package org.apache.hyracks.control.nc.resources;

import java.util.List;
import java.util.Vector;

import org.apache.hyracks.api.resources.IDeallocatable;
import org.apache.hyracks.api.resources.IDeallocatableRegistry;

public class DefaultDeallocatableRegistry implements IDeallocatableRegistry {
    private final List<IDeallocatable> deallocatables;

    public DefaultDeallocatableRegistry() {
        deallocatables = new Vector<IDeallocatable>();
    }

    @Override
    public void registerDeallocatable(IDeallocatable deallocatable) {
        deallocatables.add(deallocatable);
    }

    public void close() {
        for (IDeallocatable d : deallocatables) {
            try {
                d.deallocate();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}


text:
package io.jooby.utow;

import static io.undertow.UndertowOptions.ENABLE_HTTP2;

import java.net.BindException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import javax.net.ssl.SSLContext;

import org.xnio.Options;
import org.xnio.Sequence;
import org.xnio.SslClientAuthMode;

import edu.umd.cs.findbugs.annotations.NonNull;
import io.jooby.Jooby;
import io.jooby.Server;
import io.jooby.ServerOptions;
import io.jooby.SneakyThrows;
import io.jooby.SslOptions;
import io.jooby.internal.utow.UtowHandler;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.HttpContinueReadHandler;
import io.undertow.server.handlers.encoding.ContentEncodingRepository;
import io.undertow.server.handlers.encoding.DeflateEncodingProvider;
import io.undertow.server.handlers.encoding.EncodingHandler;
import io.undertow.server.handlers.encoding.GzipEncodingProvider;

/**
 * Web server implementation using Undertow.
 *
 * @author edgar
 * @since 2.0.0
 */
public class Utow extends Server.Base {

  private static final int BACKLOG = 8192;

  private static final int _100 = 100;

  private static final int _10 = 10;

  private Undertow server;

  private List<Jooby> applications = new ArrayList<>();

  private ServerOptions options =
      new ServerOptions().setIoThreads(ServerOptions.IO_THREADS).setServer("utow");

  @NonNull @Override
  public Utow setOptions(@NonNull ServerOptions options) {
    this.options = options.setIoThreads(options.getIoThreads());
    return this;
  }

  @NonNull @Override
  public ServerOptions getOptions() {
    return options;
  }

  @Override
  public Server start(@NonNull Jooby application) {
    try {
      applications.add(application);

      addShutdownHook();

      HttpHandler handler =
          new UtowHandler(
              applications.get(0),
              options.getBufferSize(),
              options.getMaxRequestSize(),
              options.getDefaultHeaders());

      if (options.getCompressionLevel() != null) {
        int compressionLevel = options.getCompressionLevel();
        handler =
            new EncodingHandler(
                handler,
                new ContentEncodingRepository()
                    .addEncodingHandler("gzip", new GzipEncodingProvider(compressionLevel), _100)
                    .addEncodingHandler(
                        "deflate", new DeflateEncodingProvider(compressionLevel), _10));
      }

      if (options.isExpectContinue() == Boolean.TRUE) {
        handler = new HttpContinueReadHandler(handler);
      }

      Undertow.Builder builder =
          Undertow.builder()
              .setBufferSize(options.getBufferSize())
              /** Socket : */
              .setSocketOption(Options.BACKLOG, BACKLOG)
              /** Server: */
              // HTTP/1.1 is keep-alive by default, turn this option off
              .setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false)
              .setServerOption(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, true)
              .setServerOption(UndertowOptions.ALWAYS_SET_DATE, options.getDefaultHeaders())
              .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, false)
              .setServerOption(UndertowOptions.DECODE_URL, false)
              /** Worker: */
              .setIoThreads(options.getIoThreads())
              .setWorkerOption(Options.WORKER_NAME, "worker")
              .setWorkerThreads(options.getWorkerThreads())
              .setHandler(handler);

      if (!options.isHttpsOnly()) {
        builder.addHttpListener(options.getPort(), options.getHost());
      }

      // HTTP @
      builder.setServerOption(ENABLE_HTTP2, options.isHttp2() == Boolean.TRUE);

      SSLContext sslContext = options.getSSLContext(application.getEnvironment().getClassLoader());
      if (sslContext != null) {
        builder.addHttpsListener(options.getSecurePort(), options.getHost(), sslContext);
        SslOptions ssl = options.getSsl();
        builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(ssl.getProtocol()));
        Optional.ofNullable(options.getSsl())
            .map(SslOptions::getClientAuth)
            .map(this::toSslClientAuthMode)
            .ifPresent(
                clientAuth -> builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, clientAuth));
      } else if (options.isHttpsOnly()) {
        throw new IllegalArgumentException(
            "Server configured for httpsOnly, but ssl options not set");
      }

      server = builder.build();
      server.start();
      // NOT IDEAL, but we need to fire onStart after server.start to get access to Worker
      fireStart(applications, server.getWorker());

      fireReady(Collections.singletonList(application));

      return this;
    } catch (RuntimeException x) {
      Throwable sourceException = x;
      Throwable cause = Optional.ofNullable(x.getCause()).orElse(x);
      if (Server.isAddressInUse(cause)) {
        sourceException = new BindException("Address already in use: " + options.getPort());
      }
      throw SneakyThrows.propagate(sourceException);
    }
  }

  private SslClientAuthMode toSslClientAuthMode(SslOptions.ClientAuth clientAuth) {
    switch (clientAuth) {
      case REQUESTED:
        return SslClientAuthMode.REQUESTED;
      case REQUIRED:
        return SslClientAuthMode.REQUIRED;
      default:
        return SslClientAuthMode.NOT_REQUESTED;
    }
  }

  @NonNull @Override
  public synchronized Server stop() {
    try {
      fireStop(applications);
      applications = null;
    } catch (Exception x) {
      throw SneakyThrows.propagate(x);
    } finally {
      shutdownServer();
    }
    return this;
  }

  private void shutdownServer() {
    if (server != null) {
      try {
        server.stop();
      } finally {
        server = null;
      }
    }
  }
}


text:
class GpaCounterGeneratorDx12Base : public GpaCounterGeneratorBase
{
public:
    /// @brief Get the SW counter description for the given SW counter index.
    ///
    /// @param [in] sw_counter_index The SW counter index.
    /// @param [out] sw_counter_desc Software counter description.
    ///
    /// @return The SW counter description.
    static bool GetSwCounterDesc(const GpaUInt32 sw_counter_index, GpaSoftwareCounterDesc& sw_counter_desc);

    /// @brief Constructor.
    GpaCounterGeneratorDx12Base() = default;

    /// @brief Virtual Destructor.
    virtual ~GpaCounterGeneratorDx12Base() = default;

protected:
    /// @copydoc GpaCounterGeneratorBase::GeneratePublicCounters()
    virtual GpaStatus GeneratePublicCounters(GDT_HW_GENERATION   desired_generation,
                                             GDT_HW_ASIC_TYPE    asic_type,
                                             GpaUInt8            generate_asic_specific_counters,
                                             GpaDerivedCounters* public_counters) override;

    /// @copydoc GpaCounterGeneratorBase::GenerateHardwareCounters()
    virtual GpaStatus GenerateHardwareCounters(GDT_HW_GENERATION    desired_generation,
                                               GDT_HW_ASIC_TYPE     asic_type,
                                               GpaUInt8             generate_asic_specific_counters,
                                               GpaHardwareCounters* hardware_counters) override;

    /// @copydoc GpaCounterGeneratorBase::GenerateSoftwareCounters()
    virtual GpaStatus GenerateSoftwareCounters(GDT_HW_GENERATION    desired_generation,
                                               GDT_HW_ASIC_TYPE     asic_type,
                                               GpaUInt8             generate_asic_specific_counters,
                                               GpaSoftwareCounters* software_counters) override;

    /// @copydoc GpaCounterGeneratorBase::ComputeSWCounterValue()
    void ComputeSwCounterValue(GpaUInt32 software_counter_index, GpaUInt64 value, void* result, const GpaHwInfo* hw_info) const override;

private:
    static const GpaSoftwareCounterDesc kDx12SoftwareCounters[];     ///< DX12 SW counters list.
    static const size_t                 kDx12SoftwareCountersCount;  ///< DX12 SW counter list size.

    /// @brief Copy constructor - private override to prevent usage.
    GpaCounterGeneratorDx12Base(const GpaCounterGeneratorDx12Base&) = delete;

    /// @brief Move constructor - private override to prevent usage.
    GpaCounterGeneratorDx12Base(GpaCounterGeneratorDx12Base&&) = delete;

    /// @brief Copy operator - private override to prevent usage.
    ///
    /// @return reference to object.
    GpaCounterGeneratorDx12Base& operator=(const GpaCounterGeneratorDx12Base&) = delete;

    /// @brief Move operator - private override to prevent usage.
    ///
    /// @return reference to object.
    GpaCounterGeneratorDx12Base& operator=(GpaCounterGeneratorDx12Base&&) = delete;

    /// @brief Generate DX12 API software counters.
    ///
    /// @return kGpaStatusOk if generating counters succeeded, false if it failed.
    GpaStatus GenerateDX12SoftwareCounters() const;
};

#endif  // GPU_PERF_API_COUNTER_GENERATOR_DX12_GPA_COUNTER_GENERATOR_DX12_BASE_H_


text:
using namespace rime;

using TestDb = UserDbWrapper<TextDb>;

TEST(RimeUserDbTest, AccessRecordByKey) {
  TestDb db("user_db_test.txt", "user_db_test");
  if (db.Exists())
    db.Remove();
  ASSERT_FALSE(db.Exists());
  db.Open();
  EXPECT_TRUE(db.loaded());
  EXPECT_TRUE(db.Update("abc", "ZYX"));
  EXPECT_TRUE(db.Update("zyx", "CBA"));
  EXPECT_TRUE(db.Update("zyx", "ABC"));
  string value;
  EXPECT_TRUE(db.Fetch("abc", &value));
  EXPECT_EQ("ZYX", value);
  value.clear();
  EXPECT_TRUE(db.Fetch("zyx", &value));
  EXPECT_EQ("ABC", value);
  value.clear();
  EXPECT_FALSE(db.Fetch("wvu", &value));
  EXPECT_TRUE(value.empty());
  value.clear();
  EXPECT_TRUE(db.Erase("zyx"));
  EXPECT_FALSE(db.Fetch("zyx", &value));
  EXPECT_TRUE(value.empty());
  EXPECT_TRUE(db.Close());
  ASSERT_FALSE(db.loaded());
}

TEST(RimeUserDbTest, Query) {
  TestDb db("user_db_test.txt", "user_db_test");
  if (db.Exists())
    db.Remove();
  ASSERT_FALSE(db.Exists());
  db.Open();
  EXPECT_TRUE(db.Update("abc", "ZYX"));
  EXPECT_TRUE(db.Update("abc\tdef", "ZYX WVU"));
  EXPECT_TRUE(db.Update("zyx", "ABC"));
  EXPECT_TRUE(db.Update("wvu", "DEF"));
  {
    an<DbAccessor> accessor = db.Query("abc");
    ASSERT_TRUE(bool(accessor));
    EXPECT_FALSE(accessor->exhausted());
    string key, value;
    EXPECT_TRUE(accessor->GetNextRecord(&key, &value));
    EXPECT_EQ("abc", key);
    EXPECT_EQ("ZYX", value);
    key.clear();
    value.clear();
    EXPECT_TRUE(accessor->GetNextRecord(&key, &value));
    EXPECT_EQ("abc\tdef", key);
    EXPECT_EQ("ZYX WVU", value);
    key.clear();
    value.clear();
    EXPECT_FALSE(accessor->GetNextRecord(&key, &value));
    // key, value contain invalid contents
    EXPECT_EQ("", key);
    EXPECT_EQ("", value);
  }
  {
    an<DbAccessor> accessor = db.Query("wvu\tt");
    ASSERT_TRUE(bool(accessor));
    EXPECT_TRUE(accessor->exhausted());
    string key, value;
    EXPECT_FALSE(accessor->GetNextRecord(&key, &value));
  }
  {
    an<DbAccessor> accessor = db.Query("z");
    ASSERT_TRUE(bool(accessor));
    EXPECT_FALSE(accessor->exhausted());
    string key, value;
    EXPECT_TRUE(accessor->GetNextRecord(&key, &value));
    EXPECT_EQ("zyx", key);
    EXPECT_EQ("ABC", value);
    EXPECT_FALSE(accessor->GetNextRecord(&key, &value));
  }
  db.Close();
}


text:
Javascript library to connect and interact with Quassel IRC server.

## Install
```sh
npm install --production libquassel
```

## Use in browser
You just need to import `dist/libquassel.js` in your HTML page.

## Development
```sh
npm install libquassel
```

In order to create a browser compatible file, run the following commands
```sh
# use browserify to build on change
npm run watch
# before commit, make the dev version + minified version + the doc
npm run build
```

### 3.0 breaking changes
Version `3.0` introduces the following breaking changes:

- `message.Type` has been superseded by `message.Types`, and all its constants are now UPPERCASE
- `channel.active` has been superseded by `channel.isActive`
- `channel.isChannel()` has been superseded by `channel.isChannel`
- `channel.isHighlighted()` has been superseded by `channel.isHighlighted`
- `message.isHighlighted()` has been superseded by `message.isHighlighted`
- `message.isSelf()` has been superseded by `message.isSelf`
- `network.getBufferCollection()` and `network.getBufferMap()` have been merged into `networks.buffers`
- `networkCollection.findBuffer(...)` and `networkCollection.get(...)` have been merged into `network.getBuffer(...)`
- The majority of setter methods has been replaced by direct affectation to the target property
  - e.g. `network.setName(name)` as been superseded by `network.name = name`
- The majority of getter methods has been replaced by direct access to the target property
  - e.g. `network.getStatusBuffer()` as been superseded by `network.statusBuffer`

#### node specific
- `Client(...).connect` method expects a `Socket` or any other `Duplex` as parameter.

#### browser specific
- `libquassel` is available as a global object.
- `Client(...).connect` method expects a `libquassel.WebSocketStream` or any other `Duplex` as parameter.

### Getting Started
#### node
```javascript
const { Client } = require('libquassel');
const net = require('net');

const socket = net.createConnection({
  host: "localhost",
  port: 4242
});

const quassel = new Client((next) => next("user", "password"));

quassel.on('network.init', (networkId) => {
    network = quassel.networks.get(networkId);
    // ...
});

// ...

quassel.connect(socket);
```

#### browser
```html
<!-- In your HTML -->
<script src="/path/to/libquassel.js"></script>
```
```javascript
// libquassel in available as a global in browser
const socket = new libquassel.WebSocketStream('wss://domain.tld:12345', ['binary', 'base64']);
const quassel = new libquassel.Client((next) => next("user", "password"));

quassel.on('network.init', (networkId) => {
    network = quassel.networks.get(networkId);
    // ...
});

// ...

quassel.connect(socket);
```

### Documentation
[3.1.0](https://magne4000.github.com/libquassel/3.1.0 "libquassel 3.1.0 documentation")

### Examples
See [test](test) folder for examples.

### Changelog

#### 3.1.0
- Add support for core highlight rules

#### 3.1.1
- Update dependencies

## License
Copyright (c) 2019 Joël Charles
Licensed under the MIT license.


text:
package io.strimzi.api.kafka.model;

import io.strimzi.test.TestUtils;
import io.strimzi.test.k8s.exceptions.KubeClusterException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertThrows;

/**
 * The purpose of this test is to confirm that we can create a
 * resource from the POJOs, serialize it and create the resource in K8S.
 * I.e. that such instance resources obtained from POJOs are valid according to the schema
 * validation done by K8S.
 */
public class KafkaRebalanceCrdIT extends AbstractCrdIT {

    public static final String NAMESPACE = "kafkarebalance-crd-it";

    @Test
    void testKafkaRebalanceIsNotScaling() {
        assertThrows(KubeClusterException.class, () -> createScaleDelete(KafkaRebalance.class, "KafkaRebalance.yaml"));
    }

    @Test
    void testKafkaRebalanceMinimal() {
        createDeleteCustomResource("KafkaRebalance-minimal.yaml");
    }

    @Test
    void testKafkaRebalanceWithGoals() {
        createDeleteCustomResource("KafkaRebalance-with-goals.yaml");
    }

    @Test
    void testKafkaRebalanceWithGoalsSkipHardGoalCheck() {
        createDeleteCustomResource("KafkaRebalance-with-goals-skip-hard-goal-check.yaml");
    }

    @Test
    void testKafkaRebalanceWithPerformanceTuning() {
        createDeleteCustomResource("KafkaRebalance-performance-tuning.yaml");
    }

    @Test
    void testKafkaRebalanceWithExcludedTopics() {
        createDeleteCustomResource("KafkaRebalance-excluded-topics.yaml");
    }

    @Test
    void testKafkaRebalanceAddBroker() {
        createDeleteCustomResource("KafkaRebalance-add-brokers.yaml");
    }

    @Test
    void testKafkaRebalanceRemoveBroker() {
        createDeleteCustomResource("KafkaRebalance-remove-brokers.yaml");
    }

    @Test
    void testKafkaRebalanceWrongMode() {
        Throwable exception = assertThrows(
                KubeClusterException.class,
                () -> createDeleteCustomResource("KafkaRebalance-wrong-mode.yaml"));

        assertThat(exception.getMessage(), containsString("spec.mode: Unsupported value: \"wrong-mode\": supported values: \"full\", \"add-brokers\", \"remove-brokers\""));
    }

    @BeforeAll
    void setupEnvironment() {
        cluster.createCustomResources(TestUtils.CRD_KAFKA_REBALANCE);
        cluster.waitForCustomResourceDefinition("kafkarebalances.kafka.strimzi.io");
        cluster.createNamespace(NAMESPACE);

        try {
            Thread.sleep(1_000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @AfterAll
    void teardownEnvironment() {
        cluster.deleteCustomResources();
        cluster.deleteNamespaces();
    }
}


text:
WaitStaff Calculator
=========

Waitstaff is an application for calculating Tips. This is an example implementation of a project for the Thinkful Angular course.

Unit 1 Lesson 3


text:
import React from 'react'
import { shallow } from 'enzyme'

import Logout from '../../app/containers/App/Sidebar/Logout/Logout'

describe('Logout', () => {
  const logout = jest.fn()

  const promptHasBeenDisplayed = jest.fn()

  test('should render without crashing', () => {
    const wrapper = shallow(<Logout logout={logout} />)
    expect(wrapper).toMatchSnapshot()
  })

  test('should dispatch logout action when clicked', () => {
    const wrapper = shallow(
      <Logout
        id="logout"
        logout={logout}
        promptHasBeenDisplayed={promptHasBeenDisplayed}
      />,
    )
    expect(logout.mock.calls.length).toEqual(0)
    wrapper.find('#logout').simulate('click')
    expect(logout.mock.calls.length).toEqual(1)
  })
})


text:
import sys
import os
import threading
import socket
import fcntl

from errno import EAGAIN, EINTR, EWOULDBLOCK

try:
    from OpenSSL import SSL
except ImportError:
    pass

from xen.xend.XendLogging import log

"""General classes to support server and client sockets, without
specifying what kind of socket they are. There are subclasses
for TCP and unix-domain sockets (see tcp.py and unix.py).
"""

BUFFER_SIZE = 16384
BACKLOG = 5

class SocketServerConnection:
    """An accepted connection to a server.
    """

    def __init__(self, sock, protocol_class):
        self.sock = sock
        self.protocol = protocol_class()
        self.protocol.setTransport(self)
        threading.Thread(target=self.main).start()

    def main(self):
        try:
            while True:
                try:
                    data = self.sock.recv(BUFFER_SIZE)
                    if data == '':
                        break
                    if self.protocol.dataReceived(data):
                        break
                except socket.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
        finally:
            try:
                self.sock.close()
            except:
                pass

    def close(self):
        self.sock.close()

    def write(self, data):
        self.sock.send(data)

class SocketListener:
    """A server socket, running listen in a thread.
    Accepts connections and runs a thread for each one.
    """

    def __init__(self, protocol_class):
        self.protocol_class = protocol_class
        self.sock = self.createSocket()
        threading.Thread(target=self.main).start()

    def close(self):
        try:
            self.sock.close()
        except:
            pass

    def createSocket(self):
        raise NotImplementedError()

    def acceptConnection(self, sock, protocol, addr):
        raise NotImplementedError()

    def main(self):
        try:
            fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
            self.sock.listen(BACKLOG)

            while True:
                try:
                    (sock, addr) = self.sock.accept()
                    self.acceptConnection(sock, addr)
                except socket.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
        finally:
            self.close()

class SSLSocketServerConnection(SocketServerConnection):
    """An SSL aware accepted connection to a server.

    As pyOpenSSL SSL.Connection fileno() method just retrieve the file
    descriptor number for the underlying socket, direct read/write to the file
    descriptor will result no data encrypted.

    recv2fd() and fd2send() are simple wrappers for functions who need direct
    read/write to a file descriptor rather than a socket like object.

    To use recv2fd(), you can create a pipe and start a thread to transfer all
    received data to one end of the pipe, then read from the other end:

    p2cread, p2cwrite = os.pipe()
    threading.Thread(target=connection.SSLSocketServerConnection.recv2fd,
                     args=(sock, p2cwrite)).start()
    os.read(p2cread, 1024)

    To use fd2send():

    p2cread, p2cwrite = os.pipe()
    threading.Thread(target=connection.SSLSocketServerConnection.fd2send,
                     args=(sock, p2cread)).start()
    os.write(p2cwrite, "data")
    """

    def __init__(self, sock, protocol_class):
        SocketServerConnection.__init__(self, sock, protocol_class)

    def main(self):
        try:
            while True:
                try:
                    data = self.sock.recv(BUFFER_SIZE)
                    if data == "":
                        break
                    if self.protocol.dataReceived(data):
                        break
                except socket.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
                except (SSL.WantReadError, SSL.WantWriteError, \
                        SSL.WantX509LookupError):
                    # The operation did not complete; the same I/O method
                    # should be called again.
                    continue
                except SSL.ZeroReturnError:
                    # The SSL Connection has been closed.
                    break
                except SSL.SysCallError, (retval, desc):
                    if ((retval == -1 and desc == "Unexpected EOF")
                        or retval > 0):
                        # The SSL Connection is lost.
                        break
                    log.debug("SSL SysCallError:%d:%s" % (retval, desc))
                    break
                except SSL.Error, e:
                    # other SSL errors
                    log.debug("SSL Error:%s" % e)
                    break
        finally:
            try:
                self.sock.close()
            except:
                pass

    def recv2fd(sock, fd):
        try:
            while True:
                try:
                    data = sock.recv(BUFFER_SIZE)
                    if data == "":
                        break
                    count = 0
                    while count < len(data):
                        try:
                            nbytes = os.write(fd, data[count:])
                            count += nbytes
                        except os.error, ex:
                            if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                                raise
                except socket.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
                except (SSL.WantReadError, SSL.WantWriteError, \
                        SSL.WantX509LookupError):
                    # The operation did not complete; the same I/O method
                    # should be called again.
                    continue
                except SSL.ZeroReturnError:
                    # The SSL Connection has been closed.
                    break
                except SSL.SysCallError, (retval, desc):
                    if ((retval == -1 and desc == "Unexpected EOF")
                        or retval > 0):
                        # The SSL Connection is lost.
                        break
                    log.debug("SSL SysCallError:%d:%s" % (retval, desc))
                    break
                except SSL.Error, e:
                    # other SSL errors
                    log.debug("SSL Error:%s" % e)
                    break
        finally:
            try:
                sock.close()
                os.close(fd)
            except:
                pass

    recv2fd = staticmethod(recv2fd)

    def fd2send(sock, fd):
        try:
            while True:
                try:
                    data = os.read(fd, BUFFER_SIZE)
                    if data == "":
                        break
                    count = 0
                    while count < len(data):
                        try:
                            nbytes = sock.send(data[count:])
                            count += nbytes
                        except socket.error, ex:
                            if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                                raise
                        except (SSL.WantReadError, SSL.WantWriteError, \
                                SSL.WantX509LookupError):
                            # The operation did not complete; the same I/O method
                            # should be called again.
                            continue
                        except SSL.ZeroReturnError:
                            # The SSL Connection has been closed.
                            raise
                        except SSL.SysCallError, (retval, desc):
                            if not (retval == -1 and data == ""):
                                # errors when writing empty strings are expected
                                # and can be ignored
                                log.debug("SSL SysCallError:%d:%s" % (retval, desc))
                                raise
                        except SSL.Error, e:
                            # other SSL errors
                            log.debug("SSL Error:%s" % e)
                            raise
                except os.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
        finally:
            try:
                sock.close()
                os.close(fd)
            except:
                pass

    fd2send = staticmethod(fd2send)

def hostAllowed(addrport, hosts_allowed):
    if hosts_allowed is None:
        return True
    else:
        fqdn = socket.getfqdn(addrport[0])
        for h in hosts_allowed:
            if h.match(fqdn) or h.match(addrport[0]):
                return True
        log.warn("Rejected connection from %s (%s).", addrport[0], fqdn)
        return False

class SocketDgramListener:
    """A connectionless server socket, running listen in a thread.
    """

    def __init__(self, protocol_class):
        self.protocol = protocol_class()
        self.sock = self.createSocket()
        threading.Thread(target=self.main).start()

    def close(self):
        try:
            self.sock.close()
        except:
            pass

    def createSocket(self):
        raise NotImplementedError()

    def main(self):
        try:
            fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)

            while True:
                try:
                    data = self.sock.recv(BUFFER_SIZE)
                    self.protocol.dataReceived(data)
                except socket.error, ex:
                    if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
                        break
        finally:
            try:
                self.close()
            except:
                pass


text:
<refentry id="default.float.class">
<refmeta>
<refentrytitle>default.float.class</refentrytitle>
<refmiscinfo role="type">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>default.float.class</refname>
<refpurpose>Specifies the default float class</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='default.float.class.frag'>
<xsl:param name="default.float.class" select="'before'"/>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>FIXME:</para>

</refsect1>
</refentry>


text:
<title>S12Z - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Architectures.html#Architectures" title="Architectures">
<link rel="prev" href="Sparc64.html#Sparc64" title="Sparc64">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Previous: Sparc64,
Up: Architectures

21.4.10 S12Z

When gdb is debugging the S12Z architecture,
it provides the following special command:

maint info bdccsr
This command displays the current value of the microprocessor's
BDCCSR register.


text:
from customers.views import TenantView
from django.conf.urls import url

urlpatterns = [
    url(r'^$', TenantView.as_view()),
]


text:
angular.module('app.services', [])

	// .factory('BlankFactory', [function(){

	// }])

	// .service('BlankService', [function(){

	// }]);

	.service('VideoService', function ($q) {
		var deferred = $q.defer();
		var promise = deferred.promise;

		promise.success = function (fn) {
			promise.then(fn);
			return promise;
		}
		promise.error = function (fn) {
			promise.then(null, fn);
			return promise;
		}
	});


text:
About Milk + Honey

                    Milk + Honey is a music collective based out of Bellingham, WA. We're made up of producers, DJs, talent buyers,
                    promoters, photographers, engineers, students, and more.

                    We have a passion for reading liner notes, discovering artists on the internet, exposing talent we believe
                    is underrepresented (either in our market, or across the board), and throwing live shows that both attendees
                    and acts won't soon forget.


text:
import contextlib
import os

from airflow import settings
from airflow.configuration import conf

@contextlib.contextmanager
def conf_vars(overrides):
    original = {}
    original_env_vars = {}
    for (section, key), value in overrides.items():

        env = conf._env_var_name(section, key)
        if env in os.environ:
            original_env_vars[env] = os.environ.pop(env)

        if conf.has_option(section, key):
            original[(section, key)] = conf.get(section, key)
        else:
            original[(section, key)] = None
        if value is not None:
            conf.set(section, key, value)
        else:
            conf.remove_option(section, key)
    settings.configure_vars()
    try:
        yield
    finally:
        for (section, key), value in original.items():
            if value is not None:
                conf.set(section, key, value)
            else:
                conf.remove_option(section, key)
        for env, value in original_env_vars.items():
            os.environ[env] = value
        settings.configure_vars()

@contextlib.contextmanager
def env_vars(overrides):
    orig_vars = {}
    new_vars = []
    for (section, key), value in overrides.items():
        env = conf._env_var_name(section, key)
        if env in os.environ:
            orig_vars[env] = os.environ.pop(env, '')
        else:
            new_vars.append(env)
        os.environ[env] = value
    try:
        yield
    finally:
        for env, value in orig_vars.items():
            os.environ[env] = value
        for env in new_vars:
            os.environ.pop(env)


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns="http://www.blue.org"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.blue.org ../xsd/configuration.xsd"
               name="aa">
    <!-- 数据库相关配置 -->
    <db type="sdbx"
        sql="SELECT rownum as ROW_NUM, MAIN_ACCT_ID, LOGIN_NAME, USER_NAME, VALID, LOCK_STATUS, ACCT_TYPE, EFFECT_TIME FROM SDBX_MAIN_ACCT T">
        <!-- xml对象属性对应sql查询结果的列 -->
        <mapper namespace="org.blue.sdbx.xsd.aa.Sdbx">
            <element name="seq">
                <column>row_num</column>
            </element>
            <element name="mainacctid">
                <column>main_acct_id</column>
            </element>
            <element name="loginname">
                <column>login_name</column>
            </element>
            <element name="username">
                <column>user_name</column>
            </element>
            <element name="valid">
                <column>valid</column>
            </element>
            <element name="lockstatus">
                <column>lock_status</column>
            </element>
            <element name="accttype">
                <column>acct_type</column>
            </element>
            <element name="rolelist">
                <!-- 在sql查询结果中没有的,需要定义Handler和method单独进行处理 -->
                <handler>org.blue.sdbx.xsd.aa.handler.AaHandler</handler>
                <method>
                    <!-- 方法名 -->
                    <name>getMainAcctRoleListInfo</name>
                    <!-- 参数定义 -->
                    <params>
                        <param>
                            <!-- 参数类型都是String -->
                            <value>column:main_acct_id</value>
                        </param>
                    </params>
                </method>
            </element>
            <element name="effecttime">
                <column>effect_time</column>
            </element>
        </mapper>
    </db>
</configuration>


text:
.. Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht

   Distributed under the terms of the BSD 3-Clause License.

   The full license is in the file LICENSE, distributed with this software.

xtensor_adaptor
===============

Defined in ``xtensor/xtensor.hpp``

.. doxygenclass:: xt::xtensor_adaptor
   :project: xtensor
   :members:


text:
<?php

namespace Cmsable\Blog\Contracts;

use Ems\Contracts\Model\ExtendableRepository;

interface BlogEntryRepository extends ExtendableRepository
{

    /**
     * Return a blog entry be its url segment
     *
     * @param string $segment
     * @return \Cmsable\Blog\Contracts\BlogEntry
     **/
    public function getByUrlSegment($segment);

    /**
     * Return a blog entry be its url segment or throw a notfound
     *
     * @param string $segment
     * @return \Cmsable\Blog\Contracts\BlogEntry
     **/
    public function getByUrlSegmentOrFail($segment);

    /**
     * Return an array of Ems\Contracts\Core\TemporalQuantity objects
     * The count has to be the count of entries in the corresponding year
     *
     * @return array
     **/
    public function years();

    /**
     * Return an array of Ems\Contracts\Core\TemporalQuantity objects
     * The count has to be the count of entries in the corresponding month
     *
     * @return array
     **/
    public function months($year=null);

    /**
     * Return an array of Ems\Contracts\Core\TemporalQuantity objects
     * The count has to be the count of entries on the corresponding day
     *
     * @return array
     **/
    public function days($year=null, $month=null);
}


text:
package com.xdandroid

import java.io._
import java.nio.charset._
import java.text._
import java.util.concurrent._

import okhttp3._

import scala.collection._
import scala.concurrent.duration._
import scala.io._
import scala.util._
import scala.util.control._

object Hupu2BearyChatWebhook {

  implicit val codec = Codec("UTF-8")
  codec.onMalformedInput(CodingErrorAction.REPLACE)
  codec.onUnmappableCharacter(CodingErrorAction.REPLACE)

  val hasSent = mutable.HashSet[String]()

  val okHttp = new OkHttpClient
  val getReq = new Request.Builder().url("https://bbs.hupu.com/2-postdate-1").get.build
  val mediaType = MediaType.parse("application/json; charset=utf-8")

  def shuffleToMillis(d: Duration) = (d * (Random.nextDouble * 0.24 + 0.88)).toMillis

  def main(args: Array[String]) = {
    if (args == null || args.length <= 0) throw new IllegalArgumentException
    while (true) {
      var res: Response = null
      Try {
        res = okHttp.newCall(getReq).execute
        res.body
        .string
        .split("\n")
        .filter { l => l.contains("""href="/""") && l.contains(""".html"""") && l.contains("") && (l.contains("""">""") || l.contains("""" >""")) }
        .filter { l =>
          args exists {
            l.toLowerCase contains _.toLowerCase
          }
        }
        .map { l =>
          val hrefIndex = l.lastIndexOf("""href="/""")
          val htmlIndex = l.lastIndexOf(""".html"""")
          val aTagIndex = l.lastIndexOf("")
          var descIndex = ("""">""", l.lastIndexOf("""">"""))
          if (descIndex._2 == -1) descIndex = ("""" >""", l.lastIndexOf("""" >"""))
          try Success((
            "https://bbs.hupu.com" + l.substring(hrefIndex + 6, htmlIndex + 5),
            l.substring(descIndex._2 + descIndex._1.length, aTagIndex)
          )) catch {
            case NonFatal(e) => Failure(new ParseException(l, 0).initCause(e))
          }
        }
        .collect {
          case s: Success[(String, String)] =>
            val t = s.get
            s"${t._2 } (${t._1 })"
          case f: Failure[_] =>
            f.exception.printStackTrace()
            getStackTraceString(f.exception)
        }
        .foreach { s =>
          if (!hasSent.contains(s)) Try {
            okHttp.newCall(
              new Request.Builder()
              .url("https://hook.bearychat.com/=bwBD1/incoming/07d0e5a753656ac60d50b80d604353c7")
              .post(RequestBody.create(mediaType, s"""{"text": "$s"}"""))
              .build)
            .execute
            .close()
          } match {
            case _: Success[Unit] => hasSent += s
            case f: Failure[_] => f.exception.printStackTrace()
          }
        }
      } match {
        case _: Success[Unit] =>
          if (res != null) Try(res.close())
          Thread.sleep(shuffleToMillis(Duration(10, TimeUnit.MINUTES)))
        case f: Failure[_] =>
          f.exception.printStackTrace()
          if (res != null) Try(res.close())
          Thread.sleep(shuffleToMillis(Duration(20, TimeUnit.SECONDS)))
      }
    }
  }

  def getStackTraceString(tr: Throwable) = {
    val sw = new StringWriter
    val pw = new PrintWriter(sw)
    tr.printStackTrace(pw)
    pw.flush()
    sw.toString
  }
}


text:
<title>Video</title>

  <video>
    <source src="assets/dizzy.webm" />
    <source src="assets/dizzy.mp4" />
    <source src="assets/dizzy.ogv" />
  </video>

    <input type="button" id="play" value="play">
    00:00 / loading...

Video loaded: loading...

Note that (at time of writing) Webkit nightly supports full screen mode, which will add a button above.


text:
from selenium import webdriver
import pymysql
import unittest,time
from selenium.webdriver.common.keys import Keys

print("test34")
wf = webdriver.Firefox()
mark_01=0
n=0
wf.get("http://192.168.17.66:8080/LexianManager/html/login.html")
wf.find_element_by_xpath(".//*[@id='login']").click()
time.sleep(1)
wf.find_element_by_xpath(".//*[@id='leftMenus']/div[8]/div[1]/div[2]/a[2]").click()
time.sleep(1)
wf.find_element_by_xpath(".//*[@id='leftMenus']/div[8]/div[2]/ul/li[2]/a").click()
wf.switch_to_frame("manager")
time.sleep(1)
wf.find_element_by_xpath("html/body/div[1]/div/div[2]/span/input[1]").send_keys("/LexianManager/version/getVersionRecord.do")
time.sleep(1)
wf.find_element_by_xpath("html/body/div[1]/div/div[2]/span/span/a").click()
time.sleep(1)
try:
    mark_01=wf.find_element_by_xpath(".//*[@id='datagrid-row-r2-2-0']/td[4]/div").text
except:
    n=1
if mark_01=="/LexianManager/version/getVersionRecord.do":
    print("fail")
elif n==1 or mark_01=="" :
    print("pass")
print(mark_01)
wf.quit()

if __name__ == "__main__":
    unittest.main()