text:
// Original - Christopher Lloyd <cjwl@objc.net>
#import <AppKit/NSSubmenuView.h>
#import <AppKit/NSMenuWindow.h>
#import <AppKit/NSGraphicsStyle.h>

@implementation NSSubmenuView

#define MIN_TITLE_KEY_GAP 8
#define WINDOW_BORDER_THICKNESS 3
#define IMAGE_TITLE_GAP 8

-(NSSize)sizeForMenuItemImage:(NSMenuItem *)item {
	NSSize result=NSZeroSize;

	if([item image]!=nil)
		result=[[item image] size];

	return result;
}

-(NSSize)contentSizeForItem:(NSMenuItem *)item {
	if ([item isSeparatorItem])	{
		return [[self graphicsStyle] menuItemSeparatorSize];
	}
	else {
#define ITEM_MAX(size) height = MAX(height,size.height); width += size.width;
		float width = [[self graphicsStyle] menuItemGutterGap];
		float height = 0.0f;
		NSSize size;

		size = [[self graphicsStyle] menuItemGutterSize];
		ITEM_MAX(size);
		size = [self sizeForMenuItemImage:item];
		if (size.width > 0.0f)
		{
			ITEM_MAX(size);
			width += IMAGE_TITLE_GAP;
		}
		size = [[self graphicsStyle] menuItemTextSize:[item title]];
		ITEM_MAX(size);
		if ([[item keyEquivalent] length] == 0)
		{
			size = [[self graphicsStyle] menuItemTextSize:[item _keyEquivalentDescription]];
			ITEM_MAX(size);
		}
		if ([item hasSubmenu])
		{
			size = [[self graphicsStyle] menuItemBranchArrowSize];
			ITEM_MAX(size);
		}

		return NSMakeSize(width,height);
	}
}

-(NSSize)sizeForMenuItems:(NSArray *)items {
	NSSize   result=NSZeroSize;
	float    maxTitleWidth = 0.0f;
	BOOL     anItemHasAnImage = NO;
	float    maxKeyWidth = 0.0f;
	float    totalHeight = 0.0f;
	NSSize   gutterSize = [[self graphicsStyle] menuItemGutterSize];
	NSSize   rightArrowSize = [[self graphicsStyle] menuItemBranchArrowSize];
	unsigned i,count=[items count];

	for (i = 0;i<count;i++)
	{
		NSMenuItem *item = [items objectAtIndex:i];
		if ([item isSeparatorItem])
		{
			totalHeight += [[self graphicsStyle] menuItemSeparatorSize].height;
		}
		else
		{
			NSSize     size = NSZeroSize;
			float      height = 0.0f;
			float      titleAndIconWidth = 0.0f;

			size = [self sizeForMenuItemImage:item];
			height = MAX(height,size.height);
			if ((titleAndIconWidth = size.width) > 0.0f)
				anItemHasAnImage = YES;

			size = [[self graphicsStyle] menuItemTextSize:[item title]];
			titleAndIconWidth += size.width;
			maxTitleWidth = MAX(maxTitleWidth,titleAndIconWidth);
			height = MAX(height,size.height);

			if ([[item keyEquivalent] length] != 0)
			{
				size = [[self graphicsStyle] menuItemTextSize:[item _keyEquivalentDescription]];
				maxKeyWidth=MAX(maxKeyWidth,size.width);
				height = MAX(height,size.height);
			}
			height = MAX(height,gutterSize.height);
			height = MAX(height,rightArrowSize.height);

			totalHeight += height;
        }
	}

	result.height = totalHeight;
	result.width = gutterSize.width;
	result.width += [[self graphicsStyle] menuItemGutterGap];
	if (anItemHasAnImage)
		result.width += IMAGE_TITLE_GAP;
	result.width += maxTitleWidth;
	if (maxKeyWidth > 0.0f)
	{
		result.width += MIN_TITLE_KEY_GAP;
		result.width += maxKeyWidth;
	}
	result.width += rightArrowSize.width;

	// border. Magic constants that may not be right for Win7 vs XP
	result.width += WINDOW_BORDER_THICKNESS*2;
	result.height += WINDOW_BORDER_THICKNESS*2;

	return result;
}

-initWithMenu:(NSMenu *)menu {
   NSRect frame=NSZeroRect;

   [self initWithFrame:frame];

   _menu=[menu retain];
   _selectedItemIndex=NSNotFound;

   frame.size=[self sizeForMenuItems:[self visibleItemArray]];
   [self setFrame:frame];

   return self;
}

-(BOOL)isFlipped {
   return YES;
}

static NSRect boundsToTitleAreaRect(NSRect rect){
   return NSInsetRect(rect, WINDOW_BORDER_THICKNESS, WINDOW_BORDER_THICKNESS);
}

-(float)heightOfMenuItem:(NSMenuItem *)item {
	NSSize titleSize=[self contentSizeForItem:item];

	return titleSize.height;
}

-(void)drawRect:(NSRect)rect
{
	NSRect   bounds = [self bounds];
	NSRect   itemArea=boundsToTitleAreaRect(bounds);
	NSArray *items=[self visibleItemArray];
	unsigned i,count=[items count];
	NSPoint  origin=itemArea.origin;

	[[self graphicsStyle] drawMenuWindowBackgroundInRect:rect];

	for(i=0;i<count;i++)
	{
		NSMenuItem *item=[items objectAtIndex:i];

		if ([item isSeparatorItem])
		{
			NSRect separatorRect = NSMakeRect(origin.x,origin.y,NSWidth(itemArea),[[self graphicsStyle] menuItemSeparatorSize].height);

			[[self graphicsStyle] drawMenuSeparatorInRect:separatorRect];

			origin.y += NSHeight(separatorRect);
		}
		else
		{
#define CENTER_PART_RECT_VERTICALLY(partSize)                          \
{                                                                      \
	NSSize __partSize = (partSize);                                    \
	partRect.origin.y = origin.y + (itemHeight - __partSize.height) / 2; \
	partRect.size.height = __partSize.height;                            \
	partRect.size.width = __partSize.width;                              \
}
			NSImage      *image = [item image];
			BOOL         selected = (i ==_selectedItemIndex) ? YES : NO;
			float        itemHeight = [self heightOfMenuItem:item];
			NSRect       partRect;
			NSSize       partSize;
			BOOL         showsEnabled = ([item isEnabled] || [item hasSubmenu]);

			partRect = NSMakeRect(origin.x,origin.y,itemArea.size.width,itemHeight);

			if (selected)
				[[self graphicsStyle] drawMenuSelectionInRect:partRect enabled:showsEnabled];

			// Draw the gutter and checkmark (if any)
			CENTER_PART_RECT_VERTICALLY([[self graphicsStyle] menuItemGutterSize]);
			if ([item state])
			{
				[[self graphicsStyle] drawMenuGutterInRect:partRect];
				[[self graphicsStyle] drawMenuCheckmarkInRect:partRect enabled:showsEnabled selected:selected];
			}

			partRect.origin.x += [[self graphicsStyle] menuItemGutterGap];;

			// Draw the image
			if (image)
			{
				NSRect imageRect;

				partRect.origin.x += partRect.size.width;
				CENTER_PART_RECT_VERTICALLY([image size]);

                CGContextRef ctx=[[NSGraphicsContext currentContext] graphicsPort];
                CGContextSaveGState(ctx);
                CGContextTranslateCTM(ctx,partRect.origin.x,partRect.origin.y);
                if([self isFlipped]){
                    CGContextTranslateCTM(ctx,0,partRect.size.height);
                    CGContextScaleCTM(ctx,1,-1);
                }
                NSRect drawingRect = partRect;
                drawingRect.origin = NSZeroPoint;
                [[self graphicsStyle] drawButtonImage:image inRect:drawingRect enabled:showsEnabled mixed:NO];
                CGContextRestoreGState(ctx);

				partRect.origin.x += IMAGE_TITLE_GAP;
			}

			// Draw the title
			partRect.origin.x += partRect.size.width;

			NSAttributedString     *atitle = [item attributedTitle];
			if (atitle != nil && [atitle length] > 0) {
				CENTER_PART_RECT_VERTICALLY([atitle size]);
				[[self graphicsStyle] drawAttributedMenuItemText:atitle inRect:partRect enabled:showsEnabled selected:selected];
			} else {
				NSString     *title = [item title];
				CENTER_PART_RECT_VERTICALLY([[self graphicsStyle] menuItemTextSize:title]);
				[[self graphicsStyle] drawMenuItemText:title inRect:partRect enabled:showsEnabled selected:selected];
			}

			// Draw the key equivalent
			if ([[item keyEquivalent] length] != 0)
			{
				NSString *keyString = [item _keyEquivalentDescription];
				NSSize   branchArrowSize = [[self graphicsStyle] menuItemBranchArrowSize];
				NSSize   keyEquivalentSize = [[self graphicsStyle] menuItemTextSize:keyString];

				partRect.origin.x = origin.x + NSWidth(itemArea) - branchArrowSize.width - keyEquivalentSize.width;
				CENTER_PART_RECT_VERTICALLY(keyEquivalentSize);
				[[self graphicsStyle] drawMenuItemText:keyString inRect:partRect enabled:showsEnabled selected:selected];
			}

			// Draw the submenu arrow
			if([item hasSubmenu])
			{
				NSSize branchArrowSize = [[self graphicsStyle] menuItemBranchArrowSize];
				partRect.origin.x = origin.x + NSWidth(itemArea) - branchArrowSize.width;
				partRect.size.width = branchArrowSize.width;
				CENTER_PART_RECT_VERTICALLY(branchArrowSize);
				[[self graphicsStyle] drawMenuBranchArrowInRect:partRect enabled:showsEnabled selected:selected];
			}

			origin.y += itemHeight;
		}
	}
}

-(unsigned)itemIndexAtPoint:(NSPoint)point {
   NSArray *items=[[self menu] itemArray];
   unsigned i,count=[items count];
   NSRect   check=boundsToTitleAreaRect([self bounds]);

   for(i=0;i<count;i++){
    NSMenuItem *item=[items objectAtIndex:i];

    check.size.height=[self heightOfMenuItem:item];

    if(NSMouseInRect(point,check,[self isFlipped]))
     return i;

    check.origin.y+=check.size.height;
   }

   return NSNotFound;
}

