text:
package com.sequenceiq.mock.swagger.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;

/**
 * Arguments used for disable Sentry HA API call.
 */
@ApiModel(description = "Arguments used for disable Sentry HA API call.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-12-10T21:24:30.629+01:00")

public class ApiDisableSentryHaArgs   {
  @JsonProperty("activeName")
  private String activeName = null;

  public ApiDisableSentryHaArgs activeName(String activeName) {
    this.activeName = activeName;
    return this;
  }

  /**
   * Name of the single role that will remain active after HA is disabled.
   * @return activeName
  **/
  @ApiModelProperty(value = "Name of the single role that will remain active after HA is disabled.")

  public String getActiveName() {
    return activeName;
  }

  public void setActiveName(String activeName) {
    this.activeName = activeName;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ApiDisableSentryHaArgs apiDisableSentryHaArgs = (ApiDisableSentryHaArgs) o;
    return Objects.equals(this.activeName, apiDisableSentryHaArgs.activeName);
  }

  @Override
  public int hashCode() {
    return Objects.hash(activeName);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class ApiDisableSentryHaArgs {\n");

    sb.append("    activeName: ").append(toIndentedString(activeName)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
package com.fasterxml.jackson.databind.util;

import java.io.*;
import java.nio.ByteBuffer;

/**
 * Simple {@link OutputStream} implementation that appends content
 * written in given {@link ByteBuffer} instance.
 */
public class ByteBufferBackedOutputStream extends OutputStream {
    protected final ByteBuffer _b;

    public ByteBufferBackedOutputStream(ByteBuffer buf) { _b = buf; }

    @Override public void write(int b) throws IOException { _b.put((byte) b); }
    @Override public void write(byte[] bytes, int off, int len) throws IOException { _b.put(bytes, off, len); }
}

redpajama_set_name: RedPajamaGithub


text:
class MakeBatterTask < CompositeTask
  def initialize
    super('Make Batter')
    add_task(AddIngredientsTask.new)
    add_task(AddLiquidTask.new)
    add_task(MixingTask.new)
  end
end


text:
const WebSocketServer = require('./util/WebSocketServer.js');
const UUID = require('node-uuid');

const wss = new WebSocketServer({port:9090},{
  'register' : onRegister,
  'discovery' : onDiscovery
});
const helper = require('./util/WebSocketHelpers')();
const containers = {};
const clients = {};

function onRegister(data, ws) {
  var clientID = UUID.v4();
  if (typeof containers[data.container] === 'undefined') {
    containers[data.container] = {};
    containers[data.container].nodes = {};
  }

  containers[data.container].nodes[data.body.name] = {
    client : clientID
  };
  clients[clientID] = ws;

  console.log("Registering new node[%s] for the %s with id %s",data.body.name,data.container,clientID);
  announce(data, ws);
}

function announce(data, ws) {
  container = containers[data.container];

  for (var node in container.nodes) {
    if (container.nodes[node].client.socket !== ws) {
      clients[container.nodes[node].client].sendAsJSON(helper.requestMapping('announcement',data.container,container.nodes));
    }
  }

}

function onUnregister(data, ws) {
  for (var node in containers[data.container].nodes) {
    if (containers[data.container].nodes.hasOwnProperty(node)) {
      if (clients[node.client] == ws) {
        delete clients[node.client];
        delete container[data.container].nodes[node];
      }
    }
  }

}

function onDiscovery(data, ws) {
  var nodes = containers[data.container].nodes;
  if (typeof nodes !== 'undefined') {
      ws.sendAsJSON(helper.requestMapping('discovery',data.container,nodes));
  }
}


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:singleLine="true"
    android:textAllCaps="true"
    android:textColor="@color/background_purple"
    android:background="@android:color/transparent"
    android:textSize="16sp"
    android:id="@+id/section_text"
    android:textStyle="bold" />


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_max_add_66b.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-66b.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: max Set data to the max value for unsigned int
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE190_Integer_Overflow__unsigned_int_max_add_66b_badSink(unsigned int dataArray[])
{
    /* copy data out of dataArray */
    unsigned int data = dataArray[2];
    {
        /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */
        unsigned int result = data + 1;
        printUnsignedLine(result);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE190_Integer_Overflow__unsigned_int_max_add_66b_goodG2BSink(unsigned int dataArray[])
{
    unsigned int data = dataArray[2];
    {
        /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */
        unsigned int result = data + 1;
        printUnsignedLine(result);
    }
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE190_Integer_Overflow__unsigned_int_max_add_66b_goodB2GSink(unsigned int dataArray[])
{
    unsigned int data = dataArray[2];
    /* FIX: Add a check to prevent an overflow from occurring */
    if (data < UINT_MAX)
    {
        unsigned int result = data + 1;
        printUnsignedLine(result);
    }
    else
    {
        printLine("data value is too large to perform arithmetic safely.");
    }
}

#endif /* OMITGOOD */


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Infrastructure.Validation;

namespace Squidex.Areas.Api.Controllers.News.Models;

public class FeaturesDto
{
    /// <summary>
    /// The latest features.
    /// </summary>
    [LocalizedRequired]
    public List<FeatureDto> Features { get; } = new List<FeatureDto>();

    /// <summary>
    /// The recent version.
    /// </summary>
    public int Version { get; set; }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
 Describes an elastic inference accelerator.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API LaunchTemplateElasticInferenceAcceleratorResponse
  {
  public:
    LaunchTemplateElasticInferenceAcceleratorResponse();
    LaunchTemplateElasticInferenceAcceleratorResponse(const Aws::Utils::Xml::XmlNode& xmlNode);
    LaunchTemplateElasticInferenceAcceleratorResponse& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline LaunchTemplateElasticInferenceAcceleratorResponse& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline LaunchTemplateElasticInferenceAcceleratorResponse& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
 The type of elastic inference accelerator. The possible values are
     * eia1.medium, eia1.large, and eia1.xlarge.

     */
    inline LaunchTemplateElasticInferenceAcceleratorResponse& WithType(const char* value) { SetType(value); return *this;}

    /**
     *
 The number of elastic inference accelerators to attach to the instance.

     *
Default: 1

     */
    inline int GetCount() const{ return m_count; }

    /**
     *
 The number of elastic inference accelerators to attach to the instance.

     *
Default: 1

     */
    inline bool CountHasBeenSet() const { return m_countHasBeenSet; }

    /**
     *
 The number of elastic inference accelerators to attach to the instance.

     *
Default: 1

     */
    inline void SetCount(int value) { m_countHasBeenSet = true; m_count = value; }

    /**
     *
 The number of elastic inference accelerators to attach to the instance.

     *
Default: 1

     */
    inline LaunchTemplateElasticInferenceAcceleratorResponse& WithCount(int value) { SetCount(value); return *this;}

  private:

    Aws::String m_type;
    bool m_typeHasBeenSet = false;

    int m_count;
    bool m_countHasBeenSet = false;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See https://javaee.github.io/jaxb-v2/
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2022.06.28 at 02:49:33 PM PDT
//

package com.intuit.ipp.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.intuit.sb.cdm.util.v3.DateAdapter;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.HashCode2;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 * Describes Budget specifications
 *
 *
Java class for Budget complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Budget">
 *   <complexContent>
 *     <extension base="{http://schema.intuit.com/finance/v3}IntuitEntity">
 *       <sequence>
 *         <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="StartDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
 *         <element name="EndDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
 *         <element name="BudgetType" type="{http://schema.intuit.com/finance/v3}BudgetTypeEnum" minOccurs="0"/>
 *         <element name="BudgetEntryType" type="{http://schema.intuit.com/finance/v3}BudgetEntryTypeEnum" minOccurs="0"/>
 *         <element name="Active" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="BudgetDetail" type="{http://schema.intuit.com/finance/v3}BudgetDetail" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Budget", propOrder = {
    "name",
    "startDate",
    "endDate",
    "budgetType",
    "budgetEntryType",
    "active",
    "budgetDetail"
})
public class Budget
    extends IntuitEntity
    implements Serializable, Equals2, HashCode2
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "Name")
    protected String name;
    @XmlElement(name = "StartDate", type = String.class)
    @XmlJavaTypeAdapter(DateAdapter.class)
    @XmlSchemaType(name = "date")
    protected Date startDate;
    @XmlElement(name = "EndDate", type = String.class)
    @XmlJavaTypeAdapter(DateAdapter.class)
    @XmlSchemaType(name = "date")
    protected Date endDate;
    @XmlElement(name = "BudgetType")
    @XmlSchemaType(name = "string")
    protected BudgetTypeEnum budgetType;
    @XmlElement(name = "BudgetEntryType")
    @XmlSchemaType(name = "string")
    protected BudgetEntryTypeEnum budgetEntryType;
    @XmlElement(name = "Active")
    protected Boolean active;
    @XmlElement(name = "BudgetDetail")
    protected List<BudgetDetail> budgetDetail;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the startDate property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public Date getStartDate() {
        return startDate;
    }

    /**
     * Sets the value of the startDate property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStartDate(Date value) {
        this.startDate = value;
    }

    /**
     * Gets the value of the endDate property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public Date getEndDate() {
        return endDate;
    }

    /**
     * Sets the value of the endDate property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEndDate(Date value) {
        this.endDate = value;
    }

    /**
     * Gets the value of the budgetType property.
     *
     * @return
     *     possible object is
     *     {@link BudgetTypeEnum }
     *
     */
    public BudgetTypeEnum getBudgetType() {
        return budgetType;
    }

    /**
     * Sets the value of the budgetType property.
     *
     * @param value
     *     allowed object is
     *     {@link BudgetTypeEnum }
     *
     */
    public void setBudgetType(BudgetTypeEnum value) {
        this.budgetType = value;
    }

    /**
     * Gets the value of the budgetEntryType property.
     *
     * @return
     *     possible object is
     *     {@link BudgetEntryTypeEnum }
     *
     */
    public BudgetEntryTypeEnum getBudgetEntryType() {
        return budgetEntryType;
    }

    /**
     * Sets the value of the budgetEntryType property.
     *
     * @param value
     *     allowed object is
     *     {@link BudgetEntryTypeEnum }
     *
     */
    public void setBudgetEntryType(BudgetEntryTypeEnum value) {
        this.budgetEntryType = value;
    }

    /**
     * Gets the value of the active property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isActive() {
        return active;
    }

    /**
     * Sets the value of the active property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setActive(Boolean value) {
        this.active = value;
    }

    /**
     * Gets the value of the budgetDetail property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the budgetDetail property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getBudgetDetail().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link BudgetDetail }
     *
     *
     */
    public List<BudgetDetail> getBudgetDetail() {
        if (budgetDetail == null) {
            budgetDetail = new ArrayList<BudgetDetail>();
        }
        return this.budgetDetail;
    }

    /**
     * Sets the value of the budgetDetail property.
     *
     * @param budgetDetail
     *     allowed object is
     *     {@link BudgetDetail }
     *
     */
    public void setBudgetDetail(List<BudgetDetail> budgetDetail) {
        this.budgetDetail = budgetDetail;
    }

    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
        if ((object == null)||(this.getClass()!= object.getClass())) {
            return false;
        }
        if (this == object) {
            return true;
        }
        if (!super.equals(thisLocator, thatLocator, object, strategy)) {
            return false;
        }
        final Budget that = ((Budget) object);
        {
            String lhsName;
            lhsName = this.getName();
            String rhsName;
            rhsName = that.getName();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "name", lhsName), LocatorUtils.property(thatLocator, "name", rhsName), lhsName, rhsName, (this.name!= null), (that.name!= null))) {
                return false;
            }
        }
        {
            Date lhsStartDate;
            lhsStartDate = this.getStartDate();
            Date rhsStartDate;
            rhsStartDate = that.getStartDate();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "startDate", lhsStartDate), LocatorUtils.property(thatLocator, "startDate", rhsStartDate), lhsStartDate, rhsStartDate, (this.startDate!= null), (that.startDate!= null))) {
                return false;
            }
        }
        {
            Date lhsEndDate;
            lhsEndDate = this.getEndDate();
            Date rhsEndDate;
            rhsEndDate = that.getEndDate();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "endDate", lhsEndDate), LocatorUtils.property(thatLocator, "endDate", rhsEndDate), lhsEndDate, rhsEndDate, (this.endDate!= null), (that.endDate!= null))) {
                return false;
            }
        }
        {
            BudgetTypeEnum lhsBudgetType;
            lhsBudgetType = this.getBudgetType();
            BudgetTypeEnum rhsBudgetType;
            rhsBudgetType = that.getBudgetType();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "budgetType", lhsBudgetType), LocatorUtils.property(thatLocator, "budgetType", rhsBudgetType), lhsBudgetType, rhsBudgetType, (this.budgetType!= null), (that.budgetType!= null))) {
                return false;
            }
        }
        {
            BudgetEntryTypeEnum lhsBudgetEntryType;
            lhsBudgetEntryType = this.getBudgetEntryType();
            BudgetEntryTypeEnum rhsBudgetEntryType;
            rhsBudgetEntryType = that.getBudgetEntryType();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "budgetEntryType", lhsBudgetEntryType), LocatorUtils.property(thatLocator, "budgetEntryType", rhsBudgetEntryType), lhsBudgetEntryType, rhsBudgetEntryType, (this.budgetEntryType!= null), (that.budgetEntryType!= null))) {
                return false;
            }
        }
        {
            Boolean lhsActive;
            lhsActive = this.isActive();
            Boolean rhsActive;
            rhsActive = that.isActive();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "active", lhsActive), LocatorUtils.property(thatLocator, "active", rhsActive), lhsActive, rhsActive, (this.active!= null), (that.active!= null))) {
                return false;
            }
        }
        {
            List<BudgetDetail> lhsBudgetDetail;
            lhsBudgetDetail = (((this.budgetDetail!= null)&&(!this.budgetDetail.isEmpty()))?this.getBudgetDetail():null);
            List<BudgetDetail> rhsBudgetDetail;
            rhsBudgetDetail = (((that.budgetDetail!= null)&&(!that.budgetDetail.isEmpty()))?that.getBudgetDetail():null);
            if (!strategy.equals(LocatorUtils.property(thisLocator, "budgetDetail", lhsBudgetDetail), LocatorUtils.property(thatLocator, "budgetDetail", rhsBudgetDetail), lhsBudgetDetail, rhsBudgetDetail, ((this.budgetDetail!= null)&&(!this.budgetDetail.isEmpty())), ((that.budgetDetail!= null)&&(!that.budgetDetail.isEmpty())))) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(Object object) {
        final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE;
        return equals(null, null, object, strategy);
    }

    public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
        int currentHashCode = super.hashCode(locator, strategy);
        {
            String theName;
            theName = this.getName();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "name", theName), currentHashCode, theName, (this.name!= null));
        }
        {
            Date theStartDate;
            theStartDate = this.getStartDate();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "startDate", theStartDate), currentHashCode, theStartDate, (this.startDate!= null));
        }
        {
            Date theEndDate;
            theEndDate = this.getEndDate();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "endDate", theEndDate), currentHashCode, theEndDate, (this.endDate!= null));
        }
        {
            BudgetTypeEnum theBudgetType;
            theBudgetType = this.getBudgetType();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "budgetType", theBudgetType), currentHashCode, theBudgetType, (this.budgetType!= null));
        }
        {
            BudgetEntryTypeEnum theBudgetEntryType;
            theBudgetEntryType = this.getBudgetEntryType();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "budgetEntryType", theBudgetEntryType), currentHashCode, theBudgetEntryType, (this.budgetEntryType!= null));
        }
        {
            Boolean theActive;
            theActive = this.isActive();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "active", theActive), currentHashCode, theActive, (this.active!= null));
        }
        {
            List<BudgetDetail> theBudgetDetail;
            theBudgetDetail = (((this.budgetDetail!= null)&&(!this.budgetDetail.isEmpty()))?this.getBudgetDetail():null);
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "budgetDetail", theBudgetDetail), currentHashCode, theBudgetDetail, ((this.budgetDetail!= null)&&(!this.budgetDetail.isEmpty())));
        }
        return currentHashCode;
    }

    public int hashCode() {
        final HashCodeStrategy2 strategy = JAXBHashCodeStrategy.INSTANCE;
        return this.hashCode(null, strategy);
    }

}


