text:
import {
  Component, EventEmitter, ChangeDetectorRef, ElementRef, AfterViewInit, HostListener, HostBinding,
  ViewChild, Input, Output
} from '@angular/core';
import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
  selector: 'app-ui-slider',
  templateUrl: './ui-slider.component.html',
  styleUrls: ['./ui-slider.component.scss']
})
export class UiSliderComponent implements AfterViewInit {
  @Input()
  set value(value: number) {
    const boundsValue = (this.min && this.max) ?
      Math.min(this.max, Math.max(this.min, value)) : value;
    this._currentValue = this.getStepValue(boundsValue);
    this.updatePosition(this._currentValue);
  }
  get value(): number {
    return this._currentValue;
  }
  @Input() label;
  @Input() min;
  @Input() max;
  @Input() step = 1;
  @Output() valueChange = new EventEmitter<number>();
  @ViewChild('scrubber') scrubber: ElementRef;
  @ViewChild('container') el: ElementRef;
  @HostBinding('class.active') pressed = false;
  @HostBinding('attr.role') ariaRole = 'slider';
  @HostBinding('attr.aria-valuemin') get ariaValueMin() {
    return this.min;
  }
  @HostBinding('attr.aria-valuemax') get ariaValueMax() {
    return this.max;
  }
  @HostBinding('attr.aria-valuenow') get ariaValueNow() {
    return this._currentValue;
  }
  position = 0;
  get percent() { return (this.position * 100) + '%'; }
  get pxValue() { return this.elRect ? this.position * this.elRect.width : 0; }
  private elRect = null;
  private _currentValue = 0;

  constructor(private cdRef: ChangeDetectorRef) {}

  /** Set the dimensions of the component and set the position to the current value */
  ngAfterViewInit() {
    this.setSliderDimensions();
    this.updatePosition(this.value);
    // need to notify of changes when modifying inside of AfterViewInit
    // https://github.com/angular/angular/issues/14748
    this.cdRef.detectChanges();
  }

  /**
   * Update the slider dimensions when the window resizes
   * @param e window resize event
   */
  @HostListener('window:resize', ['$event']) onResize(e) {
    this.setSliderDimensions();
  }

  /**
   * Set the pressed status and scrubber position when element is pressed
   * @param e mousedown event
   */
  @HostListener('mousedown', ['$event']) onPress(e) {
    this.setSliderDimensions();
    this.setScrubberPosition(e);
    this.pressed = true;
  }

  /**
   * If the scrubber is currently pressed, update the position when the
   * mouse moves.
   * @param e mousemove event
   */
  @HostListener('document:mousemove', ['$event']) onMove(e) {
    if (this.pressed) {
      this.setScrubberPosition(e);
    }
    e.stopPropagation();
    e.preventDefault();
  }

  /**
   * Remove the pressed status and update scrubber position when released
   * after dragging or clicking
   * @param e mousup event
   */
  @HostListener('document:mouseup', ['$event']) onRelease(e) {
    if (this.pressed) {
      this.pressed = false;
      this.updatePosition(this.value);
    }
  }

  @HostListener('touchstart', ['$event']) onTouchPress(e) {
    if (e.touches && e.touches.length === 1) {
      this.setSliderDimensions();
      this.setScrubberPosition(e.touches[0]);
      this.pressed = true;
    }
  }

  @HostListener('touchmove', ['$event']) onTouchMove(e) {
    if (this.pressed && e.touches && e.touches.length === 1) {
      this.setScrubberPosition(e.touches[0]);
    }
    e.stopPropagation();
    e.preventDefault();
  }

  @HostListener('touchend', ['$event']) onTouchEnd(e) {
    if (this.pressed) {
      this.pressed = false;
      this.updatePosition(this.value);
    }
  }

  /** Move the scrubber left and right with arrow keys */
  @HostListener('keydown', ['$event']) onKeypress(e) {
    if ((e.keyCode === 37 || e.keyCode === 39)) {
      // left or right
      const newValue = (e.keyCode === 37) ?
        this.valueInRange(this.value - this.step) :
        this.valueInRange(this.value + this.step);
      if (newValue !== this.value) {
        this.valueChange.emit(newValue);
      }
    }
  }

  /** Gets the nearest step increment value to the provided value */
  getStepValue(val?: number): number {
    const step = 1 / this.step;
    if (!val) { val = ((this.max - this.min) * this.position + this.min); }
    return (Math.round((val * step)) / step);
  }

  /** Updates the position of the scrubber to the provided value if the scrubber is not pressed */
  updatePosition(val: number) {
    if (!this.pressed) {
      this.position = (val - this.min) / (this.max - this.min);
    }
  }

  /** Returns the value within the min / max range */
  private valueInRange(value) {
    return Math.min(this.max, Math.max(this.min, value));
  }

  /**
   * update the dimensions of the parent element
   */
  private setSliderDimensions() {
    this.elRect = this.el.nativeElement.getBoundingClientRect();
  }

  /**
   * Gets a value between 0 and 1 based on the element rectangle and screen offset
   * @param offset clientY (or pageY) position
   */
  private getVerticalValue(offset) {
      return Math.max(0,
        ((this.elRect.height - Math.abs(offset - this.elRect.top)) / this.elRect.height)
      );
  }

    /**
   * Gets a value between 0 and 1 based on the element rectangle and screen offset
   * @param offset clientX (or pageX) position
   */
  private getHorizontalValue(offset) {
    return Math.max(0, ((offset - this.elRect.left) / this.elRect.width));
  }

  /**
   * Set the scrubber position based on event values, but keep between 0 and 100
   * @param e the mouse event
   */
  private setScrubberPosition(e) {
    if (e.clientX && this.elRect) {
      const maxVal = this.getHorizontalValue(e.clientX);
      this.position = Math.min(1, maxVal);
      const newValue = this.getStepValue();
      if (newValue !== this.value) {
        this.valueChange.emit(newValue);
      }
    }
  }
}


text:
class CGSH_OpenGLWin32 : public CGSH_OpenGL, public CSettingsDialogProvider
{
public:
									CGSH_OpenGLWin32(Framework::Win32::CWindow*);
	virtual							~CGSH_OpenGLWin32();

	static FactoryFunction			GetFactoryFunction(Framework::Win32::CWindow*);

	virtual void					InitializeImpl();
	virtual void					ReleaseImpl();

	CSettingsDialogProvider*		GetSettingsDialogProvider();

	Framework::Win32::CModalWindow* CreateSettingsDialog(HWND);
	void							OnSettingsDialogDestroyed();

protected:
	virtual void					PresentBackbuffer();

private:
	static CGSHandler*				GSHandlerFactory(Framework::Win32::CWindow*);

	Framework::Win32::CWindow*		m_outputWnd = nullptr;

	HGLRC							m_context = nullptr;
	HDC								m_dc = nullptr;
	static PIXELFORMATDESCRIPTOR	m_pfd;
};

redpajama_set_name: RedPajamaGithub


text:
.class public interface abstract Lcom/actionbarsherlock/ActionBarSherlock$OnActionModeStartedListener;
.super Ljava/lang/Object;
.source "ActionBarSherlock.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/actionbarsherlock/ActionBarSherlock;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "OnActionModeStartedListener"
.end annotation

# virtual methods
.method public abstract onActionModeStarted(Lcom/actionbarsherlock/view/ActionMode;)V
.end method


text:
#include "Node_World.h"

using namespace node;

Node_World::Node_World(std::string name, Node* parent)
: Node(name, NT_WORLD, parent)
{
    //ctor
}

Node_World::~Node_World()
{
    //dtor
}


text:
'''
| Filename    : lstm_seqlabel_circuit_compilation.py
| Description :
| Author      : Pushpendre Rastogi
| Created     : Sun Nov 15 03:29:29 2015 (-0500)
| Last-Updated: Fri Jan 22 11:28:23 2016 (-0500)
|           By: Pushpendre Rastogi
|     Update #: 82
'''
import rasengan
import util_lstm_seqlabel
import lstm_seqlabel_training
import lstm_seqlabel_validation
import numpy
import re
import pickle
import class_stack_config
import lstm_seqlabel_circuit
import theano
import contextlib
import os

def compile_args(args):
    stack_config = class_stack_config.StackConfig(args)
    stack_ns = lstm_seqlabel_circuit.metaStackMaker(
        args.chips,
        stack_config)
    stack_config.stack_ns = stack_ns
    model = args.optimizer(stack_config)
    model.stack_config = stack_config
    return model

def get_train_test_namespace(args):
    if args.perform_training:
        print 'Compiling train_model'
        train_model = compile_args(args)

    set_dropout_to_zero(args)
    print 'Compiling test_model'
    test_model = compile_args(args)
    # Prepare the `ttns` namespace by adding train and test prefixes.
    ttns = rasengan.Namespace('ttns')
    if args.perform_training:
        ttns = ttns.update_and_append_prefix(
            train_model, 'train_')
    ttns = ttns.update_and_append_prefix(
        test_model, 'test_')
    return ttns

def print_pklfn_performance(args, add_newline=True):
    if ((not hasattr(args, 'pretrained_param_pklfile'))
        or (args.pretrained_param_pklfile is None)):
        return
    pkl_fn = args.pretrained_param_pklfile
    if  not os.path.exists(pkl_fn):
        print 'The pretrained param file', pkl_fn, 'does not exist.'
        return
    pkl = pickle.load(open(pkl_fn))
    pa_best_epoch = pkl['best_epoch_id']
    pa_training_f1 = pkl['training_result'][pa_best_epoch]['f1']
    pa_validation_f1 = pkl['validation_result'][pa_best_epoch]['f1']
    arr = ['pklfn', pkl_fn, 'Training F1', pa_training_f1,
           'Validation F1', pa_validation_f1, 'Best Epoch', pa_best_epoch,]
    for e in arr:
        print e,
    if add_newline:
        print
    return pkl, arr

