text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.Internals;
using EasyNetQ.Persistent;
using EasyNetQ.Producer;

namespace EasyNetQ.ChannelDispatcher;

/// <summary>
///     Invokes client commands using multiple channels
/// </summary>
public sealed class MultiPersistentChannelDispatcher : IPersistentChannelDispatcher
{
    private readonly ConcurrentDictionary<PersistentChannelDispatchOptions, AsyncQueue<IPersistentChannel>> channelsPoolPerOptions;
    private readonly Func<PersistentChannelDispatchOptions, AsyncQueue<IPersistentChannel>> channelsPoolFactory;

    /// <summary>
    ///     Creates a dispatcher
    /// </summary>
    public MultiPersistentChannelDispatcher(
        int channelsCount,
        IProducerConnection producerConnection,
        IConsumerConnection consumerConnection,
        IPersistentChannelFactory channelFactory
    )
    {
        channelsPoolPerOptions = new ConcurrentDictionary<PersistentChannelDispatchOptions, AsyncQueue<IPersistentChannel>>();
        channelsPoolFactory = o =>
        {
            var options = new PersistentChannelOptions(o.PublisherConfirms);
            return new AsyncQueue<IPersistentChannel>(
                Enumerable.Range(0, channelsCount)
                    .Select(
                        _ => o.ConnectionType switch
                        {
                            PersistentConnectionType.Producer => channelFactory.CreatePersistentChannel(
                                producerConnection, options
                            ),
                            PersistentConnectionType.Consumer => channelFactory.CreatePersistentChannel(
                                consumerConnection, options
                            ),
                            _ => throw new ArgumentOutOfRangeException()
                        }
                    )
            );
        };
    }

    /// <inheritdoc />
    public void Dispose()
    {
        channelsPoolPerOptions.ClearAndDispose(x =>
        {
            while (x.TryDequeue(out var channel))
                channel.Dispose();
            x.Dispose();
        });
    }

    /// <inheritdoc />
    public async Task<TResult> InvokeAsync<TResult, TChannelAction>(
        TChannelAction channelAction,
        PersistentChannelDispatchOptions options,
        CancellationToken cancellationToken = default
    ) where TChannelAction : struct, IPersistentChannelAction<TResult>
    {
        var channelsPool = channelsPoolPerOptions.GetOrAdd(options, channelsPoolFactory);
        var channel = await channelsPool.DequeueAsync(cancellationToken).ConfigureAwait(false);
        try
        {
            return await channel.InvokeChannelActionAsync<TResult, TChannelAction>(channelAction, cancellationToken).ConfigureAwait(false);
        }
        finally
        {
            channelsPool.Enqueue(channel);
        }
    }
}


text:
const nock = require('nock')

const getDiffCommits = require('../../lib/get-diff-commits')

test('get-diff-commits', async () => {
  expect.assertions(4)

  nock('https://api.github.com')
    .post('/app/installations/123/access_tokens')
    .optionally()
    .reply(200, {
      token: 'secret'
    })
    .get('/rate_limit')
    .optionally()
    .reply(200, {})
    .get('/repos/finnp/test/compare/dead...beef')
    .reply(200, () => {
      // GitHub endpoint called
      expect(true).toBeTruthy()
      return {
        total_commits: 1,
        behind_by: 0,
        html_url: '...',
        commits: [
          {
            sha: 'deadbeef',
            commit: {
              message: 'abccommitmessage'
            }
          }
        ]
      }
    })
    .post('/markdown', ({ text }) => {
      expect(text).toMatch(/abccommitmessage/)
      return true
    })
    .reply(200, 'body <a href="https://github.com/greenkeeperio/greenkeeper">', {
      'content-type': 'text/html;charset=utf-8'
    })

  const diff = await getDiffCommits({
    installationId: '123',
    owner: 'finnp',
    repo: 'test',
    base: 'dead',
    head: 'beef'
  })
  expect(diff).toMatch(/<summary>Commits<\/summary>/)
  expect(diff).toMatch(/https:\/\/urls.greenkeeper.io/)
})

redpajama_set_name: RedPajamaGithub


text:
"""This module contains the FRC robot class."""

# Imports
import wpilib
#import autoscript
import common
import drivetrain
import feeder
import lift
import logging
import logging.config
import math
import userinterface