text:
using AllReady.Features.Notifications;
using AllReady.Models;
using MediatR;
using Microsoft.Data.Entity;
using System.Collections.Generic;
using System.Linq;

namespace AllReady.Areas.Admin.Features.Activities
{
    public class MessageActivityVolunteersCommandHandler : RequestHandler<MessageActivityVolunteersCommand>
    {
        private AllReadyContext _context;
        private IMediator _bus;

        public MessageActivityVolunteersCommandHandler(AllReadyContext context, IMediator bus)
        {
            _context = context;
            _bus = bus;
        }

        protected override void HandleCore(MessageActivityVolunteersCommand message)
        {
            var users =
                _context.ActivitySignup.AsNoTracking()
                .Include(a => a.User)
                .Where(a => a.Activity.Id == message.Model.ActivityId).ToList();

            // send all notifications to the queue
            var smsRecipients = new List<string>();
            var emailRecipients = new List<string>();

            smsRecipients.AddRange(users.Where(u => u.User.PhoneNumberConfirmed).Select(v => v.User.PhoneNumber));
            emailRecipients.AddRange(users.Where(u => u.User.EmailConfirmed).Select(v => v.User.Email));

            var command = new NotifyVolunteersCommand
            {
                // todo: what information do we add about the task?
                // todo: should we use a template from the email service provider?
                // todo: what about non-English volunteers?
                ViewModel = new NotifyVolunteersViewModel
                {
                    SmsMessage = message.Model.Message,
                    SmsRecipients = smsRecipients,
                    EmailMessage = message.Model.Message,
                    HtmlMessage = message.Model.Message,
                    EmailRecipients = emailRecipients,
                    Subject = message.Model.Subject
                }
            };

            _bus.Send(command);
        }
    }
}


text:
on     = -> light { light.on = true  }
off    = -> light { light.on = false }

dark   = -> light { light.brightness = 0   }
dim    = -> light { light.brightness = 125 }
bright = -> light { light.brightness = 255 }

white  = -> light { light.saturation = 0   }
color  = -> light { light.saturation = 255 }
red    = -> light { color.call(light); light.hue =      0 }
orange = -> light { color.call(light); light.hue =  7_000 }
yellow = -> light { color.call(light); light.hue = 15_000 }
green  = -> light { color.call(light); light.hue = 25_000 }
blue   = -> light { color.call(light); light.hue = 47_000 }
violet = -> light { color.call(light); light.hue = 50_000 }
pink   = -> light { color.call(light); light.hue = 55_000 }


text:
require "sequel"
require "models/query"
require "csv"
require "zlib"

class QueryResult < Sequel::Model
  one_to_one :query, key: :query_id
  unrestrict_primary_key

  def rows
    return [] unless results_path && File.file?(results_path)
    return [] unless rows_count < 1000
    Zlib::GzipReader.open(results_path) do |io|
      CSV.new(io).read
    end
  end

  def query_title
    query.title
  end

  def query_author
    query.author
  end
end


text:
<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:clickable="false"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <EditText
       android:id="@+id/pnr_number"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_weight="2"
       android:hint="@string/pnr_number"
       android:imeOptions="actionGo"
       android:inputType="number" />

    <Button
        android:id="@+id/get_status"
       	android:layout_width="0dp"
       	android:layout_weight="1"
       	android:layout_height="wrap_content"
       	android:text="@string/get_status" />

</LinearLayout>


text:
package google

import (
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccApiGatewayGatewayIamBindingGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/apigateway.viewer",
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProvidersOiCS,
		Steps: []resource.TestStep{
			{
				Config: testAccApiGatewayGatewayIamBinding_basicGenerated(context),
			},
			{
				// Test Iam Binding update
				Config: testAccApiGatewayGatewayIamBinding_updateGenerated(context),
			},
		},
	})
}

func TestAccApiGatewayGatewayIamMemberGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/apigateway.viewer",
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProvidersOiCS,
		Steps: []resource.TestStep{
			{
				// Test Iam Member creation (no update for member, no need to test)
				Config: testAccApiGatewayGatewayIamMember_basicGenerated(context),
			},
		},
	})
}

func TestAccApiGatewayGatewayIamPolicyGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/apigateway.viewer",
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProvidersOiCS,
		Steps: []resource.TestStep{
			{
				Config: testAccApiGatewayGatewayIamPolicy_basicGenerated(context),
			},
			{
				Config: testAccApiGatewayGatewayIamPolicy_emptyBinding(context),
			},
		},
	})
}

func testAccApiGatewayGatewayIamMember_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_api_gateway_api" "api_gw" {
  provider = google-beta
  api_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_api_config" "api_gw" {
  provider = google-beta
  api = google_api_gateway_api.api_gw.api_id
  api_config_id = "config%{random_suffix}"

  openapi_documents {
    document {
      path = "spec.yaml"
      contents = filebase64("test-fixtures/apigateway/openapi.yaml")
    }
  }
  lifecycle {
    create_before_destroy = true
  }
}

resource "google_api_gateway_gateway" "api_gw" {
  provider = google-beta
  api_config = google_api_gateway_api_config.api_gw.id
  gateway_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_gateway_iam_member" "foo" {
  provider = google-beta
  project = google_api_gateway_gateway.api_gw.project
  region = google_api_gateway_gateway.api_gw.region
  gateway = google_api_gateway_gateway.api_gw.gateway_id
  role = "%{role}"
  member = "user:admin@hashicorptest.com"
}
`, context)
}

func testAccApiGatewayGatewayIamPolicy_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_api_gateway_api" "api_gw" {
  provider = google-beta
  api_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_api_config" "api_gw" {
  provider = google-beta
  api = google_api_gateway_api.api_gw.api_id
  api_config_id = "config%{random_suffix}"

  openapi_documents {
    document {
      path = "spec.yaml"
      contents = filebase64("test-fixtures/apigateway/openapi.yaml")
    }
  }
  lifecycle {
    create_before_destroy = true
  }
}

resource "google_api_gateway_gateway" "api_gw" {
  provider = google-beta
  api_config = google_api_gateway_api_config.api_gw.id
  gateway_id = "tf-test-api-gw%{random_suffix}"
}

data "google_iam_policy" "foo" {
  provider = google-beta
  binding {
    role = "%{role}"
    members = ["user:admin@hashicorptest.com"]
  }
}

resource "google_api_gateway_gateway_iam_policy" "foo" {
  provider = google-beta
  project = google_api_gateway_gateway.api_gw.project
  region = google_api_gateway_gateway.api_gw.region
  gateway = google_api_gateway_gateway.api_gw.gateway_id
  policy_data = data.google_iam_policy.foo.policy_data
}
`, context)
}

func testAccApiGatewayGatewayIamPolicy_emptyBinding(context map[string]interface{}) string {
	return Nprintf(`
resource "google_api_gateway_api" "api_gw" {
  provider = google-beta
  api_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_api_config" "api_gw" {
  provider = google-beta
  api = google_api_gateway_api.api_gw.api_id
  api_config_id = "config%{random_suffix}"

  openapi_documents {
    document {
      path = "spec.yaml"
      contents = filebase64("test-fixtures/apigateway/openapi.yaml")
    }
  }
  lifecycle {
    create_before_destroy = true
  }
}

resource "google_api_gateway_gateway" "api_gw" {
  provider = google-beta
  api_config = google_api_gateway_api_config.api_gw.id
  gateway_id = "tf-test-api-gw%{random_suffix}"
}

data "google_iam_policy" "foo" {
  provider = google-beta
}

resource "google_api_gateway_gateway_iam_policy" "foo" {
  provider = google-beta
  project = google_api_gateway_gateway.api_gw.project
  region = google_api_gateway_gateway.api_gw.region
  gateway = google_api_gateway_gateway.api_gw.gateway_id
  policy_data = data.google_iam_policy.foo.policy_data
}
`, context)
}

func testAccApiGatewayGatewayIamBinding_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_api_gateway_api" "api_gw" {
  provider = google-beta
  api_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_api_config" "api_gw" {
  provider = google-beta
  api = google_api_gateway_api.api_gw.api_id
  api_config_id = "config%{random_suffix}"

  openapi_documents {
    document {
      path = "spec.yaml"
      contents = filebase64("test-fixtures/apigateway/openapi.yaml")
    }
  }
  lifecycle {
    create_before_destroy = true
  }
}

resource "google_api_gateway_gateway" "api_gw" {
  provider = google-beta
  api_config = google_api_gateway_api_config.api_gw.id
  gateway_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_gateway_iam_binding" "foo" {
  provider = google-beta
  project = google_api_gateway_gateway.api_gw.project
  region = google_api_gateway_gateway.api_gw.region
  gateway = google_api_gateway_gateway.api_gw.gateway_id
  role = "%{role}"
  members = ["user:admin@hashicorptest.com"]
}
`, context)
}

func testAccApiGatewayGatewayIamBinding_updateGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_api_gateway_api" "api_gw" {
  provider = google-beta
  api_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_api_config" "api_gw" {
  provider = google-beta
  api = google_api_gateway_api.api_gw.api_id
  api_config_id = "config%{random_suffix}"

  openapi_documents {
    document {
      path = "spec.yaml"
      contents = filebase64("test-fixtures/apigateway/openapi.yaml")
    }
  }
  lifecycle {
    create_before_destroy = true
  }
}

resource "google_api_gateway_gateway" "api_gw" {
  provider = google-beta
  api_config = google_api_gateway_api_config.api_gw.id
  gateway_id = "tf-test-api-gw%{random_suffix}"
}

resource "google_api_gateway_gateway_iam_binding" "foo" {
  provider = google-beta
  project = google_api_gateway_gateway.api_gw.project
  region = google_api_gateway_gateway.api_gw.region
  gateway = google_api_gateway_gateway.api_gw.gateway_id
  role = "%{role}"
  members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"]
}
`, context)
}