def load_params_from_pklfile_to_stack_config(pkl_fn, stack_config):
    '''
    Params
    ------
    pkl_fn       : The path of the pickle file that contains the parameters.
    stack_config : The stack_config object that contains handles to theano
      shared variabes to be updated.
    Returns
    -------
    '''
    # Check which parameters of `ttns` need to be loaded
    # from pklfile.
    parameters_required = [str(k) for k in
                           stack_config.differentiable_parameters()]
    # Read required parameters from pklfile.
    # Upto the last id, the parameter names would be similar.
    parameters_available_pkl = pickle.load(open(pkl_fn))
    parameters_available = [k for k in parameters_available_pkl
                            if k.startswith('tparam_')]
    print 'Loading pretrained parameters from pklfn:', pkl_fn, ' to model'
    print 'parameters_required', parameters_required
    print 'parameters_available', parameters_available

    req_to_ava_map = {}
    for p in parameters_required:
        lemma = re.match(r'(.*)_\d+', p).group(1)
        l = [e for e in parameters_available
             if e.startswith(lemma)]
        if len(l) == 1:
            l = l[0]
        elif len(l) == 0:
            l = None
        else:
            raise Exception(str(parameters_available) + p)
        req_to_ava_map[p] = l
    # Update `ttns`
    for p in parameters_required:
        pretrained_param = req_to_ava_map[p]
        if pretrained_param is not None:
            required_shape = stack_config[p].shape.eval()
            available_shape = parameters_available_pkl[pretrained_param].shape
            pp_val = parameters_available_pkl[pretrained_param]
            shape_check = lambda s1, s2 : (
                len(s1) == 2 and len(s2) == 2 and s1[1] == s2[1])
            if shape_check(required_shape, available_shape):
                row_req = required_shape[0]
                row_ava = available_shape[0]
                pad_width = (row_req - row_ava)/2
                pp_val = numpy.pad(
                    pp_val, ((pad_width, pad_width), (0, 0)), mode='constant')
                print 'Padded', pretrained_param, 'with', pad_width, 'zero rows'
            if (all(a == b for (a,b) in zip(required_shape, available_shape))
                or shape_check(required_shape, available_shape)):
                stack_config[p].set_value(pp_val)
                print 'Setting value of', p, 'with', pretrained_param, \
                    'Shape:', pp_val.shape
            else:
                print 'Error:', p, 'requires shape ', required_shape, \
                    'but', pretrained_param, 'has shape', available_shape
                raise NotImplementedError
                pass
            pass
        pass
    return

def load_params_from_pklfile(ttns, args):
    if ((not hasattr(args, 'pretrained_param_pklfile'))
        or (args.pretrained_param_pklfile is None)):
        return
    pkl_fn = args.pretrained_param_pklfile
    if  not os.path.exists(pkl_fn):
        print 'The pretrained param file', pkl_fn, 'does not exist.'
        return
    if args.perform_training:
        print 'Loading params from pklfile to train stack config'
        load_params_from_pklfile_to_stack_config(
            pkl_fn, ttns.train_stack_config)
    print 'Loading params from pklfile to test stack config'
    load_params_from_pklfile_to_stack_config(pkl_fn, ttns.test_stack_config)
    return

def perform_training_and_testing(training_stage, args, data):
    '''
    Returns
    -------
    The validation error. A quantity that we want to minimize.
    '''
    stats = None
    with rasengan.tictoc(training_stage):
        with rasengan.debug_support():
            if args.perform_training or args.perform_testing:
                with rasengan.tictoc("Circuit Compilation"):
                    ttns = get_train_test_namespace(args)
                with rasengan.tictoc("Loading Parameters"):
                    load_params_from_pklfile(ttns, args)
                pass
            rasengan.decrease_print_indent()
            print_pklfn_performance(args)
            rasengan.increase_print_indent()
            # Train
            if args.perform_training:
                with rasengan.tictoc("Training"):
                    stats = lstm_seqlabel_training.training(args, data, ttns)
            # Test (IF asked)
            if args.perform_testing:
                with rasengan.tictoc("Testing"):
                    stats = lstm_seqlabel_validation.testing(args, data, ttns)
                    return (100 - stats)
    if stats is None:
        return 100
    else:
        best_epoch_id = stats['best_epoch_id']
        return (100 - stats['validation_result'][best_epoch_id]['f1'])

def set_dropout_to_zero(args):
    ''' Set all the parameters that have specify dropout
    in a layer to zero.
    Params
    ------
    args : A namespace object.
    Returns
    -------
    A handle to the inplace modified namespace object.
    '''
    for attr in args.__dict__:
        if attr.endswith('do_dropout'):
            args.__dict__[attr] = 0
    return args

@contextlib.contextmanager
def make(args, force=False, pipeline=False):
    ''' In each training run we have to check whether a trained pickle
    file `saveto` for that stage already exists. If it exists then we
    skip the training. Otherwise we load the trained parameters and
    when we leave then we set the pretrained_param_pklfile as the
    pkl file that we just saved parameters to (or that already exists).

    Also we restore the state of perform_training and saveto to defaults.
    Params
    ------
    args  :
    saveto :
    force  : (default False)
    Returns
    -------
    '''
    saveto = os.path.join(args.folder, args.pkl_name)
    with rasengan.tictoc('Making ' + saveto):
        rasengan.ensure_dir(args.folder, verbose=1, treat_as_dir=1)
        if hasattr(args, 'saveto'):
            assert args.saveto == saveto, str((args.saveto, saveto))
        else:
            args.saveto = saveto
            print 'Set args.saveto=', args.saveto
        # Check whether we need to do any training unless forced
        # explicitly.
        pt = args.perform_training
        if not force and os.path.exists(args.saveto):
            args.perform_training = 0
        rasengan.increase_print_indent()
        #----#
        yield
        #----#
        rasengan.decrease_print_indent()
        args.perform_training = pt
        if pipeline:
            # Set the pretrained_param_pklfile field to a value after saving
            # parameters to that location.
            args.pretrained_param_pklfile = args.saveto
            # Reset args.saveto to null
            args.saveto = None


text:
layout: base
title:  'Statistics of Abbr in UD_Komi_Zyrian-Lattice'
udver: '2'
---

## Treebank Statistics: UD_Komi_Zyrian-Lattice: Features: `Abbr`

This feature is universal.
It occurs with 1 different values: `Yes`.

1 tokens (0%) have a non-empty value of `Abbr`.
1 types (0%) occur at least once with a non-empty value of `Abbr`.
1 lemmas (0%) occur at least once with a non-empty value of `Abbr`.
The feature is used with 1 part-of-speech tags: <tt>ADV</tt> (1; 0% instances).

### `ADV`

1 <tt>ADV</tt> tokens (0% of all `ADV` tokens) have a non-empty value of `Abbr`.

The most frequent other feature values with which `ADV` and `Abbr` co-occurred: <tt>AdvType</tt><tt>=EMPTY</tt> (1; 100%), <tt>Case</tt><tt>=EMPTY</tt> (1; 100%).

`ADV` tokens may have the following values of `Abbr`:

* `Yes` (1; 100% of non-empty `Abbr`): с.в.
* `EMPTY` (875): нин, жӧ, на, и, сӧмын, сэсся, зэв, кыдзи, пыр, бара


text:
package net.lightoze.jooq;

import org.jooq.*;
import org.jooq.impl.AbstractBinding;
import org.jooq.impl.DSL;

import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Types;

public abstract class AbstractObjectBinding<T> extends AbstractBinding<Object, T> {

    @Override
    protected void sqlInline(BindingSQLContext<T> ctx) throws SQLException {
        ctx.render().visit(DSL.inline(ctx.convert(converter()).value()));
    }

    @Override
    public void register(BindingRegisterContext<T> ctx) throws SQLException {
        ctx.statement().registerOutParameter(ctx.index(), Types.JAVA_OBJECT);
    }

    @Override
    public void set(BindingSetStatementContext<T> ctx) throws SQLException {
        ctx.statement().setObject(ctx.index(), ctx.convert(converter()).value());
    }

    @Override
    public void get(BindingGetResultSetContext<T> ctx) throws SQLException {
        ctx.convert(converter()).value(ctx.resultSet().getObject(ctx.index()));
    }

    @Override
    public void get(BindingGetStatementContext<T> ctx) throws SQLException {
        ctx.convert(converter()).value(ctx.statement().getObject(ctx.index()));
    }

    @Override
    public void set(BindingSetSQLOutputContext<T> ctx) throws SQLException {
        throw new SQLFeatureNotSupportedException();
    }

    @Override
    public void get(BindingGetSQLInputContext<T> ctx) throws SQLException {
        throw new SQLFeatureNotSupportedException();
    }
}


text:
#include "Modules/Graphics/Lighting/Indirect/Indirect_Technique.h"
#include "Modules/Graphics/Lighting/Indirect/IndirectVisibility_System.h"
#include "Modules/Graphics/Lighting/Indirect/IndirectSync_System.h"
#include "Engine.h"
#include <random>

Indirect_Technique::~Indirect_Technique()
{
	// Update indicator
	*m_aliveIndicator = false;
}