-(void)positionBranchForSelectedItem:(NSWindow *)branch screen:(NSScreen *)screen {
   NSRect   branchFrame=[branch frame];
   NSRect   screenVisible=[screen visibleFrame];
   NSArray *items=[[self menu] itemArray];
   unsigned i,count=[items count];
   NSRect   itemRect=boundsToTitleAreaRect([self bounds]);
   NSPoint  topLeft=NSZeroPoint;

   for(i=0;i<count;i++){
    NSMenuItem *item=[items objectAtIndex:i];

    itemRect.size.height=[self heightOfMenuItem:item];

    if(i==_selectedItemIndex){
     topLeft=itemRect.origin;

     topLeft.x+=itemRect.size.width;
     topLeft.y-=WINDOW_BORDER_THICKNESS;

     break;
    }

    itemRect.origin.y+=itemRect.size.height;
   }

   topLeft=[self convertPoint:topLeft toView:nil];
   topLeft=[[self window] convertBaseToScreen:topLeft];

   if(topLeft.y-branchFrame.size.height<NSMinY(screenVisible)){
    topLeft=itemRect.origin;

    topLeft.x+=itemRect.size.width;
    topLeft.y+=itemRect.size.height;
    topLeft.y+=WINDOW_BORDER_THICKNESS;

    topLeft=[self convertPoint:topLeft toView:nil];
    topLeft=[[self window] convertBaseToScreen:topLeft];

    topLeft.y+=branchFrame.size.height;
   }

   if(topLeft.x+branchFrame.size.width>NSMaxX(screenVisible)){
    NSPoint redo=itemRect.origin;

    redo=[self convertPoint:redo toView:nil];
    redo=[[self window] convertBaseToScreen:redo];
    redo.x-=branchFrame.size.width;

    topLeft.x=redo.x;
   }

   [branch setFrameTopLeftPoint:topLeft];
}

-(NSMenuView *)viewAtSelectedIndexPositionOnScreen:(NSScreen *)screen {
   NSArray *items=[self visibleItemArray];

   if(_selectedItemIndex<[items count]){
    NSMenuItem *item=[items objectAtIndex:_selectedItemIndex];

    if([item hasSubmenu]){
     NSMenuWindow *branch=[[NSMenuWindow alloc] initWithMenu:[item submenu]];

     [self positionBranchForSelectedItem:branch screen:screen];

     [branch orderFront:nil];
     return [branch menuView];
    }
   }
   return nil;
}

@end

/*@implementation MenuMetrics

-(id)initWithStyle:(NSGraphicsStyle *)style
{
	checkBoxMargins = [style menuItemCheckBoxMargins];
	checkBoxBackgroundMargins = [style menuItemCheckBoxBackgroundMargins];
	itemMargins = [style menuItemMargins];
    keyEquivalentMargins = [style menuItemKeyEquivalentMargins];

	checkMarkSize = [style menuItemCheckMarkSize];
	separatorSize = [style menuItemSeparatorSize];

	minTitleKeyEquivalentWidth = [style minimumTitleKeyEquivalentWidth];
	extraTitleGutterMargin = [style extraTitleGutterMargin];

	titleMargins = itemMargins;
	titleMargins.left = [style menuBorderBackgroundSize].width;
	titleMargins.right = [style menuBorderSize].width;

	extraCheckMarkHeight = checkBoxBackgroundMargins.top + checkBoxBackgroundMargins.bottom;
}

-(Margins)checkMarkMargins
{
	return checkMarkMargins;
}

-(Margins)checkMarkBackgroundMargins
{
	return checkMarkBackgroundMargins;
}

-(Margins)itemMargins
{
	return itemMargins;
}

-(Margins)titleMargins
{
	return titleMargins;
}

-(Margins)keyEquivalentMargins
{
	return keyEquivalentMargins;
}

-(NSSize)checkMarkSize
{
	return checkMarkSize;
}

-(NSSize)separatorSize
{
	return separatorSize;
}

-(float)minTitleKeyEquivalentWidth
{
	return minTitleKeyEquivalentWidth;
}

-(float)extraTitleGutterMargin
{
	return extraTitleGutterMargin;
}

-(float)extraCheckMarkHeight
{
	return extraCheckMarkHeight;
}

@end
*/


text:
import roslib; roslib.load_manifest('articulation_structure')
import rospy
import sys
from visualization_msgs.msg import Marker, MarkerArray
from geometry_msgs.msg import Vector3, Point, Pose, PoseArray
from std_msgs.msg import ColorRGBA
from sensor_msgs.msg import ChannelFloat32,CameraInfo,CompressedImage
from articulation_msgs.msg import *
from articulation_msgs.srv import *
from articulation_models.track_utils import *
import logging
import getopt
import colorsys
import numpy
import copy
import rosbag

def all_detected(pose_array):
  for p in pose_array.poses:
    r = [p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w]
    if( numpy.dot(r,r) == 0 ):
      return False
  return True

def main():
  rospy.init_node('articulation_eval')

  info_pub = rospy.Publisher('/camera/camera_info',CameraInfo)
  image_pub = rospy.Publisher('/camera/image_raw/compressed',CompressedImage)
  posearray_pub = rospy.Publisher('/camera/pose_array',PoseArray)
  model_pub = rospy.Publisher('/model', ModelMsg)
  track_pub = rospy.Publisher('/track', TrackMsg)

  fit_models = rospy.ServiceProxy('fit_models', ArticulatedObjectSrv)
  get_spanning_tree = rospy.ServiceProxy('get_spanning_tree', ArticulatedObjectSrv)
  get_fast_graph = rospy.ServiceProxy('get_fast_graph', ArticulatedObjectSrv)
  get_graph = rospy.ServiceProxy('get_graph', ArticulatedObjectSrv)
  get_graph_all = rospy.ServiceProxy('get_graph_all', ArticulatedObjectSrv)
  visualize_graph = rospy.ServiceProxy('visualize_graph', ArticulatedObjectSrv)

  downsample = rospy.get_param("~downsample",100)
  first_n = rospy.get_param("~first_n",0)
  start_n = rospy.get_param("~start_n",0)
  sigma_position = rospy.get_param("~sigma_position",0.005)
  sigma_orientation = rospy.get_param("~sigma_orientation",0.4)
  sigmax_position = rospy.get_param("~sigmax_position",0.005)
  sigmax_orientation = rospy.get_param("~sigmax_orientation",0.4)
  reduce_dofs = rospy.get_param("~reduce_dofs",1)
  mode = rospy.get_param("~mode","spanningtree")
  #sigma_position = 0.007
  #sigma_orientation = 0.02

  #inbag_filename = '/home/sturm/sturm-data/sturm10tro/closedchain-pose.bag'
  #inbag_filename = '/home/sturm/sturm-data/sturm10tro/openchain-pose.bag'
  #inbag_filename = '/home/sturm/sturm-data/sturm10tro/lampe-pose.bag'
  inbag_filename = rospy.get_param('~bagfile','/home/sturm/sturm-data/sturm10tro/cabinet-pose.bag')

  # read whole bag file, group by timestamp in header
  bag = {}
  for topic, msg, t in rosbag.Bag(inbag_filename).read_messages():
    timestamp = t
    if not timestamp in bag:
      bag[timestamp] = {}
    bag[timestamp][topic] = msg
  print "read bagfile %s with %d different header timestamps"%( inbag_filename, len(bag) )
  topics = max([len(msgs.keys()) for (timestamp,msgs) in bag.iteritems()])
  for (timestamp) in bag.keys():
    if len( bag[timestamp] ) != topics or not all_detected(bag[timestamp]['/camera/pose_array']):
      del bag[timestamp]
#    else:
#      bag[timestamp]['/camera/pose_array'].poses = [
#              bag[timestamp]['/camera/pose_array'].poses[0],
#              bag[timestamp]['/camera/pose_array'].poses[1]
#              ]
  timestamps = bag.keys()
  timestamps.sort()
  if(first_n>0):
    timestamps = timestamps[0:first_n]

  # downsample sequence
  sequence = [ bag[timestamp]['/camera/pose_array'] for timestamp in timestamps ]
  parts = len( sequence[0].poses )
  print "read %d observations of %d object parts"%(len(bag),parts)
  downsampled = [ i for i in range(len(timestamps)) if (i % (max(1,(len(sequence)-start_n) / downsample)) == 0 ) and i>=start_n]
  downsampled = downsampled[len(downsampled) - downsample:]
  sequence_downsampled = [ sequence[i] for i in downsampled ]
  print "downsampled to %d pose observations"%len(sequence_downsampled)

  # debugging:
  #parts = 3

  # build service request message
  request = ArticulatedObjectSrvRequest()
  request.object.header = sequence_downsampled[-1].header
  request.object.parts = [
    TrackMsg(
             id=i,

             header=request.object.header,
             pose=[p.poses[i] for p in sequence_downsampled]
    )
    for i in range(parts)
  ]
  set_param(request.object, "sigma_position", sigma_position, ParamMsg.PRIOR)
  set_param(request.object, "sigma_orientation", sigma_orientation, ParamMsg.PRIOR)
  set_param(request.object, "sigmax_position", sigmax_position, ParamMsg.PRIOR)
  set_param(request.object, "sigmax_orientation", sigmax_orientation, ParamMsg.PRIOR)
  set_param(request.object, "reduce_dofs", reduce_dofs, ParamMsg.PRIOR)

#  b=rosbag.Bag("eval.bag","w")
#  b.write("/object",request.object,rospy.Time(0))
#  b.close()

  print "fitting models"
  response = fit_models(request)
  print '\n'.join(
     ['(%s:%d,%d) bic=%f pos_err=%f rot_err=%f gamma=%f'%(
          model.name[0:2],
          model.id/parts,
          model.id%parts,
          get_param(model,'bic'),
          get_param(model,'avg_error_position'),
          get_param(model,'avg_error_orientation'),
          get_param(model,'outlier_ratio')
      ) for model in response.object.models])

  if mode=="fastgraph":
    print "running fastgraph"
    response = get_fast_graph(request)
  elif mode=="graph":
    print "running graph"
    response = get_graph(request)
  elif mode=="spanningtree":
    print "running spanningtree"
    response = get_spanning_tree(request)
  elif mode=="all":
    print "running all structure selection methods"
    response = get_graph_all(request)

  request.object = copy.deepcopy(response.object)
  response = visualize_graph(request)

  rospy.loginfo('received articulation model: '+(' '.join(
     ['(%s:%d,%d)'%(model.name[0:2],model.id/parts,model.id%parts) for model in response.object.models])))

  print '\n'.join(
     ['(%s:%d,%d) bic=%f pos_err=%f rot_err=%f'%(
          model.name[0:2],
          model.id/parts,
          model.id%parts,
          get_param(model,'bic'),
          get_param(model,'avg_error_position'),
          get_param(model,'avg_error_orientation')
      ) for model in response.object.models])
  print "dofs=%d, nominal dofs=%d, bic=%f pos_err=%f rot_err=%f"%(
          get_param(response.object,'dof'),
          get_param(response.object,'dof.nominal'),
          get_param(response.object,'bic'),
          get_param(response.object,'avg_error_position'),
          get_param(response.object,'avg_error_orientation')
          )

  #outbag = rosbag.Bag("debug-%s.bag"%mode,"w")
  #outbag.write("/object",response.object,rospy.Time(0))
  #outbag.close()

  print response.object.params
  #print response.object.models

  # send image and info for last pose
  last_timestamp = timestamps[ downsampled[-1] ]
  info_pub.publish( bag[last_timestamp]['/camera/camera_info'] )
  image_pub.publish( bag[last_timestamp]['/camera/image_raw/compressed'] )
  posearray_pub.publish( bag[last_timestamp]['/camera/pose_array'] )

