text:
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import settings from '/imports/utils/settings';
import { photoSwipeOpen } from '/imports/ui/redux/actions';
import GridLayout from '/imports/ui/components/GridLayout';
import ConnectedGridImageHolder from './components/GridImageHolder';

const { imageDomain } = settings;

export class JustifiedGridLayout extends PureComponent {
  static propTypes = {
    isEditing: PropTypes.bool,
    images: PropTypes.array.isRequired,
    showGallery: PropTypes.bool,
    filterType: PropTypes.oneOf(['latest', 'oldest', 'popular']),
    device: PropTypes.object.isRequired,
    photoSwipeOpen: PropTypes.func.isRequired,
  }

  static defaultProps = {
    isEditing: false,
    showGallery: false,
    filterType: 'latest',
  }

  constructor(props) {
    super(props);
    this._loadedItems = [];
    this._pswpItems = props.showGallery ? this.generateItems(props) : null;
  }

  componentWillReceiveProps(nextProps) {
    const { images, showGallery } = this.props;
    // When image added in GroupHolder we need to refresh both two state
    if (
      showGallery &&
      images.length !== nextProps.images.length
    ) {
      this._pswpItems = this.generateItems(nextProps);
    }
  }

  // 获取网格布局图片宽
  generateImageDimension() {
    const { device } = this.props;
    const { width, pixelRatio } = device;
    return Math.round((width / 3) * pixelRatio);
  }

  // 获取屏幕宽
  generateDimension() {
    const { device } = this.props;
    const { width, pixelRatio } = device;
    return Math.round(width * pixelRatio);
  }

  // eslint-disable-next-line class-methods-use-this
  generateItems(props) {
    const { images } = props;
    const pswpItems = images.map((image) => {
      const thumbnailDimension = this.generateDimension();
      const url = `${imageDomain}/${image.user}/${image.collection}/${image.name}.${image.type}`;
      // generate based on Qiniu imageView2 mode 3 API
      // more details see https://developer.qiniu.com/dora/api/basic-processing-images-imageview2
      const largeImageWidth = this.generateDimension();
      const largeImageHeight = Math.round((image.dimension[1] / image.dimension[0]) * largeImageWidth);
      return ({
        _id: image._id,
        msrc: `${url}?imageView2/1/w/${thumbnailDimension}`,
        src: `${url}?imageView2/3/w/${largeImageWidth}`,
        w: largeImageWidth,
        h: largeImageHeight,
      });
    });
    return pswpItems;
  }

  _handleRenderGallery(i) {
    const { showGallery } = this.props;
    if (showGallery && this._loadedItems.includes(i)) {
      this.props.photoSwipeOpen(
        this._pswpItems,
        {
          index: i,
          history: false,
          showHideOpacity: true,
          getThumbBoundsFn: (index) => {
            const thumbnail = this[`thumbnail${index}`];
            const img = thumbnail.getWrappedInstance().image;
            const pageYScroll = window.pageYOffset || document.documentElement.scrollTop;
            const rect = img.getBoundingClientRect();
            return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
          },
        },
      );
    }
  }

  _handleImageLoad(i) {
    if (!this._loadedItems.includes(i)) {
      this._loadedItems.push(i);
    }
  }

  render() {
    const { isEditing, filterType, images } = this.props;
    let filteredImages;
    if (filterType === 'latest') filteredImages = images;
    if (filterType === 'oldest') filteredImages = images.reverse();
    if (filterType === 'popular') filteredImages = images.sort((p, n) => n.liker.length - p.liker.length);
    return (
      <GridLayout>
        {
          filteredImages.map((image, i) => (
            <ConnectedGridImageHolder
              key={image._id}
              isEditing={isEditing}
              image={image}
              total={images.length}
              dimension={this.generateImageDimension()}
              ref={(node) => { this[`thumbnail${i}`] = node; }}
              onImageClick={() => this._handleRenderGallery(i)}
              onImageLoad={() => this._handleImageLoad(i)}
            />
          ))
        }
      </GridLayout>
    );
  }
}

