text:
namespace System.ServiceModel
{
    using System;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Security;
    using System.IdentityModel.Claims;
    using System.IdentityModel.Policy;
    using System.IdentityModel.Tokens;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Security.Principal;

    public class ServiceSecurityContext
    {
        static ServiceSecurityContext anonymous;
        ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies;
        AuthorizationContext authorizationContext;
        IIdentity primaryIdentity;
        Claim identityClaim;
        WindowsIdentity windowsIdentity;

        // Perf: delay created authorizationContext using forward chain.
        public ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
        {
            if (authorizationPolicies == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
            }
            this.authorizationContext = null;
            this.authorizationPolicies = authorizationPolicies;
        }

        public ServiceSecurityContext(AuthorizationContext authorizationContext)
            : this(authorizationContext, EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance)
        {
        }

        public ServiceSecurityContext(AuthorizationContext authorizationContext, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
        {
            if (authorizationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
            }
            if (authorizationPolicies == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
            }
            this.authorizationContext = authorizationContext;
            this.authorizationPolicies = authorizationPolicies;
        }

        public static ServiceSecurityContext Anonymous
        {
            get
            {
                if (anonymous == null)
                {
                    anonymous = new ServiceSecurityContext(EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance);
                }
                return anonymous;
            }
        }

        public static ServiceSecurityContext Current
        {
            get
            {
                ServiceSecurityContext result = null;

                OperationContext operationContext = OperationContext.Current;
                if (operationContext != null)
                {
                    MessageProperties properties = operationContext.IncomingMessageProperties;
                    if (properties != null)
                    {
                        SecurityMessageProperty security = properties.Security;
                        if (security != null)
                        {
                            result = security.ServiceSecurityContext;
                        }
                    }
                }

                return result;
            }
        }

        public bool IsAnonymous
        {
            get
            {
                return this == Anonymous || this.IdentityClaim == null;
            }
        }

        internal Claim IdentityClaim
        {
            get
            {
                if (this.identityClaim == null)
                {
                    this.identityClaim = SecurityUtils.GetPrimaryIdentityClaim(this.AuthorizationContext);
                }
                return this.identityClaim;
            }
        }

        public IIdentity PrimaryIdentity
        {
            get
            {
                if (this.primaryIdentity == null)
                {
                    IIdentity primaryIdentity = null;
                    IList<IIdentity> identities = GetIdentities();
                    // Multiple Identities is treated as anonymous
                    if (identities != null && identities.Count == 1)
                    {
                        primaryIdentity = identities[0];
                    }

                    this.primaryIdentity = primaryIdentity ?? SecurityUtils.AnonymousIdentity;
                }
                return this.primaryIdentity;
            }
        }

        public WindowsIdentity WindowsIdentity
        {
            get
            {
                if (this.windowsIdentity == null)
                {
                    WindowsIdentity windowsIdentity = null;
                    IList<IIdentity> identities = GetIdentities();
                    if (identities != null)
                    {
                        for (int i = 0; i < identities.Count; ++i)
                        {
                            WindowsIdentity identity = identities[i] as WindowsIdentity;
                            if (identity != null)
                            {
                                // Multiple Identities is treated as anonymous
                                if (windowsIdentity != null)
                                {
                                    windowsIdentity = WindowsIdentity.GetAnonymous();
                                    break;
                                }
                                windowsIdentity = identity;
                            }
                        }
                    }

                    this.windowsIdentity = windowsIdentity ?? WindowsIdentity.GetAnonymous();
                }
                return this.windowsIdentity;
            }
        }

        public ReadOnlyCollection<IAuthorizationPolicy> AuthorizationPolicies
        {
            get
            {
                return this.authorizationPolicies;
            }
            set
            {
                this.authorizationPolicies = value;
            }
        }

        public AuthorizationContext AuthorizationContext
        {
            get
            {
                if (this.authorizationContext == null)
                {
                    this.authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(this.authorizationPolicies);
                }
                return this.authorizationContext;
            }
        }

        IList<IIdentity> GetIdentities()
        {
            object identities;
            AuthorizationContext authContext = this.AuthorizationContext;
            if (authContext != null && authContext.Properties.TryGetValue(SecurityUtils.Identities, out identities))
            {
                return identities as IList<IIdentity>;
            }
            return null;
        }
    }
}


text:
sleep 2

if [ ! -f /cre/versions.txt ]; then
    echo "[FAIL]: File /cre/versions.txt not found!"
    exit 1
fi

if [ ! -f /cre/php-procfile ]; then
    echo "[FAIL]: File /cre/php-packages-procfile not found!"
    exit 1
fi

isInFile=$(cat /cre/versions.txt | grep -c "crePhp")
if [ $isInFile -eq 0 ]; then
    echo "[FAIL]: Php not installed!"
    exit 1
fi

isInFile=$(cat /cre/versions.txt | grep -cP "PHP $PHP_VERSION")
if [ $isInFile -eq 0 ]; then
    echo "[WARNING]: Wrong version of php installed!"
    #exit 1
fi

sleep 2

#Do some fancy tests....?

echo "[SUCCESS]"
exit 0

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.table.types.logical;

import org.apache.flink.annotation.PublicEvolving;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Logical type of a 2-byte signed integer with values from -32,768 to 32,767.
 *
 * <p>The serialized string representation is {@code SMALLINT}.
 */
@PublicEvolving
public final class SmallIntType extends LogicalType {
    private static final long serialVersionUID = 1L;

    public static final int PRECISION = 5;

    private static final String FORMAT = "SMALLINT";

    private static final Set<String> NULL_OUTPUT_CONVERSION = conversionSet(Short.class.getName());

    private static final Set<String> NOT_NULL_INPUT_OUTPUT_CONVERSION =
            conversionSet(Short.class.getName(), short.class.getName());

    private static final Class<?> DEFAULT_CONVERSION = Short.class;

    public SmallIntType(boolean isNullable) {
        super(isNullable, LogicalTypeRoot.SMALLINT);
    }

    public SmallIntType() {
        this(true);
    }

    @Override
    public LogicalType copy(boolean isNullable) {
        return new SmallIntType(isNullable);
    }

    @Override
    public String asSerializableString() {
        return withNullability(FORMAT);
    }

    @Override
    public boolean supportsInputConversion(Class<?> clazz) {
        return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
    }

    @Override
    public boolean supportsOutputConversion(Class<?> clazz) {
        if (isNullable()) {
            return NULL_OUTPUT_CONVERSION.contains(clazz.getName());
        }
        return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
    }

    @Override
    public Class<?> getDefaultConversion() {
        return DEFAULT_CONVERSION;
    }

    @Override
    public List<LogicalType> getChildren() {
        return Collections.emptyList();
    }

    @Override
    public <R> R accept(LogicalTypeVisitor<R> visitor) {
        return visitor.visit(this);
    }
}


text:
<?php

namespace Rudolf\Modules\Albums\Category\One\Admin;

use Rudolf\Framework\View\AdminView;

class DelView extends AdminView
{
    /**
     * @var Category
     */
    protected $category;

    /**
     * @var string
     */
    protected $path;

    /**
     * Set data to delete category.
     *
     * @param array $category
     */
    public function delCategory(array $category)
    {
        $this->category = new Category($category);

        $this->pageTitle = _('Delete category');
        $this->head->setTitle($this->pageTitle);

        $this->path = $this->category->delUrl();

        $this->templateType = 'del';

        $this->template = 'categories-del';
    }
}


text:
namespace media {

// TODO(msu.koo): http://crbug.com/532272, remove checking the switch in favour
// of deferring GetModel() call to the actual VideoCaptureDevice object.
const std::string VideoCaptureDevice::Name::GetNameAndModel() const {
  const std::string model_id = GetModel();
  if (model_id.empty())
    return device_name_;
  const std::string suffix = " (" + model_id + ")";
  if (base::EndsWith(device_name_, suffix, base::CompareCase::SENSITIVE) ||
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kUseFakeDeviceForMediaStream))
    // Ignore |model_id| if |kUseFakeDeviceForMediaStream| flag is present.
    return device_name_;
  return device_name_ + suffix;
}

VideoCaptureDevice::Name::Name() {
}

VideoCaptureDevice::Name::Name(const std::string& name, const std::string& id)
    : device_name_(name), unique_id_(id) {
}

#if defined(OS_LINUX)
VideoCaptureDevice::Name::Name(const std::string& name,
                               const std::string& id,
                               const CaptureApiType api_type)
    : device_name_(name), unique_id_(id), capture_api_class_(api_type) {
}
#elif defined(OS_WIN)
VideoCaptureDevice::Name::Name(const std::string& name,
                               const std::string& id,
                               const CaptureApiType api_type)
    : device_name_(name),
      unique_id_(id),
      capture_api_class_(api_type),
      capabilities_id_(id) {
}
#elif defined(OS_MACOSX)
VideoCaptureDevice::Name::Name(const std::string& name,
                               const std::string& id,
                               const CaptureApiType api_type)
    : device_name_(name),
      unique_id_(id),
      capture_api_class_(api_type),
      transport_type_(OTHER_TRANSPORT),
      is_blacklisted_(false) {
}

VideoCaptureDevice::Name::Name(const std::string& name,
                               const std::string& id,
                               const CaptureApiType api_type,
                               const TransportType transport_type)
    : device_name_(name),
      unique_id_(id),
      capture_api_class_(api_type),
      transport_type_(transport_type),
      is_blacklisted_(false) {
}
#elif defined(ANDROID)
VideoCaptureDevice::Name::Name(const std::string& name,
                               const std::string& id,
                               const CaptureApiType api_type)
    : device_name_(name), unique_id_(id), capture_api_class_(api_type) {
}
#endif

VideoCaptureDevice::Name::~Name() {
}

#if defined(OS_LINUX)
const char* VideoCaptureDevice::Name::GetCaptureApiTypeString() const {
  switch (capture_api_type()) {
    case V4L2_SINGLE_PLANE:
      return "V4L2 SPLANE";
    case V4L2_MULTI_PLANE:
      return "V4L2 MPLANE";
    default:
      NOTREACHED() << "Unknown Video Capture API type!";
      return "Unknown API";
  }
}
#elif defined(OS_WIN)
const char* VideoCaptureDevice::Name::GetCaptureApiTypeString() const {
  switch (capture_api_type()) {
    case MEDIA_FOUNDATION:
      return "Media Foundation";
    case DIRECT_SHOW:
      return "Direct Show";
    case RSSDK:
      return "RSSDK";
    default:
      NOTREACHED() << "Unknown Video Capture API type!";
      return "Unknown API";
  }
}
#elif defined(OS_MACOSX)
const char* VideoCaptureDevice::Name::GetCaptureApiTypeString() const {
  switch (capture_api_type()) {
    case AVFOUNDATION:
      return "AV Foundation";
    case QTKIT:
      return "QTKit";
    case DECKLINK:
      return "DeckLink";
    default:
      NOTREACHED() << "Unknown Video Capture API type!";
      return "Unknown API";
  }
}
#elif defined(OS_ANDROID)
const char* VideoCaptureDevice::Name::GetCaptureApiTypeString() const {
  switch (capture_api_type()) {
    case API1:
      return "Camera API1";
    case API2_LEGACY:
      return "Camera API2 Legacy";
    case API2_FULL:
      return "Camera API2 Full";
    case API2_LIMITED:
      return "Camera API2 Limited";
    case TANGO:
      return "Tango API";
    case API_TYPE_UNKNOWN:
    default:
      NOTREACHED() << "Unknown Video Capture API type!";
      return "Unknown API";
  }
}
#endif

VideoCaptureDevice::Client::Buffer::~Buffer() {
}

VideoCaptureDevice::~VideoCaptureDevice() {
}

PowerLineFrequency VideoCaptureDevice::GetPowerLineFrequencyForLocation()
    const {
  const std::string current_country = base::CountryCodeForCurrentTimezone();
  if (current_country.empty())
    return PowerLineFrequency::FREQUENCY_DEFAULT;
  // Sorted out list of countries with 60Hz power line frequency, from
  // http://en.wikipedia.org/wiki/Mains_electricity_by_country
  const char* countries_using_60Hz[] = {
      "AI", "AO", "AS", "AW", "AZ", "BM", "BR", "BS", "BZ", "CA", "CO",
      "CR", "CU", "DO", "EC", "FM", "GT", "GU", "GY", "HN", "HT", "JP",
      "KN", "KR", "KY", "MS", "MX", "NI", "PA", "PE", "PF", "PH", "PR",
      "PW", "SA", "SR", "SV", "TT", "TW", "UM", "US", "VG", "VI", "VE"};
  const char** countries_using_60Hz_end =
      countries_using_60Hz + arraysize(countries_using_60Hz);
  if (std::find(countries_using_60Hz, countries_using_60Hz_end,
                current_country) == countries_using_60Hz_end) {
    return media::PowerLineFrequency::FREQUENCY_50HZ;
  }
  return media::PowerLineFrequency::FREQUENCY_60HZ;
}

PowerLineFrequency VideoCaptureDevice::GetPowerLineFrequency(
    const VideoCaptureParams& params) const {
  switch (params.power_line_frequency) {
    case media::PowerLineFrequency::FREQUENCY_50HZ:  // fall through
    case media::PowerLineFrequency::FREQUENCY_60HZ:
      return params.power_line_frequency;
    default:
      return GetPowerLineFrequencyForLocation();
  }
}

}  // namespace media