#  model_pub.publish(response.object.models[1])
#  track_pub.publish(request.object.parts[0])
#  track_pub.publish(request.object.parts[1])
#  rospy.sleep(5)
  #model_pub.publish(response.object.models[0])
  rospy.sleep(5)

if __name__ == '__main__':
  main()

redpajama_set_name: RedPajamaGithub


text:
/**
 *  Include guard
 */
#pragma once

#include "../include/ValueImpl.h"

/**
 *  Set up namespace
 */
namespace Variant {

/**
 *  Numeric value implementation
 */
class ValueInt64 : public ValueImpl
{
private:
    /**
     *  Value of this value
     */
    int64_t _value;
public:
    /**
     *  Get the implementation type
     */
    virtual ValueType type() const override
    {
        return ValueInt64Type;
    }

    /**
     *  Clone the implementation
     */
    virtual ValueImpl* clone() const override
    {
        return new ValueInt64(_value);
    }

    /**
     *  Construct new long value
     *
     *  @param  value
     */
    ValueInt64(int32_t value) : ValueInt64((int64_t) value) {}
    ValueInt64(int64_t value) : _value(value) {}

    /**
     *  Convert the value to a boolean
     */
    virtual operator bool () const override
    {
        return _value;
    }

    /**
     *  Convert the value to a number
     */
    virtual operator int32_t () const override
    {
        return _value;
    }

    /**
     *  Convert the value to a number
     */
    virtual operator int64_t () const override
    {
        return _value;
    }

    /**
     *  Convert the value to a number
     */
    virtual operator double() const override
    {
        return _value;
    }

    /**
     *  Convert the value to a string
     */
    virtual operator std::string () const override
    {
        return std::to_string(_value);
    }

    /**
     *  Turn the value into a json compatible type
     */
    virtual struct json_object *toJson() const override
    {
        return json_object_new_int64(_value);
    }

    /**
     *  Comparison operator
     */
    virtual bool operator==(const ValueImpl &that) const override
    {
        // Start off with checking if we are the same type
        if (that.type() != ValueInt64Type) return false;

        // Cast that to a int64_t
        int64_t i = that;

        // Compare the two longs
        return _value == i;
    }
};

/**
 *  End namespace
 */
}


text:
#include "config.h"
#include "DFGJITCompiler.h"

#if ENABLE(DFG_JIT)

#include "CodeBlock.h"
#include "DFGJITCodeGenerator.h"
#include "DFGNonSpeculativeJIT.h"
#include "DFGOperations.h"
#include "DFGRegisterBank.h"
#include "DFGSpeculativeJIT.h"
#include "JSGlobalData.h"
#include "LinkBuffer.h"