Indirect_Technique::Indirect_Technique(Engine& engine, ShadowData& shadowData, Camera& clientCamera, std::vector<Camera*>& sceneCameras) :
	Graphics_Technique(Technique_Category::PRIMARY_LIGHTING),
	m_engine(engine),
	m_shader_Bounce(Shared_Shader(engine, "Core\\Light\\Bounce")),
	m_shader_Recon(Shared_Shader(engine, "Core\\Light\\Reconstruction")),
	m_shader_Rebounce(Shared_Shader(engine, "Core\\Light\\Rebounce")),
	m_shapeQuad(Shared_Auto_Model(engine, "quad")),
	m_frameData(shadowData, clientCamera),
	m_sceneCameras(sceneCameras)
{
	// Auxiliary Systems
	m_auxilliarySystems.makeSystem<IndirectVisibility_System>(m_frameData);
	m_auxilliarySystems.makeSystem<IndirectSync_System>(m_frameData);

	// Noise Texture
	const std::uniform_real_distribution<float> randomFloats(0.0, 1.0);
	std::default_random_engine generator;
	float texData[32 * 32 * 32 * 3]{};
	std::generate(std::begin(texData), std::end(texData), [&]() { return randomFloats(generator); });
	glCreateTextures(GL_TEXTURE_3D, 1, &m_textureNoise32);
	glTextureImage3DEXT(m_textureNoise32, GL_TEXTURE_3D, 0, GL_RGB16F, 32, 32, 32, 0, GL_RGB, GL_FLOAT, texData);
	glTextureParameteri(m_textureNoise32, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
	glTextureParameteri(m_textureNoise32, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
	glTextureParameteri(m_textureNoise32, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);
	glTextureParameteri(m_textureNoise32, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTextureParameteri(m_textureNoise32, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	// Preferences
	auto& preferences = engine.getPreferenceState();
	preferences.getOrSetValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, m_bounceSize);
	preferences.addCallback(PreferenceState::Preference::C_RH_BOUNCE_SIZE, m_aliveIndicator, [&](const float& f) noexcept { m_bounceSize = static_cast<GLuint>(f); });
}

void Indirect_Technique::clearCache(const float& /*deltaTime*/) noexcept
{
	m_frameData.lightBuffer.endReading();
	m_frameData.viewInfo.clear();
	m_drawIndex = 0;
}

void Indirect_Technique::updateCache(const float& deltaTime, ecsWorld& world)
{
	// Link together the dimensions of view info to that of the viewport vectors
	m_frameData.viewInfo.resize(m_sceneCameras.size());
	world.updateSystems(m_auxilliarySystems, deltaTime);
}

void Indirect_Technique::renderTechnique(const float& /*deltaTime*/, Viewport& viewport, const std::vector<std::pair<int, int>>& perspectives)
{
	// Update light-bounce volume
	if (m_enabled && (!m_frameData.viewInfo.empty()) && Asset::All_Ready(m_shapeQuad, m_shader_Bounce, m_shader_Recon, m_shader_Rebounce)) {
		// Light bounce using client camera
		if (m_drawIndex >= m_drawData.size())
			m_drawData.resize(size_t(m_drawIndex) + 1ULL);
		auto& [camBufferIndex, camBufferRebounce, camBufferRecon, visLights, indirectBounce, indirectQuad, indirectQuadRecon] = m_drawData[m_drawIndex];

		// Accumulate all visibility info for the cameras passed in
		std::vector<glm::ivec2> camIndicesGen;
		std::vector<glm::ivec2> camIndiciesRebounce;
		std::vector<glm::ivec2> camIndiciesRecon;
		std::vector<GLint> lightIndices;
		for (auto& [camIndex, layer] : perspectives) {
			const std::vector<glm::ivec2> tempIndices(m_frameData.viewInfo[camIndex].lightIndices.size(), { camIndex, layer });
			camIndicesGen.insert(camIndicesGen.end(), tempIndices.begin(), tempIndices.end());
			lightIndices.insert(lightIndices.end(), m_frameData.viewInfo[camIndex].lightIndices.begin(), m_frameData.viewInfo[camIndex].lightIndices.end());
			const std::vector<glm::ivec2> tempIndices2(m_bounceSize, { camIndex, layer });
			camIndiciesRebounce.insert(camIndiciesRebounce.end(), tempIndices2.begin(), tempIndices2.end());
			camIndiciesRecon.push_back({ camIndex, layer });
		}
		const auto shadowCount = camIndicesGen.size();

		if (!lightIndices.empty()) {
			updateDrawParams(camIndicesGen, camIndiciesRebounce, camIndiciesRecon, lightIndices, shadowCount, perspectives.size());
			fillBounceVolume(shadowCount, viewport.m_gfxFBOS.m_rhVolume);
			rebounceVolume(viewport.m_gfxFBOS.m_rhVolume, camBufferRebounce, indirectQuad);
			reconstructVolume(viewport, camBufferRecon, indirectQuadRecon);
			camBufferIndex.endReading();
			camBufferRebounce.endReading();
			camBufferRecon.endReading();
			visLights.endReading();
			indirectBounce.endReading();
			indirectQuad.endReading();
			indirectQuadRecon.endReading();
			Shader::Release();

			m_drawIndex++;
		}
	}
}

void Indirect_Technique::updateDrawParams(std::vector<glm::ivec2>& camIndicesGen, std::vector<glm::ivec2>& camIndiciesRebounce, std::vector<glm::ivec2>& camIndiciesRecon, std::vector<int>& lightIndices, const size_t& shadowCount, const size_t& perspectivesSize) noexcept
{
	// Write accumulated data
	auto& [camBufferIndex, camBufferRebounce, camBufferRecon, visLights, indirectBounce, indirectQuad, indirectQuadRecon] = m_drawData[m_drawIndex];
	camBufferIndex.beginWriting();
	camBufferRebounce.beginWriting();
	camBufferRecon.beginWriting();
	visLights.beginWriting();
	indirectBounce.beginWriting();
	indirectQuad.beginWriting();
	indirectQuadRecon.beginWriting();
	camBufferIndex.write(0, sizeof(glm::ivec2) * camIndicesGen.size(), camIndicesGen.data());
	camBufferRebounce.write(0, sizeof(glm::ivec2) * camIndiciesRebounce.size(), camIndiciesRebounce.data());
	camBufferRecon.write(0, sizeof(glm::ivec2) * camIndiciesRecon.size(), camIndiciesRecon.data());
	visLights.write(0, sizeof(GLuint) * lightIndices.size(), lightIndices.data());
	const GLuint dataBounce[] = { static_cast<GLuint>(m_shapeQuad->getSize()), static_cast<GLuint>(shadowCount * m_bounceSize), 0, 0 };
	indirectBounce.write(0, sizeof(GLuint) * 4, &dataBounce);
	indirectQuad.setPrimitiveCount(m_bounceSize);
	indirectQuadRecon.setPrimitiveCount(static_cast<GLuint>(perspectivesSize));
	camBufferIndex.endWriting();
	camBufferRebounce.endWriting();
	camBufferRecon.endWriting();
	visLights.endWriting();
	indirectBounce.endWriting();
	indirectQuad.endWriting();
	indirectQuadRecon.endWriting();
}

void Indirect_Technique::fillBounceVolume(const size_t& shadowCount, RH_Volume& rhVolume) noexcept
{
	// Prepare rendering state
	glBlendEquationSeparatei(0, GL_MIN, GL_MIN);
	glBindVertexArray(m_shapeQuad->m_vaoID);
	m_shader_Bounce->setUniform(0, static_cast<GLint>(shadowCount));
	m_shader_Bounce->setUniform(1, rhVolume.m_max);
	m_shader_Bounce->setUniform(2, rhVolume.m_min);
	m_shader_Bounce->setUniform(4, rhVolume.m_resolution);
	m_shader_Bounce->setUniform(6, rhVolume.m_unitSize);

	glViewport(0, 0, static_cast<GLsizei>(rhVolume.m_resolution), static_cast<GLsizei>(rhVolume.m_resolution));
	m_shader_Bounce->bind();
	rhVolume.writePrimary();
	glBindTextureUnit(0, m_frameData.shadowData.shadowFBO.m_texNormal);
	glBindTextureUnit(1, m_frameData.shadowData.shadowFBO.m_texColor);
	glBindTextureUnit(2, m_frameData.shadowData.shadowFBO.m_texDepth);
	glBindTextureUnit(4, m_textureNoise32);
	m_drawData[m_drawIndex].bufferCamIndex.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 3);
	m_drawData[m_drawIndex].visLights.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 4);
	m_frameData.lightBuffer.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 8);
	m_drawData[m_drawIndex].indirectBounce.bindBuffer(GL_DRAW_INDIRECT_BUFFER);
	glDrawArraysIndirect(GL_TRIANGLES, nullptr);
}

void Indirect_Technique::rebounceVolume(RH_Volume& rhVolume, const DynamicBuffer<>& camBufferRebounce, IndirectDraw<>& indirectQuad) noexcept
{
	// Bind common data
	glDepthMask(GL_TRUE);
	glBlendEquation(GL_FUNC_ADD);
	glBlendFunc(GL_ONE, GL_ZERO);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);
	m_shader_Rebounce->setUniform(1, rhVolume.m_max);
	m_shader_Rebounce->setUniform(2, rhVolume.m_min);
	m_shader_Rebounce->setUniform(4, rhVolume.m_resolution);
	m_shader_Rebounce->setUniform(5, rhVolume.m_unitSize);
	m_shader_Recon->setUniform(1, rhVolume.m_max);
	m_shader_Recon->setUniform(2, rhVolume.m_min);
	m_shader_Recon->setUniform(3, rhVolume.m_resolution);
	glBindVertexArray(m_shapeQuad->m_vaoID);

	// Bounce light a second time
	m_shader_Rebounce->bind();
	rhVolume.readPrimary(0);
	rhVolume.writeSecondary();
	glViewport(0, 0, static_cast<GLsizei>(rhVolume.m_resolution), static_cast<GLsizei>(rhVolume.m_resolution));
	camBufferRebounce.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 3);
	indirectQuad.drawCall();
}

void Indirect_Technique::reconstructVolume(Viewport& viewport, const DynamicBuffer<>& camBufferRecon, IndirectDraw<>& indirectQuadRecon)
{
	// Reconstruct indirect radiance
	glViewport(0, 0, GLsizei(viewport.m_dimensions.x), GLsizei(viewport.m_dimensions.y));
	m_shader_Recon->bind();
	viewport.m_gfxFBOS.bindForReading("GEOMETRY", 0);
	viewport.m_gfxFBOS.m_rhVolume.readSecondary(4);
	viewport.m_gfxFBOS.bindForWriting("BOUNCE");
	camBufferRecon.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 3);
	indirectQuadRecon.drawCall();
	glEnable(GL_DEPTH_TEST);
}


text:
#include "../prConfig.h"

#include "prBackgroundManager.h"
#include "prBackground.h"
#include "../core/prMacros.h"
#include "../core/prResourceManager.h"
#include "../core/prCore.h"
#include "../debug/prAssert.h"
#include "../debug/prTrace.h"
#include "../debug/prDebug.h"

using namespace Proteus::Core;

