text:
//------------------------------------------------------------------------------
// <copyright file="Device.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Text;

namespace Microsoft.Azure.Kinect.Sensor
{
    /// <summary>
    /// Represents an Azure Kinect device.
    /// </summary>
    public class Device : IDisposable
    {
        // Cache these values so we don't need to re-marshal them for each
        // access since they are immutable.
        private string serialNum = null;
        private HardwareVersion version = null;

        // The native handle to the device.
        private NativeMethods.k4a_device_t handle;

        // To detect redundant calls to Dispose
        private bool disposedValue = false;

        private Device(NativeMethods.k4a_device_t handle)
        {
            // Hook the native allocator and register this object.
            // .Dispose() will be called on this object when the allocator is shut down.
            Allocator.Singleton.RegisterForDisposal(this);

            this.handle = handle;
        }

        /// <summary>
        /// Gets the devices serial number.
        /// </summary>
        public string SerialNum
        {
            get
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Device));
                    }

                    if (this.serialNum != null)
                    {
                        return this.serialNum;
                    }
                    else
                    {
                        // Determine the required string size
                        UIntPtr size = new UIntPtr(0);
                        if (NativeMethods.k4a_device_get_serialnum(this.handle, null, ref size) != NativeMethods.k4a_buffer_result_t.K4A_BUFFER_RESULT_TOO_SMALL)
                        {
                            throw new InvalidOperationException($"Unexpected internal state calling {nameof(NativeMethods.k4a_device_get_serialnum)}");
                        }

                        // Allocate a string buffer
                        StringBuilder serialno = new StringBuilder((int)size.ToUInt32());

                        // Get the serial number
                        AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_serialnum(this.handle, serialno, ref size));

                        this.serialNum = serialno.ToString();

                        return this.serialNum;
                    }
                }
            }
        }

        /// <summary>
        /// Gets the depth mode the device is currently set to.
        /// </summary>
        public DepthMode CurrentDepthMode { get; private set; } = DepthMode.Off;

        /// <summary>
        /// Gets the color resolution the device is currently set to.
        /// </summary>
        public ColorResolution CurrentColorResolution { get; private set; } = ColorResolution.Off;

        /// <summary>
        /// Gets a value indicating whether gets the Sync In jack is connected.
        /// </summary>
        public bool SyncInJackConnected
        {
            get
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Device));
                    }

                    bool sync_in = default;
                    bool sync_out = default;
                    AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_sync_jack(
                        this.handle,
                        out sync_in,
                        out sync_out));

                    return sync_in;
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether gets the Sync Out jack is connected.
        /// </summary>
        public bool SyncOutJackConnected
        {
            get
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Device));
                    }

                    bool sync_in = default;
                    bool sync_out = default;
                    AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_sync_jack(
                        this.handle,
                        out sync_in,
                        out sync_out));

                    return sync_out;
                }
            }
        }

        /// <summary>
        /// Gets the hardware version of the device.
        /// </summary>
        public HardwareVersion Version
        {
            get
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Device));
                    }

                    if (this.version != null)
                    {
                        return this.version;
                    }

                    NativeMethods.k4a_hardware_version_t nativeVersion = default;
                    AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_version(
                        this.handle,
                        out nativeVersion));

                    this.version = nativeVersion.ToHardwareVersion();
                    return this.version;
                }
            }
        }

        /// <summary>
        /// Gets the number of currently connected devices.
        /// </summary>
        /// <returns>The number of connected devices.</returns>
        public static int GetInstalledCount()
        {
            return (int)NativeMethods.k4a_device_get_installed_count();
        }

        /// <summary>
        /// Opens an Azure Kinect device.
        /// </summary>
        /// <param name="index">Index of the device to open if there are multiple connected.</param>
        /// <returns>A Device object representing that device.</returns>
        /// <remarks>The device will remain opened for exclusive access until the Device object is disposed.</remarks>
        public static Device Open(int index = 0)
        {
            NativeMethods.k4a_device_t handle = default;
            AzureKinectOpenDeviceException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_open((uint)index, out handle));
            return new Device(handle);
        }

        /// <summary>
        /// Gets the calibration of the device.
        /// </summary>
        /// <param name="depthMode">Depth mode for the calibration.</param>
        /// <param name="colorResolution">Color camera resolution for the calibration.</param>
        /// <returns>Calibration object.</returns>
        public Calibration GetCalibration(DepthMode depthMode, ColorResolution colorResolution)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                Calibration calibration = default;
                AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_calibration(this.handle, depthMode, colorResolution, out calibration));
                return calibration;
            }
        }

        /// <summary>
        /// Gets the calibration of the device for the current operating mode.
        /// </summary>
        /// <returns>Calibration object.</returns>
        public Calibration GetCalibration()
        {
            if (this.CurrentColorResolution == ColorResolution.Off && this.CurrentDepthMode == DepthMode.Off)
            {
                throw new AzureKinectException("Cameras not started");
            }

            return this.GetCalibration(this.CurrentDepthMode, this.CurrentColorResolution);
        }

        /// <summary>
        /// Gets the device raw calibration data.
        /// </summary>
        /// <returns>The raw data can be stored off-line for future use.</returns>
        public byte[] GetRawCalibration()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                // Determine the required calibration size
                UIntPtr size = new UIntPtr(0);
                if (NativeMethods.k4a_device_get_raw_calibration(this.handle, null, ref size) != NativeMethods.k4a_buffer_result_t.K4A_BUFFER_RESULT_TOO_SMALL)
                {
                    throw new AzureKinectException($"Unexpected result calling {nameof(NativeMethods.k4a_device_get_raw_calibration)}");
                }

                // Allocate a string buffer
                byte[] raw = new byte[size.ToUInt32()];

                // Get the raw calibration
                AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_get_raw_calibration(this.handle, raw, ref size));

                return raw;
            }
        }

        /// <summary>
        /// Reads a sensor capture.
        /// </summary>
        /// <param name="timeout">Time to wait for a capture.</param>
        /// <returns>A Capture object holding image data.</returns>
        /// <remarks>
        /// Gets the next capture in the streamed sequence of captures from the camera.
        /// If a new capture is not currently available, this function will block until the timeout is reached.
        /// The SDK will buffer at least two captures worth of data before dropping the oldest capture.
        /// Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average.
        /// </remarks>
        public Capture GetCapture(TimeSpan timeout)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                using (LoggingTracer tracer = new LoggingTracer())
                {
                    NativeMethods.k4a_wait_result_t result = NativeMethods.k4a_device_get_capture(this.handle, out NativeMethods.k4a_capture_t capture, (int)timeout.TotalMilliseconds);

                    if (result == NativeMethods.k4a_wait_result_t.K4A_WAIT_RESULT_TIMEOUT)
                    {
                        throw new TimeoutException("Timed out waiting for capture");
                    }

                    AzureKinectException.ThrowIfNotSuccess(tracer, result);

                    if (capture.IsInvalid)
                    {
                        throw new AzureKinectException("k4a_device_get_capture did not return a valid capture handle");
                    }

                    return new Capture(capture);
                }
            }
        }

        /// <summary>
        /// Reads a sensor capture.
        /// </summary>
        /// <returns>A Capture object holding image data.</returns>
        /// <remarks>
        /// Gets the next capture in the streamed sequence of captures from the camera.
        /// If a new capture is not currently available, this function will block until the timeout is reached.
        /// The SDK will buffer at least two captures worth of data before dropping the oldest capture.
        /// Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average.
        /// </remarks>
        public Capture GetCapture()
        {
            return this.GetCapture(TimeSpan.FromMilliseconds(-1));
        }

        /// <summary>
        /// Reads an IMU sample from the device.
        /// </summary>
        /// <param name="timeout">Time to wait for an IMU sample.</param>
        /// <returns>The next unread IMU sample from the device.</returns>
        /// <remarks>Gets the next sample in the streamed sequence of IMU samples from the device.
        /// If a new sample is not currently available, this function will block until the timeout is reached.
        /// The API will buffer at least two camera capture intervals worth of samples before dropping the oldest sample. Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average.
        /// </remarks>
        public ImuSample GetImuSample(TimeSpan timeout)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                using (LoggingTracer tracer = new LoggingTracer())
                {
                    NativeMethods.k4a_imu_sample_t sample = new NativeMethods.k4a_imu_sample_t();
                    NativeMethods.k4a_wait_result_t result = NativeMethods.k4a_device_get_imu_sample(this.handle, sample, (int)timeout.TotalMilliseconds);

                    if (result == NativeMethods.k4a_wait_result_t.K4A_WAIT_RESULT_TIMEOUT)
                    {
                        throw new TimeoutException("Timed out waiting for IMU sample");
                    }

                    AzureKinectException.ThrowIfNotSuccess(tracer, result);

                    return sample.ToImuSample();
                }
            }
        }

        /// <summary>
        /// Reads an IMU sample from the device.
        /// </summary>
        /// <returns>The next unread IMU sample from the device.</returns>
        /// <remarks>Gets the next sample in the streamed sequence of IMU samples from the device.
        /// If a new sample is not currently available, this function will block until one is available.
        /// The API will buffer at least two camera capture intervals worth of samples before dropping the oldest sample. Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average.
        /// </remarks>
        public ImuSample GetImuSample()
        {
            return this.GetImuSample(TimeSpan.FromMilliseconds(-1));
        }

        /// <summary>
        /// Get the Azure Kinect color sensor control value.
        /// </summary>
        /// <param name="command">Color sensor control command.</param>
        /// <returns>The value of the color control option.</returns>
        public int GetColorControl(ColorControlCommand command)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                return this.GetColorControl(command, out ColorControlMode mode);
            }
        }

        /// <summary>
        /// Get the Azure Kinect color sensor control value.
        /// </summary>
        /// <param name="command">Color sensor control command.</param>
        /// <param name="mode">The mode of the color control option.</param>
        /// <returns>The value of the color control option.</returns>
        public int GetColorControl(ColorControlCommand command, out ColorControlMode mode)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                using (LoggingTracer tracer = new LoggingTracer())
                {
                    AzureKinectException.ThrowIfNotSuccess(tracer, NativeMethods.k4a_device_get_color_control(this.handle, command, out mode, out int value));
                    return value;
                }
            }
        }

        /// <summary>
        /// Sets the Azure Kinect color sensor control value.
        /// </summary>
        /// <param name="command">Color sensor control command.</param>
        /// <param name="mode">The mode of the color control option.</param>
        /// <param name="value">The value of the color control option.</param>
        public void SetColorControl(ColorControlCommand command, ColorControlMode mode, int value)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_set_color_control(this.handle, command, mode, value));
            }
        }

        /// <summary>
        /// Starts color and depth camera capture.
        /// </summary>
        /// <param name="configuration">The configuration we want to run the device in.</param>
        public void StartCameras(DeviceConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                NativeMethods.k4a_device_configuration_t nativeConfig = configuration.GetNativeConfiguration();
                AzureKinectStartCamerasException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_start_cameras(this.handle, ref nativeConfig));

                this.CurrentDepthMode = configuration.DepthMode;
                this.CurrentColorResolution = configuration.ColorResolution;
            }
        }

        /// <summary>
        /// Stops the color and depth camera capture.
        /// </summary>
        public void StopCameras()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                NativeMethods.k4a_device_stop_cameras(this.handle);

                this.CurrentDepthMode = DepthMode.Off;
                this.CurrentColorResolution = ColorResolution.Off;
            }
        }

        /// <summary>
        /// Starts the IMU sample stream.
        /// </summary>
        public void StartImu()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                AzureKinectStartImuException.ThrowIfNotSuccess(() => NativeMethods.k4a_device_start_imu(this.handle));
            }
        }

        /// <summary>
        /// Stops the IMU sample stream.
        /// </summary>
        public void StopImu()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Device));
                }

                NativeMethods.k4a_device_stop_imu(this.handle);
            }
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(disposing) below.
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>True</c> to release both managed and unmanaged resources; <c>False</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposedValue)
            {
                if (disposing)
                {
                    Allocator.Singleton.UnregisterForDisposal(this);

                    this.handle.Close();
                    this.handle = null;

                    this.disposedValue = true;
                }
            }
        }
    }
}