namespace JSC { namespace DFG {

// This method used to fill a numeric value to a FPR when linking speculative -> non-speculative.
void JITCompiler::fillNumericToDouble(NodeIndex nodeIndex, FPRReg fpr, GPRReg temporary)
{
    Node& node = graph()[nodeIndex];
    MacroAssembler::RegisterID tempReg = gprToRegisterID(temporary);

    if (node.isConstant()) {
        ASSERT(node.op == DoubleConstant);
        move(MacroAssembler::ImmPtr(reinterpret_cast<void*>(reinterpretDoubleToIntptr(valueOfDoubleConstant(nodeIndex)))), tempReg);
        movePtrToDouble(tempReg, fprToRegisterID(fpr));
    } else {
        loadPtr(addressFor(node.virtualRegister), tempReg);
        Jump isInteger = branchPtr(MacroAssembler::AboveOrEqual, tempReg, tagTypeNumberRegister);
        jitAssertIsJSDouble(gpr0);
        addPtr(tagTypeNumberRegister, tempReg);
        movePtrToDouble(tempReg, fprToRegisterID(fpr));
        Jump hasUnboxedDouble = jump();
        isInteger.link(this);
        convertInt32ToDouble(tempReg, fprToRegisterID(fpr));
        hasUnboxedDouble.link(this);
    }
}

// This method used to fill an integer value to a GPR when linking speculative -> non-speculative.
void JITCompiler::fillInt32ToInteger(NodeIndex nodeIndex, GPRReg gpr)
{
    Node& node = graph()[nodeIndex];

    if (node.isConstant()) {
        ASSERT(node.op == Int32Constant);
        move(MacroAssembler::Imm32(valueOfInt32Constant(nodeIndex)), gprToRegisterID(gpr));
    } else {
#if DFG_JIT_ASSERT
        // Redundant load, just so we can check the tag!
        loadPtr(addressFor(node.virtualRegister), gprToRegisterID(gpr));
        jitAssertIsJSInt32(gpr);
#endif
        load32(addressFor(node.virtualRegister), gprToRegisterID(gpr));
    }
}

// This method used to fill a JSValue to a GPR when linking speculative -> non-speculative.
void JITCompiler::fillToJS(NodeIndex nodeIndex, GPRReg gpr)
{
    Node& node = graph()[nodeIndex];

    if (node.isConstant()) {
        if (isInt32Constant(nodeIndex)) {
            JSValue jsValue = jsNumber(valueOfInt32Constant(nodeIndex));
            move(MacroAssembler::ImmPtr(JSValue::encode(jsValue)), gprToRegisterID(gpr));
        } else if (isDoubleConstant(nodeIndex)) {
            JSValue jsValue(JSValue::EncodeAsDouble, valueOfDoubleConstant(nodeIndex));
            move(MacroAssembler::ImmPtr(JSValue::encode(jsValue)), gprToRegisterID(gpr));
        } else {
            ASSERT(isJSConstant(nodeIndex));
            JSValue jsValue = valueOfJSConstant(nodeIndex);
            move(MacroAssembler::ImmPtr(JSValue::encode(jsValue)), gprToRegisterID(gpr));
        }
        return;
    }

    loadPtr(addressFor(node.virtualRegister), gprToRegisterID(gpr));
}

void JITCompiler::jumpFromSpeculativeToNonSpeculative(const SpeculationCheck& check, const EntryLocation& entry, SpeculationRecovery* recovery)
{
    ASSERT(check.m_nodeIndex == entry.m_nodeIndex);

    // Link the jump from the Speculative path to here.
    check.m_check.link(this);

    // Does this speculation check require any additional recovery to be performed,
    // to restore any state that has been overwritten before we enter back in to the
    // non-speculative path.
    if (recovery) {
        // The only additional recovery we currently support is for integer add operation
        ASSERT(recovery->type() == SpeculativeAdd);
        // Revert the add.
        sub32(gprToRegisterID(recovery->src()), gprToRegisterID(recovery->dest()));
    }

    // FIXME: - This is hideously inefficient!
    // Where a value is live in a register in the speculative path, and is required in a register
    // on the non-speculative path, we should not need to be spilling it and reloading (we may
    // need to spill anyway, if the value is marked as spilled on the non-speculative path).
    // This may also be spilling values that don't need spilling, e.g. are already spilled,
    // are constants, or are arguments.

    // Spill all GPRs in use by the speculative path.
    for (GPRReg gpr = gpr0; gpr < numberOfGPRs; next(gpr)) {
        NodeIndex nodeIndex = check.m_gprInfo[gpr].nodeIndex;
        if (nodeIndex == NoNode)
            continue;

        DataFormat dataFormat = check.m_gprInfo[gpr].format;
        VirtualRegister virtualRegister = graph()[nodeIndex].virtualRegister;

        ASSERT(dataFormat == DataFormatInteger || DataFormatCell || dataFormat & DataFormatJS);
        if (dataFormat == DataFormatInteger)
            orPtr(tagTypeNumberRegister, gprToRegisterID(gpr));
        storePtr(gprToRegisterID(gpr), addressFor(virtualRegister));
    }

    // Spill all FPRs in use by the speculative path.
    for (FPRReg fpr = fpr0; fpr < numberOfFPRs; next(fpr)) {
        NodeIndex nodeIndex = check.m_fprInfo[fpr];
        if (nodeIndex == NoNode)
            continue;

        VirtualRegister virtualRegister = graph()[nodeIndex].virtualRegister;

        moveDoubleToPtr(fprToRegisterID(fpr), regT0);
        subPtr(tagTypeNumberRegister, regT0);
        storePtr(regT0, addressFor(virtualRegister));
    }

    // Fill all FPRs in use by the non-speculative path.
    for (FPRReg fpr = fpr0; fpr < numberOfFPRs; next(fpr)) {
        NodeIndex nodeIndex = entry.m_fprInfo[fpr];
        if (nodeIndex == NoNode)
            continue;

        fillNumericToDouble(nodeIndex, fpr, gpr0);
    }

    // Fill all GPRs in use by the non-speculative path.
    for (GPRReg gpr = gpr0; gpr < numberOfGPRs; next(gpr)) {
        NodeIndex nodeIndex = entry.m_gprInfo[gpr].nodeIndex;
        if (nodeIndex == NoNode)
            continue;

        DataFormat dataFormat = entry.m_gprInfo[gpr].format;
        if (dataFormat == DataFormatInteger)
            fillInt32ToInteger(nodeIndex, gpr);
        else {
            ASSERT(dataFormat & DataFormatJS || dataFormat == DataFormatCell); // Treat cell as JSValue for now!
            fillToJS(nodeIndex, gpr);
            // FIXME: For subtypes of DataFormatJS, should jitAssert the subtype?
        }
    }

    // Jump into the non-speculative path.
    jump(entry.m_entry);
}

void JITCompiler::linkSpeculationChecks(SpeculativeJIT& speculative, NonSpeculativeJIT& nonSpeculative)
{
    // Iterators to walk over the set of bail outs & corresponding entry points.
    SpeculationCheckVector::Iterator checksIter = speculative.speculationChecks().begin();
    SpeculationCheckVector::Iterator checksEnd = speculative.speculationChecks().end();
    NonSpeculativeJIT::EntryLocationVector::Iterator entriesIter = nonSpeculative.entryLocations().begin();
    NonSpeculativeJIT::EntryLocationVector::Iterator entriesEnd = nonSpeculative.entryLocations().end();

    // Iterate over the speculation checks.
    while (checksIter != checksEnd) {
        // For every bail out from the speculative path, we must have provided an entry point
        // into the non-speculative one.
        ASSERT(checksIter->m_nodeIndex == entriesIter->m_nodeIndex);

        // There may be multiple bail outs that map to the same entry point!
        do {
            ASSERT(checksIter != checksEnd);
            ASSERT(entriesIter != entriesEnd);

            // Plant code to link this speculation failure.
            const SpeculationCheck& check = *checksIter;
            const EntryLocation& entry = *entriesIter;
            jumpFromSpeculativeToNonSpeculative(check, entry, speculative.speculationRecovery(check.m_recoveryIndex));
             ++checksIter;
        } while (checksIter != checksEnd && checksIter->m_nodeIndex == entriesIter->m_nodeIndex);
         ++entriesIter;
    }

    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=56289
    ASSERT(!(checksIter != checksEnd));
    ASSERT(!(entriesIter != entriesEnd));
}

void JITCompiler::compileFunction(JITCode& entry, MacroAssemblerCodePtr& entryWithArityCheck)
{
    // === Stage 1 - Function header code generation ===
    //
    // This code currently matches the old JIT. In the function header we need to
    // pop the return address (since we do not allow any recursion on the machine
    // stack), and perform a fast register file check.

    // This is the main entry point, without performing an arity check.
    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=56292
    // We'll need to convert the remaining cti_ style calls (specifically the register file
    // check) which will be dependent on stack layout. (We'd need to account for this in
    // both normal return code and when jumping to an exception handler).
    preserveReturnAddressAfterCall(regT2);
    emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
    // If we needed to perform an arity check we will already have moved the return address,
    // so enter after this.
    Label fromArityCheck(this);

    // Setup a pointer to the codeblock in the CallFrameHeader.
    emitPutImmediateToCallFrameHeader(m_codeBlock, RegisterFile::CodeBlock);

    // Plant a check that sufficient space is available in the RegisterFile.
    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=56291
    addPtr(Imm32(m_codeBlock->m_numCalleeRegisters * sizeof(Register)), callFrameRegister, regT1);
    Jump registerFileCheck = branchPtr(Below, AbsoluteAddress(m_globalData->interpreter->registerFile().addressOfEnd()), regT1);
    // Return here after register file check.
    Label fromRegisterFileCheck = label();

    // === Stage 2 - Function body code generation ===
    //
    // We generate the speculative code path, followed by the non-speculative
    // code for the function. Next we need to link the two together, making
    // bail-outs from the speculative path jump to the corresponding point on
    // the non-speculative one (and generating any code necessary to juggle
    // register values around, rebox values, and ensure spilled, to match the
    // non-speculative path's requirements).

#if DFG_JIT_BREAK_ON_EVERY_FUNCTION
    // Handy debug tool!
    breakpoint();
#endif

    // First generate the speculative path.
    Label speculativePathBegin = label();
    SpeculativeJIT speculative(*this);
    bool compiledSpeculative = speculative.compile();

    // Next, generate the non-speculative path. We pass this a SpeculationCheckIndexIterator
    // to allow it to check which nodes in the graph may bail out, and may need to reenter the
    // non-speculative path.
    if (compiledSpeculative) {
        SpeculationCheckIndexIterator checkIterator(speculative.speculationChecks());
        NonSpeculativeJIT nonSpeculative(*this);
        nonSpeculative.compile(checkIterator);

        // Link the bail-outs from the speculative path to the corresponding entry points into the non-speculative one.
        linkSpeculationChecks(speculative, nonSpeculative);
    } else {
        // If compilation through the SpeculativeJIT failed, throw away the code we generated.
        m_calls.clear();
        rewindToLabel(speculativePathBegin);

        SpeculationCheckVector noChecks;
        SpeculationCheckIndexIterator checkIterator(noChecks);
        NonSpeculativeJIT nonSpeculative(*this);
        nonSpeculative.compile(checkIterator);
    }

    // === Stage 3 - Function footer code generation ===
    //
    // Generate code to lookup and jump to exception handlers, to perform the slow
    // register file check (if the fast one in the function header fails), and
    // generate the entry point with arity check.

    // Iterate over the m_calls vector, checking for exception checks,
    // and linking them to here.
    unsigned exceptionCheckCount = 0;
    for (unsigned i = 0; i < m_calls.size(); ++i) {
        Jump& exceptionCheck = m_calls[i].m_exceptionCheck;
        if (exceptionCheck.isSet()) {
            exceptionCheck.link(this);
            ++exceptionCheckCount;
        }
    }
    // If any exception checks were linked, generate code to lookup a handler.
    if (exceptionCheckCount) {
        // lookupExceptionHandler is passed two arguments, exec (the CallFrame*), and
        // an identifier for the operation that threw the exception, which we can use
        // to look up handler information. The identifier we use is the return address
        // of the call out from JIT code that threw the exception; this is still
        // available on the stack, just below the stack pointer!
        move(callFrameRegister, argumentRegister0);
        peek(argumentRegister1, -1);
        m_calls.append(CallRecord(call(), lookupExceptionHandler));
        // lookupExceptionHandler leaves the handler CallFrame* in the returnValueRegister,
        // and the address of the handler in returnValueRegister2.
        jump(returnValueRegister2);
    }

    // Generate the register file check; if the fast check in the function head fails,
    // we need to call out to a helper function to check whether more space is available.
    // FIXME: change this from a cti call to a DFG style operation (normal C calling conventions).
    registerFileCheck.link(this);
    move(stackPointerRegister, argumentRegister0);
    poke(callFrameRegister, OBJECT_OFFSETOF(struct JITStackFrame, callFrame) / sizeof(void*));
    Call callRegisterFileCheck = call();
    jump(fromRegisterFileCheck);

    // The fast entry point into a function does not check the correct number of arguments
    // have been passed to the call (we only use the fast entry point where we can statically
    // determine the correct number of arguments have been passed, or have already checked).
    // In cases where an arity check is necessary, we enter here.
    // FIXME: change this from a cti call to a DFG style operation (normal C calling conventions).
    Label arityCheck = label();
    preserveReturnAddressAfterCall(regT2);
    emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
    branch32(Equal, regT1, Imm32(m_codeBlock->m_numParameters)).linkTo(fromArityCheck, this);
    move(stackPointerRegister, argumentRegister0);
    poke(callFrameRegister, OBJECT_OFFSETOF(struct JITStackFrame, callFrame) / sizeof(void*));
    Call callArityCheck = call();
    move(regT0, callFrameRegister);
    jump(fromArityCheck);

    // === Stage 4 - Link ===
    //
    // Link the code, populate data in CodeBlock data structures.

    LinkBuffer linkBuffer(this, m_globalData->executableAllocator.poolForSize(m_assembler.size()), 0);

#if DFG_DEBUG_VERBOSE
    fprintf(stderr, "JIT code start at %p\n", linkBuffer.debugAddress());
#endif

    // Link all calls out from the JIT code to their respective functions.
    for (unsigned i = 0; i < m_calls.size(); ++i)
        linkBuffer.link(m_calls[i].m_call, m_calls[i].m_function);

    if (m_codeBlock->needsCallReturnIndices()) {
        m_codeBlock->callReturnIndexVector().reserveCapacity(exceptionCheckCount);
        for (unsigned i = 0; i < m_calls.size(); ++i) {
            if (m_calls[i].m_exceptionCheck.isSet()) {
                unsigned returnAddressOffset = linkBuffer.returnAddressOffset(m_calls[i].m_call);
                unsigned exceptionInfo = m_calls[i].m_exceptionInfo;
                m_codeBlock->callReturnIndexVector().append(CallReturnOffsetToBytecodeOffset(returnAddressOffset, exceptionInfo));
            }
        }
    }

    // FIXME: switch the register file check & arity check over to DFGOpertaion style calls, not JIT stubs.
    linkBuffer.link(callRegisterFileCheck, cti_register_file_check);
    linkBuffer.link(callArityCheck, m_codeBlock->m_isConstructor ? cti_op_construct_arityCheck : cti_op_call_arityCheck);

    entryWithArityCheck = linkBuffer.locationOf(arityCheck);
    entry = linkBuffer.finalizeCode();
}

#if DFG_JIT_ASSERT
void JITCompiler::jitAssertIsInt32(GPRReg gpr)
{
#if CPU(X86_64)
    Jump checkInt32 = branchPtr(BelowOrEqual, gprToRegisterID(gpr), TrustedImmPtr(reinterpret_cast<void*>(static_cast<uintptr_t>(0xFFFFFFFFu))));
    breakpoint();
    checkInt32.link(this);
#else
    UNUSED_PARAM(gpr);
#endif
}

void JITCompiler::jitAssertIsJSInt32(GPRReg gpr)
{
    Jump checkJSInt32 = branchPtr(AboveOrEqual, gprToRegisterID(gpr), tagTypeNumberRegister);
    breakpoint();
    checkJSInt32.link(this);
}

void JITCompiler::jitAssertIsJSNumber(GPRReg gpr)
{
    Jump checkJSNumber = branchTestPtr(MacroAssembler::NonZero, gprToRegisterID(gpr), tagTypeNumberRegister);
    breakpoint();
    checkJSNumber.link(this);
}

void JITCompiler::jitAssertIsJSDouble(GPRReg gpr)
{
    Jump checkJSInt32 = branchPtr(AboveOrEqual, gprToRegisterID(gpr), tagTypeNumberRegister);
    Jump checkJSNumber = branchTestPtr(MacroAssembler::NonZero, gprToRegisterID(gpr), tagTypeNumberRegister);
    checkJSInt32.link(this);
    breakpoint();
    checkJSNumber.link(this);
}
#endif

#if ENABLE(SAMPLING_COUNTERS) && CPU(X86_64) // Or any other 64-bit platform!
void JITCompiler::emitCount(AbstractSamplingCounter& counter, uint32_t increment)
{
    addPtr(TrustedImm32(increment), AbsoluteAddress(counter.addressOfCounter()));
}
#endif

#if ENABLE(SAMPLING_COUNTERS) && CPU(X86) // Or any other little-endian 32-bit platform!
void JITCompiler::emitCount(AbstractSamplingCounter& counter, uint32_t increment)
{
    intptr_t hiWord = reinterpret_cast<intptr_t>(counter.addressOfCounter()) + sizeof(int32_t);
    add32(TrustedImm32(increment), AbsoluteAddress(counter.addressOfCounter()));
    addWithCarry32(TrustedImm32(0), AbsoluteAddress(reinterpret_cast<void*>(hiWord)));
}
#endif

} } // namespace JSC::DFG

#endif