text:
<?php

require_once './Person.php';
require_once './functions.php';

$people = getPeople();

$name = trim(fgets(STDIN));

echo personExists($people, $name);


text:
extern void RunAllTests(void);

int _tmain(int argc, _TCHAR* argv[])
{
	RunAllTests();
	return 0;
}

#endif


text:
#ifndef _ODE_JOINT_H_
#define _ODE_JOINT_H_

#include <ode/contact.h>
#include "../objects.h"
#include "../obstack.h"

// joint flags
enum
{
    // if this flag is set, the joint was allocated in a joint group
    dJOINT_INGROUP = 1,

    // if this flag is set, the joint was attached with arguments (0,body).
    // our convention is to treat all attaches as (body,0), i.e. so node[0].body
    // is always nonzero, so this flag records the fact that the arguments were
    // swapped.
    dJOINT_REVERSE = 2,

    // if this flag is set, the joint can not have just one body attached to it,
    // it must have either zero or two bodies attached.
    dJOINT_TWOBODIES = 4,

    dJOINT_DISABLED = 8
};

// there are two of these nodes in the joint, one for each connection to a
// body. these are node of a linked list kept by each body of it's connecting
// joints. but note that the body pointer in each node points to the body that
// makes use of the *other* node, not this node. this trick makes it a bit
// easier to traverse the body/joint graph.

struct dxJointNode
{
    dxJoint *joint;     // pointer to enclosing dxJoint object
    dxBody *body;       // *other* body this joint is connected to
    dxJointNode *next;  // next node in body's list of connected joints
};

struct dxJoint : public dObject
{
    // naming convention: the "first" body this is connected to is node[0].body,
    // and the "second" body is node[1].body. if this joint is only connected
    // to one body then the second body is 0.

    // info returned by getInfo1 function. the constraint dimension is m (<=6).
    // i.e. that is the total number of rows in the jacobian. `nub' is the
    // number of unbounded variables (which have lo,hi = -/+ infinity).

    struct Info1
    {
        // Structure size should not exceed sizeof(pointer) bytes to have
        // to have good memory pattern in dxQuickStepper()
        int8 m, nub;
    };

    // info returned by getInfo2 function

    struct Info2
    {
        // integrator parameters: frames per second (1/stepsize), default error
        // reduction parameter (0..1).
        dReal fps, erp;

        // for the first and second body, pointers to two (linear and angular)
        // n*3 jacobian sub matrices, stored by rows. these matrices will have
        // been initialized to 0 on entry. if the second body is zero then the
        // J2xx pointers may be 0.
        dReal *J1l, *J1a, *J2l, *J2a;

        // jacobians for joint damping
        // angular ones are implemented first
        dReal *J1ld, *J1ad, *J2ld, *J2ad;

        // elements to jump from one row to the next in J's
        int rowskip;

        // right hand sides of the equation J*v = c + cfm * lambda. cfm is the
        // "constraint force mixing" vector. c is set to zero on entry, cfm is
        // set to a constant value (typically very small or zero) value on entry.
        dReal *c, *cfm;
        dReal *c_v_max;

        // lo and hi limits for variables (set to -/+ infinity on entry).
        dReal *lo, *hi;

        // findex vector for variables. see the LCP solver interface for a
        // description of what this does. this is set to -1 on entry.
        // note that the returned indexes are relative to the first index of
        // the constraint.
        int *findex;
    };

    // info returned by getSureMaxInfo function.
    // The information is used for memory reservation in calculations.

    struct SureMaxInfo
    {
      // The value of `max_m' must ALWAYS be not less than the value of `m'
      // the getInfo1 call can generate in current joint state. Another
      // requirement is that the value should be provided very quickly,
      // without the excessive calculations.
      // If it is hard/impossible to quickly predict the maximal value of `m'
      // (which is the case for most joint types) the maximum for current
      // joint type in general should be returned. If it can be known the `m'
      // will be smaller, it can save a bit of memory from being reserved
      // for calculations if that smaller value is returned.

      int8 max_m; // Estimate of maximal `m' in Info1
    };

    unsigned flags;             // dJOINT_xxx flags
    dxJointNode node[2];        // connections to bodies. node[1].body can be 0
    dJointFeedback *feedback;   // optional feedback structure
    dReal lambda[6];            // lambda generated by last step
    dReal lambda_erp[6];            // lambda generated by last step

    dxJoint( dxWorld *w );
    virtual ~dxJoint();

    virtual void getInfo1( Info1* info ) = 0;
    virtual void getInfo2( Info2* info ) = 0;
    // This call quickly!!! estimates maximum value of "m" that could be returned by getInfo1()
	// See comments at definition of SureMaxInfo for defails.
    virtual void getSureMaxInfo( SureMaxInfo* info ) = 0;
    virtual dJointType type() const = 0;
    virtual size_t size() const = 0;

    /// Set values which are relative with respect to bodies.
    /// Each dxJoint should redefine it if needed.
    virtual void setRelativeValues() {};

	// Test if this joint should be used in the simulation step
	// (has the enabled flag set, and is attached to at least one dynamic body)
	bool isEnabled() const;

    // to use joint damping set use_damping to true
    // and set damping_coefficient to the desired value
    bool use_damping;
    dReal damping_coefficient;

    // Moved from ball.h and fixed.h by OSRF
    dReal erp;          // error reduction
    dReal cfm;          // constraint force mix in
};

// joint group. NOTE: any joints in the group that have their world destroyed
// will have their world pointer set to 0.

struct dxJointGroup : public dBase
{
    int num;        // number of joints on the stack
    dObStack stack; // a stack of (possibly differently sized) dxJoint
};                  // objects.

// common limit and motor information for a single joint axis of movement
struct dxJointLimitMotor
{
    dReal vel, fmax;        // powered joint: velocity, max force
    dReal lostop, histop;   // joint limits, relative to initial position
    dReal fudge_factor;     // when powering away from joint limits
    dReal normal_cfm;       // cfm to use when not at a stop
    dReal stop_erp, stop_cfm; // erp and cfm for when at joint limit
    dReal bounce;           // restitution factor
    // variables used between getInfo1() and getInfo2()
    int limit;          // 0=free, 1=at lo limit, 2=at hi limit
    dReal limit_err;    // if at limit, amount over limit

    void init( dxWorld * );
    void set( int num, dReal value );
    dReal get( int num );
    int testRotationalLimit( dReal angle );
    int addLimot( dxJoint *joint, dxJoint::Info2 *info, int row,
                  const dVector3 ax1, int rotational );
};

#endif

// Local Variables:
// mode:c++
// c-basic-offset:4
// End:


text:
package com.orientechnologies.orient.core.sql.query;

import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OMemoryStream;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * SQL synchronous query. When executed the caller wait for the result.
 *
 * @author Luca Garulli
 *
 * @param <T>
 * @see OSQLAsynchQuery
 */
@SuppressWarnings({ "unchecked", "serial" })
public class OSQLSynchQuery<T extends Object> extends OSQLAsynchQuery<T> implements OCommandResultListener, Iterable<T> {
  private final OResultSet<T> result              = new OConcurrentResultSet<T>();
  private ORID                nextPageRID;
  private Map<Object, Object> previousQueryParams = new HashMap<Object, Object>();

  public OSQLSynchQuery() {
    resultListener = this;
  }

  public OSQLSynchQuery(final String iText) {
    super(iText);
    resultListener = this;
  }

  public OSQLSynchQuery(final String iText, final int iLimit) {
    super(iText, iLimit, null);
    resultListener = this;
  }

  @Override
  public void reset() {
    result.clear();
  }

  public boolean result(final Object iRecord) {
    if (iRecord != null)
      result.add((T) iRecord);
    return true;
  }

  @Override
  public void end() {
    result.setCompleted();
  }

  @Override
  public List<T> run(final Object... iArgs) {
    result.clear();

    final Map<Object, Object> queryParams;
    queryParams = fetchQueryParams(iArgs);
    resetNextRIDIfParametersWereChanged(queryParams);

    final List<Object> res = (List<Object>) super.run(iArgs);

    if (res != result && res != null) {
      Iterator<Object> iter = res.iterator();
      while (iter.hasNext()) {
        Object item = iter.next();
        result.add((T) item);
      }
    }

    ((OResultSet) result).setCompleted();

    if (!result.isEmpty()) {
      previousQueryParams = new HashMap<Object, Object>(queryParams);
      final ORID lastRid = ((OIdentifiable) result.get(result.size() - 1)).getIdentity();
      nextPageRID = new ORecordId(lastRid.next());
    }

    return result;
  }

  @Override
  public boolean isIdempotent() {
    return true;
  }

  public Object getResult() {
    return result;
  }

  /**
   * @return RID of the record that will be processed first during pagination mode.
   */
  public ORID getNextPageRID() {
    return nextPageRID;
  }

  public void resetPagination() {
    nextPageRID = null;
  }

  public Iterator<T> iterator() {
    execute();
    return ((Iterable<T>) getResult()).iterator();
  }

  @Override
  public boolean isAsynchronous() {
    return false;
  }

  @Override
  protected OMemoryStream queryToStream() {
    final OMemoryStream buffer = super.queryToStream();

    buffer.setUtf8(nextPageRID != null ? nextPageRID.toString() : "");

    final byte[] queryParams = serializeQueryParameters(previousQueryParams);
    buffer.set(queryParams);

    return buffer;
  }

  @Override
  protected void queryFromStream(final OMemoryStream buffer) {
    super.queryFromStream(buffer);

    final String rid = buffer.getAsString();
    if ("".equals(rid))
      nextPageRID = null;
    else
      nextPageRID = new ORecordId(rid);

    final byte[] serializedPrevParams = buffer.getAsByteArray();
    previousQueryParams = deserializeQueryParameters(serializedPrevParams);

  }

  private void resetNextRIDIfParametersWereChanged(final Map<Object, Object> queryParams) {
    if (!queryParams.equals(previousQueryParams))
      nextPageRID = null;
  }