text:
/**
 * session management
 *
 * adapted from:
 *  https://github.com/mgesmundo/restify-session/blob/master/lib/restify-session.js
 *  @class node_modules.restify_session
 *  @author Marcello Gesmundo
 */

 'use strict';
module.exports = function(config) {
  // namespace
  var session = {};
  var utils   = require('object_utils');
  var Random  = require('secure-rnd');
  var rnd     = new Random();
  var Cookies = require('cookies');
  var fs      = require('fs');
  var toJSON  = require('./tojson');

// need this to create tmp folder per sid
  var Collection = require('./collection')
  var path = require('path')

  // where we store active sessions
  session.sessions = {};
  session.timeouts = {};

  /**
   * @ignore
   * @private
   */
  session.name = 'rest3d';

  /**
   * @ignore
   * @private
   */
  session.merge = utils.merge;

  config = config || {};
  /**
   * Configuration
   */
  session.config = {
    /**
     * @cfg {Integer} ttl=600 The time to live for the session in seconds
     */
    ttl: 600, // 10min
    /**
     * @cfg {Boolean} debug=true true to enable debug session
     */
    debug: false,
    /**
     * @cfg {Object} logger=console The logger. If you use winston set your desired log level and set debug = true.
     */
    logger: console,
    /**
     * @cfg {Integer} sidLength=40 The number of characters to create the session ID.
     */
    sidLength: 40,
    /**
     * @cfg {Boolean} persist=false Persistence of session
     * If persist is false, the session will expire after the ttl config.
     * If persist is true, the session will never expire and ttl config will be ignored.
     */
    persist: false,

    /**
     * @cfg {String} sidHeader='Session-Id' The Header section name to store the session identifier
     */
    sidHeader: 'x-session-id',

    /**
     * @cfg {Boolean} cookies=true Store the session in a cookie
     */
    cookies: true,

    /**
     * @cfg {Boolean} db = database driver oject, or null if no database is connected
     */
    db: null
  };

  // merge new config with default config
  session.merge(session.config, config);

  if ('function' !== typeof session.config.logger.debug) {
    session.config.logger.debug = session.config.logger.log;
  }
  if ('function' !== typeof session.config.logger.error) {
    session.config.logger.error = session.config.logger.log;
  }
  if ('function' !== typeof session.config.logger.info) {
    session.config.logger.info = session.config.logger.log;
  }

  var cfg = session.config;

  var isNull = utils.isNull;

  /**
   * Create session identifier
   *
   * @param {Function} callback Function called when the identifier is created
   * @return {callback(err, sid)} The callback to execute as result
   * @param {String} callback.err Error if occurred
   * @param {String} callback.sid session identifier
   * @private
   */
  var createSid = function(callback) {
    var chars  = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz',
        codes  = [],
        cLen   = chars.length,
        len    = cfg.sidLength,
        sid    = '',
        i      = 0,
        rNum;

    var cb = callback;
    codes.length = cLen;

    // generate secure randoms
    rnd(codes);

    for ( i = 0; i < len; i++) {
      rNum = Math.floor(codes[i] * cLen / 255);
      sid += chars.substring(rNum, rNum + 1);
    }

    if (session.sessions[sid] != undefined) {
          createSid(cb);
    } else {
      if (cfg.db) {
        console.log('createSid - check for sid='+sid)
        cfg.db.loadCookie(sid, function (err,res){
          if (err) {
            console.log('createSid new Key='+sid);
            session.sessions[sid]={};
            cb(undefined,sid);
          } else {
            console.log('sid collision - trying again')
            createSid(cb);
          }
        })
      } else {
        console.log("Created sessionID="+sid);
        session.sessions[sid]={};
        cb(undefined,sid);
      }
    }
  };

  /**
   * Save session data
   *
   * @param {String} sid session identifier
   * @param {Object} data session data
   * @param {Function} callback Function called when the session is saved
   * @return {callback(err, status)} The callback to execute as result
   * @param {String} callback.err Error if occurred
   * @param {String} callback.status Result from Redis query
   */
  session.save = function(sid, data, cb) {
    console.log('session.save sid='+sid)
    if (isNull(sid)) {
      cb && cb.call(session, 'no sid given', undefined);
      return;
    }
    session.sessions[sid]=data;
    if (cfg.db) {
      cfg.db.saveCookie(sid,data, function (err,res){
        if (err) {
          console.log('Error save Cookie ='+err);
          return callback.call(session, err, null);
        } else {
          session.refresh(sid,function(err,res) {
            if (err) {
              console.log('session.save -> refresh error='+err)
            } else {
              //console.log('session.save -> refreshed session='+res);
            }
             cb && cb.call(session, undefined, data);
          })
        }
      })
    } else {
       session.refresh(sid,function(err,res) {
            if (err) {
              console.log('session.save -> refresh error='+err)
            } else {
              //console.log('session.save -> refreshed session='+res);
            }
             cb && cb.call(session, undefined, data);
          })
    }

  };

  /**
   * Load session data
   *
   * @param {String} sid session identifier
   * @param {Function} callback Function called when the session is loaded
   * @return {callback(err, data)} The callback to execute as result
   * @param {String} callback.err Error if occurred
   * @param {Object} callback.data session data
   */
  session.load = function(sid, cb) {
    if (isNull(sid)) {
      cb && cb.call(session, 'no sid given', undefined);
      return;
    }
    var data = session.sessions[sid];

    if (data === undefined) {
      if (cfg.db) {
        cfg.db.loadCookie(sid, function (err,res){
          if (err) {
            console.log('session.load Error load Cookie ['+err+']');
            cb && cb.call(session, err, null);
          } else if (!res) {
            err = 'session.load load Cookie returned empty cookie';
            console.log(err);
            cb && cb.call(session, err, null);
          } else {
            console.log('session.load load Cookie returned ['+toJSON(res)+']')
            cb && cb.call(session, undefined, res);
          }
        })
      } else {
        var err='session.js cannot load sessionID='+sid;
        cb && cb.call(session, err, data);
      }
    } else {
      cb && cb.call(session, undefined, data);
    }
  };

  /**
   * Update the ttl for the session
   *
   * @param {String} sid session identifier
   * @param {Function} callback Function called when the session is refreshed
   * @return {callback(err, active)} The callback to execute as result
   * @param {String} callback.err Error if occurred
   * @param {Boolean} callback.active True if the sid is active (not expired)
   */
  session.refresh = function(sid, cb) {
    if (isNull(sid)) {
      cb && cb.call(session, 'no sid given', false);
      return null;
    }
    if (cfg.persist) {
      cb && cb.call(session, undefined, sid);
      return null;
    }

    var err=undefined;
    if (session.timeouts[sid] != undefined){
      clearTimeout(session.timeouts[sid] )
      //console.log('refresh -> update timeout for sid='+sid)
    } else {
      //console.log('refresh -> new timeout for sid='+sid)
    }
                                        // closure to pass sid value
    session.timeouts[sid] = setTimeout(function(){session.destroy.call(session,sid)},  cfg.ttl*1000 );

    cb && cb.call(session, err, sid);
    return session;
  };

  /**
   * Get all session identifier
   *
   * @param {Function} callback Function called when the session identifiers are loaded
   * @return {callback(err, keys)} The callback to execute as result
   * @param {String} callback.err Error if occurred
   * @param {Array} callback.keys All valid session identifiers
   * @private
   */
  session.getAllKeys = function(callback) {
    if (!cfg.debug) {
      cfg.logger.debug(session.name + ': unable to get all session identifiers when not in debug mode');
      if (callback) {
        callback.call(session, 'unable to get all session identifiers when not in debug mode');
      }
      return;
    }
    var keys = Object.keys(session.sessions);
    if (callback)
      callback.call(session, err, keys);

  };

  /**
   * Destroy a session
   *
   * @param {String} sid session identifier
   * @param {Function} callback Function called when finishing
   * @return {callback(err, status)} The callback to execute as result
   * @param {String} callback.err Returned error if occurred
   * @param {String} callback.status Returned status code from Redis
   * @private
   */

  // note cb is often null, this function called in a timeOut
  session.destroy = function(sid, cb) {

    var self=this;

    if (isNull(sid)) return done('no sid given');

    if (self.timeouts[sid] !== undefined){
      clearTimeout(self.timeouts[sid]);
      delete self.timeouts[sid];
    }

    var session = self.sessions[sid];
    if (!session) return deleteCookie(undefined);

    var done = function(error) {
      self.sessions[sid] && delete self.sessions[sid];
      cb && cb.call(self, error, undefined);
    }

    var deleteCookie = function(error){
      if (error) return done(error)
      if (cfg.db) {
        cfg.db.delCookie(sid, function (err,res){
          if (err) {
            console.log('Error delete Cookie ='+err);
            return done(undefined); // no need to alert client
          } else {
            console.log('key removed cookie ['+sid+']')
             return done(undefined);
          }
        })
      }
    }

   if (session.tmpdir)
     return self.delTMP(session.tmpdir, deleteCookie);
    deleteCookie(undefined);
  };

  /**
   * Destroy all sessions
   *
   * @param {Function} callback Function called when finishing
   * @return {callback(status)} The callback to execute as result
   * @param {String} callback.err Returned error if occurred
   * @param {String} callback.status Returned status code from Redis
   * @private
   */
  session.destroyAll = function(callback) {
    if (!cfg.debug) {
      cfg.logger.debug(session.name + ': unable to destroy all sessions when not in debug mode');
      if (callback) {
        callback.call(session, 'unable to destroy all sessions when not in debug mode');
      }
      return;
    }
    session.sessions={};
    for (var timeout in session.timeouts){
      clearTimeout(session.timeouts[timeout]);
      delete session.timeouts[timeout];
    }
    if (callback)
      callback.call(session, undefined, true);
  };

  /**
   * Set data in session object to use in other middlewares below this
   *
   * @param {String} sid The session identifier
   * @param {{sid: String, ...}} data The data to store in session
   * @param {{session: data, ...}} req Client request with new __session__ property
   * containing session data
   * @param {Object} res Server response
   * @param {Function} next Calback to execute at the end of saving
   */
  var setSessionData = function(sid, data, req, res, next) {

  if (isNull(data)) {
    data = {};
  }
  // important! this is used by other modules to get the current sid
  data.sid  = sid;

  req.session = data;
  //console.log('session.js stored data='+toJSON(data)+' in req.session');
  res.setHeader(cfg.sidHeader.toLowerCase(), sid);//add header

  if (cfg.cookies) {
    var jar = new Cookies(req, res);
    jar.set(session.name,sid);//add cookie
  }

  next && next(data);

  };

  /**
   * Manage session in http requests
   *
   * @param {Object} req Request from client
   * @param {Object} res Response from server
   * @param {Function} next Next function to execute in server
   */
  session.sessionManager = function (req, res, next) {

    if (cfg.debug) {

      cfg.logger.log('SessionManager !!')
      cfg.logger.log(session.name + ': request url: ' + req.url);
    }

    var reqSid = req.headers[cfg.sidHeader.toLowerCase()];
    var rest3dCookie=null;
    if (cfg.cookies) {
      var jar = new Cookies(req,res);
      if (jar)
         rest3dCookie = jar.get(session.name);
    }
    reqSid = reqSid || rest3dCookie;

    session.load(reqSid, function(loadErr, data){
      if (loadErr) {
        if (cfg.debug)
          cfg.logger.log('creating new Key')
        createSid(function(createErr, sid) {
          if (!createErr) {
            console.log('sessionManager -> addSessionData:'+sid);
            setSessionData(sid, {}, req, res, function(data){
              session.save(sid, data, function(err,data) {
                if (err)
                  console.log('sessionManager session.save error='+err)
                next();
              })
            })

          } else {
            console.log('sessionManager error createSid='+sid)
            next();
          }
        });
      } else {
        if (cfg.debug)
          cfg.logger.log('sessionManager found Key ='+reqSid);
        session.refresh(reqSid,function(err,resp) {
          setSessionData(reqSid, data, req, res, next);
        })

      }

    });
  }

  return session;
};