class MyRobot(wpilib.IterativeRobot):
    """Controls the robot.

    This is the main robot class that controls the robot during all 3 modes.
    """
    # Public member variables

    # Private member objects
    _drive_train = None
    _feeder = None
    _lift = None
    _log = None
    _user_interface = None

    # Private member variables
    _log_enabled = False
    _driver_alternate = False

    # Iterative robot methods that we override.
    # These get called by the main control loop in the IterativeRobot class.
    def robotInit(self):
        """Performs robot-wide initialization.

        Called upon robot power-on.

        """
        self._initialize("/home/lvuser/par/robot.par", True)

    def disabledInit(self):
        """Prepares the robot for Disabled mode.

        Called only when first disabled.

        """
        self._set_robot_state(common.ProgramState.DISABLED)

        # Read sensors
        self._read_sensors()

    def autonomousInit(self):
        """Prepares the robot for Autonomous mode.

        Called each and every time autonomous is entered from another mode.

        """
        self._set_robot_state(common.ProgramState.AUTONOMOUS)

        # Read sensors
        self._read_sensors()

    def teleopInit(self):
        """Prepares the robot for Teleop mode.

        Called each and every time teleop is entered from another mode.

        """
        self._set_robot_state(common.ProgramState.TELEOP)

        # Read sensors
        self._read_sensors()

    def testInit(self):
        """Prepares the robot for Test mode.

        Called each and every time test mode is entered from another mode.

        """
        pass

    def disabledPeriodic(self):
        """Called iteratively during disabled mode.

        The period is synced to the driver station control packets,
        giving a periodic frequency of about 50Hz (50 times per second).

        """
        # Set all motors to be stopped (prevent motor safety errors)
        if self._drive_train:
            self._drive_train.drive(0.0, 0.0, False)

        # Read sensors
        self._read_sensors()

    def autonomousPeriodic(self):
        """Called iteratively during autonomous mode.

        The period is synced to the driver station control packets,
        giving a periodic frequency of about 50Hz (50 times per second).

        """
        # Read sensors
        self._read_sensors()

    def teleopPeriodic(self):
        """Called iteratively during teleop mode.

        The period is synced to the driver station control packets,
        giving a periodic frequency of about 50Hz (50 times per second).

        """
        # Read sensors
        self._read_sensors()

        # Perform user controlled actions
        if self._user_interface:
            # Check for alternate speed mode request
            self._check_alternate_speed_modes()

            # Manually control the robot
            self._control_drive_train()
            self._control_feeder()
            self._control_lift()

            # Update/store the UI button state
            self._user_interface.store_button_states(
                    userinterface.UserControllers.DRIVER)
            self._user_interface.store_button_states(
                    userinterface.UserControllers.SCORING)

    def testPeriodic(self):
        """Called iteratively during test mode.

        The period is synced to the driver station control packets,
        giving a periodic frequency of about 50Hz (50 times per second).

        """
        pass

    # Custom methods used by the methods above
    def _initialize(self, params, logging_enabled):
        """Initialize the robot.

        Initialize instance variables to defaults, read parameter values from
        the specified file, instantiate required objects and update status
        variables.

        Args:
            params: The parameters filename to use for configuration.
            logging_enabled: True if logging should be enabled.

        """
        # Initialize public member variables

        # Initialize private member objects
        self._drive_train = None
        self._feeder = None
        self._lift = None
        self._log = None
        self._user_interface = None

        # Initialize private member variables
        self._log_enabled = False
        self._driver_alternate = False

        # Enable logging if specified
        if logging_enabled:
            # Create a new data log object
            self._log = logging.getLogger('robot')
            self._log.setLevel(logging.DEBUG)
            fh = logging.FileHandler('/home/lvuser/log/robot.log')
            fh.setLevel(logging.DEBUG)
            formatter = logging.Formatter(
                    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            self._log.addHandler(fh)
            if self._log:
                self._log_enabled = True
            else:
                self._log = None

        # Create robot objects
        self._drive_train = drivetrain.DriveTrain(
                                    "/home/lvuser/par/drivetrain.par",
                                    self._log_enabled)
        self._feeder = feeder.Feeder("/home/lvuser/par/feeder.par",
                                     self._log_enabled)
        self._lift = lift.Lift("/home/lvuser/par/lift.par", self._log_enabled)
        self._user_interface = userinterface.UserInterface(
                                    "/home/lvuser/par/userinterface.par",
                                    self._log_enabled)

    def _read_sensors(self):
        """Have the objects read their sensors."""
        if self._drive_train:
            self._drive_train.read_sensors()
        if self._feeder:
            self._feeder.read_sensors()
        if self._lift:
            self._lift.read_sensors()

    def _set_robot_state(self, state):
        """Notify objects of the current mode."""
        if self._drive_train:
            self._drive_train.set_robot_state(state)
        if self._feeder:
            self._feeder.set_robot_state(state)
        if self._lift:
            self._lift.set_robot_state(state)
        if self._user_interface:
            self._user_interface.set_robot_state(state)

    def _check_alternate_speed_modes(self):
        """Check for alternate speed mode."""
        if (self._user_interface.get_button_state(
                        userinterface.UserControllers.DRIVER,
                        userinterface.JoystickButtons.LEFTBUMPER) == 1):
            self._driver_alternate = True
        else:
            self._driver_alternate = False

    def _control_drive_train(self):
        """Manually control the drive train."""
        if self._drive_train:
            driver_left_y = self._user_interface.get_axis_value(
                    userinterface.UserControllers.DRIVER,
                    userinterface.JoystickAxis.LEFTY)
            driver_right_x = self._user_interface.get_axis_value(
                    userinterface.UserControllers.DRIVER,
                    userinterface.JoystickAxis.RIGHTX)
            if driver_left_y != 0.0 or driver_right_x != 0.0:
                self._drive_train.drive(driver_left_y, driver_right_x,
                                        self._driver_alternate)
            else:
                self._drive_train.drive(0.0, 0.0, False)

    def _control_feeder(self):
        """Manually control the feeder."""
        if self._feeder:
            scoring_right_x = self._user_interface.get_axis_value(
                    userinterface.UserControllers.SCORING,
                    userinterface.JoystickAxis.RIGHTX)
            scoring_left_trigger = self._user_interface.get_button_state(
                    userinterface.UserControllers.SCORING,
                    userinterface.JoystickButtons.LEFTTRIGGER)
            scoring_right_trigger = self._user_interface.get_button_state(
                    userinterface.UserControllers.SCORING,
                    userinterface.JoystickButtons.RIGHTTRIGGER)

            if scoring_right_x != 0.0:
                direction = common.Direction.STOP
                if scoring_right_x > 0:
                    direction = common.Direction.OPEN
                else:
                    direction = common.Direction.CLOSE
                self._feeder.move_arms(direction, math.fabs(scoring_right_x))
            else:
                self._feeder.move_arms(common.Direction.STOP, 0.0)

            if scoring_left_trigger != 0.0 or scoring_right_trigger != 0.0:
                direction = common.Direction.STOP
                if scoring_right_trigger > 0:
                    direction = common.Direction.IN
                else:
                    direction = common.Direction.OUT
                self._feeder.feed(direction, 1.0)
            else:
                self._feeder.feed(common.Direction.STOP, 0.0)

    def _control_lift(self):
        """Manually control the lift."""
        if self._lift:
            scoring_left_y = self._user_interface.get_axis_value(
                    userinterface.UserControllers.SCORING,
                    userinterface.JoystickAxis.LEFTY)
            scoring_left_bumper = self._user_interface.get_button_state(
                    userinterface.UserControllers.SCORING,
                    userinterface.JoystickButtons.LEFTBUMPER)

            if scoring_left_bumper != 0.0:
                self._lift.ignore_encoder_limits(True)
            else:
                self._lift.ignore_encoder_limits(False)

            if scoring_left_y != 0.0:
                self._lift.move_lift(scoring_left_y)
            else:
                self._lift.move_lift(0.0)

if __name__ == "__main__":
    wpilib.run(MyRobot)


text:
package opennlp.tools.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import opennlp.tools.chunker.ChunkerContextGenerator;
import opennlp.tools.dictionary.Dictionary;
import opennlp.tools.ml.model.Event;
import opennlp.tools.parser.chunking.Parser;
import opennlp.tools.postag.DefaultPOSContextGenerator;
import opennlp.tools.postag.POSContextGenerator;
import opennlp.tools.util.ObjectStream;

/**
 * Abstract class extended by parser event streams which perform tagging and chunking.
 */
public abstract class AbstractParserEventStream extends opennlp.tools.util.AbstractEventStream<Parse> {

  private ChunkerContextGenerator chunkerContextGenerator;
  private POSContextGenerator tagContextGenerator;
  protected HeadRules rules;
  protected Set<String> punctSet;

  /**
   * The type of events being generated by this event stream.
   */
  protected ParserEventTypeEnum etype;
  protected boolean fixPossesives;
  protected Dictionary dict;

  public AbstractParserEventStream(ObjectStream<Parse> d,
      HeadRules rules, ParserEventTypeEnum etype, Dictionary dict) {
    super(d);
    this.dict = dict;
    if (etype == ParserEventTypeEnum.CHUNK) {
      this.chunkerContextGenerator = new ChunkContextGenerator();
    }
    else if (etype == ParserEventTypeEnum.TAG) {
      this.tagContextGenerator = new DefaultPOSContextGenerator(null);
    }
    this.rules = rules;
    punctSet = rules.getPunctuationTags();
    this.etype = etype;

    init();
  }

  @Override
  protected Iterator<Event> createEvents(Parse sample) {
    List<Event> newEvents = new ArrayList<>();

    Parse.pruneParse(sample);
    if (fixPossesives) {
      Parse.fixPossesives(sample);
    }
    sample.updateHeads(rules);
    Parse[] chunks = getInitialChunks(sample);
    if (etype == ParserEventTypeEnum.TAG) {
      addTagEvents(newEvents, chunks);
    }
    else if (etype == ParserEventTypeEnum.CHUNK) {
      addChunkEvents(newEvents, chunks);
    }
    else {
      addParseEvents(newEvents, Parser.collapsePunctuation(chunks,punctSet));
    }

    return newEvents.iterator();
  }

  protected void init() {
    fixPossesives = false;
  }

  public AbstractParserEventStream(ObjectStream<Parse> d, HeadRules rules, ParserEventTypeEnum etype) {
    this(d,rules,etype,null);
  }

  public static Parse[] getInitialChunks(Parse p) {
    List<Parse> chunks = new ArrayList<>();
    getInitialChunks(p, chunks);
    return chunks.toArray(new Parse[chunks.size()]);
  }

  private static void getInitialChunks(Parse p, List<Parse> ichunks) {
    if (p.isPosTag()) {
      ichunks.add(p);
    }
    else {
      Parse[] kids = p.getChildren();
      boolean allKidsAreTags = true;
      for (Parse kid : kids) {
        if (!kid.isPosTag()) {
          allKidsAreTags = false;
          break;
        }
      }
      if (allKidsAreTags) {
        ichunks.add(p);
      }
      else {
        for (Parse kid : kids) {
          getInitialChunks(kid, ichunks);
        }
      }
    }
  }

  /**
   * Produces all events for the specified sentence chunks
   * and adds them to the specified list.
   * @param newEvents A list of events to be added to.
   * @param chunks Pre-chunked constituents of a sentence.
   */
  protected abstract void addParseEvents(List<Event> newEvents, Parse[] chunks);

  private void addChunkEvents(List<Event> chunkEvents, Parse[] chunks) {
    List<String> toks = new ArrayList<>();
    List<String> tags = new ArrayList<>();
    List<String> preds = new ArrayList<>();
    for (Parse c : chunks) {
      if (c.isPosTag()) {
        toks.add(c.getCoveredText());
        tags.add(c.getType());
        preds.add(Parser.OTHER);
      } else {
        boolean start = true;
        String ctype = c.getType();
        Parse[] kids = c.getChildren();
        for (Parse tok : kids) {
          toks.add(tok.getCoveredText());
          tags.add(tok.getType());
          if (start) {
            preds.add(Parser.START + ctype);
            start = false;
          } else {
            preds.add(Parser.CONT + ctype);
          }
        }
      }
    }
    for (int ti = 0, tl = toks.size(); ti < tl; ti++) {
      chunkEvents.add(new Event(preds.get(ti),
          chunkerContextGenerator.getContext(ti, toks.toArray(new String[toks.size()]),
          tags.toArray(new String[tags.size()]), preds.toArray(new String[preds.size()]))));
    }
  }

  private void addTagEvents(List<Event> tagEvents, Parse[] chunks) {
    List<String> toks = new ArrayList<>();
    List<String> preds = new ArrayList<>();
    for (Parse c : chunks) {
      if (c.isPosTag()) {
        toks.add(c.getCoveredText());
        preds.add(c.getType());
      } else {
        Parse[] kids = c.getChildren();
        for (Parse tok : kids) {
          toks.add(tok.getCoveredText());
          preds.add(tok.getType());
        }
      }
    }
    for (int ti = 0, tl = toks.size(); ti < tl; ti++) {
      tagEvents.add(new Event(preds.get(ti), tagContextGenerator.getContext(ti,
          toks.toArray(new String[toks.size()]), preds.toArray(new String[preds.size()]), null)));
    }
  }

  /**
   * Returns true if the specified child is the last child of the specified parent.
   * @param child The child parse.
   * @param parent The parent parse.
   * @return true if the specified child is the last child of the specified parent; false otherwise.
   */
  protected boolean lastChild(Parse child, Parse parent) {
    Parse[] kids = AbstractBottomUpParser.collapsePunctuation(parent.getChildren(),punctSet);
    return kids[kids.length - 1] == child;
  }

}


text:
<?php

namespace Google\Service\YouTube;

class VideoFileDetailsVideoStream extends \Google\Model
{
  public $aspectRatio;
  /**
   * @var string
   */
  public $bitrateBps;
  /**
   * @var string
   */
  public $codec;
  public $frameRateFps;
  /**
   * @var string
   */
  public $heightPixels;
  /**
   * @var string
   */
  public $rotation;
  /**
   * @var string
   */
  public $vendor;
  /**
   * @var string
   */
  public $widthPixels;

  public function setAspectRatio($aspectRatio)
  {
    $this->aspectRatio = $aspectRatio;
  }
  public function getAspectRatio()
  {
    return $this->aspectRatio;
  }
  /**
   * @param string
   */
  public function setBitrateBps($bitrateBps)
  {
    $this->bitrateBps = $bitrateBps;
  }
  /**
   * @return string
   */
  public function getBitrateBps()
  {
    return $this->bitrateBps;
  }
  /**
   * @param string
   */
  public function setCodec($codec)
  {
    $this->codec = $codec;
  }
  /**
   * @return string
   */
  public function getCodec()
  {
    return $this->codec;
  }
  public function setFrameRateFps($frameRateFps)
  {
    $this->frameRateFps = $frameRateFps;
  }
  public function getFrameRateFps()
  {
    return $this->frameRateFps;
  }
  /**
   * @param string
   */
  public function setHeightPixels($heightPixels)
  {
    $this->heightPixels = $heightPixels;
  }
  /**
   * @return string
   */
  public function getHeightPixels()
  {
    return $this->heightPixels;
  }
  /**
   * @param string
   */
  public function setRotation($rotation)
  {
    $this->rotation = $rotation;
  }
  /**
   * @return string
   */
  public function getRotation()
  {
    return $this->rotation;
  }
  /**
   * @param string
   */
  public function setVendor($vendor)
  {
    $this->vendor = $vendor;
  }
  /**
   * @return string
   */
  public function getVendor()
  {
    return $this->vendor;
  }
  /**
   * @param string
   */
  public function setWidthPixels($widthPixels)
  {
    $this->widthPixels = $widthPixels;
  }
  /**
   * @return string
   */
  public function getWidthPixels()
  {
    return $this->widthPixels;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(VideoFileDetailsVideoStream::class, 'Google_Service_YouTube_VideoFileDetailsVideoStream');


text:
/*
 * ExtensionType.hpp
 *
 *  Created on: 22.08.2016
 *      Author: Jarod
 */

#ifndef COREENGINE_SRC_DATA_EXTENSIONTYPE_HPP_
#define COREENGINE_SRC_DATA_EXTENSIONTYPE_HPP_
#include <stdint.h>
namespace Data{
	typedef uint_fast32_t ExtensionTypeID;
}
#include "Data.hpp"
namespace Data{
	typedef Data::Extension *(*ExtensionInitFunction)(Universal::Node&,Universal::Extension&);

	namespace ExtensionType{
	extern ExtensionTypeID registerExtensionType(ExtensionInitFunction,std::string);
	extern ExtensionInitFunction getInitFunction(ExtensionTypeID id);
	extern ExtensionTypeID getRuntimeID(std::string);

}
}

#endif /* COREENGINE_SRC_DATA_EXTENSIONTYPE_HPP_ */


text:
#define TYPE_SAFE

using System;
using System.Collections.Generic;
using NiL.JS.Core;

namespace NiL.JS.Expressions
{
#if !(PORTABLE || NETCORE)
    [Serializable]
#endif
    public sealed class Substract : Expression
    {
        protected internal override PredictedType ResultType
        {
            get
            {
                return PredictedType.Number;
            }
        }

        internal override bool ResultInTempContainer
        {
            get { return true; }
        }

        public Substract(Expression first, Expression second)
            : base(first, second, true)
        {

        }

        public override JSValue Evaluate(Context context)
        {
            //lock (this)
            {
#if TYPE_SAFE
                JSValue f = _left.Evaluate(context);
                JSValue s = null;
                long l = 0;
                int a;
                double da = 0.0;
                if (f._valueType == JSValueType.Integer
                    || f._valueType == JSValueType.Boolean)
                {
                    a = f._iValue;
                    s = _right.Evaluate(context);
                    if (s._valueType == JSValueType.Integer
                    || s._valueType == JSValueType.Boolean)
                    {
                        l = (long)a - s._iValue;
                        //if (l > 2147483647L
                        //    || l < -2147483648L)
                        if (l != (int)l)
                        {
                            _tempContainer._dValue = l;
                            _tempContainer._valueType = JSValueType.Double;
                        }
                        else
                        {
                            _tempContainer._iValue = (int)l;
                            _tempContainer._valueType = JSValueType.Integer;
                        }
                        return _tempContainer;
                    }
                    else
                        da = a;
                }
                else
                {
                    da = Tools.JSObjectToDouble(f);
                    s = _right.Evaluate(context);
                }
                _tempContainer._dValue = da - Tools.JSObjectToDouble(s);
                _tempContainer._valueType = JSValueType.Double;
                return _tempContainer;
#else
                tempResult.dValue = Tools.JSObjectToDouble(first.Invoke(context)) - Tools.JSObjectToDouble(second.Invoke(context));
                tempResult.valueType = JSObjectType.Double;
                return tempResult;
#endif
            }
        }

        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary<string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            var res = base.Build(ref _this, expressionDepth,  variables, codeContext, message, stats, opts);
            if (!res)
            {
                if (_left is Constant && Tools.JSObjectToDouble(_left.Evaluate(null)) == 0.0)
                {
                    _this = new Negation(_right);
                    return true;
                }
            }
            return res;
        }

        public override T Visit<T>(Visitor<T> visitor)
        {
            return visitor.Visit(this);
        }

        public override string ToString()
        {
            return "(" + _left + " - " + _right + ")";
        }
    }
}


text:
package org.reldb.dbrowser.ui.content.conversion;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ToolBar;
import org.reldb.dbrowser.ui.DbTab;
import org.reldb.dbrowser.ui.preferences.PreferenceChangeAdapter;
import org.reldb.dbrowser.ui.preferences.PreferenceChangeEvent;
import org.reldb.dbrowser.ui.preferences.PreferenceChangeListener;
import org.reldb.dbrowser.ui.preferences.PreferencePageGeneral;
import org.reldb.dbrowser.ui.preferences.Preferences;

public class DbTabContentConversion extends Composite {

	private ConversionPanel conversion;

    private PreferenceChangeListener preferenceChangeListener;

	public DbTabContentConversion(DbTab parentTab, String message, String dbDir, Composite contentParent) {
		super(contentParent, SWT.None);
		setLayout(new FormLayout());

		ToolBar toolBar = new ToolBar(this, SWT.None);
		FormData fd_toolBar = new FormData();
		fd_toolBar.left = new FormAttachment(0);
		fd_toolBar.top = new FormAttachment(0);
		fd_toolBar.right = new FormAttachment(100);
		toolBar.setLayoutData(fd_toolBar);

		conversion = new ConversionPanel(this, parentTab, message, dbDir, SWT.None);
		FormData fd_composite = new FormData();
		fd_composite.left = new FormAttachment(0);
		fd_composite.top = new FormAttachment(toolBar);
		fd_composite.right = new FormAttachment(100);
		fd_composite.bottom = new FormAttachment(100);
		conversion.setLayoutData(fd_composite);

		setupIcons();

		preferenceChangeListener = new PreferenceChangeAdapter("DbTabContentConversion") {
			@Override
			public void preferenceChange(PreferenceChangeEvent evt) {
				setupIcons();
			}
		};
		Preferences.addPreferenceChangeListener(PreferencePageGeneral.LARGE_ICONS, preferenceChangeListener);
	}

	public void dispose() {
		Preferences.removePreferenceChangeListener(PreferencePageGeneral.LARGE_ICONS, preferenceChangeListener);
		super.dispose();
	}

	private void setupIcons() {
	}

	public void notifyIconSizeChange() {
		setupIcons();
	}

}


text:
"""The ONVIF integration."""
from onvif.exceptions import ONVIFAuthError, ONVIFError, ONVIFTimeoutError

from homeassistant.components.ffmpeg import CONF_EXTRA_ARGUMENTS
from homeassistant.components.stream import CONF_RTSP_TRANSPORT, RTSP_TRANSPORTS
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    EVENT_HOMEASSISTANT_STOP,
    HTTP_BASIC_AUTHENTICATION,
    HTTP_DIGEST_AUTHENTICATION,
    Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady

from .const import CONF_SNAPSHOT_AUTH, DEFAULT_ARGUMENTS, DOMAIN
from .device import ONVIFDevice

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up ONVIF from a config entry."""
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    if not entry.options:
        await async_populate_options(hass, entry)

    device = ONVIFDevice(hass, entry)

    if not await device.async_setup():
        await device.device.close()
        return False

    if not device.available:
        raise ConfigEntryNotReady()

    if not entry.data.get(CONF_SNAPSHOT_AUTH):
        await async_populate_snapshot_auth(hass, device, entry)

    hass.data[DOMAIN][entry.unique_id] = device

    platforms = [Platform.BUTTON, Platform.CAMERA]

    if device.capabilities.events:
        platforms += [Platform.BINARY_SENSOR, Platform.SENSOR]

    await hass.config_entries.async_forward_entry_setups(entry, platforms)

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.async_stop)
    )

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""

    device = hass.data[DOMAIN][entry.unique_id]
    platforms = ["camera"]

    if device.capabilities.events and device.events.started:
        platforms += ["binary_sensor", "sensor"]
        await device.events.async_stop()

    return await hass.config_entries.async_unload_platforms(entry, platforms)

async def _get_snapshot_auth(device):
    """Determine auth type for snapshots."""
    if not device.capabilities.snapshot or not (device.username and device.password):
        return HTTP_DIGEST_AUTHENTICATION

    try:
        snapshot = await device.device.get_snapshot(device.profiles[0].token)

        if snapshot:
            return HTTP_DIGEST_AUTHENTICATION
        return HTTP_BASIC_AUTHENTICATION
    except (ONVIFAuthError, ONVIFTimeoutError):
        return HTTP_BASIC_AUTHENTICATION
    except ONVIFError:
        return HTTP_DIGEST_AUTHENTICATION

async def async_populate_snapshot_auth(hass, device, entry):
    """Check if digest auth for snapshots is possible."""
    auth = await _get_snapshot_auth(device)
    new_data = {**entry.data, CONF_SNAPSHOT_AUTH: auth}
    hass.config_entries.async_update_entry(entry, data=new_data)

async def async_populate_options(hass, entry):
    """Populate default options for device."""
    options = {
        CONF_EXTRA_ARGUMENTS: DEFAULT_ARGUMENTS,
        CONF_RTSP_TRANSPORT: next(iter(RTSP_TRANSPORTS)),
    }

    hass.config_entries.async_update_entry(entry, options=options)


text:
package org.apache.james.smtpserver;

import org.apache.james.protocols.smtp.SMTPSession;
import org.apache.james.protocols.smtp.hook.Hook;
import org.apache.james.protocols.smtp.hook.HookResult;
import org.apache.mailet.Mail;

/**
 * Custom message handlers must implement this interface The message hooks will
 * be server-wide common to all the SMTPHandlers, therefore the handlers must
 * store all the state information in the SMTPSession object
 */
public interface JamesMessageHook extends Hook {
    /**
     * Handle Message
     */
    HookResult onMessage(SMTPSession session, Mail mail);

}


text:
OAuth 1.0a
==========

`const createOAuth1Client = require('@arangodb/foxx/oauth1');`

The OAuth1 module provides abstractions over OAuth 1.0a providers like Twitter, XING and Tumblr.

**Examples**

The following extends the [user management example](Users.md):

```js
const router = createRouter();
const oauth1 = createOAuth1Client({
  // We'll use Twitter for this example
  requestTokenEndpoint: 'https://api.twitter.com/oauth/request_token',
  authEndpoint: 'https://api.twitter.com/oauth/authorize',
  accessTokenEndpoint: 'https://api.twitter.com/oauth/access_token',
  activeUserEndpoint: 'https://api.twitter.com/1.1/account/verify_credentials.json',
  clientId: 'keyboardcat',
  clientSecret: 'keyboardcat'
});

module.context.use('/oauth1', router);

// See the user management example for setting up the
// sessions and users objects used in this example
router.use(sessions);

router.post('/auth', function (req, res) {
  const url = req.reverse('oauth1_callback');
  const oauth_callback = req.makeAbsolute(url);
  const requestToken = oauth1.fetchRequestToken(oauth_callback);
  if (requestToken.oauth_callback_confirmed !== 'true') {
    res.throw(500, 'Could not fetch OAuth request token');
  }
  // Set request token cookie for five minutes
  res.cookie('oauth1_request_token', requestToken.oauth_token, {ttl: 60 * 5});
  // Redirect to the provider's authorization URL
  res.redirect(303, oauth1.getAuthUrl(requestToken.oauth_token));
});

router.get('/auth', function (req, res) {
  // Make sure CSRF cookie matches the URL
  const expectedToken = req.cookie('oauth1_request_token');
  if (!expectedToken || req.queryParams.oauth_token !== expectedToken) {
    res.throw(400, 'CSRF mismatch.');
  }
  const authData = oauth1.exchangeRequestToken(
    req.queryParams.oauth_token,
    req.queryParams.oauth_verifier
  );
  const twitterToken = authData.oauth_token;
  const twitterSecret = authData.oauth_token_secret;
  // Fetch the active user's profile info
  const profile = oauth1.fetchActiveUser(twitterToken, twitterSecret);
  const twitterId = profile.screen_name;
  // Try to find an existing user with the user ID
  // (this requires the users collection)
  let user = users.firstExample({twitterId});
  if (user) {
    // Update the twitterToken if it has changed
    if (
      user.twitterToken !== twitterToken ||
      user.twitterSecret !== twitterSecret
    ) {
      users.update(user, {twitterToken, twitterSecret});
    }
  } else {
    // Create a new user document
    user = {
      username: `twitter:${twitterId}`,
      twitterId,
      twitterToken
    }
    const meta = users.save(user);
    Object.assign(user, meta);
  }
  // Log the user in (this requires the session middleware)
  req.session.uid = user._key;
  req.session.twitterToken = authData.twitterToken;
  req.session.twitterSecret = authData.twitterSecret;
  req.sessionStorage.save(req.session);
  // Redirect to the default route
  res.redirect(303, req.makeAbsolute('/'));
}, 'oauth1_callback')
.queryParam('oauth_token', joi.string().optional())
.queryParam('oauth_verifier', joi.string().optional());
```

Creating an OAuth1.0a client
----------------------------

`createOAuth1Client(options): OAuth1Client`

Creates an OAuth1.0a client.

**Arguments**

* **options**: `Object`

  An object with the following properties:

  * **requestTokenEndpoint**: `string`

    The fully-qualified URL of the provider's [Temporary Credentials Request endpoint](https://tools.ietf.org/html/rfc5849#section-2.1). This URL is used to fetch the unauthenticated temporary credentials that will be used to generate the authorization redirect for the user.

  * **authEndpoint**: `string`

    The fully-qualified URL of the provider's [Resource Owner Authorization endpoint](https://tools.ietf.org/html/rfc5849#section-2.2). This is the URL the user will be redirected to in order to authorize the OAuth consumer (i.e. your service).

  * **accessTokenEndpoint**: `string`

    The fully-qualified URL of the provider's [Token Request endpoint](https://tools.ietf.org/html/rfc5849#section-2.3). This URL is used to exchange the authenticated temporary credentials received from the authorization redirect for the actual token credentials that can be used to make requests to the API server.

  * **activeUserEndpoint**: `string` (optional)

    The fully-qualified URL of the provider's endpoint for fetching details about the current user.

  * **clientId**: `string`

    The application's *Client ID* (or *Consumer Key*) for the provider.

  * **clientSecret**: `string`

    The application's *Client Secret* (or *Consumer Secret*) for the provider.

  * **signatureMethod**: `string` (Default: `"HMAC-SHA1"`)

    The cryptographic method that will be used to sign OAuth 1.0a requests.
    Only `"HMAC-SHA1-"` and `"PLAINTEXT"` are supported at this time.

    Note that many providers may not implement `"PLAINTEXT"` as it exposes the
    *Client Secret* and `oauth_token_secret` instead of generating a signature.

Returns an OAuth 1.0a client for the given provider.

### Setting up OAuth 1.0a for Twitter

If you want to use Twitter as the OAuth 1.0a provider, use the following options:

* *requestTokenEndpoint*: `https://api.twitter.com/oauth/request_token`
* *authEndpoint*: `https://api.twitter.com/oauth/authorize`
* *accessTokenEndpoint*: `https://api.twitter.com/oauth/access_token`
* *activeUserEndpoint*: `https://api.twitter.com/1.1/account/verify_credentials.json`

You also need to obtain a client ID and client secret from Twitter:

1. Create a regular account at [Twitter](https://www.twitter.com) or use an existing account you own.
2. Visit the [Twitter Application Management](https://apps.twitter.com) dashboard and sign in with your Twitter account.
3. Click on *Create New App* and follow the instructions provided. The *Callback URL* should match your *oauth_callback* later. You may be prompted to add a mobile phone number to your account and verify it.
4. Open the *Keys and Access Tones* tab, then note down the *Consumer Key* and *Consumer Secret*.
5. Set the option *clientId* to the *Consumer Key* and the option *clientSecret* to the *Consumer Secret*.

Note that if you only need read-only access to public information, [you can also use the *clientId* and *clientSecret* directly](https://dev.twitter.com/oauth/application-only) without OAuth 1.0a.

See [Twitter REST API Reference Documentation](https://dev.twitter.com/rest/reference).

### Setting up OAuth 1.0a for XING

If you want to use XING as the OAuth 1.0a provider, use the following options:

* *requestTokenEndpoint*: `https://api.xing.com/v1/request_token`
* *authEndpoint*: `https://api.xing.com/v1/authorize`
* *accessTokenEndpoint*: `https://api.xing.com/v1/access_token`
* *activeUserEndpoint*: `https://api.xing.com/v1/users/me`

You also need to obtain a client ID and client secret from XING:

1. Create a regular account at [XING](https://xing.com) or use an existing account you own.
2. Visit the [XING Developer](https://dev.xing.com) page and sign in with your XING account.
3. Click on *Create app* and note down the *Consumer key* and *Consumer secret*.
4. Set the option *clientId* to the *Consumer key* and the option *clientSecret* to the *Consumer secret*.

See [XING Developer Documentation](https://dev.xing.com/docs).

### Setting up OAuth 1.0a for Tumblr

If you want to use Tumblr as the OAuth 1.0a provider, use the following options:

* *requestTokenEndpoint*: `https://www.tumblr.com/oauth/request_token`
* *authEndpoint*: `https://www.tumblr.com/oauth/authorize`
* *accessTokenEndpoint*: `https://www.tumblr.com/oauth/access_token`
* *activeUserEndpoint*: `https://api.tumblr.com/v2/user/info`

You also need to obtain a client ID and client secret from Tumblr:

1. Create a regular account at [Tumblr](https://www.tumblr.com) or use an existing account you own.
2. Visit the [Tumblr Applications](https://www.tumblr.com/oauth/apps) dashboard.
3. Click on *Register application*, then follow the instructions provided. The *Default callback URL* should match your *oauth_callback* later.
4. Note down the *OAuth Consumer Key* and *Secret Key*. The secret may be hidden by default.
5. Set the option *clientId* to the *OAuth Consumer Key* and the option *clientSecret* to the *Secret Key*.

See [Tumblr API Documentation](https://www.tumblr.com/docs/en/api/v2).

Fetch an unauthenticated request token
--------------------------------------

`oauth1.fetchRequestToken(oauth_callback, opts)`

Fetches an `oauth_token` that can be used to create an authorization URL that redirects to the given `oauth_callback` on confirmation.

Performs a *POST* response to the *requestTokenEndpoint*.

Throws an exception if the remote server responds with an empty response body.

**Arguments**

* **oauth_callback**: `string`

  The fully-qualified URL of your application's OAuth 1.0a callback.

* **opts**: `Object` (optional)

  An object with additional query parameters to include in the request.

  See [RFC 5849](https://tools.ietf.org/html/rfc5849).

Returns the parsed response object.

Get the authorization URL
-------------------------

`oauth1.getAuthUrl(oauth_token, opts): string`

Generates the authorization URL for the authorization endpoint.

**Arguments**

* **oauth_token**: `string`

  The `oauth_token` previously returned by `fetchRequestToken`.

* **opts**: (optional)

  An object with additional query parameters to add to the URL.

  See [RFC 5849](https://tools.ietf.org/html/rfc5849).

Returns a fully-qualified URL for the authorization endpoint of the provider by appending the `oauth_token` and any additional arguments from *opts* to the *authEndpoint*.

**Examples**

```js
const requestToken = oauth1.fetchRequestToken(oauth_callback);
if (requestToken.oauth_callback_confirmed !== 'true') {
  throw new Error('Provider could not confirm OAuth 1.0 callback');
}
const authUrl = oauth1.getAuthUrl(requestToken.oauth_token);
```

Exchange an authenticated request token for an access token
-----------------------------------------------------------

`oauth1.exchangeRequestToken(oauth_token, oauth_verifier, opts)`

Takes a pair of authenticated temporary credentials passed to the callback URL by the provider and exchanges it for an `oauth_token` and `oauth_token_secret` than can be used to perform authenticated requests to the OAuth 1.0a provider.

Performs a *POST* response to the *accessTokenEndpoint*.

Throws an exception if the remote server responds with an empty response body.

**Arguments**

* **oauth_token**: `string`

  The `oauth_token` passed to the callback URL by the provider.

* **oauth_verifier**: `string`

  The `oauth_verifier` passed to the callback URL by the provider.

* **opts**: `Object` (optional)

  An object with additional query parameters to include in the request.

  See [RFC 5849](https://tools.ietf.org/html/rfc5849).

Returns the parsed response object.

Fetch the active user
---------------------

`oauth1.fetchActiveUser(oauth_token, oauth_token_secret, opts): Object`

Fetches details of the active user.

Performs a *GET* response to the *activeUserEndpoint*.

Throws an exception if the remote server responds with an empty response body.

Returns `null` if the *activeUserEndpoint* is not configured.

**Arguments**

* **oauth_token**: `string`

  An OAuth 1.0a access token as returned by *exchangeRequestToken*.

* **oauth_token_secret**: `string`

  An OAuth 1.0a access token secret as returned by *exchangeRequestToken*.

* **opts**: `Object` (optional)

  An object with additional query parameters to include in the request.

  See [RFC 5849](https://tools.ietf.org/html/rfc5849).

Returns the parsed response object.

**Examples**

```js
const authData = oauth1.exchangeRequestToken(oauth_token, oauth_verifier);
const userData = oauth1.fetchActiveUser(authData.oauth_token, authData.oauth_token_secret);
```

Create an authenticated request object
--------------------------------------

`oauth1.createSignedRequest(method, url, parameters, oauth_token, oauth_token_secret)`

Creates a request object that can be used to perform a request to the OAuth 1.0a provider with the provided token credentials.

**Arguments**

* **method**: `string`

  HTTP method the request will use, e.g. `"POST"`.

* **url**: `string`

  The fully-qualified URL of the provider the request will be performed against.

  The URL may optionally contain any number of query parameters.

* **parameters**: `string | Object | null`

  An additional object or query string containing query parameters or body parameters that will be part of the signed request.

* **oauth_token**: `string`

  An OAuth 1.0a access token as returned by *exchangeRequestToken*.

* **oauth_token_secret**: `string`

  An OAuth 1.0a access token secret as returned by *exchangeRequestToken*.

Returns an object with three properties:

 * **url**: The normalized URL without any query parameters.

 * **qs**: A normalized query string containing all *parameters* and query parameters.

 * **headers**: An object containing the following properties:

   * **accept**: The string `"application/json"`.

   * **authorization**: An OAuth authorization header containing all OAuth parameters and the request signature.

**Examples**

Fetch a list of tweets mentioning `@arangodb`:

```js
const request = require('@arangodb/request');
const req = oauth1.createSignedRequest(
  'GET',
  'https://api.twitter.com/1.1/search/tweets.json',
  {q: '@arangodb'},
  authData.oauth_token,
  authData.oauth_token_secret
);
const res = request(req);
console.log(res.json.statuses);
```

Signing a more complex request:

```js
const url = 'https://api.example.com/v1/timeline?visible=public';
const params = {hello: 'world', longcat: 'is long'};
const req = oauth1.createSignedRequest(
  'POST',
  url, // URL includes a query parameter that will be signed
  params, // Request body needs to be signed too
  authData.oauth_token,
  authData.oauth_token_secret
);
const res = request.post(url, {
  form: params,
  headers: {
    accept: 'application/x-www-form-urlencoded',
    // Authorization header includes the signature
    authorization: req.headers.authorization
  }
});
console.log(res.json);
```


text:
<?php

namespace Doctrine\DBAL;

use function str_replace;
use function strtolower;
use function version_compare;

/**
 * Class to store and retrieve the version of Doctrine.
 */
class Version
{
    /**
     * Current Doctrine Version.
     */
    public const VERSION = '2.10.4';

    /**
     * Compares a Doctrine version with the current one.
     *
     * @param string $version The Doctrine version to compare to.
     *
     * @return int -1 if older, 0 if it is the same, 1 if version passed as argument is newer.
     */
    public static function compare($version)
    {
        $currentVersion = str_replace(' ', '', strtolower(self::VERSION));
        $version        = str_replace(' ', '', $version);

        return version_compare($version, $currentVersion);
    }
}


text:
package picklesjar.pickles.ut.runtime.routine.config;

import picklesjar.pickles.ut.recipes.sequence.ShouldBeBefore;
import picklesjar.pickles.ut.runtime.UnitTestRuntimeFoundation;
import picklesjar.pickles.ut.runtime.routine.lock.LockRoutine;

public interface ThreadConfigRoutine
	extends ConfigureRoutine {

	/**
	 *
	 *
	 *
	 */
	@ShouldBeBefore( value = LockRoutine.class, queries = { "lock()" } )
	public static void setToSingleThread() {

		ConfigureCommonUtil.config(
			UnitTestRuntimeFoundation.SINGLE_THREAD_MODE );
	}

	/**
	 *
	 *
	 *
	 * @param flag
	 */
	@ShouldBeBefore( value = LockRoutine.class, queries = { "lock()" } )
	public static void setToSingleThreadWith( int flag ) {

		ConfigureCommonUtil.config(
			UnitTestRuntimeFoundation.SINGLE_THREAD_MODE | flag );
	}

	/**
	 *
	 *
	 *
	 */
	@ShouldBeBefore( value = LockRoutine.class, queries = { "lock()" } )
	public static void setToMultiThread() {

		ConfigureCommonUtil.config(
			UnitTestRuntimeFoundation.MULTI_THREAD_MODE );
	}

	/**
	 *
	 *
	 *
	 * @param flag
	 */
	@ShouldBeBefore( value = LockRoutine.class, queries = { "lock()" } )
	public static void setToMultiThreadWith( int flag ) {

		ConfigureCommonUtil.config(
			UnitTestRuntimeFoundation.MULTI_THREAD_MODE | flag );
	}

}


text:
package cern.accsoft.steering.aloha.gui.icons;

import javax.swing.ImageIcon;

public enum Icon {

	MAIN("hawaii-dancer-icon.gif"),
	FILE_OPEN("file-open.png"),
	EXIT("exit.gif"),
	SAVE("save.png"),
	MADX("madx.png"),
	SELECT_RANGE("tool.png"),
	VIEW_DATA("barchart.png"),
	SINE_FIT("linechart.png"),
	CALC_ONCE("small_playstop2.gif"),
	CALC_ONCE_DISABLED("small_playstop_d.gif"),
	SPLASH("aloha-splash.jpg"),
	ABOUT("hawaii-sunset-left.jpg");

	private final static String PATH_PREFIX = "data/";

	private String name = null;

	private Icon(String name) {
		this.name = name;
	}

	public ImageIcon getImageIcon() {
		return new ImageIcon(Icon.class.getResource(PATH_PREFIX + name));
	}
}


text:
class ProviderUdp : public LedDevice
{
public:
	///
	/// Constructs specific LedDevice
	///
	ProviderUdp();

	///
	/// Destructor of the LedDevice; closes the output device if it is open
	///
	virtual ~ProviderUdp();

	///
	/// Sets configuration
	///
	/// @param deviceConfig the json device config
	/// @return true if success
	bool init(const QJsonObject &deviceConfig, std::string defaultHost="127.0.0.1");

	///
	/// Opens and configures the output device
	///
	/// @return Zero on succes else negative
	///
	int open();

protected:
	///
	/// Writes the given bytes/bits to the SPI-device and sleeps the latch time to ensure that the
	/// values are latched.
	///
	/// @param[in] size The length of the data
	/// @param[in] data The data
	///
	/// @return Zero on succes else negative
	///
	int writeBytes(const unsigned size, const uint8_t *data);

	/// The time which the device should be untouched after a write
	int _LatchTime_ns;

	///
	QUdpSocket * _udpSocket;
	QHostAddress _address;
	quint16      _port;
};


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/debug/crash_logging.h"
#include "base/debug/debugger.h"
#include "base/files/file_path.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_executor.h"
#include "base/threading/platform_thread.h"
#include "build/build_config.h"
#include "content/child/child_process.h"
#include "content/common/content_constants_internal.h"
#include "content/common/content_switches_internal.h"
#include "content/ppapi_plugin/ppapi_thread.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "ipc/ipc_sender.h"
#include "ppapi/proxy/plugin_globals.h"
#include "ppapi/proxy/proxy_module.h"
#include "services/tracing/public/cpp/trace_startup.h"
#include "ui/base/ui_base_switches.h"

#if defined(OS_WIN)
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
#include "content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.h"
#include "sandbox/win/src/sandbox.h"
#include "third_party/blink/public/web/win/web_font_rendering.h"
#include "third_party/skia/include/ports/SkTypeface_win.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/win/direct_write.h"
#endif

#if defined(OS_CHROMEOS)
#include "base/files/file_util.h"
#endif

#if defined(OS_LINUX)
#include "content/public/common/sandbox_init.h"
#include "services/service_manager/sandbox/linux/sandbox_linux.h"
#endif

#ifdef V8_USE_EXTERNAL_STARTUP_DATA
#include "gin/v8_initializer.h"
#endif

#if defined(OS_POSIX) && !defined(OS_ANDROID)
#include <stdlib.h>
#endif

#if defined(OS_WIN)
sandbox::TargetServices* g_target_services = NULL;
#else
void* g_target_services = nullptr;
#endif

namespace content {

// Main function for starting the PPAPI plugin process.
int PpapiPluginMain(const MainFunctionParams& parameters) {
  const base::CommandLine& command_line = parameters.command_line;

#if defined(OS_WIN)
  g_target_services = parameters.sandbox_info->target_services;
#endif

  // If |g_target_services| is not null this process is sandboxed. One side
  // effect is that we can't pop dialogs like WaitForDebugger() does.
  if (command_line.HasSwitch(switches::kPpapiStartupDialog)) {
    if (g_target_services)
      base::debug::WaitForDebugger(2*60, false);
    else
      WaitForDebugger("Ppapi");
  }

  // Set the default locale to be the current UI language. WebKit uses ICU's
  // default locale for some font settings (especially switching between
  // Japanese and Chinese fonts for the same characters).
  if (command_line.HasSwitch(switches::kLang)) {
    std::string locale = command_line.GetSwitchValueASCII(switches::kLang);
    base::i18n::SetICUDefaultLocale(locale);

#if defined(OS_POSIX) && !defined(OS_ANDROID)
    // TODO(shess): Flash appears to have a POSIX locale dependency
    // outside of the existing PPAPI ICU support.  Certain games hang
    // while loading, and it seems related to datetime formatting.
    // http://crbug.com/155396
    // http://crbug.com/155671
    //
    // ICU can accept "en-US" or "en_US", but POSIX wants "en_US".
    std::replace(locale.begin(), locale.end(), '-', '_');
    locale.append(".UTF-8");
    setlocale(LC_ALL, locale.c_str());
    setenv("LANG", locale.c_str(), 0);
#endif
  }

#if defined(OS_CHROMEOS)
  // Specifies $HOME explicitly because some plugins rely on $HOME but
  // no other part of Chrome OS uses that.  See crbug.com/335290.
  base::FilePath homedir;
  base::PathService::Get(base::DIR_HOME, &homedir);
  setenv("HOME", homedir.value().c_str(), 1);
#endif

  base::SingleThreadTaskExecutor main_thread_task_executor;
  base::PlatformThread::SetName("CrPPAPIMain");
  base::trace_event::TraceLog::GetInstance()->set_process_name("PPAPI Process");
  base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
      kTraceEventPpapiProcessSortIndex);

#ifdef V8_USE_EXTERNAL_STARTUP_DATA
  gin::V8Initializer::LoadV8Snapshot();
#endif

#if defined(OS_LINUX)
  service_manager::SandboxLinux::GetInstance()->InitializeSandbox(
      service_manager::SandboxTypeFromCommandLine(command_line),
      service_manager::SandboxLinux::PreSandboxHook(),
      service_manager::SandboxLinux::Options());
#endif

  ChildProcess ppapi_process;
  base::RunLoop run_loop;
  ppapi_process.set_main_thread(new PpapiThread(run_loop.QuitClosure(),
                                                parameters.command_line,
                                                false /* Not a broker */));

#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
  // Startup tracing is usually enabled earlier, but if we forked from a zygote,
  // we can only enable it after mojo IPC support is brought up by PpapiThread,
  // because the mojo broker has to create the tracing SMB on our behalf due to
  // the zygote sandbox.
  if (parameters.zygote_child)
    tracing::EnableStartupTracingIfNeeded();
#endif  // OS_POSIX && !OS_ANDROID && !!OS_MACOSX

#if defined(OS_WIN)
  if (!base::win::IsUser32AndGdi32Available())
    gfx::win::InitializeDirectWrite();
  InitializeDWriteFontProxy();

  int antialiasing_enabled = 1;
  base::StringToInt(
      command_line.GetSwitchValueASCII(switches::kPpapiAntialiasedTextEnabled),
      &antialiasing_enabled);
  blink::WebFontRendering::SetAntialiasedTextEnabled(
      antialiasing_enabled ? true : false);

  int subpixel_rendering = 0;
  base::StringToInt(command_line.GetSwitchValueASCII(
                        switches::kPpapiSubpixelRenderingSetting),
                    &subpixel_rendering);
  blink::WebFontRendering::SetLCDTextEnabled(
      subpixel_rendering != gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE);
#endif

  run_loop.Run();

#if defined(OS_WIN)
  UninitializeDWriteFontProxy();
#endif
  return 0;
}

}  // namespace content


text:
#ifndef GCC_TREE_SSA_LOOP_H
#define GCC_TREE_SSA_LOOP_H

/* Affine iv.  */

struct affine_iv
{
  /* Iv = BASE + STEP * i.  */
  tree base, step;

  /* True if this iv does not overflow.  */
  bool no_overflow;
};

/* Description of number of iterations of a loop.  All the expressions inside
   the structure can be evaluated at the end of the loop's preheader
   (and due to ssa form, also anywhere inside the body of the loop).  */

struct tree_niter_desc
{
  tree assumptions;	/* The boolean expression.  If this expression evaluates
			   to false, then the other fields in this structure
			   should not be used; there is no guarantee that they
			   will be correct.  */
  tree may_be_zero;	/* The boolean expression.  If it evaluates to true,
			   the loop will exit in the first iteration (i.e.
			   its latch will not be executed), even if the niter
			   field says otherwise.  */
  tree niter;		/* The expression giving the number of iterations of
			   a loop (provided that assumptions == true and
			   may_be_zero == false), more precisely the number
			   of executions of the latch of the loop.  */
  double_int max;	/* The upper bound on the number of iterations of
			   the loop.  */

  /* The simplified shape of the exit condition.  The loop exits if
     CONTROL CMP BOUND is false, where CMP is one of NE_EXPR,
     LT_EXPR, or GT_EXPR, and step of CONTROL is positive if CMP is
     LE_EXPR and negative if CMP is GE_EXPR.  This information is used
     by loop unrolling.  */
  affine_iv control;
  tree bound;
  enum tree_code cmp;
};

extern bool for_each_index (tree *, bool (*) (tree, tree *, void *), void *);
extern char *get_lsm_tmp_name (tree ref, unsigned n, const char *suffix = NULL);
extern unsigned tree_num_loop_insns (struct loop *, struct eni_weights_d *);

/* Returns the loop of the statement STMT.  */

static inline struct loop *
loop_containing_stmt (gimple stmt)
{
  basic_block bb = gimple_bb (stmt);
  if (!bb)
    return NULL;

  return bb->loop_father;
}

#endif /* GCC_TREE_SSA_LOOP_H */


text:
from numpy.random.mtrand import uniform
import netCDF4
from timeit import Timer
import os, sys

# create an n1dim by n2dim by n3dim random array.
n1dim = 30
n2dim = 15
n3dim = 73
n4dim = 144
ntrials = 10
sys.stdout.write('reading and writing a %s by %s by %s by %s random array ..\n'%(n1dim,n2dim,n3dim,n4dim))
sys.stdout.write('(average of %s trials)\n\n' % ntrials)
array = uniform(size=(n1dim,n2dim,n3dim,n4dim))

def write_netcdf(filename,complevel,lsd):
    file = netCDF4.Dataset(filename,'w',format='NETCDF4')
    file.createDimension('n1', n1dim)
    file.createDimension('n2', n2dim)
    file.createDimension('n3', n3dim)
    file.createDimension('n4', n4dim)
    foo = file.createVariable('data',\
                              'f8',('n1','n2','n3','n4'),\
                              zlib=True,shuffle=True,complevel=complevel,\
                              least_significant_digit=lsd)
    foo[:] = array
    file.close()

def read_netcdf(filename):
    file = netCDF4.Dataset(filename)
    data = file.variables['data'][:]
    file.close()

lsd = None
sys.stdout.write('using least_significant_digit %s\n\n' % lsd)
for complevel in range(0,10,2):
    sys.stdout.write('testing compression with complevel %s...\n' % complevel)
    # writing.
    t = Timer("write_netcdf('test.nc',%s,%s)" % (complevel,lsd),"from __main__ import write_netcdf")
    sys.stdout.write('writing took %s seconds\n' %\
            repr(sum(t.repeat(ntrials,1))/ntrials))
    # test reading.
    t = Timer("read_netcdf('test.nc')","from __main__ import read_netcdf")
    sys.stdout.write('reading took %s seconds\n' %
            repr(sum(t.repeat(ntrials,1))/ntrials))
    # print out size of resulting files.
    sys.stdout.write('size of test.nc = %s\n'%repr(os.stat('test.nc').st_size))

complevel = 4
sys.stdout.write('\nusing complevel %s\n\n' % complevel)
for lsd in range(1,6):
    sys.stdout.write('testing compression with least_significant_digit %s...\n' % lsd)
    # writing.
    t = Timer("write_netcdf('test.nc',%s,%s)" % (complevel,lsd),"from __main__ import write_netcdf")
    sys.stdout.write('writing took %s seconds\n' %\
            repr(sum(t.repeat(ntrials,1))/ntrials))
    # test reading.
    t = Timer("read_netcdf('test.nc')","from __main__ import read_netcdf")
    sys.stdout.write('reading took %s seconds\n' %
            repr(sum(t.repeat(ntrials,1))/ntrials))
    # print out size of resulting files.
    sys.stdout.write('size of test.nc = %s\n'%repr(os.stat('test.nc').st_size))


text:
@if($data)
    @php
        // need to recreate object because policy might depend on record data
        $class = get_class($action);
        $action = new $class($dataType, $data);
    @endphp
    @can ($action->getPolicy(), $data)
        @if ($action->shouldActionDisplayOnRow($data))
            getRoute($dataType->name) }}" title="{{ $action->getTitle() }}" {!! $action->convertAttributesToHtml() !!}>
                getIcon() }}"> {{ $action->getTitle() }}

        @endif
    @endcan
@elseif (method_exists($action, 'massAction'))
    <form method="post" action="{{ route('voyager.'.$dataType->slug.'.action') }}" style="display:inline">
        {{ csrf_field() }}
        <button type="submit" {!! $action->convertAttributesToHtml() !!}>getIcon() }}">  {{ $action->getTitle() }}</button>
        <input type="hidden" name="action" value="{{ get_class($action) }}">
        <input type="hidden" name="ids" value="" class="selected_ids">
    </form>
@endif


text:
function noSideBar() {
    $(".navbar-side").toggleClass("collapsed");
    $("#page-wrapper").toggleClass("collapsed");
    $("#sidebar-toggle").hide();
}

//Sidebar Toggle
$("#sidebar-toggle").click(function(e) {
    e.preventDefault();
    $(".navbar-side").toggleClass("collapsed");
    $("#page-wrapper").toggleClass("collapsed");
});

//Portlet Icon Toggle
$(".portlet-widgets .fa-chevron-down, .portlet-widgets .fa-chevron-up").click(function() {
    $(this).toggleClass("fa-chevron-down fa-chevron-up");
});

//Portlet Refresh Icon
(function($) {

    $.fn.extend({

        addTemporaryClass: function(className, duration) {
            var elements = this;
            setTimeout(function() {
                elements.removeClass(className);
            }, duration);

            return this.each(function() {
                $(this).addClass(className);
            });
        }
    });

})(jQuery);

$("a i.fa-refresh").click(function() {
    $(this).addTemporaryClass("fa-spin fa-spinner", 2000);
});

//Slim Scroll
$(function() {
    $('#messageScroll, #alertScroll, #taskScroll').slimScroll({
        height: '200px',
        alwaysVisible: true,
        disableFadeOut: true,
        touchScrollStep: 50
    });
});

//Easing Script for Smooth Page Transitions
$(function() {
    $('.page-content').addClass('page-content-ease-in');
});

//Tooltips
$(function() {

    // Tooltips for sidebar toggle and sidebar logout button
    $('.tooltip-sidebar-toggle, .tooltip-sidebar-logout').tooltip({
        selector: "[data-toggle=tooltip]",
        container: "body"
    })

})

//HISRC Responsive Images
$(document).ready(function() {
    $(".hisrc").hisrc();
});


text:
/**
 *
 */
package conversores;

import java.text.MessageFormat;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
//import javax.faces.component.UIViewRoot;
//import java.util.Locale;

import util.Utilitario;

/**
 * @author marques
 *
 */
public class ConversorDouble implements Converter {

	/**
	 *
	 */
	public ConversorDouble() {

			System.out.println(">>>>>>>> Instanciou o ConversorDouble");
	}

	public Object getAsObject(FacesContext contexto,
                              UIComponent componente,
                              String novoValor)
		throws ConverterException
	{
		System.out.println(">>>>>>>>>>>>>>>>>>> Executou getAsObject de ConversorDouble");

		try
		{	Double valor = null;

			if (novoValor != null && novoValor.trim().length() > 0)
			{
			System.out.println(">>>>>>>>>>>>>>>>>>> Executou getAsObject de ConversorDouble <<<<<<<<<<<<<<<<<<<<<<");
				valor = Utilitario.strToDouble(novoValor);
			}

			return valor;
		}
		catch(Exception e)
		{
			//	recuperando o texto da mensagem a partir do message bundle
			FacesContext context = FacesContext.getCurrentInstance();

			Application app = context.getApplication();
			String appBundleName = app.getMessageBundle();

			ResourceBundle bundle = ResourceBundle.getBundle(appBundleName);
			String msg = bundle.getString("erroConversaoDouble");

			String campo = bundle.getString(componente.getId());
			campo = "'"+campo+"'";

			Object[] params = {campo};
			MessageFormat formatter = new MessageFormat(msg);
			String texto = formatter.format(params);

			FacesMessage mensagem = new FacesMessage(texto);

			throw new ConverterException(mensagem);
		}

  }

	public String getAsString(FacesContext contexto,
			                  UIComponent componente,
			                  Object valor)
		throws ConverterException
	{	System.out.println(">>>>>>>>>>>>>>>>>>> Executou getAsString de ConversorDouble");

		return Utilitario.doubleToStr((Double)valor);
	}
}


text:
var subscription = Meteor.subscribe('orion_dictionary');

/**
 * Access the dictionary on any template
 */
Template.registerHelper('dict', function(name, defaultValue) {
  return orion.dictionary.get(name, defaultValue);
});

/**
 * Is the dictionary subscription ready
 */
orion.dictionary.isReady = function() {
  return subscription.ready();
};

/**
 * Is the dictionary subscription ready for templates
 */
Template.registerHelper('dictionaryReady', function() {
  return subscription.ready();
});

orion.dictionary.availableCategories = function() {
  return _.union.apply(this, Roles.helper(Meteor.userId(), 'dictionary.allowedCategories'));
};


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.Framework;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Evaluation;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Shared;
using Microsoft.Build.Execution;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using Microsoft.Build.Unittest;

namespace Microsoft.Build.UnitTests.BackEnd
{
    [TestClass]
    public class BuildResult_Tests
    {
        private int _nodeRequestId;

        [TestInitialize]
        public void SetUp()
        {
            _nodeRequestId = 1;
        }

        [TestCleanup]
        public void TearDown()
        {
        }

        [TestMethod]
        public void TestConstructorGood()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result2 = new BuildResult(request);
        }

        [TestMethod]
        public void Clone()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result1 = new BuildResult(request);
            result1.ResultsByTarget.Add("FOO", TestUtilities.GetEmptySucceedingTargetResult());
            Assert.IsTrue(result1.ResultsByTarget.ContainsKey("foo")); // test comparer

            BuildResult result2 = result1.Clone();

            result1.ResultsByTarget.Add("BAR", TestUtilities.GetEmptySucceedingTargetResult());
            Assert.IsTrue(result1.ResultsByTarget.ContainsKey("foo")); // test comparer
            Assert.IsTrue(result1.ResultsByTarget.ContainsKey("bar"));

            Assert.AreEqual(result1.SubmissionId, result2.SubmissionId);
            Assert.AreEqual(result1.ConfigurationId, result2.ConfigurationId);
            Assert.AreEqual(result1.GlobalRequestId, result2.GlobalRequestId);
            Assert.AreEqual(result1.ParentGlobalRequestId, result2.ParentGlobalRequestId);
            Assert.AreEqual(result1.NodeRequestId, result2.NodeRequestId);
            Assert.AreEqual(result1.CircularDependency, result2.CircularDependency);
            Assert.AreEqual(result1.ResultsByTarget["foo"], result2.ResultsByTarget["foo"]);
            Assert.AreEqual(result1.OverallResult, result2.OverallResult);
        }

        [ExpectedException(typeof(InternalErrorException))]
        [TestMethod]
        public void TestConstructorBad()
        {
            BuildResult result = new BuildResult(null);
        }

        [TestMethod]
        public void TestConfigurationId()
        {
            BuildRequest request = CreateNewBuildRequest(-1, new string[0]);
            BuildResult result = new BuildResult(request);
            Assert.AreEqual(-1, result.ConfigurationId);

            BuildRequest request2 = CreateNewBuildRequest(1, new string[0]);
            BuildResult result2 = new BuildResult(request2);
            Assert.AreEqual(1, result2.ConfigurationId);
        }

        [TestMethod]
        public void TestExceptionGood()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            Assert.IsNull(result.Exception);

            AccessViolationException e = new AccessViolationException();
            result = new BuildResult(request, e);

            Assert.AreEqual(e, result.Exception);
        }

        [TestMethod]
        public void TestOverallResult()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            Assert.AreEqual(BuildResultCode.Success, result.OverallResult);

            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());
            Assert.AreEqual(BuildResultCode.Success, result.OverallResult);

            result.AddResultsForTarget("bar", new TargetResult(new TaskItem[0] { }, new WorkUnitResult(WorkUnitResultCode.Success, WorkUnitActionCode.Continue, new Exception())));
            Assert.AreEqual(BuildResultCode.Success, result.OverallResult);

            result.AddResultsForTarget("baz", new TargetResult(new TaskItem[0] { }, TestUtilities.GetStopWithErrorResult(new Exception())));
            Assert.AreEqual(BuildResultCode.Failure, result.OverallResult);

            BuildRequest request2 = CreateNewBuildRequest(2, new string[0]);
            BuildResult result2 = new BuildResult(request2);
            result2.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());
            result2.AddResultsForTarget("bar", TestUtilities.GetEmptyFailingTargetResult());
            Assert.AreEqual(BuildResultCode.Failure, result2.OverallResult);
        }

        [TestMethod]
        public void TestPacketType()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            Assert.AreEqual(NodePacketType.BuildResult, ((INodePacket)result).Type);
        }

        [TestMethod]
        public void TestAddAndRetrieve()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());
            result.AddResultsForTarget("bar", TestUtilities.GetEmptyFailingTargetResult());

            Assert.AreEqual(TargetResultCode.Success, result["foo"].ResultCode);
            Assert.AreEqual(TargetResultCode.Failure, result["bar"].ResultCode);
        }

        [ExpectedException(typeof(KeyNotFoundException))]
        [TestMethod]
        public void TestIndexerBad1()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            ITargetResult targetResult = result["foo"];
        }

        [ExpectedException(typeof(KeyNotFoundException))]
        [TestMethod]
        public void TestIndexerBad2()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());
            ITargetResult targetResult = result["bar"];
        }

        [ExpectedException(typeof(ArgumentNullException))]
        [TestMethod]
        public void TestAddResultsInvalid1()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget(null, TestUtilities.GetEmptySucceedingTargetResult());
        }

        [ExpectedException(typeof(ArgumentNullException))]
        [TestMethod]
        public void TestAddResultsInvalid2()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", null);
        }

        [ExpectedException(typeof(ArgumentNullException))]
        [TestMethod]
        public void TestAddResultsInvalid3()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget(null, TestUtilities.GetEmptySucceedingTargetResult());
        }

        [TestMethod]
        public void TestMergeResults()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());

            BuildResult result2 = new BuildResult(request);
            result.AddResultsForTarget("bar", TestUtilities.GetEmptyFailingTargetResult());

            result.MergeResults(result2);
            Assert.AreEqual(TargetResultCode.Success, result["foo"].ResultCode);
            Assert.AreEqual(TargetResultCode.Failure, result["bar"].ResultCode);

            BuildResult result3 = new BuildResult(request);
            result.MergeResults(result3);

            BuildResult result4 = new BuildResult(request);
            result4.AddResultsForTarget("xor", TestUtilities.GetEmptySucceedingTargetResult());
            result.MergeResults(result4);
            Assert.AreEqual(TargetResultCode.Success, result["foo"].ResultCode);
            Assert.AreEqual(TargetResultCode.Failure, result["bar"].ResultCode);
            Assert.AreEqual(TargetResultCode.Success, result["xor"].ResultCode);
        }

        [ExpectedException(typeof(ArgumentNullException))]
        [TestMethod]
        public void TestMergeResultsBad1()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());

            result.MergeResults(null);
        }

        // See the implementation of BuildResult.MergeResults for an explanation of why this
        // test is disabled.
#if false
        [ExpectedException(typeof(InternalErrorException))]
        [TestMethod]
        public void TestMergeResultsBad2()
        {
            BuildResult result = new BuildResult(1);
            result["foo"] = new TargetResult(new BuildItem[0] { }, BuildResultCode.Success);

            BuildResult result2 = new BuildResult(1);
            result2["foo"] = new TargetResult(new BuildItem[0] { }, BuildResultCode.Success);

            result.MergeResults(result2);
        }
#endif

        [ExpectedException(typeof(InternalErrorException))]
        [TestMethod]
        public void TestMergeResultsBad3()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());

            BuildRequest request2 = CreateNewBuildRequest(2, new string[0]);
            BuildResult result2 = new BuildResult(request2);
            result2.AddResultsForTarget("bar", TestUtilities.GetEmptySucceedingTargetResult());

            result.MergeResults(result2);
        }

        [TestMethod]
        public void TestHasResultsForTarget()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());

            Assert.IsTrue(result.HasResultsForTarget("foo"));
            Assert.IsFalse(result.HasResultsForTarget("bar"));
        }

        [TestMethod]
        public void TestEnumerator()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0]);
            BuildResult result = new BuildResult(request);
            int countFound = 0;
            foreach (KeyValuePair<string, TargetResult> resultPair in result.ResultsByTarget)
            {
                countFound++;
            }
            Assert.AreEqual(countFound, 0);

            result.AddResultsForTarget("foo", TestUtilities.GetEmptySucceedingTargetResult());
            bool foundFoo = false;
            countFound = 0;
            foreach (KeyValuePair<string, TargetResult> resultPair in result.ResultsByTarget)
            {
                if (resultPair.Key == "foo")
                {
                    foundFoo = true;
                }
                countFound++;
            }
            Assert.AreEqual(countFound, 1);
            Assert.IsTrue(foundFoo);

            result.AddResultsForTarget("bar", TestUtilities.GetEmptySucceedingTargetResult());
            foundFoo = false;
            bool foundBar = false;
            countFound = 0;
            foreach (KeyValuePair<string, TargetResult> resultPair in result.ResultsByTarget)
            {
                if (resultPair.Key == "foo")
                {
                    Assert.IsFalse(foundFoo);
                    foundFoo = true;
                }
                if (resultPair.Key == "bar")
                {
                    Assert.IsFalse(foundBar);
                    foundBar = true;
                }
                countFound++;
            }
            Assert.AreEqual(countFound, 2);
            Assert.IsTrue(foundFoo);
            Assert.IsTrue(foundBar);
        }

        [TestMethod]
        public void TestTranslation()
        {
            BuildRequest request = new BuildRequest(1, 1, 2, new string[] { "alpha", "omega" }, null, new BuildEventContext(1, 1, 2, 3, 4, 5), null);
            BuildResult result = new BuildResult(request, new BuildAbortedException());

            TaskItem fooTaskItem = new TaskItem("foo", "asdf.proj");
            fooTaskItem.SetMetadata("meta1", "metavalue1");
            fooTaskItem.SetMetadata("meta2", "metavalue2");

            result.InitialTargets = new List<string> { "a", "b" };
            result.DefaultTargets = new List<string> { "c", "d" };

            result.AddResultsForTarget("alpha", new TargetResult(new TaskItem[] { fooTaskItem }, TestUtilities.GetSuccessResult()));
            result.AddResultsForTarget("omega", new TargetResult(new TaskItem[] { }, TestUtilities.GetStopWithErrorResult(new ArgumentException("The argument was invalid"))));

            Assert.AreEqual(NodePacketType.BuildResult, (result as INodePacket).Type);
            ((INodePacketTranslatable)result).Translate(TranslationHelpers.GetWriteTranslator());
            INodePacket packet = BuildResult.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());

            BuildResult deserializedResult = packet as BuildResult;

            Assert.AreEqual(result.ConfigurationId, deserializedResult.ConfigurationId);
            Assert.IsTrue(TranslationHelpers.CompareCollections(result.DefaultTargets, deserializedResult.DefaultTargets, StringComparer.Ordinal));
            Assert.IsTrue(TranslationHelpers.CompareExceptions(result.Exception, deserializedResult.Exception));
            Assert.AreEqual(result.Exception.Message, deserializedResult.Exception.Message);
            Assert.AreEqual(result.GlobalRequestId, deserializedResult.GlobalRequestId);
            Assert.IsTrue(TranslationHelpers.CompareCollections(result.InitialTargets, deserializedResult.InitialTargets, StringComparer.Ordinal));
            Assert.AreEqual(result.NodeRequestId, deserializedResult.NodeRequestId);
            Assert.AreEqual(result["alpha"].ResultCode, deserializedResult["alpha"].ResultCode);
            Assert.IsTrue(TranslationHelpers.CompareExceptions(result["alpha"].Exception, deserializedResult["alpha"].Exception));
            Assert.IsTrue(TranslationHelpers.CompareCollections(result["alpha"].Items, deserializedResult["alpha"].Items, TaskItemComparer.Instance));
            Assert.AreEqual(result["omega"].ResultCode, deserializedResult["omega"].ResultCode);
            Assert.IsTrue(TranslationHelpers.CompareExceptions(result["omega"].Exception, deserializedResult["omega"].Exception));
            Assert.IsTrue(TranslationHelpers.CompareCollections(result["omega"].Items, deserializedResult["omega"].Items, TaskItemComparer.Instance));
        }

        private BuildRequest CreateNewBuildRequest(int configurationId, string[] targets)
        {
            return new BuildRequest(1 /* submissionId */, _nodeRequestId++, configurationId, targets, null, BuildEventContext.Invalid, null);
        }
    }
}


text:
void AddWarp( Unit *un, QVector beg, float tim );
void WarpTrailDraw();

#endif


text:
#include "btRigidBody.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "LinearMath/btMinMax.h"
#include "LinearMath/btTransformUtil.h"
#include "LinearMath/btMotionState.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include "LinearMath/btSerializer.h"

//'temporarily' global variables
btScalar	gDeactivationTime = btScalar(2.);
bool	gDisableDeactivation = false;
static int uniqueId = 0;

btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
{
	setupRigidBody(constructionInfo);
}

btRigidBody::btRigidBody(btScalar mass, btMotionState *motionState, btCollisionShape *collisionShape, const btVector3 &localInertia)
{
	btRigidBodyConstructionInfo cinfo(mass,motionState,collisionShape,localInertia);
	setupRigidBody(cinfo);
}

void	btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
{

	m_internalType=CO_RIGID_BODY;

	m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
	m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
	m_angularFactor.setValue(1,1,1);
	m_linearFactor.setValue(1,1,1);
	m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
	m_gravity_acceleration.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
	m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
	m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)),
    setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);

	m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold;
	m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold;
	m_optionalMotionState = constructionInfo.m_motionState;
	m_contactSolverType = 0;
	m_frictionSolverType = 0;
	m_additionalDamping = constructionInfo.m_additionalDamping;
	m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor;
	m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr;
	m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr;
	m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor;

	if (m_optionalMotionState)
	{
		m_optionalMotionState->getWorldTransform(m_worldTransform);
	} else
	{
		m_worldTransform = constructionInfo.m_startWorldTransform;
	}

	m_interpolationWorldTransform = m_worldTransform;
	m_interpolationLinearVelocity.setValue(0,0,0);
	m_interpolationAngularVelocity.setValue(0,0,0);

	//moved to btCollisionObject
	m_friction = constructionInfo.m_friction;
	m_rollingFriction = constructionInfo.m_rollingFriction;
	m_restitution = constructionInfo.m_restitution;

	setCollisionShape( constructionInfo.m_collisionShape );
	m_debugBodyId = uniqueId++;

	setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia);
	updateInertiaTensor();

	m_rigidbodyFlags = BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY;

	m_deltaLinearVelocity.setZero();
	m_deltaAngularVelocity.setZero();
	m_invMass = m_inverseMass*m_linearFactor;
	m_pushVelocity.setZero();
	m_turnVelocity.setZero();

}

void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform)
{
	btTransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform);
}

void			btRigidBody::saveKinematicState(btScalar timeStep)
{
	//todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
	if (timeStep != btScalar(0.))
	{
		//if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
		if (getMotionState())
			getMotionState()->getWorldTransform(m_worldTransform);
		btVector3 linVel,angVel;

		btTransformUtil::calculateVelocity(m_interpolationWorldTransform,m_worldTransform,timeStep,m_linearVelocity,m_angularVelocity);
		m_interpolationLinearVelocity = m_linearVelocity;
		m_interpolationAngularVelocity = m_angularVelocity;
		m_interpolationWorldTransform = m_worldTransform;
		//printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ());
	}
}

void	btRigidBody::getAabb(btVector3& aabbMin,btVector3& aabbMax) const
{
	getCollisionShape()->getAabb(m_worldTransform,aabbMin,aabbMax);
}

void btRigidBody::setGravity(const btVector3& acceleration)
{
	if (m_inverseMass != btScalar(0.0))
	{
		m_gravity = acceleration * (btScalar(1.0) / m_inverseMass);
	}
	m_gravity_acceleration = acceleration;
}

void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping)
{
	m_linearDamping = btClamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
	m_angularDamping = btClamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
}

///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping
void			btRigidBody::applyDamping(btScalar timeStep)
{
	//On new damping: see discussion/issue report here: http://code.google.com/p/bullet/issues/detail?id=74
	//todo: do some performance comparisons (but other parts of the engine are probably bottleneck anyway

//#define USE_OLD_DAMPING_METHOD 1
#ifdef USE_OLD_DAMPING_METHOD
	m_linearVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
	m_angularVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
#else
	m_linearVelocity *= btPow(btScalar(1)-m_linearDamping, timeStep);
	m_angularVelocity *= btPow(btScalar(1)-m_angularDamping, timeStep);
#endif

	if (m_additionalDamping)
	{
		//Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
		//Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
		if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) &&
			(m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr))
		{
			m_angularVelocity *= m_additionalDampingFactor;
			m_linearVelocity *= m_additionalDampingFactor;
		}

		btScalar speed = m_linearVelocity.length();
		if (speed < m_linearDamping)
		{
			btScalar dampVel = btScalar(0.005);
			if (speed > dampVel)
			{
				btVector3 dir = m_linearVelocity.normalized();
				m_linearVelocity -=  dir * dampVel;
			} else
			{
				m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
			}
		}

		btScalar angSpeed = m_angularVelocity.length();
		if (angSpeed < m_angularDamping)
		{
			btScalar angDampVel = btScalar(0.005);
			if (angSpeed > angDampVel)
			{
				btVector3 dir = m_angularVelocity.normalized();
				m_angularVelocity -=  dir * angDampVel;
			} else
			{
				m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
			}
		}
	}
}

void btRigidBody::applyGravity()
{
	if (isStaticOrKinematicObject())
		return;

	applyCentralForce(m_gravity);

}

void btRigidBody::proceedToTransform(const btTransform& newTrans)
{
	setCenterOfMassTransform( newTrans );
}

void btRigidBody::setMassProps(btScalar mass, const btVector3& inertia)
{
	if (mass == btScalar(0.))
	{
		m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
		m_inverseMass = btScalar(0.);
	} else
	{
		m_collisionFlags &= (~btCollisionObject::CF_STATIC_OBJECT);
		m_inverseMass = btScalar(1.0) / mass;
	}

	//Fg = m * a
	m_gravity = mass * m_gravity_acceleration;

	m_invInertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x(): btScalar(0.0),
				   inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y(): btScalar(0.0),
				   inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z(): btScalar(0.0));

	m_invMass = m_linearFactor*m_inverseMass;
}

void btRigidBody::updateInertiaTensor()
{
	m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose();
}

btVector3 btRigidBody::getLocalInertia() const
{

	btVector3 inertiaLocal;
	const btVector3 inertia = m_invInertiaLocal;
	inertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x() : btScalar(0.0),
		inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y() : btScalar(0.0),
		inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z() : btScalar(0.0));
	return inertiaLocal;
}

inline btVector3 evalEulerEqn(const btVector3& w1, const btVector3& w0, const btVector3& T, const btScalar dt,
	const btMatrix3x3 &I)
{
	const btVector3 w2 = I*w1 + w1.cross(I*w1)*dt - (T*dt + I*w0);
	return w2;
}

inline btMatrix3x3 evalEulerEqnDeriv(const btVector3& w1, const btVector3& w0, const btScalar dt,
	const btMatrix3x3 &I)
{

	btMatrix3x3 w1x, Iw1x;
	const btVector3 Iwi = (I*w1);
	w1.getSkewSymmetricMatrix(&w1x[0], &w1x[1], &w1x[2]);
	Iwi.getSkewSymmetricMatrix(&Iw1x[0], &Iw1x[1], &Iw1x[2]);

	const btMatrix3x3 dfw1 = I + (w1x*I - Iw1x)*dt;
	return dfw1;
}

btVector3 btRigidBody::computeGyroscopicForceExplicit(btScalar maxGyroscopicForce) const
{
	btVector3 inertiaLocal = getLocalInertia();
	btMatrix3x3 inertiaTensorWorld = getWorldTransform().getBasis().scaled(inertiaLocal) * getWorldTransform().getBasis().transpose();
	btVector3 tmp = inertiaTensorWorld*getAngularVelocity();
	btVector3 gf = getAngularVelocity().cross(tmp);
	btScalar l2 = gf.length2();
	if (l2>maxGyroscopicForce*maxGyroscopicForce)
	{
		gf *= btScalar(1.)/btSqrt(l2)*maxGyroscopicForce;
	}
	return gf;
}

void btSetCrossMatrixMinus(btMatrix3x3& res, const btVector3& a)
{
	const btScalar a_0 = a[0], a_1 = a[1], a_2 = a[2];
	res.setValue(0, +a_2, -a_1,
		-a_2, 0, +a_0,
		+a_1, -a_0, 0);
}

btVector3 btRigidBody::computeGyroscopicImpulseImplicit_Body(btScalar step) const
{
	btVector3 idl = getLocalInertia();
	btVector3 omega1 = getAngularVelocity();
	btQuaternion q = getWorldTransform().getRotation();

	// Convert to body coordinates
	btVector3 omegab = quatRotate(q.inverse(), omega1);
	btMatrix3x3 Ib;
	Ib.setValue(idl.x(),0,0,
				0,idl.y(),0,
				0,0,idl.z());

	btVector3 ibo = Ib*omegab;

	// Residual vector
	btVector3 f = step * omegab.cross(ibo);

	btMatrix3x3 skew0;
	omegab.getSkewSymmetricMatrix(&skew0[0], &skew0[1], &skew0[2]);
	btVector3 om = Ib*omegab;
	btMatrix3x3 skew1;
	om.getSkewSymmetricMatrix(&skew1[0],&skew1[1],&skew1[2]);

	// Jacobian
	btMatrix3x3 J = Ib +  (skew0*Ib - skew1)*step;

//	btMatrix3x3 Jinv = J.inverse();
//	btVector3 omega_div = Jinv*f;
	btVector3 omega_div = J.solve33(f);

	// Single Newton-Raphson update
	omegab = omegab - omega_div;//Solve33(J, f);
	// Back to world coordinates
	btVector3 omega2 = quatRotate(q,omegab);
	btVector3 gf = omega2-omega1;
	return gf;
}

btVector3 btRigidBody::computeGyroscopicImpulseImplicit_World(btScalar step) const
{
	// use full newton-euler equations.  common practice to drop the wxIw term. want it for better tumbling behavior.
	// calculate using implicit euler step so it's stable.

	const btVector3 inertiaLocal = getLocalInertia();
	const btVector3 w0 = getAngularVelocity();

	btMatrix3x3 I;

	I = m_worldTransform.getBasis().scaled(inertiaLocal) *
		m_worldTransform.getBasis().transpose();

	// use newtons method to find implicit solution for new angular velocity (w')
	// f(w') = -(T*step + Iw) + Iw' + w' + w'xIw'*step = 0
	// df/dw' = I + 1xIw'*step + w'xI*step

	btVector3 w1 = w0;

	// one step of newton's method
	{
		const btVector3 fw = evalEulerEqn(w1, w0, btVector3(0, 0, 0), step, I);
		const btMatrix3x3 dfw = evalEulerEqnDeriv(w1, w0, step, I);

		btVector3 dw;
		dw = dfw.solve33(fw);
		//const btMatrix3x3 dfw_inv = dfw.inverse();
		//dw = dfw_inv*fw;

		w1 -= dw;
	}

	btVector3 gf = (w1 - w0);
	return gf;
}

void btRigidBody::integrateVelocities(btScalar step)
{
	if (isStaticOrKinematicObject())
		return;

	m_linearVelocity += m_totalForce * (m_inverseMass * step);
	m_angularVelocity += m_invInertiaTensorWorld * m_totalTorque * step;

#define MAX_ANGVEL SIMD_HALF_PI
	/// clamp angular velocity. collision calculations will fail on higher angular velocities
	btScalar angvel = m_angularVelocity.length();
	if (angvel*step > MAX_ANGVEL)
	{
		m_angularVelocity *= (MAX_ANGVEL/step) /angvel;
	}

}

btQuaternion btRigidBody::getOrientation() const
{
		btQuaternion orn;
		m_worldTransform.getBasis().getRotation(orn);
		return orn;
}

void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
{

	if (isKinematicObject())
	{
		m_interpolationWorldTransform = m_worldTransform;
	} else
	{
		m_interpolationWorldTransform = xform;
	}
	m_interpolationLinearVelocity = getLinearVelocity();
	m_interpolationAngularVelocity = getAngularVelocity();
	m_worldTransform = xform;
	updateInertiaTensor();
}

void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
	///disable collision with the 'other' body

	int index = m_constraintRefs.findLinearSearch(c);
	//don't add constraints that are already referenced
	//btAssert(index == m_constraintRefs.size());
	if (index == m_constraintRefs.size())
	{
		m_constraintRefs.push_back(c);
		btCollisionObject* colObjA = &c->getRigidBodyA();
		btCollisionObject* colObjB = &c->getRigidBodyB();
		if (colObjA == this)
		{
			colObjA->setIgnoreCollisionCheck(colObjB, true);
		}
		else
		{
			colObjB->setIgnoreCollisionCheck(colObjA, true);
		}
	}
}

void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
	int index = m_constraintRefs.findLinearSearch(c);
	//don't remove constraints that are not referenced
	if(index < m_constraintRefs.size())
    {
        m_constraintRefs.remove(c);
        btCollisionObject* colObjA = &c->getRigidBodyA();
        btCollisionObject* colObjB = &c->getRigidBodyB();
        if (colObjA == this)
        {
            colObjA->setIgnoreCollisionCheck(colObjB, false);
        }
        else
        {
            colObjB->setIgnoreCollisionCheck(colObjA, false);
        }
    }
}

int	btRigidBody::calculateSerializeBufferSize()	const
{
	int sz = sizeof(btRigidBodyData);
	return sz;
}

	///fills the dataBuffer and returns the struct name (and 0 on failure)
const char*	btRigidBody::serialize(void* dataBuffer, class btSerializer* serializer) const
{
	btRigidBodyData* rbd = (btRigidBodyData*) dataBuffer;

	btCollisionObject::serialize(&rbd->m_collisionObjectData, serializer);

	m_invInertiaTensorWorld.serialize(rbd->m_invInertiaTensorWorld);
	m_linearVelocity.serialize(rbd->m_linearVelocity);
	m_angularVelocity.serialize(rbd->m_angularVelocity);
	rbd->m_inverseMass = m_inverseMass;
	m_angularFactor.serialize(rbd->m_angularFactor);
	m_linearFactor.serialize(rbd->m_linearFactor);
	m_gravity.serialize(rbd->m_gravity);
	m_gravity_acceleration.serialize(rbd->m_gravity_acceleration);
	m_invInertiaLocal.serialize(rbd->m_invInertiaLocal);
	m_totalForce.serialize(rbd->m_totalForce);
	m_totalTorque.serialize(rbd->m_totalTorque);
	rbd->m_linearDamping = m_linearDamping;
	rbd->m_angularDamping = m_angularDamping;
	rbd->m_additionalDamping = m_additionalDamping;
	rbd->m_additionalDampingFactor = m_additionalDampingFactor;
	rbd->m_additionalLinearDampingThresholdSqr = m_additionalLinearDampingThresholdSqr;
	rbd->m_additionalAngularDampingThresholdSqr = m_additionalAngularDampingThresholdSqr;
	rbd->m_additionalAngularDampingFactor = m_additionalAngularDampingFactor;
	rbd->m_linearSleepingThreshold=m_linearSleepingThreshold;
	rbd->m_angularSleepingThreshold = m_angularSleepingThreshold;

	return btRigidBodyDataName;
}

void btRigidBody::serializeSingleObject(class btSerializer* serializer) const
{
	btChunk* chunk = serializer->allocate(calculateSerializeBufferSize(),1);
	const char* structType = serialize(chunk->m_oldPtr, serializer);
	serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,(void*)this);
}