/// ---------------------------------------------------------------------------
/// Constructs the background manager.
/// ---------------------------------------------------------------------------
prBackgroundManager::prBackgroundManager() : prCoreSystem(PRSYSTEM_BACKGROUNDMANAGER, "prBackgroundManager")
{
    for (int i=0; i<MAX_BACKGROUNDS; i++)
    {
        backgrounds[i] = nullptr;
    }
}

/// ---------------------------------------------------------------------------
/// Dtor
/// ---------------------------------------------------------------------------
prBackgroundManager::~prBackgroundManager()
{
    ReleaseAll();
}

/// ---------------------------------------------------------------------------
/// Creates a background.
/// ---------------------------------------------------------------------------
prBackground *prBackgroundManager::Create(const char *filename)
{
    // Game builds will assert if there's no filename
    #if !defined(PROTEUS_TOOL)
    PRASSERT(filename && *filename);
    #endif

    for (int i=0; i<MAX_BACKGROUNDS; i++)
    {
        if (backgrounds[i] == nullptr)
        {
            #if !defined(REMOVE_EXCEPTIONS)
            try
            #endif
            {
                backgrounds[i] = new prBackground(filename);
                return backgrounds[i];
            }
            #if !defined(REMOVE_EXCEPTIONS)
            catch(...)
            {
                PRWARN("Failed to create background: ", filename);
            }
            #endif
        }
    }

    return nullptr;
}

/// ---------------------------------------------------------------------------
/// Releases a background and any asssociated assets.
/// ---------------------------------------------------------------------------
void prBackgroundManager::Release(prBackground *bg)
{
    PRASSERT(bg);

    for (int i=0; i<MAX_BACKGROUNDS; i++)
    {
        if (backgrounds[i] == bg)
        {
            PRSAFE_DELETE(backgrounds[i]);
            return;
        }
    }
}

/// ---------------------------------------------------------------------------
/// Releases all backgrounds and their asssociated assets.
/// ---------------------------------------------------------------------------
void prBackgroundManager::ReleaseAll()
{
    for (int i=0; i<MAX_BACKGROUNDS; i++)
    {
        PRSAFE_DELETE(backgrounds[i]);
    }
}

/// ---------------------------------------------------------------------------
/// Shows all the assets being used by the background manager.
/// ---------------------------------------------------------------------------
void prBackgroundManager::DisplayUsage()
{
#if defined(_DEBUG) || defined(DEBUG)

    prTrace(prLogLevel::LogError, "\nBackground Manager: =============================================================\n");

    for (s32 i=0; i<MAX_BACKGROUNDS; i++)
    {
        if (backgrounds[i])
        {
            prTrace(prLogLevel::LogError, "Slot %i occupied: W: %i, H: %i\n", i, backgrounds[i]->GetWidth(),
                                                           backgrounds[i]->GetHeight());
        }
        else
        {
            prTrace(prLogLevel::LogError, "Slot %i unoccupied\n", i);
        }
    }

#endif
}


text:
'use strict';

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
	res.render('index', {title: '<%= appName %>'});
});

module.exports = router;


text:
var exec = require("cordova/exec");

var updateApp = {
	update: function(jsonObj, s, f) {
	console.log(jsonObj);
	 cordova.exec(s, f, "UpdateAppPlugin", "update", [jsonObj]);
	}
};
module.exports = updateApp;


text:
package main

// import fmt for input/output
import "fmt"

// function declaration is executed at runtime
func main(){
	fmt.Println("Hello World.")
}


text:
<?php

namespace Magento\Sales\Test\Unit\Model\ResourceModel;

/**
 * Class AttributeTest
 */
class AttributeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Sales\Model\ResourceModel\Attribute|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $attribute;

    /**
     * @var \Magento\Framework\App\ResourceConnection|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $appResourceMock;

    /**
     * @var \Magento\Framework\Event\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $eventManagerMock;

    /**
     * @var \Magento\Sales\Model\AbstractModel|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $modelMock;

    /**
     * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $connectionMock;

    protected function setUp()
    {
        $this->appResourceMock = $this->getMock(
            'Magento\Framework\App\ResourceConnection',
            [],
            [],
            '',
            false
        );
        $this->eventManagerMock = $this->getMockForAbstractClass(
            'Magento\Framework\Event\ManagerInterface',
            [],
            '',
            false,
            false,
            true,
            []
        );
        $this->modelMock = $this->getMockForAbstractClass(
            'Magento\Sales\Model\AbstractModel',
            [],
            '',
            false,
            false,
            true,
            ['__wakeup', 'getId', 'getEventPrefix', 'getEventObject']
        );
        $this->connectionMock = $this->getMock(
            'Magento\Framework\DB\Adapter\Pdo\Mysql',
            ['describeTable', 'insert', 'lastInsertId', 'beginTransaction', 'rollback', 'commit'],
            [],
            '',
            false
        );
        $this->connectionMock->expects($this->any())
            ->method('describeTable')
            ->will($this->returnValue([]));
        $this->connectionMock->expects($this->any())
            ->method('insert');
        $this->connectionMock->expects($this->any())
            ->method('lastInsertId');
        $this->attribute = new \Magento\Sales\Model\ResourceModel\Attribute(
            $this->appResourceMock,
            $this->eventManagerMock
        );
    }

    /**
     * @throws \Exception
     */
    public function testSave()
    {
        $this->appResourceMock->expects($this->once())
            ->method('getConnection')
            ->will($this->returnValue($this->connectionMock));
        $this->modelMock->expects($this->any())
            ->method('getEventPrefix')
            ->will($this->returnValue('event_prefix'));
        $this->modelMock->expects($this->any())
            ->method('getEventObject')
            ->will($this->returnValue('event_object'));
        $this->eventManagerMock->expects($this->at(0))
            ->method('dispatch')
            ->with('event_prefix_save_attribute_before', [
                'event_object' => $this->attribute,
                'object' => $this->modelMock,
                'attribute' => ['attribute']
            ]);
        $this->eventManagerMock->expects($this->at(1))
            ->method('dispatch')
            ->with('event_prefix_save_attribute_after', [
                'event_object' => $this->attribute,
                'object' => $this->modelMock,
                'attribute' => ['attribute']
            ]);
        $this->connectionMock->expects($this->once())
            ->method('beginTransaction');
        $this->connectionMock->expects($this->once())
            ->method('commit');
        $this->assertEquals($this->attribute, $this->attribute->saveAttribute($this->modelMock, 'attribute'));
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage Expected Exception
     * @throws \Exception
     */
    public function testSaveFailed()
    {
        $this->modelMock->expects($this->any())
            ->method('getEventPrefix')
            ->will($this->returnValue('event_prefix'));
        $this->modelMock->expects($this->any())
            ->method('getEventObject')
            ->will($this->returnValue('event_object'));
        $this->appResourceMock->expects($this->once())
            ->method('getConnection')
            ->will($this->returnValue($this->connectionMock));
        $exception  = new \Exception('Expected Exception');
        $this->modelMock->expects($this->any())
            ->method('getId')
            ->will($this->throwException($exception));
        $this->connectionMock->expects($this->once())
            ->method('beginTransaction');
        $this->connectionMock->expects($this->once())
            ->method('rollback');
        $this->eventManagerMock->expects($this->once())
            ->method('dispatch')
            ->with(
                'event_prefix_save_attribute_before',
                [
                    'event_object' =>  $this->attribute,
                    'object' => $this->modelMock,
                    'attribute' => ['attribute']
                ]
            );
        $this->attribute->saveAttribute($this->modelMock, 'attribute');
    }
}


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>FreeType-2.7.1 API Reference</title>

[Index]	[TOC]

FreeType-2.7.1 API Reference

GZIP Streams

Synopsis

FT_Stream_OpenGzip	FT_Gzip_Uncompress

This section contains the declaration of Gzip-specific functions.

FT_Stream_OpenGzip

Defined in FT_GZIP_H (freetype/ftgzip.h).

  FT_EXPORT( FT_Error )
  FT_Stream_OpenGzip( FT_Stream  stream,
                      FT_Stream  source );

Open a new stream to parse gzip-compressed font files. This is mainly used to support the compressed ‘*.pcf.gz’ fonts that come with XFree86.

input

stream

The target embedding stream.

source

The source stream.

return

FreeType error code. 0 means success.

note

The source stream must be opened before calling this function.

Calling the internal function ‘FT_Stream_Close’ on the new stream will not call ‘FT_Stream_Close’ on the source stream. None of the stream objects will be released to the heap.

The stream implementation is very basic and resets the decompression process each time seeking backwards is needed within the stream.

In certain builds of the library, gzip compression recognition is automatically handled when calling FT_New_Face or FT_Open_Face. This means that if no font driver is capable of handling the raw compressed file, the library will try to open a gzipped stream from it and re-open the face with it.

This function may return ‘FT_Err_Unimplemented_Feature’ if your build of FreeType was not compiled with zlib support.

[Index]	[Top]	[TOC]

FT_Gzip_Uncompress

Defined in FT_GZIP_H (freetype/ftgzip.h).

  FT_EXPORT( FT_Error )
  FT_Gzip_Uncompress( FT_Memory       memory,
                      FT_Byte*        output,
                      FT_ULong*       output_len,
                      const FT_Byte*  input,
                      FT_ULong        input_len );

Decompress a zipped input buffer into an output buffer. This function is modeled after zlib's ‘uncompress’ function.

input

memory

A FreeType memory handle.

input

The input buffer.

input_len

The length of the input buffer.

output

output

The output buffer.

inout

output_len

Before calling the function, this is the total size of the output buffer, which must be large enough to hold the entire uncompressed data (so the size of the uncompressed data must be known in advance). After calling the function, ‘output_len’ is the size of the used data in ‘output’.

return

FreeType error code. 0 means success.

note

This function may return ‘FT_Err_Unimplemented_Feature’ if your build of FreeType was not compiled with zlib support.

[Index]	[Top]	[TOC]