  private Map<Object, Object> fetchQueryParams(final Object... iArgs) {
    if (iArgs != null && iArgs.length > 0)
      return convertToParameters(iArgs);

    Map<Object, Object> queryParams = getParameters();
    if (queryParams == null)
      queryParams = new HashMap<Object, Object>();
    return queryParams;
  }

}


text:
package com.mercury.platform.ui.components.panel;

import javax.swing.*;
import java.awt.*;

public class VerticalScrollContainer extends JPanel implements Scrollable {

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return super.getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 16;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 16;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
}


text:
"""Test that user ops can be used as expected."""
from __future__ import print_function

import tensorflow.python.platform

import tensorflow as tf

class FactTest(tf.test.TestCase):

  def test(self):
    with self.test_session():
      print(tf.user_ops.my_fact().eval())

if __name__ == '__main__':
  tf.test.main()


text:
package com.xcesys.extras.framework.entity;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;

import com.fasterxml.jackson.annotation.JsonView;
import com.xcesys.extras.framework.core.model.IdAuditableEntity;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Dict generated by hbm2java
 */
@Entity
@DynamicInsert
@DynamicUpdate
@NoArgsConstructor
@Getter
@Setter
public class Dict extends IdAuditableEntity {

	private static final long serialVersionUID = -8572522105499245114L;
	@JsonView(DataTablesOutput.View.class)
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn
	private DictType type;
	@JsonView(DataTablesOutput.View.class)
	private String name;
	@JsonView(DataTablesOutput.View.class)
	private String value;
	@JsonView(DataTablesOutput.View.class)
	private Integer sort;
	@JsonView(DataTablesOutput.View.class)
	private String description;

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StockBuddy.Common.Utilities
{
    public static class LinqUtils
    {
        public static Func<T, bool> AndAlso<T>(
    this Func<T, bool> predicate1,
    Func<T, bool> predicate2)
        {
            return arg => predicate1(arg) && predicate2(arg);
        }

        public static Func<T, bool> OrElse<T>(
            this Func<T, bool> predicate1,
            Func<T, bool> predicate2)
        {
            return arg => predicate1(arg) || predicate2(arg);
        }
    }
}


text:
package sidetrack.adam;

import java.util.Scanner;

public class UserInput {
  public int getFirstNumber() {
    return obtainNumber("Please enter first number: ");
  }

  public int getSecondNumber() {
    return obtainNumber("Please enter second number: ");
  }

  private int obtainNumber(String message) {
    int input;
    System.out.println(message);
    Scanner scan = new Scanner(System.in);
    input = scan.nextInt();
    //TODO: input validation
    return input;
  }

  public Operator obtainOperation() {
    Operator operator = null;
    System.out.println("Please enter a type of operator: ");
    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    switch (input) {
      case "+":
        operator = new Add();
        break;
      case "-":
        operator = new Subtract();
        break;
      case "*":
        operator = new Multiply();
        break;
      case "/":
        operator = new Divide();
        break;
      default:
        System.out.println("Invalid operation " + input);
    }
    return operator;
  }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M1.896,16.229 L5.875,10 1.896,3.771H13.688L18.104,10L13.729,16.229Z"/>
</vector>


text:
package storage

import (
	"log"
	"testing"

	"github.com/coreos/etcd/storage/backend"
)

func BenchmarkStorePut(b *testing.B) {
	be, tmpPath := backend.NewDefaultTmpBackend()
	s := NewStore(be)
	defer cleanup(s, be, tmpPath)

	// arbitrary number of bytes
	bytesN := 64
	keys := createBytesSlice(bytesN, b.N)
	vals := createBytesSlice(bytesN, b.N)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		s.Put(keys[i], vals[i], NoLease)
	}
}

// BenchmarkStoreTxnPut benchmarks the Put operation
// with transaction begin and end, where transaction involves
// some synchronization operations, such as mutex locking.
func BenchmarkStoreTxnPut(b *testing.B) {
	be, tmpPath := backend.NewDefaultTmpBackend()
	s := NewStore(be)
	defer cleanup(s, be, tmpPath)

	// arbitrary number of bytes
	bytesN := 64
	keys := createBytesSlice(bytesN, b.N)
	vals := createBytesSlice(bytesN, b.N)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		id := s.TxnBegin()
		if _, err := s.TxnPut(id, keys[i], vals[i], NoLease); err != nil {
			log.Fatalf("txn put error: %v", err)
		}
		s.TxnEnd(id)
	}
}


text:
FineDiff
========