text:
RSpec.describe RuboCop::Cop::Layout::MultilineAssignmentLayout, :config do
  subject(:cop) { described_class.new(config) }

  let(:supported_types) { %w[if] }

  let(:cop_config) do
    {
      'EnforcedStyle' => enforced_style,
      'SupportedTypes' => supported_types
    }
  end

  context 'new_line style' do
    let(:enforced_style) { 'new_line' }

    it 'registers an offense when the rhs is on the same line' do
      expect_offense(<<~RUBY)
        blarg = if true
        ^^^^^^^^^^^^^^^ Right hand side of multi-line assignment is on the same line as the assignment operator `=`.
        end
      RUBY
    end

    it 'auto-corrects offenses' do
      new_source = autocorrect_source(<<~RUBY)
        blarg = if true
        end
      RUBY

      expect(new_source).to eq(<<~RUBY)
        blarg =
         if true
        end
      RUBY
    end

    it 'ignores arrays' do
      expect_no_offenses(<<~RUBY)
        a, b = 4,
        5
      RUBY
    end

    context 'configured supported types' do
      let(:supported_types) { %w[array] }

      it 'allows supported types to be configured' do
        expect_offense(<<~RUBY)
          a, b = 4,
          ^^^^^^^^^ Right hand side of multi-line assignment is on the same line as the assignment operator `=`.
          5
        RUBY
      end
    end

    it 'allows multi-line assignments on separate lines' do
      expect_no_offenses(<<~RUBY)
        blarg=
        if true
        end
      RUBY
    end

    it 'registers an offense for masgn with multi-line lhs' do
      expect_offense(<<~RUBY)
        a,
        ^^ Right hand side of multi-line assignment is on the same line as the assignment operator `=`.
        b = if foo
        end
      RUBY
    end

    context 'when supported types is block' do
      let(:supported_types) { %w[block] }

      it 'registers an offense when multi-line assignments ' \
         'using block definition is on the same line' do
        expect_offense(<<~RUBY)
          lambda = -> {
          ^^^^^^^^^^^^^ Right hand side of multi-line assignment is on the same line as the assignment operator `=`.
            puts 'hello'
          }
        RUBY
      end

      it 'allows multi-line assignments when using block definition ' \
         'on separate lines' do
        expect_no_offenses(<<~RUBY)
          lambda =
            -> {
              puts 'hello'
            }
        RUBY
      end

      it 'allows multi-line block defines on separate lines' do
        expect_no_offenses(<<~RUBY)
          default_scope -> {
            where(foo: "bar")
          }
        RUBY
      end

      it 'allows multi-line assignments when using shovel operator' do
        expect_no_offenses(<<~'RUBY')
          foo << items.map do |item|
            "#{item}!"
          end
        RUBY
      end
    end
  end

  context 'same_line style' do
    let(:enforced_style) { 'same_line' }

    it 'registers an offense when the rhs is a different line' do
      expect_offense(<<~RUBY)
        blarg =
        ^^^^^^^ Right hand side of multi-line assignment is not on the same line as the assignment operator `=`.
        if true
        end
      RUBY
    end

    it 'auto-corrects offenses' do
      new_source = autocorrect_source(<<~RUBY)
        blarg =
        if true
        end
      RUBY

      expect(new_source).to eq(<<~RUBY)
        blarg = if true
        end
      RUBY
    end

    it 'ignores arrays' do
      expect_no_offenses(<<~RUBY)
        a, b =
        4,
        5
      RUBY
    end

    context 'configured supported types' do
      let(:supported_types) { %w[array] }

      it 'allows supported types to be configured' do
        expect_offense(<<~RUBY)
          a, b =
          ^^^^^^ Right hand side of multi-line assignment is not on the same line as the assignment operator `=`.
          4,
          5
        RUBY
      end
    end

    it 'allows multi-line assignments on the same line' do
      expect_no_offenses(<<~RUBY)
        blarg= if true
        end
      RUBY
    end

    it 'registers an offense for masgn with multi-line lhs' do
      expect_offense(<<~RUBY)
        a,
        ^^ Right hand side of multi-line assignment is not on the same line as the assignment operator `=`.
        b =
        if foo
        end
      RUBY
    end

    context 'when supported types is block' do
      let(:supported_types) { %w[block] }

      it 'allows when multi-line assignments using block definition ' \
         'is on the same line' do
        expect_no_offenses(<<~RUBY)
          lambda = -> {
            puts 'hello'
          }
        RUBY
      end

      it 'registers an offense when multi-line assignments ' \
         'using block definition on separate lines' do
        expect_offense(<<~RUBY)
          lambda =
          ^^^^^^^^ Right hand side of multi-line assignment is not on the same line as the assignment operator `=`.
            -> {
              puts 'hello'
            }
        RUBY
      end

      it 'allows multi-line block defines on separate lines' do
        expect_no_offenses(<<~RUBY)
          default_scope -> {
            where(foo: "bar")
          }
        RUBY
      end

      it 'allows multi-line assignments when using shovel operator' do
        expect_no_offenses(<<~'RUBY')
          foo << items.map do |item|
            "#{item}!"
          end
        RUBY
      end
    end
  end
end


text:
You can see below the API reference of this module.

### `fromProvider(providerName, user, repo, status, auth, callback)`
Fetches the issues from provider.

#### Params
- **String** `providerName`: The provider name (currently supported `"bitbucket"` and `"github"`).
- **String** `user`: The repository owner.
- **String** `repo`: The repository name.
- **String** `status`: The issue status.
- **Object** `auth`: The authorization object:
 - `username` (String): The provider username.
 - `password` (String): The provider password/token.
- **Function** `callback`: The callback function.

### `fromPath(path, status, auth, callback)`
Fetches the issues by passing the local repository path.

#### Params
- **String** `path`: The path to the local repository.
- **String** `status`: The issue status.
- **Object** `auth`: The authorization object:
 - `username` (String): The provider username.
 - `password` (String): The provider password/token.
- **Function** `callback`: The callback function.


text:
<!DOCTYPE html>

    <title>Votos por prédio - 2° Turno São Luís </title>


text:
import os

from cyclus_tools import run_cyclus
from testcases import sim_files

def main():
    """Creates reference databases. Assumes that cyclus is included into PATH.
    """
    cwd = os.getcwd()

    # Run cyclus
    run_cyclus("cyclus", cwd, sim_files)

if __name__ == "__main__":
    main()


text:
<?php

namespace Symfony\Component\Routing\Loader;

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Config\Resource\DirectoryResource;

class DirectoryLoader extends FileLoader
{
    /**
     * {@inheritdoc}
     */
    public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        $collection = new RouteCollection();
        $collection->addResource(new DirectoryResource($path));

        foreach (scandir($path) as $dir) {
            if ('.' !== $dir[0]) {
                $this->setCurrentDir($path);
                $subPath = $path.'/'.$dir;
                $subType = null;

                if (is_dir($subPath)) {
                    $subPath .= '/';
                    $subType = 'directory';
                }

                $subCollection = $this->import($subPath, $subType, false, $path);
                $collection->addCollection($subCollection);
            }
        }

        return $collection;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($resource, $type = null)
    {
        // only when type is forced to directory, not to conflict with AnnotationLoader

        return 'directory' === $type;
    }
}


text:
from django.conf import settings  # noqa
from django.core.exceptions import ImproperlyConfigured
from django.utils import importlib

from appconf import AppConf

def load_path_attr(path):
    i = path.rfind(".")
    module, attr = path[:i], path[i + 1:]
    try:
        mod = importlib.import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured("Error importing {0}: '{1}'".format(module, e))
    try:
        attr = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured("Module '{0}' does not define a '{1}'".format(module, attr))
    return attr

class TeamAppConf(AppConf):

    PROFILE_MODEL = ""
    HOOKSET = "pinax.teams.hooks.TeamDefaultHookset"
    NAME_BLACKLIST = []

    def configure_profile_model(self, value):
        if value:
            return load_path_attr(value)

    def configure_hookset(self, value):
        return load_path_attr(value)()


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Transgenic Citrate-Producing Plants for Lead Phytoremediation|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2003-06-24" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

Final Report

SBIR Phase I

                              | Final Report

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Transgenic Citrate-Producing Plants for Lead Phytoremediation

    EPA Contract Number: 68D03043

    Title: Transgenic Citrate-Producing Plants for Lead Phytoremediation

    Investigators:
     Elless, Mark P.

    Small Business:

      Edenspace Systems Corporation

    	EPA Contact:

           Manager, SBIR Program

        Phase: II

      Project Period:
      May 1, 2003 through
        April 30, 2005

        Project Amount:

          $225,000

      RFA:
      Small Business Innovation Research (SBIR) - Phase II (2002)

          Recipients Lists

      Research Category:

          Hazardous Waste/Remediation
          ,
          SBIR - Waste
          ,
          Small Business Innovation Research (SBIR)

Description:

In 1991, the U.S. Secretary of Health and Human Services called lead "the
  number one environmental threat to the health of children in the United States."
  Lead exposure can cause premature birth and impair a child's mental and physical
  development. In adults, lead exposure can cause kidney damage, high blood pressure,
  and other problems. The U.S. Environmental Protection Agency estimates that
  12,000,000 homes exceed the new 400 ppm standard for soil lead in play areas.
  Soil lead at small arms firing ranges, manufacturing plants, and other government
  and industrial sites poses similar challenges.

A promising alternative to excavation and replacement of lead-contaminated
  soil is phytoremediation, whereby living plants remove lead from firing ranges,
  industrial sites, and residences. Phytoremediation relies on crop species and
  chelators that facilitate higher plant uptake rates. The annual cost of chelators
  can range up to $20,000 per acre. Furthermore, sites with sandy, well-drained
  soil may need a water-impermeable liner to prevent slowly degrading chelators
  such as ethylenediamine tetraacetic acid from leaching metals into groundwater.
  Costs of a liner can double the total cost of phytoextraction, rendering phytoremediation
  impractical for certain sites.

In this Phase II project, Edenspace Systems Corporation seeks to demonstrate
  the use of transgenic plants that exude significant amounts of a rapidly biodegradable
  chelator-citric acid-from their roots, enabling a cost savings of more than
  70 percent in lead phytoextraction. A citrate synthase (CS) transgene was placed
  under the control of different plant promoters to overexpress the gene in roots.
  In Phase I, 100 lines of CS-transgenic tobacco, Nicotiana tabacum, were
  created and tested. Preliminary results with five hemizygous strains are promising,
  suggesting that higher-performing homozygous strains created at the end of Phase
  I may hyperaccumulate lead from soil (bioconcentration factor >1). Significantly,
  little soluble lead remained in the soil, indicating that the plants may successfully
  address leaching concerns. In Phase II, the highest performing transgenic lines
  will be demonstrated at a small arms firing range in Maryland and a residential
  site in Massachusetts. Phase II objectives also include concentrating lead in
  harvested plants to facilitate disposal or recycling, and mating transgenic
  lines of a proven lead-accumulating plant species, Brassica juncea.

 At many sites, applying rapidly biodegradable citric acid precisely at the
  root/soil interface where metal uptake occurs may eliminate the need for expensive
  chelating agents and liners. Attainment of the project's goals therefore may
  reduce the substantial public health hazard of soil lead by realizing phytoremediation's
  low-cost potential.