text:
/*

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package v3

import (
	"fmt"
	"net/http"
	"sort"
	"strings"
	"testing"
	"time"

	"github.com/apache/trafficcontrol/lib/go-rfc"
	"github.com/apache/trafficcontrol/lib/go-tc"
)

const queryParamFormat = "?profileId=%d&parameterId=%d"

func TestProfileParameters(t *testing.T) {
	WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, ProfileParameters}, func() {
		SortTestProfileParameters(t)
		GetTestProfileParametersIMS(t)
		GetTestProfileParameters(t)
		InvalidCreateTestProfileParameters(t)
	})
}

func GetTestProfileParametersIMS(t *testing.T) {
	var header http.Header
	header = make(map[string][]string)
	futureTime := time.Now().AddDate(0, 0, 1)
	time := futureTime.Format(time.RFC1123)
	header.Set(rfc.IfModifiedSince, time)
	for _, pp := range testData.ProfileParameters {
		queryParams := fmt.Sprintf(queryParamFormat, pp.ProfileID, pp.ParameterID)
		_, reqInf, err := TOSession.GetProfileParameterByQueryParamsWithHdr(queryParams, header)
		if err != nil {
			t.Fatalf("Expected no error, but got %v", err.Error())
		}
		if reqInf.StatusCode != http.StatusNotModified {
			t.Fatalf("Expected 304 status code, got %v", reqInf.StatusCode)
		}
	}
}

func CreateTestProfileParameters(t *testing.T) {

	firstProfile := testData.Profiles[0]
	profileResp, _, err := TOSession.GetProfileByNameWithHdr(firstProfile.Name, nil)
	if err != nil {
		t.Errorf("cannot GET Profile by name: %v - %v", firstProfile.Name, err)
	}

	firstParameter := testData.Parameters[0]
	paramResp, _, err := TOSession.GetParameterByNameWithHdr(firstParameter.Name, nil)
	if err != nil {
		t.Errorf("cannot GET Parameter by name: %v - %v", firstParameter.Name, err)
	}

	profileID := profileResp[0].ID
	parameterID := paramResp[0].ID

	pp := tc.ProfileParameter{
		ProfileID:   profileID,
		ParameterID: parameterID,
	}
	resp, _, err := TOSession.CreateProfileParameter(pp)
	t.Log("Response: ", resp)
	if err != nil {
		t.Errorf("could not CREATE profile parameters: %v", err)
	}

}

func InvalidCreateTestProfileParameters(t *testing.T) {
	pp := tc.ProfileParameter{
		ProfileID:   0,
		ParameterID: 0,
	}
	_, _, err := TOSession.CreateProfileParameter(pp)
	if err == nil {
		t.Fatalf("creating invalid profile parameter - expected: error, actual: nil")
	}
	if !strings.Contains(err.Error(), "profileId") {
		t.Errorf("expected: error message to contain 'profileId', actual: %v", err)
	}
	if !strings.Contains(err.Error(), "parameterId") {
		t.Errorf("expected: error message to contain 'parameterId', actual: %v", err)
	}

}

func SortTestProfileParameters(t *testing.T) {
	var header http.Header
	var sortedList []string
	resp, _, err := TOSession.GetProfileParametersWithHdr(header)
	if err != nil {
		t.Fatalf("Expected no error, but got %v", err.Error())
	}
	for i, _ := range resp {
		sortedList = append(sortedList, resp[i].Parameter)
	}

	res := sort.SliceIsSorted(sortedList, func(p, q int) bool {
		return sortedList[p] < sortedList[q]
	})
	if res != true {
		t.Errorf("list is not sorted by their names: %v", sortedList)
	}
}

func GetTestProfileParameters(t *testing.T) {

	for _, pp := range testData.ProfileParameters {
		queryParams := fmt.Sprintf(queryParamFormat, pp.ProfileID, pp.ParameterID)
		resp, _, err := TOSession.GetProfileParameterByQueryParamsWithHdr(queryParams, nil)
		if err != nil {
			t.Errorf("cannot GET Parameter by name: %v - %v", err, resp)
		}
	}
}

func DeleteTestProfileParameters(t *testing.T) {

	for _, pp := range testData.ProfileParameters {
		DeleteTestProfileParameter(t, pp)
	}
}

func DeleteTestProfileParameter(t *testing.T, pp tc.ProfileParameter) {

	queryParams := fmt.Sprintf(queryParamFormat, pp.ProfileID, pp.ParameterID)
	// Retrieve the PtofileParameter by profile so we can get the id for the Update
	resp, _, err := TOSession.GetProfileParameterByQueryParamsWithHdr(queryParams, nil)
	if err != nil {
		t.Errorf("cannot GET Parameter by profile: %v - %v", pp.Profile, err)
	}
	if len(resp) > 0 {
		respPP := resp[0]

		delResp, _, err := TOSession.DeleteParameterByProfileParameter(respPP.ProfileID, respPP.ParameterID)
		if err != nil {
			t.Errorf("cannot DELETE Parameter by profile: %v - %v", err, delResp)
		}

		// Retrieve the Parameter to see if it got deleted
		pps, _, err := TOSession.GetProfileParameterByQueryParamsWithHdr(queryParams, nil)
		if err != nil {
			t.Errorf("error deleting Parameter name: %s", err.Error())
		}
		if len(pps) > 0 {
			t.Errorf("expected Parameter Name: %s and ConfigFile: %s to be deleted", pp.Profile, pp.Parameter)
		}
	}
}


text:
require 'rails_helper'

field_name = 'string'
type = type_from __FILE__
describe field_name do
  it_behaves_like \
    "#{type} partial", field_name,
    partial_name: 'link',
    value: 'https://reinteractive.com/',
    metadata: { title: 'Rails Developers', html_options: { target: '_blank' } },
    skip_escaping: true,
    expected_value: 'Rails Developers'
end


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>
org.apache.hadoop.hbase.client.replication (HBase 0.94.19 API)
</TITLE>

<META NAME="date" CONTENT="2014-04-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.hbase.client.replication

Classes

ReplicationAdmin


text:
package org.apache.hadoop.hdfs.qjournal.server;

import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ADMIN;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_JOURNALNODE_KEYTAB_FILE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_JOURNALNODE_INTERNAL_SPNEGO_USER_NAME_KEY;

import java.io.IOException;
import java.net.InetSocketAddress;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.server.common.JspHelper;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.SecurityUtil;

/**
 * Encapsulates the HTTP server started by the Journal Service.
 */
@InterfaceAudience.Private
public class JournalNodeHttpServer {
  public static final Log LOG = LogFactory.getLog(
      JournalNodeHttpServer.class);

  public static final String JN_ATTRIBUTE_KEY = "localjournal";

  private HttpServer httpServer;
  private int infoPort;
  private JournalNode localJournalNode;

  private final Configuration conf;

  JournalNodeHttpServer(Configuration conf, JournalNode jn) {
    this.conf = conf;
    this.localJournalNode = jn;
  }

  void start() throws IOException {
    final InetSocketAddress bindAddr = getAddress(conf);

    // initialize the webserver for uploading/downloading files.
    LOG.info("Starting web server as: "+ SecurityUtil.getServerPrincipal(conf
        .get(DFS_JOURNALNODE_INTERNAL_SPNEGO_USER_NAME_KEY),
        bindAddr.getHostName()));

    int tmpInfoPort = bindAddr.getPort();
    httpServer = new HttpServer("journal", bindAddr.getHostName(),
        tmpInfoPort, tmpInfoPort == 0, conf, new AccessControlList(conf
            .get(DFS_ADMIN, " "))) {
      {
        if (UserGroupInformation.isSecurityEnabled()) {
          initSpnego(conf, DFS_JOURNALNODE_INTERNAL_SPNEGO_USER_NAME_KEY,
              DFS_JOURNALNODE_KEYTAB_FILE_KEY);
        }
      }
    };
    httpServer.setAttribute(JN_ATTRIBUTE_KEY, localJournalNode);
    httpServer.setAttribute(JspHelper.CURRENT_CONF, conf);
    httpServer.addInternalServlet("getJournal", "/getJournal",
        GetJournalEditServlet.class, true);
    httpServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = httpServer.getPort();

    LOG.info("Journal Web-server up at: " + bindAddr + ":" + infoPort);
  }

  void stop() throws IOException {
    if (httpServer != null) {
      try {
        httpServer.stop();
      } catch (Exception e) {
        throw new IOException(e);
      }
    }
  }

  /**
   * Return the actual address bound to by the running server.
   */
  public InetSocketAddress getAddress() {
    InetSocketAddress addr = httpServer.getListenerAddress();
    assert addr.getPort() != 0;
    return addr;
  }

  private static InetSocketAddress getAddress(Configuration conf) {
    String addr = conf.get(DFSConfigKeys.DFS_JOURNALNODE_HTTP_ADDRESS_KEY,
        DFSConfigKeys.DFS_JOURNALNODE_HTTP_ADDRESS_DEFAULT);
    return NetUtils.createSocketAddr(addr,
        DFSConfigKeys.DFS_JOURNALNODE_HTTP_PORT_DEFAULT,
        DFSConfigKeys.DFS_JOURNALNODE_HTTP_ADDRESS_KEY);
  }

  public static Journal getJournalFromContext(ServletContext context, String jid)
      throws IOException {
    JournalNode jn = (JournalNode)context.getAttribute(JN_ATTRIBUTE_KEY);
    return jn.getOrCreateJournal(jid);
  }

  public static Configuration getConfFromContext(ServletContext context) {
    return (Configuration) context.getAttribute(JspHelper.CURRENT_CONF);
  }
}


text:
package org.watertemplate.example.collection;

import java.time.Year;

public class Main {

    public static void main(String[] args) {
        MonthsGrid monthsGrid = new MonthsGrid(Year.of(2015));
        System.out.println(monthsGrid.render());
    }
}


text:
package com.internetitem.web.html;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface TemplateName {
	String name();
}


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>org.java_websocket.exceptions (Java WebSocket 1.3.1-SNAPSHOT API)</title>
<meta name="date" content="2014-06-19">
<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 Package

Next Package

Frames

No Frames

All Classes

Package org.java_websocket.exceptions

Exception Summary

Exception
Description

IncompleteHandshakeException

InvalidDataException

InvalidFrameException

InvalidHandshakeException

LimitExedeedException

NotSendableException