redpajama_set_name: RedPajamaGithub


text:
from funcs import *
from config import *

#
# License 3 clause BSD
# https://github.com/UKParlDataSheets/UKParlDataSheets-Scripts
#

go(CONFIG, False)


text:
local defaultdamageweight = 1.58;
local defaultmasteryweight = .56;
local defaultcritweight = .62;
local defaulthasteweight = .52;
local defaultAttackPowerweight = .33;

local defaultOffsetPlagues = 7000;

local firstLoadPerGameStart = true;
local maxentries = 6;
local defaultbufftable = {}

parentaddon = {};

table.insert(defaultbufftable, {"Velocity", "Haste", 3278, 1});

local defaultclbufftable = {}

--class abilities
table.insert(defaultclbufftable, {32182, "Haste", 30, 1});      -- Heroism
table.insert(defaultclbufftable, {2825, "Haste", 30, 1});       -- Bloodlust
table.insert(defaultclbufftable, {80353, "Haste", 30, 1});      -- Time Warp
table.insert(defaultclbufftable, {90355, "Haste", 30, 1});      -- Ancient Hysteria
table.insert(defaultclbufftable, {114207, "Crit", 12000, 1});	-- Skullbanner
table.insert(defaultclbufftable, {57934, "Damage", 15, 1});		-- Tricks of the Trade (Rogue)
table.insert(defaultclbufftable, {49016, "Damage", 10, 1});      -- Unholy Frenzy (Unholy Death Knight)

--race abilities
table.insert(defaultclbufftable, {26297, "Haste", 20, 1});      -- Berserking

--profession abilities
table.insert(defaultclbufftable, {96230, "Strength", 1920, 1});      -- Synapse Spring
table.insert(defaultclbufftable, {121279, "Haste", 2880, 1});   	-- Lifeblood
table.insert(defaultclbufftable, {55777, "AttackPower", 4000, 1});  -- Swordguard Embroidery

--manufactured items
table.insert(defaultclbufftable, {146555, "Haste", 25, 1});     -- Drums of Rage
table.insert(defaultclbufftable, {76095, "Strength", 4000, 1});  -- Potion of Mogu Power

--weapon enchants
table.insert(defaultclbufftable, {104510, "Mastery", 1500, 1}); -- Windsong Mastery
table.insert(defaultclbufftable, {104423, "Haste", 1500, 1});   -- Windsong Haste
table.insert(defaultclbufftable, {104509, "Crit", 1500, 1});    -- Windsong Crit
table.insert(defaultclbufftable, {104434, "Strength", 1650, 1}); -- Dancing Steel

--death knight
table.insert(defaultclbufftable, {53365, "Strength", 15, 1});	-- Unholy Strength effect from Rune of the Fallen Crusader
--table.insert(defaultclbufftable, {144901, "Mastery", 15, 10});	--Death Shroud

--boss ability buffs
table.insert(defaultclbufftable, {140741, "Damage", 100, 1});	-- Primal Nutriment in ToT 6.Boss
table.insert(defaultclbufftable, {118977, "Damage", 60, 1});	-- Fearless in ToeS 4. Boss(Sha)

function OptionsFrame_OnLoad(panel)
    -- Set the name for the Category for the Panel
	panel:RegisterEvent("ADDON_LOADED");
	panel:RegisterEvent("PLAYER_LOGOUT");
	panel:RegisterEvent("SPELLS_CHANGED");
    panel.name = "UnhDkTimer";

    -- When the player clicks okay, run this function.
    panel.okay = function (self) saveVariables(); end;

    -- When the player clicks cancel, run this function.
    panel.cancel = function (self) fillBoxesWithSavedVariables();  end;

	--Build the list of buttons in the table.
	local entry = CreateFrame("Button", "$parentEntry1", BuffListTable, "BuffListEntry");
	entry:SetID(1);
	entry:SetPoint("TOPLEFT", 4, -32);

	for i = 2, maxentries do
		local entry = CreateFrame("Button", "$parentEntry" .. i, BuffListTable, "BuffListEntry");
		entry:SetID(i);
		entry:SetPoint("TOP", "$parentEntry" .. (i - 1), "BOTTOM");
	end

    -- Add the panel to the Interface Options
    InterfaceOptions_AddCategory(panel);
    OptionsFrame:Hide();
    parentaddon = panel;
end

function OptionsFrame_OnEvent(self, event, ...)
	local arg1 = ...;
	--if (event == "ADDON_LOADED" and arg1 == "UnhDkTimer") then
	if (event == "SPELLS_CHANGED" and firstLoadPerGameStart) then
	if(not isUnhDk()) then return; end
		if(not HasteWeight) then
			HasteWeight = defaulthasteweight;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default HasteWeight Loaded.");
		end
		if(not CritWeight) then
			CritWeight = defaultcritweight;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default CritWeight Loaded.");
		end
		if(not MasteryWeight) then
			MasteryWeight = defaultmasteryweight;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default MasteryWeight Loaded.");
		end
		if(not DamageWeight) then
			DamageWeight = defaultdamageweight;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default DamageWeight Loaded.");
		end
		if(not AttackPowerWeight) then
			AttackPowerWeight = defaultAttackPowerweight;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default AttackPowerWeight Loaded.");
		end
		if(not offsetPlagues) then
			offsetPlagues = defaultOffsetPlagues;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default Offset for Plagues Loaded.");
		end
		if(not BuffList) then
			BuffList = defaultbufftable;
			DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Default BuffList Loaded.");
		end

		ClassBuffList = defaultclbufftable;

		fillBoxesWithSavedVariables();
		BuffListBoxUpdate();

		firstLoadPerGameStart = false;
		DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Stat weights loaded.");
	elseif (event == "PLAYER_LOGOUT") then
		saveVariables();
	end