Supplemental Keywords:

      small business, SBIR, lead, soil, phytoremediation, phytoextraction, chelator, transgenic plants, Brassica juncea, Nicotiana tabacum, citrate synthase transgene, citric acid, ethylenediamine tetraacetic acid, EPA., RFA, Scientific Discipline, INTERNATIONAL COOPERATION, Waste, Water, TREATMENT/CONTROL, Contaminated Sediments, Treatment Technologies, Microbiology, Analytical Chemistry, Environmental Microbiology, Hazardous Waste, Bioremediation, Molecular Biology/Genetics, Hazardous, degradation, bioavailability, biodegradation, lead, contaminated sediment, Brassica juncea, transgenic plants, citric acid, contaminated soil, contaminants in soil, bioremediation of soils, natural recovery, biochemistry, chlorinated organics, phytoremediation

Progress and Final Reports:

                Final Report

SBIR Phase I:

              Transgenic Citrate-Producing Plants for Lead Phytoremediation

               | Final Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Tuesday, June 24, 2003


text:
import collections
import json

import click

import unicodecsv as csv

def parse_object(obj, path=''):
    """Borrowed from `csvkit`
    """

    if isinstance(obj, dict):
        iterator = obj.items()
    elif isinstance(obj, (list, tuple)):
        iterator = enumerate(obj)
    else:
        return { path.strip('/'): obj }

    d = {}

    for key, value in iterator:
        key = unicode(key)
        d.update(parse_object(value, path + key + '/'))

    return d

@click.command()
@click.option('-t', 'player_type',
              type=click.Choice(('batting', 'pitching', )))
@click.option('-i', 'input_fp', type=click.File('rb'), required=True)
@click.argument('output_fp', type=click.File('w'), required=True)
def convert(player_type, input_fp, output_fp):
    data = json.load(input_fp, object_pairs_hook=collections.OrderedDict)

    if not isinstance(data, list):
        raise click.BadParameter('JSON input object must be a list')

    keys = set()
    rows = []
    valid_type = 'b' if player_type == 'batting' else 'p'

    for projection in data:
        if not projection['player_type'] == valid_type:
            continue

        projection = parse_object(projection)

        for key in projection:
            keys.add(key)

        rows.append(projection)

    headers = sorted(keys)
    writer = csv.DictWriter(output_fp, headers)
    writer.writeheader()

    for row in rows:
        writer.writerow(row)

if __name__ == '__main__':
    convert()


text:
<?php

declare(strict_types=1);

namespace FSi\FixturesBundle\Form\Type;

use FSi\Bundle\FormExtensionsBundle\Form\Type\FSiMapType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

final class SingleMapType extends AbstractType
{
    /**
     * @param FormBuilderInterface<FormBuilderInterface> $builder
     * @param array<string, mixed> $options
     * @return void
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('map', FSiMapType::class, ['label' => 'Map field']);
    }
}


text:
class Issue < ApplicationRecord
	belongs_to :department
	has_many :reports

	validates :department, presence: true
	validates :description, presence: true
end


text:
/*
Added by Roman Ponomarev (rponom@gmail.com)
April 04, 2008
*/

#include "btSliderConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btTransformUtil.h"
#include <new>

#define USE_OFFSET_FOR_CONSTANT_FRAME true

void btSliderConstraint::initParams()
{
	m_lowerLinLimit = btScalar(1.0);
	m_upperLinLimit = btScalar(-1.0);
	m_lowerAngLimit = btScalar(0.);
	m_upperAngLimit = btScalar(0.);
	m_softnessDirLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingDirLin = btScalar(0.);
	m_cfmDirLin = SLIDER_CONSTRAINT_DEF_CFM;
	m_softnessDirAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionDirAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingDirAng = btScalar(0.);
	m_cfmDirAng = SLIDER_CONSTRAINT_DEF_CFM;
	m_softnessOrthoLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionOrthoLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingOrthoLin = SLIDER_CONSTRAINT_DEF_DAMPING;
	m_cfmOrthoLin = SLIDER_CONSTRAINT_DEF_CFM;
	m_softnessOrthoAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionOrthoAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingOrthoAng = SLIDER_CONSTRAINT_DEF_DAMPING;
	m_cfmOrthoAng = SLIDER_CONSTRAINT_DEF_CFM;
	m_softnessLimLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionLimLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingLimLin = SLIDER_CONSTRAINT_DEF_DAMPING;
	m_cfmLimLin = SLIDER_CONSTRAINT_DEF_CFM;
	m_softnessLimAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
	m_restitutionLimAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
	m_dampingLimAng = SLIDER_CONSTRAINT_DEF_DAMPING;
	m_cfmLimAng = SLIDER_CONSTRAINT_DEF_CFM;

	m_poweredLinMotor = false;
	m_targetLinMotorVelocity = btScalar(0.);
	m_maxLinMotorForce = btScalar(0.);
	m_accumulatedLinMotorImpulse = btScalar(0.0);

	m_poweredAngMotor = false;
	m_targetAngMotorVelocity = btScalar(0.);
	m_maxAngMotorForce = btScalar(0.);
	m_accumulatedAngMotorImpulse = btScalar(0.0);

	m_flags = 0;
	m_flags = 0;

	m_useOffsetForConstraintFrame = USE_OFFSET_FOR_CONSTANT_FRAME;

	calculateTransforms(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform());
}

btSliderConstraint::btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
	: btTypedConstraint(SLIDER_CONSTRAINT_TYPE, rbA, rbB),
	  m_useSolveConstraintObsolete(false),
	  m_frameInA(frameInA),
	  m_frameInB(frameInB),
	  m_useLinearReferenceFrameA(useLinearReferenceFrameA)
{
	initParams();
}

btSliderConstraint::btSliderConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameA)
	: btTypedConstraint(SLIDER_CONSTRAINT_TYPE, getFixedBody(), rbB),
	  m_useSolveConstraintObsolete(false),
	  m_frameInB(frameInB),
	  m_useLinearReferenceFrameA(useLinearReferenceFrameA)
{
	///not providing rigidbody A means implicitly using worldspace for body A
	m_frameInA = rbB.getCenterOfMassTransform() * m_frameInB;
	//	m_frameInA.getOrigin() = m_rbA.getCenterOfMassTransform()(m_frameInA.getOrigin());

	initParams();
}

void btSliderConstraint::getInfo1(btConstraintInfo1* info)
{
	if (m_useSolveConstraintObsolete)
	{
		info->m_numConstraintRows = 0;
		info->nub = 0;
	}
	else
	{
		info->m_numConstraintRows = 4;  // Fixed 2 linear + 2 angular
		info->nub = 2;
		//prepare constraint
		calculateTransforms(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform());
		testAngLimits();
		testLinLimits();
		if (getSolveLinLimit() || getPoweredLinMotor())
		{
			info->m_numConstraintRows++;  // limit 3rd linear as well
			info->nub--;
		}
		if (getSolveAngLimit() || getPoweredAngMotor())
		{
			info->m_numConstraintRows++;  // limit 3rd angular as well
			info->nub--;
		}
	}
}

void btSliderConstraint::getInfo1NonVirtual(btConstraintInfo1* info)
{
	info->m_numConstraintRows = 6;  // Fixed 2 linear + 2 angular + 1 limit (even if not used)
	info->nub = 0;
}

void btSliderConstraint::getInfo2(btConstraintInfo2* info)
{
	getInfo2NonVirtual(info, m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform(), m_rbA.getLinearVelocity(), m_rbB.getLinearVelocity(), m_rbA.getInvMass(), m_rbB.getInvMass());
}

void btSliderConstraint::calculateTransforms(const btTransform& transA, const btTransform& transB)
{
	if (m_useLinearReferenceFrameA || (!m_useSolveConstraintObsolete))
	{
		m_calculatedTransformA = transA * m_frameInA;
		m_calculatedTransformB = transB * m_frameInB;
	}
	else
	{
		m_calculatedTransformA = transB * m_frameInB;
		m_calculatedTransformB = transA * m_frameInA;
	}
	m_realPivotAInW = m_calculatedTransformA.getOrigin();
	m_realPivotBInW = m_calculatedTransformB.getOrigin();
	m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0);  // along X
	if (m_useLinearReferenceFrameA || m_useSolveConstraintObsolete)
	{
		m_delta = m_realPivotBInW - m_realPivotAInW;
	}
	else
	{
		m_delta = m_realPivotAInW - m_realPivotBInW;
	}
	m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
	btVector3 normalWorld;
	int i;
	//linear part
	for (i = 0; i < 3; i++)
	{
		normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
		m_depth[i] = m_delta.dot(normalWorld);
	}
}

void btSliderConstraint::testLinLimits(void)
{
	m_solveLinLim = false;
	m_linPos = m_depth[0];
	if (m_lowerLinLimit <= m_upperLinLimit)
	{
		if (m_depth[0] > m_upperLinLimit)
		{
			m_depth[0] -= m_upperLinLimit;
			m_solveLinLim = true;
		}
		else if (m_depth[0] < m_lowerLinLimit)
		{
			m_depth[0] -= m_lowerLinLimit;
			m_solveLinLim = true;
		}
		else
		{
			m_depth[0] = btScalar(0.);
		}
	}
	else
	{
		m_depth[0] = btScalar(0.);
	}
}

void btSliderConstraint::testAngLimits(void)
{
	m_angDepth = btScalar(0.);
	m_solveAngLim = false;
	if (m_lowerAngLimit <= m_upperAngLimit)
	{
		const btVector3 axisA0 = m_calculatedTransformA.getBasis().getColumn(1);
		const btVector3 axisA1 = m_calculatedTransformA.getBasis().getColumn(2);
		const btVector3 axisB0 = m_calculatedTransformB.getBasis().getColumn(1);
		//		btScalar rot = btAtan2Fast(axisB0.dot(axisA1), axisB0.dot(axisA0));
		btScalar rot = btAtan2(axisB0.dot(axisA1), axisB0.dot(axisA0));
		rot = btAdjustAngleToLimits(rot, m_lowerAngLimit, m_upperAngLimit);
		m_angPos = rot;
		if (rot < m_lowerAngLimit)
		{
			m_angDepth = rot - m_lowerAngLimit;
			m_solveAngLim = true;
		}
		else if (rot > m_upperAngLimit)
		{
			m_angDepth = rot - m_upperAngLimit;
			m_solveAngLim = true;
		}
	}
}

btVector3 btSliderConstraint::getAncorInA(void)
{
	btVector3 ancorInA;
	ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * btScalar(0.5) * m_sliderAxis;
	ancorInA = m_rbA.getCenterOfMassTransform().inverse() * ancorInA;
	return ancorInA;
}

btVector3 btSliderConstraint::getAncorInB(void)
{
	btVector3 ancorInB;
	ancorInB = m_frameInB.getOrigin();
	return ancorInB;
}