WebsocketNotConnectedException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2014. All Rights Reserved.


text:
import { Observable } from 'app/utils/observable';

/**
 * The currently selected store for showing gear power.
 */
export const showGearPower$ = new Observable<string | undefined>(undefined);

/**
 * Show the gear power sheet
 */
export function showGearPower(selectedStoreId: string) {
  showGearPower$.next(selectedStoreId);
}


text:
"""WARNING: running code from this file might destroy existing databases or tables.

This file contains integration tests. Tests invoke mschematool commands using
subprocess module and check command output and database contents.

For tests using SQLite3, it only requires write access in /tmp.

For tests using PostgreSQL, you need a locally running Postgres server and
commands:
$ createdb mtest1
$ dropdb mtest1
working without additional arguments.

For tests using Cassandra, you need a locally running Cassandra server that
accepts local connections without authorization. WARNING: running tests will
drop 'migrations' keyspace on the default cluster.

To execute tests, run (CWD must be the directory of this file):

$ ./test_basic.py # postgres + cassandra
$ ./test_basic.py CassandraTestBasic # cassandra
$ ./test_basic.py PostgresTestBasic # postgres
$ ./test_basic.py Sqlite3TestBasic # sqlite3
"""

import unittest
import os
import shlex
import subprocess
import sys
import imp
import traceback

sys.path.append('.')

class RunnerBase(object):

    def __init__(self, config, dbnick):
        self.config = config
        self.dbnick = dbnick
        self.config_module = imp.load_source('mschematool_config', self.config)
        self.last_retcode = None

    def run(self, cmd):
        os.environ['PYTHONPATH'] = '..'
        full_cmd = '../mschematool/cli.py --config {self.config} --verbose {self.dbnick} {cmd}'.format(self=self,
                                                                                cmd=cmd)
        sys.stderr.write(full_cmd + '\n')
        try:
            out = subprocess.check_output(shlex.split(full_cmd))
        except subprocess.CalledProcessError as e:
            self.last_retcode = e.returncode
            out = e.output
        except:
            self.last_retcode = None
            sys.stderr.write(traceback.format_exc() + '\n')
            out = ''
        else:
            self.last_retcode = 0
        sys.stderr.write(out.decode('unicode_escape'))
        return out.decode('unicode_escape').strip()

    def close(self):
        pass

class RunnerPostgres(RunnerBase):

    def __init__(self, config, dbnick):
        import psycopg2
        RunnerBase.__init__(self, config, dbnick)
        self.conn = psycopg2.connect(self.config_module.DATABASES[self.dbnick]['dsn'])

    def cursor(self):
        import psycopg2.extras
        return self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    def close(self):
        self.conn.close()

    def configured_migration_table(self):
        return self.config_module.DATABASES[self.dbnick].get('migration_table', 'public.migration')

class RunnerCassandra(RunnerBase):

    def __init__(self, config, dbnick):
        import cassandra.cluster

        RunnerBase.__init__(self, config, dbnick)

        assert self.config_module.DATABASES[dbnick]['engine'] == 'cassandra'
        self.cluster = cassandra.cluster.Cluster(**self.config_module.DATABASES[self.dbnick]\
                                                 ['cluster_kwargs'])
        self.keyspace = self.config_module.DATABASES[self.dbnick]['keyspace']
        s = self.cluster.connect()
        s.execute("""CREATE KEYSPACE IF NOT EXISTS {keyspace} WITH REPLICATION = {{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }}""".format(keyspace=self.keyspace))
        s.shutdown()

    def session(self):
        s = self.cluster.connect()
        return s

    def close(self):
        self.cluster.shutdown()

class RunnerSqlite3(RunnerBase):

    def __init__(self, config, dbnick):
        import sqlite3

        RunnerBase.__init__(self, config, dbnick)

        dbconfig = self.config_module.DATABASES[self.dbnick]
        try:
            os.unlink(dbconfig['database'])
        except OSError:
            pass
        assert dbconfig['engine'] == 'sqlite3'
        self.conn = sqlite3.connect(dbconfig['database'], **dbconfig['connect_kwargs'])

    def cursor(self):
        return self.conn.cursor()

    def close(self):
        try:
            dbconfig = self.config_module.DATABASES[self.dbnick]
            os.unlink(dbconfig['database'])
        except OSError:
            pass

### Tests common to all databases

class CommonTests(object):

    def testInitdbIdempotency(self):
        self.r.run('init_db')
        self.assertEqual(0, self.r.last_retcode)
        self.r.run('init_db')
        self.assertEqual(0, self.r.last_retcode)

### Postgres tests

class PostgresTestBase(unittest.TestCase):
    db = 'mtest1'
    dbnick = 'default'
    schema_file = '/tmp/mtest1.sql'

    def setUp(self):
        os.system('createdb %s' % self.db)
        self.r = RunnerPostgres('config_basic.py', self.dbnick)

    def tearDown(self):
        self.r.close()
        os.system('dropdb %s' % self.db)
        try:
            os.unlink(self.schema_file)
        except OSError:
            pass

class PostgresTestBasic(PostgresTestBase, CommonTests):

    def testInitdb(self):
        self.r.run('init_db')

        # check existence of the migration table
        schema, table = self.r.configured_migration_table().split('.')
        with self.r.cursor() as cur:
            cur.execute("""SELECT EXISTS(SELECT * FROM information_schema.tables
                           WHERE table_name = %s AND table_schema = %s)""",
                        [table, schema])
            self.assertTrue(cur.fetchone()[0])

    def testToSync(self):
        self.r.run('init_db')
        out = self.r.run('to_sync')
        self.assertEqual(5, len(out.split('\n')))

    def testSync(self):
        self.r.run('init_db')
        self.r.run('sync')
        with self.r.cursor() as cur:
            cur.execute("""SELECT COUNT(*) FROM article""")
            self.assertEqual(4, cur.fetchone()[0])

    def testLatestSynced(self):
        self.r.run('init_db')
        self.r.run('sync')
        out = self.r.run('latest_synced')
        assert out.endswith('m20140615135414_insert3.py')

    def testForceSyncSingle(self):
        self.r.run('init_db')
        self.r.run('force_sync_single m20140615132456_init2.sql')

        out = self.r.run('synced')
        self.assertEqual(1, len(out.split('\n')))

        out = self.r.run('latest_synced')
        assert out.endswith('m20140615132456_init2.sql')

    def testPrintNew(self):
        self.r.run('init_db')
        out = self.r.run('print_new xxx')
        assert out.endswith('_xxx.sql'), out

    def testPrintNewPy(self):
        self.r.run('init_db')
        out = self.r.run('print_new xxx py')
        assert out.endswith('_xxx.py'), out

class PostgresTestSpecial(PostgresTestBase):
    dbnick = 'error'

    def testSync(self):
        self.r.run('init_db')
        self.r.run('sync')
        with self.r.cursor() as cur:
            cur.execute("""SELECT COUNT(*) FROM article""")
            self.assertEqual(1, cur.fetchone()[0])

class PostgresTestFileExtensions(PostgresTestBase):
    dbnick = 'extensions1'

    def testToSync(self):
        self.r.run('init_db')
        out = self.r.run('to_sync')
        self.assertEqual([
            u'm20140615132455_init.sql',
            u'm20140615132456_init.postgres',
            u'no_m.sql',
            u'pgsql_specific.postgres',
        ], out.splitlines())

class PostgresTestPassingDbConfig(PostgresTestBase):
    dbnick = 'migrate_args'

    def testSync(self):
        self.r.run('init_db')
        self.r.run('sync')

        out = self.r.run('synced')
        self.assertEqual(5, len(out.split('\n')))

        with self.r.cursor() as cur:
            cur.execute("""SELECT id FROM article""")
            ids = [r[0] for r in cur.fetchall()]
        self.assertEqual([1, 2, 3], ids)

class PostgresTestDifferentSchema(PostgresTestBase):
    dbnick = 'different_schema'

    def testSync(self):
        with self.r.cursor() as cur:
            cur.execute("""CREATE SCHEMA hooli""")
            cur.execute("""COMMIT""")
        self.r.run('init_db')

        with self.r.cursor() as cur:
            cur.execute("""SELECT EXISTS(SELECT * FROM information_schema.tables
                           WHERE table_name = 'migration' AND table_schema = 'hooli')""")
            self.assertTrue(cur.fetchone()[0])

        self.r.run('sync')
        out = self.r.run('latest_synced')
        assert out.endswith('004_phone.sql')

### Cassandra tests

class CassandraTestBasic(unittest.TestCase, CommonTests):

    def setUp(self):
        self.r = RunnerCassandra('config_basic.py', 'cass_default')

    def tearDown(self):
        s = self.r.session()
        s.execute("""DROP KEYSPACE IF EXISTS migrations""")
        s.execute("""DROP KEYSPACE IF EXISTS mtest""")
        self.r.close()

    def testInitdb(self):
        self.r.run('init_db')
        s = self.r.session()
        rows = s.execute("""SELECT columnfamily_name FROM system.schema_columnfamilies
            WHERE columnfamily_name=%s AND keyspace_name=%s""", ['migration', 'migrations'])
        self.assertEqual(1, len(rows))

    def testToSync(self):
        self.r.run('init_db')
        out = self.r.run('to_sync')
        self.assertEqual(6, len(out.split('\n')))

    def testSync(self):
        self.r.run('init_db')
        self.r.run('sync')
        s = self.r.session()
        rows = s.execute("""SELECT COUNT(*) FROM mtest.article""")
        self.assertEqual(4, rows[0].count)

    def testLatestSynced(self):
        self.r.run('init_db')
        self.r.run('sync')
        out = self.r.run('latest_synced')
        assert out.endswith('m20140615133009_insert2.cql'), repr(out)

    def testForceSyncSingle(self):
        self.r.run('init_db')
        self.r.run('force_sync_single m20140615132456_init2.cql')

        out = self.r.run('synced')
        self.assertEqual(1, len(out.split('\n')))

        out = self.r.run('latest_synced')
        assert out.endswith('m20140615132456_init2.cql')

    def testPrintNew(self):
        self.r.run('init_db')
        out = self.r.run('print_new xxx cql')
        assert out.endswith('_xxx.cql'), out