end

function resetStatWeights()
	--set the Weights to the defaults
	HasteWeight = defaulthasteweight;
	CritWeight = defaultcritweight;
	MasteryWeight = defaultmasteryweight;
	DamageWeight = defaultdamageweight;
	AttackPowerWeight = defaultAttackPowerweight;

	--Set the Edit Boxes to the new values
	EditBoxHaste:SetText(string.format("%1.2f", HasteWeight));
	EditBoxCrit:SetText(string.format("%1.2f", CritWeight));
	EditBoxMastery:SetText(string.format("%1.2f", MasteryWeight));
	EditBoxDamage:SetText(string.format("%1.2f", DamageWeight));
	EditBoxAttackPower:SetText(string.format("%1.2f", AttackPowerWeight));

	FontStringError:SetText("Stat weights reset to defaults.");
end

function resetOffsets()
	offsetPlagues = defaultOffsetPlagues;
	EditBoxOffsetPlagues:SetText(string.format("%d", offsetPlagues));

	FontStringError:SetText("Offsets reset to defaults.");
end

function saveVariables()
	HasteWeight = EditBoxHaste:GetNumber();
	CritWeight = EditBoxCrit:GetNumber();
	MasteryWeight = EditBoxMastery:GetNumber();
	DamageWeight = EditBoxDamage:GetNumber();
	AttackPowerWeight = EditBoxAttackPower:GetNumber();

	offsetPlagues = EditBoxOffsetPlauges:GetNumber();

	DEFAULT_CHAT_FRAME:AddMessage("[UnhDkTimer] Variables Saved.");
end

function fillBoxesWithSavedVariables()
	EditBoxHaste:SetText(string.format("%1.2f", HasteWeight));
	EditBoxCrit:SetText(string.format("%1.2f", CritWeight));
	EditBoxMastery:SetText(string.format("%1.2f", MasteryWeight));
	EditBoxDamage:SetText(string.format("%1.2f", DamageWeight));
	EditBoxAttackPower:SetText(string.format("%1.2f", AttackPowerWeight));

	EditBoxOffsetPlagues:SetText(string.format("%d", offsetPlagues));
end

function ButtonAddBuff_OnClick()
	local selection = nil;

	for i = 1, #BuffList do
		local entry = BuffList[i]
		if (entry) then
			if (entry[1] == EditBoxAddBuffName:GetText()) then
				selection = entry;
			end
		end
	end

	if (not selection) then
		-- If we have data, add the buff to the list.
		local stat = EditBoxAddStat:GetText();
		local buff = EditBoxAddBuffName:GetText();
		local modifier = EditBoxAddModifier:GetNumber();
		local maxstacks = EditBoxAddMaxStacks:GetNumber();

		if (stat and buff and modifier and maxstacks) then
			if (string.lower(stat) == "strength" or
				string.lower(stat) == "mastery" or
				string.lower(stat) == "haste" or
				string.lower(stat) == "crit" or
				string.lower(stat) == "attackpower" or
				string.lower(stat) == "damage") then
				table.insert(BuffList, {buff, stat, modifier, maxstacks});
    			sort(BuffList, function(a,b) return a[1] < b[1] end);
				FontStringError:SetText("Added...");
			else
				FontStringError:SetText("Stat must be one of: strength, mastery, haste, crit, attackpower or damage.");
			end
		else
			FontStringError:SetText("All fields are required to add a buff. Modifier and maxstacks must be numeric.");
		end
	else
		FontStringError:SetText("Buff already exists.  Remove it first.");
	end

	EditBoxAddStat:SetText("");
	EditBoxAddBuffName:SetText("");
	EditBoxAddModifier:SetText("");
	EditBoxAddMaxStacks:SetText("");
	BuffListBoxUpdate();
end