void btSliderConstraint::getInfo2NonVirtual(btConstraintInfo2* info, const btTransform& transA, const btTransform& transB, const btVector3& linVelA, const btVector3& linVelB, btScalar rbAinvMass, btScalar rbBinvMass)
{
	const btTransform& trA = getCalculatedTransformA();
	const btTransform& trB = getCalculatedTransformB();

	btAssert(!m_useSolveConstraintObsolete);
	int i, s = info->rowskip;

	btScalar signFact = m_useLinearReferenceFrameA ? btScalar(1.0f) : btScalar(-1.0f);

	// difference between frames in WCS
	btVector3 ofs = trB.getOrigin() - trA.getOrigin();
	// now get weight factors depending on masses
	btScalar miA = rbAinvMass;
	btScalar miB = rbBinvMass;
	bool hasStaticBody = (miA < SIMD_EPSILON) || (miB < SIMD_EPSILON);
	btScalar miS = miA + miB;
	btScalar factA, factB;
	if (miS > btScalar(0.f))
	{
		factA = miB / miS;
	}
	else
	{
		factA = btScalar(0.5f);
	}
	factB = btScalar(1.0f) - factA;
	btVector3 ax1, p, q;
	btVector3 ax1A = trA.getBasis().getColumn(0);
	btVector3 ax1B = trB.getBasis().getColumn(0);
	if (m_useOffsetForConstraintFrame)
	{
		// get the desired direction of slider axis
		// as weighted sum of X-orthos of frameA and frameB in WCS
		ax1 = ax1A * factA + ax1B * factB;
		ax1.normalize();
		// construct two orthos to slider axis
		btPlaneSpace1(ax1, p, q);
	}
	else
	{  // old way - use frameA
		ax1 = trA.getBasis().getColumn(0);
		// get 2 orthos to slider axis (Y, Z)
		p = trA.getBasis().getColumn(1);
		q = trA.getBasis().getColumn(2);
	}
	// make rotations around these orthos equal
	// the slider axis should be the only unconstrained
	// rotational axis, the angular velocity of the two bodies perpendicular to
	// the slider axis should be equal. thus the constraint equations are
	//    p*w1 - p*w2 = 0
	//    q*w1 - q*w2 = 0
	// where p and q are unit vectors normal to the slider axis, and w1 and w2
	// are the angular velocity vectors of the two bodies.
	info->m_J1angularAxis[0] = p[0];
	info->m_J1angularAxis[1] = p[1];
	info->m_J1angularAxis[2] = p[2];
	info->m_J1angularAxis[s + 0] = q[0];
	info->m_J1angularAxis[s + 1] = q[1];
	info->m_J1angularAxis[s + 2] = q[2];

	info->m_J2angularAxis[0] = -p[0];
	info->m_J2angularAxis[1] = -p[1];
	info->m_J2angularAxis[2] = -p[2];
	info->m_J2angularAxis[s + 0] = -q[0];
	info->m_J2angularAxis[s + 1] = -q[1];
	info->m_J2angularAxis[s + 2] = -q[2];
	// compute the right hand side of the constraint equation. set relative
	// body velocities along p and q to bring the slider back into alignment.
	// if ax1A,ax1B are the unit length slider axes as computed from bodyA and
	// bodyB, we need to rotate both bodies along the axis u = (ax1 x ax2).
	// if "theta" is the angle between ax1 and ax2, we need an angular velocity
	// along u to cover angle erp*theta in one step :
	//   |angular_velocity| = angle/time = erp*theta / stepsize
	//                      = (erp*fps) * theta
	//    angular_velocity  = |angular_velocity| * (ax1 x ax2) / |ax1 x ax2|
	//                      = (erp*fps) * theta * (ax1 x ax2) / sin(theta)
	// ...as ax1 and ax2 are unit length. if theta is smallish,
	// theta ~= sin(theta), so
	//    angular_velocity  = (erp*fps) * (ax1 x ax2)
	// ax1 x ax2 is in the plane space of ax1, so we project the angular
	// velocity to p and q to find the right hand side.
	//	btScalar k = info->fps * info->erp * getSoftnessOrthoAng();
	btScalar currERP = (m_flags & BT_SLIDER_FLAGS_ERP_ORTANG) ? m_softnessOrthoAng : m_softnessOrthoAng * info->erp;
	btScalar k = info->fps * currERP;

	btVector3 u = ax1A.cross(ax1B);
	info->m_constraintError[0] = k * u.dot(p);
	info->m_constraintError[s] = k * u.dot(q);
	if (m_flags & BT_SLIDER_FLAGS_CFM_ORTANG)
	{
		info->cfm[0] = m_cfmOrthoAng;
		info->cfm[s] = m_cfmOrthoAng;
	}

	int nrow = 1;  // last filled row
	int srow;
	btScalar limit_err;
	int limit;

	// next two rows.
	// we want: velA + wA x relA == velB + wB x relB ... but this would
	// result in three equations, so we project along two orthos to the slider axis

	btTransform bodyA_trans = transA;
	btTransform bodyB_trans = transB;
	nrow++;
	int s2 = nrow * s;
	nrow++;
	int s3 = nrow * s;
	btVector3 tmpA(0, 0, 0), tmpB(0, 0, 0), relA(0, 0, 0), relB(0, 0, 0), c(0, 0, 0);
	if (m_useOffsetForConstraintFrame)
	{
		// get vector from bodyB to frameB in WCS
		relB = trB.getOrigin() - bodyB_trans.getOrigin();
		// get its projection to slider axis
		btVector3 projB = ax1 * relB.dot(ax1);
		// get vector directed from bodyB to slider axis (and orthogonal to it)
		btVector3 orthoB = relB - projB;
		// same for bodyA
		relA = trA.getOrigin() - bodyA_trans.getOrigin();
		btVector3 projA = ax1 * relA.dot(ax1);
		btVector3 orthoA = relA - projA;
		// get desired offset between frames A and B along slider axis
		btScalar sliderOffs = m_linPos - m_depth[0];
		// desired vector from projection of center of bodyA to projection of center of bodyB to slider axis
		btVector3 totalDist = projA + ax1 * sliderOffs - projB;
		// get offset vectors relA and relB
		relA = orthoA + totalDist * factA;
		relB = orthoB - totalDist * factB;
		// now choose average ortho to slider axis
		p = orthoB * factA + orthoA * factB;
		btScalar len2 = p.length2();
		if (len2 > SIMD_EPSILON)
		{
			p /= btSqrt(len2);
		}
		else
		{
			p = trA.getBasis().getColumn(1);
		}
		// make one more ortho
		q = ax1.cross(p);
		// fill two rows
		tmpA = relA.cross(p);
		tmpB = relB.cross(p);
		for (i = 0; i < 3; i++) info->m_J1angularAxis[s2 + i] = tmpA[i];
		for (i = 0; i < 3; i++) info->m_J2angularAxis[s2 + i] = -tmpB[i];
		tmpA = relA.cross(q);
		tmpB = relB.cross(q);
		if (hasStaticBody && getSolveAngLimit())
		{  // to make constraint between static and dynamic objects more rigid
			// remove wA (or wB) from equation if angular limit is hit
			tmpB *= factB;
			tmpA *= factA;
		}
		for (i = 0; i < 3; i++) info->m_J1angularAxis[s3 + i] = tmpA[i];
		for (i = 0; i < 3; i++) info->m_J2angularAxis[s3 + i] = -tmpB[i];
		for (i = 0; i < 3; i++) info->m_J1linearAxis[s2 + i] = p[i];
		for (i = 0; i < 3; i++) info->m_J1linearAxis[s3 + i] = q[i];
		for (i = 0; i < 3; i++) info->m_J2linearAxis[s2 + i] = -p[i];
		for (i = 0; i < 3; i++) info->m_J2linearAxis[s3 + i] = -q[i];
	}
	else
	{  // old way - maybe incorrect if bodies are not on the slider axis
		// see discussion "Bug in slider constraint" http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=4024&start=0
		c = bodyB_trans.getOrigin() - bodyA_trans.getOrigin();
		btVector3 tmp = c.cross(p);
		for (i = 0; i < 3; i++) info->m_J1angularAxis[s2 + i] = factA * tmp[i];
		for (i = 0; i < 3; i++) info->m_J2angularAxis[s2 + i] = factB * tmp[i];
		tmp = c.cross(q);
		for (i = 0; i < 3; i++) info->m_J1angularAxis[s3 + i] = factA * tmp[i];
		for (i = 0; i < 3; i++) info->m_J2angularAxis[s3 + i] = factB * tmp[i];

		for (i = 0; i < 3; i++) info->m_J1linearAxis[s2 + i] = p[i];
		for (i = 0; i < 3; i++) info->m_J1linearAxis[s3 + i] = q[i];
		for (i = 0; i < 3; i++) info->m_J2linearAxis[s2 + i] = -p[i];
		for (i = 0; i < 3; i++) info->m_J2linearAxis[s3 + i] = -q[i];
	}
	// compute two elements of right hand side

	//	k = info->fps * info->erp * getSoftnessOrthoLin();
	currERP = (m_flags & BT_SLIDER_FLAGS_ERP_ORTLIN) ? m_softnessOrthoLin : m_softnessOrthoLin * info->erp;
	k = info->fps * currERP;

	btScalar rhs = k * p.dot(ofs);
	info->m_constraintError[s2] = rhs;
	rhs = k * q.dot(ofs);
	info->m_constraintError[s3] = rhs;
	if (m_flags & BT_SLIDER_FLAGS_CFM_ORTLIN)
	{
		info->cfm[s2] = m_cfmOrthoLin;
		info->cfm[s3] = m_cfmOrthoLin;
	}

	// check linear limits
	limit_err = btScalar(0.0);
	limit = 0;
	if (getSolveLinLimit())
	{
		limit_err = getLinDepth() * signFact;
		limit = (limit_err > btScalar(0.0)) ? 2 : 1;
	}
	bool powered = getPoweredLinMotor();
	// if the slider has joint limits or motor, add in the extra row
	if (limit || powered)
	{
		nrow++;
		srow = nrow * info->rowskip;
		info->m_J1linearAxis[srow + 0] = ax1[0];
		info->m_J1linearAxis[srow + 1] = ax1[1];
		info->m_J1linearAxis[srow + 2] = ax1[2];
		info->m_J2linearAxis[srow + 0] = -ax1[0];
		info->m_J2linearAxis[srow + 1] = -ax1[1];
		info->m_J2linearAxis[srow + 2] = -ax1[2];
		// linear torque decoupling step:
		//
		// we have to be careful that the linear constraint forces (+/- ax1) applied to the two bodies
		// do not create a torque couple. in other words, the points that the
		// constraint force is applied at must lie along the same ax1 axis.
		// a torque couple will result in limited slider-jointed free
		// bodies from gaining angular momentum.
		if (m_useOffsetForConstraintFrame)
		{
			// this is needed only when bodyA and bodyB are both dynamic.
			if (!hasStaticBody)
			{
				tmpA = relA.cross(ax1);
				tmpB = relB.cross(ax1);
				info->m_J1angularAxis[srow + 0] = tmpA[0];
				info->m_J1angularAxis[srow + 1] = tmpA[1];
				info->m_J1angularAxis[srow + 2] = tmpA[2];
				info->m_J2angularAxis[srow + 0] = -tmpB[0];
				info->m_J2angularAxis[srow + 1] = -tmpB[1];
				info->m_J2angularAxis[srow + 2] = -tmpB[2];
			}
		}
		else
		{                   // The old way. May be incorrect if bodies are not on the slider axis
			btVector3 ltd;  // Linear Torque Decoupling vector (a torque)
			ltd = c.cross(ax1);
			info->m_J1angularAxis[srow + 0] = factA * ltd[0];
			info->m_J1angularAxis[srow + 1] = factA * ltd[1];
			info->m_J1angularAxis[srow + 2] = factA * ltd[2];
			info->m_J2angularAxis[srow + 0] = factB * ltd[0];
			info->m_J2angularAxis[srow + 1] = factB * ltd[1];
			info->m_J2angularAxis[srow + 2] = factB * ltd[2];
		}
		// right-hand part
		btScalar lostop = getLowerLinLimit();
		btScalar histop = getUpperLinLimit();
		if (limit && (lostop == histop))
		{  // the joint motor is ineffective
			powered = false;
		}
		info->m_constraintError[srow] = 0.;
		info->m_lowerLimit[srow] = 0.;
		info->m_upperLimit[srow] = 0.;
		currERP = (m_flags & BT_SLIDER_FLAGS_ERP_LIMLIN) ? m_softnessLimLin : info->erp;
		if (powered)
		{
			if (m_flags & BT_SLIDER_FLAGS_CFM_DIRLIN)
			{
				info->cfm[srow] = m_cfmDirLin;
			}
			btScalar tag_vel = getTargetLinMotorVelocity();
			btScalar mot_fact = getMotorFactor(m_linPos, m_lowerLinLimit, m_upperLinLimit, tag_vel, info->fps * currERP);
			info->m_constraintError[srow] -= signFact * mot_fact * getTargetLinMotorVelocity();
			info->m_lowerLimit[srow] += -getMaxLinMotorForce() / info->fps;
			info->m_upperLimit[srow] += getMaxLinMotorForce() / info->fps;
		}
		if (limit)
		{
			k = info->fps * currERP;
			info->m_constraintError[srow] += k * limit_err;
			if (m_flags & BT_SLIDER_FLAGS_CFM_LIMLIN)
			{
				info->cfm[srow] = m_cfmLimLin;
			}
			if (lostop == histop)
			{  // limited low and high simultaneously
				info->m_lowerLimit[srow] = -SIMD_INFINITY;
				info->m_upperLimit[srow] = SIMD_INFINITY;
			}
			else if (limit == 1)
			{  // low limit
				info->m_lowerLimit[srow] = -SIMD_INFINITY;
				info->m_upperLimit[srow] = 0;
			}
			else
			{  // high limit
				info->m_lowerLimit[srow] = 0;
				info->m_upperLimit[srow] = SIMD_INFINITY;
			}
			// bounce (we'll use slider parameter abs(1.0 - m_dampingLimLin) for that)
			btScalar bounce = btFabs(btScalar(1.0) - getDampingLimLin());
			if (bounce > btScalar(0.0))
			{
				btScalar vel = linVelA.dot(ax1);
				vel -= linVelB.dot(ax1);
				vel *= signFact;
				// only apply bounce if the velocity is incoming, and if the
				// resulting c[] exceeds what we already have.
				if (limit == 1)
				{  // low limit
					if (vel < 0)
					{
						btScalar newc = -bounce * vel;
						if (newc > info->m_constraintError[srow])
						{
							info->m_constraintError[srow] = newc;
						}
					}
				}
				else
				{  // high limit - all those computations are reversed
					if (vel > 0)
					{
						btScalar newc = -bounce * vel;
						if (newc < info->m_constraintError[srow])
						{
							info->m_constraintError[srow] = newc;
						}
					}
				}
			}
			info->m_constraintError[srow] *= getSoftnessLimLin();
		}  // if(limit)
	}      // if linear limit
	// check angular limits
	limit_err = btScalar(0.0);
	limit = 0;
	if (getSolveAngLimit())
	{
		limit_err = getAngDepth();
		limit = (limit_err > btScalar(0.0)) ? 1 : 2;
	}
	// if the slider has joint limits, add in the extra row
	powered = getPoweredAngMotor();
	if (limit || powered)
	{
		nrow++;
		srow = nrow * info->rowskip;
		info->m_J1angularAxis[srow + 0] = ax1[0];
		info->m_J1angularAxis[srow + 1] = ax1[1];
		info->m_J1angularAxis[srow + 2] = ax1[2];

		info->m_J2angularAxis[srow + 0] = -ax1[0];
		info->m_J2angularAxis[srow + 1] = -ax1[1];
		info->m_J2angularAxis[srow + 2] = -ax1[2];

		btScalar lostop = getLowerAngLimit();
		btScalar histop = getUpperAngLimit();
		if (limit && (lostop == histop))
		{  // the joint motor is ineffective
			powered = false;
		}
		currERP = (m_flags & BT_SLIDER_FLAGS_ERP_LIMANG) ? m_softnessLimAng : info->erp;
		if (powered)
		{
			if (m_flags & BT_SLIDER_FLAGS_CFM_DIRANG)
			{
				info->cfm[srow] = m_cfmDirAng;
			}
			btScalar mot_fact = getMotorFactor(m_angPos, m_lowerAngLimit, m_upperAngLimit, getTargetAngMotorVelocity(), info->fps * currERP);
			info->m_constraintError[srow] = mot_fact * getTargetAngMotorVelocity();
			info->m_lowerLimit[srow] = -getMaxAngMotorForce() / info->fps;
			info->m_upperLimit[srow] = getMaxAngMotorForce() / info->fps;
		}
		if (limit)
		{
			k = info->fps * currERP;
			info->m_constraintError[srow] += k * limit_err;
			if (m_flags & BT_SLIDER_FLAGS_CFM_LIMANG)
			{
				info->cfm[srow] = m_cfmLimAng;
			}
			if (lostop == histop)
			{
				// limited low and high simultaneously
				info->m_lowerLimit[srow] = -SIMD_INFINITY;
				info->m_upperLimit[srow] = SIMD_INFINITY;
			}
			else if (limit == 1)
			{  // low limit
				info->m_lowerLimit[srow] = 0;
				info->m_upperLimit[srow] = SIMD_INFINITY;
			}
			else
			{  // high limit
				info->m_lowerLimit[srow] = -SIMD_INFINITY;
				info->m_upperLimit[srow] = 0;
			}
			// bounce (we'll use slider parameter abs(1.0 - m_dampingLimAng) for that)
			btScalar bounce = btFabs(btScalar(1.0) - getDampingLimAng());
			if (bounce > btScalar(0.0))
			{
				btScalar vel = m_rbA.getAngularVelocity().dot(ax1);
				vel -= m_rbB.getAngularVelocity().dot(ax1);
				// only apply bounce if the velocity is incoming, and if the
				// resulting c[] exceeds what we already have.
				if (limit == 1)
				{  // low limit
					if (vel < 0)
					{
						btScalar newc = -bounce * vel;
						if (newc > info->m_constraintError[srow])
						{
							info->m_constraintError[srow] = newc;
						}
					}
				}
				else
				{  // high limit - all those computations are reversed
					if (vel > 0)
					{
						btScalar newc = -bounce * vel;
						if (newc < info->m_constraintError[srow])
						{
							info->m_constraintError[srow] = newc;
						}
					}
				}
			}
			info->m_constraintError[srow] *= getSoftnessLimAng();
		}  // if(limit)
	}      // if angular limit or powered
}