### Sqlite3 tests

class Sqlite3TestBasic(unittest.TestCase, CommonTests):

    def setUp(self):
        self.r = RunnerSqlite3('config_basic.py', 'sqlite3_default')

    def tearDown(self):
        self.r.close()

    def testInitdb(self):
        self.r.run('init_db')
        cur = self.r.cursor()
        cur.execute("""SELECT EXISTS(SELECT * FROM sqlite_master
        WHERE tbl_name='migration')""")
        self.assertTrue(cur.fetchone()[0])

    def testToSync(self):
        self.r.run('init_db')
        out = self.r.run('to_sync')
        self.assertEqual(5, len(out.split('\n')))

    def testSync(self):
        self.r.run('init_db')
        self.r.run('sync')
        cur = self.r.cursor()
        cur.execute("""SELECT COUNT(*) FROM article""")
        self.assertEqual(4, cur.fetchone()[0])

    def testLatestSynced(self):
        self.r.run('init_db')
        self.r.run('sync')
        out = self.r.run('latest_synced')
        assert out.endswith('m20140615135414_insert3.py')

    def testForceSyncSingle(self):
        self.r.run('init_db')
        self.r.run('force_sync_single m20140615132456_init2.sql')

        out = self.r.run('synced')
        self.assertEqual(1, len(out.split('\n')))

        out = self.r.run('latest_synced')
        assert out.endswith('m20140615132456_init2.sql')

    def testPrintNew(self):
        self.r.run('init_db')
        out = self.r.run('print_new xxx')
        assert out.endswith('_xxx.sql'), out

    def testPrintNewPy(self):
        self.r.run('init_db')
        out = self.r.run('print_new xxx py')
        assert out.endswith('_xxx.py'), out

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


text:
require 'rack'
require 'helpers'

class Kibana
	include Helpers

	def call(env)
		# Default to /index.html
		if env['PATH_INFO'].delete('/').empty? then
			env['PATH_INFO'] = '/index.html'
		end

		response = ::Rack::File.new('kibana/src').call(env)
		if env['PATH_INFO'] == '/index.html' then
			# Tack on our header to add a logout button
			status, headers, body = response
			# 304 means 304 for us too
			return response if status == 304

			html_header = html('kibana_header')

			new_body = ''
			body.each{|i| new_body += i}

			new_body.gsub!(/(<body.*?>)/, "#{$1}#{html_header}")

			headers['Content-Length'] = new_body.bytesize.to_s
			headers['Cache-Control'] = 'max-age=0, must-revalidate'
			response = status, headers, [new_body]
		end

		return response
	end
end


text:
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="bex.step_time_logger_extension.config" class="Bex\Behat\StepTimeLoggerExtension\ServiceContainer\Config" />
        <service id="bex.step_time_logger_extension.output_printer.current" class="Bex\Behat\StepTimeLoggerExtension\Service\OutputPrinter\Console" />

        <service id="bex.step_time_logger_extension.filesystem" class="Symfony\Component\Filesystem\Filesystem" />
        <service id="bex.step_time_logger_extension.step_time_logger" class="Bex\Behat\StepTimeLoggerExtension\Service\StepTimeLogger" />

        <service id="bex.step_time_logger_extension.cli_controller" class="Bex\Behat\StepTimeLoggerExtension\Cli\StepTimeLoggerController">
            <tag name="cli.controller" priority="1"/>
            <argument type="service" id="bex.step_time_logger_extension.config" />
        </service>

        <!-- event listener -->
        <service id="bex.step_time_logger_extension.steptimelogger_listener" class="Bex\Behat\StepTimeLoggerExtension\Listener\StepTimeLoggerListener" public="false">
            <tag name="event_dispatcher.subscriber" />
            <argument type="service" id="bex.step_time_logger_extension.config" />
            <argument type="service" id="bex.step_time_logger_extension.step_time_logger" />
        </service>

        <!-- output printers -->
        <service id="bex.step_time_logger_extension.output_printer.console" class="Bex\Behat\StepTimeLoggerExtension\Service\OutputPrinter\Console" public="true">
            <argument type="service" id="cli.output" />
        </service>
        <service id="bex.step_time_logger_extension.output_printer.csv" class="Bex\Behat\StepTimeLoggerExtension\Service\OutputPrinter\Csv" public="true">
            <argument type="service" id="cli.output" />
            <argument type="service" id="bex.step_time_logger_extension.filesystem" />
        </service>
    </services>
</container>


text:
.SUFFIXES:
MAKEFLAGS+=-r

config=debug
defines=standard
cxxstd=c++11
# set cxxstd=any to disable use of -std=...

BUILD=build/make-$(CXX)-$(config)-$(defines)-$(cxxstd)

SOURCES=src/pugixml.cpp $(filter-out tests/fuzz_%,$(wildcard tests/*.cpp))
EXECUTABLE=$(BUILD)/test

VERSION=$(shell sed -n 's/.*version \(.*\).*/\1/p' src/pugiconfig.hpp)
RELEASE=$(filter-out scripts/archive.py docs/%.adoc,$(shell git ls-files docs scripts src CMakeLists.txt LICENSE.md readme.txt))

CXXFLAGS=-g -Wall -Wextra -Werror -pedantic -Wundef -Wshadow -Wcast-align -Wcast-qual -Wold-style-cast -Wdouble-promotion
LDFLAGS=

ifeq ($(config),release)
	CXXFLAGS+=-O3 -DNDEBUG
endif

ifeq ($(config),coverage)
	CXXFLAGS+=-coverage
	LDFLAGS+=-coverage
endif

ifeq ($(config),sanitize)
	CXXFLAGS+=-fsanitize=address,undefined -fno-sanitize=float-divide-by-zero,float-cast-overflow -fno-sanitize-recover=all
	LDFLAGS+=-fsanitize=address,undefined
endif

ifeq ($(config),analyze)
	CXXFLAGS+=--analyze
endif

ifneq ($(defines),standard)
	COMMA=,
	CXXFLAGS+=-D $(subst $(COMMA), -D ,$(defines))
endif

ifneq ($(findstring PUGIXML_NO_EXCEPTIONS,$(defines)),)
	CXXFLAGS+=-fno-exceptions
endif

ifneq ($(cxxstd),any)
	CXXFLAGS+=-std=$(cxxstd)
endif

OBJECTS=$(SOURCES:%=$(BUILD)/%.o)

all: $(EXECUTABLE)

ifeq ($(config),coverage)
test: $(EXECUTABLE)
	-@find $(BUILD) -name '*.gcda' -exec rm {} +
	./$(EXECUTABLE)
	@gcov -b -o $(BUILD)/src/ pugixml.cpp.gcda | sed -e '/./{H;$!d;}' -e 'x;/pugixml.cpp/!d;'
	@find . -name '*.gcov' -and -not -name 'pugixml.cpp.gcov' -exec rm {} +
	@sed -i -e "s/#####\(.*\)\(\/\/ unreachable.*\)/    1\1\2/" pugixml.cpp.gcov
else
test: $(EXECUTABLE)
	./$(EXECUTABLE)
endif

fuzz_%: $(BUILD)/fuzz_%
	@mkdir -p build/$@
	$< build/$@ tests/data_fuzz_$* -max_len=1024 -dict=tests/fuzz_$*.dict

clean:
	rm -rf $(BUILD)

release: build/pugixml-$(VERSION).tar.gz build/pugixml-$(VERSION).zip

docs: docs/quickstart.html docs/manual.html

build/pugixml-%: .FORCE | $(RELEASE)
	@mkdir -p $(BUILD)
	TIMESTAMP=`git show v$(VERSION) -s --format=%ct` && python3 scripts/archive.py $@ pugixml-$(VERSION) $$TIMESTAMP $|

$(EXECUTABLE): $(OBJECTS)
	$(CXX) $(OBJECTS) $(LDFLAGS) -o $@

$(BUILD)/fuzz_%: tests/fuzz_%.cpp src/pugixml.cpp
	@mkdir -p $(BUILD)
	$(CXX) $(CXXFLAGS) -fsanitize=address,fuzzer $^ -o $@

$(BUILD)/%.o: %
	@mkdir -p $(dir $@)
	$(CXX) $< $(CXXFLAGS) -c -MMD -MP -o $@

-include $(OBJECTS:.o=.d)

.SECONDEXPANSION:
docs/%.html: docs/%.adoc $$(shell sed -n 's/include\:\:\(.*\)\[.*/docs\/\1/p' docs/%.adoc)
	asciidoctor -b html5 -a version=$(VERSION) $< -o $@

.PHONY: all test clean release .FORCE


text:
package org.artificer.integration.teiid;

import org.artificer.common.i18n.AbstractMessages;

/**
 * Internationalized messages for the Teiid S-RAMP integration module.
 */
public final class Messages extends AbstractMessages {

    /**
     * The shared instance of the localized messages.
     */
    public static final Messages I18N = new Messages();

    /**
     * Don't allow construct outside of this class.
     */
    private Messages() {
        super(Messages.class);
    }

}


text:
<#
    .SYNOPSIS

    .DESCRIPTION

    .PARAMETER alguno

    .EXAMPLE

    .NOTES

#>
[CmdletBinding()]

param (
    [String]
    $Group = "Zarcam SA"
)

process {
    $ArrayObjects = New-Object System.Collections.Generic.List[System.Object]

    try {
        $Members = (Get-DistributionGroupMember -Identity $Group).Where( { $_.RecipientType -eq "User" })
        Foreach ($Member in $Members) {
            $PropertyObject = @{}
            Remove-DistributionGroupMember -Identity $Group -Member $Member.Name -Confirm:$False
            $PropertyObject.RemovedUsers = $Member.Name
            $Object = New-Object PSObject -Property $PropertyObject
            $ArrayObjects.Add($Object)
        }
        Write-Output $ArrayObjects
    } catch {
        Write-Error -Message "Usuario no conectado a Exchange Online. Usar Script 'Connect-ExchangeOnline.ps1'. Ejecutar desde una consola. "
    }
}


text:
require 'minitest_helper.rb'
require 'minitest/autorun'

require 'aptly_cli'

module AptlyCli
  class AptlyCommand
    def ask(_prompt)
      'zane'
    end

    def password(_prompt)
      'secret'
    end
  end
end

describe AptlyCli::AptlyCommand do
  it 'has a default config' do
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config)
    cmd.config[:proto].must_equal 'http'
    cmd.config[:server].must_equal '127.0.0.1'
    cmd.config[:port].must_equal 8082
  end

  it 'accepts empty options and no config changes' do
    options = Options.new
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config, options)
    cmd.config[:proto].must_equal 'http'
    cmd.config[:server].must_equal '127.0.0.1'
    cmd.config[:port].must_equal 8082
  end

  it 'can take options and updates its config accordingly' do
    options = Options.new
    options.server = 'my-server'
    options.port = 9000
    options.username = 'me'
    options.password = 'secret'
    options.debug = false
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config, options)
    cmd.config[:server].must_equal 'my-server'
    cmd.config[:port].must_equal 9000
    cmd.config[:username].must_equal 'me'
    cmd.config[:password].must_equal 'secret'
    assert_nil cmd.config[:debug]
  end

  it 'handles the "debug" option' do
    options = Options.new
    options.debug = true
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config, options)
    cmd.config[:debug].must_equal true
  end

  it 'can process an option with \'${PROMPT}\' in it' do
    options = Options.new
    options.username = '${PROMPT}'
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config, options)
    cmd.config[:username].must_equal 'zane'
  end

  it 'can process an option with \'${PROMPT_PASSWORD}\' in it' do
    options = Options.new
    options.username = '${PROMPT_PASSWORD}'
    config = AptlyCli::AptlyLoad.new.configure_with(nil)
    cmd = AptlyCli::AptlyCommand.new(config, options)
    cmd.config[:username].must_equal 'secret'
  end

  it 'can process an option with \'${KEYRING`}\' in it' do
    options = Options.new
    options.username = 'marc'
    options.password = '${KEYRING}'
    Keyring = class << self; self; end # rubocop:disable ConstantName
    keyring = Minitest::Mock.new
    keyring.expect(
      :get_password,
      nil,
      ['Aptly API server at 127.0.0.1:8082', 'marc'])
    keyring.expect(
      :set_password,
      nil,
      ['Aptly API server at 127.0.0.1:8082', 'marc', 'secret'])
    Keyring.stub :new, keyring do
      config = AptlyCli::AptlyLoad.new.configure_with(nil)
      cmd = AptlyCli::AptlyCommand.new(config, options)
      cmd.config[:username].must_equal 'marc'
      cmd.config[:password].must_equal 'secret'
    end
  end