function BuffListBoxUpdate(self)
	for i = 1, maxentries do
		local entry = BuffList[i + BuffListScrollFrame.offset];
		local frame = getglobal("BuffListTableEntry" .. i);

		if (entry) then
			frame:Show();
			getglobal(frame:GetName() .. "Name"):SetText(entry[1]);
			getglobal(frame:GetName() .. "Stat"):SetText(entry[2]);
			if (entry[2] == "Damage") then
				getglobal(frame:GetName() .. "Modifier"):SetText(entry[3] .. "%");
			else
				getglobal(frame:GetName() .. "Modifier"):SetText(entry[3]);
			end
			getglobal(frame:GetName() .. "MaxStacks"):SetText(entry[4]);
		else
			frame:Hide();
		end
	end

	FauxScrollFrame_Update(BuffListScrollFrame, #BuffList, maxentries, 24, "BuffListTableEntry", 464, 480, BuffListTableHeaderMaxStacks, 88, 104);
end

function BuffListScrollFrame_OnVerticalScroll(self, value, itemHeight, updateFunction)
	local scrollbar = getglobal(self:GetName() .. "ScrollBar");
	scrollbar:SetValue(value);
	self.offset = floor((value / itemHeight) + 0.5);
	BuffListBoxUpdate(self);
end

function ScrollFrameTemplate_OnMouseWheel(self, value, scrollBar)
	scrollBar = scrollBar or getglobal(self:GetName() .. "ScrollBar");
	if (value > 0) then
		scrollBar:SetValue(scrollBar:GetValue() - (scrollBar:GetHeight() /2));
	else
		scrollBar:SetValue(scrollBar:GetValue() + (scrollBar:GetHeight() /2));
	end
end

function BuffListEntry_OnClick(self)
	local id = self:GetID();
	local entry = BuffList[id + BuffListScrollFrame.offset];

	if (entry) then
		table.remove(BuffList, id + BuffListScrollFrame.offset);
		FontStringError:SetText("Removed: " .. entry[1] );
	end

	BuffListBoxUpdate();
end


text:
module Chewy
  class Index
    module Aliases
      extend ActiveSupport::Concern

      module ClassMethods
        def indexes
          indexes = empty_if_not_found { client.indices.get(index: index_name).keys }
          indexes += empty_if_not_found { client.indices.get_alias(name: index_name).keys }
          indexes.compact.uniq
        end

        def aliases
          empty_if_not_found do
            client.indices.get_alias(index: index_name, name: '*').values.flat_map do |aliases|
              aliases['aliases'].keys
            end
          end.compact.uniq
        end

      private

        def empty_if_not_found
          yield
        rescue Elasticsearch::Transport::Transport::Errors::NotFound
          []
        end
      end
    end
  end
end


text:
const	auths = require('../../libs/auths.js'),
	removeDiacritics = require('../../libs/naming.js').removeDiacritics,
	MIN_DELAY = 40, // delay in seconds between two fireworks in a room
	lastFireworkPerRoom = new Map; // map roomId -> firework info (0 as key for global)

var	miaou,
	nextFireworkId = Date.now();

exports.init = function(_miaou, pluginpath){
	miaou = _miaou;
}

var launch = exports.launch = function(roomId, user, args, isServerAdmin){
	var	match = args.match(/^([^\/]*\/)?(.*)/),
		modifiers = match[1],
		text = match[2].trim(),
		global = /\bg/i.test(modifiers),
		flash = /\fg/i.test(modifiers);
	if (global && !isServerAdmin) {
		throw "Only a server admin can send global fireworks";
	}
	var firework = {
		text: text,
		id: nextFireworkId++,
		sent: Date.now()/1000,
		author: user.name,
		global: global,
		flash: flash
	};
	firework.text = removeDiacritics(firework.text.replace(/\s/g, ' '));
	var infoKey = firework.global ? 0 : roomId;
	if (firework.text.trim().length<2) throw "Too short";
	if (firework.text.length>50) throw "Too long";
	if (firework.text.split(' ').length>5) throw "Too many words";
	if (!firework.flash) {
		var lastFirework = lastFireworkPerRoom.get(infoKey);
		if (lastFirework && (lastFirework.sent+MIN_DELAY>firework.sent)) {
			throw "Min delay between two fireworks: " + MIN_DELAY + " seconds";
		}
		lastFireworkPerRoom.set(infoKey, firework);
	}
	var sockets = miaou.io.sockets;
	if (!global) sockets = sockets.in(roomId);
	sockets.emit("fireworks.launch", firework);
}
function onCommand(ct){
	ct.silent = true;
	ct.nostore = true;
	launch(ct.shoe.room.id, ct.shoe.publicUser, ct.args, auths.isServerAdmin(ct.shoe.completeUser));
}
function onBotCommand(cmd, args, bot, m){
	launch(m.room, bot, args, false); // TODO make it a silent message
}
function onReplay(ct){
	ct.shoe.emit('fireworks.reset');
	var firework = lastFireworkPerRoom.get(ct.shoe.room.id) || lastFireworkPerRoom.get(0);
	if (firework) ct.shoe.emit("fireworks.launch", firework);
	ct.silent = true;
}

exports.registerCommands = function(cb){
	cb({
		name: 'fireworks',
		fun: onCommand,
		botfun:onBotCommand,
		help: "start some fireworks"
	});
	cb({
		name: 'replay_fireworks',
		fun: onReplay,
		help: "replay last fireworks"
	});
}

exports.onNewShoe = function(shoe){
	setTimeout(function(){
		if (!shoe.room) {
			console.log("fireworks: no room in shoe");
			return;
		}
		var firework = lastFireworkPerRoom.get(shoe.room.id) || lastFireworkPerRoom.get(0);
		if (firework) shoe.emit("fireworks.launch", firework);
	}, 5000);
}


text:
package org.apache.flink.runtime.clusterframework;

import org.apache.flink.api.common.resources.CPUResource;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ConfigurationUtils;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.ExecutorUtils;
import org.apache.flink.util.OperatingSystem;
import org.apache.flink.util.TestLogger;
import org.apache.flink.util.function.CheckedSupplier;

import akka.actor.ActorSystem;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.apache.flink.configuration.GlobalConfiguration.FLINK_CONF_FILENAME;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/** Tests for {@link BootstrapToolsTest}. */
public class BootstrapToolsTest extends TestLogger {

    private static final Logger LOG = LoggerFactory.getLogger(BootstrapToolsTest.class);

    @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Test
    public void testSubstituteConfigKey() {
        String deprecatedKey1 = "deprecated-key";
        String deprecatedKey2 = "another-out_of-date_key";
        String deprecatedKey3 = "yet-one-more";

        String designatedKey1 = "newkey1";
        String designatedKey2 = "newKey2";
        String designatedKey3 = "newKey3";

        String value1 = "value1";
        String value2Designated = "designated-value2";
        String value2Deprecated = "deprecated-value2";

        // config contains only deprecated key 1, and for key 2 both deprecated and designated
        Configuration cfg = new Configuration();
        cfg.setString(deprecatedKey1, value1);
        cfg.setString(deprecatedKey2, value2Deprecated);
        cfg.setString(designatedKey2, value2Designated);

        BootstrapTools.substituteDeprecatedConfigKey(cfg, deprecatedKey1, designatedKey1);
        BootstrapTools.substituteDeprecatedConfigKey(cfg, deprecatedKey2, designatedKey2);
        BootstrapTools.substituteDeprecatedConfigKey(cfg, deprecatedKey3, designatedKey3);

        // value 1 should be set to designated
        assertEquals(value1, cfg.getString(designatedKey1, null));

        // value 2 should not have been set, since it had a value already
        assertEquals(value2Designated, cfg.getString(designatedKey2, null));

        // nothing should be in there for key 3
        assertNull(cfg.getString(designatedKey3, null));
        assertNull(cfg.getString(deprecatedKey3, null));
    }

    @Test
    public void testSubstituteConfigKeyPrefix() {
        String deprecatedPrefix1 = "deprecated-prefix";
        String deprecatedPrefix2 = "-prefix-2";
        String deprecatedPrefix3 = "prefix-3";

        String designatedPrefix1 = "p1";
        String designatedPrefix2 = "ppp";
        String designatedPrefix3 = "zzz";

        String depr1 = deprecatedPrefix1 + "var";
        String depr2 = deprecatedPrefix2 + "env";
        String depr3 = deprecatedPrefix2 + "x";

        String desig1 = designatedPrefix1 + "var";
        String desig2 = designatedPrefix2 + "env";
        String desig3 = designatedPrefix2 + "x";

        String val1 = "1";
        String val2 = "2";
        String val3Depr = "3-";
        String val3Desig = "3+";

        // config contains only deprecated key 1, and for key 2 both deprecated and designated
        Configuration cfg = new Configuration();
        cfg.setString(depr1, val1);
        cfg.setString(depr2, val2);
        cfg.setString(depr3, val3Depr);
        cfg.setString(desig3, val3Desig);

        BootstrapTools.substituteDeprecatedConfigPrefix(cfg, deprecatedPrefix1, designatedPrefix1);
        BootstrapTools.substituteDeprecatedConfigPrefix(cfg, deprecatedPrefix2, designatedPrefix2);
        BootstrapTools.substituteDeprecatedConfigPrefix(cfg, deprecatedPrefix3, designatedPrefix3);

        assertEquals(val1, cfg.getString(desig1, null));
        assertEquals(val2, cfg.getString(desig2, null));
        assertEquals(val3Desig, cfg.getString(desig3, null));

        // check that nothing with prefix 3 is contained
        for (String key : cfg.keySet()) {
            assertFalse(key.startsWith(designatedPrefix3));
            assertFalse(key.startsWith(deprecatedPrefix3));
        }
    }

    @Test
    public void testGetTaskManagerShellCommand() {
        final Configuration cfg = new Configuration();
        final TaskExecutorProcessSpec taskExecutorProcessSpec =
                new TaskExecutorProcessSpec(
                        new CPUResource(1.0),
                        new MemorySize(0), // frameworkHeapSize
                        new MemorySize(0), // frameworkOffHeapSize
                        new MemorySize(111), // taskHeapSize
                        new MemorySize(0), // taskOffHeapSize
                        new MemorySize(222), // networkMemSize
                        new MemorySize(0), // managedMemorySize
                        new MemorySize(333), // jvmMetaspaceSize
                        new MemorySize(0), // jvmOverheadSize
                        Collections.emptyList());
        final ContaineredTaskManagerParameters containeredParams =
                new ContaineredTaskManagerParameters(
                        taskExecutorProcessSpec, new HashMap<String, String>());

        // no logging, with/out krb5
        final String java = "$JAVA_HOME/bin/java";
        final String jvmmem =
                "-Xmx111 -Xms111 -XX:MaxDirectMemorySize=222 -XX:MaxMetaspaceSize=333";
        final String jvmOpts = "-Djvm"; // if set
        final String tmJvmOpts = "-DtmJvm"; // if set
        final String logfile = "-Dlog.file=./logs/taskmanager.log"; // if set
        final String logback = "-Dlogback.configurationFile=file:./conf/logback.xml"; // if set
        final String log4j =
                "-Dlog4j.configuration=file:./conf/log4j.properties"
                        + " -Dlog4j.configurationFile=file:./conf/log4j.properties"; // if set
        final String mainClass = "org.apache.flink.runtime.clusterframework.BootstrapToolsTest";
        final String dynamicConfigs =
                TaskExecutorProcessUtils.generateDynamicConfigsStr(taskExecutorProcessSpec).trim();
        final String basicArgs = "--configDir ./conf";
        final String mainArgs = "-Djobmanager.rpc.address=host1 -Dkey.a=v1";
        final String args = dynamicConfigs + " " + basicArgs + " " + mainArgs;
        final String redirects = "1> ./logs/taskmanager.out 2> ./logs/taskmanager.err";

        assertEquals(
                java
                        + " "
                        + jvmmem
                        + ""
                        + // jvmOpts
                        ""
                        + // logging
                        " "
                        + mainClass
                        + " "
                        + dynamicConfigs
                        + " "
                        + basicArgs
                        + " "
                        + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        false,
                        false,
                        false,
                        this.getClass(),
                        ""));

        assertEquals(
                java + " " + jvmmem + "" + // jvmOpts
                        "" + // logging
                        " " + mainClass + " " + args + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        false,
                        false,
                        false,
                        this.getClass(),
                        mainArgs));

        final String krb5 = "-Djava.security.krb5.conf=krb5.conf";
        assertEquals(
                java + " " + jvmmem + " " + krb5 + // jvmOpts
                        "" + // logging
                        " " + mainClass + " " + args + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        false,
                        false,
                        true,
                        this.getClass(),
                        mainArgs));

        // logback only, with/out krb5
        assertEquals(
                java + " " + jvmmem + "" + // jvmOpts
                        " " + logfile + " " + logback + " " + mainClass + " " + args + " "
                        + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        false,
                        false,
                        this.getClass(),
                        mainArgs));

        assertEquals(
                java + " " + jvmmem + " " + krb5 + // jvmOpts
                        " " + logfile + " " + logback + " " + mainClass + " " + args + " "
                        + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        false,
                        true,
                        this.getClass(),
                        mainArgs));

        // log4j, with/out krb5
        assertEquals(
                java + " " + jvmmem + "" + // jvmOpts
                        " " + logfile + " " + log4j + " " + mainClass + " " + args + " "
                        + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        false,
                        true,
                        false,
                        this.getClass(),
                        mainArgs));

        assertEquals(
                java + " " + jvmmem + " " + krb5 + // jvmOpts
                        " " + logfile + " " + log4j + " " + mainClass + " " + args + " "
                        + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        false,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));

        // logback + log4j, with/out krb5
        assertEquals(
                java + " " + jvmmem + "" + // jvmOpts
                        " " + logfile + " " + logback + " " + log4j + " " + mainClass + " " + args
                        + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        false,
                        this.getClass(),
                        mainArgs));

        assertEquals(
                java + " " + jvmmem + " " + krb5 + // jvmOpts
                        " " + logfile + " " + logback + " " + log4j + " " + mainClass + " " + args
                        + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));

        // logback + log4j, with/out krb5, different JVM opts
        cfg.setString(CoreOptions.FLINK_JVM_OPTIONS, jvmOpts);
        assertEquals(
                java + " " + jvmmem + " " + jvmOpts + " " + logfile + " " + logback + " " + log4j
                        + " " + mainClass + " " + args + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        false,
                        this.getClass(),
                        mainArgs));

        assertEquals(
                java + " " + jvmmem + " " + jvmOpts + " " + krb5 + // jvmOpts
                        " " + logfile + " " + logback + " " + log4j + " " + mainClass + " " + args
                        + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));

        // logback + log4j, with/out krb5, different JVM opts
        cfg.setString(CoreOptions.FLINK_TM_JVM_OPTIONS, tmJvmOpts);
        assertEquals(
                java + " " + jvmmem + " " + jvmOpts + " " + tmJvmOpts + " " + logfile + " "
                        + logback + " " + log4j + " " + mainClass + " " + args + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        false,
                        this.getClass(),
                        mainArgs));

        assertEquals(
                java + " " + jvmmem + " " + jvmOpts + " " + tmJvmOpts + " " + krb5 + // jvmOpts
                        " " + logfile + " " + logback + " " + log4j + " " + mainClass + " " + args
                        + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));

        // now try some configurations with different yarn.container-start-command-template

        cfg.setString(
                ConfigConstants.YARN_CONTAINER_START_COMMAND_TEMPLATE,
                "%java% 1 %jvmmem% 2 %jvmopts% 3 %logging% 4 %class% 5 %args% 6 %redirects%");
        assertEquals(
                java + " 1 " + jvmmem + " 2 " + jvmOpts + " " + tmJvmOpts + " " + krb5 + // jvmOpts
                        " 3 " + logfile + " " + logback + " " + log4j + " 4 " + mainClass + " 5 "
                        + args + " 6 " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));

        cfg.setString(
                ConfigConstants.YARN_CONTAINER_START_COMMAND_TEMPLATE,
                "%java% %logging% %jvmopts% %jvmmem% %class% %args% %redirects%");
        assertEquals(
                java + " " + logfile + " " + logback + " " + log4j + " " + jvmOpts + " " + tmJvmOpts
                        + " " + krb5 + // jvmOpts
                        " " + jvmmem + " " + mainClass + " " + args + " " + redirects,
                BootstrapTools.getTaskManagerShellCommand(
                        cfg,
                        containeredParams,
                        "./conf",
                        "./logs",
                        true,
                        true,
                        true,
                        this.getClass(),
                        mainArgs));
    }

    @Test
    public void testUpdateTmpDirectoriesInConfiguration() {
        Configuration config = new Configuration();

        // test that default value is taken
        BootstrapTools.updateTmpDirectoriesInConfiguration(config, "default/directory/path");
        assertEquals(config.getString(CoreOptions.TMP_DIRS), "default/directory/path");

        // test that we ignore default value is value is set before
        BootstrapTools.updateTmpDirectoriesInConfiguration(config, "not/default/directory/path");
        assertEquals(config.getString(CoreOptions.TMP_DIRS), "default/directory/path");

        // test that empty value is not a magic string
        config.setString(CoreOptions.TMP_DIRS, "");
        BootstrapTools.updateTmpDirectoriesInConfiguration(config, "some/new/path");
        assertEquals(config.getString(CoreOptions.TMP_DIRS), "");
    }

    @Test
    public void testShouldNotUpdateTmpDirectoriesInConfigurationIfNoValueConfigured() {
        Configuration config = new Configuration();
        BootstrapTools.updateTmpDirectoriesInConfiguration(config, null);
        assertEquals(config.getString(CoreOptions.TMP_DIRS), CoreOptions.TMP_DIRS.defaultValue());
    }

    /**
     * Tests that we can concurrently create two {@link ActorSystem} without port conflicts. This
     * effectively tests that we don't open a socket to check for a ports availability. See
     * FLINK-10580 for more details.
     */
    @Test
    public void testConcurrentActorSystemCreation() throws Exception {
        final int concurrentCreations = 10;
        final ExecutorService executorService = Executors.newFixedThreadPool(concurrentCreations);
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(concurrentCreations);

        try {
            final List<CompletableFuture<Void>> actorSystemFutures =
                    IntStream.range(0, concurrentCreations)
                            .mapToObj(
                                    ignored ->
                                            CompletableFuture.supplyAsync(
                                                    CheckedSupplier.unchecked(
                                                            () -> {
                                                                cyclicBarrier.await();

                                                                return BootstrapTools
                                                                        .startRemoteActorSystem(
                                                                                new Configuration(),
                                                                                "localhost",
                                                                                "0",
                                                                                LOG);
                                                            }),
                                                    executorService))
                            .map(
                                    // terminate ActorSystems
                                    actorSystemFuture ->
                                            actorSystemFuture.thenCompose(
                                                    AkkaUtils::terminateActorSystem))
                            .collect(Collectors.toList());

            FutureUtils.completeAll(actorSystemFutures).get();
        } finally {
            ExecutorUtils.gracefulShutdown(10000L, TimeUnit.MILLISECONDS, executorService);
        }
    }

    /**
     * Tests that the {@link ActorSystem} fails with an expressive exception if it cannot be
     * instantiated due to an occupied port.
     */
    @Test
    public void testActorSystemInstantiationFailureWhenPortOccupied() throws Exception {
        final ServerSocket portOccupier = new ServerSocket(0, 10, InetAddress.getByName("0.0.0.0"));

        try {
            final int port = portOccupier.getLocalPort();
            BootstrapTools.startRemoteActorSystem(
                    new Configuration(), "0.0.0.0", String.valueOf(port), LOG);
            fail("Expected to fail with a BindException");
        } catch (Exception e) {
            assertThat(ExceptionUtils.findThrowable(e, BindException.class).isPresent(), is(true));
        } finally {
            portOccupier.close();
        }
    }

    @Test
    public void testGetDynamicPropertiesAsString() {
        final Configuration baseConfig = new Configuration();
        baseConfig.setString("key.a", "a");
        baseConfig.setString("key.b", "b1");

        final Configuration targetConfig = new Configuration();
        targetConfig.setString("key.b", "b2");
        targetConfig.setString("key.c", "c");

        final String dynamicProperties =
                BootstrapTools.getDynamicPropertiesAsString(baseConfig, targetConfig);
        if (OperatingSystem.isWindows()) {
            assertEquals("-Dkey.b=\"b2\" -Dkey.c=\"c\"", dynamicProperties);
        } else {
            assertEquals("-Dkey.b='b2' -Dkey.c='c'", dynamicProperties);
        }
    }

    @Test
    public void testEscapeDynamicPropertyValueWithSingleQuote() {
        final String value1 = "#a,b&c^d*e@f(g!h";
        assertEquals("'" + value1 + "'", BootstrapTools.escapeWithSingleQuote(value1));

        final String value2 = "'foobar";
        assertEquals("''\\''foobar'", BootstrapTools.escapeWithSingleQuote(value2));

        final String value3 = "foo''bar";
        assertEquals("'foo'\\'''\\''bar'", BootstrapTools.escapeWithSingleQuote(value3));

        final String value4 = "'foo' 'bar'";
        assertEquals("''\\''foo'\\'' '\\''bar'\\'''", BootstrapTools.escapeWithSingleQuote(value4));
    }

    @Test
    public void testEscapeDynamicPropertyValueWithDoubleQuote() {
        final String value1 = "#a,b&c^d*e@f(g!h";
        assertEquals("\"#a,b&c\"^^\"d*e@f(g!h\"", BootstrapTools.escapeWithDoubleQuote(value1));

        final String value2 = "foo\"bar'";
        assertEquals("\"foo\\\"bar'\"", BootstrapTools.escapeWithDoubleQuote(value2));

        final String value3 = "\"foo\" \"bar\"";
        assertEquals("\"\\\"foo\\\" \\\"bar\\\"\"", BootstrapTools.escapeWithDoubleQuote(value3));
    }

    @Test
    public void testGetEnvironmentVariables() {
        Configuration testConf = new Configuration();
        testConf.setString("containerized.master.env.LD_LIBRARY_PATH", "/usr/lib/native");

        Map<String, String> res =
                ConfigurationUtils.getPrefixedKeyValuePairs("containerized.master.env.", testConf);

        Assert.assertEquals(1, res.size());
        Map.Entry<String, String> entry = res.entrySet().iterator().next();
        Assert.assertEquals("LD_LIBRARY_PATH", entry.getKey());
        Assert.assertEquals("/usr/lib/native", entry.getValue());
    }

    @Test
    public void testGetEnvironmentVariablesErroneous() {
        Configuration testConf = new Configuration();
        testConf.setString("containerized.master.env.", "/usr/lib/native");

        Map<String, String> res =
                ConfigurationUtils.getPrefixedKeyValuePairs("containerized.master.env.", testConf);

        Assert.assertEquals(0, res.size());
    }

    @Test
    public void testWriteConfigurationAndReload() throws IOException {
        final File flinkConfDir = temporaryFolder.newFolder().getAbsoluteFile();
        final Configuration flinkConfig = new Configuration();

        final ConfigOption<List<String>> listStringConfigOption =
                ConfigOptions.key("test-list-string-key").stringType().asList().noDefaultValue();
        final List<String> list =
                Arrays.asList("A,B,C,D", "A'B'C'D", "A;BCD", "AB\"C\"D", "AB'\"D:B");
        flinkConfig.set(listStringConfigOption, list);
        assertThat(flinkConfig.get(listStringConfigOption), containsInAnyOrder(list.toArray()));

        final ConfigOption<List<Duration>> listDurationConfigOption =
                ConfigOptions.key("test-list-duration-key")
                        .durationType()
                        .asList()
                        .noDefaultValue();
        final List<Duration> durationList =
                Arrays.asList(Duration.ofSeconds(3), Duration.ofMinutes(1));
        flinkConfig.set(listDurationConfigOption, durationList);
        assertThat(
                flinkConfig.get(listDurationConfigOption),
                containsInAnyOrder(durationList.toArray()));

        final ConfigOption<Map<String, String>> mapConfigOption =
                ConfigOptions.key("test-map-key").mapType().noDefaultValue();
        final Map<String, String> map = new HashMap<>();
        map.put("key1", "A,B,C,D");
        map.put("key2", "A;BCD");
        map.put("key3", "A'B'C'D");
        map.put("key4", "AB\"C\"D");
        map.put("key5", "AB'\"D:B");
        flinkConfig.set(mapConfigOption, map);
        assertThat(
                flinkConfig.get(mapConfigOption).entrySet(),
                containsInAnyOrder(map.entrySet().toArray()));

        final ConfigOption<Duration> durationConfigOption =
                ConfigOptions.key("test-duration-key").durationType().noDefaultValue();
        final Duration duration = Duration.ofMillis(3000);
        flinkConfig.set(durationConfigOption, duration);
        assertEquals(duration, flinkConfig.get(durationConfigOption));

        BootstrapTools.writeConfiguration(flinkConfig, new File(flinkConfDir, FLINK_CONF_FILENAME));
        final Configuration loadedFlinkConfig =
                GlobalConfiguration.loadConfiguration(flinkConfDir.getAbsolutePath());
        assertThat(
                loadedFlinkConfig.get(listStringConfigOption), containsInAnyOrder(list.toArray()));
        assertThat(
                loadedFlinkConfig.get(listDurationConfigOption),
                containsInAnyOrder(durationList.toArray()));
        assertThat(
                loadedFlinkConfig.get(mapConfigOption).entrySet(),
                containsInAnyOrder(map.entrySet().toArray()));
        assertEquals(duration, loadedFlinkConfig.get(durationConfigOption));
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression

    <[UseExportProvider]>
    Public Class ImplementedByGraphQueryTests
        <Fact, Trait(Traits.Feature, Traits.Features.Progression)>
        Public Async Function TestImplementedBy1() As Task
            Using testState = ProgressionTestState.Create(
                    <Workspace>
                        <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
                            <Document FilePath="Z:\Project.cs">
using System;

interface $$IBlah {
}

abstract class Base
{
    public abstract int CompareTo(object obj);
}

class Goo : Base, IComparable, IBlah
{
    public override int CompareTo(object obj)
    {
        throw new NotImplementedException();
    }
}

class Goo2 : Base, IBlah
{
    public override int CompareTo(object obj)
    {
        throw new NotImplementedException();
    }
}
                         </Document>
                        </Project>
                    </Workspace>)

                Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
                Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementedByGraphQuery(), GraphContextDirection.Target)

                AssertSimplifiedGraphIs(
                    outputContext.Graph,
                    <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
                        <Nodes>
                            <Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
                            <Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
                            <Node Id="(@1 Type=IBlah)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="IBlah" Icon="Microsoft.VisualStudio.Interface.Internal" Label="IBlah"/>
                        </Nodes>
                        <Links>
                            <Link Source="(@1 Type=Goo)" Target="(@1 Type=IBlah)" Category="Implements"/>
                            <Link Source="(@1 Type=Goo2)" Target="(@1 Type=IBlah)" Category="Implements"/>
                        </Links>
                        <IdentifierAliases>
                            <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
                        </IdentifierAliases>
                    </DirectedGraph>)
            End Using
        End Function
    End Class