///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
///If no axis is provided, it uses the default axis for this constraint.
void btSliderConstraint::setParam(int num, btScalar value, int axis)
{
	switch (num)
	{
		case BT_CONSTRAINT_STOP_ERP:
			if (axis < 1)
			{
				m_softnessLimLin = value;
				m_flags |= BT_SLIDER_FLAGS_ERP_LIMLIN;
			}
			else if (axis < 3)
			{
				m_softnessOrthoLin = value;
				m_flags |= BT_SLIDER_FLAGS_ERP_ORTLIN;
			}
			else if (axis == 3)
			{
				m_softnessLimAng = value;
				m_flags |= BT_SLIDER_FLAGS_ERP_LIMANG;
			}
			else if (axis < 6)
			{
				m_softnessOrthoAng = value;
				m_flags |= BT_SLIDER_FLAGS_ERP_ORTANG;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
		case BT_CONSTRAINT_CFM:
			if (axis < 1)
			{
				m_cfmDirLin = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_DIRLIN;
			}
			else if (axis == 3)
			{
				m_cfmDirAng = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_DIRANG;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
		case BT_CONSTRAINT_STOP_CFM:
			if (axis < 1)
			{
				m_cfmLimLin = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_LIMLIN;
			}
			else if (axis < 3)
			{
				m_cfmOrthoLin = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_ORTLIN;
			}
			else if (axis == 3)
			{
				m_cfmLimAng = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_LIMANG;
			}
			else if (axis < 6)
			{
				m_cfmOrthoAng = value;
				m_flags |= BT_SLIDER_FLAGS_CFM_ORTANG;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
	}
}

///return the local value of parameter
btScalar btSliderConstraint::getParam(int num, int axis) const
{
	btScalar retVal(SIMD_INFINITY);
	switch (num)
	{
		case BT_CONSTRAINT_STOP_ERP:
			if (axis < 1)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_LIMLIN);
				retVal = m_softnessLimLin;
			}
			else if (axis < 3)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_ORTLIN);
				retVal = m_softnessOrthoLin;
			}
			else if (axis == 3)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_LIMANG);
				retVal = m_softnessLimAng;
			}
			else if (axis < 6)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_ORTANG);
				retVal = m_softnessOrthoAng;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
		case BT_CONSTRAINT_CFM:
			if (axis < 1)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_DIRLIN);
				retVal = m_cfmDirLin;
			}
			else if (axis == 3)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_DIRANG);
				retVal = m_cfmDirAng;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
		case BT_CONSTRAINT_STOP_CFM:
			if (axis < 1)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_LIMLIN);
				retVal = m_cfmLimLin;
			}
			else if (axis < 3)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_ORTLIN);
				retVal = m_cfmOrthoLin;
			}
			else if (axis == 3)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_LIMANG);
				retVal = m_cfmLimAng;
			}
			else if (axis < 6)
			{
				btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_ORTANG);
				retVal = m_cfmOrthoAng;
			}
			else
			{
				btAssertConstrParams(0);
			}
			break;
	}
	return retVal;
}