text:
[![Issue Stats](http://issuestats.com/github/fsprojects/SQLProvider/badge/issue)](http://issuestats.com/github/fsprojects/SQLProvider)
[![Issue Stats](http://issuestats.com/github/fsprojects/SQLProvider/badge/pr)](http://issuestats.com/github/fsprojects/SQLProvider)

# SQLProvider [![NuGet Status](http://img.shields.io/nuget/v/SQLProvider.svg?style=flat)](https://www.nuget.org/packages/SQLProvider/)

A general SQL database type provider, supporting LINQ queries, schema exploration, individuals, CRUD operations and much more besides. The provider currently supports MS SQL Server, SQLite, PostgreSQL, Oracle, MySQL, ODBC and MS Access.

## Documentation

Core documentation and samples can be found at the [SQLProvider home page](http://fsprojects.github.io/SQLProvider/). This documentation is generated from [docs/content/](https://github.com/fsprojects/SQLProvider/tree/master/docs/content), so please feel free to submit a pull request if you have fixed typos are added additional samples and documentation!

## Building

* Mono: Run *build.sh*  [![Mono build status](https://travis-ci.org/fsprojects/SQLProvider.png)](https://travis-ci.org/fsprojects/SQLProvider)
* Windows: Run *build.cmd* [![Build status](https://ci.appveyor.com/api/projects/status/68u9qx5vw1uf5opl/branch/master?svg=true)](https://ci.appveyor.com/project/colinbull/sqlprovider/branch/master)

## Known issues

- Database vendors other than MS SQL Server use dynamic assembly loading.  This may cause some security problems depending on your system's configuration and which version of the .NET framework you are using.  If you encounter problems loading dynamic assemblies, they can likely be resolved by applying the following element into the configuration files of  fsi.exe, devenv.exe and your program or the program using your library : http://msdn.microsoft.com/en-us/library/dd409252(VS.100).aspx

## Disclaimer

This is an alpha build and as such may have problems yet undetected. This is not suitable for production use.  I am not responsible for any inadvertent damage and destruction caused by this software.

Always fully assert the results of your queries!

## Maintainer(s)

- [@pezipink](https://github.com/pezipink)
- [@colinbull](https://github.com/colinbull)

The default maintainer account for projects under "fsprojects" is [@fsprojectsgit](https://github.com/fsprojectsgit) - F# Community Project Incubation Space (repo management)


text:
<?php

namespace Main;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getServiceConfig(){

        return array(
            'factories' => array(
                'Zend\Authentication\AuthenticationService' => function($serviceManager){
                    return $serviceManager->get('doctrine.authenticationservice.orm_default');
                }
            )
        );
    }

    /**
     * Executa no bootstrap do módulo
     *
     * @param MvcEvent $e
     */
    public function onBootstrap($e){
        /** @var \Zend\ModuleManager\ModuleManager $moduleManager */
        $moduleManager = $e->getApplication()->getServiceManager()->get('modulemanager');
        /** @var \Zend\ModuleManager\ModuleManager $sharedEvents */
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();

        //adicionaeventos ao modulo
        $sharedEvents->attach('Zend\Mvc\Controller\AbstractActionController', \Zend\Mvc\MvcEvent::EVENT_DISPATCH,array($this, 'mvcPreDispatch'),100);

    }

    /**
     * Verifica se precisa fazer a autorizacao do acesso
     * @param MvcEvent $event Evento
     * @return boolean
     */
    public function mvcPreDispatch($event){

        $di = $event->getTarget()->getServiceLocator();
        $routeMatch = $event->getRouteMatch();
        $moduleName = $routeMatch->getParam('module');
        $controllerName = $routeMatch->getParam('controller');
        $actionName = $routeMatch->getParam('action');
        $authService = $di->get('Admin\Service\Auth');

        if(!$authService->authorize($moduleName,$controllerName,$actionName)){
            throw new \Exception('Voce não tem permissao para acessar esse recurso!');
        }

        return true;

    }

   }


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CollisionTest.Views
{
    /// <summary>
    /// Interaction logic for SquareItemView.xaml
    /// </summary>
    public partial class SquareItemView : UserControl
    {
        public SquareItemView()
        {
            InitializeComponent();
        }
    }
}


text:
Poziomy

To pole mo¿e zawieraæ kilka znaków okre¶laj±cych ró¿ne poziomy uruchomienia
systemu. Na przyk³ad, <tt>123</tt> okre¶la, ¿e proces powinien byæ
uruchomiony na poziomach 1, 2 i 3.

Gdy poziom uruchomienia systemu ulega zmianie, wszystkie dzia³aj±ce,
a nie wyszczególnione dla nowego poziomu uruchomienia procesy, s±
zabijane. Najpierw poprzez wys³anie do nich sygna³u <tt>SIGTERM</tt>,
a nastêpnie <tt>SIGKILL</tt>.


text:
Relational storage for FHIR resources in PostgreSQL.

Fhirbase implements essential part of FHIR standard directly in postgres.

Fhirbase could be installed in a minutes on top of standard postgresql
with version more than 9.4.
Fhirbase also could be installed on hosted postgres like Amazon RDS and Heroku.

### Why we've started fhirbase?

Our team is mostly polyglot programmers - clojure, ruby, js, sometimes java, c# etc
So the idea was to move most of FHIR implementation inside database for reuse.

Also we know that data is a heart of many applications and postgresql is a perfect
tool to deal with data:

* reuse on diff platforms
* performance, data & logic locality

### Who is an audience of fhirbase?

Fhirbase is designed for development of new applications based on FHIR.

It handles essential part of FHIR standard implementation details and
allows you focus on implementation of buisness features using platform of your choice,
which only has to have a connectors to postgresql.

We alse expect, that for some complicated cases FHIR abstraction layer could be skipped
and you could use SQL directly for analytic, ad-hock queries or batch updates and migrations.

So from some point of view fhirbase is just ordinary (smart) postgresql database.

### Why postgresql?

Postgresql is most advanced opensource database:

* pure open source
* good experience with postgresql in production for a decade
* jsonb - binary json format
* advanced indexing with GIST & GIN (Generalized Search Tree & Generalized Inverted Index)
* extensibility (extensions, different procedural languages etc)

Postgres is a operating system for the data :)

### What parts of FHIR has already been implemented?

 * CRUD
 * history
 * transactions (partially)
 * search

### How fhirbase structured?

* Fhirbase consists of API facade implemented as a set of procedures.
* Reloadable code modules, which make API works
* Schema migrations (which allows update existing instance of fhirbase)
* tables to store resources

### How fhirbase stores resources?

fhirbase stores each resoure type in dedicated tables.
One for actual versions and another for historical versions.

For example Patient resource will be saved in
**patient** & **patient_history** tables

Most of tables have similar structure:

 * logical_id
 * version_id
 * resource_type
 * resource content (as a binary json datatype)

For search we inherites all resource tables from resource table.
Yeh postgresql support table inheretance :)
When we make query against **resource** table, it searches thro all resource types.

### What is fhirbase API?

Fhirbase API is aligned with FHIR REST interactions:

* CRUD
* history
* transaction
* search

### How fhirbase use metadata?

Initial installation of fhirbase consists of several tables for meta-resources.

* struturedefinition
* searchparameters
* valuesets, namesystems and conceptmaps

### How fhirbase implements search?

* build dynamic query

### How fhirbase makes search fast?

### Performance

### Usage

* fhirplace
* netrika laboratory buss

### What is fhirbase roadmap?

* migrate to PLV8

* incorporate terminology
* referencial consistency
* validate structure definition and value sets
* Connectors: .NET, HAPI, clj, js, ruby etc


text:
/**
 * Copyright 2014 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kaaproject.kaa.examples.robotrun.labyrinth;

public enum BorderType {
    UNKNOWN, SOLID, FREE;
}


text:
/**
 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jivesoftware.smackx.bytestreams.socks5;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.bytestreams.BytestreamListener;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;

/**
 * InitiationListener handles all incoming SOCKS5 Bytestream initiation requests. If there are no
 * listeners for a SOCKS5 bytestream request InitiationListener will always refuse the request and
 * reply with a <not-acceptable/> error (<a
 * href="http://xmpp.org/extensions/xep-0065.html#usecase-alternate" >XEP-0065</a> Section 5.2.A2).
 * @author Henning Staib
 */
final class InitiationListener implements PacketListener {
	/* manager containing the listeners and the XMPP connection */
	private final Socks5BytestreamManager manager;
	/* packet filter for all SOCKS5 Bytestream requests */
	private final PacketFilter initFilter = new AndFilter(new PacketTypeFilter(
			Bytestream.class), new IQTypeFilter(IQ.Type.SET));
	/* executor service to process incoming requests concurrently */
	private final ExecutorService initiationListenerExecutor;

	/**
	 * Constructor
	 * @param manager the SOCKS5 Bytestream manager
	 */
	protected InitiationListener(Socks5BytestreamManager manager) {
		this.manager = manager;
		initiationListenerExecutor = Executors.newCachedThreadPool();
	}
	@Override
	public void processPacket(final Packet packet) {
		initiationListenerExecutor.execute(new Runnable() {
			@Override
			public void run() {
				processRequest(packet);
			}
		});
	}
	private void processRequest(Packet packet) {
		Bytestream byteStreamRequest = (Bytestream) packet;
		// ignore request if in ignore list
		if (this.manager.getIgnoredBytestreamRequests().remove(
				byteStreamRequest.getSessionID())) {
			return;
		}
		// build bytestream request from packet
		Socks5BytestreamRequest request = new Socks5BytestreamRequest(
				this.manager, byteStreamRequest);
		// notify listeners for bytestream initiation from a specific user
		BytestreamListener userListener = this.manager
				.getUserListener(byteStreamRequest.getFrom());
		if (userListener != null) {
			userListener.incomingBytestreamRequest(request);
		} else if (!this.manager.getAllRequestListeners().isEmpty()) {
			/*
			 * if there is no user specific listener inform listeners for all initiation requests
			 */
			for (BytestreamListener listener : this.manager
					.getAllRequestListeners()) {
				listener.incomingBytestreamRequest(request);
			}
		} else {
			/*
			 * if there is no listener for this initiation request, reply with reject message
			 */
			this.manager.replyRejectPacket(byteStreamRequest);
		}
	}
	/**
	 * Returns the packet filter for SOCKS5 Bytestream initialization requests.
	 * @return the packet filter for SOCKS5 Bytestream initialization requests
	 */
	protected PacketFilter getFilter() {
		return this.initFilter;
	}
	/**
	 * Shuts down the listeners executor service.
	 */
	protected void shutdown() {
		this.initiationListenerExecutor.shutdownNow();
	}
}


text:
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>BabylonJS Viewer - Basic usage</title>
        <style>
            babylon {
                max-width: 800px;
                max-height: 500px;
                width: 100%;
                height: 600px;
            }
        </style>
    </head>

    <body>
        <babylon id="babylon-viewer" model.title="Amazing Rabbit" model.subtitle="BabylonJS" model.thumbnail="https://www.babylonjs.com/img/favicon/apple-icon-144x144.png"
            model.url="https://playground.babylonjs.com/scenes/Rabbit.babylon" observers.on-scene-init="globalSceneInitCallback"></babylon>
        <script src="viewer.js"></script>
        <script>
            //get by id ONLY after viewer init
            var willNotWork = BabylonViewer.viewerManager.getViewerById('babylon-viewer');
            console.log('viewer not yet initialized');

            // Promise-based API:
            BabylonViewer.viewerManager.getViewerPromiseById('babylon-viewer').then(function (viewer) {
                // this will resolve only after the viewer with this specific ID is initialized
                console.log('Using promises: ', 'viewer - ' + viewer.getBaseId());

                viewerObservables(viewer);
            });

            // call back variant:
            BabylonViewer.viewerManager.onViewerAdded = function (viewer) {
                console.log('Using viewerManager.onViewerAdded: ', 'viewer - ' + viewer.getBaseId());
            }

            // using observers:
            BabylonViewer.viewerManager.onViewerAddedObservable.add(function (viewer) {
                console.log('Using viewerManager.onViewerAddedObservable: ', 'viewer - ' + viewer.getBaseId());
            });

            function viewerObservables(viewer) {
                viewer.onEngineInitObservable.add(function (engine) {
                    console.log('Engine initialized');
                });

                viewer.onSceneInitObservable.add(function (scene) {
                    console.log('Scene initialized');
                });

                viewer.onModelLoadedObservable.add(function (meshes) {
                    console.log('Model loaded');
                });
            }

            function globalSceneInitCallback(scene) {
                console.log('scene-init function defined in the configuration');
            }

        </script>
    </body>

</html>


text:
package org.terracotta.offheapstore.util;

import org.junit.Test;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.InterruptibleChannel;
import java.util.Iterator;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ReopeningInterruptibleChannelTest {

  @Test
  public void testStraightExecution() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    reopeningChannel.execute(SimpleInterruptibleChannel::operation);

    verify(delegate, times(1)).operation();
  }

  @Test
  public void testInterruptIsPreserved() throws IOException {
    Thread.currentThread().interrupt();

    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> mock(SimpleInterruptibleChannel.class));

    reopeningChannel.execute(SimpleInterruptibleChannel::operation);
    assertThat(Thread.interrupted(), is(true));
  }

  @Test
  public void testIOExceptionPropagates() throws IOException {
    IOException ioException = new IOException();
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    when(delegate.operation()).thenThrow(ioException);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    try {
      reopeningChannel.execute(SimpleInterruptibleChannel::operation);
      fail("Expected IOException");
    } catch (IOException e) {
      assertThat(e, is(sameInstance(ioException)));
    }
  }

  @Test
  public void testClosedChannelExceptionRefetches() throws IOException {
    SimpleInterruptibleChannel closed = mock(SimpleInterruptibleChannel.class);
    when(closed.operation()).thenThrow(ClosedChannelException.class);
    SimpleInterruptibleChannel open = mock(SimpleInterruptibleChannel.class);
    Object result = new Object();
    when(open.operation()).thenReturn(result);
    Iterator<SimpleInterruptibleChannel> sequence = asList(closed, open).iterator();
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(sequence::next);

    assertThat(reopeningChannel.execute(SimpleInterruptibleChannel::operation), is(sameInstance(result)));

    verify(closed, times(1)).operation();
    verify(open, times(1)).operation();
  }

  @Test
  public void testClosingClosesDelegate() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    reopeningChannel.close();

    verify(delegate, times(1)).close();
  }

  @Test
  public void testClosingIsIdempotent() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    reopeningChannel.close();
    reopeningChannel.close();

    verify(delegate, times(1)).close();
  }

  @Test
  public void testClosedDevicesThrows() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    reopeningChannel.close();

    try {
      reopeningChannel.execute(SimpleInterruptibleChannel::operation);
      fail("Expected ClosedChannelException");
    } catch (ClosedChannelException e) {
      //expected
    }
  }

  @Test
  public void testOpenInitially() {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    assertThat(reopeningChannel.isOpen(), is(true));
  }

  @Test
  public void testClosedAfterExplicitlyClosed() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    reopeningChannel.close();

    assertThat(reopeningChannel.isOpen(), is(false));
  }

  @Test
  public void testOpenDespiteDelegateClosure() throws IOException {
    SimpleInterruptibleChannel delegate = mock(SimpleInterruptibleChannel.class);
    when(delegate.operation()).thenThrow(ClosedChannelException.class);
    ReopeningInterruptibleChannel<SimpleInterruptibleChannel> reopeningChannel = ReopeningInterruptibleChannel.create(() -> delegate);

    assertThat(reopeningChannel.isOpen(), is(true));
  }

  interface SimpleInterruptibleChannel extends InterruptibleChannel {

    Object operation() throws IOException;
  }
}


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

namespace Pytocs.Core.CodeModel
{
    public class CodeNamespace :ICodeElement
    {
        public CodeNamespace(string @namespace)
        {
            this.Name = @namespace;
            this.Types = new List<CodeTypeDeclaration>();
            this.Imports = new List<CodeNamespaceImport>();
            this.Comments = new List<CodeCommentStatement>();
        }

        public T Accept<T>(ICodeElementVisitor<T> visitor)
        {
            return visitor.VisitNamespace(this);
        }

        public string Name { get; set; }
        public List<CodeTypeDeclaration> Types {get; private set; }
        public List<CodeNamespaceImport> Imports { get; private set; }
        public List<CodeCommentStatement> Comments { get; private set; }
    }
}


text:
layout: drawing_page
number: 135
permalink: 135/
---


text:
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text;

namespace Elasticsearch.Powershell.Types
{
    public class SearchResponse
    {
        public SearchResponse()
        {
            this.Documents = new PSObject[0];
        }

        public string ScrollId { get; set; }

        public long Total { get; set; }

        public PSObject[] Documents { get; set; }
    }
}


text:
:root {
  --media-row-height: 56px;
  --media-row-thumb-width: 55px;
  --media-row-duration-width: 70px;
  --media-row-icon-width: 50px;
  --unpadded-media-row-height: calc(var(--media-row-height) - 14px);
}

.MediaListRow {
  display: grid;
  grid-template-columns: var(--media-row-thumb-width) auto var(--media-row-duration-width) var(--media-row-icon-width);
  grid-template-rows: var(--media-row-height);
  grid-gap: 15px;
  padding: 0 15px;
  height: var(--media-row-height);
  line-height: var(--media-row-height);
  width: 100%;
  background: var(--media-list-color);
  border-bottom: 1px solid var(--divider-color);

  &.is-loading {
    opacity: 0.75;
  }

  &.is-selected {
    background: var(--selected-media-row-color);
  }

  &:focus {
    box-shadow: inset 0 0 0 2px var(--highlight-color);
    outline: none;
  }
}

.MediaListRow-thumb {
  height: 100%;
  padding: 7px 0;
}

.MediaListRow-image {
  max-width: 100%;
  max-height: 100%;
  pointer-events: none;
}

.MediaListRow-data {
  padding: 7px 0;
  line-height: var(--unpadded-media-row-height);
}

.MediaListRow-artist {
  height: 100%;
  float: inline-start;
  width: calc(40% - var(--media-list-spacing));
  margin-inline-end: var(--media-list-spacing);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.MediaListRow-title {
  height: 100%;
  float: inline-start;
  width: calc(60% - var(--media-list-spacing));
  margin-inline-end: var(--media-list-spacing);
  overflow: hidden;
  color: var(--secondary-text-color);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.MediaListRow-note {
  height: calc(var(--unpadded-media-row-height) / 3);
  line-height: calc(var(--unpadded-media-row-height) / 3);
  width: calc(100% - var(--media-list-spacing));
  margin-inline-end: var(--media-list-spacing);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 75%;
}

.MediaListRow-duration {
  height: 100%;
}

.MediaListRow-icon {
  height: 100%;
  display: flex;
  align-items: center;
}

.MediaListRow-actions {
  height: 100%;
  position: absolute;
  inset-inline-end: 0;
  display: none;
}

.MediaListRow:hover .MediaListRow-actions,
.MediaListRow:focus .MediaListRow-actions,
.MediaListRow:focus-within .MediaListRow-actions {
  display: block;
}

.MediaListRow.is-selected .MediaListRow-actions {
  background: var(--highlight-color);
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<link rel="stylesheet" href="extension_commands_overlay.css">
<link rel="stylesheet" href="extensions.css">
<link rel="stylesheet" href="pack_extension_overlay.css">
<link rel="stylesheet" href="chrome://resources/css/alert_overlay.css">
<link rel="stylesheet" href="chrome://resources/css/chrome_shared.css">
<link rel="stylesheet" href="chrome://resources/css/overlay.css">
<link rel="stylesheet" href="chrome://resources/css/trash.css">
<link rel="stylesheet" href="../uber/uber_shared.css">

  <include src="extension_commands_overlay.html">
  <include src="pack_extension_overlay.html">
  <include src="../../../../ui/webui/resources/html/alert_overlay.html">

          <input id="toggle-dev-on" type="checkbox">

    <button id="load-unpacked"
        i18n-content="extensionSettingsLoadUnpackedButton"></button>
    <button id="pack-extension"
        i18n-content="extensionSettingsPackButton"></button>

    <button id="update-extensions-now"
        i18n-content="extensionSettingsUpdateButton"></button>

          <button class="show-button"
              i18n-content="extensionSettingsShowButton" hidden></button>

            <input type="checkbox">

            <input type="checkbox">

          <input type="checkbox">

  <include src="../../../../ui/webui/resources/html/trash.html">


text:
using System.Collections.Concurrent;
using LightBDD.Core.Configuration;
using LightBDD.Framework.Configuration;
using LightBDD.Framework.Notification;

namespace LightBDD.Fixie2.UnitTests
{
    public class WithLightBddConventions : LightBddDiscoveryConvention { }

    public class ConfiguredLightBddScope : LightBddScope
    {
        public static readonly ConcurrentQueue<string> CapturedNotifications = new ConcurrentQueue<string>();
        protected override void OnConfigure(LightBddConfiguration configuration)
        {
            configuration.ReportWritersConfiguration()
                .Clear();

            configuration.FeatureProgressNotifierConfiguration()
                .ClearNotifiers();

            configuration.ScenarioProgressNotifierConfiguration()
                .ClearNotifierProviders()
                .AppendNotifierProviders(() => new DefaultProgressNotifier(x => CapturedNotifications.Enqueue(x)));
        }
    }
}


text:
package at.bestsolution.framework.grid.swt.internal;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.swt.SWT;

import at.bestsolution.framework.grid.Property;
import at.bestsolution.framework.grid.Property.ChangeListener;
import at.bestsolution.framework.grid.Util;
import at.bestsolution.framework.grid.XGrid.SelectionMode;
import at.bestsolution.framework.grid.XGridCell;
import at.bestsolution.framework.grid.XGridColumn;
import at.bestsolution.framework.grid.XGridContentProvider;
import at.bestsolution.framework.grid.XGridContentProvider.ContentChangeListener;
import at.bestsolution.framework.grid.XGridContentProvider.ContentChangeType;
import at.bestsolution.framework.grid.XSelection;
import at.bestsolution.framework.grid.swt.SWTGridColumn;
import at.bestsolution.framework.grid.swt.SWTGridTable;

/**
 * @param <R>
 *            content type
 */
public class SWTGridContentHandler<R> {
	private final List<@NonNull Wrapper> data = new ArrayList<@NonNull Wrapper>();
	private final Map<@NonNull Integer, @Nullable GridItem> dataMapByR = new HashMap<>();
	private final Map<@NonNull GridItem, @NonNull Wrapper> dataMapByCol = new HashMap<>();

	final @NonNull SWTGridTable<R> grid;

	private final @NonNull Property<@Nullable Comparator<@NonNull R>> defaultSortProperty = new SimpleProperty<>(null);
	private final @NonNull Property<@Nullable SWTGridColumn<R, ?>> sortColumnProperty = new SimpleProperty<>(null);

	private @Nullable XGridContentProvider<R> contentProvider;
	private final @NonNull ChangeListener<@Nullable Comparator<@NonNull R>> defaultSortChangeListener = this::handleDefaultSortChanged;
	private final @NonNull ChangeListener<@Nullable SWTGridColumn<R, ?>> sortColumnChangeListener = this::handleSortColumnChanged;
	private final @NonNull ContentChangeListener<R> contentChangeListener = this::handleContentChange;
	private final @NonNull ChangeListener<@Nullable XGridContentProvider<R>> contentProviderChangeListener = this::handleContentProviderChanged;

	/**
	 * @param grid
	 *            grid
	 */
	public SWTGridContentHandler(@NonNull SWTGridTable<R> grid) {
		this.grid = grid;
		registerPropertyListeners();
	}

	/**
	 *
	 */
	private void registerPropertyListeners() {
		defaultSortProperty.addChangeListener(defaultSortChangeListener);
		sortColumnProperty.addChangeListener(sortColumnChangeListener);
		grid.contentProviderProperty().addChangeListener(contentProviderChangeListener);
	}

	private void handleDefaultSortChanged(Property<@Nullable Comparator<@NonNull R>> property, @Nullable Comparator<@NonNull R> oldValue,
			@Nullable Comparator<@NonNull R> newValue) {
		resetContent(contentProvider);
	}

	private void handleSortColumnChanged(Property<@Nullable SWTGridColumn<R, ?>> property, @Nullable SWTGridColumn<R, ?> oldValue,
			@Nullable SWTGridColumn<R, ?> newValue) {
		resetContent(contentProvider);
	}

	private void handleContentProviderChanged(Property<@Nullable XGridContentProvider<R>> property,
			@Nullable XGridContentProvider<R> oldValue, @Nullable XGridContentProvider<R> newValue) {
		resetContent(newValue);
	}

	/**
	 * reset content
	 */
	public void resetContent() {
		resetContent(contentProvider);
	}

	/**
	 *
	 * @param newContentProvider
	 *            the new content provider
	 */
	private void resetContent(@Nullable XGridContentProvider<R> newContentProvider) {
		XSelection<R> previousSelection = grid.selectionProperty().get();
		if (contentProvider != newContentProvider) {
			@Nullable
			XGridContentProvider<R> oldContentProvider = contentProvider;
			if (oldContentProvider != null) {
				oldContentProvider.removeChangeListener(contentChangeListener);
			}
			contentProvider = newContentProvider;
			if (newContentProvider != null) {
				newContentProvider.addChangeListener(contentChangeListener);
			}
		}
		clearData();
		grid.getNebulaGrid().disposeAllItems();
		if (newContentProvider != null) {
			insertData(newContentProvider);
			createGridItems();
			List<@NonNull R> newSelection = new ArrayList<>();

			for (R element : previousSelection.asList()) {
				// find elements which match elements from old selection
				if (data.contains(new Wrapper(element))) {
					newSelection.add(element);
				}
			}
			// restore selection
			if (newSelection.isEmpty() && !data.isEmpty()) {
				// if there is no previous selection select the first item
				newSelection.add(data.get(0).get());
			}
			if (newSelection.isEmpty()) {
				grid.selectionProperty().set(Util.emptySelection());
			} else if (grid.selectionModeProperty().get() == SelectionMode.SINGLE_ROW) {
				grid.selectionProperty().set(new SimpleSelection<@NonNull R>(grid,newSelection, grid.getColumns()));
			} else if (grid.selectionModeProperty().get() == SelectionMode.SINGLE_CELL) {
				SimpleCellSelection<R> scs = (SimpleCellSelection<R>) previousSelection;
				List<XGridCell<@NonNull R, ?>> cellList = new ArrayList<XGridCell<@NonNull R, ?>>(scs.getCells());
				grid.selectionProperty().set(new SimpleCellSelection<@NonNull R>(grid,cellList, newSelection, grid.getColumns()));
			}
		}
		// pack
		for (@NonNull
		XGridColumn<@NonNull R, @Nullable ?> xcol : grid.getColumns()) {
			if (xcol.autoWidthProperty().get().booleanValue()) {
				SWTGridColumn<R, ?> col = (SWTGridColumn<R, ?>) xcol;
				col.getNebulaColumn().pack();
			}
		}
	}

	private Comparator<@NonNull Wrapper> getComparator() {
		@Nullable
		SWTGridColumn<R, ?> column = sortColumnProperty.get();
		Comparator<@NonNull R> comp = null;
		if (column != null) {
			switch (column.sortingProperty().get()) {
			case UP:
				comp = column.sorterProperty().get();
				break;
			case DOWN:
				@Nullable
				Comparator<@NonNull R> originComparator = column.sorterProperty().get();
				if (originComparator != null) {
					comp = originComparator.reversed();
				}
				break;
			default:
				comp = defaultSortProperty.get();
			}

		} else if (defaultSortProperty.get() != null) {
			comp = defaultSortProperty.get();
		}
		if (comp != null) {
			final Comparator<@NonNull R> rComparator = comp;
			return (o1, o2) -> rComparator.compare(o1.get(), o2.get());
		}
		return null;
	}

	private void insertData(XGridContentProvider<R> newContentProvider) {
		for (int i = 0; i < newContentProvider.size(); i++) {
			data.add(new Wrapper(newContentProvider.getElementAt(i)));
		}
		Comparator<@NonNull Wrapper> comparator = getComparator();
		if (comparator != null) {
			data.sort(comparator);
		}
	}

	private void clearData() {
		data.clear();
		dataMapByR.clear();
		dataMapByCol.clear();
	}

	private void handleContentChange(@NonNull ContentChangeType type, @NonNull List<@NonNull R> values) {
		switch (type) {
		case ADD:
		case REMOVE:
			resetContent();
			break;
		case MODIFY:
			for (R element : values) {
				for (@NonNull
				XGridColumn<@NonNull R, @Nullable ?> col : grid.getColumns()) {
					col.requestUpdate(element);
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * create a {@link GridItem} for each row where no {@link GridItem} exist an
	 * which is not excluded by current filter settings
	 */
	private void createGridItems() {
		grid.getNebulaGrid().setRedraw(false);
		try {
			for (@NonNull
			Wrapper element : data) {
				if (dataMapByR.get(element) == null) {
					boolean visible = true;
					for (@NonNull
					XGridColumn<@NonNull R, @Nullable ?> xcol : grid.getColumns()) {
						SWTGridColumn<R, ?> col = (SWTGridColumn<R, ?>) xcol;
						visible = col.matchesColumnFilter(element.get());
						if (!visible) {
							break;
						}
					}
					if (visible) {
						final GridItem item = new GridItem(grid.getNebulaGrid(), SWT.NONE);
						dataMapByR.put(new Integer(element.hashCode()), item);
						dataMapByCol.put(item, element);
						for (XGridColumn<@NonNull R, @Nullable ?> col : grid.getColumns()) {
							col.requestUpdate(element.get());
						}
					}
				}
			}
		} finally {
			grid.getNebulaGrid().setRedraw(true);
		}
	}

	/**
	 * @param item
	 *            grid item
	 * @return corresponding row value
	 */
	public R get(@NonNull GridItem item) {
		return dataMapByCol.get(item).get();
	}

	/**
	 * @param r
	 *            row value
	 * @return corresponding GridItem
	 */
	public @Nullable GridItem get(@NonNull R r) {
		return dataMapByR.get(new Integer(new Wrapper(r).hashCode()));
	}

	/**
	 * @return the defaultSortProperty
	 */
	public @NonNull Property<@Nullable Comparator<@NonNull R>> defaultSortProperty() {
		return defaultSortProperty;
	}

	/**
	 * @return the sortProperty
	 */
	public Property<@Nullable SWTGridColumn<R, ?>> sortColumnProperty() {
		return sortColumnProperty;
	}

	/**
	 * @return list of visible elements
	 */
	@SuppressWarnings("null")
	public @NonNull List<@NonNull R> getVisibleElements() {
		return dataMapByCol.values().stream().map((x) -> x.get()).collect(Collectors.<@NonNull R> toList());
	}

	/**
	 * @param allRows
	 *            export all elements if true, otherwise exclude
	 *            filtered items
	 * @return export data
	 */
	@SuppressWarnings("null")
	public @NonNull Object[][] getData(boolean allRows) {
		if (allRows) {
			return getData(data);
		} else {
			List<@NonNull Wrapper> unFilteredElements = new ArrayList<>();
			for (Wrapper w : data) {
				if (get(w.get()) != null) {
					unFilteredElements.add(w);
				}
			}
			return getData(unFilteredElements);
		}
	}

	private Object[][] getData(List<@NonNull Wrapper> rows) {
		Object[][] exportData = new Object[rows.size()][grid.getColumns().size()];
		int rowIndex = 0;
		for (Wrapper element : rows) {
			int colIndex = 0;
			for (XGridColumn<R, ?> column : grid.getColumns()) {
				exportData[rowIndex][colIndex] = column.getExportValue(element.get());
				colIndex++;
			}
			rowIndex++;
		}
		return exportData;
	}

	/**
	 * dispose content handler.
	 *

	 * remove listeners & do necessary cleanup
	 *

	 */
	public void dispose() {
		defaultSortProperty.removeChangeListener(defaultSortChangeListener);
		sortColumnProperty.removeChangeListener(sortColumnChangeListener);
		@Nullable
		XGridContentProvider<R> cp = contentProvider;
		if (cp != null) {
			cp.removeChangeListener(contentChangeListener);
		}
		grid.contentProviderProperty().removeChangeListener(contentProviderChangeListener);
	}

	/**
	 * content wrapper
	 */
	private class Wrapper {
		private final @NonNull R object;

		public Wrapper(@NonNull R object) {
			this.object = object;
		}

		public @NonNull R get() {
			return object;
		}

		@Override
		public int hashCode() {
			return grid.elementComparerProperty().get().hashCode(object);
		}

		@Override
		public boolean equals(Object obj) {
			if (obj != null && obj instanceof SWTGridContentHandler.Wrapper) {
				@SuppressWarnings("unchecked")
				Wrapper w = (Wrapper) obj;
				return grid.elementComparerProperty().get().equals(object, w.get());
			}
			return false;
		}
	}
}


text:
import React from 'react'

export default class UserTypeSelector extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      userType: null
    }
    this.handleClick = this.handleClick.bind(this)
    this.handleLoginClick = this.handleLoginClick.bind(this)
  }

  handleClick (event) {
    const value = event.currentTarget.value
    console.log('INFO changing type', value)
    ga('send', 'event', 'User Registration', 'Form', 'Step 1 Completed - ' + value.charAt(0).toUpperCase() + value.slice(1))
    this.props.onUserTypeSelect(value)
  }

  handleLoginClick (event) {
    event.preventDefault()
    ga('send', 'event', 'User Registration', 'Form', 'Step 1 Log in Link Clicked')
    PortalComponents.renderLoginModal({
      oauthProviders: this.state.oauthProviders,
      afterSigninPath: this.props.afterSigninPath
    })
    ga('send', 'event', 'Login', 'Form', 'Opened')
  }

  render () {
    console.log('INFO UserTypeSelector rendering')

    return (

        <button onClick={this.handleClick} name='type' value='teacher'>
          I am a Teacher
        </button>
        <button onClick={this.handleClick} name='type' value='student'>
          I am a Student
        </button>

Already have an account? Log in »

    )
  }
}


text:
/*jslint nomen: true, unparam: true, regexp: true */
/*global $, window, document */

$(function() {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/pyme/demoUpload/',
        previewAsCanvas: false,
        add: function (e, data) {
            data.context = $('#leo').text('Upload')
                .click(function () {
                    //data.context = $('<p/>').text('Uploading...').replaceAll($(this));
                    data.submit();
                });
        },

    }).bind('fileuploadalways', function (e, data) {
        var response = data.result[0];
            console.log(response.status);
        });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );

    if (window.location.hostname === 'blueimp.github.com') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            process: [
                {
                    action: 'load',
                    fileTypes: /^image\/(gif|jpeg|png)$/,
                    maxFileSize: 20000000 // 20MB
                },
                {
                    action: 'resize',
                    maxWidth: 1440,
                    maxHeight: 900
                },
                {
                    action: 'save'
                }
            ]
        });
        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }).fail(function () {
                $('<span class="alert alert-error"/>')
                    .text('Upload server currently unavailable - ' +
                            new Date())
                    .appendTo('#fileupload');
            });
        }
    } else {
        // Load existing files:
        /*
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).done(function (result) {
            if (result && result.length) {
                $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
            }
        });*/
    }

});