end


text:
package org.mutabilitydetector;

import java.util.Map;

import org.mutabilitydetector.checkers.info.AnalysisInProgress;
import org.mutabilitydetector.locations.Dotted;

public interface AnalysisSession {
    AnalysisResult resultFor(Dotted className);
    AnalysisResult processTransitiveAnalysis(Dotted className, AnalysisInProgress analysisInProgress);

    Iterable<AnalysisResult> getResults();
    Map<Dotted, AnalysisResult> resultsByClass();

    Iterable<AnalysisError> getErrors();

}


text:
package maps

import (
	"sync"
)

type StringIntMap struct {
	sync.RWMutex
	M map[string]int
}

func NewStringIntMap() *StringIntMap {
	return &StringIntMap{M: make(map[string]int)}
}

func (this *StringIntMap) Put(key string, val int) {
	this.Lock()
	defer this.Unlock()
	this.M[key] = val
}

func (this *StringIntMap) Puts(m map[string]int) {
	todo := make(map[string]int)
	this.RLock()
	for k, v := range m {
		old, exists := this.M[k]
		if exists && v == old {
			continue
		}
		todo[k] = v
	}
	this.RUnlock()

	if len(todo) == 0 {
		return
	}

	this.Lock()
	for k, v := range todo {
		this.M[k] = v
	}
	this.Unlock()
}

func (this *StringIntMap) Get(key string) (int, bool) {
	this.RLock()
	defer this.RUnlock()
	val, exists := this.M[key]
	return val, exists
}

func (this *StringIntMap) Exists(key string) bool {
	_, exists := this.Get(key)
	return exists
}

func (this *StringIntMap) Remove(key string) {
	this.Lock()
	defer this.Unlock()
	delete(this.M, key)
}


text:
<?php
namespace CodeCloud\Bundle\ShopifyBundle\Api\Endpoint;

use CodeCloud\Bundle\ShopifyBundle\Api\Request\GetJson;
use CodeCloud\Bundle\ShopifyBundle\Api\Request\PostJson;
use CodeCloud\Bundle\ShopifyBundle\Api\Request\PutJson;
use CodeCloud\Bundle\ShopifyBundle\Api\GenericResource;

class CommentEndpoint extends AbstractEndpoint
{
    /**
     * @param array $query
     * @return array|GenericResource[]
     */
    public function findAll(array $query = array())
    {
        $request = new GetJson('/admin/comments.json', $query);
        $response = $this->sendPaged($request, 'comments');
        return $this->createCollection($response);
    }

    /**
     * @param array $query
     * @return int
     */
    public function countAll(array $query = array())
    {
        $request = new GetJson('/admin/comments/count.json', $query);
        $response = $this->send($request);
        return $response->get('count');
    }

    /**
     * @param int $commentId
     * @return \CodeCloud\Bundle\ShopifyBundle\Api\GenericResource
     */
    public function findOne($commentId)
    {
        $request = new GetJson('/admin/comments/' . $commentId . '.json');
        $response = $this->send($request);
        return $this->createEntity($response->get('comment'));
    }

    /**
     * @param \CodeCloud\Bundle\ShopifyBundle\Api\GenericResource $comment
     * @return \CodeCloud\Bundle\ShopifyBundle\Api\GenericResource
     */
    public function create(GenericResource $comment)
    {
        $request = new PostJson('/admin/comments.json', array('comment' => $comment->toArray()));
        $response = $this->send($request);
        return $this->createEntity($response->get('comment'));
    }

    /**
     * @param int $commentId
     * @param \CodeCloud\Bundle\ShopifyBundle\Api\GenericResource $comment
     * @return \CodeCloud\Bundle\ShopifyBundle\Api\GenericResource
     */
    public function update($commentId, GenericResource $comment)
    {
        $request = new PutJson('/admin/comments/' . $commentId . '.json', array('comment' => $comment->toArray()));
        $response = $this->send($request);
        return $this->createEntity($response->get('comment'));
    }

    /**
     * @param int $commentId
     */
    public function markAsSpam($commentId)
    {
        $request = new PostJson('/admin/comments/' . $commentId . '/spam.json');
        $this->send($request);
    }

    /**
     * @param int $commentId
     */
    public function markAsNotSpam($commentId)
    {
        $request = new PostJson('/admin/comments/' . $commentId . '/not_spam.json');
        $this->send($request);
    }

    /**
     * @param int $commentId
     */
    public function approve($commentId)
    {
        $request = new PostJson('/admin/comments/' . $commentId . '/approve.json');
        $this->send($request);
    }

    /**
     * @param int $commentId
     */
    public function remove($commentId)
    {
        $request = new PostJson('/admin/comments/' . $commentId . '/remove.json');
        $this->send($request);
    }

    /**
     * @param int $commentId
     */
    public function restore($commentId)
    {
        $request = new PostJson('/admin/comments/' . $commentId . '/restore.json');
        $this->send($request);
    }
}


text:
<?php $this->load->view('template_header') ?>

FGD

Edit/Input Data

          <form enctype="multipart/form-data" name="myForm">

              Judul

                Judul harus diisi

              <input type="text" name="txtJudul" class="form-control" id="Judul" ng-model="txtJudul" placeholder="Judul" required>
              <input type="hidden" class="form-control" id="ID" ng-model="txtID">

              Tahun

                Tahun harus diisi
                 Not valid number!

              <input type="number" min="1900" max="2100" class="form-control" name="txtTahun" id="Tahun" ng-model="txtTahun" placeholder="YYYY" required>

              Kategori

                Kategori harus dipilih

              <select class="form-control" ng-model="cmbKategory" name="cmbKategory" required>
                <option value="">--Pilih Kategori--</option>
                <option ng-repeat="cmbCat in optCategories" value="{{cmbCat.id}}">{{cmbCat.nama}}</option>
              </select>

              watching model:
              <input class="button" ngf-reset-on-click="true" type="file" ngf-select ng-model="file">Upload File</input>

            <button type="button" class="btn btn-info"><< Back</button>
            <button type="reset" class="btn btn-warning">Reset</button>
            <button type="button" ng-disabled="myForm.$invalid" multiple="true" ng-model="formSubmit" ng-click="doSubmit()" class="btn btn-primary">Submit</button>
          </form>

<?php
$this->load->view('template_menu');
$this->load->view('template_footer');
?>


text:
package com.ksa.web.struts2.action.finance.charge;

import java.util.Date;

import com.ksa.context.ServiceContextUtils;
import com.ksa.service.finance.ChargeService;
import com.ksa.service.logistics.BookingNoteService;
import com.ksa.service.security.util.SecurityUtils;

public class ChargeSaveAction extends ChargeEditAction {

    private static final long serialVersionUID = -3776802985971150958L;

    @Override
    protected String doExecute() throws Exception {
        Date chargeDate = bookingNote.getChargeDate();
        BookingNoteService service = ServiceContextUtils.getService( BookingNoteService.class );
        bookingNote = service.loadBookingNoteById( bookingNote.getId() );
        bookingNote.setChargeDate( chargeDate );
        ChargeService chargeService = ServiceContextUtils.getService( ChargeService.class );
        chargeService.saveBookingNoteCharges( bookingNote, incomes, expenses );

        // 这里利用 bookingNote.creator 属性显示当前用户信息。
        bookingNote.setCreator( SecurityUtils.getCurrentUser() );
        return SUCCESS;
    }
}


text:
<settings>
  <localRepository>/tmp/fitnesse-maven-classpath/user-repository</localRepository>
</settings>