const mapStateToProps = ({ device }) => ({
  device,
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
  photoSwipeOpen,
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(JustifiedGridLayout);

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\IpMessaging\V2\Service\User;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;

/**
 * @property string accountSid
 * @property string serviceSid
 * @property string channelSid
 * @property string userSid
 * @property string memberSid
 * @property string status
 * @property integer lastConsumedMessageIndex
 * @property integer unreadMessagesCount
 * @property array links
 * @property string url
 * @property string notificationLevel
 */
class UserChannelInstance extends InstanceResource {
    /**
     * Initialize the UserChannelInstance
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $serviceSid The unique id of the Service this channel belongs
     *                           to.
     * @param string $userSid The unique id of the User this Channel belongs to.
     * @param string $channelSid The unique id of a Channel.
     * @return \Twilio\Rest\IpMessaging\V2\Service\User\UserChannelInstance
     */
    public function __construct(Version $version, array $payload, $serviceSid, $userSid, $channelSid = null) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = array(
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'serviceSid' => Values::array_get($payload, 'service_sid'),
            'channelSid' => Values::array_get($payload, 'channel_sid'),
            'userSid' => Values::array_get($payload, 'user_sid'),
            'memberSid' => Values::array_get($payload, 'member_sid'),
            'status' => Values::array_get($payload, 'status'),
            'lastConsumedMessageIndex' => Values::array_get($payload, 'last_consumed_message_index'),
            'unreadMessagesCount' => Values::array_get($payload, 'unread_messages_count'),
            'links' => Values::array_get($payload, 'links'),
            'url' => Values::array_get($payload, 'url'),
            'notificationLevel' => Values::array_get($payload, 'notification_level'),
        );

        $this->solution = array(
            'serviceSid' => $serviceSid,
            'userSid' => $userSid,
            'channelSid' => $channelSid ?: $this->properties['channelSid'],
        );
    }

    /**
     * Generate an instance context for the instance, the context is capable of
     * performing various actions.  All instance actions are proxied to the context
     *
     * @return \Twilio\Rest\IpMessaging\V2\Service\User\UserChannelContext Context
     *                                                                     for this
     *                                                                     UserChannelInstance
     */
    protected function proxy() {
        if (!$this->context) {
            $this->context = new UserChannelContext(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['userSid'],
                $this->solution['channelSid']
            );
        }

        return $this->context;
    }

    /**
     * Fetch a UserChannelInstance
     *
     * @return UserChannelInstance Fetched UserChannelInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch() {
        return $this->proxy()->fetch();
    }

    /**
     * Update the UserChannelInstance
     *
     * @param string $notificationLevel Push notification level to be assigned to
     *                                  Channel of the User.
     * @return UserChannelInstance Updated UserChannelInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function update($notificationLevel) {
        return $this->proxy()->update($notificationLevel);
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get($name) {
        if (array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (property_exists($this, '_' . $name)) {
            $method = 'get' . ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.IpMessaging.V2.UserChannelInstance ' . implode(' ', $context) . ']';
    }
}


text:
/*
 * Class MethodEvaluator
 * @author Jeka
 */
package com.intellij.debugger.engine.evaluation.expression;

import com.intellij.Patches;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.JVMName;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.impl.ClassLoadingUtils;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.rt.debugger.DefaultMethodInvoker;
import com.sun.jdi.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MethodEvaluator implements Evaluator {
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.MethodEvaluator");
  private final JVMName myClassName;
  private final JVMName myMethodSignature;
  private final String myMethodName;
  private final Evaluator[] myArgumentEvaluators;
  private final Evaluator myObjectEvaluator;
  private final boolean myCheckDefaultInterfaceMethod;
  private final boolean myMustBeVararg;

  public MethodEvaluator(Evaluator objectEvaluator,
                         JVMName className,
                         String methodName,
                         JVMName signature,
                         Evaluator[] argumentEvaluators) {
    this(objectEvaluator, className, methodName, signature, argumentEvaluators, false, false);
  }

  public MethodEvaluator(Evaluator objectEvaluator,
                         JVMName className,
                         String methodName,
                         JVMName signature,
                         Evaluator[] argumentEvaluators,
                         boolean checkDefaultInterfaceMethod,
                         boolean mustBeVararg) {
    myObjectEvaluator = new DisableGC(objectEvaluator);
    myClassName = className;
    myMethodName = methodName;
    myMethodSignature = signature;
    myArgumentEvaluators = argumentEvaluators;
    myCheckDefaultInterfaceMethod = checkDefaultInterfaceMethod;
    myMustBeVararg = mustBeVararg;
  }

  @Override
  public Modifier getModifier() {
    return null;
  }

  @Override
  public Object evaluate(EvaluationContextImpl context) throws EvaluateException {
    if(!context.getDebugProcess().isAttached()) return null;
    DebugProcessImpl debugProcess = context.getDebugProcess();

    final boolean requiresSuperObject =
      myObjectEvaluator instanceof SuperEvaluator ||
      (myObjectEvaluator instanceof DisableGC && ((DisableGC)myObjectEvaluator).getDelegate() instanceof SuperEvaluator);

    final Object object = myObjectEvaluator.evaluate(context);
    if (LOG.isDebugEnabled()) {
      LOG.debug("MethodEvaluator: object = " + object);
    }
    if(object == null) {
      throw EvaluateExceptionUtil.createEvaluateException(new NullPointerException());
    }
    if (!(object instanceof ObjectReference || object instanceof ClassType)) {
      throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.evaluating.method", myMethodName));
    }
    List args = new ArrayList(myArgumentEvaluators.length);
    for (Evaluator evaluator : myArgumentEvaluators) {
      args.add(evaluator.evaluate(context));
    }
    try {
      ReferenceType referenceType = null;

      if(object instanceof ObjectReference) {
        // it seems that if we have an object of the class, the class must be ready, so no need to use findClass here
        referenceType = ((ObjectReference)object).referenceType();
      }
      else if(object instanceof ClassType) {
        final ClassType qualifierType = (ClassType)object;
        referenceType = debugProcess.findClass(context, qualifierType.name(), context.getClassLoader());
      }
      else {
        final String className = myClassName != null? myClassName.getName(debugProcess) : null;
        if (className != null) {
          referenceType = debugProcess.findClass(context, className, context.getClassLoader());
        }
      }

      if (referenceType == null) {
        throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(
          DebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", myMethodName))
        );
      }
      final String signature = myMethodSignature != null ? myMethodSignature.getName(debugProcess) : null;
      final String methodName = DebuggerUtilsEx.methodName(referenceType.name(), myMethodName, signature);
      if (object instanceof ClassType) {
        if(referenceType instanceof ClassType) {
          Method jdiMethod;
          if(myMethodSignature != null) {
            jdiMethod = ((ClassType)referenceType).concreteMethodByName(myMethodName, myMethodSignature.getName(debugProcess));
          }
          else {
            List list = referenceType.methodsByName(myMethodName);
            jdiMethod = (Method)(list.size() > 0 ? list.get(0) : null);
          }
          if (jdiMethod != null && jdiMethod.isStatic()) {
            return debugProcess.invokeMethod(context, (ClassType)referenceType, jdiMethod, args);
          }
        }
        throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.no.static.method", methodName));
      }
      // object should be an ObjectReference
      final ObjectReference objRef = (ObjectReference)object;
      ReferenceType _refType = referenceType;
      if (requiresSuperObject && (referenceType instanceof ClassType)) {
        _refType = ((ClassType)referenceType).superclass();
      }
      Method jdiMethod = DebuggerUtils.findMethod(_refType, myMethodName, signature);
      if (signature == null) {
        // we know nothing about expected method's signature, so trying to match my method name and parameter count
        // dummy matching, may be improved with types matching later
        // IMPORTANT! using argumentTypeNames() instead of argumentTypes() to avoid type resolution inside JDI, which may be time-consuming
        if (jdiMethod == null || jdiMethod.argumentTypeNames().size() != args.size()) {
          for (Method method : _refType.methodsByName(myMethodName)) {
            if (method.argumentTypeNames().size() == args.size()) {
              jdiMethod = method;
              break;
            }
          }
        }
      }
      else if (myMustBeVararg && jdiMethod != null && !jdiMethod.isVarArgs() && jdiMethod.isBridge()) {
        // see IDEA-129869, avoid bridge methods for varargs
        int retTypePos = signature.lastIndexOf(")");
        if (retTypePos >= 0) {
          String signatureNoRetType = signature.substring(0, retTypePos + 1);
          for (Method method : _refType.visibleMethods()) {
            if (method.name().equals(myMethodName) && method.signature().startsWith(signatureNoRetType) && !method.isBridge() && !method.isAbstract()) {
              jdiMethod = method;
              break;
            }
          }
        }
      }
      if (jdiMethod == null) {
        throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.no.instance.method", methodName));
      }
      if (requiresSuperObject) {
        return debugProcess.invokeInstanceMethod(context, objRef, jdiMethod, args, ObjectReference.INVOKE_NONVIRTUAL);
      }
      // fix for default methods in interfaces, see IDEA-124066
      if (Patches.JDK_BUG_ID_8042123 && myCheckDefaultInterfaceMethod && jdiMethod.declaringType() instanceof InterfaceType) {
        try {
          return invokeDefaultMethod(debugProcess, context, objRef, myMethodName);
        } catch (EvaluateException e) {
          LOG.info(e);
        }
      }
      return debugProcess.invokeMethod(context, objRef, jdiMethod, args);
    }
    catch (Exception e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(e);
      }
      throw EvaluateExceptionUtil.createEvaluateException(e);
    }
  }

  // only methods without arguments for now
  private static Value invokeDefaultMethod(DebugProcess debugProcess, EvaluationContext evaluationContext,
                                           Value obj, String name)
    throws EvaluateException {
    ClassType invokerClass = ClassLoadingUtils.getHelperClass(DefaultMethodInvoker.class.getName(), evaluationContext, debugProcess);

    if (invokerClass != null) {
      List<Method> methods = invokerClass.methodsByName("invoke");
      if (!methods.isEmpty()) {
        return debugProcess.invokeMethod(evaluationContext, invokerClass, methods.get(0),
               Arrays.asList(obj, ((VirtualMachineProxyImpl)debugProcess.getVirtualMachineProxy()).mirrorOf(name)));
      }
    }
    return null;
  }

  @Override
  public String toString() {
    return "call " + myMethodName;
  }
}


text:
package marshal

import (
	"time"

	. "gopkg.in/check.v1"

	"github.com/zorkian/kafka/kafkatest"
)

var _ = Suite(&MarshalSuite{})

type MarshalSuite struct {
	s *kafkatest.Server
	m *Marshaler
}

func (s *MarshalSuite) SetUpTest(c *C) {
	ResetTestLogger(c)

	s.s = StartServer()

	var err error
	s.m, err = NewMarshaler("cl", "gr", []string{s.s.Addr()})
	if err != nil {
		c.Errorf("New Marshaler failed: %s", err)
	}
}

func (s *MarshalSuite) TearDownTest(c *C) {
	s.m.Terminate()
	s.s.Close()
}

func MakeTopic(srv *kafkatest.Server, topic string, numPartitions int) {
	for i := 0; i < numPartitions; i++ {
		srv.AddMessages(topic, int32(i))
	}
}

func StartServer() *kafkatest.Server {
	srv := kafkatest.NewServer()
	srv.MustSpawn()
	MakeTopic(srv, MarshalTopic, 4)
	MakeTopic(srv, "test1", 1)
	MakeTopic(srv, "test2", 2)
	MakeTopic(srv, "test3", 3)
	return srv
}

func (s *MarshalSuite) TestNewMarshaler(c *C) {
	// Test that Marshaler starts up and learns about the topics.
	c.Assert(s.m.Partitions(MarshalTopic), Equals, 4)
	c.Assert(s.m.Partitions("test1"), Equals, 1)
	c.Assert(s.m.Partitions("test2"), Equals, 2)
	c.Assert(s.m.Partitions("test3"), Equals, 3)
	c.Assert(s.m.Partitions("unknown"), Equals, 0)

	// If our hash algorithm changes, these values will have to change. This tests the low
	// level hash function.
	c.Assert(s.m.cluster.getClaimPartition("test1"), Equals, 2)
	c.Assert(s.m.cluster.getClaimPartition("test2"), Equals, 1)
	c.Assert(s.m.cluster.getClaimPartition("test3"), Equals, 2)
	c.Assert(s.m.cluster.getClaimPartition("unknown"), Equals, 1)
	c.Assert(s.m.cluster.getClaimPartition("unknown"), Equals, 1) // Twice on purpose.
}

// This is a full integration test of claiming including writing to Kafka via the marshaler
// and waiting for responses
func (s *MarshalSuite) TestClaimPartitionIntegration(c *C) {
	resp := make(chan bool)
	go func() {
		resp <- s.m.ClaimPartition("test1", 0) // true
		resp <- s.m.ClaimPartition("test1", 0) // true (no-op)
		s.m.lock.Lock()
		s.m.clientID = "cl-other"
		s.m.lock.Unlock()
		resp <- s.m.ClaimPartition("test1", 0) // false (collission)
		resp <- s.m.ClaimPartition("test1", 1) // true (new client)
	}()

	select {
	case out := <-resp:
		c.Assert(out, Equals, true)
	case <-time.After(5 * time.Second):
		c.Error("Timed out claiming partition")
	}

	select {
	case out := <-resp:
		c.Assert(out, Equals, true)
	case <-time.After(5 * time.Second):
		c.Error("Timed out claiming partition")
	}

	select {
	case out := <-resp:
		c.Assert(out, Equals, false)
	case <-time.After(5 * time.Second):
		c.Error("Timed out claiming partition")
	}

	select {
	case out := <-resp:
		c.Assert(out, Equals, true)
	case <-time.After(5 * time.Second):
		c.Error("Timed out claiming partition")
	}
}

// This is a full integration test of a claim, heartbeat, and release cycle
func (s *MarshalSuite) TestPartitionLifecycleIntegration(c *C) {
	// Claim partition (this is synchronous, will only return when)
	// it has succeeded
	c.Assert(s.m.ClaimPartition("test1", 0), Equals, true)
	steps, err := s.m.cluster.waitForRsteps(1)
	c.Assert(err, IsNil)
	c.Assert(steps, Equals, 1)

	// Ensure we have claimed it
	cl := s.m.GetPartitionClaim("test1", 0)
	if cl.LastHeartbeat <= 0 || cl.ClientID != "cl" || cl.GroupID != "gr" {
		c.Errorf("PartitionClaim values unexpected %+v", cl)
	}
	if cl.CurrentOffset != 0 {
		c.Error("CurrentOffset is not 0")
	}

	// Now heartbeat on it to update the last offset
	c.Assert(s.m.Heartbeat("test1", 0, 10), IsNil)
	steps, err = s.m.cluster.waitForRsteps(2)
	c.Assert(err, IsNil)
	c.Assert(steps, Equals, 2)

	// Get the claim again, validate it's updated
	cl = s.m.GetPartitionClaim("test1", 0)
	if cl.LastHeartbeat <= 0 || cl.ClientID != "cl" || cl.GroupID != "gr" {
		c.Errorf("PartitionClaim values unexpected %+v", cl)
	}
	if cl.CurrentOffset != 10 {
		c.Error("CurrentOffset is not 10")
	}

	// Release
	c.Assert(s.m.ReleasePartition("test1", 0, 20), IsNil)
	steps, err = s.m.cluster.waitForRsteps(3)
	c.Assert(err, IsNil)
	c.Assert(steps, Equals, 3)

	// Get the claim again, validate it's empty
	cl = s.m.GetPartitionClaim("test1", 0)
	if cl.LastHeartbeat > 0 || cl.ClientID != "" || cl.GroupID != "" {
		c.Errorf("PartitionClaim values unexpected %+v", cl)
	}
	if cl.CurrentOffset != 0 {
		c.Error("CurrentOffset is not 20")
	}

	// Get the last known claim data
	cl = s.m.GetLastPartitionClaim("test1", 0)
	if cl.LastHeartbeat > 0 || cl.ClientID != "cl" || cl.GroupID != "gr" {
		c.Errorf("PartitionClaim values unexpected %+v", cl)
	}
	if cl.CurrentOffset != 20 {
		c.Error("CurrentOffset is not 20")
	}
}

func (s *MarshalSuite) TestTerminatedMarshalRemovesSelfFromCluster(c *C) {
	// Test that terminated Marshalers remove their cluster's reference to it.
	c.Assert(s.m.cluster.marshalers, DeepEquals, []*Marshaler{s.m})
	s.m.Terminate()
	c.Assert(s.m.cluster.marshalers, DeepEquals, []*Marshaler{})
}


text:
require('./angular-locale_agq-cm');
module.exports = 'ngLocale';


text:
package ws.rocket.config.test.data.filter;

/**
 * A sample filter implementation.
 *
 * @author Martti Tamm
 */
public final class Phase1Filter implements TestFilter {

  @Override
  public String doFilter(String src) {
    return src;
  }

}


text:
const test = require('ava')
const path = require('path')

const IntTypes = require(path.resolve(__dirname, '..', 'dist', 'IntTypes.js'))
const PixelTypes = require(path.resolve(__dirname, '..', 'dist', 'PixelTypes.js'))
const readImageLocalFileSync = require(path.resolve(__dirname, '..', 'dist', 'readImageLocalFileSync.js'))

const testFilePath = path.resolve(__dirname, '..', 'build', 'ExternalData', 'test', 'Input', 'cthead1.png')

test('readImageLocalFile reads a file path given on the local filesystem', (t) => {
  const image = readImageLocalFileSync(testFilePath)
  t.is(image.imageType.dimension, 2)
  t.is(image.imageType.componentType, IntTypes.UInt8)
  t.is(image.imageType.pixelType, PixelTypes.RGB)
  t.is(image.imageType.components, 3)
  t.is(image.origin[0], 0.0)
  t.is(image.origin[1], 0.0)
  t.is(image.spacing[0], 1.0)
  t.is(image.spacing[1], 1.0)
  t.is(image.direction.getElement(0, 0), 1.0)
  t.is(image.direction.getElement(0, 1), 0.0)
  t.is(image.direction.getElement(1, 0), 0.0)
  t.is(image.direction.getElement(1, 1), 1.0)
  t.is(image.size[0], 256)
  t.is(image.size[1], 256)
  t.is(image.data.length, 196608)
})


text:
module Serverspec
  module Type
    class Ipfilter < Base
      def has_rule?(rule)
        backend.check_ipfilter_rule(nil, rule)
      end

      def to_s
        'ipfilter'
      end
    end
  end
end


text:
<?php
/**
 * Created by Philippe Le Van.
 * Date: 12/07/13
 */

namespace Tbbc\MoneyBundle\Pair\RatioProvider;

use Money\UnknownCurrencyException;
use Money\Currency;
use Tbbc\MoneyBundle\MoneyException;
use Tbbc\MoneyBundle\Pair\RatioProviderInterface;

class RateExchangeRatioProvider
    implements RatioProviderInterface
{
    /**
     * @inheritdoc
     */
    public function fetchRatio($referenceCurrencyCode, $currencyCode)
    {
        try {
            new Currency($currencyCode);
            new Currency($referenceCurrencyCode);
        } catch (UnknownCurrencyException $e) {
            throw new MoneyException("one of your currency code doesn't exist");
        }

        $responseString = file_get_contents("http://rate-exchange.appspot.com/currency?from=$referenceCurrencyCode&to=$currencyCode");
        if (!$responseString) {
            throw new MoneyException("No response from rate-exchange API");
        }
        $response = json_decode($responseString, true);
        if (!$response) {
            throw new MoneyException("Response from rate-exchange API is not a valid JSON");
        }
        if (!array_key_exists("rate", $response)) {
            throw new MoneyException("No rate defined in the response");
        }
        $ratio = floatval($response["rate"]);
        if ($ratio <= 0) {
            throw new MoneyException("invalid ratio");
        }
        return $ratio;
    }

}


text:
app.create('message', {
    preShowMsg: function(id, isSentMessage){
        c.log('app.message.preShowMsg', id);

        var attr = isSentMessage ? 'data-ack='+id : 'data-id='+id
            , $row = ui.$pg.find('tbody tr['+attr+']')
            , colCount = $row.find('td').length;

        $row.after(ui.tpl('message', {
            id: id,
            colCount: colCount
        }));
    },

    showMsg: function(msg, isSentMessage, renderHtml){
        c.log('app.message.showMsg', msg);

        var attr = isSentMessage ? 'data-ack='+msg.ackData : 'data-id='+msg.msgid
            , $row =  ui.$pg.find('tbody tr['+attr+']')
            , $msg = $row.next('.msg')
            , $content = $msg.find('.content')
            , $messageHtml
            , $message;

        $messageHtml = $(ui.tpl('messageContent', {
            msg: msg
            , isSentMessage: isSentMessage
            , renderHtml: renderHtml
        }));

        $message = $messageHtml.find('.message');
        $message.html(this.parseMessage($message.html(), renderHtml));

        $content.html($messageHtml);
        $content.removeClass('loading');

        //hide maximize button if not needed
        if ( $message.prop('scrollHeight') <= 325 ) { //max-height of .minimize class
            $content.find('.minimize').addClass('hide');
        }

        $row.data('isopen', true);
        $row.removeClass('unread');
    },

    sanitize: function(html){
        function stripTag(html, tag){
            var div, els, i;

            div = document.createElement('div');
            div.innerHTML = html;
            els = div.getElementsByTagName(tag);
            i = els.length;

            while (i--) {
                els[i].parentNode.removeChild(els[i]);
            }

            return div.innerHTML;
        }

        function trimAttributes(node, allowedAttrs) {
            $.each(node.attributes, function() {
                var attrName = this.name;

                if ($.inArray(attrName, allowedAttrs) == -1) {
                    $(node).removeAttr(attrName)
                }
            });
        }

        function clean(html, whitelist) {
            var tags = {font: ['color'], b: [], i: [], img: ['src'], ol: [], ul: [], li: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], code: [], center: [], div: [], blockquote: [], pre: [], table: ['border', 'cellpadding', 'cellspacing'], caption: [], tr: [], th: ['colspan', 'rowspan'], td: ['colspan', 'rowspan'], em: [], strong: [], sub: [], sup: [], p: [], br: [], audio: ['src', 'controls'], video: ['src', 'controls'], source: ['type', 'src'] };

            //<audio src="audio.mp3" controls></audio>

            whitelist = _.extend(tags, whitelist);

            var $el = $('
'+html+'
');

            $el.find('*').each(function() {
                var allowedAttrs = whitelist[this.nodeName.toLowerCase()];
                if(!allowedAttrs) {
                    $(this).remove();
                } else {
                    trimAttributes(this, allowedAttrs);
                }
            });

            return $el.html();
        }

        html = stripTag(html, 'script');
        html = clean(html);

        return html;
    },

    parseMessage: function(html, renderHtml){
        var URI = require('URIjs')
            , settings = ui.settings();

        //!renderHtml is already escaped by hbs and considered safe
        if ( renderHtml ) {
            html = this.sanitize(html);
        }

        html = URI.withinString(html, function(url){
            var label = url
                , proxy_url = false;

            //data urls are very long and can be ignored.
            if ( /^data:/.test(url) ) {
                return !renderHtml ? url.substring(0, 500)+'...' : url;
            }

            //make a valid url if we have a domain only
            if ( !/^\w+:/.test(url) ) {
                url = 'http://'+url;
            }

            //make the proxy url if we are using one
            if ( settings.proxy_urls ) {
                if ( settings.proxy_urls === 'ixquick' ) {
                    proxy_url = 'https://ixquick.com/?query='+url;
                } else if ( settings.proxy_urls === 'anonymouse' ) {
                    proxy_url = 'http://anonymouse.org/cgi-bin/anon-www.cgi/'+url;
                } else if ( settings.proxy_urls === 'webproxynet' ) {
                    proxy_url = 'http://webproxy.net/view?q='+url;
                }
            }

            return (
                ''+label+'' +

                    (
                        proxy_url ?
                            '[proxy]'
                            : ''
                    )
            );
        });

        //Bitmessage addressses
        html = html.replace(
            /(BM-[123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ]{32,34})/g,
            '$1'
        );

        return html;
    },

    hideMsg: function(id, isSentMessage){
        c.log('app.message.hideMsg', id);

        var attr = isSentMessage ? 'data-ack='+id : 'data-id='+id
            , $row = ui.$pg.find('tbody tr['+attr+']');

        $row.data('isopen', false);
        $row.next('.msg').remove();
    },

    readMsg: function ($table, isSentMessage) {
        c.log('app.message.readMessage: isSentMessage', isSentMessage);

        $table.on('click.message', 'tr:not(.msg) .subject', function (e) {
            e.preventDefault();

            var $subject = $(e.currentTarget)
                , $row = $subject.parents('tr')
                , isOpen = !!$row.data('isopen')
                , id = isSentMessage ? $row.attr('data-ack') : $row.attr('data-id');

            c.log('app.message.readMsg', id);

            if ( isOpen ) {
                this.hideMsg(id, isSentMessage);
                return;
            }

            this.preShowMsg(id, isSentMessage);

            if ( isSentMessage ) {
                api.getSentMessageByAck(id, function(msg){
                    this.showMsg(msg, isSentMessage);
                }.bind(this));
            } else {
                api.getMessage(id, function(msg){
                    this.showMsg(msg, isSentMessage);
                }.bind(this), true); //mark as read
            }
        }.bind(this));
    },

    renderHtml: function(id, isSentMessage){
        c.log('app.message.renderHtml', id);

        var renderHtml = true;

        this.hideMsg(id, isSentMessage);
        this.preShowMsg(id, isSentMessage);

        if ( isSentMessage ) {
            api.getSentMessageByAck(id, function(msg){
                this.showMsg(msg, isSentMessage, renderHtml);
            }.bind(this));
        } else {
            api.getMessage(id, function(msg){
                this.showMsg(msg, isSentMessage, renderHtml);
            }.bind(this));
        }
    },

    reverseThread: function(id, isSentMessage){
        var $msg = ui.$pg.find('tr[data-msgid='+id+'].msg .message')
            , delim = '\n\n------------------------------------------------------\n'
            , msg = $msg.html().split(delim).reverse().join(delim);

        $msg.html(msg);
    },

    maximize: function($row){
        var $nav = $row.find('.message-container nav.icons');

        $row.find('.message').removeClass('minimize');
        $nav.find('.maximize').addClass('hide');
        $nav.find('.minimize').removeClass('hide');
    },

    minimize: function($row){
        var $nav = $row.find('.message-container nav.icons');

        $row.find('.message').addClass('minimize');
        $nav.find('.maximize').removeClass('hide');
        $nav.find('.minimize').addClass('hide');
    },

    nextMsg: function($row, id, isSentMessage){
        var direction = 'next';

        this.navigateMsg($row, id, isSentMessage, direction);
    },

    prevMsg: function($row, id, isSentMessage){
        var direction = 'prev';

        this.navigateMsg($row, id, isSentMessage, direction);
    },

    //navigate to previous and next messages
    navigateMsg: function($row, id, isSentMessage, direction){
        var $toOpen = direction == 'prev' ? $row.prev().prev() : $row.next();

        if ( !$toOpen.length ) {
            ui.err('No more messages');
            return;
        }

        app.message.hideMsg(id, isSentMessage);
        $toOpen.find('.subject').click();

        $('html, body').animate({
            scrollTop: $toOpen.offset().top
        }, 400, 'easeOutQuad');
    },

    destroy: function(){
        c.log('app.message.destroy');

        $(document).add('*').off('.message');
    }
});


text:
module Kramdown::Converter::SyntaxHighlighter

  # Uses Coderay to highlight code blocks and code spans.
  module Coderay

    begin
      require 'coderay'

      # Highlighting via coderay is available if this constant is +true+.
      AVAILABLE = true
    rescue LoadError
      AVAILABLE = false  # :nodoc:
    end

    def self.call(converter, text, lang, type, _unused_opts)
      return nil unless converter.options[:enable_coderay]

      if type == :span && lang
        ::CodeRay.scan(text, lang.to_sym).html(options(converter, :span)).chomp
      elsif type == :block && (lang || options(converter, :default_lang))
        lang = (lang || options(converter, :default_lang)).to_s.gsub(/-/, '_').to_sym
        ::CodeRay.scan(text, lang).html(options(converter, :block)).chomp << "\n"
      else
        nil
      end
    rescue
      converter.warning("There was an error using CodeRay: #{$!.message}")
      nil
    end

    def self.options(converter, type)
      prepare_options(converter)
      converter.data[:syntax_highlighter_coderay][type]
    end

    def self.prepare_options(converter)
      return if converter.data.key?(:syntax_highlighter_coderay)

      cache = converter.data[:syntax_highlighter_coderay] = {}

      opts = converter.options[:syntax_highlighter_opts].dup
      span_opts = (opts.delete(:span) || {}).dup
      block_opts = (opts.delete(:block) || {}).dup
      [span_opts, block_opts].each do |hash|
        hash.keys.each do |k|
          hash[k.kind_of?(String) ? Kramdown::Options.str_to_sym(k) : k] = hash.delete(k)
        end
      end

      cache[:default_lang] = converter.options[:coderay_default_lang] || opts.delete(:default_lang)
      cache[:span] = {
        :css => converter.options[:coderay_css]
      }.update(opts).update(span_opts).update(:wrap => :span)
      cache[:block] = {
        :wrap => converter.options[:coderay_wrap],
        :line_numbers => converter.options[:coderay_line_numbers],
        :line_number_start => converter.options[:coderay_line_number_start],
        :tab_width => converter.options[:coderay_tab_width],
        :bold_every => converter.options[:coderay_bold_every],
        :css => converter.options[:coderay_css]
      }.update(opts).update(block_opts)

      [:css, :wrap, :line_numbers].each do |key|
        [:block, :span].each do |type|
          cache[type][key] = cache[type][key].to_sym if cache[type][key].kind_of?(String)
        end
      end
    end

  end

end


text:
void Animate(Ctrl& c, const Rect& target, int type = -1);
void Animate(Ctrl& c, int x, int y, int cx, int cy, int type = -1);

bool CtrlLibDisplayError(const Value& ev);

bool EditText(String& s, const char *title, const char *label, int (*filter)(int), int maxlen = 0);
bool EditText(String& s, const char *title, const char *label, int maxlen = 0);

bool EditText(WString& s, const char *title, const char *label, int (*filter)(int), int maxlen = 0);
bool EditText(WString& s, const char *title, const char *label, int maxlen = 0);

bool EditNumber(int& n, const char *title, const char *label, int min = INT_MIN, int max = INT_MAX, bool notnull = false);
bool EditNumber(double& n, const char *title, const char *label, double min = -DBL_MAX, double max = DBL_MAX, bool notnull = false);

void Show2(Ctrl& ctrl1, Ctrl& ctrl, bool show = true);
void Hide2(Ctrl& ctrl1, Ctrl& ctrl);

#ifndef PLATFORM_WINCE //TODO?
void UpdateFile(const char *filename);
void SelfUpdate();
bool SelfUpdateSelf();
#endif

void WindowsList();
void WindowsMenu(Bar& bar);

class DelayCallback : public Pte<DelayCallback> {
	Callback target;
	int      delay;

public:
	void     Invoke();
	void     operator<<=(Callback x)  { target = x; }
	void     SetDelay(int ms)         { delay = ms; }
	Callback Get()                    { return callback(this, &DelayCallback::Invoke); }
	Callback operator~()              { return Get(); }
	operator Callback()               { return Get(); }

	DelayCallback()                   { delay = 2000; }
	~DelayCallback()                  { KillTimeCallback(this); }
};

#ifdef GUI_WIN
struct Win32PrintDlg_;
#endif

#ifndef PLATFORM_WINCE

#if defined(GUI_WIN) || defined(PLATFORM_X11)

class PrinterJob {
#ifdef GUI_WIN
	One<Win32PrintDlg_> pdlg;
#endif
#ifdef PLATFORM_X11
	Size                pgsz;
	Size                GetDefaultPageSize(String *name = NULL);
#endif
	One<Draw>           draw;
	Vector<int>         page;
	int                 from, to, current;
	bool                landscape;
	String              name;
	String              options;
	bool                Execute0(bool dodlg);

public:
	Draw&               GetDraw();
	operator            Draw&()                         { return GetDraw(); }
	const Vector<int>&  GetPages() const                { return page; }
	int                 operator[](int i) const         { return page[i]; }
	int                 GetPageCount() const            { return page.GetCount(); }

	bool                Execute();

	PrinterJob& Landscape(bool b = true)                { landscape = b; return *this; }
	PrinterJob& MinMaxPage(int minpage, int maxpage);
	PrinterJob& PageCount(int n)                        { return MinMaxPage(0, n - 1); }
	PrinterJob& CurrentPage(int currentpage);
	PrinterJob& Name(const char *_name)                 { name = _name; return *this; }

	PrinterJob(const char *name = NULL);
	~PrinterJob();
};

#endif

#endif

#ifdef GUI_X11

class TrayIcon : Ctrl {
	virtual bool HookProc(XEvent *event);
	virtual void Paint(Draw& draw);
	virtual void LeftDown(Point p, dword keyflags);
	virtual void LeftUp(Point p, dword keyflags);
	virtual void LeftDouble(Point p, dword keyflags);
	virtual void RightDown(Point p, dword keyflags);

private:
	void AddToTray();

	Window traywin;
	Image  icon;
	void DoMenu(Bar& bar);
	void Call(int code, unsigned long d1, unsigned long d2, unsigned long d3);
	void Message(int type, const char *title, const char *text, int timeout);

public:
	virtual void    LeftDown();
	virtual void    LeftUp();
	virtual void    LeftDouble();
	virtual void    Menu(Bar& bar);
	virtual void    BalloonLeftDown();
	virtual void    BalloonShow();
	virtual void    BalloonHide();
	virtual void    BalloonTimeout();

	Callback        WhenLeftDown;
	Callback        WhenLeftUp;
	Callback        WhenLeftDouble;
	Callback1<Bar&> WhenBar;
	Callback        WhenBalloonLeftDown;
	Callback        WhenBalloonShow;
	Callback        WhenBalloonHide;
	Callback        WhenBalloonTimeout;

	void            Break()                                { EndLoop(0); }
	void            Run()                                  { EventLoop(this); }

	void            Show(bool b = true);
	void            Hide()                                 { Show(false); }
	bool            IsVisible() const                      { return true; }

	void            Info(const char *title, const char *text, int timeout = 10)    { Message(1, title, text, timeout); }
	void            Warning(const char *title, const char *text, int timeout = 10) { Message(2, title, text, timeout); }
	void            Error(const char *title, const char *text, int timeout = 10)   { Message(3, title, text, timeout); }

	TrayIcon&  Icon(const Image &img)                      { icon = img; Refresh(); return *this; }
	TrayIcon&  Tip(const char *text)                       { Ctrl::Tip(text); return *this; }

	typedef TrayIcon CLASSNAME;

	TrayIcon();
};

#endif

#ifdef GUI_GTK

class TrayIcon {
private:
	GtkStatusIcon *tray_icon;
	String         tooltip;
	ImageGdk       image;
	bool           active;

	static gboolean DoButtonPress(GtkStatusIcon *, GdkEventButton *e, gpointer user_data);
	static gboolean DoButtonRelease(GtkStatusIcon *, GdkEventButton *e, gpointer user_data);
	static void     PopupMenu(GtkStatusIcon *, guint, guint32, gpointer user_data);
	static void     DoActivate(GtkStatusIcon *, gpointer user_data);

	void DoMenu(Bar& bar);
	void ExecuteMenu();

	void Sync();

	void Message(int type, const char *title, const char *text, int timeout);

public:
	virtual void    Menu(Bar& bar);
	virtual void    LeftDown();
	virtual void    LeftUp();
	virtual void    LeftDouble();

	Callback        WhenLeftDown;
	Callback        WhenLeftUp;
	Callback        WhenLeftDouble;
	Callback1<Bar&> WhenBar;

	void            Break();
	void            Run();

	void            Show(bool b = true);
	void            Hide()                                 { Show(false); }
	bool            IsVisible() const;

	// Not implemented by GTK:
	void            Info(const char *title, const char *text, int timeout = 10)    { Message(1, title, text, timeout); }
	void            Warning(const char *title, const char *text, int timeout = 10) { Message(2, title, text, timeout); }
	void            Error(const char *title, const char *text, int timeout = 10)   { Message(3, title, text, timeout); }

	TrayIcon&  Icon(const Image &img)                      { if(image.Set(img)) Sync(); return *this; }
	TrayIcon&  Tip(const char *text)                       { if(tooltip != text) tooltip = text; Sync(); return *this; }

	typedef TrayIcon CLASSNAME;

	TrayIcon();
	~TrayIcon();
};

#endif

#ifdef GUI_WIN
#ifndef PLATFORM_WINCE

class TrayIcon : private Ctrl {
	struct NotifyIconOld {
		dword sz;
		HWND  hwnd;
		dword id;
		dword flags;
		dword message;
		HICON icon;
		char  tip[64];
	};
	struct NotifyIconNew {
		dword sz;
		HWND  hwnd;
		dword id;
		dword flags;
		dword message;
		HICON icon;
		char  tip[128];

		dword state;
		dword statemask;
		char  info[256];
		dword timeout;
		char  title[64];
		dword infoflags;
	};

	Image          icon;
	bool           visible;
	String         tip;
	NotifyIconNew  nid;
	HWND           hwnd;

	virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
	void Notify(dword msg);
	void DoMenu(Bar& bar);
	void Message(int type, const char *title, const char *text, int timeout = 10);

public:
	virtual void    Menu(Bar& bar);
	virtual void    LeftDown();
	virtual void    LeftUp();
	virtual void    LeftDouble();
	virtual void    BalloonLeftDown();
	virtual void    BalloonShow();
	virtual void    BalloonHide();
	virtual void    BalloonTimeout();

	Callback        WhenLeftDown;
	Callback        WhenLeftUp;
	Callback        WhenLeftDouble;
	Callback1<Bar&> WhenBar;
	Callback        WhenBalloonLeftDown;
	Callback        WhenBalloonShow;
	Callback        WhenBalloonHide;
	Callback        WhenBalloonTimeout;

	void            Show(bool b = true);
	void            Hide()                                 { Show(false); }
	bool            IsVisible() const                      { return visible; }
	void            Break()                                { EndLoop(0); }
	void            Run()                                  { EventLoop(this); }

	void            Info(const char *title, const char *text, int timeout = 10)    { Message(1, title, text, timeout); }
	void            Warning(const char *title, const char *text, int timeout = 10) { Message(2, title, text, timeout); }
	void            Error(const char *title, const char *text, int timeout = 10)   { Message(3, title, text, timeout); }

	TrayIcon&  Icon(const Image &img);
	TrayIcon&  Tip(const char *text);

	typedef TrayIcon CLASSNAME;

	TrayIcon();
	~TrayIcon();
};

class FileSelector {
protected:
	struct FileType : Moveable<FileType> {
		String name;
		String ext;
	};

	Vector<FileType> type;

	int    activetype;
	String activedir;
	String defext;
	bool   rdonly;
	bool   multi;
	bool   readonly;
	bool   asking;

	Vector<String> filename;

public:
	void Serialize(Stream& s);

	void New()                                   { filename.Clear(); }
	bool IsNew() const                           { return filename.IsEmpty(); }
	bool Execute(bool open, const char *title = NULL);
	bool ExecuteOpen(const char *title = NULL)   { return Execute(true, title); }
	bool ExecuteSaveAs(const char *title = NULL) { return Execute(false, title); }

	String Get() const;
	void  Set(const String& s)                   { filename.At(0) = s; }

	operator String() const                      { return Get(); }
	void operator=(const String& s)              { Set(s); }

	String operator~() const                     { return Get(); }
	void operator<<=(const String& s)            { Set(s); }

	int   GetCount() const                       { return filename.GetCount(); }
	const String& operator[](int i) const        { return filename[i]; }

	bool   GetReadOnly() const                   { return readonly; }
	String GetActiveDir() const                  { return activedir; }

	FileSelector& Type(const char *name, const char *ext);
	FileSelector& AllFilesType();
	FileSelector& ActiveDir(const String& dir)   { activedir = dir; return *this; }
	FileSelector& ActiveType(int i)              { activetype = i; return *this;  }
	FileSelector& DefaultExt(const char *ext)    { defext = ext; return *this; }
	FileSelector& Multi(bool b = true)           { multi = b; return *this; }
	FileSelector& ReadOnlyOption(bool b = true)  { rdonly = b; return *this; }
	FileSelector& Asking(bool b = true)          { asking = b; return *this; }
	FileSelector& NoAsking()                     { return Asking(false); }

	FileSelector();
};

#endif
#endif

#ifdef GUI_X11
typedef FileSel FileSelector;
#endif

#ifdef GUI_GTK
class FileSelector {
	Vector<String> path;
	Vector< Tuple2<String, String> > type;

	String ipath;
	bool   confirm;
	bool   multi;
	bool   hidden;
	int    activetype;

public:
	bool   Execute(bool open, const char *title = NULL);
	bool   ExecuteOpen(const char *title = NULL)          { return Execute(true, title); }
	bool   ExecuteSaveAs(const char *title = NULL)        { return Execute(false, title); }

	String Get() const                                    { return path.GetCount() ? path[0] : String::GetVoid(); }
	operator String() const                               { return Get(); }
	String operator~() const                              { return Get(); }

	void   Set(const String& s)                           { ipath = s; }
	void   operator=(const String& s)                     { Set(s); }
	void   operator<<=(const String& s)                   { Set(s); }

	int    GetCount() const                               { return path.GetCount(); }
	const  String& operator[](int i) const                { return path[i]; }

	FileSelector& Type(const char *name, const char *ext) { type.Add(MakeTuple(String(name), String(ext))); return *this; }
	FileSelector& AllFilesType();
	FileSelector& Asking(bool b = true)                   { confirm = b; return *this; }
	FileSelector& NoAsking()                              { return Asking(false); }
	FileSelector& Multi(bool b = true)                    { multi = b; return *this; }
	FileSelector& ShowHidden(bool b = true)               { hidden = b; return *this; }
	FileSelector& ActiveDir(const String& dir)            { ipath = dir; return *this; }
	FileSelector& ActiveType(int i)                       { activetype = i; return *this; }

	FileSelector();
};
#endif

class CtrlRetriever {
public:
	struct Item {
		virtual void Retrieve() = 0;
		virtual ~Item() {}
	};

private:
	struct CtrlItem0 : Item {
		Ctrl  *ctrl;
	};

	template <class T>
	struct CtrlItem : CtrlItem0 {
		T     *value;

		virtual void Retrieve()  { *value = ~*ctrl; }
		virtual ~CtrlItem() {}
	};

	Array<Item> item;

public:
	void Put(Item *newitem)                       { item.Add(newitem); }

	template <class T>
	void Put(Ctrl& ctrl, T& val);

	template <class T>
	CtrlRetriever& operator()(Ctrl& ctrl, T& val) { Put(ctrl, val); return *this; }

	void Retrieve();

	Callback operator<<=(Callback cb);
};

template <class T>
void CtrlRetriever::Put(Ctrl& ctrl, T& val)
{
	CtrlItem<T> *m = new CtrlItem<T>();
	m->ctrl = &ctrl;
	m->value = &val;
	ctrl <<= val;
	Put(m);
}

class IdCtrls {
	struct Item {
		Id    id;
		Ctrl *ctrl;
	};
	Array<Item> item;

public:
	void        Reset()                              { item.Clear(); }

	void        Add(Id id, Ctrl& ctrl);
	IdCtrls&    operator()(Id id, Ctrl& ctrl)        { Add(id, ctrl); return *this; }
	int         GetCount() const                     { return item.GetCount(); }
	Ctrl&       operator[](int i)                    { return *item[i].ctrl; }
	const Ctrl& operator[](int i) const              { return *item[i].ctrl; }
	Id          GetKey(int i) const                  { return item[i].id; }
	Id          operator()(int i) const              { return item[i].id; }

	ValueMap    Get() const;
	void        Set(const ValueMap& m);
};

void Set(ArrayCtrl& array, int ii, IdCtrls& m);
void Get(ArrayCtrl& array, int ii, IdCtrls& m);

void   UpdateSetDir(const char *path);
void   UpdateSetUpdater(const char *exename);
String UpdateGetDir();

void UpdateFile(String dst, String src);

void MemoryProfileInfo();

struct sPaintRedirectCtrl : Ctrl {
	Ctrl *ctrl;

	virtual void Paint(Draw& w) {
		ctrl->Paint(w);
	}
};


text:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Identity;

/// <summary>
/// Provides the APIs for managing roles in a persistence store.
/// </summary>
/// <typeparam name="TRole">The type encapsulating a role.</typeparam>
public class AspNetRoleManager<TRole> : RoleManager<TRole>, IDisposable where TRole : class
{
    private readonly CancellationToken _cancel;

    /// <summary>
    /// Constructs a new instance of <see cref="RoleManager{TRole}"/>.
    /// </summary>
    /// <param name="store">The persistence store the manager will operate over.</param>
    /// <param name="roleValidators">A collection of validators for roles.</param>
    /// <param name="keyNormalizer">The normalizer to use when normalizing role names to keys.</param>
    /// <param name="errors">The <see cref="IdentityErrorDescriber"/> used to provider error messages.</param>
    /// <param name="logger">The logger used to log messages, warnings and errors.</param>
    /// <param name="contextAccessor">The accessor used to access the <see cref="HttpContext"/>.</param>
    public AspNetRoleManager(IRoleStore<TRole> store,
        IEnumerable<IRoleValidator<TRole>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<RoleManager<TRole>> logger,
        IHttpContextAccessor contextAccessor)
        : base(store, roleValidators, keyNormalizer, errors, logger)
    {
        _cancel = contextAccessor?.HttpContext?.RequestAborted ?? CancellationToken.None;
    }

    /// <summary>
    /// The cancellation token associated with the current HttpContext.RequestAborted or CancellationToken.None if unavailable.
    /// </summary>
    protected override CancellationToken CancellationToken => _cancel;
}


text:
package xdroid.collections;

/**
 * @author Oleksii Kropachov (o.kropachov@shamanland.com)
 */
public interface FactoryArg1<T, A1> {
    T create(A1 arg1);
}


text:
module ActiveModel
  module Validations
    # Adds collection items validation to ActiveModel::Model.
    #
    # Usage:
    # @example
    #   class FooBar
    #     include ActiveModel::Model
    #
    #     attr_accessor :kinds
    #
    #     validates :kinds, collection_items { type: Symbol, inclusion: { in: [:foo, :bar] } }
    #   end
    class CollectionItemsValidator < ActiveModel::EachValidator
      extend ActiveSupport::Autoload

      autoload :ArrayAttributeReader
      autoload :ArrayAttributeGetter
      autoload :InnerValidatorBuilder

      def initialize(*)
        super.tap { set_inner_validators }
      end

      def validate_each(record, attribute, value)
        if value.kind_of? Enumerable
          validate_collection(record, attribute, value)
        else
          record.errors.add attribute, 'must be a collection'
        end
      end

      private

      attr_reader :inner_validators

      def set_inner_validators
        inner_validation_options = options.except(:class)
        @inner_validators = inner_validation_options.map do |validator_name, inner_options|
          InnerValidatorBuilder.build validator_name, inner_options
        end
      end

      def validator_value_pairs_for(value)
        inner_validators.product(value.each_with_index.to_a)
      end

      def validate_collection(record, attribute, value)
        record.extend ArrayAttributeReader
        validator_value_pairs_for(value).each do |validator, (item, index)|
          validator.validate_each record, :"#{attribute}[#{index}]", item
        end
      end
    end
  end
end


text:
def under_queen_attack(n, queens, queries):
    result = []
    for query in queries:
        attack_status = False
        for queen in queens:
            horizontal = query[0] == queen[0]
            vertical = query[1] == queen[1]
            diagonal = abs(queen[0] - query[0]) == abs(queen[1] - query[1])
            attack_status = (horizontal or vertical or diagonal)
            if attack_status is True:
                break
        result.append(attack_status)
    return result