text:
const path = require('path');
const createMochaWebpack = require('mocha-webpack/lib/createMochaWebpack');
const getWebpackConfig = require('./get-webpack-config');

const rootPath = path.join(__dirname, '..');

const args = process.argv.slice(2);

const isWatching = args.indexOf('-w') !== -1;
const isCoverage = args.indexOf('-coverage') !== -1;

const webpackConfig = getWebpackConfig({
  isTest: true,
  isCoverage,
  coveragePaths: [
    path.join(rootPath, 'src')
  ]
});

const mochaWebpack = createMochaWebpack();
mochaWebpack.cwd(rootPath);
mochaWebpack.webpackConfig(webpackConfig);
mochaWebpack.bail(!isWatching);
mochaWebpack.addEntry(
  path.join('test', 'index.js')
);

Promise.resolve()
.then(() => {
  if (isWatching) {
    return mochaWebpack.watch();
  } else {
    return mochaWebpack.run();
  }
})
.then(failures => {
  if (!isWatching) {
    process.exit(failures);
  }
})
.catch(e => {
  if (e) {
    console.error(e.stack); // eslint-disable-line
  }
  if (!isWatching) {
    process.exit(1);
  }
});


text:
import unittest
from typing import Callable

from smartobjects.api_manager import APIManager, ServiceUnavailable
from smartobjects.smartobjects_client import ExponentialBackoffConfig
from tests.mocks.local_api_server import LocalApiServer

