text:
import os
import re
import unittest

import PRESUBMIT

class MockInputApi(object):
  def __init__(self):
    self.re = re
    self.os_path = os.path
    self.files = []
    self.is_committing = False

  def AffectedFiles(self):
    return self.files

class MockOutputApi(object):
  class PresubmitResult(object):
    def __init__(self, message, items=None, long_text=''):
      self.message = message
      self.items = items
      self.long_text = long_text

  class PresubmitError(PresubmitResult):
    def __init__(self, message, items, long_text=''):
      MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
      self.type = 'error'

  class PresubmitPromptWarning(PresubmitResult):
    def __init__(self, message, items, long_text=''):
      MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
      self.type = 'warning'

  class PresubmitNotifyResult(PresubmitResult):
    def __init__(self, message, items, long_text=''):
      MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
      self.type = 'notify'

  class PresubmitPromptOrNotify(PresubmitResult):
    def __init__(self, message, items, long_text=''):
      MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
      self.type = 'promptOrNotify'

class MockFile(object):
  def __init__(self, local_path, new_contents):
    self._local_path = local_path
    self._new_contents = new_contents
    self._changed_contents = [(i + 1, l) for i, l in enumerate(new_contents)]

  def ChangedContents(self):
    return self._changed_contents

  def NewContents(self):
    return self._new_contents

  def LocalPath(self):
    return self._local_path

class MockChange(object):
  def __init__(self, changed_files):
    self._changed_files = changed_files

  def LocalPaths(self):
    return self._changed_files