End Namespace


text:
const { OutlookRequest } = require("./base");
const { merge_ids, split_merged_id } = require("../../utils");
const { PROVIDER_NB_MONTHS_FUTURE, PROVIDER_NB_MONTHS_PAST } = require("../../config");

const moment = require("moment-timezone");
const querystring = require("querystring");
const _ = require("lodash");

/**
 * Utils
 */
function _normalize_response_status(response_status) {
    return {
        None: "needs_action",
        Declined: "declined",
        TentativelyAccepted: "tentative",
        Accepted: "accepted"
    }[response_status];
}

/**
 * Formatting helpers
 */
function _format_layer(source_id, outlook_layer) {
    const output = {
        id: merge_ids(source_id, outlook_layer.Id),
        title: outlook_layer.Name,
        text_color: "#FFFFFF",
        acl: {
            edit: false,
            create: false,
            delete: false
        },
        selected: false
    };

    // TODO: make it work for `Auto`?
    const colors = {
        LightBlue: "#a6d1f5",
        LightTeal: "#4adacc",
        LightGreen: "#87d28e",
        LightGray: "#c0c0c0",
        LightRed: "#f88c9b",
        LightPink: "#f08cc0",
        LightBrown: "#cba287",
        LightOrange: "#fcab73",
        LightYellow: "#f4d07a"
    };
    output.color = _.get(colors, _.get(outlook_layer, "Color", "Auto"), "#EB3D01");
    return output;
}