class TestBackoff(unittest.TestCase):
    """
    Retry on 503 response
    """

    @classmethod
    def setUpClass(cls):
        cls.server = LocalApiServer()
        cls.server.start()

    @classmethod
    def tearDownClass(cls):
        cls.server.stop()

    def setUp(self):
        self.server.server.backend.clear()

    def test_retry_default(self):
        config = ExponentialBackoffConfig()
        api = APIManager("CLIENT_ID", "CLIENT_SECRET", self.server.path, compression_enabled=False,
                         backoff_config=config, token_override=None)
        value = api.get('/api/v3/unvailable/1')
        self.assertEqual(value.json()['data'], "ok")

    def test_retry_until_200(self):
        self.counter = 0

        def on_retry(func: Callable):
            self.counter = self.counter + 1

        config = ExponentialBackoffConfig(5, 0.5, on_retry)
        api = APIManager("CLIENT_ID", "CLIENT_SECRET", self.server.path, compression_enabled=False,
                         backoff_config=config, token_override=None)
        value = api.get('/api/v3/unvailable/3')
        self.assertEqual(self.counter, 4)
        self.assertEqual(value.json()['data'], "ok")

    def test_retry_until_limit(self):
        self.counter = 0

        def on_retry(func: Callable):
            self.counter = self.counter + 1

        config = ExponentialBackoffConfig(5, 0.1, on_retry)
        api = APIManager("CLIENT_ID", "CLIENT_SECRET", self.server.path, compression_enabled=False,
                         backoff_config=config, token_override=None)
        with self.assertRaises(ServiceUnavailable) as ctx:
            api.get('/api/v3/unvailable/100')
        self.assertEqual(self.counter, 5)

    def test_do_not_retry_if_success(self):
        api = APIManager("CLIENT_ID", "CLIENT_SECRET", self.server.path, compression_enabled=False, backoff_config=None,
                         token_override=None)
        value = api.get('/api/v3/unvailable/0')
        self.assertEqual(value.json()['data'], "ok")