class IncludeOrderTest(unittest.TestCase):
  def testSystemHeaderOrder(self):
    scope = [(1, '#include <csystem.h>'),
             (2, '#include <cppsystem>'),
             (3, '#include "acustom.h"')]
    all_linenums = [linenum for (linenum, _) in scope]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', all_linenums)
    self.assertEqual(0, len(warnings))

  def testSystemHeaderOrderMismatch1(self):
    scope = [(10, '#include <cppsystem>'),
             (20, '#include <csystem.h>'),
             (30, '#include "acustom.h"')]
    all_linenums = [linenum for (linenum, _) in scope]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', all_linenums)
    self.assertEqual(1, len(warnings))
    self.assertTrue('20' in warnings[0])

  def testSystemHeaderOrderMismatch2(self):
    scope = [(10, '#include <cppsystem>'),
             (20, '#include "acustom.h"'),
             (30, '#include <csystem.h>')]
    all_linenums = [linenum for (linenum, _) in scope]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', all_linenums)
    self.assertEqual(1, len(warnings))
    self.assertTrue('30' in warnings[0])

  def testSystemHeaderOrderMismatch3(self):
    scope = [(10, '#include "acustom.h"'),
             (20, '#include <csystem.h>'),
             (30, '#include <cppsystem>')]
    all_linenums = [linenum for (linenum, _) in scope]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', all_linenums)
    self.assertEqual(2, len(warnings))
    self.assertTrue('20' in warnings[0])
    self.assertTrue('30' in warnings[1])

  def testAlphabeticalOrderMismatch(self):
    scope = [(10, '#include <csystem.h>'),
             (15, '#include <bsystem.h>'),
             (20, '#include <cppsystem>'),
             (25, '#include <bppsystem>'),
             (30, '#include "bcustom.h"'),
             (35, '#include "acustom.h"')]
    all_linenums = [linenum for (linenum, _) in scope]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', all_linenums)
    self.assertEqual(3, len(warnings))
    self.assertTrue('15' in warnings[0])
    self.assertTrue('25' in warnings[1])
    self.assertTrue('35' in warnings[2])

  def testSpecialFirstInclude1(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/path/foo.h"',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo.cc', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testSpecialFirstInclude2(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/other/path/foo.h"',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo.cc', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testSpecialFirstInclude3(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/path/foo.h"',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo_platform.cc', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testSpecialFirstInclude4(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/path/bar.h"',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo_platform.cc', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(1, len(warnings))
    self.assertTrue('2' in warnings[0])

  def testSpecialFirstInclude5(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/other/path/foo.h"',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo-suffix.h', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testSpecialFirstInclude6(self):
    mock_input_api = MockInputApi()
    contents = ['#include "some/other/path/foo_win.h"',
                '#include <set>',
                '#include "a/header.h"']
    mock_file = MockFile('some/path/foo_unittest_win.h', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testOrderAlreadyWrong(self):
    scope = [(1, '#include "b.h"'),
             (2, '#include "a.h"'),
             (3, '#include "c.h"')]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', [3])
    self.assertEqual(0, len(warnings))

  def testConflictAdded1(self):
    scope = [(1, '#include "a.h"'),
             (2, '#include "c.h"'),
             (3, '#include "b.h"')]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', [2])
    self.assertEqual(1, len(warnings))
    self.assertTrue('3' in warnings[0])

  def testConflictAdded2(self):
    scope = [(1, '#include "c.h"'),
             (2, '#include "b.h"'),
             (3, '#include "d.h"')]
    mock_input_api = MockInputApi()
    warnings = PRESUBMIT._CheckIncludeOrderForScope(scope, mock_input_api,
                                                    '', [2])
    self.assertEqual(1, len(warnings))
    self.assertTrue('2' in warnings[0])

  def testIfElifElseEndif(self):
    mock_input_api = MockInputApi()
    contents = ['#include "e.h"',
                '#define foo',
                '#include "f.h"',
                '#undef foo',
                '#include "e.h"',
                '#if foo',
                '#include "d.h"',
                '#elif bar',
                '#include "c.h"',
                '#else',
                '#include "b.h"',
                '#endif',
                '#include "a.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testExcludedIncludes(self):
    # #include <sys/...>'s can appear in any order.
    mock_input_api = MockInputApi()
    contents = ['#include <sys/b.h>',
                '#include <sys/a.h>']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

    contents = ['#include <atlbase.h>',
                '#include <aaa.h>']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

    contents = ['#include "build/build_config.h"',
                '#include "aaa.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(0, len(warnings))

  def testCheckOnlyCFiles(self):
    mock_input_api = MockInputApi()
    mock_output_api = MockOutputApi()
    contents = ['#include <b.h>',
                '#include <a.h>']
    mock_file_cc = MockFile('something.cc', contents)
    mock_file_h = MockFile('something.h', contents)
    mock_file_other = MockFile('something.py', contents)
    mock_input_api.files = [mock_file_cc, mock_file_h, mock_file_other]
    warnings = PRESUBMIT._CheckIncludeOrder(mock_input_api, mock_output_api)
    self.assertEqual(1, len(warnings))
    self.assertEqual(2, len(warnings[0].items))
    self.assertEqual('promptOrNotify', warnings[0].type)

  def testUncheckableIncludes(self):
    mock_input_api = MockInputApi()
    contents = ['#include <windows.h>',
                '#include "b.h"',
                '#include "a.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(1, len(warnings))

    contents = ['#include "gpu/command_buffer/gles_autogen.h"',
                '#include "b.h"',
                '#include "a.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(1, len(warnings))

    contents = ['#include "gl_mock_autogen.h"',
                '#include "b.h"',
                '#include "a.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(1, len(warnings))

    contents = ['#include "ipc/some_macros.h"',
                '#include "b.h"',
                '#include "a.h"']
    mock_file = MockFile('', contents)
    warnings = PRESUBMIT._CheckIncludeOrderInFile(
        mock_input_api, mock_file, range(1, len(contents) + 1))
    self.assertEqual(1, len(warnings))

class VersionControlConflictsTest(unittest.TestCase):
  def testTypicalConflict(self):
    lines = ['<<<<<<< HEAD',
             '  base::ScopedTempDir temp_dir_;',
             '=======',
             '  ScopedTempDir temp_dir_;',
             '>>>>>>> master']
    errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
        MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
    self.assertEqual(3, len(errors))
    self.assertTrue('1' in errors[0])
    self.assertTrue('3' in errors[1])
    self.assertTrue('5' in errors[2])

class BadExtensionsTest(unittest.TestCase):
  def testBadRejFile(self):
    mock_input_api = MockInputApi()
    mock_input_api.files = [
      MockFile('some/path/foo.cc', ''),
      MockFile('some/path/foo.cc.rej', ''),
      MockFile('some/path2/bar.h.rej', ''),
    ]

    results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
    self.assertEqual(1, len(results))
    self.assertEqual(2, len(results[0].items))
    self.assertTrue('foo.cc.rej' in results[0].items[0])
    self.assertTrue('bar.h.rej' in results[0].items[1])

  def testBadOrigFile(self):
    mock_input_api = MockInputApi()
    mock_input_api.files = [
      MockFile('other/path/qux.h.orig', ''),
      MockFile('other/path/qux.h', ''),
      MockFile('other/path/qux.cc', ''),
    ]

    results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
    self.assertEqual(1, len(results))
    self.assertEqual(1, len(results[0].items))
    self.assertTrue('qux.h.orig' in results[0].items[0])

  def testGoodFiles(self):
    mock_input_api = MockInputApi()
    mock_input_api.files = [
      MockFile('other/path/qux.h', ''),
      MockFile('other/path/qux.cc', ''),
    ]
    results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
    self.assertEqual(0, len(results))

  def testOnlyOwnersFiles(self):
    mock_change = MockChange([
      'some/path/OWNERS',
      'A\Windows\Path\OWNERS',
    ])
    results = PRESUBMIT.GetPreferredTryMasters(None, mock_change)
    self.assertEqual({}, results)

class InvalidOSMacroNamesTest(unittest.TestCase):
  def testInvalidOSMacroNames(self):
    lines = ['#if defined(OS_WINDOWS)',
             ' #elif defined(OS_WINDOW)',
             ' # if defined(OS_MACOSX) || defined(OS_CHROME)',
             '# else  // defined(OS_MAC)',
             '#endif  // defined(OS_MACOS)']
    errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
        MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
    self.assertEqual(len(lines), len(errors))
    self.assertTrue(':1 OS_WINDOWS' in errors[0])
    self.assertTrue('(did you mean OS_WIN?)' in errors[0])

  def testValidOSMacroNames(self):
    lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
    errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
        MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
    self.assertEqual(0, len(errors))

class CheckAddedDepsHaveTetsApprovalsTest(unittest.TestCase):
  def testFilesToCheckForIncomingDeps(self):
    changed_lines = [
      '"+breakpad",',
      '"+chrome/installer",',
      '"+chrome/plugin/chrome_content_plugin_client.h",',
      '"+chrome/utility/chrome_content_utility_client.h",',
      '"+chromeos/chromeos_paths.h",',
      '"+components/breakpad",',
      '"+components/nacl/common",',
      '"+content/public/browser/render_process_host.h",',
      '"+jni/fooblat.h",',
      '"+grit",  # For generated headers',
      '"+grit/generated_resources.h",',
      '"+grit/",',
      '"+policy",  # For generated headers and source',
      '"+sandbox",',
      '"+tools/memory_watcher",',
      '"+third_party/lss/linux_syscall_support.h",',
    ]
    files_to_check = PRESUBMIT._FilesToCheckForIncomingDeps(re, changed_lines)
    expected = set([
      'breakpad/DEPS',
      'chrome/installer/DEPS',
      'chrome/plugin/chrome_content_plugin_client.h',
      'chrome/utility/chrome_content_utility_client.h',
      'chromeos/chromeos_paths.h',
      'components/breakpad/DEPS',
      'components/nacl/common/DEPS',
      'content/public/browser/render_process_host.h',
      'policy/DEPS',
      'sandbox/DEPS',
      'tools/memory_watcher/DEPS',
      'third_party/lss/linux_syscall_support.h',
    ])
    self.assertEqual(expected, files_to_check);

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


text:
package org.yggard.brokkgui.element;

import org.yggard.brokkgui.component.GuiNode;
import org.yggard.brokkgui.control.GuiLabeled;
import org.yggard.brokkgui.data.EOrientation;
import org.yggard.brokkgui.skin.GuiListCellSkin;
import org.yggard.brokkgui.skin.GuiSkinBase;

import fr.ourten.teabeans.binding.BaseBinding;
import fr.ourten.teabeans.value.BaseProperty;

public class GuiListCell<T> extends GuiLabeled
{
    private final GuiListView<T>        listView;

    private final BaseProperty<T>       itemProperty;
    private final BaseProperty<GuiNode> graphicProperty;

    public GuiListCell(final GuiListView<T> listView, final T item)
    {
        this.listView = listView;

        this.itemProperty = new BaseProperty<>(item, "itemProperty");
        this.graphicProperty = new BaseProperty<>(null, "graphicProperty");

        this.getWidthProperty().bind(listView.getCellWidthProperty());
        this.getHeightProperty().bind(listView.getCellHeightProperty());

        this.getxPosProperty().bind(new BaseBinding<Float>()
        {
            {
                super.bind(listView.getxPosProperty(), GuiListCell.this.getWidthProperty(),
                        listView.getOrientationProperty());
            }

            @Override
            public Float computeValue()
            {
                if (listView.getOrientation() == EOrientation.HORIZONTAL)
                    return listView.getxPos()
                            + listView.getElements().indexOf(GuiListCell.this.getItem()) * GuiListCell.this.getWidth()
                            + GuiListCell.this.getWidth() / 2;
                else
                    return listView.getxPos();
            }
        });

        this.getyPosProperty().bind(new BaseBinding<Float>()
        {
            {
                super.bind(listView.getyPosProperty(), GuiListCell.this.getHeightProperty(),
                        listView.getOrientationProperty());
            }

            @Override
            public Float computeValue()
            {
                if (listView.getOrientation() == EOrientation.VERTICAL)
                    return listView.getyPos()
                            + listView.getElements().indexOf(GuiListCell.this.getItem()) * GuiListCell.this.getHeight();
                else
                    return listView.getyPos();
            }
        });
    }

    public GuiListCell(final GuiListView<T> listView)
    {
        this(listView, null);
    }

    @Override
    protected GuiSkinBase<?> makeDefaultSkin()
    {
        return new GuiListCellSkin<>(this);
    }

    public BaseProperty<T> getItemProperty()
    {
        return this.itemProperty;
    }

    public BaseProperty<GuiNode> getGraphicProperty()
    {
        return this.graphicProperty;
    }

    public T getItem()
    {
        return this.getItemProperty().getValue();
    }

    public void setItem(final T item)
    {
        this.getItemProperty().setValue(item);
    }

    public GuiNode getGraphic()
    {
        return this.getGraphicProperty().getValue();
    }

    public void setGraphic(final GuiNode graphic)
    {
        if (this.getGraphic() != null)
        {
            this.getGraphic().setFather(null);
            this.getChildrensProperty().remove(this.getGraphic());
        }
        if (this.getGraphic() != null)
        {
            this.getGraphic().getxPosProperty().unbind();
            this.getGraphic().getyPosProperty().unbind();
            this.getGraphic().getWidthProperty().unbind();
            this.getGraphic().getHeightProperty().unbind();
        }
        this.getGraphicProperty().setValue(graphic);
        if (this.getGraphic() != null)
        {
            this.getGraphic().getxPosProperty().bind(this.getxPosProperty());
            this.getGraphic().getyPosProperty().bind(this.getyPosProperty());
            this.getGraphic().getWidthProperty().bind(this.getWidthProperty());
            this.getGraphic().getHeightProperty().bind(this.getHeightProperty());
            this.getChildrensProperty().add(graphic);
            graphic.setFather(this);
        }
    }

    public GuiListView<T> getListView()
    {
        return this.listView;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package tracer_test

import (
	"context"
	"testing"

	"github.com/altairsix/pkg/tracer"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/log"
)

func init() {
	opentracing.InitGlobalTracer(tracer.DefaultTracer)
}

func TestTracer(t *testing.T) {
	root := context.Background()

	parentSpan, parentCtx := opentracing.StartSpanFromContext(root, "op")
	defer parentSpan.Finish()

	parentSpan.SetBaggageItem("argle", "bargle")
	parentSpan.LogFields(log.String("a", "b"))

	childSpan, _ := opentracing.StartSpanFromContext(parentCtx, "op")
	defer childSpan.Finish()

	childSpan.LogFields(log.String("hello", "world"))
}

func TestSpanFromContext(t *testing.T) {
	root := context.Background()
	parentSpan, ctx := opentracing.StartSpanFromContext(root, "parent")
	parentSpan.LogFields(log.String("shared", "item"))
	parentSpan.SetBaggageItem("baggage", "true")
	defer parentSpan.Finish()

	segment := tracer.SegmentFromContext(ctx)

	segment.Info("info", log.String("hello", "world"))
}


text:
/* global define, require */
(function (root, factory) {
	'use strict';

	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['seriously'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		factory(require('seriously'));
	} else {
		if (!root.Seriously) {
			root.Seriously = { plugin: function (name, opt) { this[name] = opt; } };
		}
		factory(root.Seriously);
	}
}(window, function (Seriously) {
	'use strict';

	//particle parameters
	var minVelocity = 0.2,
		maxVelocity = 0.8,
		minSize = 0.02,
		maxSize = 0.3,
		particleCount = 20;

	Seriously.plugin('tvglitch', function () {
		var lastHeight,
			lastTime,
			particleBuffer,
			particleShader,
			particleFrameBuffer,
			gl;

		return {
			initialize: function (parent) {
				var i,
					sizeRange,
					velocityRange,
					particleVertex,
					particleFragment,
					particles;

				gl = this.gl;

				lastHeight = this.height;

				//initialize particles
				particles = [];
				sizeRange = maxSize - minSize;
				velocityRange = maxVelocity - minVelocity;
				for (i = 0; i < particleCount; i++) {
					particles.push(Math.random() * 2 - 1); //position
					particles.push(Math.random() * velocityRange + minVelocity); //velocity
					particles.push(Math.random() * sizeRange + minSize); //size
					particles.push(Math.random() * 0.2); //intensity
				}

				particleBuffer = gl.createBuffer();
				gl.bindBuffer(gl.ARRAY_BUFFER, particleBuffer);
				gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(particles), gl.STATIC_DRAW);
				particleBuffer.itemSize = 4;
				particleBuffer.numItems = particleCount;

				particleVertex = [
					'#define SHADER_NAME seriously.tvglitch.particle',
					'precision mediump float;',

					'attribute vec4 particle;',

					'uniform float time;',
					'uniform float height;',

					'varying float intensity;',

					'void main(void) {',
					'	float y = particle.x + time * particle.y;',
					'	y = fract((y + 1.0) / 2.0) * 4.0 - 2.0;',
					'	intensity = particle.w;',
					'	gl_Position = vec4(0.0, -y , 1.0, 2.0);',
					//'	gl_Position = vec4(0.0, 1.0 , 1.0, 1.0);',
					'	gl_PointSize = height * particle.z;',
					'}'
				].join('\n');

				particleFragment = [
					'#define SHADER_NAME seriously.tvglitch.particle',
					'precision mediump float;',

					'varying float intensity;',

					'void main(void) {',
					'	gl_FragColor = vec4(1.0);',
					'	gl_FragColor.a = 2.0 * intensity * (1.0 - abs(gl_PointCoord.y - 0.5));',
					'}'
				].join('\n');

				particleShader = new Seriously.util.ShaderProgram(gl, particleVertex, particleFragment);

				particleFrameBuffer = new Seriously.util.FrameBuffer(gl, 1, Math.max(1, this.height / 2));
				parent();
			},
			commonShader: true,
			shader: function (inputs, shaderSource) {
				shaderSource.fragment = [
					'precision mediump float;',

					'#define HardLight(top, bottom)  (1.0 - 2.0 * (1.0 - top) * (1.0 - bottom))',

					'varying vec2 vTexCoord;',

					'uniform sampler2D source;',
					'uniform sampler2D particles;',
					'uniform float time;',
					'uniform float scanlines;',
					'uniform float lineSync;',
					'uniform float lineHeight;', //for scanlines and distortion
					'uniform float distortion;',
					'uniform float vsync;',
					'uniform float bars;',
					'uniform float frameSharpness;',
					'uniform float frameShape;',
					'uniform float frameLimit;',
					'uniform vec4 frameColor;',

					//todo: need much better pseudo-random number generator
					Seriously.util.shader.noiseHelpers +
					Seriously.util.shader.snoise2d +

					'void main(void) {',
					'	vec2 texCoord = vTexCoord;',

						//distortion
					'	float drandom = snoise(vec2(time * 10.0, texCoord.y /lineHeight));',
					'	float distortAmount = distortion * (drandom - 0.25) * 0.5;',
						//line sync
					'	vec4 particleOffset = texture2D(particles, vec2(0.0, texCoord.y));',
					'	distortAmount -= lineSync * (2.0 * particleOffset.a - 0.5);',

					'	texCoord.x -= distortAmount;',
					'	texCoord.x = mod(texCoord.x, 1.0);',

						//vertical sync
					'	float roll;',
					'	if (vsync != 0.0) {',
					'		roll = fract(time / vsync);',
					'		texCoord.y = mod(texCoord.y - roll, 1.0);',
					'	}',

					'	vec4 pixel = texture2D(source, texCoord);',

						//horizontal bars
					'	float barsAmount = particleOffset.r;',
					'	if (barsAmount > 0.0) {',
					'		pixel = vec4(pixel.r + bars * barsAmount,' +
								'pixel.g + bars * barsAmount,' +
								'pixel.b + bars * barsAmount,' +
								'pixel.a);',
					'	}',

					'	if (mod(texCoord.y / lineHeight, 2.0) < 1.0 ) {',
					'		pixel.rgb *= (1.0 - scanlines);',
					'	}',

					'	float f = (1.0 - gl_FragCoord.x * gl_FragCoord.x) * (1.0 - gl_FragCoord.y * gl_FragCoord.y);',
					'	float frame = clamp( frameSharpness * (pow(f, frameShape) - frameLimit), 0.0, 1.0);',

					'	gl_FragColor = mix(frameColor, pixel, frame);',
					'}'
				].join('\n');

				return shaderSource;
			},
			resize: function () {
				if (particleFrameBuffer) {
					particleFrameBuffer.resize(1, Math.max(1, this.height / 2));
				}
			},
			draw: function (shader, model, uniforms, frameBuffer, parent) {
				var doParticles = (lastTime !== this.inputs.time),
					vsyncPeriod;

				if (lastHeight !== this.height) {
					lastHeight = this.height;
					doParticles = true;
				}

				//todo: make this configurable?
				uniforms.lineHeight = 1 / this.height;

				if (this.inputs.verticalSync) {
					vsyncPeriod = 0.2 / this.inputs.verticalSync;
					uniforms.vsync = vsyncPeriod;
				} else {
					vsyncPeriod = 1;
					uniforms.vsync = 0;
				}
				uniforms.time = (this.inputs.time % (1000 * vsyncPeriod));
				uniforms.distortion = Math.random() * this.inputs.distortion;

				//render particle canvas and attach uniform
				//todo: this is a good spot for parallel processing. ParallelArray maybe?
				if (doParticles && (this.inputs.lineSync || this.inputs.bars)) {
					particleShader.use();
					gl.viewport(0, 0, 1, this.height / 2);
					gl.bindFramebuffer(gl.FRAMEBUFFER, particleFrameBuffer.frameBuffer);
					gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
					gl.enableVertexAttribArray(particleShader.location.particle);
					gl.bindBuffer(gl.ARRAY_BUFFER, particleBuffer);
					gl.vertexAttribPointer(particleShader.location.particle, particleBuffer.itemSize, gl.FLOAT, false, 0, 0);
					gl.enable(gl.BLEND);
					gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
					particleShader.time.set(uniforms.time * this.inputs.barsRate);
					particleShader.height.set(this.height);
					gl.drawArrays(gl.POINTS, 0, particleCount);

					lastTime = this.inputs.time;
				}
				uniforms.particles = particleFrameBuffer.texture;

				parent(shader, model, uniforms, frameBuffer);
			},
			destroy: function () {
				particleBuffer = null;
				if (particleFrameBuffer) {
					particleFrameBuffer.destroy();
					particleFrameBuffer = null;
				}
			}
		};
	},
	{
		inPlace: false,
		inputs: {
			source: {
				type: 'image',
				uniform: 'source',
				shaderDirty: false
			},
			time: {
				type: 'number',
				defaultValue: 0
			},
			distortion: {
				type: 'number',
				defaultValue: 0.1,
				min: 0,
				max: 1
			},
			verticalSync: {
				type: 'number',
				defaultValue: 0.1,
				min: 0,
				max: 1
			},
			lineSync: {
				type: 'number',
				uniform: 'lineSync',
				defaultValue: 0.2,
				min: 0,
				max: 1
			},
			scanlines: {
				type: 'number',
				uniform: 'scanlines',
				defaultValue: 0.3,
				min: 0,
				max: 1
			},
			bars: {
				type: 'number',
				uniform: 'bars',
				defaultValue: 0,
				min: 0,
				max: 1
			},
			barsRate: {
				type: 'number',
				defaultValue: 1
			},
			frameShape: {
				type: 'number',
				uniform: 'frameShape',
				min: 0,
				max: 2,
				defaultValue: 0.27
			},
			frameLimit: {
				type: 'number',
				uniform: 'frameLimit',
				min: -1,
				max: 1,
				defaultValue: 0.34
			},
			frameSharpness: {
				type: 'number',
				uniform: 'frameSharpness',
				min: 0,
				max: 40,
				defaultValue: 8.4
			},
			frameColor: {
				type: 'color',
				uniform: 'frameColor',
				defaultValue: [0, 0, 0, 1]
			}
		},
		title: 'TV Glitch'
	});
}));


text:
<?php
/**
 * Theme Utility Functions and Template Tags
 */

/**
 * _get_singletons
 *
 * Convenience function to retrieve all php files within a directory and build the singleton
 * classname so that they can be instantiated without having to explicitly declare that the
 * singleton needs to be instantiated.
 *
 * Assumes that the filenames in $dir look like 'fname.php'. All chacters in the filename will
 * be mad lowercase and any dashes or whitespace characters in the filename will be converted
 * to '_' when building the classnames.
 *
 * @param $dir (string) the directory to scan for files
 * @param $base (string) the base name which is used to build the singleton classname
 *
 * @return (array) an array of singleton classnames
 */
function _get_singletons( $dir, $base )
{
  // make sure base is lowercase
  $base = strtolower( $base );

  // make sure that the 'settings' and 'theme' singletons come first
  $fnames = array( 'settings', 'theme' );

  // get all the files in the singleton direcotry
  if( $handle = opendir( $dir ) ) {
    while ( false !== ( $entry = readdir( $handle ) ) ) {
      if( false !== strpos( $entry, '.php' ) ) {
        $fname = str_replace( '.php', '', $entry );

        // if not already added, add it
        if( !in_array( $fname, $fnames ) )
          $fnames[] = $fname;
      }
    }
    closedir( $handle );
  }

  // turn file names into class names
  foreach( $fnames as $fn ) {
    $fn = nu_utils::clean_string($fn, 50, '_');
    $singletons[] = $base . '_' . $fn . '_singleton';
  }

  return $singletons;
}

/**
 * _include
 *
 * Based on the wordpress get_template_part function
 *
 * Include the Post-Format-specific template for the content.
 *
 * If you want to overload this in a child theme then include a file
 * called single-___.php (where ___ is the Post Format name) at the same
 * location within the child theme directory and that will be used instead.
 *
 * @uses locate_template()
 *
 * @param $name (str) The name of the template.
 * @param $format (str) The specific format of the template to retrieve.
 * @param $dir (str) The directory within the current theme folder.
 *
 * @return (str) The template filename if one is located, an empty string if not.
 */
function _include( $template, $format=false, $dir=false )
{
    // nu_debug( 'Particle Template Include', array( 'dir'=>$dir, 'format'=>$format ) );

    $template = apply_filters( 'particle_template_include', $template );

    // if not specificed set to the partials directory (relative to the theme top dir level)
    if( false === $dir )
        $dir = 'app/includes/';

    $templates = array();
    if( $format )
        $templates[] = trailingslashit( $dir ) . "$template-$format.inc";

    $templates[] = trailingslashit( $dir ) . "$template.inc";

    $located = locate_template( $templates, true, false );

    if( !$located ) {
        $msg = implode( ', ', $templates );
        echo "Failed to load the following template(s): $msg";
    }

    return $located;
}

/**
 * _include_sidebar
 *
 * Loads a sidebar template file
 *
 * @uses _include()
 */
function _include_sidebar( $name )
{
    return _include( $name, '', 'app/includes/sidebars/' );
}

/**
 * _get_page_var
 *
 * Retrieve a page level (as opposed to loop) variable. A page level variable is considered
 * anything that can be set as soon as the page loads without having to do the wordpress
 * loop
 */
function _get_page_var( $key, $echo=true )
{
    global $particle_tpl_vars;
    $val = isset( $particle_tpl_vars[ $key ] ) ? $particle_tpl_vars[ $key ] : '';
    if( $echo ) echo $val;
    else return $val;
}

function _set_page_var( $key, $val )
{
    global $particle_tpl_vars;
    $particle_tpl_vars[ $key ] = $val;
}

/**
 * _get_loop_var
 *
 * Retrieve a loop (as opposed to page) variable. A loop variable is considered
 * anything that is set when the wordpress loop runs, and changes depending on
 * the post that is currently being output
 */
function _get_loop_var( $key, $echo=true )
{
    global $particle_loop_vars;
    $val = isset( $particle_loop_vars[ $key ] ) ? $particle_loop_vars[ $key ] : '';
    if( $echo ) echo $val;
    else return $val;
}

function _set_loop_var( $key, $val )
{
    global $particle_loop_vars;
    $particle_loop_vars[ $key ] = $val;
}


text:
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Zergatul.Security.Tests.MessageDigest
{
    [TestClass]
    public class Groestl384Tests
    {
        private static SecurityProvider[] _providers = new SecurityProvider[]
        {
            new DefaultSecurityProvider()
        };

        [TestMethod]
        public void BasicTest()
        {
            foreach (var provider in _providers)
            {
                var md = provider.GetMessageDigest(MessageDigests.Groestl384);

                var digest = md.Digest();
                Assert.IsTrue(BitHelper.BytesToHex(digest) == "ac353c1095ace21439251007862d6c62f829ddbe6de4f78e68d310a9205a736d8b11d99bffe448f57a1cfa2934f044a5");
                md.Reset();

                digest = md.Digest(Encoding.ASCII.GetBytes("abc"));
                Assert.IsTrue(BitHelper.BytesToHex(digest) == "32c39f82ab41ee4fdb1582f83dde41089d47b904988b1a9a647553cb1a502cf07df7eb1e11dc3d66bec096a39a790336");
                md.Reset();

                digest = md.Digest(Encoding.ASCII.GetBytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqopqrpqrsqrstrstustuvtuvwuvwxvwxywxyzxyzayzabzabcabcdbcdecdefdefg"));
                Assert.IsTrue(BitHelper.BytesToHex(digest) == "33625fdddcc2809a83b912d70910d3b5e1408ef017c949617c5543bb835939f13484e60bfe6ff27acf225c7a4b596504");
                md.Reset();
            };
        }
    }
}


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

<title>CommandProcessor</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.thoughtworks.selenium

Interface CommandProcessor

All Known Implementing Classes:

HttpCommandProcessor, WebDriverCommandProcessor

public interface CommandProcessor

 Provides a doCommand method, which sends the command to the browser to be performed.

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
doCommand(java.lang.String command,
         java.lang.String[] args)

Send the specified remote command to the browser to be performed

boolean
getBoolean(java.lang.String string,
          java.lang.String[] strings)

boolean[]
getBooleanArray(java.lang.String string,
               java.lang.String[] strings)

java.lang.Number
getNumber(java.lang.String string,
         java.lang.String[] strings)

java.lang.Number[]
getNumberArray(java.lang.String string,
              java.lang.String[] strings)

java.lang.String
getRemoteControlServerLocation()

The URL that the RemoteControl instance is allegedly running on

java.lang.String
getString(java.lang.String string,
         java.lang.String[] strings)

java.lang.String[]
getStringArray(java.lang.String string,
              java.lang.String[] strings)

void
setExtensionJs(java.lang.String extensionJs)

Sets extension Javascript for the session

void
start()

Starts a new Selenium testing session

void
start(java.lang.Object optionsObject)

Starts a new Selenium testing session with a configuration options object

void
start(java.lang.String optionsString)

Starts a new Selenium testing session with a String, representing a configuration

void
stop()

Ends the current Selenium testing session (normally killing the browser)

Method Detail

getRemoteControlServerLocation

java.lang.String getRemoteControlServerLocation()

The URL that the RemoteControl instance is allegedly running on

Returns:

the URL

doCommand

java.lang.String doCommand(java.lang.String command,
                         java.lang.String[] args)

Send the specified remote command to the browser to be performed

Parameters:

command - - the remote command verb

args - - the arguments to the remote command (depends on the verb)

Returns:

- the command result, defined by the remote JavaScript. "getX" style commands may
         return data from the browser; other "doX" style commands may just return "OK" or an
         error message.

setExtensionJs

void setExtensionJs(java.lang.String extensionJs)

Sets extension Javascript for the session

start

void start()

Starts a new Selenium testing session

start

void start(java.lang.String optionsString)

Starts a new Selenium testing session with a String, representing a configuration

start

void start(java.lang.Object optionsObject)

Starts a new Selenium testing session with a configuration options object

stop

void stop()

Ends the current Selenium testing session (normally killing the browser)

getString

java.lang.String getString(java.lang.String string,
                         java.lang.String[] strings)

getStringArray

java.lang.String[] getStringArray(java.lang.String string,
                                java.lang.String[] strings)

getNumber

java.lang.Number getNumber(java.lang.String string,
                         java.lang.String[] strings)

getNumberArray

java.lang.Number[] getNumberArray(java.lang.String string,
                                java.lang.String[] strings)

getBoolean

boolean getBoolean(java.lang.String string,
                 java.lang.String[] strings)

getBooleanArray

boolean[] getBooleanArray(java.lang.String string,
                        java.lang.String[] strings)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
code|sub|meaning
---|:---:|---
0000|X|No code provided or unknown error


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<title>Modal Activity Indicator</title>
   <link rel="stylesheet" href="../chui/chui.android.css">

	<app>
		<view id='main' id="main" ui-navigation-status="current">
			<navbar id="segmentedToolbar">

Expander

			</navbar>
			<subview id="subview1" class="mySubView" ui-associations="withNavBar">
				<scrollpanel>

						<uibutton id='showModalActivityIndicator' ui-kind="action">
							Show Activity Indicator
						</uibutton>

				</scrollpanel>
			</subview>
		</view>
	</app>


text:
package com.peth.towerdefense;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

public class HealthBar extends Rectangle {

	// constants
	private static final float WIDTH = 15;
	private static final float HEIGHT = 1;
	private static final float YOFFSET = 15;
	private static final float BORDER_THICKNESS = 1;

	// globals
	public Enemy mParent;
	public Rectangle mHealthForeground;
	public Rectangle mHealthBackground;

	public HealthBar(Enemy parent, VertexBufferObjectManager pVertexBufferObjectManager) {
		super(parent.mCenterX - (WIDTH + BORDER_THICKNESS * 2) / 2, parent.mCenterY - YOFFSET - BORDER_THICKNESS, WIDTH + BORDER_THICKNESS * 2, HEIGHT + BORDER_THICKNESS * 2, pVertexBufferObjectManager);

		// set variables
		mParent = parent;
		setColor(0.3f, 0.3f, 0.3f);
		setZIndex(800);
		TowerDefense.mSceneManager.getCurrentLevel().attachChild(this);

		// set background
		mHealthBackground = new Rectangle(mParent.mCenterX - WIDTH / 2, mParent.mCenterY - YOFFSET, WIDTH, HEIGHT, getVertexBufferObjectManager());
		mHealthBackground.setColor(220f/255, 25f/255, 25f/255);
		mHealthBackground.setZIndex(801);
		TowerDefense.mSceneManager.getCurrentLevel().attachChild(mHealthBackground);

		// set foreground
		mHealthForeground = new Rectangle(mParent.mCenterX - WIDTH / 2, mParent.mCenterY - YOFFSET, WIDTH, HEIGHT, getVertexBufferObjectManager());
		mHealthForeground.setColor(100f/255, 220f/255, 20f/255);
		mHealthForeground.setZIndex(802);
		TowerDefense.mSceneManager.getCurrentLevel().attachChild(mHealthForeground);

	}

	public void follow() {

		setPosition(mParent.mCenterX - (WIDTH + BORDER_THICKNESS * 2) / 2, mParent.mCenterY - YOFFSET - BORDER_THICKNESS);
		mHealthBackground.setPosition(mParent.mCenterX - WIDTH / 2, mParent.mCenterY - YOFFSET);
		mHealthForeground.setPosition(mParent.mCenterX - WIDTH / 2, mParent.mCenterY - YOFFSET);

	}

	public void hide() {

		setVisible(false);
		mHealthForeground.setVisible(false);
		mHealthBackground.setVisible(false);

		setTag(TowerDefense.TAG_DETACHABLE);
		mHealthForeground.setTag(TowerDefense.TAG_DETACHABLE);
		mHealthBackground.setTag(TowerDefense.TAG_DETACHABLE);

	}

	public void update(float percentage) {

		mHealthForeground.setWidth(WIDTH * percentage);

	}

}


text:
namespace {

// Run on (12 X 3492 MHz CPUs); 2018-11-05T13:44:29.814239103-08:00
// CPU: Intel Haswell with HyperThreading (6 cores) dL1:32KB dL2:256KB dL3:15MB
// Benchmark                 Time(ns)        CPU(ns)     Iterations
// ----------------------------------------------------------------
// BM_Difference_Days              14.5           14.5     48531105
// BM_Step_Days                    12.6           12.6     54876006
// BM_Format                      587            587        1000000
// BM_Parse                       692            692        1000000
// BM_RoundTripFormatParse       1309           1309         532075
// BM_CivilYearAbslHash             0.710          0.710  976400000
// BM_CivilMonthAbslHash            1.13           1.13   619500000
// BM_CivilDayAbslHash              1.70           1.70   426000000
// BM_CivilHourAbslHash             2.45           2.45   287600000
// BM_CivilMinuteAbslHash           3.21           3.21   226200000
// BM_CivilSecondAbslHash           4.10           4.10   171800000

void BM_Difference_Days(benchmark::State& state) {
  const absl::CivilDay c(2014, 8, 22);
  const absl::CivilDay epoch(1970, 1, 1);
  while (state.KeepRunning()) {
    const absl::civil_diff_t n = c - epoch;
    benchmark::DoNotOptimize(n);
  }
}
BENCHMARK(BM_Difference_Days);

void BM_Step_Days(benchmark::State& state) {
  const absl::CivilDay kStart(2014, 8, 22);
  absl::CivilDay c = kStart;
  while (state.KeepRunning()) {
    benchmark::DoNotOptimize(++c);
  }
}
BENCHMARK(BM_Step_Days);

void BM_Format(benchmark::State& state) {
  const absl::CivilSecond c(2014, 1, 2, 3, 4, 5);
  while (state.KeepRunning()) {
    const std::string s = absl::FormatCivilTime(c);
    benchmark::DoNotOptimize(s);
  }
}
BENCHMARK(BM_Format);

void BM_Parse(benchmark::State& state) {
  const std::string f = "2014-01-02T03:04:05";
  absl::CivilSecond c;
  while (state.KeepRunning()) {
    const bool b = absl::ParseCivilTime(f, &c);
    benchmark::DoNotOptimize(b);
  }
}
BENCHMARK(BM_Parse);

void BM_RoundTripFormatParse(benchmark::State& state) {
  const absl::CivilSecond c(2014, 1, 2, 3, 4, 5);
  absl::CivilSecond out;
  while (state.KeepRunning()) {
    const bool b = absl::ParseCivilTime(absl::FormatCivilTime(c), &out);
    benchmark::DoNotOptimize(b);
  }
}
BENCHMARK(BM_RoundTripFormatParse);

template <typename T>
void BM_CivilTimeAbslHash(benchmark::State& state) {
  const int kSize = 100000;
  std::vector<T> civil_times(kSize);
  std::iota(civil_times.begin(), civil_times.end(), T(2018));

  absl::Hash<T> absl_hasher;
  while (state.KeepRunningBatch(kSize)) {
    for (const T civil_time : civil_times) {
      benchmark::DoNotOptimize(absl_hasher(civil_time));
    }
  }
}
void BM_CivilYearAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilYear>(state);
}
void BM_CivilMonthAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilMonth>(state);
}
void BM_CivilDayAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilDay>(state);
}
void BM_CivilHourAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilHour>(state);
}
void BM_CivilMinuteAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilMinute>(state);
}
void BM_CivilSecondAbslHash(benchmark::State& state) {
  BM_CivilTimeAbslHash<absl::CivilSecond>(state);
}
BENCHMARK(BM_CivilYearAbslHash);
BENCHMARK(BM_CivilMonthAbslHash);
BENCHMARK(BM_CivilDayAbslHash);
BENCHMARK(BM_CivilHourAbslHash);
BENCHMARK(BM_CivilMinuteAbslHash);
BENCHMARK(BM_CivilSecondAbslHash);

}  // namespace


text:
CQChartsTest -tcl -exec point_annotation.tcl

#CQChartsTest -ceil -exec point_annotation.cl


text:
scripts
=======

Collection of useful scripts.

- addtimestamp: Adds the file creation timestamp to a given file.
- splitmirror: Creates a lvm splitmirror clone of RHEL 6 os volumes.
- cloneremove : Removes a lvm splitmirror clone of RHEL 6 os volumes.
- snapbackup: Creates a lvm snapshot backup of RHEL 6 os volumes.
- snapremove: Removes a lvm snapshot backup of RHEL 6 os volumes.
- snaprestore: Restores a previously taken lvm snapshot backup of RHEL 6 os volumes.
- uips.py: Script checks ips whether they may be removed from DNS.
- mkbond.sh: Script that creates bonded network interfaces on RHEL5/RHEL6


text:
#ifndef WEBDRIVER_IE_CLICKELEMENTCOMMANDHANDLER_H_
#define WEBDRIVER_IE_CLICKELEMENTCOMMANDHANDLER_H_

#include "../Generated/atoms.h"
#include "../Browser.h"
#include "../IECommandHandler.h"
#include "../IECommandExecutor.h"
#include "logging.h"

namespace webdriver {

class ClickElementCommandHandler : public IECommandHandler {
 public:
  ClickElementCommandHandler(void) {
  }

  virtual ~ClickElementCommandHandler(void) {
  }

 protected:
  void ExecuteInternal(const IECommandExecutor& executor,
                       const LocatorMap& locator_parameters,
                       const ParametersMap& command_parameters,
                       Response* response) {
    LocatorMap::const_iterator id_parameter_iterator = locator_parameters.find("id");
    if (id_parameter_iterator == locator_parameters.end()) {
      response->SetErrorResponse(400, "Missing parameter in URL: id");
      return;
    } else {
      int status_code = SUCCESS;
      std::string element_id = id_parameter_iterator->second;

      BrowserHandle browser_wrapper;
      status_code = executor.GetCurrentBrowser(&browser_wrapper);
      if (status_code != SUCCESS) {
        response->SetErrorResponse(status_code, "Unable to get browser");
        return;
      }

      ElementHandle element_wrapper;
      status_code = this->GetElement(executor, element_id, &element_wrapper);
      if (status_code == SUCCESS) {
        if (executor.enable_native_events()) {
          if (IsOptionElement(element_wrapper)) {
            this->ClickOption(browser_wrapper, element_wrapper, response);
            return;
          } else {
            status_code = element_wrapper->Click(executor.scroll_behavior());
            browser_wrapper->set_wait_required(true);
            if (status_code != SUCCESS) {
              if (status_code == EELEMENTCLICKPOINTNOTSCROLLED) {
                // We hard-code the error code here to be "Element not visible"
                // to maintain compatibility with previous behavior.
                response->SetErrorResponse(EELEMENTNOTDISPLAYED, "The point at which the driver is attempting to click on the element was not scrolled into the viewport.");
              } else {
                response->SetErrorResponse(status_code, "Cannot click on element");
              }
              return;
            }
          }
        } else {
          std::wstring script_source = L"(function() { return function(){" +
                                       atoms::asString(atoms::INPUTS) +
                                       L"; return webdriver.atoms.inputs.click(arguments[0], arguments[1]);" +
                                       L"};})();";

          CComPtr<IHTMLDocument2> doc;
          browser_wrapper->GetDocument(&doc);
          Script script_wrapper(doc, script_source, 2);
          script_wrapper.AddArgument(element_wrapper);
          script_wrapper.AddArgument(executor.mouse_state());
          status_code = script_wrapper.Execute();
          if (status_code != SUCCESS) {
            // This is a hack. We should change this when we can get proper error
            // codes back from the atoms. We'll assume the script failed because
            // the element isn't visible.
            response->SetErrorResponse(EELEMENTNOTDISPLAYED,
                "Received a JavaScript error attempting to click on the element using synthetic events. We are assuming this is because the element isn't displayed, but it may be due to other problems with executing JavaScript.");
            return;
          } else {
            IECommandExecutor& mutable_executor = const_cast<IECommandExecutor&>(executor);
            mutable_executor.set_mouse_state(script_wrapper.result());
          }
        }
      } else {
        response->SetErrorResponse(status_code, "Element is no longer valid");
        return;
      }

      response->SetSuccessResponse(Json::Value::null);
    }
  }

 private:
  bool IsOptionElement(ElementHandle element_wrapper) {
    CComQIPtr<IHTMLOptionElement> option(element_wrapper->element());
    return option != NULL;
  }

  void ClickOption(BrowserHandle browser_wrapper,
                   ElementHandle element_wrapper,
                   Response* response) {
    int status_code = SUCCESS;
    CComPtr<IHTMLDocument2> doc;
    browser_wrapper->GetDocument(&doc);

    // The atom is just the definition of an anonymous
    // function: "function() {...}"; Wrap it in another function so we can
    // invoke it with our arguments without polluting the current namespace.
    std::wstring script_source = L"(function() { return (";
    script_source += atoms::asString(atoms::CLICK);
    script_source += L")})();";

    Script script_wrapper(doc, script_source, 1);
    script_wrapper.AddArgument(element_wrapper);
    status_code = script_wrapper.Execute();
    if (status_code != SUCCESS) {
      response->SetErrorResponse(status_code,
                                 "An error occurred executing the click atom");
      return;
    }

    // Require a short sleep here to let the browser update the DOM.
    ::Sleep(100);
    response->SetSuccessResponse(Json::Value::null);
  }
};

} // namespace webdriver

#endif // WEBDRIVER_IE_CLICKELEMENTCOMMANDHANDLER_H_


text:
classdef TrajectoryLibraryGenerator

    properties (SetAccess = private)
        cyclicIdx
        nonCyclicIdx
        robot
        trajLength
    end

    methods (Abstract)
        trajLib = generateTrajectories(obj);
    end

    methods
        function obj = TrajectoryLibraryGenerator(robot)
            obj.robot = robot;
        end

        function obj = setCyclicCoordinateIndexes(obj, cyclicIdx)
            obj.cyclicIdx = cyclicIdx;
            obj.nonCyclicIdx = setdiff(1:numel(obj.robot.getStateFrame.coordinates), cyclicIdx);
        end

        function obj = setTrajectoryLength(obj, trajLength)
            obj.trajLength = trajLength;
        end
    end
end


text:
package org.apache.cassandra.distributed.test;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import org.apache.cassandra.distributed.test.DistributedRepairUtils.RepairParallelism;
import org.apache.cassandra.distributed.test.DistributedRepairUtils.RepairType;

@RunWith(Parameterized.class)
public class IncrementalRepairCoordinatorFastTest extends RepairCoordinatorFast
{
    public IncrementalRepairCoordinatorFastTest(RepairParallelism parallelism, boolean withNotifications)
    {
        super(RepairType.INCREMENTAL, parallelism, withNotifications);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.UI;
using RemoteControl.Models;
using IoTHelpers.Gpio.Modules;
using IoTHelpers.Boards;
using Microsoft.Azure.Devices.Client;
using Windows.Devices.Geolocation;
using Newtonsoft.Json;
using System.Text;

namespace RemoteControl
{
    public sealed partial class MainPage : Page
    {
        private readonly MulticolorLed led;
        private readonly Dht11HumitureSensor humitureSensor;
        private readonly Relay relay;
        private readonly Sr501PirMotionDetector motionDetector;
        private readonly MetalTouchSensor metalTouchSensor;
        private readonly FlameSensor flameSensor;

        private readonly RemoteConnection connection;
        private readonly DispatcherTimer timer;

        private static DeviceClient deviceClient;

        private const string deviceName = "MARCO-RPI2-02";
        private const string iotHubUri = "marcominervaiothub.azure-devices.net";
        private const string deviceKey = "QnSfmX9WneWnCDOn1hYwNIpFhan2ex3PU5VNdetV9n0=";

        private Geolocator geolocator;
        private Geocoordinate position;

        private bool detectMovement;
        private bool detectTouch;
        private bool detectFlame;

        public MainPage()
        {
            InitializeComponent();
            Unloaded += MainPage_Unloaded;

            //Window.Current.CoreWindow.PointerCursor = null;

            connection = new RemoteConnection();
            connection.OnLedEvent(LedEvent);

            led = new MulticolorLed(redPinNumber: 18, greenPinNumber: 23, bluePinNumber: 25);

            humitureSensor = new Dht11HumitureSensor(pinNumber: 4);
            humitureSensor.RaiseEventsOnUIThread = true;
            humitureSensor.ReadingChanged += HumitureSensor_ReadingChanged;

            relay = new Relay(pinNumber: 16);

            motionDetector = new Sr501PirMotionDetector(pinNumber: 12);
            motionDetector.RaiseEventsOnUIThread = true;
            motionDetector.MotionDetected += MotionDetector_MotionDetected;
            motionDetector.MotionStopped += MotionDetector_MotionStopped;

            metalTouchSensor = new MetalTouchSensor(pinNumber: 5);
            metalTouchSensor.RaiseEventsOnUIThread = true;
            metalTouchSensor.TouchDetected += MetalTouchSensor_TouchDetected;
            metalTouchSensor.TouchRemoved += MetalTouchSensor_TouchRemoved;

            flameSensor = new FlameSensor(pinNumber: 26);
            flameSensor.RaiseEventsOnUIThread = true;
            flameSensor.FlameDetected += FlameSensor_FlameDetected;
            flameSensor.FlameExtinguished += FlameSensor_FlameExtinguished;

            timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, object e)
        {
            this.SendHumiture();

            var temperature = humitureSensor.CurrentTemperature.GetValueOrDefault();
            var humidity = humitureSensor.CurrentHumidity.GetValueOrDefault();

            SendDeviceToCloudMessagesAsync(temperature, humidity, 0);
        }

        private void HumitureSensor_ReadingChanged(object sender, EventArgs e)
            => SendHumiture();

        private void SendHumiture()
        {
            var temperature = humitureSensor.CurrentTemperature.GetValueOrDefault();
            var humidity = humitureSensor.CurrentHumidity.GetValueOrDefault();

            temperatureTextBox.Text = $"{temperature}° C";
            humidityTextBox.Text = $"{humidity}%";

            connection.SendHumiture(humidity, temperature);

            AddEvents("Temperature and humidity sent to Azure");
        }

        private async void SendDeviceToCloudMessagesAsync(double temperature, double humidity, double lightLevel)
        {
            if (deviceClient == null || position == null)
                return;

            AddEvents("Sending telemetry data...");

            try
            {
                var telemetryDataPoint = new TelemetryData
                {
                    DeviceId = deviceName,
                    Temperature = Math.Round(temperature, 6),
                    Humidity = Math.Round(humidity, 6),
                    LightLevel = Math.Round(lightLevel, 6),
                    Position = new Position
                    {
                        Latitude = position.Point.Position.Latitude,
                        Longitude = position.Point.Position.Longitude,
                        Accuracy = position.Accuracy,
                        Timestamp = position.Timestamp
                    }
                };

                var messageString = JsonConvert.SerializeObject(telemetryDataPoint, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                var message = new Message(Encoding.ASCII.GetBytes(messageString));

                await deviceClient.SendEventAsync(message);

                AddEvents("Telemetry data successfully sent.");
            }
            catch (Exception ex)
            {
                AddEvents($"An error occured while sending data: {ex.Message}");
            }
        }

        private void relaySwitch_Toggled(object sender, RoutedEventArgs e)
            => relay.IsOn = relaySwitch.IsOn;

        private void motionDetectorSwitch_Toggled(object sender, RoutedEventArgs e)
            => detectMovement = motionDetectorSwitch.IsOn;

        private void touchSensorSwitch_Toggled(object sender, RoutedEventArgs e)
            => detectTouch = touchSensorSwitch.IsOn;

        private void flameSensorSwitch_Toggled(object sender, RoutedEventArgs e)
            => detectFlame = flameSensorSwitch.IsOn;

        private void MotionDetector_MotionDetected(object sender, EventArgs e)
        {
            AddEvents("Motion detected");

            if (detectMovement)
            {
                led.TurnRed();
                alarm.Play();
            }
        }

        private void MotionDetector_MotionStopped(object sender, EventArgs e)
        {
            AddEvents("Motion stopped");

            if (detectMovement)
            {
                led.TurnOff();
                alarm.Stop();
            }
        }

        private void MetalTouchSensor_TouchDetected(object sender, EventArgs e)
        {
            AddEvents("Touch detected");

            if (detectTouch)
            {
                alarm.Play();
                led.TurnRed();
            }
        }

        private void MetalTouchSensor_TouchRemoved(object sender, EventArgs e)
        {
            AddEvents("Touch removed");

            if (detectTouch)
            {
                led.TurnOff();
                alarm.Stop();
            }
        }

        private void FlameSensor_FlameDetected(object sender, EventArgs e)
        {
            AddEvents("Flame detected");

            if (detectFlame)
            {
                alarm.Play();
                led.TurnRed();
            }
        }

        private void FlameSensor_FlameExtinguished(object sender, EventArgs e)
        {
            AddEvents("Flame extinguished");

            if (detectFlame)
            {
                led.TurnOff();
                alarm.Stop();
            }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            await connection.ConnectAsync();

            var board = RaspberryPi2Board.GetDefault();
            if (board != null)
            {
                board.PowerLed.TurnOff();
                board.StatusLed.TurnOn();
            }

            if (!string.IsNullOrWhiteSpace(deviceName) && !string.IsNullOrWhiteSpace(deviceKey))
            {
                geolocator = new Geolocator();
                geolocator.PositionChanged += OnPositionChanged;

                deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceName, deviceKey),
                    TransportType.Http1);
            }

            timer.Start();
            base.OnNavigatedTo(e);
        }

        private void LedEvent(Rgb rgb)
        {
            AddEvents("Received Led Event from Azure.");

            led.Red = rgb.Red;
            led.Green = rgb.Green;
            led.Blue = rgb.Blue;
        }

        private void AddEvents(string message)
        {
            var dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));
            eventListBox.Items.Insert(0, $"[{dateTime}] {message}");
        }

        private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e)
        {
            position = e.Position.Coordinate;
        }

        private void MainPage_Unloaded(object sender, object args)
        {
            // Cleanup
            if (timer != null)
            {
                timer.Tick -= Timer_Tick;
                timer.Stop();
            }

            connection?.Dispose();

            if (deviceClient != null)
            {
                geolocator.PositionChanged -= OnPositionChanged;
                geolocator = null;
                deviceClient = null;
            }

            led?.Dispose();
            relay?.Dispose();

            if (humitureSensor != null)
            {
                humitureSensor.ReadingChanged -= HumitureSensor_ReadingChanged;
                humitureSensor.Dispose();
            }

            if (motionDetector != null)
            {
                motionDetector.MotionDetected -= MotionDetector_MotionDetected;
                motionDetector.MotionStopped -= MotionDetector_MotionStopped;
                motionDetector.Dispose();
            }

            if (metalTouchSensor != null)
            {
                metalTouchSensor.TouchDetected -= MetalTouchSensor_TouchRemoved;
                metalTouchSensor.TouchRemoved -= MetalTouchSensor_TouchDetected;
                metalTouchSensor.Dispose();
            }

            if (flameSensor != null)
            {
                flameSensor.FlameDetected -= FlameSensor_FlameDetected;
                flameSensor.FlameDetected -= FlameSensor_FlameExtinguished;
                flameSensor.Dispose();
            }
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace O365_UWP_Unified_API_Snippets
{
    class OrganizationSnippets
    {
        const string serviceEndpoint = "https://graph.microsoft.com/v1.0/";

        // Returns all of the contacts in your tenant's directory.
        // Returns all of the drives in your tenant's directory.
        public static async Task<List<string>> GetDrivesAsync()
        {
            var drives = new List<string>();
            JObject jResult = null;

            try
            {
                HttpClient client = new HttpClient();
                var token = await AuthenticationHelper.GetTokenForUserAsync();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                // Endpoint for all contacts in your organization
                Uri contactsEndpoint = new Uri(serviceEndpoint + "myOrganization/drives");

                HttpResponseMessage response = await client.GetAsync(contactsEndpoint);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    jResult = JObject.Parse(responseContent);

                    foreach (JObject contact in jResult["value"])
                    {
                        string driveId = (string)contact["Id"];
                        drives.Add(driveId);
                        Debug.WriteLine("Got contact: " + driveId);
                    }
                }

                else
                {
                    Debug.WriteLine("We could not get drives. The request returned this status code: " + response.StatusCode);
                    return null;
                }

                return drives;

            }

            catch (Exception e)
            {
                Debug.WriteLine("We could not get drives: " + e.Message);
                return null;
            }
        }

    }
}
//*********************************************************
//
//O365-UWP-Microsoft-Graph-Snippets, https://github.com/OfficeDev/O365-UWP-Microsoft-Graph-Snippets
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************


text:
<?xml version="1.0" encoding="UTF-8"?>
<javaee:handler-chains
     xmlns:javaee="http://java.sun.com/xml/ns/javaee"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <javaee:handler-chain>
    <javaee:handler>
      <javaee:handler-class>it.polito.dp2.FDS.sol4.server.ValidationHandler</javaee:handler-class>
    </javaee:handler>
  </javaee:handler-chain>
</javaee:handler-chains>


text:
DOM.Ready(function(){
  if (!DOM.Exists('.content-editable-toolbar')) {
    return
  }

    // Activate editable content
  Editable.Activate('.content-editable-toolbar');
});

var Editable = (function() {
return {
  // Activate editable elements with selector s
  Activate:function(s) {
    if (!DOM.Exists(s)) {
      return;
    }

    DOM.Each('.content-editable-toolbar',function(toolbar){
        // Store associated elements for access later
        toolbar.buttons = toolbar.querySelectorAll('a');
        var dataEditable = toolbar.getAttribute('data-editable');
        toolbar.editable = DOM.First(DOM.Format("#{0}-editable",dataEditable));
        toolbar.textarea = DOM.First(DOM.Format("#{0}-textarea",dataEditable));

        if (toolbar.editable === undefined) {
          toolbar.editable = DOM.Nearest(toolbar,'.content-editable')[0];
        }
        if (toolbar.textarea === undefined) {
          toolbar.textarea = DOM.Nearest(toolbar,'.content-textarea')[0];
        }

        // Set textarea to hidden initially
        toolbar.textarea.style.display = 'none';

        // Listen to a form submit, and call updateContent to make sure
        // our textarea in the form is up to date with the latest content
        toolbar.textarea.form.addEventListener('submit', function(e) {
            Editable.updateContent(toolbar.editable,toolbar.textarea,false);
            return false;
        });

        // Intercept paste on editable and remove complex html before it is pasted in
        toolbar.editable.addEventListener('input', function(e) {
          Editable.cleanHTMLElements(this);
        });

        // Listen to button clicks within the toolbar
        DOM.ForEach(toolbar.buttons,function(el,i){
          el.addEventListener('click', function(e) {
            var cmd = this.id;
            var insert = "";

             switch (cmd){
             case "showCode":
                 Editable.updateContent(toolbar.editable,toolbar.textarea,true);
             break;
             case "createLink":
                 insert = prompt("Supply the web URL to link to");
                 // Prefix url with http:// if no scheme supplied
                 if (insert.indexOf('http') !== 0) {
                     insert = "http://" + insert;
                 }
             break;
             case "formatblock":
                 insert = this.getAttribute('data-format');
             break;
             default:
             break;
             }

            if (cmd.length > 0) {
                 document.execCommand(cmd,false,insert);
            }

            // Find and remove evil html created by browsers
            var sel = Editable.getSelectionParentElement();

            if (sel !== null) {
               // Clean align stuff
               Editable.cleanAlign(cmd,sel);
               Editable.cleanHTMLElements(sel);
               sel.removeAttribute('style');
            }

            return false;
          });
        });
    });
  },// End activate

  // cleanAlign
  cleanAlign:function(cmd,el) {

    switch (cmd){
     case "justifyCenter":

         if (sel.hasClass('align-center')) {
             sel.removeClass('align-center');
         } else {
             sel.addClass('align-center');
         }

         sel.removeClass('align-left').removeClass('align-right');
         sel.removeAttr('style');
     break;
     case "justifyLeft":
         if (sel.hasClass('align-left')) {
             sel.removeClass('align-left');
         } else {
             sel.addClass('align-left');
         }

         sel.removeClass('align-center').removeClass('align-right');
         sel.removeAttribute('style');

     break;
     case "justifyRight":

         if (sel.hasClass('align-right')) {
             sel.removeClass('align-right');
         } else {
             sel.addClass('align-right');
         }

         sel.removeClass('align-center').removeClass('align-left');
         sel.removeAttribute('style');
     break;
     }
  },

  // CleanHTML is used to clean the html content from the contenteditable before it is assigned to the textarea
  cleanHTML:function(html) {
    html = html.replace(/<\/?span>/gi,'');// Remove all empty span tags
    html = html.replace(/<\/?font [^>]*>/gi,'');// Remove ALL font tags
    html = html.replace(/ </gi,' <');// this is sometimes required, be careful
    html = html.replace(/
<\/p>/gi,'\n');// pretty format but remove empty paras
    html = html.replace(/
<\/li>/gi,'<\/li>');

    // Remove comments and other MS cruft
    html = html.replace(//gi,'');
    html = html.replace(/ class\=\"MsoNormal\"/gi,'');
    html = html.replace(/
<o:p> <\/o:p><\/p>/gi,'');

    // Pretty printing elements which follow on from one another
    html = html.replace(/><(li|ul|ol|p|h\d|\/ul|\/ol)>/gi,'>\n<$1>');

    return html;
  },

  // cleanHTMLElements removes certain attributes which are usually full of junk (style, color etc)
  cleanHTMLElements:function(el) {
    // Browsers tend to use style attributes to add all sorts of awful stuff to the html
    // No inline styles allowed
    DOM.ForEach(el.querySelectorAll('p, div, b, i, h1, h2, h3, h4, h5, h6'),function(e){e.removeAttribute('style');});
    DOM.ForEach(el.querySelectorAll('span'),function(e){e.removeAttribute('style');e.removeAttribute('lang');});
    DOM.ForEach(el.querySelectorAll('font'),function(e){e.removeAttribute('color');});
  },

  // If textarea visible update the content editable with new html
  // else update the textarea with new content editable html
  updateContent:function(editable,textarea,toggle) {
      var html = '';
      if (textarea.style.display !== 'none') {
          html = textarea.value;
          editable.innerHTML = html;
          if (toggle){
              editable.style.display = '';
              textarea.style.display = 'none';
          }
      } else {
          html = editable.innerHTML;
          // Cleanup the html by removing plain spans
          html = Editable.cleanHTML(html);
          textarea.value = html;
          if (toggle){
              editable.style.display = 'none';
              textarea.style.display = '';
          }
      }

  },

  // The closest parent element which encloses the entire text selection
  getSelectionParentElement:function() {
      var p = null, sel;
      if (window.getSelection) {
          sel = window.getSelection();
          if (sel.rangeCount) {
              p = sel.getRangeAt(0).commonAncestorContainer;
              if (p.nodeType != 1) {
                  p = p.parentNode;
              }
          }
      } else if ( (sel = document.selection) && sel.type != "Control") {
          p = sel.createRange().parentElement();
      }
      return p;
  }

  };
}());


text:
package org.ovirt.engine.core.common.action;

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

import org.ovirt.engine.core.compat.Guid;

public class VmHostDevicesParameters extends VmOperationParameterBase {

    private List<String> deviceNames;

    public VmHostDevicesParameters(Guid vmId, List<String> deviceNames) {
        super(vmId);
        this.deviceNames = deviceNames;
    }

    public VmHostDevicesParameters(Guid vmId, String... deviceNames) {
        this(vmId, Arrays.asList(deviceNames));
    }

    public VmHostDevicesParameters() {
        this(Guid.Empty, Collections.<String>emptyList());
    }

    public List<String> getDeviceNames() {
        return deviceNames;
    }

    public void setDeviceNames(List<String> deviceNames) {
        this.deviceNames = deviceNames;
    }
}


text:
namespace dxshoot {

Shot::Shot(Vector2 pos, float s, float a)
	: Character("bullet_test.png")
{
	position = pos;
	velocity = Vector2::polar(s, a);
	collisionRect = Vector2(16.0f, 16.0f);
}

Shot::~Shot()
{
	Character::~Character();
}

void Shot::update()
{
	position += velocity;
}

bool Shot::canDelete()
{
	return !PlayEngine::getInstance().getPlayArea().isCollision(Rectangle(position, collisionRect));
}

}


text:
package com.foc.saas.manager;

import java.sql.Date;

import com.foc.Globals;
import com.foc.admin.FocUser;
import com.foc.desc.FocConstructor;
import com.foc.desc.FocObject;
import com.foc.list.FocList;
import com.foc.property.FProperty;

@SuppressWarnings("serial")
public class SaaSConfig extends FocObject {

	private SaaSApplicationAdaptor saasApplicationAdaptor = null;

	public SaaSConfig(FocConstructor constr) {
    super(constr);
    newFocProperties();
  }

  public void dispose(){
  	super.dispose();
  	if(saasApplicationAdaptor != null){
  		saasApplicationAdaptor.dispose();
  		saasApplicationAdaptor = null;
  	}
  }

	public int getPlan(){
  	return getPropertyInteger(SaaSConfigDesc.FLD_PLAN);
  }

  public void setPlan(int plan){
  	setPropertyInteger(SaaSConfigDesc.FLD_PLAN, plan);
  }

  public void setPlan(String plan){
  	setPropertyString(SaaSConfigDesc.FLD_PLAN, plan);
  }

  public int getApplicationType(){
  	return getPropertyInteger(SaaSConfigDesc.FLD_APPLICATION_TYPE);
  }

  public void setApplicationType(String applicationType){
  	FProperty prop = getFocProperty(SaaSConfigDesc.FLD_APPLICATION_TYPE);
  	if(prop != null){
  		prop.setString(applicationType);
  	}
  }

  public void setApplicationType(int applicationType){
  	setPropertyInteger(SaaSConfigDesc.FLD_APPLICATION_TYPE, applicationType);
  }

  public void setRenewedUntilDate(Date renewedUntilDate){
    setPropertyDate(SaaSConfigDesc.FLD_RENEWED_UNTIL, renewedUntilDate);
  }

  public Date getRenewedUntilDate(){
    return getPropertyDate(SaaSConfigDesc.FLD_RENEWED_UNTIL);
  }

  public static SaaSConfig getInstance(){
  	return Globals.getApp().getSaaSConfig();
  }

  public static SaaSConfig loadInstance(){
  	SaaSConfig appConfig = null;

    FocList appConfigList = SaaSConfigDesc.getList(FocList.LOAD_IF_NEEDED);
    if(appConfigList.size() > 0){
    	appConfig = (SaaSConfig) appConfigList.getFocObject(0);
    }

    if(appConfig == null){
    	appConfig = (SaaSConfig) appConfigList.newEmptyItem();
    	appConfigList.add(appConfig);
    	appConfig.validate(true);
    }

  	return appConfig;
  }

	public SaaSApplicationAdaptor getSaasApplicationAdaptor() {
		return saasApplicationAdaptor;
	}

	public void setSaasApplicationAdaptor(SaaSApplicationAdaptor saasApplicationAdaptor) {
		this.saasApplicationAdaptor = saasApplicationAdaptor;
	}

  public void adaptUserRights(){
  	if(getSaasApplicationAdaptor() != null) getSaasApplicationAdaptor().adaptUserRights();
  }

  public void adaptUserRights(FocUser user){
  	if(getSaasApplicationAdaptor() != null) getSaasApplicationAdaptor().adaptUserRights(user);
  }

  public static boolean isFreePlanUser(){
  	SaaSConfig saaSConfig = SaaSConfig.getInstance();
		return saaSConfig != null && saaSConfig.getPlan() == SaaSConfigDesc.PLAN_FREE;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Debaryomyces hominis Todd & E.A. Herrm.

### Remarks
null


text:
import tempfile
import subprocess
import os
import logging
import array
import numpy as np
import time

import caffe

from players import DistributionBot, DistWrappingMaxPlayer
import cubes
from state import gomill_gamestate2state, State

class DetlefDistBot(DistributionBot):
    """
    CNN as kindly provided by Detlef Schmicker. See
    http://computer-go.org/pipermail/computer-go/2015-December/008324.html

    The net should (as of January 2016) be available here:
    http://physik.de/CNNlast.tar.gz

    """
    def __init__(self, caffe_net):
        super(DetlefDistBot,  self).__init__()
        self.caffe_net = caffe_net

    def gen_probdist_raw(self, game_state, player):
        cube = cubes.get_cube_detlef(gomill_gamestate2state(game_state), player)
        cube = cube.reshape( (1,) + cube.shape)

        logging.debug("%s sending data of shape=%s"%(self, cube.shape))

        resp = self.caffe_net.forward_all(**{'data':cube})['ip']
        logging.debug("%s read response of shape=%s"%(self, resp.shape))

        # FIXME update, 128 output channels is detlef's mistake :-)
        resp = resp.reshape((128, game_state.board.side, game_state.board.side))
        tot = resp.sum()
        ret = resp[0]
        logging.debug("%s trimming channelstook off %.3f %%"%(self,
                                                                100 * (tot - ret.sum())/tot))

        return ret / ret.sum()

if __name__ == "__main__":
    def test_bot():
        import gomill
        import rank

        logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                            level=logging.DEBUG)

        # substitute with your own
        caffe_net = caffe.Net('golast19.prototxt', 'golast.trained', 0)

        player = DistWrappingMaxPlayer(DetlefDistBot(caffe_net))

        class GameState:
            pass
        s = GameState()
        s.board = gomill.boards.Board(19)
        s.ko_point = None
        s.move_history = []

        print player.genmove(s, 'b').move

    test_bot()


text:
<?php

namespace Github\Api;

@trigger_error('The '.__NAMESPACE__.'\Integrations class is deprecated. Use the '.__NAMESPACE__.'\Apps class instead.', E_USER_DEPRECATED);

/**
 * @deprecated Use the Apps class
 * @link   https://developer.github.com/v3/apps/
 *
 * @author Nils Adermann <naderman@naderman.de>
 */
class Integrations extends Apps
{
    /**
     * @deprecated
     * Configure the accept header for Early Access to the integrations api (DEPRECATED)
     * @see https://developer.github.com/v3/apps/
     *
     * @return self
     */
    public function configure()
    {
        return $this;
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!--
  This update manifest points to the good_v1.crx file. It is meant to be used
  with a URLRequestMockHTTPJob, and the hostname must be kept in sync.
-->
<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>
  <app appid='ldnnhddmnhbkjipkidpdiheffobcpfmf'>
    <updatecheck codebase='http://mock.http/extensions/good_v1.crx'
                 version='1.0.0.0' />
   </app>
</gupdate>


text:
function query = parseContent(content, character)
% Utility function.
%
% Parses the query string and produce a cell array of cell arrays.
% This function is called from several functions in the toolbox.
%
% It is case sensitive.
%

if nargin == 1
    character = ',';
end

query = {};
ndx = [0 findstr(content, character) length(content)+1];
for n=1:length(ndx)-1
    element = content(ndx(n)+1:ndx(n+1)-1);
    if element(1)~='+' & element(1)~='-'
        element = ['+' element];
    end

    %clear term;
    ndxQ = sort([findstr(element, '+') findstr(element, '-') length(element)+1]);
    for m=1:length(ndxQ)-1
        if element(ndxQ(m))
            %term{m} = lower(element(ndxQ(m):ndxQ(m+1)-1));
            %term{m} = element(ndxQ(m):ndxQ(m+1)-1);
            query{n}{m} = element(ndxQ(m):ndxQ(m+1)-1);
        end
        %query{n} = term;
    end
end


text:
module Azure::ApiManagement::Mgmt::V2016_10_10
  module Models
    #
    # Defines values for IdentityProviderNameType
    #
    module IdentityProviderNameType
      Facebook = "facebook"
      Google = "google"
      Microsoft = "microsoft"
      Twitter = "twitter"
      Aad = "aad"
      AadB2C = "aadB2C"
    end
  end
end


text:
namespace Gek
{
	namespace FileSystem
	{
		struct Path
		{
        private:
            std::experimental::filesystem::path data;

        private:
            Path(std::experimental::filesystem::path const &path);

        public:
			Path(void);
            Path(std::string_view path);
            Path(std::string const &path);
			Path(Path const &path);

            void operator = (std::string_view path);
            void operator = (std::string const &path);
			void operator = (Path const &path);

            Path &removeFileName(void);
            Path &removeExtension(void);

			Path &replaceFileName(std::string_view fileName);
            Path &replaceExtension(std::string_view extension);

			Path withExtension(std::string_view extension) const;
			Path withoutExtension() const;

			Path getParentPath(void) const;
			std::string getFileName(void) const;
			std::string getExtension(void) const;
            std::string getString(void) const;
            std::wstring getWindowsString(void) const;

            void rename(Path const &name) const;
            bool isNewerThan(Path const &path) const;

			bool isFile(void) const;
            size_t getFileSize(void) const;

			bool isDirectory(void) const;
            void createChain(void) const;
            void findFiles(std::function<bool(Path const &filePath)> onFileFound) const;
        };

        struct File
            : public Path
        {
        };

		Path GetModuleFilePath(void);

        template <typename... PARAMETERS>
        Path CombinePaths(PARAMETERS const & ... nameList)
        {
            return String::Join({ nameList... }, static_cast<char>(std::experimental::filesystem::path::preferred_separator));
        }

        template <typename... PARAMETERS>
        Path CombinePaths(Path const &rootDirectory, PARAMETERS const &... nameList)
        {
            return String::Join({ rootDirectory.getString(), nameList... }, static_cast<char>(std::experimental::filesystem::path::preferred_separator));
        }

        template <typename CONTAINER>
		CONTAINER Load(Path const &filePath, CONTAINER const &defaultValue = CONTAINER(), std::uintmax_t limitReadSize = 0)
		{
			if (filePath.isFile())
			{
				CONTAINER buffer;
                std::uintmax_t fileSize = filePath.getFileSize();
                auto size = (limitReadSize == 0 ? fileSize : std::min(fileSize, limitReadSize));
				if (size > 0)
				{
					// Need to use fopen since STL methods break up the reads to multiple small calls
                    FILE *file = nullptr;
                    _wfopen_s(&file, filePath.getWindowsString().data(), L"rb");
					if (file != nullptr)
					{
						buffer.resize(size);
						auto numberOfSegmentsRead = fread(static_cast<void *>(&buffer.front()), size, 1, file);
						fclose(file);

						if (numberOfSegmentsRead == 1)
						{
							return buffer;
						}
					}
				}
			}

			return defaultValue;
		}

		template <typename CONTAINER>
		void Save(Path const &filePath, CONTAINER const &buffer)
		{
            filePath.getParentPath().createChain();

            FILE *file = nullptr;
            _wfopen_s(&file, filePath.getWindowsString().data(), L"wb");
            if (file != nullptr)
			{
				auto numberOfSegmentsWritten = fwrite(buffer.data(), buffer.size(), 1, file);
				fclose(file);
			}
		}
	}; // namespace File
}; // namespace Gek

namespace std
{
    inline std::string to_string(Gek::FileSystem::Path const &path)
    {
        return path.getString();
    }
};


text:
Ugoira
======

Ugoira is a tool for downloading Pixiv Ugoira.

Pixiv Ugoira is **Ugoku** (Animated) Illustration.

.. toctree::
   :maxdepth: 2

   install
   usage
   api
   changelog


text:
require 'builder'

class CASino::TicketValidationResponseBuilder
  attr_reader :success, :options

  def initialize(success, options)
    @success = success
    @options = options
  end

  def build
    xml = Builder::XmlMarkup.new(indent: 2)
    xml.cas :serviceResponse, 'xmlns:cas' => 'http://www.yale.edu/tp/cas' do |service_response|
      if success
        ticket = options[:ticket]
        if ticket.is_a?(CASino::ProxyTicket)
          proxies = []
          service_ticket = ticket
          while service_ticket.is_a?(CASino::ProxyTicket)
            proxy_granting_ticket = service_ticket.proxy_granting_ticket
            proxies << proxy_granting_ticket.pgt_url
            service_ticket = proxy_granting_ticket.granter
          end
          ticket_granting_ticket = service_ticket.ticket_granting_ticket
        else
          service_ticket = ticket
          ticket_granting_ticket = ticket.ticket_granting_ticket
        end

        build_success_xml(service_response, ticket, service_ticket, ticket_granting_ticket, proxies)
      else
        build_failure_xml(service_response)
      end
    end
    xml.target!
  end

  private
  def serialize_extra_attribute(builder, key, value)
    key = :"#{key}"
    if value.kind_of?(String) || value.kind_of?(Numeric) || value.kind_of?(Symbol)
      builder.cas key, "#{value}"
    elsif value.kind_of?(Array)
      value.each { |v| serialize_extra_attribute(builder, key, v) }
    else
      builder.cas key do |container|
        container.cdata! value.to_yaml
      end
    end
  end

  def build_success_xml(service_response, ticket, service_ticket, ticket_granting_ticket, proxies)
    user = ticket_granting_ticket.user
    service_response.cas :authenticationSuccess do |authentication_success|
      authentication_success.cas :user, user.username
      unless user.extra_attributes.blank?
        authentication_success.cas :attributes do |attributes|
          attributes.cas :authenticationDate, ticket_granting_ticket.created_at.iso8601
          attributes.cas :longTermAuthenticationRequestTokenUsed, ticket_granting_ticket.long_term?
          attributes.cas :isFromNewLogin, service_ticket.issued_from_credentials?
          # This would probably be the correct way, but current clients do not support this:
          # attributes.cas :userAttributes do |user_attributes|
          #   user.extra_attributes.each do |key, value|
          #     serialize_extra_attribute(user_attributes, key, value)
          #   end
          # end
          user.extra_attributes.each do |key, value|
            serialize_extra_attribute(attributes, key, value)
          end
        end
      end
      if options[:proxy_granting_ticket]
        proxy_granting_ticket = options[:proxy_granting_ticket]
        authentication_success.cas :proxyGrantingTicket, proxy_granting_ticket.iou
      end
      if ticket.is_a?(CASino::ProxyTicket)
        authentication_success.cas :proxies do |proxies_container|
          proxies.each do |proxy|
            proxies_container.cas :proxy, proxy
          end
        end
      end
    end
  end

  def build_failure_xml(service_response)
    service_response.cas :authenticationFailure, options[:error_message], code: options[:error_code]
  end
end


text:
package org.apache.geode.management.internal.rest;

import static org.apache.geode.test.junit.assertions.ClusterManagementRealizationResultAssert.assertManagementResult;
import static org.assertj.core.api.Assertions.assertThat;

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

import org.apache.geode.management.api.ClusterManagementResult;
import org.apache.geode.management.api.ClusterManagementService;
import org.apache.geode.management.client.ClusterManagementServiceBuilder;
import org.apache.geode.management.configuration.Region;
import org.apache.geode.management.configuration.RegionType;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.rules.MemberStarterRule;

public class ServerRestartTest {
  @Rule
  public ClusterStartupRule cluster = new ClusterStartupRule();

  @Test
  public void serverReconnect() {
    MemberVM locator = cluster.startLocatorVM(0, MemberStarterRule::withHttpService);
    cluster.startServerVM(1, locator.getPort());

    // we will stop the 2nd server so that we won't get "loss of qurom" error
    MemberVM server2 = cluster.startServerVM(2, locator.getPort());

    ClusterManagementService cmService =
        new ClusterManagementServiceBuilder()
            .setPort(locator.getHttpPort())
            .build();

    Region region = new Region();
    region.setName("Foo");
    region.setType(RegionType.REPLICATE);
    assertManagementResult(cmService.create(region)).hasStatusCode(
        ClusterManagementResult.StatusCode.OK);

    // force reconnect and then server should reconnect after 5 seconds
    server2.forceDisconnect();

    server2.waitTilFullyReconnected();

    server2.invoke(() -> {
      org.apache.geode.cache.Region<?, ?> foo = ClusterStartupRule.getCache().getRegion("Foo");
      assertThat(foo).isNotNull();
    });
  }

}


text:
/*
*
* Authors:
*  Dmitry Kolchev <dmitrykolchev@msn.com>
*
*/
#pragma once

#include "D2DCommon.h"
#include "D2DResource.h"
#include "TessellationSink.h"

using namespace System;
using namespace System::Runtime::InteropServices;

namespace Managed { namespace Graphics { namespace Direct2D
{
	public ref class Mesh: D2DResource
	{
	internal:
		Mesh(ID2D1Mesh *native):
			D2DResource(native)
		{
		}
	public:
		TessellationSink^ Open()
		{
			ID2D1TessellationSink *tessellationSink;
			ComUtils::CheckResult(GetNative<ID2D1Mesh>()->Open(&tessellationSink));
			return gcnew TessellationSink(tessellationSink);
		}
	};
}}}


text:
package netio

import (
	"github.com/brutella/hc/model"
	"github.com/brutella/hc/model/accessory"
	"github.com/brutella/hc/model/container"

	"bytes"
	"io/ioutil"
	"strings"
	"testing"
)

var info = model.Info{
	Name:         "My Bridge",
	SerialNumber: "001",
	Manufacturer: "Google",
	Model:        "Bridge",
}

func TestCharacteristicNotification(t *testing.T) {
	a := accessory.New(info)
	c := container.NewContainer()
	c.AddAccessory(a)

	buffer, err := Body(a, a.Info.Name.Characteristic)
	if err != nil {
		t.Fatal(err)
	}

	bytes, err := ioutil.ReadAll(buffer)

	if err != nil {
		t.Fatal(err)
	}
	if is, want := string(bytes), `{"characteristics":[{"aid":1,"iid":2,"value":"My Bridge"}]}`; is != want {
		t.Fatalf("is=%v want=%v", is, want)
	}
}

func TestCharacteristicNotificationResponse(t *testing.T) {
	a := accessory.New(info)
	resp, err := New(a, a.Info.Name.Characteristic)

	if err != nil {
		t.Fatal(err)
	}

	var buffer = new(bytes.Buffer)
	resp.Write(buffer)

	bytes, err := ioutil.ReadAll(buffer)

	if err != nil {
		t.Fatal(err)
	}
	bytes = FixProtocolSpecifier(bytes)
	if x := string(bytes); strings.HasPrefix(x, "EVENT/1.0 200 OK") == false {
		t.Fatal(x)
	}
}


text:
App.actuator = (function() {
  var config = {
    container: "display_box",
    channel: "actuator",
    socket: null,
    statusIndicator: '#status_indicator'
  };

  function init(configuration) {
    config =  Object.assign({}, config, configuration);
    config.socket = App.channel.init({
      identifiers: identifier(),
      functions: subscriptionFunctions()}
    );

    addListeners(identifier().id);
    true
  }

  function addListeners(id) {
    var input = getConsoleInput(id);

    switch(input.tagName) {
      case "A":
        input.addEventListener("click", function (event) {
          input.setAttribute('disabled', true);
          onClick(id);

          setTimeout(function() {
            input.removeAttribute('disabled');
          }, 2000)
        });
        break;
      case "INPUT":
        return input.addEventListener("keydown", function (event) {
          if (event.which == 13 || event.keyCode == 13) {
            onEnter(id);
            return false;
          }
          return true;
        });
        break;
      default:
        null;
        break;
    }
  }

  function identifier() {
    return {
      channel: config.channel, id: config.identifier
    };
  }

  function subscriptionFunctions() {
    return { connected: onConnected,
      disconnected: onDisconnected,
      received: onReceive }
  }

  // These functions will be evaluated when cable trigger the subscriptions
  function onDisconnected() {
    Materialize.toast('Connection Lost', 4000);
    appendMessageToBox({ user: 'system',
      message: "Connection Lost",
      system: true
    });
  }

  function onReceive(data) {
    getActuatorStatus().text(data.message);
    appendMessageToBox(data);
  }

  function onConnected() {
    Materialize.toast('Connection Established', 4000);
    appendMessageToBox({ user: 'system',
      message: "Connection Established",
      system: true
    });
  }

  function onEnter(id) {
    config.socket.perform('speak', {
        message: getMessageFromConsoleInput(id),
        user: getUserId().text()
      });
  }

  function onClick(id) {
    Materialize.toast('Message sent', 4000);
    var value = $("#switch" + id).text().trim();

    switch(value) {
      case 'flash_on':
        config.socket.perform('speak', { message: 'off' });
        document.getElementById('switch' + id).innerHTML = 'flash_off';
        break;
      case 'flash_off':
        config.socket.perform('speak', { message: 'on' });
        document.getElementById('switch' + id).innerHTML = 'flash_on';
        break;
    }
    return value;
  }

  // Create HTML elements
  //
  function getMessageFromConsoleInput(id) {
    var value = getConsoleInput(id).value;
    getConsoleInput(id).value = null;
    return value;
  }

  function createMessageNode(incomingMessage) {
    var node = document.createElement('div');
    node.innerHTML = '' + incomingMessage + '';
    return node;
  }

  function getUserId() {
    return $(config.userId).text();
  }

  function getMessageBoxElement() {
    return document.getElementById(config.container);
  }

  function setActuatorStatus() {
    getActuatorStatus().text(incomingMessage.message);
  }

  function getActuatorStatus() {
    return $(config.statusIndicator);
  }

  function appendMessageToBox(incomingMessage) {
    getMessageBoxElement().prepend(createMessageNode(incomingMessage.message));
  }

  function getConsoleInput(id) {
    return document.getElementById("console" + id)
  }

  return {
    init: init
  }
}());