function _format_event(layer_id, event) {
    const output = {
        id: merge_ids(layer_id, event.Id),
        title: event.Subject,
        start: {
            timezone: _.get(event, ["Start", "TimeZone"])
        },
        end: {
            timezone: _.get(event, ["End", "TimeZone"])
        },
        link: _.get(event, "WebLink"),
        kind: "event#basic"
    };

    const location = _.get(event, ["Location", "DisplayName"]);
    if (!_.isEmpty(location)) {
        output.location = location;
    }

    if (_.get(event, "IsAllDay", false)) {
        const date_format = "YYYY-MM-DD";
        output.start.date = moment
            .tz(event.Start.DateTime, event.Start.Timezone)
            .format(date_format);
        output.end.date = moment.tz(event.End.DateTime, event.End.Timezone).format(date_format);
    } else {
        output.start.date_time = moment.tz(event.Start.DateTime, event.Start.Timezone).format();
        output.end.date_time = moment.tz(event.End.DateTime, event.End.Timezone).format();
    }

    if (_.get(event, ["Body", "ContentType"], "") === "Text") {
        output.description = _.get(event, ["Body", "Content"], "");
    }

    output.attendees = _.map(_.get(event, "Attendees", []), attendee => {
        // eslint-disable-line arrow-body-style
        return {
            email: _.get(attendee, ["EmailAddress", "Address"]),
            response_status: _normalize_response_status(_.get(attendee, ["Status", "Response"])),
            self: false // TODO: need to fix this
        };
    });

    output.reminders = [];
    if (_.get(event, "IsReminderOn", false)) {
        output.reminders.push({
            minutes: _.get(event, "ReminderMinutesBeforeStart", 0)
        });
    }

    return output;
}

/**
 * Actions
 */
function load_layers(req, source) {
    return new OutlookRequest(req, source.id)
        .api("me/calendars", {
            qs: {
                $select: "Name,Color",
                $top: 50 // TODO: might need to handle pagination as well?
            }
        })
        .then(outlook_res => _.map(outlook_res.value, _.partial(_format_layer, source.id)));
}

function _load_events_promise(req, source_id, uri, options, format_event_func, events = []) {
    return new OutlookRequest(req, source_id).api(uri, options).then(outlook_res => {
        const all_events = _.concat(events, _.map(outlook_res.value, format_event_func));
        if (_.has(outlook_res, "@odata.nextLink")) {
            options.qs.$skip += options.qs.$top; // eslint-disable-line no-param-reassign
            return _load_events_promise(
                req,
                source_id,
                uri,
                options,
                format_event_func,
                all_events
            );
        }
        return all_events;
    });
}

function load_events(req, source, layer_id) {
    const [, calendar_id] = split_merged_id(layer_id);
    const min_date = new Date();
    min_date.setMonth(min_date.getMonth() - PROVIDER_NB_MONTHS_PAST);
    const max_date = new Date();
    max_date.setMonth(max_date.getMonth() + PROVIDER_NB_MONTHS_FUTURE);

    const options = {
        qs: {
            startDateTime: min_date.toISOString(),
            endDateTime: max_date.toISOString(),
            $top: 50,
            $skip: 0,
            $select: "Subject,Location,Start,End,WebLink,IsAllDay," +
                "Body,Attendees,IsReminderOn,ReminderMinutesBeforeStart"
        }
    };
    return _load_events_promise(
        req,
        source.id,
        `me/calendars/${querystring.escape(calendar_id)}/calendarview`,
        options,
        _.partial(_format_event, layer_id)
    ).then(events => {
        // eslint-disable-line arrow-body-style
        return {
            events
        };
    });
}

module.exports = {
    load_layers,
    load_events
};


text:
package com.remondis.remap.omitOthers;

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

import org.junit.Test;

import com.remondis.remap.AssertMapping;
import com.remondis.remap.Mapper;
import com.remondis.remap.Mapping;

public class MapperTest {

  @Test
  public void shouldOmitOtherSourceProperties() {
    assertThatThrownBy(() -> Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOtherSourceProperties()
        .mapper()).hasMessageContaining("- Property 'e' in AResource")
            .hasMessageContaining("- Property 'c' in AResource")
            .hasMessageContaining("- Property 'd' in AResource");
  }

  @Test
  public void shouldOmitOtherDestinationProperties() {
    assertThatThrownBy(() -> Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOtherDestinationProperties()
        .mapper()).hasMessageContaining("- Property 'b' in A")
            .hasMessageContaining("- Property 'a' in A");
  }

  @Test
  public void shouldOmitOtherSourceAndDestFields_withExpectOtherSourceAndDestFieldsToBeOmitted() {
    Mapper<A, AResource> mapper = Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOtherSourceProperties()
        .omitOtherDestinationProperties()
        .mapper();

    AssertMapping.of(mapper)
        .expectReplace(A::getId, AResource::getId)
        .andSkipWhenNull()
        .expectReassign(A::getDescription)
        .to(AResource::getName)
        .expectOtherSourceFieldsToBeOmitted()
        .expectOtherDestinationFieldsToBeOmitted()
        .ensure();
  }

  @Test
  public void shouldOmitOtherSourceAndDestFields_withExpectOthersToBeOmitted() {
    Mapper<A, AResource> mapper = Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOtherSourceProperties()
        .omitOtherDestinationProperties()
        .mapper();

    AssertMapping.of(mapper)
        .expectReplace(A::getId, AResource::getId)
        .andSkipWhenNull()
        .expectReassign(A::getDescription)
        .to(AResource::getName)
        .expectOthersToBeOmitted()
        .ensure();
  }

