text:
/* jslint node: true */
/* jslint expr: true */
/*global describe, it, before, beforeEach, after, afterEach */

var chai = require('chai');
var should = chai.should();
var assert = chai.assert;
var ___ = 'probably wrong answer';

var module = this;
module.___ = ___; // don't change that line :)

function strictModeDefaultBinding() {
  'use strict';
  return ___;
}

function nonStrictDefaultBinding() {
  'use strict'; // maybe something to do with this line... haha ! "this" line... :D
  return this;
}

describe('JS this context behavior', function () {

  describe('using strict mode', function () {
    'use strict';

    it('by default, this is bound to undefined when in strict mode', function () {
      assert.isUndefined(strictModeDefaultBinding(), 'in strict mode, default this is undefined');
    });

    it('in non strict mode, default binding rule apply', function () {
      // change the behavior in the function
      assert.isFunction(nonStrictDefaultBinding().setTimeout, 'but in non strict mode, this refers to global')
    });

    it('be careful in node, at the root is not the global, but the module', function () {
      assert.isUndefined(module.___, 'beware of some confusion in Node, where the root element is the module, and not the global');
    });

    it('implicit binding rule using a object literal', function () {
      function add(b) {
        return this.a + b;
      }

      var calculator = {
        a: 3,
        add: add
      };

      assert.equal(calculator.add(4), ___, 'when the function is bound to an object, the context is the object itself');
    });

    it('implicit binding rule does not apply so easily when used as callbacks', function (done) {
      function tryIt(callback) {
        assert.equal(callback(5), 8, 'function must be hardly bound when passed as a callback, which is not so natural at first look');
        done();
      }

      var calculator = {
        a: 3,
        add: function add(b) {
          return this.a + b;
        }
      };

      tryIt(calculator.add); // call calculator.add differently. Try 2 approaches : hard binding or closure
    });

    it('explicit binding rule with call and apply', function () {
      function add(b) {
        return this.a + b;
      }

      var calculator1 = { a: 4 };
      var calculator2 = { a: 7 };

      assert.equal(add.___(calculator1, 5), 9, 'you can use Function.prototype.call to explicitly bind a context to the function');
      assert.equal(add.___(calculator2, [6]), 13, 'you can also use Function.prototype.apply, but apply takes an array as 2nd argument');
    });

    it('looping with a callback', function (done) {
      function loop(array, fn){
        for (var i = 0; i < array.length; i++) {
          // call callback here, but don't forget the context !
        }
      }
      var num = 3;
      loop([3, 4, 5], function(value){
        assert.equal(value, num++, "Make sure the contents are as we expect it.");
        assert.instanceOf(this, Array, "The context should be the full array.");
        if (num === 5) { done(); }
      });
    });
  });

  it('the new keyword creates a brand new object, and use that object as the context', function () {
    // non strict mode !
    function Ninja(){
      this.name = "Ninja";
    }

    var ninjaA = Ninja();
    assert.isUndefined(___, "Is undefined, not an instance of Ninja." );

    var ninjaB = new Ninja();
    assert.equal(ninjaB.name, ___, "Property exists on the ninja instance." );
  });

  describe('back in strict mode', function () {
    'use strict';

    it('with new, the context is established for that particular object and not others', function () {
      function Ninja(){
        this.swung = false;

        // Should return true
        this.swingSword = function(){
          this.___ = !this.swung;
          return this.swung;
        };
      }

      var ninja = new Ninja();
      assert.isTrue(ninja.swingSword(), "Calling the instance method." );
      assert.isTrue(ninja.swung, "The ninja has swung the sword." );

      var ninjaB = new Ninja();
      assert.isFalse(ninjaB.___, "Make sure that the ninja has not swung his sword." );
    });

    it('add a method that gives a name to the ninja', function () {
      function Ninja(name){
        // Implement!
        this.changeName = ___;
      }

      var ninja = new Ninja("John");
      assert.equal(ninja.name, "John", "The name has been set on initialization" );

      ninja.changeName("Bob");
      assert.equal(ninja.name, "Bob", "The name was successfully changed." );
    });

    it('order of precedence can be proved', function () {
      function sayHey() {
        this.hey = 'hey, ' + (this.who || 'you');
      }

      assert.Throw(sayHey, ___, null, 'in strict mode, so this is null because of default binding rule');

      var jude = { who: 'Jude', sayHey: sayHey };
      jude.sayHey();
      assert.equal(jude.hey, 'hey, ' + ___, 'implicit binding goes over default binding');

      var joe = { who: 'Joe' };
      jude.sayHey.call(joe);
      assert.equal(joe.hey, 'hey, ' + ___, 'explicit binding goes over implicit binding');

      var ya = { who: 'ya!' };
      var heyYa = sayHey.bind(ya);
      heyYa.call(jude);
      assert.equal(ya.hey, 'hey, ' + ___, 'hard binding goes over explicit binding');

      assert.equal(new sayHey().hey, 'hey, ' + ___, 'new creates a new object');
      assert.equal(new jude.sayHey().hey, 'hey, ' + ___, 'new goes over implicit binding');
      assert.equal(new heyYa().hey, 'hey, ' + ___, 'new goes over hard/explicit binding, but you don't want to write this!');
    });
  });
});


text:
    function fblogin(){
        FB.login(function(response) {
            if (response.session) {
                if (response.perms) {
                    // user is logged in and granted some permissions.
                    FacebookConnect.connect(false);
                } else {
                    // user is logged in, but did not grant any permissions
                    window.location.reload();
                }
            } else {
                // user is not logged in
                window.location.reload();
            }
        }, {perms:'user_about_me,email'});
        return false;
    }
    window.fbAsyncInit = function() {
        FB.init({
            appId: facebookAppId,
            status: true,
            cookie: true,
            xfbml: true
    });
                FacebookConnect.init(
                        facebookRedir,
                        true,
                        'Para poder utilizar o login integrado do Facebook, você precisa permitir que nosso site se comunique com seu Facebook.',
                        'Login invalido, Por favor tente mais tarde'
                );
            };
var FacebookConnect = {
    status: 'unknown',
    baseUrl: '',
    loggedIn: false,
    user: '',
    genericErrorText: '',
    permissionErrorText: '',
    init: function (url, isLoggedIn, permissionText, genericText) {
        FacebookConnect.baseUrl = url;
        FacebookConnect.loggedIn = isLoggedIn;
        FacebookConnect.permissionErrorText = permissionText;
        FacebookConnect.genericErrorText = genericText;
        FB.getLoginStatus(function (response) {
            status = response.status;
            if (!FacebookConnect.loggedIn && status == 'connected') {
                var callback = function (json) {
                        if (json.success) {
                            window.location.href=url;
                        }
                    }
                FacebookConnect.loginHandler(callback);
            }
        }, true);
    },
    connect: function () {

        FacebookConnect.toggleFacebookError(false);
        var newStatus = 'unknown';
        FB.getLoginStatus(function (response) {
            newStatus = response.status;
            if (newStatus == 'notConnected') {
                FacebookConnect.toggleFacebookError(true, FacebookConnect.permissionErrorText);
            } else if (newStatus == 'connected') {
                var callback = function (json) {
                        if (json.success) {
                            FacebookConnect.forwardUser(json.url);
                        } else {
                            FacebookConnect.toggleFacebookError(true, FacebookConnect.genericErrorText)
                        }
                    }
                FacebookConnect.loginHandler(callback, response.session.access_token);
            }
            status = newStatus;
        }, true);
    },
    loginHandler: function (callback, securityToken) {
        FB.api('/me', function (user) {
            if (user != null) {
                FacebookConnect.user = user;
                /*DEBUG TABAJARA*/
                console.log('user: ', user);
                /* /DEBUG TABAJARA*/
                var params = {
                    'facebookLogin': user.username,
                    'facebookId': user.id,
                    'email': user.email,
                    'firstName': user.first_name,
                    'lastName': user.last_name,
                    'cidade': user.location.name,
                    'returnJson': 'true',
                    'gender': user.gender,
                    'facebookToken': securityToken
                };
                $.ajax({
                    url: facebookUrl,
                    data: params,
                    dataType: "json",
                    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                    scriptCharset: 'utf-8',
                    success: callback,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        FacebookConnect.toggleFacebookError(true, FacebookConnect.genericErrorText);
                    }
                });
            }
        });
    },
    toggleFacebookError: function (showError, errorText) {
        if (showError) {
            alert(errorText);
        }
    },
    forwardUser: function (url) {
         if (url) {
            window.location.href = url;
        } else {
            window.location.href = FacebookConnect.baseUrl;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
* Chef-solo is for installation cookbooks
* Knife-solo is for cookbooks deployment to server
* Berkshelf is for cookbooks dependency management

## Installation
````
$ bundle install
````

## Usage
Add server specification into nodes/{host}.json

**Note** for security reasons all real node specs are kept into separate private repo. Node specification example:

````json
{
  "run_list": [
    "recipe[sudo]",
    "recipe[rbenv::default]",
    "recipe[rbenv::ruby_build]",
    "recipe[rbenv::rbenv_vars]",
    "recipe[nodejs::nodejs_from_binary]",
    "recipe[nginx::source]",
    "recipe[redisio::install]",
    "recipe[redisio::enable]",
    "recipe[postgresql::server]",
    "recipe[postgresql::config_initdb]",
    "recipe[postgresql::config_pgtune]",
    "recipe[site_install]",
    "recipe[diptables]",
    "recipe[ssh-hardening]",
    "recipe[os-hardening]"
  ],
  "stage": "staging",
  "root_user": {
    "name": "sysadmin name",
    "password": "shadowed password for sysadmin user will be needed for sudo operations",
    "authorized_keys": [
      "list of public keys to be added during site install"
    ]
  },
  "app_user": {
    "name": "app user name",
    "password": "shadowed password for app user",
    "authorized_keys": [
      "list of public keys to be added during site install"
    ]
  },
  "postgresql": {
    "password": {
      "postgres": "shadowed password for db"
    },
    "config_pgtune": {
      "db_type": "web"
    }
  },
  "automatic": {
    "ipaddress": "192.168.33.10"
  }
}

````
and then run commands below to install the server
````
$ ./bin/init {user}@{host}
$ knife solo cook {user}@{host}
````
Check chef supermarket for more details on any cookbook used in this project and setup available.

## Resources
* Cookbook supermarket https://supermarket.getchef.com/
* Chef resources http://docs.getchef.com/chef/resources.html
* Knife-solo setup demo https://github.com/sajnikanth/knife-solo-demo
* Berkshelf setup demo https://github.com/sajnikanth/berkshelf-demo

## Disclaimer
Instalation scripts are tested against Ubuntu servers, but might work with other distros too.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Test case for source maps</title>
  <link rel="stylesheet" href="styles/style.css">

Please wait to be closed.

  <input type="text" id="color" placeholder="css color"/>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="css/main.css" type="text/css" media="screen">

Publisher <select id="select_publisher" onchange="select_change(this.value);"><option value="--ALL--">--ALL--</option></select>

<input id="heatmap_radio" type="checkbox" unchecked /> Enable heatmap


text:
#import "NSObject.h"

@class NSArray, NSMutableArray, NSMutableSet, NSSet;

@interface IDEActivityReportFileIOCoordinator : NSObject
{
    NSMutableArray *_activityReports;
    NSMutableSet *_runningThrottleableActivityReports;
    NSMutableSet *_runningUnthrottleableActivityReports;
    BOOL _isAddingReports;
}

+ (void)initialize;
+ (id)sharedActivityReportFileIOCoordinator;
- (id)_activityReportPriorityComparator;
- (unsigned long long)_allowedConcurrentActivities;
- (id)_init;
- (void)_insertSortedActivityReport:(id)arg1;
- (BOOL)_removeSortedActivityReport:(id)arg1;
- (void)_startObservingReport:(id)arg1;
- (void)_stopObservingReport:(id)arg1;
- (void)_throttleActivityReport:(id)arg1 throttleFactor:(double)arg2;
- (void)_updateRunningActivityReports;
@property(readonly) NSArray *activityReports; // @synthesize activityReports=_activityReports;
- (id)init;
@property(readonly) NSSet *runningThrottleableActivityReports; // @synthesize runningThrottleableActivityReports=_runningThrottleableActivityReports;
@property(readonly) NSSet *runningUnthrottleableActivityReports; // @synthesize runningUnthrottleableActivityReports=_runningUnthrottleableActivityReports;
- (void)updateWithAddedActivityReports:(id)arg1 deletedActivityReports:(id)arg2;

@end


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace CrazyStorm.Core
{
    public enum RebounderShape
    {
        Line,
        Circle
    }
    public struct RebounderData
    {
        public int size;
        public RebounderShape rebounderShape;
        public float rotation;
    }
    public class Rebounder : Component
    {
        #region Private Members
        float lastRotation;
        RebounderData rebounderData;
        IList<EventGroup> rebounderEventGroups;
        #endregion

        #region Public Members
        [IntProperty(0, int.MaxValue)]
        public int Size
        {
            get { return rebounderData.size; }
            set { rebounderData.size = value; }
        }
        [EnumProperty(typeof(RebounderShape))]
        public RebounderShape RebounderShape
        {
            get { return rebounderData.rebounderShape; }
            set { rebounderData.rebounderShape = value; }
        }
        [FloatProperty(float.MinValue, float.MaxValue)]
        public float Rotation
        {
            get { return rebounderData.rotation; }
            set { rebounderData.rotation = value; }
        }
        public IList<EventGroup> RebounderEventGroups { get { return rebounderEventGroups; } }
        #endregion

        #region Constructor
        public Rebounder()
        {
            rebounderData.size = 50;
            rebounderEventGroups = new GenericContainer<EventGroup>();
        }
        #endregion

        #region Private Methods
        void Update()
        {
            base.ExecuteExpression("Size");
            base.ExecuteExpression("Rotation");
            int count = 0;
            List<ParticleBase> results = ParticleManager.SearchByRect(Position.x - Size, Position.x + Size,
                Position.y - Size, Position.y + Size, out count);
            for (int i = 0; i < count; ++i)
            {
                if (results[i].IgnoreRebound || results[i].Type == null || results[i].PSpeedVector == Vector2.Zero)
                    continue;

                float radius = Math.Max(results[i].Type.Width, results[i].Type.Height) / 2;
                float rotation = Rotation;
                switch (RebounderShape)
                {
                    case RebounderShape.Line:
                        Vector2 p1 = Position + MathHelper.GetVector2(Size, Rotation);
                        Vector2 p2 = Position + MathHelper.GetVector2(Size, Rotation + 180);
                        if (!MathHelper.LineIntersectWithCircle(p1, p2, results[i].PPosition, radius))
                            continue;

                        if (SpeedVector != Vector2.Zero && Vector2.Dot(results[i].PSpeedVector, SpeedVector) >= 0)
                            continue;

                        float dr = Rotation - lastRotation;
                        if (dr > 0)
                        {
                            Vector2 rotationVector = MathHelper.GetVector2(1, Rotation + 90);
                            if (Vector2.Dot(results[i].PSpeedVector, rotationVector) >= 0)
                                continue;
                        }
                        else if (dr < 0)
                        {
                            Vector2 rotationVector = MathHelper.GetVector2(1, Rotation - 90);
                            if (Vector2.Dot(results[i].PSpeedVector, rotationVector) >= 0)
                                continue;
                        }
                        break;
                    case RebounderShape.Circle:
                        if (!MathHelper.TwoCirclesIntersect(Position, Size, results[i].PPosition, radius))
                            continue;

                        if (MathHelper.PointInsideCircle(Position, Size, results[i].PPosition))
                        {
                            if (Vector2.Dot(results[i].PSpeedVector, Position - results[i].PPosition) >= 0)
                                continue;
                        }
                        else if (Vector2.Dot(results[i].PSpeedVector, results[i].PPosition - Position) >= 0)
                            continue;

                        rotation = MathHelper.GetDegree(results[i].PPosition - Position) + 90;
                        break;
                }
                results[i].PSpeedVector = MathHelper.GetVector2(results[i].PSpeed, 2 * rotation - results[i].PSpeedAngle);
                for (int k = 0; k < RebounderEventGroups.Count; ++k)
                    RebounderEventGroups[k].Execute(results[i], null);
            }
            lastRotation = Rotation;
        }
        #endregion

        #region Public Methods
        public override object Clone()
        {
            var clone = base.Clone() as Rebounder;
            clone.rebounderEventGroups = new GenericContainer<EventGroup>();
            foreach (var item in rebounderEventGroups)
                clone.rebounderEventGroups.Add(item.Clone() as EventGroup);

            return clone;
        }
        public override XmlElement BuildFromXml(XmlElement node)
        {
            node = base.BuildFromXml(node);
            var rebounderNode = (XmlElement)node.SelectSingleNode("Rebounder");
            //rebounderData
            XmlHelper.BuildFromStruct(ref rebounderData, rebounderNode, "RebounderData");
            //rebounderEventGroups
            XmlHelper.BuildFromObjectList(rebounderEventGroups, new EventGroup(), rebounderNode, "RebounderEventGroups");
            return rebounderNode;
        }
        public override XmlElement StoreAsXml(XmlDocument doc, XmlElement node)
        {
            node = base.StoreAsXml(doc, node);
            var rebounderNode = doc.CreateElement("Rebounder");
            //rebounderData
            XmlHelper.StoreStruct(rebounderData, doc, rebounderNode, "RebounderData");
            //rebounderEventGroups
            XmlHelper.StoreObjectList(rebounderEventGroups, doc, rebounderNode, "RebounderEventGroups");
            node.AppendChild(rebounderNode);
            return rebounderNode;
        }
        public override List<byte> GeneratePlayData()
        {
            var bytes = base.GeneratePlayData();
            var rebounderBytes = new List<byte>();
            //rebounderData
            PlayDataHelper.GenerateStruct(rebounderData, rebounderBytes);
            //rebounderEventGroups
            PlayDataHelper.GenerateObjectList(rebounderEventGroups, rebounderBytes);
            bytes.AddRange(PlayDataHelper.CreateBlock(rebounderBytes));
            return bytes;
        }
        public override void LoadPlayData(BinaryReader reader, float version)
        {
            base.LoadPlayData(reader, version);
            using (BinaryReader rebounderReader = PlayDataHelper.GetBlockReader(reader))
            {
                using (BinaryReader dataReader = PlayDataHelper.GetBlockReader(rebounderReader))
                {
                    Size = dataReader.ReadInt32();
                    RebounderShape = PlayDataHelper.ReadEnum<RebounderShape>(dataReader);
                    Rotation = dataReader.ReadSingle();
                    lastRotation = Rotation;
                }
                //rebounderEventGroups
                PlayDataHelper.LoadObjectList(RebounderEventGroups, rebounderReader, version);
            }
        }
        public override bool PushProperty(string propertyName)
        {
            if (base.PushProperty(propertyName))
                return true;

            switch (propertyName)
            {
                case "Size":
                    VM.PushInt(Size);
                    return true;
                case "RebounderShape":
                    VM.PushEnum((int)RebounderShape);
                    return true;
                case "Rotation":
                    VM.PushFloat(Rotation);
                    return true;
            }
            return false;
        }
        public override bool SetProperty(string propertyName)
        {
            if (base.SetProperty(propertyName))
                return true;

            switch (propertyName)
            {
                case "Size":
                    Size = VM.PopInt();
                    return true;
                case "RebounderShape":
                    RebounderShape = (RebounderShape)VM.PopEnum();
                    return true;
                case "Rotation":
                    Rotation = VM.PopFloat();
                    return true;
            }
            return false;
        }
        public override bool Update(int currentFrame)
        {
            if (!base.Update(currentFrame))
                return false;

            if (BindingTarget == null)
                Update();
            else
                BindingUpdate(Update);

            return true;
        }
        public override void Reset()
        {
            base.Reset();
            var initialState = base.initialState as Rebounder;
            Size = initialState.Size;
            RebounderShape = initialState.RebounderShape;
            Rotation = initialState.Rotation;
        }
        #endregion
    }
}


text:
require 'spec_helper'

describe 'osx::displays::auto_brightness_adjustment' do
  let(:facts) { {:boxen_user => 'ilikebees' } }

  describe 'defaults' do
    it 'set value to 1' do
      should contain_boxen__osx_defaults('Toggle Whether Brightness is Automatically Adjusted Depending on Ambient Light').with({
        :user   => 'root',
        :key    => '"Automatic Display Enabled"',
        :domain => '/Library/Preferences/com.apple.iokit.AmbientLightSensor',
        :type   => 'int',
        :value  => 1,
      })
    end
  end

  describe 'enabled' do
    let(:params) { {:ensure => 'present'} }
    it 'set value to 1' do
      should contain_boxen__osx_defaults('Toggle Whether Brightness is Automatically Adjusted Depending on Ambient Light').with({
        :user   => 'root',
        :key    => '"Automatic Display Enabled"',
        :domain => '/Library/Preferences/com.apple.iokit.AmbientLightSensor',
        :type   => 'int',
        :value  => 1,
      })
    end
  end

  describe 'disabled' do
    let(:params) { {:ensure => 'absent'} }
    it 'set value to 0' do
      should contain_boxen__osx_defaults('Toggle Whether Brightness is Automatically Adjusted Depending on Ambient Light').with({
        :user   => 'root',
        :key    => '"Automatic Display Enabled"',
        :domain => '/Library/Preferences/com.apple.iokit.AmbientLightSensor',
        :type   => 'int',
        :value  => 0,
      })
    end
  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Trichophyton pilosum Sabour.

### Remarks
null


text:
using NQuery.Symbols;

namespace NQuery.Binding
{
    internal sealed class BoundVariableExpression : BoundExpression
    {
        public BoundVariableExpression(VariableSymbol variableSymbol)
        {
            Symbol = variableSymbol;
        }

        public override BoundNodeKind Kind
        {
            get { return BoundNodeKind.VariableExpression; }
        }

        public override Type Type
        {
            get { return Symbol.Type; }
        }

        public VariableSymbol Symbol { get; }

        public override string ToString()
        {
            return $"@{Symbol.Name}";
        }
    }
}


text:
copy/b mssql.create-all.sql +mssql.inserts.sql +mssql.create-membership-all.sql ..\mssql.nearforums-db.sql
PAUSE


text:
/**
 * This file gets copied out of the `pkg` snapshot filesystem into the `vc dev`
 * builder cache directory, so it's very important that it does not rely on any
 * modules from npm that would not be available in that directory (so basically,
 * only Vercel Runtimes and `@vercel/build-utils`.
 */
const { FileFsRef } = require('@vercel/build-utils');

process.on('unhandledRejection', err => {
  console.error('Exiting builder due to build error:');
  console.error(err);
  process.exit(1);
});

process.on('message', onMessage);

function onMessage(message) {
  processMessage(message).catch(err => {
    Object.defineProperty(err, 'message', { enumerable: true });
    Object.defineProperty(err, 'stack', { enumerable: true });
    process.removeListener('message', onMessage);
    process.send({ type: 'buildResult', error: err }, () => process.exit(1));
  });
}

async function processMessage(message) {
  const { requirePath, buildOptions } = message;
  const builder = require(requirePath);

  // Convert the `files` to back into `FileFsRef` instances
  for (const name of Object.keys(buildOptions.files)) {
    const ref = Object.assign(
      Object.create(FileFsRef.prototype),
      buildOptions.files[name]
    );
    buildOptions.files[name] = ref;
  }

  const result = await builder.build(buildOptions);

  // `@vercel/next` sets this, but it causes "Converting circular
  // structure to JSON" errors, so delete the property...
  delete result.childProcesses;

  process.send({ type: 'buildResult', result });
}

process.send({ type: 'ready' });


text:
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   %{

   Copyright [2016] [Pradeepkumar Ashok] [Project Data Clarity]

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

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

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

   %}
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   function stickSlipIndex  = computeStickSlipIndexApproach1(timeInterval_sec, statesData)

   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   %{

   Comments about this program go here:

   This is approach 1 of calculation stickSlipIndex: Shell Internal...

   SSI = (Tmax-Tmin)/Tave

   Metadata needed for this approach:

   1. timeInterval_sec
   2. rigState

   Other Comments: The 1Hz torque data is assumed to raw data collected onces every
  1 second, without averaging, or any other filtering operation.

   %}
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % Default Arguments in case the user does not specify any argument

    if nargin < 1
    timeInterval_sec =3;
    statesData = 'RigStatesForSampleData1';
    end

    if nargin < 2
    statesData = 'RigStatesForSampleData1';
    end

    timeInterval_sec

     % Load the dataset into memory

     h = waitbar(0, 'Loading Data');
     rawDataAllChannels = load (fullfile(pwd, 'InputData', 'SampleData1.csv'));

     if (nargin<2)
        rigStatesForSampleData1 = load('-ascii', fullfile(pwd, 'InputData', statesData));
     end

     % Separate arrays are created for each data channel for ease of use.
     % Not all of the channels will be needed for all derived data calculations.

     time_sec = rawDataAllChannels(:,1)
     blockHeight_feet = rawDataAllChannels(:,2);
     flowOut_percent = rawDataAllChannels(:,3);
     hookLoad_klbf = rawDataAllChannels(:,4);
     topdriveSpeed_rpm = rawDataAllChannels(:,5);
     strokesPerMinute1_spm = rawDataAllChannels(:,6);
     strokesPerMinute2_spm = rawDataAllChannels(:,7);
     standPipePressure_psi = rawDataAllChannels(:,8);
     topDriveTorque_ftlb = rawDataAllChannels(:,9);
     surveyInclination_degrees = rawDataAllChannels(:,10);
     surveyAzimuth_degrees = rawDataAllChannels(:,11);
     dataInstances_nounit = rawDataAllChannels(:,12);

     % Do the calculation here

     waitbar(0.3, h, 'Performing Calculations');

     timeIntervalCounter = 0;

     for i=1:length(dataInstances_nounit)
         % If the current state is drilling
         if(rigStatesForSampleData1(i)==2)
              % Once it starts drilling wait until after "timeInterval_sec" seconds before calulating a value
               timeIntervalCounter = timeIntervalCounter + 1;
               if(timeIntervalCounter<=timeInterval_sec)
                  stickSlipIndex(i) = NaN;
               else
                  torqueMax = max(topDriveTorque_ftlb(i-timeInterval_sec:i));
                  torqueMin = min(topDriveTorque_ftlb(i-timeInterval_sec:i));
                  torqueAve = mean(topDriveTorque_ftlb(i-timeInterval_sec:i));
                  if (torqueAve ~= 0)
                      stickSlipIndex(i) = (torqueMax-torqueMin)/torqueAve ;
                  else
                      stickSlipIndex(i) = 0;
                  end
               end

         else

           % If not drilling
           stickSlipIndex(i) = NaN;
           timeIntervalCounter = 0;

         end

     end

     stickSlipIndex = stickSlipIndex';

     % End of calculation

     % Export the data to a CSV file.

     waitbar(0.7, h, 'Writing Data to CSV file');

     fullfile(pwd, 'OutputResults', 'AnalysisResults.csv' );

     outfileName = fullfile(pwd, 'OutputResults', 'AnalysisResults.csv' );
     dataToExport = [rawDataAllChannels,rigStatesForSampleData1,stickSlipIndex];
     header='Time(sec), Block Height(feet),Flow Out(%),Hookload(klbf),Top Drive Speed(RPM),Strokes Per Minute #1,Strokes Per Minute #2,Standpipe Pressure (psi),Top Drive Torque (ftlb),Survey Inclination (degrees), Survey Azimuth (degrees), Data Instance, Rig State Code,Stick Slip Index (torque Based)';
     dlmwrite(outfileName,header,'delimiter','');
     dlmwrite(outfileName,dataToExport,'delimiter',',','-append');

     waitbar(1, h, 'All Complete');

     close(h);

     % Plot the charts

     subplot(3,3,1);
     plot(blockHeight_feet,'g');
     title (sprintf('Block Height'));
     xlabel('Data Instance (sec)');
     ylabel('Block Height(feet)');

     subplot(3,3,2);
     plot(flowOut_percent, 'k');
     title (sprintf('Flow Out (percent)'));
     xlabel('Data Instance (sec)');
     ylabel('Flow Out(%)');

     subplot(3,3,3);
     plot(hookLoad_klbf, 'b');
     title (sprintf('Hookload(klbf)'));
     xlabel('Data Instance (sec)');
     ylabel('Hookload(klbf)');

     subplot(3,3,4);
     plot(topdriveSpeed_rpm, 'm');
     title (sprintf('Top Drive Speed(RPM)'));
     xlabel('Data Instance (sec)');
     ylabel('Top Drive Speed(RPM)');

     subplot(3,3,5);
     plot(strokesPerMinute1_spm, 'r');
     title (sprintf('Strokes Per Minute #1'));
     xlabel('Data Instance (sec)');
     ylabel('Strokes Per Minute #1');

     subplot(3,3,6);
     plot(strokesPerMinute2_spm, 'b');
     title (sprintf('Strokes Per Minute #2'));
     xlabel('Data Instance (sec)');
     ylabel('Strokes Per Minute #2');

     subplot(3,3,7);
     plot(standPipePressure_psi, 'g');
     title (sprintf('Standpipe Pressure (psi)'));
     xlabel('Data Instance (sec)');
     ylabel('Standpipe Pressure (psi)');

     subplot(3,3,8);
     plot(topDriveTorque_ftlb, 'k');
     title (sprintf('Top Drive Torque (ftlb)'));
     xlabel('Data Instance (sec)');
     ylabel('Top Drive Torque (ftlb)');

     subplot(3,3,9);
     plot(stickSlipIndex, 'm');
     title (sprintf('Stick Slip Index (torque Based)'));
     xlabel('Data Instance (sec)');
     ylabel('Stick Slip Index (torque Based)');

   end


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

class Button extends Component {
  resolveContent() {
    const { isLoading, label } = this.props;

    if (isLoading) {
      return (

      )
    }

    return label;
  }

  render() {
    return (
      <button {...this.props} className="app-form_button">
        {this.resolveContent()}
      </button>
    )
  }
}

function mapStateToProps(state) {
  const { isLoading } = state.app;

  return {
    isLoading: isLoading
  }
}

export default connect(mapStateToProps)(Button);


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Windows.Forms;

namespace ViewSpreadsheet
{
    public partial class PasswordDialog : Form
    {
        public PasswordDialog()
        {
            InitializeComponent();
        }

        public string Password
        {
            get { return textBoxPassword.Text; }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            //DialogResult = DialogResult.OK;
            //Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void checkBoxHide_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxHide.Checked)
                textBoxPassword.PasswordChar = '*';
            else
                textBoxPassword.PasswordChar = '\0';
        }
    }
}


text:
package org.minijax.rs;

import static org.junit.jupiter.api.Assertions.*;

import java.security.Principal;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.ext.Provider;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.minijax.rs.test.MinijaxTest;

import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;

class SecurityTest extends MinijaxTest {

    static class User implements Principal {
        final String name;
        final String role;

        User(final String name, final String role) {
            this.name = name;
            this.role = role;
        }

        @Override
        public String getName() {
            return name;
        }
    }

    @Provider
    public static class Security implements SecurityContext {
        private final User user;

        @Inject
        public Security(@HeaderParam("Authorization") final String a) {
            if ("alice".equals(a)) {
                user = new User("Alice", "admin");
            } else if ("bob".equals(a)) {
                user = new User("Bob", "user");
            } else {
                user = null;
            }
        }

        @Override
        public Principal getUserPrincipal() {
            return user;
        }

        @Override
        public boolean isUserInRole(final String role) {
            return user != null && (user.role.equals(role) || user.role.equals("admin"));
        }

        @Override
        public boolean isSecure() {
            throw new UnsupportedOperationException();
        }

        @Override
        public String getAuthenticationScheme() {
            throw new UnsupportedOperationException();
        }
    }

    @GET
    @Path("/")
    @PermitAll
    public static String hello() {
        return "Hello world!";
    }

    @GET
    @Path("/secret")
    @RolesAllowed("user")
    public static String secret() {
        return "Top secret!";
    }

    @GET
    @Path("/admin")
    @RolesAllowed("admin")
    public static String admin() {
        return "Admins only!";
    }

    @BeforeAll
    public static void setUpSecurityTest() {
        resetServer();
        register(SecurityTest.class);
        register(SecurityTest.Security.class);
    }

    @Test
    void testHello() {
        assertEquals("Hello world!", target("/").request().get(String.class));
    }

    @Test
    void testSecretUnauthorized() {
        assertEquals(401, target("/secret").request().get().getStatus());
    }

    @Test
    void testSecretAllowed() {
        assertEquals(
                "Top secret!",
                target("/secret").request().header("Authorization", "bob").get(String.class));
    }

    @Test
    void testAdminUnauthorized() {
        assertEquals(401, target("/admin").request().get().getStatus());
    }

    @Test
    void testAdminForbidden() {
        assertEquals(403, target("/admin").request().header("Authorization", "bob").get().getStatus());
    }

    @Test
    void testAdminAllowed() {
        assertEquals(
                "Admins only!",
                target("/admin").request().header("Authorization", "alice").get(String.class));
    }
}


text:
//
//  QuizOverviewViewController.m
//  Hausaufgabenheft
//
//  Created by Gero Embser on 27.02.16.
//  Copyright © 2016 Bischöfliche Marienschule Mönchengladbach. All rights reserved.
//

#import "QuizOverviewViewController.h"
#import "QuizController.h"
#import "NSDate+AdvancedDate.h"
#import "DownloadQuizFragenViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface QuizOverviewViewController ()
///der QuizController, dessen Daten angezeigt werden bzw. der benutzt wird, um die Übersicht des Quizes für des User darzustellen und Infos über das Quiz zu gewinnen
@property QuizController *quizController;
@end

@implementation QuizOverviewViewController

#pragma mark - View Setup
- (void)viewDidLoad {
    [super viewDidLoad];

    //den QuizController für diesen ViewController setzen
    self.quizController = [QuizController defaultQuizController];

    //die Farbe vom NavigationController-View auf weiß setzen, weil es sonst - warum auch immer - zu unschönen Schatten während des Übergangs von einem zu diesem ViewController kommt --> ohne diese folgende Zeile wäre außerdem die NavigationBar wesentlich dunkler
    self.navigationController.view.backgroundColor = [UIColor whiteColor];

    //die Werte für die entsprechenden View-Objekte nach dem Laden des Views setzen
    //befüllt die Quiz-Infos, die in der Übersicht erscheinen sollen (Name des Benutzers, letztes Update, verfügbare Fragen und Punktestand)
    [self befuelleQuizInfos];

    //für Notifications registrieren
    //neue Fragen (also Herunterladen fertig)-Notification --> um die Anzahl der verfügbaren Fragen und das Datum des letzten Updates zu aktualisieren
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quizControllerDidRefreshQuestions:) name:QuizControllerDidRefreshQuestions object:self.quizController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
    // Set up the shape of the circle
    int radius = self.punkteContainerView.frame.size.width/2;
    CAShapeLayer *circle = [CAShapeLayer layer];

    UIBezierPath *path = [UIBezierPath bezierPath];
    CGPoint point = CGPointMake(self.punkteContainerView.frame.size.width/2, self.punkteContainerView.frame.size.height/2);

    [path addArcWithCenter:point radius:radius startAngle:0 endAngle:M_PI*2*0  clockwise:YES];

    // Make a circular shape
    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
                                             cornerRadius:radius/2].CGPath;
    circle.path = path.CGPath;
    // Center the shape in self.view
    circle.position = CGPointMake(0,0);
    NSLog(@"%@", NSStringFromCGPoint(circle.position));
    // Configure the apperence of the circle
    circle.fillColor = [UIColor clearColor].CGColor;
    circle.strokeColor = [UIColor whiteColor].CGColor;
    circle.lineWidth = 10;

    // Add to parent layer
    [self.punkteContainerView.layer addSublayer:circle];

    // Configure animation
    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = 1.0; // "animate over 10 seconds or so.."
    drawAnimation.repeatCount         = 1.0;  // Animate only once..

    // Animate from no part of the stroke being drawn to the entire stroke being drawn
    drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    drawAnimation.toValue   = [NSNumber numberWithFloat:1.0f];

    // Experiment with timing to get the appearence to look the way you want
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    // Add the animation to the circle
    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Methoden
///diese Methode befüllt die entsprechenden Label mit den wichtigen, grundsätzlichen Infos über das Quiz (wie das letzte Update, die verfügbaren Fragen, der Punktestand und der Name des Benutzers
- (void)befuelleQuizInfos {
    //User-Name
    self.userNameLabel.text = self.quizController.user.fullName;

    //Punkte-Stand
    self.punkteLabel.text = [NSString stringWithFormat:@"%lu Punkte", self.quizController.punktestand];

    //letztes Daten-Update
    NSString *lastUpdate = [self.quizController.user.quizLastUpdate datumUndUhrzeitString];
    self.letztesUpdateDatumLabel.text = [NSString stringWithFormat:@"letztes Update der Daten: %@", (lastUpdate && lastUpdate.length > 0 ? lastUpdate : @"noch nie")];

    //verfügbare Fragen
    self.verfuegbareFragenLabel.text = [NSString stringWithFormat:@"verfügbare Fragen: %lu", self.quizController.numberOfAvailableQuestions];

}

///folgende Methode sollte aufgerufen werden, wenn der Quiz-Controller ein Update der Fragen abgeschlossen hat
- (IBAction)quizControllerDidRefreshQuestions:(id)sender {
    //hier die neuen Werte für das Datum der letzen Aktualisierung und der Anzahl an Quiz-Fragen setzen, wenn der QuizController die Fragen aktualisiert hat --> auf dem Main-Thread ausführen --> user interface-Aktion
    dispatch_async(dispatch_get_main_queue(), ^{
        [self befuelleQuizInfos];
    });
}

#pragma mark - IB-Actions

//ruft den ViewController auf, der die neuen Fragen herunterladen soll
- (IBAction)neueFragenHerunterladen:(id)sender {
    //den ViewController anzeigen, der das Herunterladen der neuen Fragen übernimmt
    DownloadQuizFragenViewController *downloadViewController = [DownloadQuizFragenViewController defaultDownloadQuizFragenViewController];

    //den ViewController anzeigen (aber im parentViewController vom navigationController vom QuizOverviewController, damit die Transparenz erhalten bleibt, aber gleichzeitig auch die Tab-Bar überblendet wird
    [self.navigationController.parentViewController presentViewController:downloadViewController animated:YES completion:nil];
}
@end


text:
"""Tests for the extraction CLI arguments helper."""

import argparse
import unittest

from plaso.cli import tools
from plaso.cli.helpers import extraction
from plaso.lib import errors

from tests.cli import test_lib as cli_test_lib

class ExtractionArgumentsHelperTest(cli_test_lib.CLIToolTestCase):
  """Tests for the extraction CLI arguments helper."""

  # pylint: disable=no-member,protected-access

  _EXPECTED_OUTPUT = """\
usage: cli_helper.py [--preferred_year YEAR] [--process_archives]
                     [--skip_compressed_streams]

Test argument parser.

{0:s}:
  --preferred_year YEAR, --preferred-year YEAR
                        When a format\'s timestamp does not include a year,
                        e.g. syslog, use this as the initial year instead of
                        attempting auto-detection.
  --process_archives, --process-archives
                        Process file entries embedded within archive files,
                        such as archive.tar and archive.zip. This can make
                        processing significantly slower. WARNING: this option
                        is deprecated use --archives=tar,zip instead.
  --skip_compressed_streams, --skip-compressed-streams
                        Skip processing file content within compressed
                        streams, such as syslog.gz and syslog.bz2.
""".format(cli_test_lib.ARGPARSE_OPTIONS)

  def testAddArguments(self):
    """Tests the AddArguments function."""
    argument_parser = argparse.ArgumentParser(
        prog='cli_helper.py', description='Test argument parser.',
        add_help=False,
        formatter_class=cli_test_lib.SortedArgumentsHelpFormatter)

    extraction.ExtractionArgumentsHelper.AddArguments(argument_parser)

    output = self._RunArgparseFormatHelp(argument_parser)
    self.assertEqual(output, self._EXPECTED_OUTPUT)

  def testParseOptions(self):
    """Tests the ParseOptions function."""
    options = cli_test_lib.TestOptions()

    test_tool = tools.CLITool()
    extraction.ExtractionArgumentsHelper.ParseOptions(options, test_tool)

    self.assertIsNone(test_tool._preferred_year)
    self.assertFalse(test_tool._process_archives)
    self.assertTrue(test_tool._process_compressed_streams)

    with self.assertRaises(errors.BadConfigObject):
      extraction.ExtractionArgumentsHelper.ParseOptions(options, None)

    # TODO: improve test coverage.

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


text:
**OLD**

Please use the API

**Important Upgrade Notice**

I have switched over to HTTPS it is secure, and user's are more comfortable with secure websites now days. You can still use the HTTPS script but you will just have a messge from chrome that its being loaded over HTTP if you are annoyed by this just replace https with http.

**End Notice**

#Installation

You will need to use your *Own* CSS!

There are two methods you can use to install SpeedTest, you can download and manually install or you can copy and paste the following.

The first option is for developers ONLY. And shouldn't be used by anyone if you don't intend to use it for that purpose.

Step 1 Add Reference to JS :

`<script type="text/javascript" src="https://jdc20181.github.io/SpeedTest/Release/SpeedTestV120.js"></script>`

**Important**

Be sure to use the latest release as Old Versions will stop working - once depreciated they will be moved and a Error Message with "Contact Administration, No JS file detected"

Beta: This is entirely in beta, so please give me time to update it and make fixes.

Step 2 : Add HTML Snippet

To make it work you simply need a qualifying element with the `Id="progress"` to make it work.


text:
import React from 'react';

import { shallow } from 'enzyme';

import { Icon } from '..';

describe('<Icon>', function() {

  it('should render', function() {
    shallow(<Icon />);
  });

  it('should accept custom className', function() {

    // when
    const wrapper = shallow(<Icon className="foo" />);

    // then
    expect(wrapper.hasClass('foo')).to.be.true;
  });

});


text:
using EnvDTE;
using System;

namespace CoatiSoftware.SourcetrailExtension.Utility
{
	class FileUtility
	{
		public delegate void ErrorCallback(string message);

		public static ErrorCallback _errorCallback = null;

		/**
		 * Returns true when file was found, false otherwise
		 */
		public static bool OpenSourceFile(DTE dte, string fileName)
		{
			try
			{
				dte.ItemOperations.OpenFile(fileName);
				return true;
			}
			catch (Exception e)
			{
				Logging.Logging.LogError("Exception: " + e.Message);

				if (_errorCallback != null)
				{
					_errorCallback("Failed to open file at " + fileName);
				}

				string message = "Failed to open file at " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(fileName);
				Logging.Logging.LogError(message);

				return false;
			}
		}

		public static void GoToLine(DTE dte, int lineNumber, int columnNumber)
		{
			try
			{
				((EnvDTE.TextSelection)dte.ActiveDocument.Selection).MoveToLineAndOffset(lineNumber, columnNumber);
			}
			catch (Exception e)
			{
				Logging.Logging.LogError("Exception: " + e.Message);

				if (_errorCallback != null)
				{
					_errorCallback("Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]");

					string message = "Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]";
					Logging.Logging.LogError(message);
				}
			}
		}

		public static string GetActiveDocumentName(DTE dte)
		{
			return dte.ActiveDocument.Name;
		}

		public static string GetActiveDocumentPath(DTE dte)
		{
			return dte.ActiveDocument.Path;
		}

		public static int GetActiveLineNumber(DTE dte)
		{
			return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.Line;
		}

		public static int GetActiveColumnNumber(DTE dte)
		{
			return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.LineCharOffset;
		}
	}
}


text:
package com.tngtech.test.junit.dataprovider.override;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;

import com.tngtech.junit.dataprovider.DataProvider;
import com.tngtech.junit.dataprovider.UseDataProvider;
import com.tngtech.junit.dataprovider.UseDataProviderExtension;

@ExtendWith(UseDataProviderExtension.class)
class OverridingAcceptanceTest extends AbstractAcceptanceBaseTest {

    @Override
    @TestTemplate
    @UseDataProvider
    void testBase(String one) {
        assertThat(one).isEqualTo("1");
    }

    @TestTemplate
    @UseDataProvider("dataProviderBase")
    public void testBaseNotOverridden(String one) {
        assertThat(one).isEqualTo("1");
    }

    @DataProvider
    public static Object[][] dataProviderChild() {
        return new Object[][] { { "1" } };
    }

}


text:
namespace App.Infrastructure.Tracing.Dashboard.Controls
{
    /// <summary>
    /// Implementation to support bootstrap-table.
    /// </summary>
    public interface IColumnBuilder : ITableBuilder, IColumnApply<IColumnBuilder>
    {
        /// <summary>
        /// Apply an option to a column.
        /// </summary>
        /// <param name="name">Name of the property to apply</param>
        /// <param name="value">Property value</param>
        IColumnBuilder ApplyToColumn(string name, object value);
    }
}


text:
package haxe.at.dotpoint.math.geom;

public enum Space
{
	LOCAL, MODEL, WORLD
}


text:
namespace Shade.Server.World
{
    public interface WorldService
    {
       //void EnterMap();
    }
}


text:
package nl.knaw.dans.common.wicket.behavior;

import java.util.Map;

import org.apache.wicket.Component;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.ajax.WicketAjaxReference;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.WicketEventReference;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.util.collections.MiniMap;
import org.apache.wicket.util.template.TextTemplateHeaderContributor;

/**
 * Detects form modification. This behavior can be added to a {@link Form}. It compares form elements onLoad and
 * onbeforeUnload. If there are differences a confirm-message is displayed. After a submit on the form, comparison
 * parameters are renewed.
 *

 * Sometimes a model object is dynamically updated from different parts of the page and saved to the back-end storage on
 * events other than the classical form-submission. In that case, comparison parameters can be renewed by calling the
 * function {@link #FORM_MODIFICATIONS_SAVED_JS} on an ajax round trip.
 *
Example

 * Here is an ajax-event handler that updates the
 * save-button and the the state of comparison parameters on the clients machine:
 *
 *

 * public void handleAjaxEvent(AjaxRequestTarget target)
 * {
 *     // update button-looks
 *     target.addComponent(saveButton);
 *
 *     // send message that form-elements are now saved to the back-end
 *     target.appendJavascript(FormModificationDetectorBehavior.FORM_MODIFICATIONS_SAVED_JS);
 * }
 *

 *
 * Sometimes you want to get rid of form modification detection behavior altogether, like for instance after some other
 * procedure on the page bumped into an error. In that case append {@link #DISABLE_DETECTOR_JS} to the target.
 *

 * The message displayed can be influenced by overriding {@link #getDisplayMessage()}.
 *

 * See also http://www.hunlock.com/blogs
 * /Mastering_The_Back_Button_With_Javascript
 *
 * @author Sep 2, 2009 Class and js adapted from
 *         http://www.jroller.com/karthikg/entry/modelling_client_side_form_modifications
 */
public class FormModificationDetectorBehavior extends AbstractBehavior
{

    public static final String FORM_MODIFICATIONS_SAVED_JS = "setFormOnRender();";

    public static final String DISABLE_DETECTOR_JS = "setDetectFormModification(false);";

    private static final long serialVersionUID = -4529319874092963800L;

    // Wicket calls this method just after a behavior is bound to
    // a Component and that's nice as we need access to the Form
    // component.

    public void bind(Component component)
    {
        if (!(component instanceof Form))
        {
            throw new WicketRuntimeException(getClass() + " behavior can be bound only to a Form component");
        }
        Form form = (Form) component;

        // This will make sure that the Form emits the
        // HTML 'ID' attribure when rendering. We require the 'ID' in our JS file

        form.setOutputMarkupId(true);

        // Since we require the Form "id" and the 'message' in our JavaScript
        // template, we will use Wicket's TextTemplateHeaderContributor that allows us to
        // perform variable substitutions at runtime. Keep the JS file in the same package location
        // as the behavior.

        // load dependencies
        form.getWebPage().add(JavascriptPackageResource.getHeaderContribution(WicketEventReference.INSTANCE));
        form.getWebPage().add(JavascriptPackageResource.getHeaderContribution(WicketAjaxReference.INSTANCE));

        form.getWebPage().add(
                TextTemplateHeaderContributor.forJavaScript(FormModificationDetectorBehavior.class, "j-script/FormModificationDetector.js",
                        new FormModificationDetectorModel(form.getMarkupId())));
    }

    // TextTemplateHeaderContributor expects to be supplied with a Map
    // as the backing Model. It will use the map to perform variable substitution.

    class FormModificationDetectorModel extends AbstractReadOnlyModel
    {

        private static final long serialVersionUID = -7377791430281874480L;
        private Map<String, String> variables;
        private String formMarkupid;

        FormModificationDetectorModel(String formMarkupid)
        {
            this.formMarkupid = formMarkupid;
        }

        // return the Map as the model object
        public Object getObject()
        {
            if (variables == null)
            {
                // Use Wicket's built-in MiniMap when the
                // number of Map entries are known upfront.
                // A nice way of controlling Wicket's memory usage.
                // Also, while we are on this subject, you might also
                // want to look at the MicroMap class

                variables = new MiniMap(2);

                // provide runtime values for the 'form_id' and 'message'
                variables.put("form_id", formMarkupid);
                variables.put("message", getDisplayMessage());
            }
            return variables;
        }
    };

    /**
     * Get the display message.
     *
     * @return the message displayed in a confirm dialog
     */
    protected String getDisplayMessage()
    {
        return "The form on this page has unsaved changes.";
    }
}


text:
/**
 * Import dependencies.
 */
import {merge} from 'ramda';

/**
 * Import local dependencies.
 */
import {
    ROOT_FETCH_GRAPHQL_QUERY_SUCCEEDED
} from '../actions';

/**
 * Default Query entities state.
 */
const queryDefaultState = {};

/**
 * Export the Query entities store.
 */
export function queryReducer(state = queryDefaultState, action) {
    switch (action.type) {
        case ROOT_FETCH_GRAPHQL_QUERY_SUCCEEDED:
            return merge(state, action.payload.Query);
        default:
            return state;
    }
}


text:
namespace Shader
{
  static unsigned int currentProgramId = 0;

  Program::Program():
    _id(0),
    _shaders(16)
  {
  }

  Program::~Program()
  {
    if (_id != 0)
      oglDeleteProgram(_id);
  }

  bool Program::isInUse() const
  {
    return currentProgramId == _id;
  }

  void Program::use() const
  {
    if (!isInUse())
    {
      currentProgramId = _id;
      oglUseProgram(_id);
      setState(_id);
    }
  }

  void Program::unUse()
  {
    currentProgramId = 0;
    oglUseProgram(0);
  }

  void Program::detachShader(unsigned int shader)
  {
    _shaders.remove(_shaders.find(shader));
    oglDetachShader(_id, shader);
  }

  void Program::attachShader(unsigned int shader)
  {
    _shaders.add(shader);

    if (0 == _id)
    {
      _id = oglCreateProgram();
    }
    assert(_id != 0);
    oglAttachShader(_id, shader);
  }

  void Program::link()
  {
    oglLinkProgram(_id);

#ifdef DEBUG

    GLint wentFine = GL_TRUE;
    oglGetProgramiv(_id, GL_LINK_STATUS, &wentFine);

    GLsizei logsize = 0;
    oglGetProgramiv(_id, GL_INFO_LOG_LENGTH, &logsize);

    if (logsize != 0)
    {
      char * log = (char*) msys_mallocAlloc(logsize + 1);
      oglGetProgramInfoLog(_id, logsize, &logsize, log);
      // ----------------------------------
      // Parsing en dur du message d'erreur
      // En l'absence d'erreur :
      // Sur NVidia il n'y a pas de message
      // Sur ATI ça dit "...linked, ..."
      // Sur Intel ça dit "No errors."
      if (wentFine != GL_TRUE ||
	  strlen(log) > 0 &&
	  strcmp(log, "No errors.") != 0 &&
	  strcmp(log, "Fragment shader(s) linked, vertex shader(s) linked. \n ") != 0)
      {
	DBG("[%s] %s", (wentFine == GL_TRUE ? "OK" : "KO"), log);
      }
      msys_mallocFree(log);
    }

#endif // !DEBUG

  }
}


text:
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

-->

`persistent`は、メッセージを発行してconsumeするための論理的なエンドポイントであるトピックにアクセスするのに役立ちます。Producerはトピックにメッセージを発行し、Consumerはトピックを購読してトピックに発行されたメッセージをconsumeします。

以下のすべての手順とコマンドで、トピック名の構造は次のとおりです

{% include topic.html p="property" c="cluster" n="namespace" t="topic" %}

### トピックのリストの取得

指定されたネームスペースの下に存在するパーシステントトピックのリストを提供します。

#### pulsar-admin

[`list`](../../reference/CliTools#list)コマンドを使ってトピックのリストを取得できます。

```shell
$ pulsar-admin persistent list \
  my-property/my-cluster/my-namespace \
  my-topic
```

#### REST API

{% endpoint GET /admin/persistent/:property/:cluster/:namespace %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace)

#### Java

```java
String namespace = "my-property/my-cluster-my-namespace";
admin.persistentTopics().getList(namespace);
```

### パーミッションの付与

特定のトピックに対して特定のアクションを実行するために、クライアントロールに対するパーミッションを付与します。

#### pulsar-admin

[`grant-permission`](../../reference/CliTools#grant-permission)コマンドを使ってパーミッションを付与できます。

```shell
$ pulsar-admin persistent grant-permission \
  --actions produce,consume --role application1 \
  persistent://test-property/cl1/ns1/tp1 \

```

#### REST API

{% endpoint POST /admin/namespaces/:property/:cluster/:namespace/permissions/:role %}

[詳細](../../reference/RestApi#/admin/namespaces/:property/:cluster/:namespace/permissions/:role)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String role = "test-role";
Set<AuthAction> actions  = Sets.newHashSet(AuthAction.produce, AuthAction.consume);
admin.persistentTopics().grantPermission(destination, role, actions);
```

### パーミッションの取得

[`permissions`](../../reference/CliTools#permissions)コマンドを使ってパーミッションを取得できます。

#### pulsar-admin

TODO: admin

```shell
$ pulsar-admin persistent permissions \
  persistent://test-property/cl1/ns1/tp1 \

{
    "application1": [
        "consume",
        "produce"
    ]
}
```

#### REST API

{% endpoint GET /admin/namespaces/:property/:cluster/:namespace/permissions %}

[詳細](../../reference/RestApi#/admin/namespaces/:property/:cluster/:namespace/permissions)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
admin.persistentTopics().getPermissions(destination);
```

### パーミッションの剥奪

クライアントロールに付与されているパーミッションを剥奪します。

#### pulsar-admin

[`revoke-permission`](../../reference/CliTools#revoke-permission)コマンドを使ってパーミッションを剥奪できます。

```shell
$ pulsar-admin persistent revoke-permission \
  --role application1 \
  persistent://test-property/cl1/ns1/tp1 \

{
    "application1": [
        "consume",
        "produce"
    ]
}
```

#### REST API

{% endpoint DELETE /admin/namespaces/:property/:cluster/:namespace/permissions/:role %}

[詳細](../../reference/RestApi#/admin/namespaces/:property/:cluster/:namespace/permissions/:role)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String role = "test-role";
admin.persistentTopics().revokePermissions(destination, role);
```

### 統計情報の取得

パーティションドではないトピックの現在の統計情報を表示します。

  -   **msgRateIn**: 全てのローカルのPublisherとレプリケーション用のPublisherの発行レートの合計で、1秒あたりのメッセージ数です。

  -   **msgThroughputIn**: 上記と同様ですが、1秒あたりのバイト数です。

  -   **msgRateOut**: 全てのローカルのConsumerとレプリケーション用のConsumerへの配送レートの合計で、1秒あたりのメッセージ数です。

  -   **msgThroughputOut**: 上記と同様ですが、1秒あたりのバイト数です。

  -   **averageMsgSize**: 直近のインターバル内で発行されたメッセージの平均バイトサイズです。

  -   **storageSize**: Ledgerストレージのサイズの合計です。

  -   **publishers**: トピック内の全てのローカルPublisherの一覧です。0または何千もの可能性があります。

  -   **averageMsgSize**: 直近のインターバル内でこのPublisherからのメッセージの平均バイトサイズです。

  -   **producerId**: このトピック上での、このProducerの内部的な識別子です。

  -   **producerName**: クライアントライブラリによって生成されたこのProducerの内部的な識別子です。

  -   **address**: このProducerの接続用のIPアドレスと送信元ポートです。

  -   **connectedSince**: このProducerが作成または最後に再接続したタイムスタンプです。

  -   **subscriptions**: トピックに対してのローカルの全サブスクリプションリストです。

  -   **my-subscription**: このサブスクリプションの名前です (クライアントが定義します) 。

  -   **msgBacklog**: このサブスクリプションのバックログにあるメッセージの数です。

  -   **type**: このサブスクリプションのタイプです。

  -   **msgRateExpired**: TTLのため、サブスクリプションに配信されず破棄されているメッセージのレートです。

  -   **consumers**: このサブスクリプションに接続しているConsumerリストです。

  -   **consumerName**: クライアントライブラリによって生成されたこのConsumerの内部的な識別子です。

  -   **availablePermits**: このConsumerがクライアントライブラリのlistenキューに格納できるメッセージ数です。0はクライアントライブラリのキューがいっぱいであり、receive()はコールされないことを意味します。0でない場合には、このConsumerはメッセージを配送される準備ができています。

  -   **replication**: このセクションは、トピックのクラスタ間でのレプリケーションの統計情報を示します。

  -   **replicationBacklog**: メッセージの送信レプリケーションのバックログです。

  -   **connected**: 送信レプリケータが接続されているかどうかです。

  -   **replicationDelayInSeconds**: 接続されている場合、一番古いメッセージが送信されずに待機している時間です。

  -   **inboundConnection**: このBrokerに対しての、リモートクラスタのPublisher接続におけるそのBrokerのIPとポートです。

  -   **inboundConnectedSince**: リモートクラスタにメッセージを発行するために使われているTCP接続です。もし接続しているローカルのPublisherがいない場合には、この接続は数分後に自動的に閉じられます。

```json
{
  "msgRateIn": 4641.528542257553,
  "msgThroughputIn": 44663039.74947473,
  "msgRateOut": 0,
  "msgThroughputOut": 0,
  "averageMsgSize": 1232439.816728665,
  "storageSize": 135532389160,
  "publishers": [
    {
      "msgRateIn": 57.855383881403576,
      "msgThroughputIn": 558994.7078932219,
      "averageMsgSize": 613135,
      "producerId": 0,
      "producerName": null,
      "address": null,
      "connectedSince": null
    }
  ],
  "subscriptions": {
    "my-topic_subscription": {
      "msgRateOut": 0,
      "msgThroughputOut": 0,
      "msgBacklog": 116632,
      "type": null,
      "msgRateExpired": 36.98245516804671,
      "consumers": []
    }
  },
  "replication": {}
}
```

#### pulsar-admin

[`stats`](../../reference/CliTools#stats)コマンドを使ってトピックの統計情報を取得できます。

```shell
$ pulsar-admin persistent stats \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint GET /admin/persistent/:property/:cluster/:namespace/:destination/stats %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/stats)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
admin.persistentTopics().getStats(destination);
```

### 詳細な統計情報の取得

トピックの詳細な統計情報を表示します。

  -   **entriesAddedCounter**: Brokerがこのトピックを読み込んだ後に発行されたメッセージです。

  -   **numberOfEntries**: トラックされているメッセージの総数です。

  -   **totalSize**: 全てのメッセージの合計ストレージ容量 (バイト) です。

  -   **currentLedgerEntries**: 現在書き込み用に開いているLedgerに書き込まれたメッセージの数です。

  -   **currentLedgerSize**: 現在書き込み用に開いているLedgerに書き込まれたメッセージのサイズ (バイト) です。

  -   **lastLedgerCreatedTimestamp**: 最後のLedgerが作成された時間です。

  -   **lastLedgerCreationFailureTimestamp**: 最後のLedgerが破損した時間です。

  -   **waitingCursorsCount**: "捕捉"され、新しいメッセージが発行されるのを待つカーソルの数です。

  -   **pendingAddEntriesCount**: 完了を待っている書き込みリクエストを持つメッセージの数です。

  -   **lastConfirmedEntry**: 書き込みが完了した最新のメッセージのLedgerID:エントリIDです。エントリIDが-1の場合、Ledgerはオープンしたばかりであるか、現在オープンされているものの書き込みされていません。

  -   **state**: 書き込みのためのLedgerの状態です。LedgerOpenedは発行されたメッセージを保存するためのLedgerがオープンされていることを意味します。

  -   **ledgers**: メッセージを保持しているこのトピックの全てのLedgerの順序付きリストです。

  -   **cursors**: このトピックの全てのカーソルのリストです。トピックの統計情報に表示されたサブスクリプションごとに1つずつ表示されます。

  -   **markDeletePosition**: Ackの位置です。つまり、Subscriberが受信のAckを返した最後のメッセージです。

  -   **readPosition**: メッセージを読むためのSubscriberの最新の位置です。

  -   **waitingReadOp**: サブスクリプションがこのトピックに発行された最新のメッセージを受信し、新しいメッセージが発行されるのを待っている場合は、これが`true`となります。

  -   **pendingReadOps**: BookKeeperに対して処理中の未解決の読み込みリクエストの数です。

  -   **messagesConsumedCounter**: このBrokerがこのトピックをロードしてからこのカーソルがAckしたメッセージの数です。

  -   **cursorLedger**: 現在のmarkDeletePositionを永続的に保存するために使用されるLedgerです。

  -   **cursorLedgerLastEntry**: 現在のmarkDeletePositionを永続的に保存するために使用された最後のエントリIDです。

  -   **individuallyDeletedMessages**: Ackが順不同で返されている場合、markDeletePositionと読み取り位置の間でAckを返されたメッセージの範囲を表示します。

  -   **lastLedgerSwitchTimestamp**: カーソルLedgerがロールオーバーされた最後の時間です。

  -   **state**: カーソルLedgerの状態です。`Open`はmarkDeletePositionの更新を保存するためのLedgerを持つことを意味します。

```json
{
    "entriesAddedCounter": 20449518,
    "numberOfEntries": 3233,
    "totalSize": 331482,
    "currentLedgerEntries": 3233,
    "currentLedgerSize": 331482,
    "lastLedgerCreatedTimestamp": "2016-06-29 03:00:23.825",
    "lastLedgerCreationFailureTimestamp": null,
    "waitingCursorsCount": 1,
    "pendingAddEntriesCount": 0,
    "lastConfirmedEntry": "324711539:3232",
    "state": "LedgerOpened",
    "ledgers": [
        {
            "ledgerId": 324711539,
            "entries": 0,
            "size": 0
        }
    ],
    "cursors": {
        "my-subscription": {
            "markDeletePosition": "324711539:3133",
            "readPosition": "324711539:3233",
            "waitingReadOp": true,
            "pendingReadOps": 0,
            "messagesConsumedCounter": 20449501,
            "cursorLedger": 324702104,
            "cursorLedgerLastEntry": 21,
            "individuallyDeletedMessages": "[(324711539:3134‥324711539:3136], (324711539:3137‥324711539:3140], ]",
            "lastLedgerSwitchTimestamp": "2016-06-29 01:30:19.313",
            "state": "Open"
        }
    }
}
```

#### pulsar-admin

[`stats-internal`](../../reference/CliTools#stats-internal)コマンドを使って、トピックの詳細な統計情報が取得できます。

```shell
$ pulsar-admin persistent stats-internal \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint GET /admin/persistent/:property/:cluster/:namespace/:destination/internalStats %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/internalStats)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
admin.persistentTopics().getInternalStats(destination);
```

### メッセージの閲覧

特定のトピックの特定のサブスクリプションについてN個のメッセージを表示します。

#### pulsar-admin

```shell
$ pulsar-admin persistent peek-messages \
  --count 10 --subscription my-subscription \
  persistent://test-property/cl1/ns1/tp1 \

Message ID: 315674752:0
Properties:  {  "X-Pulsar-publish-time" : "2015-07-13 17:40:28.451"  }
msg-payload
```

#### REST API

{% endpoint GET /admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/position/:messagePosition %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/position/:messagePosition)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String subName = "my-subscription";
int numMessages = 1;
admin.persistentTopics().peekMessages(destination, subName, numMessages);
```

### メッセージのスキップ

特定のトピックの特定のサブスクリプションに対してN個のメッセージをスキップします。

#### pulsar-admin

```shell
$ pulsar-admin persistent skip \
  --count 10 --subscription my-subscription \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint POST /admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/skip/:numMessages %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/skip/:numMessages)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String subName = "my-subscription";
int numMessages = 1;
admin.persistentTopics().skipMessages(destination, subName, numMessages);
```

### 全てのメッセージのスキップ

特定のトピックの特定のサブスクリプションのすべての古いメッセージをスキップします。

#### pulsar-admin

```shell
$ pulsar-admin persistent skip-all \
  --subscription my-subscription \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint POST /admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/skip_all %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/skip_all)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String subName = "my-subscription";
admin.persistentTopics().skipAllMessages(destination, subName);
```

### カーソルのリセット

サブスクリプションのカーソル位置をX分前に記録された位置に戻します。これは本質的にはX分前のカーソルの時間と位置を計算し、その位置でリセットします。

#### pulsar-admin

```shell
$ pulsar-admin persistent reset-cursor \
  --subscription my-subscription --time 10 \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint POST /admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/resetcursor/:timestamp %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/subscription/:subName/resetcursor/:timestamp)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String subName = "my-subscription";
long timestamp = 2342343L;
admin.persistentTopics().skipAllMessages(destination, subName, timestamp);
```

### トピックのルックアップ

特定のトピックに対応しているBrokerのURLを探索します。

#### pulsar-admin

```shell
$ pulsar-admin persistent lookup \
  persistent://test-property/cl1/ns1/tp1 \

 "pulsar://broker1.org.com:4480"
```

#### REST API

{% endpoint GET /lookup/v2/destination/persistent/:property/:cluster/:namespace/:destination %}

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
admin.lookup().lookupDestination(destination);
```

### サブスクリプションの取得

指定されたトピックの全てのサブスクリプション名を表示します。

#### pulsar-admin

```shell
$ pulsar-admin persistent subscriptions \
  persistent://test-property/cl1/ns1/tp1 \

 my-subscription
```

#### REST API

{% endpoint GET /admin/persistent/:property/:cluster/:namespace/:destination/subscriptions %}

[詳細](../../reference/RestApi#/admin/persistent/:property/:cluster/:namespace/:destination/subscriptions)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
admin.persistentTopics().getSubscriptions(destination);
```

### 購読の解除

それ以上のメッセージを処理しないサブスクリプションの登録を解除するのに役立ちます。

#### pulsar-admin

```shell
$ pulsar-admin persistent unsubscribe \
  --subscription my-subscription \
  persistent://test-property/cl1/ns1/tp1 \
```

#### REST API

{% endpoint POST /admin/namespaces/:property/:cluster/:namespace/unsubscribe/:subscription %}

[詳細](../../reference/RestApi#/admin/namespaces/:property/:cluster/:namespace/unsubscribe/:subscription)

#### Java

```java
String destination = "persistent://my-property/my-cluster-my-namespace/my-topic";
String subscriptionName = "my-subscription";
admin.persistentTopics().deleteSubscription(destination, subscriptionName);
```


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.jira.testutils;

import static org.talend.daikon.avro.SchemaConstants.TALEND_IS_LOCKED;

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

import org.apache.avro.Schema;
import org.apache.avro.Schema.Field.Order;
import org.talend.daikon.avro.AvroRegistry;

/**
 * Jira docker image server constants, which are used in tests.
 * One single place to change this properties
 */
public final class JiraTestConstants {

    /**
     * Jira server host and port
     */
    public static final String HOST_PORT;

    /**
     * Incorrect host and port
     */
    public static final String INCORRECT_HOST_PORT = "http://incorrecthost.com";

    /**
     * Jira server user id
     */
    public static final String USER = "root";

    /**
     * Jira server wrong user id
     */
    public static final String WRONG_USER = "wrongUser";

    /**
     * Empty user constant
     */
    public static final String ANONYMOUS_USER = "";

    /**
     * Jira server user id
     */
    public static final String PASS = "123456";

    /**
     * Schemas
     */
    public static final Schema DELETE_SCHEMA;

    public static final Schema INSERT_SCHEMA;

    public static final Schema UPDATE_SCHEMA;

    /**
     * Sets default HOST_PORT in case of running tests from IDE
     */
    static {
        String systemPropertyHost = System.getProperty("jira.host");
        HOST_PORT = systemPropertyHost != null ?  systemPropertyHost : "http://192.168.99.100:8080/";

        AvroRegistry registry = new AvroRegistry();
        Schema stringSchema = registry.getConverter(String.class).getSchema();

        Schema.Field deleteIdField = new Schema.Field("id", stringSchema, null, null, Order.ASCENDING);
        DELETE_SCHEMA = Schema.createRecord("jira", null, null, false, Collections.singletonList(deleteIdField));
        DELETE_SCHEMA.addProp(TALEND_IS_LOCKED, "true");

        Schema.Field insertJsonField = new Schema.Field("json", stringSchema, null, null, Order.ASCENDING);
        INSERT_SCHEMA = Schema.createRecord("jira", null, null, false, Collections.singletonList(insertJsonField));
        INSERT_SCHEMA.addProp(TALEND_IS_LOCKED, "true");

        Schema.Field updateIdField = new Schema.Field("id", stringSchema, null, null, Order.ASCENDING);
        Schema.Field updateJsonField = new Schema.Field("json", stringSchema, null, null, Order.ASCENDING);
        List<Schema.Field> fields = Arrays.asList(updateIdField, updateJsonField);
        UPDATE_SCHEMA = Schema.createRecord("jira", null, null, false, fields);
        UPDATE_SCHEMA.addProp(TALEND_IS_LOCKED, "true");
    }
}


text:
This repository contains code that makes it easy to use an arduino as keyboard with non-US layout.

Its name is composed of letters of the topics involved:
- Arduino
- Keyboard
- USB
- HID
- Language Layout

And because I have seen quite a few people asking for help in this area,
but no generalized ready-to-use solution, I tweaked the result to contain
the name of an allegedly unpleasant place.

## Background

As you might know, some Arduinos (Leonardo or Uno) can easily be used as USB-keyboard
with the Keyboard-library that is included in the IDE or with this 3rd-Party library:
https://github.com/NicoHood/HID
But when you use this with a host (e.g. a Windows PC) that is set to a non-US (e.g. German)
keyboard-layout you will soon find that not all of the simulated keystrokes yield the
expected result. This happens because both libraries use a fixed mapping for 7bit-ASCII
to HID-Codes of an US-Keyboard.

After some research I came to a similar conclusion as
RingoM (https://github.com/NicoHood/HID/issues/22#issuecomment-138728447):
A mapping from UTF-8 to HID-Codes is needed that can be switched depending
on the desired keyboard-layout. And since the code for handling UTF-8 strings
seems to be missing in the standard libraries, I had to implement that, too.

This repository contains the code that I came up with, but there are some caveats:
- I consider this a prototype / proof of concept
- currently it contains only EN_US and DE_DE keyboard-layouts
- currently the code is not really "organized" / object oriented
- I am an Arduino newbie
- My last experience with C++ was in 2005 with MSVC

So, proposals on how to improve the code are welcome!

To compile this, I used the Arduino IDE 1.6.11 and the "HID-Project" library 2.4.3

Update: A quick test with Arduino IDE 1.8.1 and "HID-Project" library 2.4.4 yielded
the same results for the provided sample code.

# akaub
- Android
- Keyboard
- Arduino
- USB
- Bluetooth

The akaub Arduino sketch uses the akuhell code to combine an Arduino that can be used as keyboard
(e.g. Leonardo) and an HC-06 Bluetooth-Module. With this device you can send keystrokes from an Android
smartphone via Bluetooth to a PC using a serial terminal app as if they were typed on a "normal" keyboard.
I used a tiny 32U4 Arduino that has a mikro USB connector and provides solder points for power and serial
lines. Since the 32U4 pins are 3.3V tolerant, I just had to connect RX0 of the Arduino to TX of the
BT-module (and of course VCC and GND - both componets use 5V as VCC) and it worked.

The akuhell-files in this subdirectory are copies of the files in the akuhell directory
(it seems that the Arduino IDE is not able to include files from arbitrary directories).

Build Status:

[![Build status](https://ci.appveyor.com/api/projects/status/dn8aw7grml3f3ry4/branch/master?svg=true)](https://ci.appveyor.com/project/donid/akuhell/branch/master)


text:
def gethelp():
    print('Allowable command-line options include:')
    print('=======================================')
    print()
    print('-help      Prints this list.')
    print()
    print('-vollist   Followed by the path to a file containing a simple')
    print('           list of HathiTrust volume ids.')
    print()
    print('-workjson  Followed by the path to a file containing a json')
    print('           that groups volumes as "works." If this is missing,')
    print('           a vollist must be provided.')
    print()
    print('-o         Followed by path to output folder. Required.')
    print()
    print('-rh        Remove running headers.')
    print()
    print('-genres    Comma-separated list of genres to get.')
    print('           If missing, returns all pages.')
    print()
    print('-pagemeta  Folder containing page-level genre predictions for the')
    print('           volumes you are assembling.')
    print()
    print('-pairroot  The root of the pairtree that stores files.')
    sys.exit(0)

import os, sys, csv, json
import argumentparser
import header
from pagealigner import Alignment

punctuple = ('-', '.', ',', '?', '!', ';', '"', '"', '"', ':', '--', '—', ')', '(', "'", "`", "[", "]", "{", "}")

with open('MainDictionary.txt', encoding = 'utf-8') as file:
    filelines = file.readlines()
lexicon = dict()
for line in filelines:
    line = line.strip()
    fields = line.split('\t')
    lexicon[fields[0]] = int(fields[2])

def parsevols(filepath):
    with open(filepath, encoding = 'utf-8') as f:
        volumelist = [x.strip() for x in f.readlines()]

    return volumelist

def parsejson(filepath):
    with open(filepath, encoding = 'utf-8') as f:
        jsonstring = f.read()

    jobj = json.loads(jsonstring)

    works = list()
    volumes = list()

    # We assume that this json is an object where keys are
    # work ids pointing to lists of volume ids. Our goal is
    # to produce instead a zipped list where unique volume ids
    # are paired with non-unique work ids.

    for workid, vollist in jobj.items():
        for vol in vollist:
            works.append(workid)
            volumes.append(vol)

    return volumes, [x for x in zip(works, volumes)]

def genrefilter(volume, targetgenres):
    ''' Just filters a list of pages to make sure
    they belong to the target genres.
    '''

    filtered = list()

    for page in volume:
        if page[1] in targetgenres:
            filtered.append(page[0])

    return filtered

def slice_list(input, size):
    # This function totally stolen from Paolo Scardine
    # on http://stackoverflow.com/questions/4119070/how-to-divide-a-list-into-n-equal-parts-python
    input_size = len(input)
    slice_size = input_size // size
    remain = input_size % size
    result = []
    iterator = iter(input)
    for i in range(size):
        result.append([])
        for j in range(slice_size):
            result[i].append(next(iterator))
        if remain:
            result[i].append(next(iterator))
            remain -= 1
    return result

def wordfreq(astring):
    global lexicon

    if astring in lexicon:
        return lexicon[astring]
    else:
        return 0

def strip_punctuation(astring):
    global punctuple
    keepclipping = True

    while keepclipping == True and len(astring) > 1:
        keepclipping = False
        if astring.endswith(punctuple):
            astring = astring[:-1]
            keepclipping = True

    keepclipping = True
    while keepclipping == True and len(astring) > 1:
        keepclipping = False
        if astring.startswith(punctuple):
            astring = astring[1:]
            keepclipping = True

    return astring

def rejoin_hyphens(linelist):
    newlist = list()
    prevline = ""

    for i in range(len(linelist)):
        line = linelist[i].strip()
        if len(line) < 1:
            continue

        line = line.lower()
        line = line.replace('\t', ' ')

        if prevline.endswith('-') or prevline.endswith('—'):
            prevtokens = prevline.split()
            thesetokens = line.split()

            if len(prevtokens) > 0 and len(thesetokens) > 0:

                lastword = strip_punctuation(prevtokens[-1])
                nextword = strip_punctuation(thesetokens[0])

                if ((wordfreq(lastword) + wordfreq(nextword)) / 3) < wordfreq(lastword + nextword):
                    prevtokens.pop(-1)
                    thesetokens.pop(0)
                    prevtokens.append(lastword + nextword)
                    prevline = ' '.join(prevtokens)
                    line = ' '.join(thesetokens)

        newlist.append(prevline)
        prevline = line

    newlist.append(prevline)

    return newlist

def output_work(thiswork, workid, removeheaders, outputmode, outputfolder):

    if removeheaders:
        thiswork, removed = header.remove_headers(thiswork)

    if len(thiswork) > 20:
        # very small works are hard to divide evenly.

        linelist = list()
        for page in thiswork:
            linelist.extend(page)

        linelist = rejoin_hyphens(linelist)

        tenchunks = slice_list(linelist, 10)

        outpath = os.path.join(outputfolder, 'malletsource.txt')

        with open(outpath, mode = 'a', encoding = 'utf-8') as f:

            for idx, chunk in enumerate(tenchunks):
                chunkid = workid + '|' + str(idx)
                outline = chunkid + '\t' + 'null' + '\t' + ' '.join(chunk) + '\n'
                f.write(outline)

def main(argdict):

    if '-help' in argdict:
        gethelp()

    if '-vollist' in argdict:
        idstoget = parsevols(argdict['-vollist'])
        workvolseq = [x for x in zip(idstoget, idstoget)]
    elif '-workjson' in argdict:
        idstoget, workvolseq = parsejson(argdict['-workjson'])
    else:
        print('No list of volumes provided. Quitting.')
        sys.exit(0)

    # idstoget is just a list of volume ids
    #
    # the workvolseq is a list of two-tuples where the first
    # element is a workid and the second is a volumeid
    # there is one of these for each volume, and the sequence
    # must be identical to idstoget
    #
    # In the common case where you just want volumes,
    # these will just be pairs of identical volume IDs.

    if "-genre" in argdict:
        targetgenres = set(argdict["-genre"].split(","))
    elif "-g" in argdict:
        targetgenres = set(argdict["-g"].split(","))
    else:
        targetgenres = {'ads', 'back', 'bio', 'dra', 'fic', 'front', 'non', 'poe'}

    if '-pairroot' in argdict:
        pairtree_root = argdict['-pairroot']
    else:
        print('No data source provided. Quitting')

    if '-o' in argdict:
        outputfolder = argdict['-o']
    else:
        print('No output folder provided. Quitting.')

    # default
    outputmode = 'mallet'

    if '-rh' in argdict:
        removeheaders = True
    else:
        removeheaders = False

    # Proceed to align and filter volumes

    alignedvols = Alignment(idstoget, datapath = pairtree_root, datatype = 'pairtree')

    thiswork = list()
    lastworkid = workvolseq[0][0]
    failedvolumes = list()

    i = 0

    for volid, successflag, volume in alignedvols:
        workid = workvolseq[i][0]
        targetvolid = workvolseq[i][1]
        i += 1

        if successflag != 'success':
            failedvolumes.append((volid, successflag))
            continue

        if volid != targetvolid:
            print('Volume alignment error; fatal.')
            sys.exit(0)

        filteredvol = genrefilter(volume, targetgenres)

        if workid == lastworkid:
            thiswork.extend(filteredvol)

        else:
            output_work(thiswork, lastworkid, removeheaders, outputmode, outputfolder)
            thiswork = list()
            lastworkid = workid
            thiswork.extend(filteredvol)

    with open('failedvolumes.tsv', mode = 'w', encoding = 'utf-8') as f:
        for volume, flag in failedvolumes:
            f.write(volume + '\t' + flag + '\n')

if __name__ == '__main__':

    args = sys.argv
    argdict = argumentparser.simple_parse(args)
    main(argdict)


text:
from spectral.spectral import BandInfo
from spectral.algorithms.resampling import build_fwhm, normal_integral
from spectral.algorithms.resampling import overlap, ranges_overlap
import numpy

def create_resampling_matrix(centers1, centers2):
    """
    Returns a resampling matrix to convert spectra from one band discretization
    to another.  Arguments are the band centers and full-width half maximum
    spectral response for the original and new band discretizations.
    """
    fwhm1 = None
    fwhm2 = None
    if isinstance(centers1, BandInfo):
        fwhm1 = centers1.bandwidths
        centers1 = centers1.centers
    if isinstance(centers2, BandInfo):
        fwhm2 = centers2.bandwidths
        centers2 = centers2.centers
    if fwhm1 is None:
        fwhm1 = build_fwhm(centers1)
    if fwhm2 is None:
        fwhm2 = build_fwhm(centers2)

    sqrt_8log2 = 2.3548200450309493

    n_centers1 = len(centers1)
    n_centers2 = len(centers2)
    bounds1 = [[centers1[i] - fwhm1[i] / 2.0, centers1[i] + fwhm1[i] /
                2.0] for i in range(n_centers1)]
    bounds2 = [[centers2[i] - fwhm2[i] / 2.0, centers2[i] + fwhm2[i] /
                2.0] for i in range(n_centers2)]

    shape = numpy.zeros([n_centers2, n_centers1])

    j_start = 0
    nan = float('nan')
    for i in range(n_centers2):
        stdev = fwhm2[i] / sqrt_8log2
        j = j_start

        # Find the first original band that overlaps the new band
        while j < n_centers1 and bounds1[j][1] < bounds2[i][0]:
            j += 1

        if j == n_centers1:
            print(('No overlap for target band %d (%f / %f)' % (
                i, centers2[i], fwhm2[i])))
            shape[i, 0] = nan
            continue

        matches = []

        # Get indices for all original bands that overlap the new band
        while j < n_centers1 and bounds1[j][0] < bounds2[i][1]:
            if ranges_overlap(bounds1[j], bounds2[i]):
                matches.append(j)
            j += 1

        # Put NaN in first element of any row that doesn't produce a band in
        # the new schema.
        if not matches:
            print(('No overlap for target band %d (%f / %f)' % (
                i, centers2[i], fwhm2[i])))
            shape[i, 0] = nan
            continue

        # Determine the weights for the original bands that overlap the new
        # band. There may be multiple bands that overlap or even just a single
        # band that only partially overlaps.  Weights are normoalized so either
        # case can be handled.

        overlaps = [overlap(bounds1[k], bounds2[i]) for k in matches]
        contribs = numpy.zeros(len(matches))
        count = 0.
        for k in range(len(matches)):
            (first, second) = [(x - centers2[i]) / stdev for x in overlaps[k]]
            integral = normal_integral(first, second)
            contribs[k] = integral
            count += integral
        contribs = contribs / count
        for k in enumerate(matches): #range(len(matches)):
            shape[i, matches[k[0]]] = contribs[k[0]]
    return shape


text:
var browserify = require( 'browserify' );
var fs = require( 'fs' );

module.exports = function( done ) {

  var b = browserify( [ __dirname + '/../frontend/index.js' ] );

  var out = fs.createWriteStream( __dirname + '/../frontend/bundle.js' );

  b.bundle()
  .on( 'end', done )
  .pipe( out );
};


text:
@interface FeedDetailsModuleViewControllerTests : XCTestCase

@property (nonatomic, strong) FeedDetailsModuleViewController *controller;

@property (nonatomic, strong) id mockOutput;

@end

@implementation FeedDetailsModuleViewControllerTests

#pragma mark - Настройка окружения для тестирования

- (void)setUp
{
    [super setUp];

    self.controller = [[FeedDetailsModuleViewController alloc] init];

    self.mockOutput = OCMProtocolMock(@protocol(FeedDetailsModuleViewOutput));

    self.controller.output = self.mockOutput;
}

- (void)tearDown
{
    self.controller = nil;

    self.mockOutput = nil;

    [super tearDown];
}

#pragma mark - Тестирование жизненного цикла

- (void)testThatControllerNotifiesPresenterOnDidLoad
{
    // given

    // when
    [self.controller viewDidLoad];

    // then
    OCMVerify([self.mockOutput didTriggerViewReadyEvent]);
}

#pragma mark - Тестирование методов интерфейса

#pragma mark - Тестирование методов FeedDetailsModuleViewInput

@end


text:
@interface AKAChildBindingContext: NSObject<AKABindingContextProtocol>

#pragma mark - Initialization

+ (req_instancetype)          bindingContextWithParent:(nonnull id<AKABindingContextProtocol>)bindingContext
                               dataContextProperty:(req_AKAProperty)dataContextProperty;

+ (req_instancetype)           bindingContextWithParent:(nonnull id<AKABindingContextProtocol>)bindingContext
                                        dataContext:(opt_id)dataContext;

+ (req_instancetype)          bindingContextWithParent:(nonnull id<AKABindingContextProtocol>)bindingContext
                                           keyPath:(opt_NSString)keyPath;

#pragma mark - Properties

@property(nonatomic, weak, readonly, nullable) id                             dataContext;
@property(nonatomic, weak, readonly, nullable) id<AKABindingContextProtocol>  parent;

@end


text:
namespace GameCore
{
	void InitializeApp( IGameApp& game )
	{
		Graphics::Init();

		Input::Instance();

		game.Start();
	}

	void TerminateApp( IGameApp& game )
	{
		Graphics::Terminate();

		game.CleanUp();
	}

	bool UpdateApp( IGameApp& game )
	{

		Input::Instance()->Update();

		game.Update(1.f/30.f);
		game.RenderScene();

		Graphics::Present();

		return !game.IsDone();
	}

	LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
	{
		switch (message)
		{
			case WM_PAINT:
			{
				PAINTSTRUCT ps;
				HDC hdc = BeginPaint( hWnd, &ps );
				EndPaint( hWnd, &ps );
				break;
			}

			case WM_SIZE:
				Graphics::Resize(wParam & 0xFFFFFF, lParam >> 16);
			case WM_DESTROY:
				PostQuitMessage(0);
				break;

			default:
				return DefWindowProc(hWnd, message, wParam, lParam);
		}

		return 0;
	}

	HWND g_hWnd = nullptr;

	void RunApp( IGameApp& app, const wchar_t* className )
	{
		HINSTANCE hInst = GetModuleHandle( 0 );

		WNDCLASSEX wcex;
		wcex.cbSize = sizeof(WNDCLASSEX);
		wcex.style = CS_HREDRAW | CS_HREDRAW;
		wcex.lpfnWndProc = WndProc;
		wcex.cbClsExtra = 0;
		wcex.cbWndExtra = 0;
		wcex.hInstance = hInst;
		wcex.hIcon = LoadIcon( hInst, IDI_APPLICATION );
		wcex.hCursor = LoadCursor( nullptr, IDC_ARROW );
		wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		wcex.lpszMenuName = nullptr;
		wcex.hIconSm = LoadIcon( hInst, IDI_APPLICATION );
		wcex.lpszClassName = className;

		ASSERT( 0 != RegisterClassEx( &wcex ), "Unable to register a window" );

		RECT rect = { 0, 0, DEFAULT_RECT_WIDTH, DEFAULT_RECT_HEIGHT };
		AdjustWindowRect( &rect, WS_OVERLAPPEDWINDOW, false );
		g_hWnd = CreateWindow( className, className, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, nullptr, nullptr, hInst, nullptr );

		ASSERT(g_hWnd != 0 );

		InitializeApp(app);

		ShowWindow(g_hWnd, SW_SHOWDEFAULT );

		do
		{
			MSG msg = {};
			while (PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ))
			{
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
			if (msg.message == WM_QUIT)
				break;
		} while (UpdateApp(app));	// Returns false to quit loop

		TerminateApp( app );
	}
}