text:
<?php

	/**
	 * @package core
	 */

	 /**
	  * The Cacheable class is used to store data in the dedicated Symphony
	  * cache table. It is used by Symphony for Session management and by
	  * the Dynamic XML datasource, but it can be used by extensions to store
	  * anything. The cache table is `tbl_cache`
	  */
	require_once(TOOLKIT . '/class.mutex.php');

	Class Cacheable {

		/**
		 * An instance of the MySQL class to communicate with `tbl_cache`
		 * which is where the cached data is stored.
		 *
		 * @var MySQL
		 */
		private $Database;

		/**
		 * The constructor for the Cacheable takes an instance of the
		 * MySQL class and assigns it to `$this->Database`
		 *
		 * @param MySQL $Database
		 *  An instance of the MySQL class to store the cached
		 *  data in.
		 */
		public function __construct(MySQL $Database) {
			$this->Database = $Database;
		}

		/**
		 * This function will compress data for storage in `tbl_cache`.
		 * It is left to the user to define a unique hash for this data so that it can be
		 * retrieved in the future. Optionally, a `$ttl` parameter can
		 * be passed for this data. If this is omitted, it data is considered to be valid
		 * forever. This function utilizes the Mutex class to act as a crude locking
		 * mechanism.
		 *
		 * @see toolkit.Mutex
		 * @param string $hash
		 *  The hash of the Cached object, as defined by the user
		 * @param string $data
		 *  The data to be cached, this will be compressed prior to saving.
		 * @param integer $ttl
		 *  A integer representing how long the data should be valid for in minutes.
		 *  By default this is null, meaning the data is valid forever
		 * @return boolean
		 *  If an error occurs, this function will return false otherwise true
		 */
		public function write($hash, $data, $ttl = null) {

			if(!Mutex::acquire($hash, 2, TMP)) return false;

			$creation = time();
			$expiry = null;

			$ttl = intval($ttl);
			if($ttl > 0) $expiry = $creation + ($ttl * 60);

			if(!$data = $this->compressData($data)) return false;

			$this->forceExpiry($hash);
			$this->Database->insert(array('hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data), 'tbl_cache');

			Mutex::release($hash, TMP);

			return true;
		}

		/**
		 * Given some data, this function will compress it using `gzcompress`
		 * and then the result is run through `base64_encode` If this fails,
		 * false is returned otherwise the compressed data
		 *
		 * @param string $data
		 *  The data to compress
		 * @return string|boolean
		 *  The compressed data, or false if an error occurred
		 */
		public function compressData($data) {
			if(!$data = base64_encode(gzcompress($data))) return false;
			return $data;
		}

		/**
		 * Given compressed data, this function will decompress it and return
		 * the output.
		 *
		 * @param string $data
		 *  The data to decompress
		 * @return string|boolean
		 *  The decompressed data, or false if an error occurred
		 */
		public function decompressData($data) {
			if(!$data = gzuncompress(base64_decode($data))) return false;
			return $data;
		}

		/**
		 * Given the hash of a some data, check to see whether it exists in
		 * `tbl_cache`. If no cached object is found, this function will return
		 * false, otherwise the cached object will be returned as an array.
		 *
		 * @param string $hash
		 *  The hash of the Cached object, as defined by the user
		 * @return array|boolean
		 *  An associative array of the cached object including the creation time,
		 *  expiry time, the hash and the data. If the object is not found, false will
		 *  be returned.
		 */
		public function check($hash) {

			if($c = $this->Database->fetchRow(0, "SELECT SQL_NO_CACHE * FROM `tbl_cache` WHERE `hash` = '$hash' AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`) LIMIT 1")){
				if(!$c['data'] = $this->decompressData($c['data'])){
					$this->forceExpiry($hash);
					return false;
				}

				return $c;
			}

			$this->clean();
			return false;
		}

		/**
		 * Given the hash of a cacheable object, remove it from `tbl_cache`
		 * regardless of if it has expired or not.
		 *
		 * @param string $hash
		 *  The hash of the Cached object, as defined by the user
		 */
		public function forceExpiry($hash) {
			$this->Database->query("DELETE FROM `tbl_cache` WHERE `hash` = '$hash'");
		}

		/**
		 * Removes all cache objects from `tbl_cache` that have expired.
		 * After removing, the function uses the optimise function
		 *
		 * @see core.Cacheable#optimise()
		 */
		public function clean() {
			$this->Database->query("DELETE FROM `tbl_cache` WHERE UNIX_TIMESTAMP() > `expiry`");
			$this->__optimise();
		}

		/**
		 * Runs a MySQL OPTIMIZE query on `tbl_cache`
		 */
		private function __optimise() {
			$this->Database->query('OPTIMIZE TABLE `tbl_cache`');
		}

	}


text:
<?php

namespace ASMTest\Stub;

use ASM\IdGenerator;

class XKCDIDGenerator implements IdGenerator
{
    function generateSessionId()
    {
        return "4";
    }
}


text:
package com.github.steveice10.opennbt.conversion.builtin;

import com.github.steveice10.opennbt.conversion.TagConverter;
import com.github.steveice10.opennbt.tag.builtin.ShortTag;

/**
 * A converter that converts between ShortTag and short.
 */
public class ShortTagConverter implements TagConverter<ShortTag, Short> {
    @Override
    public Short convert(ShortTag tag) {
        return tag.getValue();
    }

    @Override
    public ShortTag convert(String name, Short value) {
        return new ShortTag(name, value);
    }
}


text:
/* Models */
export * from './models/navigationItem';
export * from './models/biography';

/* Services */
export * from './services/biography.service';


text:
import json, csv, os
from collections import Counter

validtags = ['front', 'back', 'non', 'bio', 'fic', 'poe', 'dra', 'ads']

def givehelp():
    print("This is a browser that allows you to load volumes and browse")
    print("wordcount information at a page level. It assumes that the")
    print("word counts are in a subdirectory called /counts located")
    print("immediately below this application. Legal commands include:")
    print("")
    print("'quit': quits this browser")
    print("'load' X: loads a volume counts/X")
    print("integer: prints wordcounts for page #integer of the loaded vol")
    print("anyword: finds pages in the loaded vol that contain anyword")
    print("anyword otherword: finds pages in the loaded vol that contain anyword and otherword")
    print("'checkvols': checks the counts in /counts against the tags in /tags, and reports")
    print("           : whether volumes have been tagged appropriately")
    print("'help' : prints this list of commands")
    print("")
    print("Note that you can't search for 'quit,' 'load,' or 'help' as words")
    print("in a volume. They'll be interpreted as commands.")

def makealphalist(adict):
    alphalist = []
    for key, value in adict.items():
        alphalist.append(key)
    alphalist.sort()

    return alphalist

def printlist(alist):
    line = ""
    ctr = 0
    for word in alist:
        line = line + word + " "
        ctr += 1
        if ctr > 5:
            print(line)
            line = ""
            ctr = 0
    if len(line) > 0:
        print(line)

class LoadedVolume:

    # Mainly a data object that contains page-level wordcounts
    # for a volume.

    def __init__(self, volumepath):
        '''initializes a LoadedVolume by reading wordcounts from
        a json file'''

        with open(volumepath, encoding = 'utf-8') as f:
            thestring = f.read()

        thejson = json.loads(thestring)
        pagedata = thejson['features']['pages']
        self.numpages = len(pagedata)
        self.pagesets = []
        self.bodylists = []
        self.headerlists = []
        self.totalcounts = []

        for i in range(self.numpages):
            wordcounts = Counter()
            headercounts = Counter()
            totalwords = 0
            thispage = pagedata[i]

            bodywords = thispage['body']['tokenPosCount']
            for token, partsofspeech in bodywords.items():
                lowertoken = token.lower()
                for part, count in partsofspeech.items():
                    totalwords += count
                    wordcounts[lowertoken] += count

            headerwords = thispage['header']['tokenPosCount']
            for token, partsofspeech in headerwords.items():
                lowertoken = token.lower()
                for part, count in partsofspeech.items():
                    totalwords += count
                    headercounts[lowertoken] += count

            # You will notice that I treat footers as part of the body
            # In practice, footers are rarely interesting.

            footerwords = thispage['footer']['tokenPosCount']
            for token, partsofspeech in footerwords.items():
                lowertoken = token.lower()
                for part, count in partsofspeech.items():
                    totalwords += count
                    wordcounts[lowertoken] += count

            thisset = set(headercounts).union(set(wordcounts))
            self.pagesets.append(thisset)

            thisbody = makealphalist(wordcounts)
            self.bodylists.append(thisbody)

            thisheader = makealphalist(headercounts)
            self.headerlists.append(thisheader)

            self.totalcounts.append(totalwords)

        # We are done with the __init__ method for this volume.

    def printpage(self, pageint):
        if pageint > self.numpages:
            print("You're requesting page # " + str(pageint))
            print("but this volume only has " + str(self.numpages) + " pages.")
        else:
            print("Page " + str(pageint) + " has " + str(self.totalcounts[pageint]) + " words.")
            print("HEADER:")
            h = self.headerlists[pageint]
            printlist(h)
            print("BODY:")
            b = self.bodylists[pageint]
            printlist(b)

    def findmatches(self, wordlist):
        '''
        We want to print all the pages that have all the words in
        wordlist. To do that we start by creating a list of all pages.
        Then we iterate through wordlist, and remove any page that
        lacks any word.
        '''

        allpages = set([x for x in range(self.numpages)])
        for word in wordlist:
            for idx, aset in enumerate(self.pagesets):
                if idx in allpages and word not in aset:
                    allpages.remove(idx)

        if len(allpages) == 0:
            print("We found no pages matching: ")
            print(wordlist)
        else:
            printlist([str(x) for x in allpages])

def checktags(tagpath, npages):
    '''
    Confirms that all pages are either tagged or
    untagged. If tagged, confirms that they belong
    to valid tagset.

    It assumes that the tagfile will take the form of
    a csv, in utf-8 format, with two columns, "page" and
    "tag."
    '''
    global validtags

    # Here are some things that could go wrong:

    found = True
    inorder = True
    allvalid = True
    invalids = []

    ctr = 0
    blanks = 0

    try:
        with open(tagpath, encoding = 'utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                page = int(row['page'])
                tag = row['tag'].strip()
                # note that we strip blanks

                if ctr != page:
                    inorder = False

                if not tag or tag == '':
                    blanks += 1
                elif tag not in validtags:
                    invalids.append((page, tag))
                    allvalid = False
                ctr += 1
    except:
        found = False

    done = False

    if not found:
        print("File " + tagpath + " was not found, or not correctly formatted.")
    elif not inorder:
        print("The page numbers in " + tagpath + " are out of order.")
    elif ctr != npages:
        print("The tagfile " + tagpath + " has " + str(ctr) + " pages; I expected " + str(npages))

    if blanks == ctr:
        print(tagpath + " not yet tagged.")
    elif blanks == 0 and allvalid:
        print(tagpath + " completely tagged; ready to review.")
        done = True
    elif blanks > 0 and allvalid:
        print(tagpath + " has some valid tags, but still lacks tags for " + str(blanks) + " pages.")
    elif not allvalid:
        print("The tagfile " + tagpath + " contains the following invalid tags: ")
        for page, tag in invalids:
            print(str(page) + " : " + tag)
        if blanks > 0:
            print("This file also contains " + str(blanks) + " blank rows.")
    print()

    return found, done

def checkvolumes():
    '''
    This function aligns the volumes in two subdirectories.
    '''

    countvols = [x for x in os.listdir('counts') if x.endswith('json')]
    tagvols = [x for x in os.listdir('tags') if x.endswith('csv')]

    ncounts = len(countvols)
    ntags = len(tagvols)

    print("There are " + str(ncounts) + " count files under /counts")
    print("and " + str(ntags) + " tag files under /tags.")

    volpairs = []
    matches = 0
    for vol in countvols:
        match = vol.replace('json', 'csv')
        if vol.endswith('json') and match in tagvols:
            matches += 1
            volpairs.append((vol, match))

    print(str(matches) + " of those volumes match.")

    numfound = 0
    numdone = 0
    print()

    for countfile, tagfile in volpairs:
        countpath = os.path.join('counts', countfile)
        cvol = LoadedVolume(countpath)
        npages = cvol.numpages

        tagpath = os.path.join('tags', tagfile)
        found, done = checktags(tagpath, npages)

        if found:
            numfound += 1
        if done:
            numdone += 1

    print('I found correctly formatted tag files in ' + str(numfound) + " cases.")
    print('Of those, ' + str(numdone) + ' were completely tagged and ready to submit.')

# MAIN LOOP BEGINS HERE.

keepgoing = True
hasvolume = False

givehelp()
while keepgoing:

    print()
    user = input(': ')
    commands = user.split()
    numwords = len(commands)
    print()

    if numwords < 1:
        continue
    elif commands[0] == 'quit':
        keepgoing = False
        continue
    elif commands[0] == 'load':
        if numwords < 2:
            print("Load what?")
            continue
        else:
            datapath = os.path.join('counts', commands[1])
            if os.path.isfile(datapath):
                volume = LoadedVolume(datapath)
                hasvolume = True
                print("You have loaded a volume with " + str(volume.numpages) + " pages.")

            else:
                print('I cannot find ' + datapath)
                continue
    elif commands[0] == 'help':
        givehelp()

    elif commands[0] == 'checkvols':
        checkvolumes()

    elif numwords > 1:
        volume.findmatches(commands)
        # Note that this gives you a way to search for integer page numbers
        # as strings within a volume by doing e.g. "the 212."

    elif commands[0].isdigit():
        if not hasvolume:
            print('I cannot give you a page until you load a volume.')
            continue
        else:
            volume.printpage(int(commands[0]))

    else:
        volume.findmatches(commands)


text:
{% extends "project_graph_base.html" %}
{% block content %}

      project_details.html

         {{project.name|title}}

        Availability

        Booking

{{project.name|title}}

Description : {{project.description}}

{% include 'projects_graph.html'%}

Users:

{% for user in users_list %}

  ID:{{ user.id }}
  Firstname:{{ user.first_name }}
  Lastname :{{ user.last_name }}
  EMAIL :{{ user.email }}
  All :{{ user.__dict__ }}

{% endfor %}

Resources:

{% for user in resources_list %}

  {{ user }}

{% endfor %}

Project Stats:

* supply_group_by_date_count, demand_group_by_date_count

{% endblock %}