  @Test
  public void shouldOmitOthers_withExpectOthersToBeOmitted() {
    Mapper<A, AResource> mapper = Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOthers() // Should add omits for a,b,c,d,e
        .mapper();

    AssertMapping.of(mapper)
        .expectReplace(A::getId, AResource::getId)
        .andSkipWhenNull()
        .expectReassign(A::getDescription)
        .to(AResource::getName)
        .expectOthersToBeOmitted()
        .ensure();
  }

  @Test
  public void shouldOmitOthers() {
    Mapper<A, AResource> mapper = Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOthers() // Should add omits for a,b,c,d,e
        .mapper();

    AssertMapping.of(mapper)
        .expectReplace(A::getId, AResource::getId)
        .andSkipWhenNull()
        .expectReassign(A::getDescription)
        .to(AResource::getName)
        .expectOmitInSource(A::getA)
        .expectOmitInSource(A::getB)
        .expectOmitInDestination(AResource::getC)
        .expectOmitInDestination(AResource::getD)
        .expectOmitInDestination(AResource::getE)
        .ensure();
  }

  @Test
  public void shouldDenyOmitOthersIfNotExpected() {
    Mapper<A, AResource> mapper = Mapping.from(A.class)
        .to(AResource.class)
        .replace(A::getId, AResource::getId)
        .withSkipWhenNull(String::valueOf)
        .reassign(A::getDescription)
        .to(AResource::getName)
        .omitOthers() // should add omits for a,b,c,d,e
        .mapper();

    assertThatThrownBy(() -> AssertMapping.of(mapper)
        .expectReplace(A::getId, AResource::getId)
        .andSkipWhenNull()
        .expectReassign(A::getDescription)
        .to(AResource::getName)
        .ensure()).isInstanceOf(AssertionError.class)
            .hasMessageContaining("The following unexpected transformation were specified on the mapping:")
            .hasMessageContaining("- Omitting Property 'a' in A")
            .hasMessageContaining("- Omitting Property 'd' in AResource")
            .hasMessageContaining("- Omitting Property 'c' in AResource")
            .hasMessageContaining("- Omitting Property 'e' in AResource")
            .hasMessageContaining("- Omitting Property 'b' in A");

  }
}


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="../paper-button/paper-button.html">
<!--
`dude-property-resource`

@group dude Elements
@element dude-property
@demo demo/index.html
-->
<dom-module id="dude-property-resource">
    <style include="iron-flex"></style>
    <style>
        #property-button {
            background: var(--dude-select1-color);
            color: var(--dude-dark1-color);
            font-family: var(--dude-font-primary);
            margin: 10px 0 0;
            width: 100%;
            border-radius: 0;
        }
    </style>
    <template>
        <paper-button id="property-button"
                      on-click="_openResourceManager">[[ resourceValueName ]]
        </paper-button>
    </template>
    <script>
        Polymer({
            is: "dude-property-resource",
            properties: {
                "property": {
                    "type": "DudePropertyElement"
                },
                "propertyType": {
                    "type": String,
                    "readonly": true
                },
                "propertyName": {
                    "type": String,
                    "readonly": true
                },
                "propertyData": {
                    "type": Object,
                    "readonly": true
                },
                "propertyValue": {
                    "type": String,
                    "value": null,
                    "observer": "_propertyValueChanged"
                },
                "resourceValueName": {
                    "computed": "_resourceValueName(propertyValue)"
                }
            },
            listeners: {
                "dude-resource-manager-submit": "_propertyValueChanged"
            },

            /**
             * Called when the property element is attached to the DOM (dude-property.$.property)
             * Notifies dude-property that we are ready
             */
            attached: function () {
                this.fire("dude-property-ready");
            },

            /**
             * Called when the propertyValue changed in dude-property
             * @param {Object} propertyValue
             */
            setPropertyValue: function (propertyValue) {
                this.set("propertyValue", propertyValue);
            },

            /**
             * Called when the propertyValue changed
             * Notifies dude-property that the property value changed
             * @private
             */
            _propertyValueChanged: function () {
                this.fire("dude-property-value-change");
            },

            /**
             * @param {Object} propertyValue
             * @private
             */
            _resourceValueName: function (propertyValue) {
                return (propertyValue && propertyValue.name) || "(None)";
            },

            /**
             * Opens the resource manager
             * @private
             */
            _openResourceManager: function () {
                this.fire("dude-property-resource-open");
            }
        });
    </script>
</dom-module>


text:
package org.apache.felix.webconsole.plugins.obr.internal;

import org.apache.felix.webconsole.AbstractWebConsolePlugin;
import org.osgi.service.log.LogService;
import org.osgi.service.obr.Requirement;
import org.osgi.service.obr.Resolver;
import org.osgi.service.obr.Resource;

class OsgiDeployer implements Runnable
{

    private final Resolver obrResolver;

    private final AbstractWebConsolePlugin logger;

    private final boolean startBundles;

    OsgiDeployer( Resolver obrResolver, AbstractWebConsolePlugin logger, boolean startBundles )
    {
        this.obrResolver = obrResolver;
        this.logger = logger;
        this.startBundles = startBundles;
    }

    static void deploy( Resolver obrResolver, AbstractWebConsolePlugin logger, boolean startBundles )
    {
        final OsgiDeployer d = new OsgiDeployer( obrResolver, logger, startBundles );
        final Thread t = new Thread( d, "OBR Bundle Deployer (OSGi API)" );
        t.start();
    }

    /**
     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        try
        {
            if ( obrResolver.resolve() )
            {

                logResource( logger, "Installing Requested Resources", obrResolver.getAddedResources() );
                logResource( logger, "Installing Required Resources", obrResolver.getRequiredResources() );
                logResource( logger, "Installing Optional Resources", obrResolver.getOptionalResources() );

                obrResolver.deploy( startBundles );
            }
            else
            {
                logRequirements( logger, "Cannot Install requested bundles due to unsatisfied requirements",
                    obrResolver.getUnsatisfiedRequirements() );
            }
        }
        catch ( Exception ie )
        {
            logger.log( LogService.LOG_ERROR, "Cannot install bundles", ie );
        }
    }

    public static void logResource( AbstractWebConsolePlugin logger, String message, Resource[] res )
    {
        if ( res != null && res.length > 0 )
        {
            logger.log( LogService.LOG_INFO, message );
            for ( int i = 0; i < res.length; i++ )
            {
                logger.log( LogService.LOG_INFO, "  " + i + ": " + res[i].getSymbolicName() + ", "
                    + res[i].getVersion() );
            }
        }
    }

    public static void logRequirements( AbstractWebConsolePlugin logger, String message, Requirement[] reasons )
    {
        logger.log( LogService.LOG_ERROR, message );
        for ( int i = 0; reasons != null && i < reasons.length; i++ )
        {
            String moreInfo = reasons[i].getComment();
            if ( moreInfo == null )
            {
                moreInfo = reasons[i].getFilter().toString();
            }
            logger.log( LogService.LOG_ERROR, "  " + i + ": " + reasons[i].getName() + " (" + moreInfo + ")" );
        }
    }

}


text:
package Pieces; /**
 * Piece.java
 *
 * Version:
 *   $Id: Piece.java,v 1.1 2002/10/22 21:12:53 se362 Exp $
 *
 * Revisions:
 *   $Log: Piece.java,v $
 *   Revision 1.1  2002/10/22 21:12:53  se362
 *   Initial creation of case study
 *
 */

/**
 * This is an abstract class representing any piece that
 * know about it's color and possible moves and captures
 *
 * @author
 *
 */

import Game.Board;

import java.util.*;
import java.awt.*;

public abstract class Piece {

    private Color color; // the color of the piece

    private Integer position; // The position of the piece on the board

   /**
    * The constructor for this piece
    *
    * @param c - the color for this piece
    */
   public Piece( Color c, Integer position) {

	   // set the color
	   this.color = c;
       this.position = position;

   }

    public Integer getPosition() {
        return position;
    }

    public void setPosition(Integer position) {
        this.position = position;
    }

    /**
    * The method which is abstract
    *
    * @return the type of the piece
    */
   abstract public int getType();

   /**
    * This method returns the color of this piece
    *
    * @return the color for this piece
    */
   public Color getColor() {

	   return color;
   }

    abstract public KingPiece kingThisPiece();

    abstract public boolean moveIsValid();

    abstract public Vector checkForJumps(Board board);

    protected int getRowPos(){
        return (position)/8;
    }
    protected int getColPos(){

        return (position)%8;
    }

}// Piece


text:
package net.jadfreex.pv.commons.view.util;

/**
 *
 * @author 170828 Grupo Salinas
 */
public class ViewExecutor {

    synchronized public static void show(Class<? extends View> clazz) {
        View menu;
        try {
            menu = clazz.newInstance();
            menu.print();
        } catch (Exception e) {
            System.out.println(String.format("ERROR AL CREAR EL MENU: %s", e.getMessage()));
        }
    }

}


text:
/**
 * @file pyrMeanShiftFiltering.cpp
 * @brief mex interface for pyrMeanShiftFiltering
 * @author Kota Yamaguchi
 * @date 2011
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    // Check the number of arguments
    if (nrhs<1 || (nrhs%2)!=1 || nlhs>1)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");

    // Argument vector
    vector<MxArray> rhs(prhs,prhs+nrhs);

    // Option processing
    double sp = 5;
    double sr = 10;
    int maxLevel=1;
    for (int i=1; i<nrhs; i+=2) {
        string key = rhs[i].toString();
        if (key=="SP")
            sp = rhs[i+1].toDouble();
        else if (key=="SR")
            sr = rhs[i+1].toDouble();
        else if (key=="MaxLevel")
            maxLevel = rhs[i+1].toInt();
        else
            mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
    }

    // Process
    Mat src(rhs[0].toMat()), dst;
    pyrMeanShiftFiltering(src, dst, sp, sr, maxLevel);
    plhs[0] = MxArray(dst);
}