Originally written by Raymond Hill ([https://github.com/gorhill/PHP-FineDiff](https://github.com/gorhill/PHP-FineDiff)) FineDiff has been tweaked to bring it up to date with the modern world. That means documented, nicely formatted, tested code that can be easily extended.

[![Build Status](https://travis-ci.org/cogpowered/FineDiff.png?branch=master)](https://travis-ci.org/cogpowered/FineDiff)

Installation
------------

**Composer**

The preferred way of using FineDiff is through [Composer](http://getcomposer.org).

Add the following to your composer.json file:

```json
{
    "require": {
        "cogpowered/finediff": "0.3.*"
    }
}
```

Upgrading
---------

**0.3.x** introduces a backwards incompatible version, so if you have stored opcodes do not upgrade!

`0.3.x` fixes a double encoding issue that generates a longer opcode than is needed.

Usage
-----

**Render HTML**

Render as HTML the difference between two strings:

```php
$diff = new cogpowered\FineDiff\Diff;
echo $diff->render('string one', 'string two');
```

This would then output:

```html
string <ins>tw</ins>o<del>ne</del>
```

You could change the granularity to `cogpowered\FineDiff\Granularity\Word` so the output is:

```html
string <del>one</del><ins>two</ins>
```

You do this by passing it into the Diff constructor:

```php
$granularity = new cogpowered\FineDiff\Granularity\Word;
$diff        = new cogpowered\FineDiff\Diff($granularity);
```

**Grab opcode instructions**

Opcode instructions are what tell FineDiff how to change one string into another.

```php
$diff = new cogpowered\FineDiff\Diff;
echo $diff->getOpcodes('string one', 'string two');
```

This would then output:

```html
c7d3i3:two
```

Render text using the opcodes:
```php
$render = new cogpowered\FineDiff\Render\Text;
echo $render->process('string one', 'c7d3i3:two');
```

Would output:
```html
string two
```

Same with HTML:
```php
$render = new cogpowered\FineDiff\Render\Html;
echo $render->process('string one', 'c7d3i3:two');
```

License
-------

Copyright (c) 2011 Raymond Hill (http://raymondhill.net/blog/?p=441)
Copyright (c) 2013 Rob Crowe (http://cogpowered.com)

Licensed under The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
import requests
import six
import six.moves.urllib.parse as urlparse

class OpenRefineClient(object):
    _COMMANDS = {
        'get_version': 'command/core/get-version',
        'get_all_project_metadata': 'command/core/get-all-project-metadata',
        'get_project_metadata': 'command/core/get-project-metadata',
        'create_project_from_upload': 'command/core/create-project-from-upload',
        'delete_project': 'command/core/delete-project',
        'export_rows': 'command/core/export-rows',
    }

    def __init__(self, server_url):
        if not isinstance(server_url, six.string_types):
            raise TypeError('"server_url" must be a string')

        self.server_url = server_url

    @property
    def version(self):
        url = self._generate_url(self._COMMANDS['get_version'])
        res = requests.get(url)
        return res.json()['version']

    def create_project(self, name, filepath):
        url = self._generate_url(self._COMMANDS['create_project_from_upload'])
        with open(filepath, 'rb') as project_file:
            params = {
                'project-name': name,
            }
            files = {
                'file': project_file,
            }

            res = requests.post(url, allow_redirects=False,
                                data=params, files=files)

            if res.is_redirect and res.headers.get('location'):
                redirected_to = urlparse.urlparse(res.headers.get('location'))
                query_params = urlparse.parse_qs(redirected_to.query)
                return query_params.get('project')[0]

    def get_projects(self):
        url = self._generate_url(self._COMMANDS['get_all_project_metadata'])
        res = requests.get(url)
        return res.json().get('projects', {})

    def get_project(self, project_id):
        url = self._generate_url(self._COMMANDS['get_project_metadata'])
        res = requests.get(url, params={'project': project_id})
        if res.status_code == 200:
            return res.json()

    def delete_project(self, project_id):
        url = self._generate_url(self._COMMANDS['delete_project'])
        res = requests.post(url, params={'project': project_id})
        if res.status_code == 200:
            return res.json().get('code') == 'ok'

    def export_project(self, project_id, file_format='csv'):
        url = self._generate_url(self._COMMANDS['export_rows'])
        res = requests.post(url, params={
            'project': project_id,
            'format': file_format,
        })
        return res.text

    def _generate_url(self, command):
        return urlparse.urljoin(self.server_url, command)


text:
class TaxHouseholdMember
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :tax_household
  embeds_many :financial_statements

  field :family_member_id, type: Moped::BSON::ObjectId

  field :is_ia_eligible, type: Boolean, default: false
  field :is_medicaid_chip_eligible, type: Boolean, default: false
  field :is_subscriber, type: Boolean, default: false

  include BelongsToFamilyMember

  validate :strictly_boolean

  def eligibility_determinations
    return nil unless tax_household
    tax_household.eligibility_determinations
  end

  def family
    return nil unless tax_household
    tax_household.family
  end

  def is_ia_eligible?
    self.is_ia_eligible
  end

  def is_medicaid_chip_eligible?
    self.is_medicaid_chip_eligible
  end

  def is_subscriber?
    self.is_subscriber
  end

  def is_primary_applicant?
    self.family_member.is_primary_applicant
  end

  def strictly_boolean
    unless is_ia_eligible.is_a? Boolean
      self.errors.add(:base, "is_ia_eligible should be a boolean")
    end

    unless is_medicaid_chip_eligible.is_a? Boolean
      self.errors.add(:base, "is_medicaid_chip_eligible should be a boolean")
    end

    unless is_subscriber.is_a? Boolean
      self.errors.add(:base, "is_subscriber should be a boolean")
    end

  end

  def tax_filing_status
    nil if self.financial_statements.empty?
    self.financial_statements.last.tax_filing_status
  end

  def tax_filing_together?
    false if self.financial_statements.empty?
    self.financial_statements.last.is_tax_filing_together
  end
end


text:
namespace rocon_interaction_msgs
{

static const char STOPPAIRING[] = "rocon_interaction_msgs/StopPairing";

  class StopPairingRequest : public ros::Msg
  {
    public:
      typedef const char* _name_type;
      _name_type name;

    StopPairingRequest():
      name("")
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      uint32_t length_name = strlen(this->name);
      varToArr(outbuffer + offset, length_name);
      offset += 4;
      memcpy(outbuffer + offset, this->name, length_name);
      offset += length_name;
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      uint32_t length_name;
      arrToVar(length_name, (inbuffer + offset));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_name; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_name-1]=0;
      this->name = (char *)(inbuffer + offset-1);
      offset += length_name;
     return offset;
    }

    const char * getType(){ return STOPPAIRING; };
    const char * getMD5(){ return "c1f3d28f1b044c871e6eff2e9fc3c667"; };

  };

  class StopPairingResponse : public ros::Msg
  {
    public:
      typedef int32_t _result_type;
      _result_type result;
      typedef const char* _message_type;
      _message_type message;

    StopPairingResponse():
      result(0),
      message("")
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      union {
        int32_t real;
        uint32_t base;
      } u_result;
      u_result.real = this->result;
      *(outbuffer + offset + 0) = (u_result.base >> (8 * 0)) & 0xFF;
      *(outbuffer + offset + 1) = (u_result.base >> (8 * 1)) & 0xFF;
      *(outbuffer + offset + 2) = (u_result.base >> (8 * 2)) & 0xFF;
      *(outbuffer + offset + 3) = (u_result.base >> (8 * 3)) & 0xFF;
      offset += sizeof(this->result);
      uint32_t length_message = strlen(this->message);
      varToArr(outbuffer + offset, length_message);
      offset += 4;
      memcpy(outbuffer + offset, this->message, length_message);
      offset += length_message;
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      union {
        int32_t real;
        uint32_t base;
      } u_result;
      u_result.base = 0;
      u_result.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
      u_result.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
      u_result.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
      u_result.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
      this->result = u_result.real;
      offset += sizeof(this->result);
      uint32_t length_message;
      arrToVar(length_message, (inbuffer + offset));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_message; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_message-1]=0;
      this->message = (char *)(inbuffer + offset-1);
      offset += length_message;
     return offset;
    }

    const char * getType(){ return STOPPAIRING; };
    const char * getMD5(){ return "81f429c124a47a1dc0c7e925328a2d0c"; };

  };

  class StopPairing {
    public:
    typedef StopPairingRequest Request;
    typedef StopPairingResponse Response;
  };

}
#endif


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"time"

	"github.com/nats-io/nats-server/v2/server"
	top "github.com/nats-io/nats-top/util"
	ui "gopkg.in/gizak/termui.v1"
)

const version = "0.5.3"

var (
	host                       = flag.String("s", "127.0.0.1", "The nats server host.")
	port                       = flag.Int("m", 8222, "The NATS server monitoring port.")
	conns                      = flag.Int("n", 1024, "Maximum number of connections to poll.")
	delay                      = flag.Int("d", 1, "Refresh interval in seconds.")
	sortBy                     = flag.String("sort", "cid", "Value for which to sort by the connections.")
	lookupDNS                  = flag.Bool("lookup", false, "Enable client addresses DNS lookup.")
	outputFile                 = flag.String("o", "", "Save the very first nats-top snapshot to the given file and exit. If '-' is passed then the snapshot is printed the standard output.")
	showVersion                = false
	outputDelimiter            = flag.String("l", "", "Specifies the delimiter to use for the output file when the '-o' parameter is used. By default this option is unset which means that standard grid-like plain-text output will be used.")
	displayRawBytes            = flag.Bool("b", false, "Display traffic in raw bytes.")
	maxStatsRefreshes          = flag.Int("r", -1, "Specifies the maximum number of times nats-top should refresh nats-stats before exiting.")
	displaySubscriptionsColumn = false

	// Secure options
	httpsPort     = flag.Int("ms", 0, "The NATS server secure monitoring port.")
	certOpt       = flag.String("cert", "", "Client cert in case NATS server using TLS")
	keyOpt        = flag.String("key", "", "Client private key in case NATS server using TLS")
	caCertOpt     = flag.String("cacert", "", "Root CA cert")
	skipVerifyOpt = flag.Bool("k", false, "Skip verifying server certificate")
)

const usageHelp = `
usage: nats-top [-s server] [-m http_port] [-ms https_port] [-n num_connections] [-d delay_secs] [-r max] [-o FILE] [-l DELIMITER] [-sort by]
                [-cert FILE] [-key FILE] [-cacert FILE] [-k] [-b] [-v|--version] [-u|--display-subscriptions-column]

`

func usage() {
	log.Fatalf(usageHelp)
}

func init() {
	flag.BoolVar(&showVersion, "v", false, "Same as --version.")
	flag.BoolVar(&showVersion, "version", false, "Show nats-top version.")

	flag.BoolVar(&displaySubscriptionsColumn, "u", false, "Same as --display-subscriptions-column.")
	flag.BoolVar(&displaySubscriptionsColumn, "display-subscriptions-column", false, "Display subscriptions-column upon launch.")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()
}

func main() {
	if showVersion {
		log.Printf("nats-top v%s", version)
		os.Exit(0)
	}

	var engine *top.Engine

	// Use secure port if set explicitly, otherwise use http port by default
	if *httpsPort != 0 {
		engine = top.NewEngine(*host, *httpsPort, *conns, *delay)
		err := engine.SetupHTTPS(*caCertOpt, *certOpt, *keyOpt, *skipVerifyOpt)
		if err != nil {
			fmt.Fprintf(os.Stderr, "nats-top: %s", err)
			usage()
		}
	} else {
		engine = top.NewEngine(*host, *port, *conns, *delay)
		engine.SetupHTTP()
	}

	if engine.Host == "" {
		fmt.Fprintf(os.Stderr, "nats-top: invalid monitoring endpoint")
		usage()
	}

	if engine.Port == 0 {
		fmt.Fprintf(os.Stderr, "nats-top: invalid monitoring port")
		usage()
	}

	// Smoke test to abort in case can't connect to server since the beginning.
	_, err := engine.Request("/varz")
	if err != nil {
		fmt.Fprintf(os.Stderr, "nats-top: /varz smoke test failed: %s", err)
		usage()
	}

	sortOpt := server.SortOpt(*sortBy)
	if !sortOpt.IsValid() {
		fmt.Fprintf(os.Stderr, "nats-top: invalid option to sort by: %s\n", sortOpt)
		usage()
	}
	engine.SortOpt = sortOpt

	if displaySubscriptionsColumn {
		engine.DisplaySubs = true
	}

	if *outputFile != "" {
		saveStatsSnapshotToFile(engine, outputFile, *outputDelimiter)
		return
	}

	err = ui.Init()
	if err != nil {
		panic(err)
	}
	defer ui.Close()

	go engine.MonitorStats()

	StartUI(engine)
}

func saveStatsSnapshotToFile(engine *top.Engine, outputFile *string, outputDelimiter string) {
	stats := engine.FetchStatsSnapshot()
	text := generateParagraph(engine, stats, outputDelimiter)

	if *outputFile == "-" {
		fmt.Print(text)
		return
	}

	f, err := os.OpenFile(*outputFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		log.Fatalf("nats-top: failed to open output file '%s': %s\n", *outputFile, err)
	}

	if _, err = f.WriteString(text); err != nil {
		log.Fatalf("nats-top: failed to write stats-snapshot to output file '%s': %s\n", *outputFile, err)
	}

	f.Close() //no point to error check    process will exit anyway
}

// clearScreen tries to ensure resetting original state of screen
func clearScreen() {
	fmt.Print("\033[2J\033[1;1H\033[?25l")
}

func cleanExit() {
	clearScreen()
	ui.Close()

	// Show cursor once again
	fmt.Print("\033[?25h")
	os.Exit(0)
}

// generateParagraph takes an options map and latest Stats
// then returns a formatted paragraph ready to be rendered
func generateParagraph(
	engine *top.Engine,
	stats *top.Stats,
	outputDelimiter string,
) string {

	if len(outputDelimiter) > 0 { //default
		return generateParagraphCSV(engine, stats, outputDelimiter)
	}

	return generateParagraphPlainText(engine, stats)
}

const (
	DEFAULT_PADDING_SIZE = 2
	DEFAULT_PADDING      = "  "

	DEFAULT_HOST_PADDING_SIZE = 15
)

var (
	resolvedHosts = map[string]string{} // cache for reducing DNS lookups in case enabled

	standardHeaders = []interface{}{"SUBS", "PENDING", "MSGS_TO", "MSGS_FROM", "BYTES_TO", "BYTES_FROM", "LANG", "VERSION", "UPTIME", "LAST_ACTIVITY"}

	defaultHeaderColumns = []string{"%-6s", "%-10s", "%-10s", "%-10s", "%-10s", "%-10s", "%-7s", "%-7s", "%-7s", "%-40s"} // Chopped: HOST CID NAME...
	defaultRowColumns    = []string{"%-6d", "%-10s", "%-10s", "%-10s", "%-10s", "%-10s", "%-7s", "%-7s", "%-7s", "%-40s"}
)

func generateParagraphPlainText(
	engine *top.Engine,
	stats *top.Stats,
) string {

	// Snapshot current stats
	cpu := stats.Varz.CPU
	memVal := stats.Varz.Mem
	uptime := stats.Varz.Uptime
	numConns := stats.Connz.NumConns
	inMsgsVal := stats.Varz.InMsgs
	outMsgsVal := stats.Varz.OutMsgs
	inBytesVal := stats.Varz.InBytes
	outBytesVal := stats.Varz.OutBytes
	slowConsumers := stats.Varz.SlowConsumers

	var serverVersion string
	if stats.Varz.Version != "" {
		serverVersion = stats.Varz.Version
	}

	mem := top.Psize(false, memVal) //memory is exempt from the rawbytes flag
	inMsgs := top.Psize(*displayRawBytes, inMsgsVal)
	outMsgs := top.Psize(*displayRawBytes, outMsgsVal)
	inBytes := top.Psize(*displayRawBytes, inBytesVal)
	outBytes := top.Psize(*displayRawBytes, outBytesVal)
	inMsgsRate := stats.Rates.InMsgsRate
	outMsgsRate := stats.Rates.OutMsgsRate
	inBytesRate := top.Psize(*displayRawBytes, int64(stats.Rates.InBytesRate))
	outBytesRate := top.Psize(*displayRawBytes, int64(stats.Rates.OutBytesRate))

	info := "NATS server version %s (uptime: %s) %s\n"
	info += "Server:\n"
	info += "  Load: CPU:  %.1f%%  Memory: %s  Slow Consumers: %d\n"
	info += "  In:   Msgs: %s  Bytes: %s  Msgs/Sec: %.1f  Bytes/Sec: %s\n"
	info += "  Out:  Msgs: %s  Bytes: %s  Msgs/Sec: %.1f  Bytes/Sec: %s"

	text := fmt.Sprintf(
		info, serverVersion, uptime, stats.Error,
		cpu, mem, slowConsumers,
		inMsgs, inBytes, inMsgsRate, inBytesRate,
		outMsgs, outBytes, outMsgsRate, outBytesRate,
	)

	text += fmt.Sprintf("\n\nConnections Polled: %d\n", numConns)
	displaySubs := engine.DisplaySubs

	header := make([]interface{}, 0) // Dynamically add columns and padding depending
	hostSize := DEFAULT_HOST_PADDING_SIZE

	nameSize := 0 // Disable name unless we have seen one using it
	for _, conn := range stats.Connz.Conns {
		var size int

		var hostname string
		if *lookupDNS {
			if addr, present := resolvedHosts[conn.IP]; !present { // Make a lookup for each one of the ips and memoize them for subsequent polls
				addrs, err := net.LookupAddr(conn.IP)
				if err == nil && len(addrs) > 0 && len(addrs[0]) > 0 {
					hostname = addrs[0]
					resolvedHosts[conn.IP] = hostname
				} else {
					// Otherwise just continue to use ip:port as resolved host
					// can be an empty string even though there were no errors
					hostname = fmt.Sprintf("%s:%d", conn.IP, conn.Port)
					resolvedHosts[conn.IP] = hostname
				}
			} else {
				hostname = addr
			}
		} else {
			hostname = fmt.Sprintf("%s:%d", conn.IP, conn.Port)
		}

		size = len(hostname) // host
		if size > hostSize {
			hostSize = size + DEFAULT_PADDING_SIZE
		}

		size = len(conn.Name) // name
		if size > nameSize {
			nameSize = size + DEFAULT_PADDING_SIZE

			minLen := len("NAME") // If using name, ensure that it is not too small...
			if nameSize < minLen {
				nameSize = minLen
			}
		}
	}

	connHeader := DEFAULT_PADDING // Initial padding

	header = append(header, "HOST") // HOST
	connHeader += "%-" + fmt.Sprintf("%d", hostSize) + "s "

	header = append(header, "CID") // CID
	connHeader += " %-6s "

	if nameSize > 0 { // NAME
		header = append(header, "NAME")
		connHeader += "%-" + fmt.Sprintf("%d", nameSize) + "s "
	}

	header = append(header, standardHeaders...)

	connHeader += strings.Join(defaultHeaderColumns, "  ")
	if displaySubs {
		connHeader += "%13s"
	}

	connHeader += "\n" // ...LAST ACTIVITY

	var connRows string
	if displaySubs {
		header = append(header, "SUBSCRIPTIONS")
	}

	connRows = fmt.Sprintf(connHeader, header...)

	text += connRows // Add to screen!

	connValues := DEFAULT_PADDING

	connValues += "%-" + fmt.Sprintf("%d", hostSize) + "s " // HOST: e.g. 192.168.1.1:78901

	connValues += " %-6d " // CID: e.g. 1234

	if nameSize > 0 { // NAME: e.g. hello
		connValues += "%-" + fmt.Sprintf("%d", nameSize) + "s "
	}

	connValues += strings.Join(defaultRowColumns, "  ")
	if displaySubs {
		connValues += "%s"
	}
	connValues += "\n"

	for _, conn := range stats.Connz.Conns {
		var h string
		if *lookupDNS {
			if rh, present := resolvedHosts[conn.IP]; present {
				h = rh
			}
		} else {
			h = fmt.Sprintf("%s:%d", conn.IP, conn.Port)
		}

		var connLine string // Build the info line
		connLineInfo := make([]interface{}, 0)
		connLineInfo = append(connLineInfo, h)
		connLineInfo = append(connLineInfo, conn.Cid)

		if nameSize > 0 { // Name not included unless present
			connLineInfo = append(connLineInfo, conn.Name)
		}

		connLineInfo = append(connLineInfo, conn.NumSubs)
		connLineInfo = append(connLineInfo, top.Psize(*displayRawBytes, int64(conn.Pending)), top.Psize(*displayRawBytes, conn.OutMsgs), top.Psize(*displayRawBytes, conn.InMsgs))
		connLineInfo = append(connLineInfo, top.Psize(*displayRawBytes, conn.OutBytes), top.Psize(*displayRawBytes, conn.InBytes))
		connLineInfo = append(connLineInfo, conn.Lang, conn.Version)
		connLineInfo = append(connLineInfo, conn.Uptime, conn.LastActivity)

		if displaySubs {
			subs := strings.Join(conn.Subs, ", ")
			connLineInfo = append(connLineInfo, subs)
		}

		connLine = fmt.Sprintf(connValues, connLineInfo...)

		text += connLine // Add line to screen!
	}

	return text
}

func generateParagraphCSV(
	engine *top.Engine,
	stats *top.Stats,
	delimiter string,
) string {

	defaultHeaderAndRowColumnsForCsv := []string{"%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s"} // Chopped: HOST CID NAME...

	cpu := stats.Varz.CPU // Snapshot current stats
	memVal := stats.Varz.Mem
	uptime := stats.Varz.Uptime
	numConns := stats.Connz.NumConns
	inMsgsVal := stats.Varz.InMsgs
	outMsgsVal := stats.Varz.OutMsgs
	inBytesVal := stats.Varz.InBytes
	outBytesVal := stats.Varz.OutBytes
	slowConsumers := stats.Varz.SlowConsumers

	var serverVersion string
	if stats.Varz.Version != "" {
		serverVersion = stats.Varz.Version
	}

	mem := top.Psize(false, memVal) //memory is exempt from the rawbytes flag
	inMsgs := top.Psize(*displayRawBytes, inMsgsVal)
	outMsgs := top.Psize(*displayRawBytes, outMsgsVal)
	inBytes := top.Psize(*displayRawBytes, inBytesVal)
	outBytes := top.Psize(*displayRawBytes, outBytesVal)
	inMsgsRate := stats.Rates.InMsgsRate
	outMsgsRate := stats.Rates.OutMsgsRate
	inBytesRate := top.Psize(*displayRawBytes, int64(stats.Rates.InBytesRate))
	outBytesRate := top.Psize(*displayRawBytes, int64(stats.Rates.OutBytesRate))

	info := "NATS server version[__DELIM__]%s[__DELIM__](uptime: %s)[__DELIM__]%s\n"
	info += "Server:\n"
	info += "Load:[__DELIM__]CPU:[__DELIM__]%.1f%%[__DELIM__]Memory:[__DELIM__]%s[__DELIM__]Slow Consumers:[__DELIM__]%d\n"
	info += "In:[__DELIM__]Msgs:[__DELIM__]%s[__DELIM__]Bytes:[__DELIM__]%s[__DELIM__]Msgs/Sec:[__DELIM__]%.1f[__DELIM__]Bytes/Sec:[__DELIM__]%s\n"
	info += "Out:[__DELIM__]Msgs:[__DELIM__]%s[__DELIM__]Bytes:[__DELIM__]%s[__DELIM__]Msgs/Sec:[__DELIM__]%.1f[__DELIM__]Bytes/Sec:[__DELIM__]%s"

	text := fmt.Sprintf(
		info, serverVersion, uptime, stats.Error,
		cpu, mem, slowConsumers,
		inMsgs, inBytes, inMsgsRate, inBytesRate,
		outMsgs, outBytes, outMsgsRate, outBytesRate,
	)

	text += fmt.Sprintf("\n\nConnections Polled:[__DELIM__]%d\n", numConns)

	displaySubs := engine.DisplaySubs
	for _, conn := range stats.Connz.Conns {
		if !*lookupDNS {
			continue
		}

		_, present := resolvedHosts[conn.IP]
		if present {
			continue
		}

		addrs, err := net.LookupAddr(conn.IP)

		hostname := ""
		if err == nil && len(addrs) > 0 && len(addrs[0]) > 0 { // Make a lookup for each one of the ips and memoize them for subsequent polls
			hostname = addrs[0]
		} else { // Otherwise just continue to use ip:port as resolved host can be an empty string even though there were no errors
			hostname = fmt.Sprintf("%s:%d", conn.IP, conn.Port)
		}

		resolvedHosts[conn.IP] = hostname
	}

	header := make([]interface{}, 0) // Dynamically add columns
	connHeader := ""

	header = append(header, "HOST") // HOST
	connHeader += "%s[__DELIM__]"

	header = append(header, "CID") // CID
	connHeader += "%s[__DELIM__]"

	header = append(header, "NAME") // NAME
	connHeader += "%s[__DELIM__]"

	header = append(header, standardHeaders...)
	connHeader += strings.Join(defaultHeaderAndRowColumnsForCsv, "[__DELIM__]")

	if displaySubs {
		connHeader += "[__DELIM__]%s" // SUBSCRIPTIONS
	}

	connHeader += "\n" // ...LAST ACTIVITY

	if displaySubs {
		header = append(header, "SUBSCRIPTIONS")
	}

	text += fmt.Sprintf(connHeader, header...) // Add to screen!

	connValues := "%s[__DELIM__]" // HOST: e.g. 192.168.1.1:78901
	connValues += "%d[__DELIM__]" // CID: e.g. 1234
	connValues += "%s[__DELIM__]" // NAME: e.g. hello

	connValues += strings.Join(defaultHeaderAndRowColumnsForCsv, "[__DELIM__]")
	if displaySubs {
		connValues += "%s"
	}
	connValues += "\n"

	for _, conn := range stats.Connz.Conns {
		var h string
		if *lookupDNS {
			if rh, present := resolvedHosts[conn.IP]; present {
				h = rh
			}
		} else {
			h = fmt.Sprintf("%s:%d", conn.IP, conn.Port)
		}

		connLineInfo := make([]interface{}, 0)
		connLineInfo = append(connLineInfo, h)
		connLineInfo = append(connLineInfo, conn.Cid)
		connLineInfo = append(connLineInfo, conn.Name)
		connLineInfo = append(connLineInfo, fmt.Sprintf("%d", conn.NumSubs))
		connLineInfo = append(connLineInfo, top.Psize(*displayRawBytes, int64(conn.Pending)), top.Psize(*displayRawBytes, conn.OutMsgs), top.Psize(*displayRawBytes, conn.InMsgs))
		connLineInfo = append(connLineInfo, top.Psize(*displayRawBytes, conn.OutBytes), top.Psize(*displayRawBytes, conn.InBytes))
		connLineInfo = append(connLineInfo, conn.Lang, conn.Version)
		connLineInfo = append(connLineInfo, conn.Uptime, conn.LastActivity)

		if displaySubs {
			subs := "[__DELIM__]" + strings.Join(conn.Subs, "  ") // its safer to use a couple of whitespaces instead of commas to separate the subs because comma is reserved to separate entire columns!
			connLineInfo = append(connLineInfo, subs)
		}

		text += fmt.Sprintf(connValues, connLineInfo...)
	}

	text = strings.ReplaceAll(text, "[__DELIM__]", delimiter)

	return text
}

type ViewMode int

const (
	TopViewMode ViewMode = iota
	HelpViewMode
)

type RedrawCause int

const (
	DueToNewStats RedrawCause = iota
	DueToViewportResize
)

// StartUI periodically refreshes the screen using recent data.
func StartUI(engine *top.Engine) {

	cleanStats := &top.Stats{
		Varz:  &server.Varz{},
		Connz: &server.Connz{},
		Rates: &top.Rates{},
		Error: fmt.Errorf(""),
	}

	// Show empty values on first display
	text := generateParagraph(engine, cleanStats, "")
	par := ui.NewPar(text)
	par.Height = ui.TermHeight()
	par.Width = ui.TermWidth()
	par.HasBorder = false

	helpText := generateHelp()
	helpPar := ui.NewPar(helpText)
	helpPar.Height = ui.TermHeight()
	helpPar.Width = ui.TermWidth()
	helpPar.HasBorder = false

	// Top like view
	paraRow := ui.NewRow(ui.NewCol(ui.TermWidth(), 0, par))

	// Help view
	helpParaRow := ui.NewRow(ui.NewCol(ui.TermWidth(), 0, helpPar))

	// Create grids that we'll be using to toggle what to render
	topViewGrid := ui.NewGrid(paraRow)
	helpViewGrid := ui.NewGrid(helpParaRow)

	// Start with the topviewGrid by default
	ui.Body.Rows = topViewGrid.Rows
	ui.Body.Align()

	// Used to toggle back to previous mode
	viewMode := TopViewMode

	// Used for pinging the IU to refresh the screen with new values
	redraw := make(chan RedrawCause)

	update := func() {
		for {
			stats := <-engine.StatsCh

			par.Text = generateParagraph(engine, stats, "") // Update top view text

			redraw <- DueToNewStats
		}
	}

	// Flags for capturing options
	waitingSortOption := false
	waitingLimitOption := false

	optionBuf := ""
	refreshOptionHeader := func() {
		clrline := "\033[1;1H\033[6;1H                  " // Need to mask what was typed before

		clrline += "  "
		for i := 0; i < len(optionBuf); i++ {
			clrline += "  "
		}
		fmt.Print(clrline)
	}

	evt := ui.EventCh()

	ui.Render(ui.Body)

	go update()

	numberOfRedrawsDueToNewStats := 0
	for {
		select {
		case e := <-evt:

			if waitingSortOption {

				if e.Type == ui.EventKey && e.Key == ui.KeyEnter {

					sortOpt := server.SortOpt(optionBuf)
					if sortOpt.IsValid() {
						engine.SortOpt = sortOpt
					} else {
						go func() {
							// Has to be at least of the same length as sort by header
							emptyPadding := "       "
							fmt.Printf("\033[1;1H\033[6;1Hinvalid order: %s%s", optionBuf, emptyPadding)
							waitingSortOption = false
							time.Sleep(1 * time.Second)
							refreshOptionHeader()
							optionBuf = ""
						}()
						continue
					}

					refreshOptionHeader()
					waitingSortOption = false
					optionBuf = ""
					continue
				}

				// Handle backspace
				if e.Type == ui.EventKey && len(optionBuf) > 0 && (e.Key == ui.KeyBackspace || e.Key == ui.KeyBackspace2) {
					optionBuf = optionBuf[:len(optionBuf)-1]
					refreshOptionHeader()
				} else {
					optionBuf += string(e.Ch)
				}
				fmt.Printf("\033[1;1H\033[6;1Hsort by [%s]: %s", engine.SortOpt, optionBuf)
			}

			if waitingLimitOption {

				if e.Type == ui.EventKey && e.Key == ui.KeyEnter {

					var n int
					_, err := fmt.Sscanf(optionBuf, "%d", &n)
					if err == nil {
						engine.Conns = n
					}

					waitingLimitOption = false
					optionBuf = ""
					refreshOptionHeader()
					continue
				}

				// Handle backspace
				if e.Type == ui.EventKey && len(optionBuf) > 0 && (e.Key == ui.KeyBackspace || e.Key == ui.KeyBackspace2) {
					optionBuf = optionBuf[:len(optionBuf)-1]
					refreshOptionHeader()
				} else {
					optionBuf += string(e.Ch)
				}
				fmt.Printf("\033[1;1H\033[6;1Hlimit   [%d]: %s", engine.Conns, optionBuf)
			}

			if e.Type == ui.EventKey && (e.Ch == 'q' || e.Key == ui.KeyCtrlC) {
				close(engine.ShutdownCh)
				cleanExit()
			}

			if e.Type == ui.EventKey && e.Ch == 's' && !(waitingLimitOption || waitingSortOption) {
				engine.DisplaySubs = !engine.DisplaySubs
			}

			if e.Type == ui.EventKey && viewMode == HelpViewMode {
				ui.Body.Rows = topViewGrid.Rows
				viewMode = TopViewMode
				continue
			}

			if e.Type == ui.EventKey && e.Ch == 'o' && !waitingLimitOption && viewMode == TopViewMode {
				fmt.Printf("\033[1;1H\033[6;1Hsort by [%s]:", engine.SortOpt)
				waitingSortOption = true
			}

			if e.Type == ui.EventKey && e.Ch == 'n' && !waitingSortOption && viewMode == TopViewMode {
				fmt.Printf("\033[1;1H\033[6;1Hlimit   [%d]:", engine.Conns)
				waitingLimitOption = true
			}

			if e.Type == ui.EventKey && (e.Ch == '?' || e.Ch == 'h') && !(waitingSortOption || waitingLimitOption) {
				if viewMode == TopViewMode {
					refreshOptionHeader()
					optionBuf = ""
				}

				ui.Body.Rows = helpViewGrid.Rows
				viewMode = HelpViewMode
				waitingLimitOption = false
				waitingSortOption = false
			}

			if e.Type == ui.EventKey && (e.Ch == 'd') && !(waitingSortOption || waitingLimitOption) {
				*lookupDNS = !*lookupDNS
			}

			if e.Type == ui.EventKey && (e.Ch == 'b') && !(waitingSortOption || waitingLimitOption) {
				*displayRawBytes = !*displayRawBytes
			}

			if e.Type == ui.EventResize {
				ui.Body.Width = ui.TermWidth()
				ui.Body.Align()
				go func() { redraw <- DueToViewportResize }()
			}

		case cause := <-redraw:
			ui.Render(ui.Body)

			if cause == DueToNewStats {
				numberOfRedrawsDueToNewStats += 1

				if *maxStatsRefreshes > 0 && numberOfRedrawsDueToNewStats >= *maxStatsRefreshes {
					close(engine.ShutdownCh)
					cleanExit()
				}
			}
		}
	}
}

func generateHelp() string {
	text := `
Command          Description

o<option>        Set primary sort key to <option>.

                 Option can be one of: {cid|subs|pending|msgs_to|msgs_from|
                 bytes_to|bytes_from|idle|last}

                 This can be set in the command line too with -sort flag.

n<limit>         Set sample size of connections to request from the server.

                 This can be set in the command line as well via -n flag.
                 Note that if used in conjunction with sort, the server
                 would respect both options allowing queries like 'connection
                 with largest number of subscriptions': -n 1 -sort subs

s                Toggle displaying connection subscriptions.

d                Toggle activating DNS address lookup for clients.

b                Toggle displaying raw bytes.

q                Quit nats-top.

Press any key to continue...

`
	return text
}


text:
'use strict';
var chaiJoi = function(chai, utils) {

    var Assertion = chai.Assertion;
    var flag = utils.flag;
    var assert = chai.assert;

    var Joi = require('joi');

    //-------------------------------------------------------------------------------------------------------------
//    path()
//
//    Assert the path exists.
//
//        Uses fs.existsSync().
//
//        expect(path).to.be.a.path(?msg);
//    expect(path).to.not.be.a.path(?msg);
//
//    path.should.be.a.path(?msg);
//    path.should.not.be.a.path(?msg);
//
//    assert.pathExists(path, ?msg);
//    assert.notPathExists(path, ?msg);
//    Use of Chai's exist-chain would've been nice but has issues with negations and the message parameter. So don't do that.
    Assertion.addMethod('guid', function(msg) {
        var preMsg = '';
        if (msg) {
            flag(this, 'message', msg);
            preMsg = msg + ': ';
        }

        var obj = this._obj;

        new chai.Assertion(obj, preMsg + 'value').is.a('string');
        var validation = Joi.validate(obj, Joi.string().guid());
        this.assert(
            !validation.error, "expected #{this} to be a guid", "expected #{this} not to be a guid"
        );
    });
    assert.guid = function(val, msg) {
        new chai.Assertion(val).to.be.a.guid(msg);
    };
    assert.notGuid = function(val, msg) {
        new chai.Assertion(val).to.not.be.a.guid(msg);
    };

};

module.exports = chaiJoi;


text:
<!DOCTYPE html>
<html ng-app="SocialShareApp">
<head>
	<title>Angular Social Share</title>
	<link rel="stylesheet" type="text/css" href="/dist/style.css">
</head>
<body ng-controller="indexController as vm">
	<social-share options="vm.shareOptions1"></social-share>

	<script src="/node_modules/jquery/dist/jquery.min.js"></script>
	<script src="/node_modules/angular/angular.min.js"></script>

	<script src="/dist/ngShare.js"></script>
	<script src="bundle.js"></script>
</body>
</html>


text: I am a global, pool, or class variable.


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from hello_package import hello

if __name__ == '__main__':
  print(hello.hello())


text:
#include <msel.h>
#include <msel/syscalls.h>
#include <msel/stdc.h>

#include "os/task.h"

#include "pol_int.h"

msel_status proof_of_life(pol_t* ret)
{
    return msel_svc(MSEL_SVC_POL, ret);
}

msel_status msel_proof_of_life(pol_t* ret)
{

    static uint64_t starting_systicks = 0;
    static gpio_t   button_val;
    uint64_t        elapsed;

    /* Validate args */
    if(!ret)
        return MSEL_EINVAL;

    /* Main can't be suspended, so it may not call this */
    if(msel_active_task_num == MSEL_TASK_MAIN)
        return MSEL_EINVAL;

    /* Only one task at a time may initiate this operation */
    for(size_t i=0; i<MSEL_TASKS_MAX;i++)
    {
        if(msel_task_list[i].wait_op == MSEL_TASK_WAIT_POL)
            if(i != msel_active_task_num)
                return MSEL_EBUSY;
    }

    int         timedout = 0;

    /* If we're already started the POL operation */
    if(!starting_systicks)
    {
        starting_systicks = msel_systicks;
        button_val = msel_gpio_read(POL_SWITCH);
    }

    elapsed = msel_systicks - starting_systicks;

    /* Check for timeout */
    if(elapsed > POL_WAIT_PERIOD)
        timedout = 1;

    /* Update indicator leds */
    if(elapsed % POL_BLINK_PERIOD > POL_BLINK_PERIOD / 2)
        msel_led_off(POL_LED);
    else
        msel_led_on(POL_LED);

    /* If button state has not changed, keep waiting */
    if(msel_gpio_read(POL_SWITCH) == button_val && !timedout)
    {
        msel_active_task->wait_op = MSEL_TASK_WAIT_POL;
        msel_active_task->state.pol.retptr = ret;
        msel_task_schedule();
        return MSEL_ESUSP;
    }

    /* Clean up static state because the syscall is not being suspended */
    starting_systicks = 0;
    button_val = 0;
    msel_led_off(POL_LED);

    *ret = (timedout)?POL_TIMEOUT:POL_USER_PRESENT;

    return MSEL_OK;
}

void msel_init_pol()
{
    /* Make sure our button is configured as an input */
    msel_gpio_config(POL_SWITCH, MSEL_GPIO_INPUT);
}


text:
def assertEqualsApprox(actual, expected, tolerance):
    # Recurse over all subdocuments
    if isinstance(actual, dict) and isinstance(expected, dict):
        for k,v in actual.iteritems():
            assert k in expected
            assertEqualsApprox(v, expected[k], tolerance)

    elif isinstance(actual, float) and isinstance(expected, float):
        if not (abs(actual - expected) < tolerance):
            raise AssertionError("AssertEqualsApprox failed. Should be: " + str(expected) + ", but was " + str(actual) + ".")
    else:
        raise ValueError('Invalid Type(s) in AssertEqualsApprox')

def assertEquals(actual, expected):
	if not actual == expected:
		raise AssertionError("AssertEquals failed. Should be: " + str(expected) + ", but was " + str(actual) + ".")

def assertTrue(val):
	if not val:
		raise AssertionError("AssertTrue failed")

def assertFalse(val):
	if val:
		raise AssertionError("AssertFalse failed")


text:
package daemon // import "github.com/docker/docker/daemon"

import (
	"fmt"
	"os"
	"testing"

	"github.com/docker/docker/api/types"
	containertypes "github.com/docker/docker/api/types/container"
	"github.com/docker/docker/container"
	"gotest.tools/v3/assert"
	is "gotest.tools/v3/assert/cmp"
)

func newDaemonWithTmpRoot(t *testing.T) (*Daemon, func()) {
	tmp, err := os.MkdirTemp("", "docker-daemon-unix-test-")
	assert.NilError(t, err)
	d := &Daemon{
		repository: tmp,
		root:       tmp,
	}
	d.containers = container.NewMemoryStore()
	return d, func() { os.RemoveAll(tmp) }
}

func newContainerWithState(state *container.State) *container.Container {
	return &container.Container{
		ID:     "test",
		State:  state,
		Config: &containertypes.Config{},
	}
}

// TestContainerDelete tests that a useful error message and instructions is
// given when attempting to remove a container (#30842)
func TestContainerDelete(t *testing.T) {
	tt := []struct {
		errMsg        string
		fixMsg        string
		initContainer func() *container.Container
	}{
		// a paused container
		{
			errMsg: "cannot remove a paused container",
			fixMsg: "Unpause and then stop the container before attempting removal or force remove",
			initContainer: func() *container.Container {
				return newContainerWithState(&container.State{Paused: true, Running: true})
			}},
		// a restarting container
		{
			errMsg: "cannot remove a restarting container",
			fixMsg: "Stop the container before attempting removal or force remove",
			initContainer: func() *container.Container {
				c := newContainerWithState(container.NewState())
				c.SetRunning(nil, nil, true)
				c.SetRestarting(&container.ExitStatus{})
				return c
			}},
		// a running container
		{
			errMsg: "cannot remove a running container",
			fixMsg: "Stop the container before attempting removal or force remove",
			initContainer: func() *container.Container {
				return newContainerWithState(&container.State{Running: true})
			}},
	}

	for _, te := range tt {
		c := te.initContainer()
		d, cleanup := newDaemonWithTmpRoot(t)
		defer cleanup()
		d.containers.Add(c.ID, c)

		err := d.ContainerRm(c.ID, &types.ContainerRmConfig{ForceRemove: false})
		assert.Check(t, is.ErrorContains(err, te.errMsg))
		assert.Check(t, is.ErrorContains(err, te.fixMsg))
	}
}

func TestContainerDoubleDelete(t *testing.T) {
	c := newContainerWithState(container.NewState())

	// Mark the container as having a delete in progress
	c.SetRemovalInProgress()

	d, cleanup := newDaemonWithTmpRoot(t)
	defer cleanup()
	d.containers.Add(c.ID, c)

	// Try to remove the container when its state is removalInProgress.
	// It should return an error indicating it is under removal progress.
	err := d.ContainerRm(c.ID, &types.ContainerRmConfig{ForceRemove: true})
	assert.Check(t, is.ErrorContains(err, fmt.Sprintf("removal of container %s is already in progress", c.ID)))
}


text:
All notable changes to this project will be documented in this file.

## [Unreleased]
### Added
- Added methods to set typing indicators `$botman->types()` and `$botman->typesAndWaits(2);`.
- Added api.ai middleware.
- Added additional parameters to `$botman->say` method.
- Added ability to load command-specific middleware:
```php
$bot->hears('foo', function($bot){})->middleware(new TestMiddleware());
```
- Added ability to listen only on specific drivers or channels.
- Added `repeat()` method to conversation objects to repeat the last asked question.
- [SlackDriver, SlackRTMDriver] added `replyInThread` method for Slacks new [threaded messaging](https://api.slack.com/docs/message-threading#threads_party) feature.
- Added video message to Facebook, BotFramework and Telegram drivers.
- Added Facebook [template support](https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template).
- Added `$botman->getUser()` method to retrieve general user information.

### Changed
- Fixed an error that occured when responding to the Facebook driver with thumbs up.
- Fixed SlackRTM driver to respond using the RTM API (Fixes issues #99 and #67).
- Moved listening to Facebook Postback payloads into a separate driver (FacebookPostbackDriver) so it does not interfere with normal user text
- Correctly handle Skype group chats #128
- Telegram - Fixed empty button callback payload #138
- Telegram - Fixed questions not working when the message type is an entity (url, email, etc) #139
- The MiddlewareInterface now uses the DriverInterface instead of the abstract Driver class

### Removed
- Removed ability to only listen to direct messages / public channels as this was a relic of the old `slackbot` package.

## [1.3.0]
### Added
- Added WeChat messaging driver.
- Added BotMan state methods to store user, channel or driver related data.
    - `$botman->userStorage()`
    - `$botman->channelStorage()`
    - `$botman->driverStorage()`

### Changed
- Forced opis/closure `$this` scope serialization.

## [1.2.2]
### Added
- Added support for Slack slash commands. Just hear for the complete slash command `$bot->hears('/command foo', ...`.

### Changed
- Fixed an error when trying to originate a message using a specific driver name (Issue #70).

## [1.2.1]
### Added
- Added support for Microsoft Bot Framework Web Chat

## [1.2.0]
### Added
- Added the `SlackRTMDriver` to make use of the Slack Realtime API.
- Added a new `Message` class to compose messages with images.
- Image support is available for these drivers:
    - Facebook
    - Telegram
    - Slack
    - Microsoft Bot Framework

### Changed
- Middleware classes now receive a third parameter `$regexMatched` inside the `isMessageMatching` method. You can use
this method to determine if the regular expression was also matched, in case you do not want to replace the complete
`hears` logic, but only add custom logic to it. **Note:** This will require you to modify your custom middleware classes.

## [1.1.1]
### Changed
- Fixed a bug where middleware `isMessageMatching` of `false` would still match the message.

## [1.1.0]
### Added
- The `hears` method can now handle `ClassName@method` syntax.

### Changed
- Fixed a bug in combination with middleware classes and regular expression matches

## [1.0.1]
### Added
- Added `send` method to BotMan, to allow originating messages

### Changed
- The `hears` regular expression now checks for the start of the string https://github.com/mpociot/botman/issues/52

### Changed

## [1.0.0] - 2016-12-08
- Initial release


text:
#include <boost/regex.hpp>
#include <boost/range/concepts.hpp>

template <class T>
void use_val(const T&){}

template <class T>
void check()
{
   BOOST_CONCEPT_ASSERT((boost::ForwardRangeConcept<T>));
   BOOST_CONCEPT_ASSERT((boost_concepts::ReadableIteratorConcept<typename boost::range_iterator<T>::type>));
   BOOST_CONCEPT_ASSERT((boost_concepts::RandomAccessTraversalConcept<typename boost::range_iterator<T>::type>));

#ifndef BOOST_NO_CXX11_RANGE_BASED_FOR
   const T val;
   for(auto item : val)
   {
      use_val(item);
   }
#endif
}

int main()
{
   check<boost::smatch>();
   check<boost::cmatch>();

   check <boost::sub_match<const char*> >();
   return 0;
}


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

import findBlockType from '../util/findBlockType';

import Node from './nodes/Node';
import SvgLinks from './SvgLinks';

import {
    blockHeight,
    blockWidth,
    blockMargin,
    blockVerticalSeparation,
    blockHorizontalSeparation,
    portSize
} from '../constants';
import placeNodes from '../util/placeNodes';
import {selectLink} from '../actions';
import {deleteNode, deleteLink} from '../larissa/redux';
import portSeparation from '../util/portSeparation';

@connect((state) => {
    return {
        blockTypes: state.blockTypes,
        subgraphs: placeNodes(state.pipeline.graph),
        selectedNode: state.pipelineUI.selectedNode,
        selectedLink: state.pipelineUI.selectedLink,
    };
}, {
    deleteNode,
    deleteLink,
    selectLink
})
export default class Pipeline extends Component {
    render() {
        const subgraphs = this.props.subgraphs;
        const blockTypes = this.props.blockTypes;
        if (!subgraphs) return null;
        let verticalOffset = 0;
        const nodes = [];
        const lines = [];
        const placementInfo = new Map();
        for (const graph of subgraphs) {
            const widths = {};
            for (const level of graph.levels) {
                widths[level[0]] = {total: level[1], current: level[1]};
            }
            for (const [id, info] of graph.nodes) {
                const widthObj = widths[info.level];
                const width = widthObj.current--;
                let padding = 0;
                if (graph.maxWidth > widthObj.total) {
                    padding = Math.round((getHeight(graph.maxWidth) - getHeight(widthObj.total)) / 2);
                }

                const left = (graph.totalLevels - info.level) * (blockWidth + blockHorizontalSeparation);
                const top = (width - 1) * (blockHeight + blockVerticalSeparation) + padding + verticalOffset;

                nodes.push(<Node
                    key={id}
                    node={id}
                    left={left}
                    top={top}
                    selected={this.props.selectedNode === id}
                />);

                const startNode = info.node;
                const startInfo = {left, top, node: info.node};

                for (const connection of info.connected) {
                    const endInfo = placementInfo.get(connection.node);
                    const endNode = endInfo.node;
                    const outPorts = getPorts(startNode, 'outputs', blockTypes);
                    const outSeparation = portSeparation(outPorts.length);
                    const inPorts = getPorts(endNode, 'inputs', blockTypes);
                    const inSeparation = portSeparation(inPorts.length);
                    for (const [fromPort, toPort] of connection.connections) {
                        const fromIndex = getIndex(fromPort, outPorts);
                        const toIndex = getIndex(toPort, inPorts);
                        const line = [
                            [
                                left + blockWidth + blockMargin + portSize - 1,
                                top + outSeparation[fromIndex] + blockMargin + portSize / 2 + 0.5
                            ],
                            [
                                endInfo.left + blockMargin - portSize + 1,
                                endInfo.top + inSeparation[toIndex] + blockMargin + portSize / 2 + 0.5
                            ]
                        ];
                        lines.push({
                            key: `${startNode.id}_${endNode.id}_${fromPort}_${toPort}`,
                            line
                        });
                    }
                }

                placementInfo.set(id, startInfo);
            }
            verticalOffset += (graph.maxWidth * blockHeight) + blockVerticalSeparation;
        }
        return (
            <div style={{position: 'relative', height: '100%'}}>
                <SvgLinks lines={lines} onClick={this.props.selectLink} selected={this.props.selectedLink} />
                {nodes}
            </div>
        );
    }

    @keydown('delete')
    deleteKeyPressed() {
        if (this.props.selectedNode) {
            this.props.deleteNode(this.props.selectedNode);
        } else if (this.props.selectedLink) {
            this.props.deleteLink(this.props.selectedLink);
        }
    }
}

function getHeight(nNodes) {
    return nNodes * blockHeight + (nNodes - 1) * blockVerticalSeparation;
}

function getPorts(node, type, blockTypes) {
    if (node.kind === 'block') {
        return findBlockType(blockTypes, node.type)[type];
    } else if (node.kind === 'pipeline' || node.kind === 'map-loop') {
        return node[type];
    } else {
        throw new Error('unexpected node kind: ' + node.kind);
    }
}

function getIndex(which, ports) {
    for (let i = 0; i < ports.length; i++) {
        if (ports[i].name === which) return i;
    }
    throw new Error('did not find port index');
}


text:
from heat.engine import clients
from heat.engine.resources.neutron import neutron
from heat.engine import constraints
from heat.engine import properties

if clients.neutronclient is not None:
    from neutronclient.common.exceptions import NeutronClientException

from heat.openstack.common import log as logging

logger = logging.getLogger(__name__)

class Firewall(neutron.NeutronResource):
    """
    A resource for the Firewall resource in Neutron FWaaS.
    """

    PROPERTIES = (
        NAME, DESCRIPTION, ADMIN_STATE_UP, FIREWALL_POLICY_ID,
    ) = (
        'name', 'description', 'admin_state_up', 'firewall_policy_id',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        ADMIN_STATE_UP: properties.Schema(
            properties.Schema.BOOLEAN,
            default=True,
            update_allowed=True
        ),
        FIREWALL_POLICY_ID: properties.Schema(
            properties.Schema.STRING,
            required=True,
            update_allowed=True
        ),
    }

    attributes_schema = {
        'name': _('Name for the Firewall.'),
        'description': _('Description of the Firewall.'),
        'admin_state_up': _('The administrative state of the Firewall.'),
        'firewall_policy_id': _('Unique identifier of the FirewallPolicy '
                                'used to  create the Firewall.'),
        'status': _('The status of the Firewall.'),
        'tenant_id': _('Id of the tenant owning the Firewall.'),
        'show': _('All attributes.'),
    }

    update_allowed_keys = ('Properties',)

    def _show_resource(self):
        return self.neutron().show_firewall(self.resource_id)['firewall']

    def handle_create(self):
        props = self.prepare_properties(
            self.properties,
            self.physical_resource_name())
        firewall = self.neutron().create_firewall({'firewall': props})[
            'firewall']
        self.resource_id_set(firewall['id'])

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.neutron().update_firewall(
                self.resource_id, {'firewall': prop_diff})

    def handle_delete(self):
        client = self.neutron()
        try:
            client.delete_firewall(self.resource_id)
        except NeutronClientException as ex:
            self._handle_not_found_exception(ex)
        else:
            return self._delete_task()

class FirewallPolicy(neutron.NeutronResource):
    """
    A resource for the FirewallPolicy resource in Neutron FWaaS.
    """

    PROPERTIES = (
        NAME, DESCRIPTION, SHARED, AUDITED, FIREWALL_RULES,
    ) = (
        'name', 'description', 'shared', 'audited', 'firewall_rules',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        SHARED: properties.Schema(
            properties.Schema.BOOLEAN,
            default=False,
            update_allowed=True
        ),
        AUDITED: properties.Schema(
            properties.Schema.BOOLEAN,
            default=False,
            update_allowed=True
        ),
        FIREWALL_RULES: properties.Schema(
            properties.Schema.LIST,
            required=True,
            update_allowed=True
        ),
    }

    attributes_schema = {
        'name': _('Name for the FirewallPolicy.'),
        'description': _('Description of the FirewallPolicy.'),
        'firewall_rules': _('List of FirewallRules in this FirewallPolicy.'),
        'shared': _('Shared status of this FirewallPolicy.'),
        'audited': _('Audit status of this FirewallPolicy.'),
        'tenant_id': _('Id of the tenant owning the FirewallPolicy.')
    }

    update_allowed_keys = ('Properties',)

    def _show_resource(self):
        return self.neutron().show_firewall_policy(self.resource_id)[
            'firewall_policy']

    def handle_create(self):
        props = self.prepare_properties(
            self.properties,
            self.physical_resource_name())
        firewall_policy = self.neutron().create_firewall_policy(
            {'firewall_policy': props})['firewall_policy']
        self.resource_id_set(firewall_policy['id'])

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.neutron().update_firewall_policy(
                self.resource_id, {'firewall_policy': prop_diff})

    def handle_delete(self):
        client = self.neutron()
        try:
            client.delete_firewall_policy(self.resource_id)
        except NeutronClientException as ex:
            self._handle_not_found_exception(ex)
        else:
            return self._delete_task()

class FirewallRule(neutron.NeutronResource):
    """
    A resource for the FirewallRule resource in Neutron FWaaS.
    """

    PROPERTIES = (
        NAME, DESCRIPTION, SHARED, PROTOCOL, IP_VERSION,
        SOURCE_IP_ADDRESS, DESTINATION_IP_ADDRESS, SOURCE_PORT,
        DESTINATION_PORT, ACTION, ENABLED,
    ) = (
        'name', 'description', 'shared', 'protocol', 'ip_version',
        'source_ip_address', 'destination_ip_address', 'source_port',
        'destination_port', 'action', 'enabled',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        SHARED: properties.Schema(
            properties.Schema.BOOLEAN,
            default=False,
            update_allowed=True
        ),
        PROTOCOL: properties.Schema(
            properties.Schema.STRING,
            constraints=[
                constraints.AllowedValues(['tcp', 'udp', 'icmp', None]),
            ],
            update_allowed=True
        ),
        IP_VERSION: properties.Schema(
            properties.Schema.STRING,
            default='4',
            constraints=[
                constraints.AllowedValues(['4', '6']),
            ],
            update_allowed=True
        ),
        SOURCE_IP_ADDRESS: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        DESTINATION_IP_ADDRESS: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        SOURCE_PORT: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        DESTINATION_PORT: properties.Schema(
            properties.Schema.STRING,
            update_allowed=True
        ),
        ACTION: properties.Schema(
            properties.Schema.STRING,
            default='deny',
            constraints=[
                constraints.AllowedValues(['allow', 'deny']),
            ],
            update_allowed=True
        ),
        ENABLED: properties.Schema(
            properties.Schema.BOOLEAN,
            default=True,
            update_allowed=True
        ),
    }

    attributes_schema = {
        'name': _('Name for the FirewallRule.'),
        'description': _('Description of the FirewallRule.'),
        'firewall_policy_id': _('Unique identifier of the FirewallPolicy to '
                                'which this FirewallRule belongs.'),
        'shared': _('Shared status of this FirewallRule.'),
        'protocol': _('Protocol value for this FirewallRule.'),
        'ip_version': _('Ip_version for this FirewallRule.'),
        'source_ip_address': _('Source ip_address for this FirewallRule.'),
        'destination_ip_address': _('Destination ip_address for this '
                                    'FirewallRule.'),
        'source_port': _('Source port range for this FirewallRule.'),
        'destination_port': _('Destination port range for this FirewallRule.'),
        'action': _('Allow or deny action for this FirewallRule.'),
        'enabled': _('Indicates whether this FirewallRule is enabled or not.'),
        'position': _('Position of the rule within the FirewallPolicy.'),
        'tenant_id': _('Id of the tenant owning the Firewall.')
    }

    update_allowed_keys = ('Properties',)

    def _show_resource(self):
        return self.neutron().show_firewall_rule(
            self.resource_id)['firewall_rule']

    def handle_create(self):
        props = self.prepare_properties(
            self.properties,
            self.physical_resource_name())
        firewall_rule = self.neutron().create_firewall_rule(
            {'firewall_rule': props})['firewall_rule']
        self.resource_id_set(firewall_rule['id'])

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.neutron().update_firewall_rule(
                self.resource_id, {'firewall_rule': prop_diff})

    def handle_delete(self):
        client = self.neutron()
        try:
            client.delete_firewall_rule(self.resource_id)
        except NeutronClientException as ex:
            self._handle_not_found_exception(ex)
        else:
            return self._delete_task()

def resource_mapping():
    if clients.neutronclient is None:
        return {}

    return {
        'OS::Neutron::Firewall': Firewall,
        'OS::Neutron::FirewallPolicy': FirewallPolicy,
        'OS::Neutron::FirewallRule': FirewallRule,
    }


text:
package org.netbeans.modules.liberty.main.nodes;

import org.netbeans.modules.j2ee.deployment.plugins.spi.RegistryNodeFactory;
import org.openide.nodes.Node;
import org.openide.util.Lookup;

public class LibertyRegistryNodeFactory implements RegistryNodeFactory {

    @Override
    public Node getTargetNode(Lookup lookup) {
        return null;
    }

    @Override
    public Node getManagerNode(Lookup lookup) {
        return new LibertyInstanceNode(lookup);
    }

}


text:
In some cases it is required to make online predictions, particularly, with trained XGBoost model. This project is designed to use trained XGBoost model for online predictions for Cython arrays many times faster than with usual XGBoost Scikit-Learn API.

Files description:
* `c_xgb/c_xgb.cpp` - classes for predictions for XGBoost models written in C++
* `c_xgb/c_xgb.h` - header for `c_xgb.cpp`
* `c_xgb/json.cpp`, `c_xgb/json.hpp` - JSON parser taken from https://github.com/nbsdx/SimpleJSON/ and modified
* `c_xgb_test.pyx` - Cython file with tests for CythonXGB
* `setup.py` - setup file for tests compilation
* `c_xgb_test.py` - Python file which runs tests

# Requirements
* Python: 2.7.12
* Cython: 0.25.2
* Numpy: 1.13.0
* Scikit-Learn: 0.18.1
* XGBoost: up-to-day version built from source

# Installation and setup
0. **Note**: current version of XGBoost still has problems with precision of floats in dumped models (https://github.com/dmlc/xgboost/issues/1204).
If your task is sensitive to high floating point precision in features, you can avoid differences in predictions by XGBoost and CythonXGB which may occur because of not enough precision in XGBoost dumps, please, change XGBoost source according to https://github.com/dmlc/xgboost/issues/1204#issuecomment-219892846 and rebuild it.
1. `mkdir trees`
2. Compile Cython module: `python setup.py build_ext --inplace`
3. Run tests: `python c_xgb_test.py`

# CythonXGB usage in Cython files:

1. Extern class from CPP file:
```python
cdef extern from "c_xgb/c_xgb.cpp":
	cdef cppclass CXgboost:
		CXgboost()
		CXgboost(int depth, int n_features, int n_trees_ , int objective_, double base_score_)
		double predict(double *features)
```

2. Train your XGBoost model and dump it:
```python
tree_data = booster.get_dump(dump_format='json')
	cdef i
	for i in xrange(len(tree_data)):
		f = open("trees/tree_%d.json" % i, 'w')
		f.write(tree_data[i])
		f.close()
```

3. After training you can create an instance of CXgboost model:
```python
cdef CXgboost model_c = CXgboost(depth, n_features, n_estimators, 0, base_score)
```

4. To make predictions for one sample:
```python
preds_c_xgb = model_c.predict(x_cy)
```
`x_cy` should be a float cython array with current sample features

# Tests
For tests were generated classification and regression datasets with Scikit-Library, they contain 10000 samples with 20 features.
Predicitons were made for each sample 10 times

*Mean_time_XGBoost* is mean time for prediction for one sample by Scikit-Learn wrapper for XGBoost
*Mean_time_CythonXGB* is mean time for prediction for one sample by CythonXGB

*Acceleration* is calculated as *Mean_time_XGBoost* / *Mean_time_CythonXGB*

Tests are performed on laptop with Intel® Core™ i5-4210U CPU, Ubuntu 16.04

| n_estimators        | max_depth           | objective  | acceleration, times |
| ------------- |:-------------:| -----:| -----:|
| 10      | 5 | "reg:linear" | 461 |
| 10      | 10 | "reg:linear"    | 188   |
| 100      | 5 | "reg:linear" | 49 |
| 100      | 10 | "reg:linear"    | 14   |
| 10 | 5      |    "binary:logistic" | 730 |
| 10 | 10      |    "binary:logistic" | 343 |
| 100 | 5      |    "binary:logistic" | 84 |
| 100 | 10      |    "binary:logistic" | 24 |


text:
package org.apache.pulsar.functions.instance.stats;

import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;

/**
 * Internal representation of Prometheus Collector Registry.
 */
public abstract class FunctionCollectorRegistry extends CollectorRegistry {
    public static FunctionCollectorRegistry getDefaultImplementation() {
        return new FunctionCollectorRegistryImpl();
    }

    /**
     * Register a metric if it does not yet exist.  If it does exist, then return the existing metric.
     * Currently, only needed by the LocalRunner when running in threaded and exposing metrics via a http server.
     * This method helps resolve the conflict in which multiple instances within
     * the LocalRunner process try to register the same metric.
     * @param metricName the name of the metric
     * @param collector the metric object e.g. Count, Gauge, etc.
     * @param <T>
     * @return If the metric with the name `metricName` already exists, return the existing metric object.
     * If not, return null
     */
    public abstract <T extends Collector> T registerIfNotExist(String metricName, T collector);
}


text:
package com.yahoo.vespa.clustercontroller.core;

import java.util.Optional;

public class NodeEvent implements Event {

    private final NodeInfo node;
    private final String description;
    private final long eventTime;
    private final Optional<String> bucketSpace;

    public enum Type {
        REPORTED,
        CURRENT,
        WANTED
    }

    private final Type type;

    private NodeEvent(NodeInfo node, String description, Type type, long currentTime) {
        this.node = node;
        this.description = description;
        this.eventTime = currentTime;
        this.type = type;
        this.bucketSpace = Optional.empty();
    }

    private NodeEvent(NodeInfo node, String bucketSpace, String description, Type type, long currentTime) {
        this.node = node;
        this.description = description;
        this.eventTime = currentTime;
        this.type = type;
        this.bucketSpace = Optional.of(bucketSpace);
    }

    public static NodeEvent forBaseline(NodeInfo node, String description, Type type, long currentTime) {
        return new NodeEvent(node, description, type, currentTime);
    }

    public static NodeEvent forBucketSpace(NodeInfo node, String bucketSpace, String description, Type type, long currentTime) {
        return new NodeEvent(node, bucketSpace, description, type, currentTime);
    }

    public NodeInfo getNode() {
        return node;
    }

    @Override
    public long getTimeMs() {
        return eventTime;
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return "Event: " + getNodeBucketSpaceDescription() + ": " + description;
    }

    private String getNodeBucketSpaceDescription() {
        if (bucketSpace.isPresent()) {
            return node.getNode() + " (" + bucketSpace.get() + ")";
        }
        return node.getNode().toString();
    }

    @Override
    public String getCategory() {
        return type.toString();
    }

    public Type getType() {
        return type;
    }

    public Optional<String> getBucketSpace() {
        return bucketSpace;
    }

}