text:
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <manuel.deneu@gmail.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.
 * ----------------------------------------------------------------------------
 */
/*
 Network.js

 */

import("Element.js");

function _NetworkController()
{
    this.prototype = new Element();
    this.id = createElement("NetworkController");

    /* form function onOsc(ip , port , address , args)*/
    this.setOscCallback = function( func , target )
    {
        return perform("setOscCallback" , this.id , [ func , target.id ] );
    };

    this.send = function( addr , port , header , vars)
    {
        return perform("sendOSC" , this.id , [ addr , port , header , vars ] );
    };

    this.sendBroadcast = function( addr , port , header , vars)
    {
        return perform("sendOSCBroadcast" , this.id , [ addr , port , header , vars ] );
    };

    this.addPort = function ( port)
    {
        return perform("addPort" , this.id , port  );
    };

    this.removePort = function ( port )
    {
        return perform("removePort" , this.id , port  );
    };

    this.stop = function ()
    {
        return perform("stop" , this.id , port  );
    };

    /* **** **** **** **** **** **** **** **** **** **** **** **** **** */

    this.getIp = function ()
    {
        var ip = this.getEthernetIp();

        if (ip == undefined )
            ip = this.getWlanIp();

        return ip;
    };

    this.getHostName = function()
    {
        return perform("getHostName" , this.id , 0  );
    };

    this.getWlanIp = function()
    {
        var ip;

        if( Application.getPlateformName() == "RaspberryPi")
            ip = perform("getIp" , this.id , "wlan0");

        else if( Application.getPlateformName() == "MacOs")
            ip = perform("getIp" , this.id , "en1");

        else
            print("Error : wlan name undefined for " +  Application.getPlateformName() );

        if ( 0 !== ip.length)
            return ip;
    };

    this.getEthernetIp = function()
    {
        var ip;

        if( Application.getPlateformName() == "RaspberryPi")
            ip = perform("getIp" , this.id , "eth0");

        else if( Application.getPlateformName() == "MacOs")
            ip = perform("getIp" , this.id , "en0");

        else
            print("Error : ethernet name undefined for " +  Application.getPlateformName() );
        if ( 0 !== ip.length)
            return ip;

    };
}

var NetworkController = new _NetworkController();


text:
cask 'insomnia' do
  version '5.9.6'
  sha256 '57c73e41654cc53370312ed270358070dfb961737e1f10e2eda2e217b623dd29'

  # github.com/getinsomnia/insomnia was verified as official when first introduced to the cask
  url "https://github.com/getinsomnia/insomnia/releases/download/v#{version}/Insomnia-#{version}.dmg"
  appcast 'https://github.com/getinsomnia/insomnia/releases.atom',
          checkpoint: 'a1b42bcbf0715c2d38e1b7f08e7af6d407bec4f26bb205c2312cb491ffa9ab5a'
  name 'Insomnia'
  homepage 'https://insomnia.rest/'

  auto_updates true

  app 'Insomnia.app'

  zap delete: [
                '~/Library/Caches/com.insomnia.app',
                '~/Library/Caches/com.insomnia.app.ShipIt',
                '~/Library/Cookies/com.insomnia.app.binarycookies',
                '~/Library/Saved Application State/com.insomnia.app.savedState',
              ],
      trash:  [
                '~/Library/Application Support/Insomnia',
                '~/Library/Preferences/com.insomnia.app.helper.plist',
                '~/Library/Preferences/com.insomnia.app.plist',
              ]
end

redpajama_set_name: RedPajamaGithub


text:
import collections

from supriya.enums import CalculationRate
from supriya.ugens.OnePole import OnePole

class OneZero(OnePole):
    """
    A one zero filter.

    ::

        >>> source = supriya.ugens.In.ar(bus=0)
        >>> one_zero = supriya.ugens.OneZero.ar(
        ...     coefficient=0.5,
        ...     source=source,
        ...     )
        >>> one_zero
        OneZero.ar()

    """

    ### CLASS VARIABLES ###

    _ordered_input_names = collections.OrderedDict(
        [("source", None), ("coefficient", 0.5)]
    )

    _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)


text:
package com.google.tsunami.plugins.detectors.rce.vbulletin.cve201916759;

import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;
import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostname;
import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort;

import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.protobuf.util.Timestamps;
import com.google.tsunami.common.net.http.HttpClientModule;
import com.google.tsunami.common.net.http.HttpStatus;
import com.google.tsunami.common.time.testing.FakeUtcClock;
import com.google.tsunami.common.time.testing.FakeUtcClockModule;
import com.google.tsunami.proto.DetectionReport;
import com.google.tsunami.proto.DetectionStatus;
import com.google.tsunami.proto.NetworkEndpoint;
import com.google.tsunami.proto.NetworkService;
import com.google.tsunami.proto.Severity;
import com.google.tsunami.proto.Software;
import com.google.tsunami.proto.TargetInfo;
import com.google.tsunami.proto.TransportProtocol;
import com.google.tsunami.proto.Vulnerability;
import com.google.tsunami.proto.VulnerabilityId;
import java.io.IOException;
import java.time.Instant;
import javax.inject.Inject;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link VBulletinCve201916759Detector}. */
@RunWith(JUnit4.class)
public final class VBulletinCve201916759DetectorTest {
  private final FakeUtcClock fakeUtcClock =
      FakeUtcClock.create().setNow(Instant.parse("2020-01-01T00:00:00.00Z"));

  private MockWebServer mockWebServer;

  @Inject private VBulletinCve201916759Detector detector;

  private static TargetInfo buildTargetInfo(NetworkEndpoint networkEndpoint) {
    return TargetInfo.newBuilder().addNetworkEndpoints(networkEndpoint).build();
  }

  @Before
  public void setUp() {
    mockWebServer = new MockWebServer();
    Guice.createInjector(
            new FakeUtcClockModule(fakeUtcClock),
            new HttpClientModule.Builder().build(),
            new VBulletinCve201916759DetectorBootstrapModule())
        .injectMembers(this);
  }

  @After
  public void tearDown() throws IOException {
    mockWebServer.shutdown();
  }

  @Test
  public void detect_whenvBulletinIsVulnerable_returnsVulnerability() throws IOException {
    startMockWebServer("/", HttpStatus.OK.code(), "294b6ae1a318501bbf3d873c026fb36a");
    ImmutableList<NetworkService> httpServices =
        ImmutableList.of(
            NetworkService.newBuilder()
                .setNetworkEndpoint(
                    forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
                .setTransportProtocol(TransportProtocol.TCP)
                .setSoftware(Software.newBuilder().setName("http"))
                .setServiceName("http")
                .build());

    assertThat(
            detector
                .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), httpServices)
                .getDetectionReportsList())
        .containsExactly(
            DetectionReport.newBuilder()
                .setTargetInfo(buildTargetInfo(forHostname(mockWebServer.getHostName())))
                .setNetworkService(httpServices.get(0))
                .setDetectionTimestamp(
                    Timestamps.fromMillis(Instant.now(fakeUtcClock).toEpochMilli()))
                .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED)
                .setVulnerability(
                    Vulnerability.newBuilder()
                        .setMainId(
                            VulnerabilityId.newBuilder()
                                .setPublisher("GOOGLE")
                                .setValue("CVE_2019_16759"))
                        .setSeverity(Severity.CRITICAL)
                        .setTitle("vBulletin Pre-Auth RCE Vulnerability (CVE-2019-16759)")
                        .setDescription(
                            "Unauthenticated attacked can gain privileged access and control over"
                                + " any vBulletin server running versions 5.0.0 up to 5.5.4, and"
                                + " potentially lock organizations out from their own sites.")
                        .setRecommendation(
                            "Upgrade vBulletin to the latest version with security patches."))
                .build());
  }

  @Test
  public void detect_whenvBulletinIsNotVulnerable_doesNotReportVulnerability() throws IOException {
    startMockWebServer("/", HttpStatus.OK.code(), "irrelevant response");
    ImmutableList<NetworkService> httpServices =
        ImmutableList.of(
            NetworkService.newBuilder()
                .setNetworkEndpoint(
                    forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
                .setTransportProtocol(TransportProtocol.TCP)
                .setSoftware(Software.newBuilder().setName("http"))
                .setServiceName("http")
                .build());

    assertThat(
            detector
                .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), httpServices)
                .getDetectionReportsList())
        .isEmpty();
  }

  @Test
  public void detect_whenNonHttpNetworkService_ignoresServices() {
    ImmutableList<NetworkService> nonHttpServices =
        ImmutableList.of(
            NetworkService.newBuilder().setServiceName("ssh").build(),
            NetworkService.newBuilder().setServiceName("rdp").build());
    assertThat(
            detector
                .detect(buildTargetInfo(forHostname(mockWebServer.getHostName())), nonHttpServices)
                .getDetectionReportsList())
        .isEmpty();
  }

  @Test
  public void detect_whenEmptyNetworkService_generatesEmptyDetectionReports() {
    assertThat(
            detector
                .detect(
                    buildTargetInfo(forHostname(mockWebServer.getHostName())), ImmutableList.of())
                .getDetectionReportsList())
        .isEmpty();
  }

  private void startMockWebServer(String url, int responseCode, String response)
      throws IOException {
    mockWebServer.enqueue(new MockResponse().setResponseCode(responseCode).setBody(response));
    mockWebServer.start();
    mockWebServer.url(url);
  }
}


text:
export * from './AxisMarksPlugin';
export * from './AxisMarksWidget';


text:
import {Component, Input} from '@angular/core';

@Component({
  selector: 'ui-review',
  templateUrl: 'ui-review.html',
})
export class UIReviewComponent {

  /**
   * The title of the field
   */
  @Input() title: string;

  /**
   * The value of the field
   */
  @Input() value: string;
}


text:
var util = require('util');
var fs = require('fs');
var path = require('path');
var async = require('async');
var tool = require('leaptool');

module.exports = function(app, moduleName) {

    var block = {};

    block.getWeb = function(req, res) {
        var callback = arguments[3] || null;
        var parameter = tool.getReqParameter(req);
        var condition = tool.getQueryCondition(parameter);
        var filter = tool.getQueryFilter(parameter);
        block.get(req, res, condition, filter, callback);
    };

    block.get = function(req, res, condition, filter, callback) {
        app.db.find(moduleName, condition, filter, function(error, docs, info){
            app.cb(error, docs, info, req, res, callback);
        });
    };

    block.getCountWeb = function(req, res) {
        var callback = arguments[3] || null;
        var parameter = tool.getReqParameter(req);
        var condition = tool.getQueryCondition(parameter);
        var filter = tool.getQueryFilter(parameter);
        block.getCount(req, res, condition, filter, callback);
    };

    block.getCount = function(req, res, condition, filter, callback) {
        app.db.findCount(moduleName, condition, filter, function(error, docs, info){
            app.cb(error, docs, info, req, res, callback);
        });
    };

    block.getByIdWeb = function(req, res) {
        var callback = arguments[3] || null;
        var parameter = tool.getReqParameter(req);
        var id = parameter.id;
        block.getById(req, res, id, callback);
    };

    block.getById = function(req, res, id, callback) {
        var condition = { _id: id };
        var filter = {};
        app.db.find(moduleName, condition, filter, function(error, docs, info){
            app.cb(error, docs, info, req, res, callback);
        });
    };

    block.addWeb = function(req, res) {
        var callback = arguments[3] || null;
        var parameter = tool.getReqParameter(req);
        block.add(req, res, parameter, callback);
    };

    block.add = function(req, res, doc) {
        var callback = arguments[3] || null;
        app.db.add(moduleName, doc, function(error, docs, info) {
            app.cb(error, docs, info, req, res, callback);
        });
    };

    block.editWeb = function(req, res) {
        var callback = arguments[3] || null;
        var parameter = tool.getReqParameter(req);
        block.edit(req, res, parameter, callback);
    };

    block.edit = function(req, res, parameter) {
        var callback = arguments[3] || null;
        var model = app.module[moduleName].model;
        var id = parameter._id || parameter.id;
        // process the input document
        var inputDoc = {};
        for (var property in model) {
            if (parameter.hasOwnProperty(property)) {
                var value = app.engine.castData(parameter[property], model[property]);
                inputDoc[property] = value;
            }
        }
        app.db.findById(moduleName, id, function(error, doc, info) {
            if (!doc) {
                error = new Error('no doc found for id=' + id);
                app.cb(error, [], info, req, res, callback);
                return;
            }
            for (var property in model) {
                if (parameter.hasOwnProperty(property)) {
                    var type = model[property].type;
                    var subtype = model[property].subtype;
                    subtype = subtype && subtype.type;
                    if (type == 'string' && subtype == 'password') {
                        var saltValue = doc.salt || '';
                        doc[property] = tool.hash(parameter[property] + saltValue);
                    } else {
                        var value = app.engine.castData(parameter[property], model[property]);
                        doc[property] = value;
                    }
                }
            }
            app.db.updateById(moduleName, id, doc, function(error, docs, info) {
                app.cb(error, docs, info, req, res, callback);
            });
        });
    };

    return block;

};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TravelAgent.Web.admin.data
{
    public partial class Club : System.Web.UI.Page
    {
        private static readonly TravelAgent.BLL.Club ClubBll = new TravelAgent.BLL.Club();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] != null)
            {
                //TravelAgent.Model.Club model = ClubBll.GetModel(Convert.ToInt32(Request["id"]));

                //if (model != null)
                //{
                    //model.clubMobile = Request["txtMobile"];
                    //model.clubEmail = Request["txtEmail"];
                    //model.classId = Convert.ToInt32(Request["ddlClass"]);
                    //model.trueName = Request["txtName"];
                    //model.clubSex = Request["ddlSex"];
                    //model.clubBirthday = Request["txtBirthday"];
                    //model.isLock = Convert.ToInt32(Request["ddlLock"]);
                    string strsql = "update club set clubMobile='" + Request["txtMobile"] + "',clubEmail='" + Request["txtEmail"] + "',classId='" + Convert.ToInt32(Request["ddlClass"]) +
                                          "',trueName='" + Request["txtName"] + "',clubSex='" + Request["ddlSex"] + "',clubBirthday='" + Request["txtBirthday"] + "',isLock='" + Convert.ToInt32(Request["ddlLock"]) + "' where Id="+Request.QueryString["id"];
                    try
                    {
                        //Access
                        // if (TravelAgent.Tool.DbHelperOleDb.ExecuteSql(strsql) > 0)
                        //SQL
                        if (TravelAgent.Tool.DbHelperSQL.ExecuteSql(strsql) > 0)
                        {
                            Response.Write("true");
                        }
                        else
                        {
                            Response.Write("false");
                        }
                    }
                    catch
                    {
                        Response.Write("false");
                    }
                //}
                //else
                //{
                //    Response.Write("false");
                //}
            }
            if (Request["clubid"] != null)
            {
                try
                {
                    if (ClubBll.Delete(Convert.ToInt32(Request["clubid"])) > 0)
                    {
                        Response.Write("true");
                    }
                    else
                    {
                        Response.Write("false");
                    }
                }
                catch
                {
                    Response.Write("false");
                }
            }
        }
    }
}


text:
using namespace Gwen;

class Window : public GUnit
{
	public:

		GWEN_CONTROL_INLINE( Window, GUnit )
		{
			{
				Controls::Button* pButton = new Controls::Button( this );
				pButton->SetText( "Normal Window" );
				pButton->onPress.Add( this, &ThisClass::OpenWindow );
				pButton->SetPos( 0, 0 );
			}
			{
				Controls::Button* pButton = new Controls::Button( this );
				pButton->SetText( "Modal Window" );
				pButton->onPress.Add( this, &ThisClass::OpenModalWindow );
				pButton->SetPos( 0, 32 );
			}
			m_iWindowCount = 1;
		}

		void OpenWindow()
		{
			Controls::WindowControl* pWindow = new Controls::WindowControl( GetCanvas() );
			pWindow->SetTitle( Utility::Format( L"Window %i", m_iWindowCount ) );
			pWindow->SetSize( 200 + rand() % 100, 200 + rand() % 100 );
			pWindow->SetPos( rand() % 700, rand() % 400 );
			pWindow->SetDeleteOnClose( true );
			m_iWindowCount++;
		}

		void OpenModalWindow()
		{
			Controls::WindowControl* pWindow = new Controls::WindowControl( GetCanvas() );
			pWindow->SetTitle( Utility::Format( L"Window %i", m_iWindowCount ) );
			pWindow->SetSize( 200 + rand() % 100, 200 + rand() % 100 );
			pWindow->MakeModal( true );
			pWindow->Position( Pos::Center );
			pWindow->SetDeleteOnClose( true );
			m_iWindowCount++;
		}

		int m_iWindowCount;

};

DEFINE_UNIT_TEST( Window, L"Window" );
#include <hadesmem/detail/warning_disable_suffix.hpp>


text:
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Xunit;

namespace Networks.Tests
{
    public class TestHelper
    {
        public static PublicIpAddress CreateDefaultPublicIpAddress(string name, string resourceGroupName, string domainNameLabel, string location,
            NetworkResourceProviderClient nrpClient)
        {
            var publicIp = new PublicIpAddress()
            {
                Location = location,
                Tags = new Dictionary<string, string>()
                    {
                       {"key","value"}
                    },
                PublicIpAllocationMethod = IpAllocationMethod.Dynamic,
                DnsSettings = new PublicIpAddressDnsSettings()
                {
                    DomainNameLabel = domainNameLabel
                }
            };

            // Put nic1PublicIpAddress
            var putPublicIpAddressResponse = nrpClient.PublicIpAddresses.CreateOrUpdate(resourceGroupName, name, publicIp);
            Assert.Equal(HttpStatusCode.OK, putPublicIpAddressResponse.StatusCode);
            Assert.Equal("Succeeded", putPublicIpAddressResponse.Status);
            var getPublicIpAddressResponse = nrpClient.PublicIpAddresses.Get(resourceGroupName, name);

            return getPublicIpAddressResponse.PublicIpAddress;
        }

        public static NetworkInterface CreateNetworkInterface(
            string name,
            string resourceGroupName,
            string publicIpAddressId,
            string subnetId,
            string location,
            string ipConfigName,
            NetworkResourceProviderClient client)
        {
            var nicParameters = new NetworkInterface()
            {
                Location = location,
                Name = name,
                Tags = new Dictionary<string, string>()
                        {
                           {"key","value"}
                        },
                IpConfigurations = new List<NetworkInterfaceIpConfiguration>()
                {
                    new NetworkInterfaceIpConfiguration()
                    {
                         Name = ipConfigName,
                         PrivateIpAllocationMethod = IpAllocationMethod.Dynamic,

                         Subnet = new ResourceId()
                         {
                             Id = subnetId
                         }
                    }
                }
            };

            if (!string.IsNullOrEmpty(publicIpAddressId))
            {
                nicParameters.IpConfigurations[0].PublicIpAddress = new ResourceId() { Id = publicIpAddressId };
            }

            // Test NIC apis
            var putNicResponse = client.NetworkInterfaces.CreateOrUpdate(resourceGroupName, name, nicParameters);
            Assert.Equal(HttpStatusCode.OK, putNicResponse.StatusCode);

            var getNicResponse = client.NetworkInterfaces.Get(resourceGroupName, name);
            Assert.Equal(getNicResponse.NetworkInterface.Name, name);
            Assert.Equal(getNicResponse.NetworkInterface.ProvisioningState, Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded);

            return getNicResponse.NetworkInterface;
        }

        public static VirtualNetwork CreateVirtualNetwork(string vnetName, string subnetName, string resourceGroupName, string location, NetworkResourceProviderClient client)
        {
            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List<string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List<string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List<Subnet>()
                        {
                            new Subnet()
                            {
                                Name = subnetName,
                                AddressPrefix = "10.0.0.0/24",
                            }
                        }
            };

            var putVnetResponse = client.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
            Assert.Equal(HttpStatusCode.OK, putVnetResponse.StatusCode);
            var getVnetResponse = client.VirtualNetworks.Get(resourceGroupName, vnetName);

            return getVnetResponse.VirtualNetwork;
        }
    }
}


text:
package org.axonframework.domain;

import org.joda.time.DateTime;

import java.util.Map;

/**
 * Generic implementation of the EventMessage interface. It simply keeps a reference to the payload and MetaData.
 *
 * @param <T> The type of payload contained in this Message
 * @author Allard Buijze
 * @since 2.0
 */
public class GenericEventMessage<T> extends GenericMessage<T> implements EventMessage<T> {

    private static final long serialVersionUID = -8370948891267874107L;

    private final DateTime timestamp;

    /**
     * Returns the given event as an EventMessage. If event already implements EventMessage, it is
     * returned as-is. If it is a Message, a new EventMessage will be created using the payload and meta data of the
     * given message. Otherwise, the given event is wrapped into a GenericEventMessage as its payload.
     *
     * @param event the event to wrap as EventMessage
     * @param <T>   The generic type of the expected payload of the resulting object
     * @return an EventMessage containing given event as payload, or event if it already
     *         implements EventMessage.
     */
    @SuppressWarnings("unchecked")
    public static <T> EventMessage<T> asEventMessage(Object event) {
        if (EventMessage.class.isInstance(event)) {
            return (EventMessage<T>) event;
        } else if (event instanceof Message) {
            Message message = (Message) event;
            return new GenericEventMessage<T>((T) message.getPayload(), message.getMetaData());
        }
        return new GenericEventMessage<T>((T) event);
    }

    /**
     * Creates a GenericEventMessage with given payload, and an empty MetaData.
     *
     * @param payload The payload for the message
     * @see #asEventMessage(Object)
     */
    public GenericEventMessage(T payload) {
        this(payload, MetaData.emptyInstance());
    }

    /**
     * Creates a GenericEventMessage with given payload and given metaData.
     *
     * @param payload  The payload of the EventMessage
     * @param metaData The MetaData for the EventMessage
     * @see #asEventMessage(Object)
     */
    public GenericEventMessage(T payload, Map<String, ?> metaData) {
        super(IdentifierFactory.getInstance().generateIdentifier(), payload, metaData);
        this.timestamp = new DateTime();
    }

    /**
     * Constructor to reconstruct an EventMessage using existing data.
     *
     * @param identifier The identifier of the Message
     * @param timestamp  The timestamp of the Message creation
     * @param payload    The payload of the message
     * @param metaData   The meta data of the message
     */
    public GenericEventMessage(String identifier, DateTime timestamp, T payload, Map<String, ?> metaData) {
        super(identifier, payload, metaData);
        this.timestamp = timestamp;
    }

    /**
     * Copy constructor that allows creation of a new GenericEventMessage with modified metaData. All information
     * from the original is copied, except for the metaData.
     *
     * @param original The original message
     * @param metaData The MetaData for the new message
     */
    private GenericEventMessage(GenericEventMessage<T> original, Map<String, ?> metaData) {
        super(original.getIdentifier(), original.getPayload(), metaData);
        this.timestamp = original.getTimestamp();
    }

    @Override
    public DateTime getTimestamp() {
        return timestamp;
    }

    @Override
    public GenericEventMessage<T> withMetaData(Map<String, ?> newMetaData) {
        if (getMetaData().equals(newMetaData)) {
            return this;
        }
        return new GenericEventMessage<T>(this, newMetaData);
    }

    @Override
    public GenericEventMessage<T> andMetaData(Map<String, ?> additionalMetaData) {
        if (additionalMetaData.isEmpty()) {
            return this;
        }
        return new GenericEventMessage<T>(this, getMetaData().mergedWith(additionalMetaData));
    }

    @Override
    public String toString() {
        return String.format("GenericEventMessage[%s]", getPayload().toString());
    }
}


text:
'use strict';
/* eslint-disable import/order */
const process = require('./process-adapter');

const opts = process.opts;
const testPath = opts.file;

// Bind globals first before anything has a chance to interfere
const globals = require('./globals');
globals.options = opts;
const Promise = require('bluebird');

// Bluebird specific
Promise.longStackTraces();

(opts.require || []).forEach(require);

process.installSourceMapSupport();

const currentlyUnhandled = require('currently-unhandled')();
const serializeError = require('./serialize-error');
const send = process.send;
const throwsHelper = require('./throws-helper');

// Check if test files required ava and show error, when they didn't
exports.avaRequired = false;

process.installPrecompilerHook();

const dependencies = [];
process.installDependencyTracking(dependencies, testPath);

require(testPath); // eslint-disable-line import/no-dynamic-require

process.on('unhandledRejection', throwsHelper);

process.on('uncaughtException', exception => {
	throwsHelper(exception);
	send('uncaughtException', {exception: serializeError(exception)});
});

// If AVA was not required, show an error
if (!exports.avaRequired) {
	send('no-tests', {avaRequired: false});
}

// Parse and re-emit AVA messages
process.on('message', message => {
	if (!message.ava) {
		return;
	}

	process.emit(message.name, message.data);
});

process.on('ava-exit', () => {
	// Use a little delay when running on AppVeyor (because it's shit)
	const delay = process.env.AVA_APPVEYOR ? 100 : 0;

	globals.setTimeout(() => {
		process.exit(0); // eslint-disable-line xo/no-process-exit
	}, delay);
});

let tearingDown = false;
process.on('ava-teardown', () => {
	// AVA-teardown can be sent more than once
	if (tearingDown) {
		return;
	}
	tearingDown = true;

	let rejections = currentlyUnhandled();

	if (rejections.length === 0) {
		exit();
		return;
	}

	rejections = rejections.map(rejection => {
		return serializeError(rejection.reason);
	});

	send('unhandledRejections', {rejections});
	globals.setTimeout(exit, 100);
});

function exit() {
	// Include dependencies in the final teardown message. This ensures the full
	// set of dependencies is included no matter how the process exits, unless
	// it flat out crashes.
	send('teardown', {dependencies});
}


text:
var _fs = require('fs'),
  _path = require('path'),
  download = require('download-git-repo'),
  sparqljsPackage = require('../sparql/node_modules/sparqljs/package.json'),
  sparqljsSrcFolder = _path.join(__dirname, '../sparql/node_modules/sparqljs-src'),
  sparqlFolder = _path.join(sparqljsSrcFolder, 'queries');

if (!_fs.existsSync(sparqlFolder)) {
  download('github:RubenVerborgh/SPARQL.js#v' + sparqljsPackage.version, sparqljsSrcFolder, function (err) {
    if (err)
      console.err(err);
    else
      console.log('Downloaded', sparqljsSrcFolder);
  });
} else {
  console.log(sparqljsSrcFolder, 'exists');
}


text:
package com.example.tests;

	public class ContactData implements Comparable<ContactData>
	{
		private String id;
		private String firstName;
		private String lastName;
		private String postalAddress;
		private String homePhoneNumber;
		private String mobilePhoneNumber;
		private String workPhoneNumber;
		private String firstEmail;
		private String secondEmail;
		private String dayOfBirth;
		private String monthOfBirth;
		private String yearOfBirth;
		private String groupName;
		private String additionalPostalAddress;
		private String additionalPhoneNumber;

		public ContactData()
		{
			this.firstName = "";
			this.lastName = "";
			this.postalAddress = "";
			this.homePhoneNumber = "";
			this.mobilePhoneNumber = "";
			this.workPhoneNumber = "";
			this.firstEmail = "";
			this.secondEmail = "";
			this.dayOfBirth = "-";
			this.monthOfBirth = "-";
			this.yearOfBirth = "";
			this.groupName = "[none]";
			this.additionalPostalAddress = "";
			this.additionalPhoneNumber = "";
		}

		public String getId()
		{
			return id;
		}

		public void setId(String id)
		{
			this.id = id;
		}

		public String getFirstName()
		{
			return firstName;
		}

		public void setFirstName(String firstName)
		{
			this.firstName = firstName;
		}

		public String getLastName()
		{
			return lastName;
		}

		public void setLastName(String lastName)
		{
			this.lastName = lastName;
		}

		public String getPostalAddress()
		{
			return postalAddress;
		}

		public void setPostalAddress(String postalAddress)
		{
			this.postalAddress = postalAddress;
		}

		public String getHomePhoneNumber()
		{
			return homePhoneNumber;
		}

		public void setHomePhoneNumber(String homePhoneNumber)
		{
			this.homePhoneNumber = homePhoneNumber;
		}

		public String getMobilePhoneNumber()
		{
			return mobilePhoneNumber;
		}

		public void setMobilePhoneNumber(String mobilePhoneNumber)
		{
			this.mobilePhoneNumber = mobilePhoneNumber;
		}

		public String getWorkPhoneNumber()
		{
			return workPhoneNumber;
		}

		public void setWorkPhoneNumber(String workPhoneNumber)
		{
			this.workPhoneNumber = workPhoneNumber;
		}

		public String getFirstEmail()
		{
			return firstEmail;
		}

		public void setFirstEmail(String firstEmail)
		{
			this.firstEmail = firstEmail;
		}

		public String getSecondEmail()
		{
			return secondEmail;
		}

		public void setSecondEmail(String secondEmail)
		{
			this.secondEmail = secondEmail;
		}

		public String getDayOfBirth()
		{
			return dayOfBirth;
		}

		public void setDayOfBirth(String dayOfBirth)
		{
			this.dayOfBirth = dayOfBirth;
		}

		public String getMonthOfBirth()
		{
			return monthOfBirth;
		}

		public void setMonthOfBirth(String monthOfBirth)
		{
			this.monthOfBirth = monthOfBirth;
		}

		public String getYearOfBirth()
		{
			return yearOfBirth;
		}

		public void setYearOfBirth(String yearOfBirth)
		{
			this.yearOfBirth = yearOfBirth;
		}

		public String getGroupName()
		{
			return groupName;
		}

		public void setGroupName(String groupName)
		{
			this.groupName = groupName;
		}

		public String getAdditionalPostalAddress()
		{
			return additionalPostalAddress;
		}

		public void setAdditionalPostalAddress(String additionalPostalAddress)
		{
			this.additionalPostalAddress = additionalPostalAddress;
		}

		public String getAdditionalPhoneNumber()
		{
			return additionalPhoneNumber;
		}

		public void setAdditionalPhoneNumber(String additionalPhoneNumber)
		{
			this.additionalPhoneNumber = additionalPhoneNumber;
		}

		@Override
		public String toString()
		{
			return "ContactData [firstName=" + firstName +
			       ", lastName=" + lastName +
			       ", homePhoneNumber=" + homePhoneNumber +
			       ", firstEmail=" + firstEmail + "]";
		}

		@Override
		public int hashCode()
		{
			final int prime = 31;
			int result = 1;
			result = prime * result	+ ((firstName == null) ? 0 : firstName.hashCode());
			result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj)
		{
			if(this == obj) return true;
			if(obj == null) return false;
			if(getClass() != obj.getClass()) return false;
			ContactData other = (ContactData) obj;
			if(firstName == null)
			{
				if(other.firstName != null) return false;
			}
			else if(!firstName.equals(other.firstName)) return false;
			if (lastName == null)
			{
				if (other.lastName != null) return false;
			} else if (!lastName.equals(other.lastName)) return false;

			return true;
		}

		@Override
		public int compareTo(ContactData other)
		{
			String vThisFullName;
			String vOtherFullName;

			vThisFullName = this.getLastName().toLowerCase() + " " + this.getFirstName().toLowerCase();
			vOtherFullName = other.getLastName().toLowerCase() + " " + other.getFirstName().toLowerCase();
			return vThisFullName.compareTo(vOtherFullName);
		}

		public ContactData withId(String id)
		{
			this.id = id;
			return this;
		}

		public ContactData withFirstName(String firstName)
		{
			this.firstName = firstName;
			return this;
		}

		public ContactData withLastName(String lastName)
		{
			this.lastName = lastName;
			return this;
		}

		public ContactData withPostalAddress(String postalAddress)
		{
			this.postalAddress = postalAddress;
			return this;
		}

		public ContactData withHomePhoneNumber(String homePhoneNumber)
		{
			this.homePhoneNumber = homePhoneNumber;
			return this;
		}

		public ContactData withMobilePhoneNumber(String mobilePhoneNumber)
		{
			this.mobilePhoneNumber = mobilePhoneNumber;
			return this;
		}

		public ContactData withWorkPhoneNumber(String workPhoneNumber)
		{
			this.workPhoneNumber = workPhoneNumber;
			return this;
		}

		public ContactData withFirstEmail(String firstEmail)
		{
			this.firstEmail = firstEmail;
			return this;
		}

		public ContactData withSecondEmail(String secondEmail)
		{
			this.secondEmail = secondEmail;
			return this;
		}

		public ContactData withDayOfBirth(String dayOfBirth)
		{
			this.dayOfBirth = dayOfBirth;
			return this;
		}

		public ContactData withMonthOfBirth(String monthOfBirth)
		{
			this.monthOfBirth = monthOfBirth;
			return this;
		}

		public ContactData withYearOfBirth(String yearOfBirth)
		{
			this.yearOfBirth = yearOfBirth;
			return this;
		}

		public ContactData withGroupName(String groupNameForContactData)
		{
			groupName = groupNameForContactData;
			return this;
		}

		public ContactData withAdditionalPostalAddress(String additionalPostalAddress)
		{
			this.additionalPostalAddress = additionalPostalAddress;
			return this;
		}

		public ContactData withAdditionalPhoneNumber(String additionalPhoneNumber)
		{
			this.additionalPhoneNumber = additionalPhoneNumber;
			return this;
		}
	}


text:
using std::cout;
using std::endl;
using std::map;
using std::vector;
using std::string;
using std::pair;

void AddFamily(map<string, vector<pair<string, string>>> &families, const string &family) {
  families[family];
}

void AddChild(map<string, vector<pair<string, string>>> &families, const string &family, const string &child, const string &birthday) {
  families[family].push_back(make_pair(child, birthday));
}

int main()
{
  map<string, vector<pair<string, string>>> families;
  AddFamily(families, "A");
  AddChild(families, "A", "aa", "1990-1-1");
  AddChild(families, "A", "aaa", "1991-2-2");
  AddChild(families, "A", "aaaa", "1993-3-3");
  AddFamily(families, "B");
  AddChild(families, "B", "bb", "2001-1-1");
  AddChild(families, "B", "bbbbb", "2002-2-2");
  AddFamily(families, "C");
  AddChild(families, "C", "cccc", "1998-8-8");
  for(const auto &f : families) {
    cout << endl << "Familiy: " << f.first << endl;;
    cout << "Children: " << endl;
    for(const auto &c : f.second) {
      cout << c.first << " " << c.second << endl;;
    }
  }
  return 0;
}


text:
DistributedLock is a .NET library that provides robust and easy-to-use distributed mutexes, reader-writer locks, and semaphores based on a variety of underlying technologies.

With DistributedLock, synchronizing access to a region of code across multiple applications/machines is as simple as:
```C#
await using (await myDistributedLock.AcquireAsync())
{
	// I hold the lock here
}
```

## Implementations

DistributedLock contains implementations based on various technologies; you can install implementation packages individually or just install the [DistributedLock NuGet package](https://www.nuget.org/packages/DistributedLock) [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.svg?style=flat)](https://www.nuget.org/packages/DistributedLock/), a ["meta" package](https://endjin.com/blog/2020/09/streamline-dependency-management-with-nuget-meta-packages) which includes all implementations as dependencies. *Note that each package is versioned independently according to SemVer*.

- **[DistributedLock.SqlServer](docs/DistributedLock.SqlServer.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.SqlServer.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.SqlServer/): uses Microsoft SQL Server
- **[DistributedLock.Postgres](docs/DistributedLock.Postgres.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.Postgres.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.Postgres/): uses Postgresql
- **[DistributedLock.MySql](docs/DistributedLock.MySql.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.MySql.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.MySql/): uses MySQL or MariaDB
- **[DistributedLock.Oracle](docs/DistributedLock.Oracle.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.Oracle.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.Oracle/): uses Oracle
- **[DistributedLock.Redis](docs/DistributedLock.Redis.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.Redis.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.Redis/): uses Redis
- **[DistributedLock.Azure](docs/DistributedLock.Azure.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.Azure.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.Azure/): uses Azure blobs
- **[DistributedLock.ZooKeeper](docs/DistributedLock.ZooKeeper.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.ZooKeeper.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.ZooKeeper/): uses Apache ZooKeeper
- **[DistributedLock.FileSystem](docs/DistributedLock.FileSystem.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.FileSystem.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.FileSystem/): uses lock files
- **[DistributedLock.WaitHandles](docs/DistributedLock.WaitHandles.md)** [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.WaitHandles.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.WaitHandles/): uses operating system global `WaitHandle`s (Windows only)

**Click on the name** of any of the above packages to see the documentation specific to that implementation, or read on for general documentation that applies to all implementations.

The [DistributedLock.Core](https://www.nuget.org/packages/DistributedLock.Core) [![NuGet Status](http://img.shields.io/nuget/v/DistributedLock.Core.svg?style=flat)](https://www.nuget.org/packages/DistributedLock.Core/) package contains common code and abstractions and is referenced by all implementations.

## Synchronization primitives

- Locks: provide exclusive access to a region of code
- [Reader-writer locks](docs/Reader-writer%20locks.md): a lock with multiple levels of access. The lock can be held concurrently either by any number of "readers" or by a single "writer".
- [Semaphores](docs/Semaphores.md): similar to a lock, but can be held by up to N users concurrently instead of just one.

While all implementations support locks, the other primitives are only supported by some implementations. See the [implementation-specific documentation pages](docs) for details.

## Basic usage

### Names

Because distributed locks (and other distributed synchronization primitives) are not isolated to a single process, their identity is based on their name which is provided through the constructor. Different underlying technologies have different restrictions on name format; however, DistributedLock largely allows you to ignore these by escaping/hashing names that would otherwise be invalid.

### Acquire

All synchronization primitives support the same basic access pattern. The `Acquire` method returns a "handle" object that represents holding the lock. When the handle is disposed, the lock is released:

```C#
var myDistributedLock = new SqlDistributedLock(name, connectionString); // e. g. if we are using SQL Server
using (myDistributedLock.Acquire())
{
	// we hold the lock here
} // implicit Dispose() call from using block releases it here
```

### TryAcquire

While `Acquire` will block until the lock is available, there is also a `TryAcquire` variant which returns `null` if the lock could not be acquired (due to being held elsewhere):

```C#
using (var handle = myDistributedLock.TryAcquire())
{
	if (handle != null)
	{
		// we acquired the lock :-)
	}
	else
	{
		// someone else has it :-(
	}
}
```

### async support

`async` versions of both of these methods are also supported. These are preferred when you are writing async code since they will not consume a thread while waiting for the lock. If you are using C#8 or higher, you can also dispose of handles asynchronously:

### Timeouts

```C#
await using (await myDistributedLock.AcquireAsync()) { ... }
```

Additionally, all of these methods support an optional `timeout` parameter. `timeout` determines how long `Acquire` will wait before failing with a `TimeoutException` and how long `TryAcquire` will wait before returning null. The default `timeout` for `Acquire` is `Timeout.InfiniteTimeSpan` while for `TryAcquire` the default `timeout` is `TimeSpan.Zero`.

### Cancellation

Finally, the methods take an optional `CancellationToken` parameter, which allows for the acquire operation to be interrupted via cancellation. Note that this won't cancel the hold on the lock once the acquire succeeds.

## Providers

For applications that use [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection), DistributedLock's providers make it easy to separate out the specification of a lock's (or other primitive's) name from its other settings (such as a database connection string). For example in an ASP.NET Core app you might do:

```C#
// in your Startup.cs:
services.AddSingleton<IDistributedLockProvider>(_ => new PostgresDistributedSynchronizationProvider(myConnectionString));
services.AddTransient<SomeService>();

// in SomeService.cs
public class SomeService
{
	private readonly IDistributedLockProvider _synchronizationProvider;

	public SomeService(IDistributedLockProvider synchronizationProvider)
	{
		this._synchronizationProvider = synchronizationProvider;
	}

	public void InitializeUserAccount(int id)
	{
		// use the provider to construct a lock
		var @lock = this._synchronizationProvider.CreateLock($"UserAccount{id}");
		using (@lock.Acquire())
		{
			// do stuff
		}

		// ALTERNATIVELY, for common use-cases extension methods allow this to be done with a single call
		using (this._synchronizationProvider.AcquireLock($"UserAccount{id}"))
		{
			// do stuff
		}
	}
}
```

## Other topics

- [Interfaces](docs/Other%20topics.md#interfaces)
- [Detecting handle loss](docs/Other%20topics.md#detecting-handle-loss)
- [Handle abandonment](docs/Other%20topics.md#handle-abandonment)
- [Safety of distributed locking](docs/Other%20topics.md#safety-of-distributed-locking)

## Contributing

Contributions are welcome! If you are interested in contributing towards a new or existing issue, please let me know via comments on the issue so that I can help you get started and avoid wasted effort on your part.

## Release notes
- 2.3.2
	- Work around underlying Postgres race condition when waiting on advisory locks with a short non-zero timeout ([#147](https://github.com/madelson/DistributedLock/issues/147), DistributedLock.Postgres 1.0.4). Thanks [@Tzachi009](https://github.com/Tzachi009) for reporting and isolating the issue!
- 2.3.1
	- Fixed concurrency issue with `HandleLostToken` for relational database locks ([#133](https://github.com/madelson/DistributedLock/issues/133), DistributedLock.Core 1.0.5, DistributedLock.MySql 1.0.1, DistributedLock.Oracle 1.0.1, DistributedLock.Postgres 1.0.3, DistributedLock.SqlServer 1.0.2). Thanks [@OskarKlintrot](https://github.com/OskarKlintrot) for testing!
	- Fixed misleading error message why trying to disable auto-extension in Redis ([#130](https://github.com/madelson/DistributedLock/issues/130), DistributedLock.Redis 1.0.2)
	- Fixed concurrency issue with canceling async waits on `WaitHandle`s ([#120](https://github.com/madelson/DistributedLock/issues/120), DistributedLock.WaitHandles 1.0.1)
- 2.3.0
	- Added Oracle-based implementation ([#45](https://github.com/madelson/DistributedLock/issues/45), DistributedLock.Oracle 1.0.0). Thanks [@odin568](https://github.com/odin568) for testing!
	- Made file-based locking more robust to transient `UnauthorizedAccessException`s ([#106](https://github.com/madelson/DistributedLock/issues/106) & [#109](https://github.com/madelson/DistributedLock/issues/109), DistributedLock.FileSystem 1.0.1)
	- Work around cancellation bug in Npgsql command preparation ([#112](https://github.com/madelson/DistributedLock/issues/112), DistributedLock.Postgres 1.0.2)
- 2.2.0
	- Added MySQL/MariaDB-based implementation ([#95](https://github.com/madelson/DistributedLock/issues/95), DistributedLock.MySql 1.0.0). Thanks [@theplacefordev](https://github.com/theplacefordev) for testing!
- 2.1.0
	- Added ZooKeeper-based implementation ([#41](https://github.com/madelson/DistributedLock/issues/41), DistributedLock.ZooKeeper 1.0.0)
- 2.0.2
	- Fixed bug where `HandleLostToken` would hang when accessed on a SqlServer or Postgres lock handle that used keepalive ([#85](https://github.com/madelson/DistributedLock/issues/85), DistributedLock.Core 1.0.1)
	- Fixed bug where broken database connections could result in future lock attempts failing when using SqlServer or Postgres locks with multiplexing ([#83](https://github.com/madelson/DistributedLock/issues/83), DistributedLock.Core 1.0.1)
	- Updated Npgsql dependency to 5.x to take advantage of various bugfixes ([#61](https://github.com/madelson/DistributedLock/issues/61), DistributedLock.Postgres 1.0.1)
- 2.0.1
	- Fixed Redis lock behavior when using a database with `WithKeyPrefix` ([#66](https://github.com/madelson/DistributedLock/issues/66), DistributedLock.Redis 1.0.1). Thanks [@skomis-mm](https://github.com/skomis-mm) for contributing!
- 2.0.0 (see also [Migrating from 1.x to 2.x](docs/Migrating%20from%201.x%20to%202.x.md#migrating-from-1x-to-2x))
	- Revamped package structure so that DistributedLock is now an umbrella package and each implementation technology has its own package (BREAKING CHANGE)
	- Added Postgresql-based locking ([#56](https://github.com/madelson/DistributedLock/issues/56), DistributedLock.Postgres 1.0.0)
	- Added Redis-based locking ([#24](https://github.com/madelson/DistributedLock/issues/24), DistributedLock.Redis 1.0.0)
	- Added Azure blob-based locking ([#42](https://github.com/madelson/DistributedLock/issues/42), DistributedLock.Azure 1.0.0)
	- Added file-based locking ([#28](https://github.com/madelson/DistributedLock/issues/28), DistributedLock.FileSystem 1.0.0)
	- Added provider classes for improved IOC integration ([#13](https://github.com/madelson/DistributedLock/issues/13))
	- Added strong naming to assemblies. Thanks [@pedropaulovc](https://github.com/pedropaulovc) for contributing! ([#47](https://github.com/madelson/DistributedLock/issues/47), BREAKING CHANGE)
	- Made lock handles implement `IAsyncDisposable` in addition to `IDisposable` [#20](https://github.com/madelson/DistributedLock/issues/20), BREAKING CHANGE)
	- Exposed implementation-agnostic interfaces (e. g. `IDistributedLock`) for all synchronization primitives ([#10](https://github.com/madelson/DistributedLock/issues/10))
	- Added `HandleLostToken` API for tracking if a lock's underlying connection dies ([#6](https://github.com/madelson/DistributedLock/issues/6), BREAKING CHANGE)
	- Added SourceLink support ([#57](https://github.com/madelson/DistributedLock/issues/57))
	- Removed `GetSafeName` API in favor of safe naming by default (BREAKING CHANGE)
	- Renamed "SystemDistributedLock" to "EventWaitHandleDistributedLock" (DistributedLock.WaitHandles 1.0.0)
	- Stopped supporting net45 (BREAKING CHANGE)
	- Removed `DbConnection` and `DbTransaction` constructors form `SqlDistributedLock`, leaving the constructors that take `IDbConnection`/`IDbTransaction` ([#35](https://github.com/madelson/DistributedLock/issues/35), BREAKING CHANGE)
	- Changed methods returning `Task<IDisposable>` to instead return `ValueTask`, making it so that `using (@lock.AcquireAsync()) { ... } without an `await` no longer compiles (#34, BREAKING CHANGE)
	- Changed `UpgradeableLockHandle.UpgradeToWriteLock` to return `void` ([#33](https://github.com/madelson/DistributedLock/issues/33), BREAKING CHANGE)
	- Switched to Microsoft.Data.SqlClient by default for all target frameworks (BREAKING CHANGE)
	- Changed all locking implementations to be non-reentrant (BREAKING CHANGE)
- 1.5.0
	- Added cross-platform support via Microsoft.Data.SqlClient ([#25](https://github.com/madelson/DistributedLock/issues/25)). This feature is available for .NET Standard >= 2.0. Thanks to [@alesebi91](https://github.com/alesebi91) for helping with the implementation and testing!
	- Added C#8 nullable annotations ([#31](https://github.com/madelson/DistributedLock/issues/31))
	- Fixed minor bug in connection multiplexing which could lead to more lock contention ([#32](https://github.com/madelson/DistributedLock/issues/32))
- 1.4.0
	- Added a SQL-based distributed semaphore ([#7](https://github.com/madelson/DistributedLock/issues/7))
	- Fix bug where SqlDistributedLockConnectionStrategy.Azure would leak connections, relying on GC to reclaim them ([#14](https://github.com/madelson/DistributedLock/issues/14)). Thanks [zavalita1](https://github.com/zavalita1) for investigating this issue!
	- Throw a specific exception type (`DeadlockException`) rather than the generic `InvalidOperationException` when a deadlock is detected ([#11](https://github.com/madelson/DistributedLock/issues/11))
- 1.3.1 Minor fix to avoid "leaking" isolation level changes in transaction-based locks ([#8](https://github.com/madelson/DistributedLock/issues/8)). Also switched to the VS2017 project file format
- 1.3.0 Added an Azure connection strategy to keep lock connections from becoming idle and being reclaimed by Azure's connection governor ([#5](https://github.com/madelson/DistributedLock/issues/5))
- 1.2.0
	- Added a SQL-based distributed reader-writer lock
	- .NET Core support via .NET Standard
	- Changed the default locking scope for SQL distributed lock to be a connection rather than a transaction, avoiding cases where long-running transactions can block backups
	- Allowed for customization of the SQL distributed lock connection strategy when connecting via a connection string
	- Added a new connection strategy which allows for multiplexing multiple held locks onto one connection
	- Added IDbConnection/IDbTransaction constructors ([#3](https://github.com/madelson/DistributedLock/issues/3))
- 1.1.0 Added support for SQL distributed locks scoped to existing connections/transactions
- 1.0.1 Minor fix when using infinite timeouts
- 1.0.0 Initial release


text:
var error = require('./error'),
  AuthCodeGrant = require('./authCodeGrant'),
  Authorise = require('./authorise'),
  Grant = require('./grant');

module.exports = OAuth2Server;

/**
 * Constructor
 *
 * @param {Object} config Configuration object
 */
function OAuth2Server (config) {

  if (!(this instanceof OAuth2Server)) return new OAuth2Server(config);

  config = config || {};

  if (!config.model) throw new Error('No model supplied to OAuth2Server');
  this.model = config.model;

  this.grants = config.grants || [];
  this.debug = config.debug || function () {};
  if (typeof this.debug !== 'function') {
      this.debug = console.log;
  }
  this.passthroughErrors = config.passthroughErrors;
  this.continueAfterResponse = config.continueAfterResponse;

  this.accessTokenLifetime = config.accessTokenLifetime !== undefined ?
    config.accessTokenLifetime : 3600;
  this.refreshTokenLifetime = config.refreshTokenLifetime !== undefined ?
    config.refreshTokenLifetime : 1209600;
  this.authCodeLifetime = config.authCodeLifetime || 30;

  this.regex = {
    clientId: config.clientIdRegex || /^[a-z0-9-_]{3,40}$/i,
    grantType: new RegExp('^(' + this.grants.join('|') + ')$', 'i')
  };
}

/**
 * Authorisation Middleware
 *
 * Returns middleware that will authorise the request using oauth,
 * if successful it will allow the request to proceed to the next handler
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.authorise = function () {
  var self = this;

  return function (req, res, next) {
    new Authorise(self, req, next);
  };
};

/**
 * Grant Middleware
 *
 * Returns middleware that will grant tokens to valid requests.
 * This would normally be mounted at '/oauth/token' e.g.
 *
 * `app.all('/oauth/token', oauth.grant());`
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.grant = function () {
  var self = this;

  return function (req, res, next) {
    new Grant(self, req, res, next);
  };
};

/**
 * Code Auth Grant Middleware
 *
 * @param  {Function} check Function will be called with req to check if the
 *                          user has authorised the request.
 * @return {Function}       middleware
 */
OAuth2Server.prototype.authCodeGrant = function (check) {
  var self = this;

  return function (req, res, next) {
    new AuthCodeGrant(self, req, res, next, check);
  };
};

/**
 * OAuth Error Middleware
 *
 * Returns middleware that will catch OAuth errors and ensure an OAuth
 * complaint response
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.errorHandler = function () {
  var self = this;

  return function (err, req, res, next) {
    if (!(err instanceof error) || self.passthroughErrors) return next(err);

    delete err.name;
    delete err.message;

    self.debug(err.stack || err);
    delete err.stack;

    if (err.headers) res.set(err.headers);
    delete err.headers;

    res.send(err.code, err);
  };
};

/**
 * Lockdown
 *
 * When using the lockdown patter, this function should be called after
 * all routes have been declared.
 * It will search through each route and if it has not been explitly bypassed
 * (by passing oauth.bypass) then authorise will be inserted.
 * If oauth.grant has been passed it will replace it with the proper grant
 * middleware
 * NOTE: When using this method, you must PASS the method not CALL the method,
 * e.g.:
 *
 * `
 * app.all('/oauth/token', app.oauth.grant);
 *
 * app.get('/secrets', function (req, res) {
 *   res.send('secrets');
 * });
 *
 * app.get('/public', app.oauth.bypass, function (req, res) {
 *   res.send('publci');
 * });
 *
 * app.oauth.lockdown(app);
 * `
 *
 * @param  {Object} app Express app
 */
OAuth2Server.prototype.lockdown = function (app) {
  var self = this;

  var lockdownExpress3 = function (stack) {
    // Check if it's a grant route
    var pos = stack.indexOf(self.grant);
    if (pos !== -1) {
      stack[pos] = self.grant();
      return;
    }

    // Check it's not been explitly bypassed
    pos = stack.indexOf(self.bypass);
    if (pos === -1) {
      stack.unshift(self.authorise());
    } else {
      stack.splice(pos, 1);
    }
  };

  var lockdownExpress4 = function (layer) {
    if (!layer.route)
      return;

    var stack = layer.route.stack;
    var handlers = stack.map(function (item) {
      return item.handle;
    });

    // Check if it's a grant route
    var pos = handlers.indexOf(self.grant);
    if (pos !== -1) {
      stack[pos].handle = self.grant();
      return;
    }

    // Check it's not been explitly bypassed
    pos = handlers.indexOf(self.bypass);
    if (pos === -1) {
      // Add authorise another route (could do it properly with express.route?)
      var copy = {};
      var first = stack[0];
      for (var key in first) {
        copy[key] = first[key];
      }
      copy.handle = self.authorise();
      stack.unshift(copy);
    } else {
      stack.splice(pos, 1);
    }
  };

  if (app.routes) {
    for (var method in app.routes) {
      app.routes[method].callbacks.forEach(lockdownExpress3);
    }
  } else {
    app._router.stack.forEach(lockdownExpress4);
  }
};

/**
 * Bypass
 *
 * This is used as placeholder for when using the lockdown pattern
 *
 * @return {Function} noop
 */
OAuth2Server.prototype.bypass = function () {};


text:
const sequelize 	= require('sequelize')
const express 		= require('express')
const bodyParser 	= require('body-parser')
const session 		= require('express-session')
const pug			= require('pug')
const pg 			= require('pg')
const sass			= require('node-sass')
const db			= require(__dirname + '/routes/database.js')

const app			= express()

app.set( 'view engine', 'pug')
app.set( 'views', __dirname + '/views' )

// Routes
let searchRoute 		= require(__dirname + '/routes/search')
let findJsonRoute		= require(__dirname + '/routes/findJson')

app.use( express.static('static'))
app.use( bodyParser.urlencoded({extended: true}))

// Routes
app.use( searchRoute )
app.use( findJsonRoute )

//listen port 8000
app.listen(8000, () => {
	console.log('Server is running')
})


text:
  <md-content layout-padding>
    <form ng-submit="prayerList.createPrayer()">
      <md-input-container>
        New request
        <input ng-model="prayerList.request">
      </md-input-container>
      <md-input-container>
        <md-button md-no-ink class="md-primary" ng-show="prayerList.request">Create request</md-button>
      </md-input-container>
    </form>
    <md-list>
      <md-list-item class="md-2-line" ng-repeat="prayer in prayerList.prayers" ng-click="prayerList.openPrayer(prayer._id)">

{{ lookupUser(prayer.author).profile.name }} ()

{{ prayer.content }}

      </md-list-item>
    </md-list>
  </md-content>


text:
chrome.browserAction.onClicked.addListener(tab => {
  chrome.tabs.executeScript(tab.id, {
    file: 'entry.js'
  });
})
;


text:
<?php namespace xconn\adapters;

/**
 * Class MySQL
 * This is an EXAMPLE of mysqli adapter
 *
 * @package xconn\adapters
 */
final class MySQL extends \xconn\Adapter {

    /**
     * @param $config
     *
     * @return \mysqli
     */
    protected function openConnection($config) {
        return new \mysqli($config['host'], $config['user'], $config['pass'], $config['name'], $config['port'], $config['socket']);
    }

    /**
     * @return bool
     */
    protected function closeConnection() {

        if (!$this->connection) {
            return false;
        }

        $this->connection->close();
    }

    /**
     * @return mixed
     */
    public function getInsertedID()
    {
        return $this->connection->insert_id;
    }

    /**
     * @param $str
     *
     * @return string
     */
    public function escapeStr($str)
    {
        return $this->connection instanceof \MySQLi ? $this->connection->real_escape_string($str) : '';
    }

    /**
     * @param $str
     *
     * @return string
     */
    public function quote($str)
    {
        return "'" . $this->escapeStr($str) . "'";
    }

    /**
     * @param $query
     *
     * @return mysqli_result
     */
    public function query($query)
    {
        return $this->connection instanceof \MySQLi ? $this->connection->query($query) : false;
    }

    /**
     * @param $result
     *
     * @return bool|integer
     */
    public function rows($result)
    {
        return $result instanceof \mysqli_result ? @$result->num_rows : false;
    }

    /**
     * @param $result
     *
     * @return bool|array
     */
    public function fetch($result)
    {
        return $result instanceof \mysqli_result ? ($result->fetch_assoc()?:false) : false;
    }
}


text:
<?php
/**
 * 微信SDK
 * @author:midoks
 * @mail: midoks@163.com
 * @blog:midoks.cachecha.com
 */

define('WEIXIN_SDK', str_replace('\\', '/', dirname(__FILE__)).'/');
include(WEIXIN_SDK.'libs/base.class.php');
include(WEIXIN_SDK.'libs/template.class.php');
defined('WEIXIN_DEBUG') or define('WEIXIN_DEBUG', true);//默认关闭

class weixin{

	public $template;
	public $base;
	public $app_id;
	public $app_sercet;

	//构造函数
	public function __construct($AppId='', $AppSecret=''){

		$this->app_id = $AppId;
		$this->app_sercet = $AppSecret;

		$this->template = new Weixin_Template();
		$this->base = new Weixin_BaseCore();
	}

//no appkey and appsercet

	// response message (text)
	public function toMsgText($fromUserName, $toUserName, $Msg){
		return $this->template->toMsgText($fromUserName, $toUserName, $Msg);
	}

	// response message (image)
	public function toMsgImage($fromUserName, $toUserName, $MediaId){
		return $this->template->toMsgImage($fromUserName, $toUserName, $MediaId);
	}

	// response message (voice)
	public function toMsgVoice($fromUserName, $toUserName, $MediaId){
		return $this->template->toMsgVoice($fromUserName, $toUserName, $MediaId);
	}

	// response message (music)
	public function toMsgMusic($fromUserName, $toUserName, $Title, $Description, $MusicUrl, $HQMusicUrl, $ThumbMediaId=''){
		if(empty($ThumbMediaId)){
			return $this->template->toMsgMusic($fromUserName, $toUserName, $Title, $Description, $MusicUrl, $HQMusicUrl, $ThumbMediaId);
		}else{
			return $this->template->toMsgMusicId($fromUserName, $toUserName, $Title, $Description, $MusicUrl, $HQMusicUrl, $ThumbMediaId);
		}
	}

	// response message (video)
	public function toMsgVideo($fromUserName, $toUserName, $MediaId, $Title, $Description){
		return $this->template->toMsgVideo($toUserName, $fromUserName, $MediaId, $Title, $Description);
	}

	// response message (news)
	public function toMsgNews($fromUserName, $toUserName, $News){
			return $this->template->toMsgNews($fromUserName, $toUserName, $News);
	}
//END TO MSG

//have appkey and appsercet
	/**
	 *	get token
	 *  @ret json
	 */
	public function getToken(){
		$app_id = $this->app_id;
		$app_sercet = $this->app_sercet;
		return $this->base->getToken($app_id, $app_sercet);
	}

	public function pushMsgText($token, $open_id, $msg){
		return $this->base->pushMsgText($token, $open_id, $msg);
	}

	public function pushMsgImage($token, $open_id, $media_id){
		return $this->base->pushMsgImage($token, $open_id, $media_id);
	}

	public function pushMsgImageAdv($token, $open_id, $file){
		$ret = $this->upload($token, 'image', $file);
		if(!$ret){
			return '{errcode: "network imeout"}';
		}
		$data = json_decode($ret, true);
		if(isset($data['errcode'])){
			return $ret;
		}
		$ret = $this->pushMsgImage($token, $open_id, $data['media_id']);
		return $ret;
	}

	public function pushMsgVoice($token, $open_id, $media_id){
		return $this->base->pushMsgVoice($token, $open_id, $media_id);
	}

	public function pushMsgVoiceAdv($token, $open_id, $file){
		$ret = $this->upload($token, 'voice', $file);
		if(!$ret){
			return '{errcode: "network imeout"}';
		}
		$data = json_decode($ret, true);
		if(isset($data['errcode'])){
			return $ret;
		}
		$ret = $this->pushMsgVoiceAdv($token, $open_id, $data['media_id']);
		return $ret;
	}

	public function pushMsgVideo($token, $open_id, $media_id, $title, $desc){
		return $this->base->pushMsgVoice($token, $open_id, $media_id, $title, $desc);
	}

	public function pushMsgVideoAdv($token, $open_id, $file, $title, $desc){
		$ret = $this->upload($token, 'voice', $file);
		if(!$ret){
			return '{errcode: "network imeout"}';
		}
		$data = json_decode($ret, true);
		if(isset($data['errcode'])){
			return $ret;
		}
		$ret = $this->pushMsgVoice($token, $open_id, $data['media_id'], $title, $desc);
		return $ret;
	}

	public function pushMsgMusic($token, $open_id, $thumb_media_id, $title, $desc, $musicurl, $hqmusicurl){
		return $this->base->pushMsgMusic($token, $open_id, $thumb_media_id, $title, $desc, $musicurl, $hqmusicurl);
	}

	public function pushMsgMusicAdv($token, $open_id, $file, $title, $desc, $musicurl, $hqmusicurl){
		$ret = $this->upload($token, 'voice', $file);
		if(!$ret){
			return '{errcode: "network imeout"}';
		}
		$data = json_decode($ret, true);
		if(isset($data['errcode'])){
			return $ret;
		}
		$ret = $this->pushMsgVoice($token, $open_id, $data['media_id'], $title, $desc, $musicurl, $hqmusicurl);
		return $ret;
	}

	/**
	 * @exp: $info should be:
	 *		$info[]["title"] = "Happy Day";
     *      $info[]["description"]="Is Really A Happy Day";
     *      $info[]["url"] = "URL";
     *      $info[]["picurl"] = "PIC_URL";
	 */
	public function pushMsgNews($token, $open_id, $info){
		return $this->base->pushMsgNews($token, $open_id, $info);
	}
///END PUSH

/**
 *  多客服系统接口 start
 *	多客服系统是在的插件中使用!!!
 */

	/**
	 *	@func 获取客服聊天记录
	 *	@param $token		调用接口凭证
	 *	@param $open_id		普通用户的标识,对当前公众号唯一
	 *	@param $starttime	查询开始时间,UNIX时间戳
	 *	@param $endtime		查询结束时间,UNIX时间戳,每次查询不能跨日查询
	 *	@param $pagesize	每页大小,每页最多拉取1000条
	 *	@param $pageindex	查询第几页,从1开始
	 */
	public function getCustomServiceLog($token, $open_id, $starttime, $endtime, $pagesize=20, $pageindex=1){
		return $this->base->getCustomServiceLog($token, $open_id, $starttime, $endtime, $pagesize, $pageindex);
	}
/* 多客服系统接口 end */

//END PUSH ADV

	//menu setting
	public function menuGet($token){
		return $this->base->menuGet($token);
	}

	public function menuSet($token, $json){
		return $this->base->menuSet($token, $json);
	}

	public function menuDel($token){
		return $this->base->menuDel($token);
	}

//

//智能接口

	//智能接口分析
	public function getSemantic($token, $query, $category, $lat, $long, $city, $region, $appid, $uid){
		return $this->base->getSemantic($token, $query, $category, $lat, $long, $city, $region, $appid, $uid);
	}

//uplaod and download

	public function download($token, $media_id){
		return $this->base->download($token, $media_id);
	}

	public function upload($token, $type, $file){
		if(in_array($type, array('image', 'voice', 'video', 'thumb'))){
			return $this->base->upload($token, $type, $file);
		}else{
			return $this->notice('upload: invalid media type', __LINE__);
		}
	}

	public function uploadUrl($token, $type, $fn, $mime, $content){
		if(in_array($type, array('image', 'voice', 'video', 'thumb'))){
			return $this->base->uploadUrl($token, $type, $fn, $mime, $content);
		}else{
			return $this->notice('upload: invalid media type', __LINE__);
		}
	}

//user info
	public function getUserInfo($token, $open_id, $lang='zh_CN'){
		return $this->base->getUserInfo($token, $open_id, $lang);
	}

	public function getUserList($token, $next_openid){
		return $this->base->getUserList($token, $next_openid);
	}

	public function setUserGroup($token, $json){
		return $this->base->setUserGroup($token, $json);
	}

	public function getUserGroup($token){
		return $this->base->getUserGroup($token);
	}

	public function getUserGroupPosition($token, $json){
		return $this->base->getUserGroupPosition($token, $json);
	}

	public function modUserGroup($token, $json){
		return $this->base->modUserGroup($token, $json);
	}

	public function movUserGroup($token, $json){
		return $this->base->movUserGroup($token, $json);
	}

	public function updateRemark($token, $open_id, $remark){
		return $this->base->updateRemark($token, $open_id, $remark);
	}

//推送消息

/* 推广相关 start */

	//创建二维码ticket
	public function temp_ticket($token, $json){
		return $this->base->temp_ticket($token, $json);
	}

	//创建永久二维码ticket
	public function permanent_ticket($token, $json){
		return $this->base->permanent_ticket($token, $json);
	}

	//返回路径
	public function get_ticket($ticket){
		return $this->base->get_ticket($ticket);
	}

	//把长连接转换为短链接
	public function long2short($token, $url){
		return $this->base->long2short($token, $url);
	}

/* 推广相关 end */

	//上传图文消息素材
	public function uploadMsgImageText($token, $msg){
		return $this->base->uploadMsgImageText($token, $msg);
	}

	//通过分组进行群发
	public function sendAllByGroup($token, $group_id, $media_id, $msgtype){
		return $this->base->sendAllByGroup($token, $group_id, $media_id, $msgtype);
	}

	//根据OpenID列表群发
	public function sendAll($token, $user, $media_id, $msgtype){
		return $this->base->sendAll($token, $user, $media_id, $msgtype);
	}

	//删除群发信息
	public function deleteSend($token, $id){
		return $this->base->deleteSend($token, $id);
	}

	//发送模版消息
	public function sendTemplateInfo($token, $json){
		return $this->base->sendTemplateInfo($token, $json);
	}

	//获取微信地址
	public function getWeixinIp($token){
		return $this->base->getWeixinIp($token);
	}

	//处理后的JSON
	public function to_json($arr){
		return $this->base->to_json($arr);
	}

	//提示
	public function notice($msg, $line){
		if(WEIXIN_DEBUG){
			$this->logs($msg, $line);
		}else{
			trigger_error($msg);
		}
		return $msg;
	}

	public function logs($msg, $line){
		$fn = WEIXIN_SDK.'logs/'.date('Y-m-d').'.log';
		$handler = fopen($fn, 'a');
		fwrite($handler, 'error: in '.__FILE__.' at '.$line.' line '.$msg."\t".date('Y-m-d H:i:s')."\r\n");
		fclose($handler);
	}
}
?>


text:
if (typeof jQuery !== 'undefined') {
    (function($) {
        $(document).ajaxStart(function() {
            $('#spinner').fadeIn();
        }).ajaxStop(function() {
            $('#spinner').fadeOut();
        });

        // Javascript to enable link to tab
        var hash = document.location.hash;
        if (hash) {
            console.log(hash);
            $('.nav-tabs a[href="'+hash+'"]').tab('show');
        }

        // Change hash for page-reload
        $('.nav-tabs a').on('shown.bs.tab', function (e) {
            console.log("update nav %s",e.target.hash);
            window.location.hash = e.target.hash;
        });

    })(jQuery);
}


text:
package com.google.android.gms.maps.model;

import android.os.Parcel;
import com.google.android.gms.common.internal.safeparcel.b;

public class k
{
  static void a(VisibleRegion paramVisibleRegion, Parcel paramParcel, int paramInt)
  {
    int i = b.o(paramParcel);
    b.c(paramParcel, 1, paramVisibleRegion.getVersionCode());
    b.a(paramParcel, 2, paramVisibleRegion.nearLeft, paramInt, false);
    b.a(paramParcel, 3, paramVisibleRegion.nearRight, paramInt, false);
    b.a(paramParcel, 4, paramVisibleRegion.farLeft, paramInt, false);
    b.a(paramParcel, 5, paramVisibleRegion.farRight, paramInt, false);
    b.a(paramParcel, 6, paramVisibleRegion.latLngBounds, paramInt, false);
    b.D(paramParcel, i);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.maps.model.k
 * JD-Core Version:    0.6.2
 */


text:
void WinAPI::Dialog::Create(HINSTANCE hInstance, int dialogID, DLGPROC dialogProc) {
	CreateDialog(hInstance, MAKEINTRESOURCE(dialogID), nullptr, dialogProc);
}

void WinAPI::Dialog::Destroy() {
	DestroyWindow(dialog);
}

void WinAPI::Dialog::Initialize(HWND _dialog) {
	dialog = _dialog;
}

void WinAPI::Dialog::Show(int nCmdShow) {
	ShowWindow(dialog, nCmdShow);
}

void WinAPI::Dialog::SetSize() {
	SetWindowPos(dialog, nullptr, NULL, NULL, ConstWidth, ConstHeight, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}

void WinAPI::Dialog::SetCaption(const wchar_t * name) {
	SetWindowText(dialog, name);
}

int WinAPI::Dialog::GetWidth() const {
	return ConstWidth;
}

int WinAPI::Dialog::GetHeight() const {
	return ConstHeight;
}

WinAPI::Dialog::operator HWND() const {
	return dialog;
}


text:
const Requests = require('./requests/query')
const { Floor, Area } = require('./classes')

class Library {

  constructor() {

  }

  /**
   * Query status of a floor
   * @param {number} floor The floor, default value is 3
   * @returns {Floor} The floor object containing information about areas
   */
  async queryFloor(floor = 3) {
    return new Floor(await Requests.getFloorStatus(floor))
  }

  /**
   * Query status of an area
   * @param {AreaInfo} area The area metadata object
   * @returns {Area} The area object containing information about seats
   */
  async queryArea(area) {
    return new Area(await Requests.getAreaStatus(area.id))
  }

  /**
   * Book a seat.
   * @param {Seat} seat The seat information
   * @param {User} user The user object
   * @returns {Promise<Object>} Booking result
   */
  async bookSeat(seat, user) {
    let timeToken = await Requests.getTimeToken(seat.area)
    let result = await Requests.book(seat, user, timeToken)
    return {
      success: result.status === 1,
      serverMessage: result.msg
    }
  }

}

module.exports = Library


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

-->
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
			   xmlns:trans="http://schemas.android.com/apk/res-auto"
			   android:startDelay="@android:integer/config_shortAnimTime">

	<transition class="com.albedinsky.android.ui.transition.Reveal"
				android:interpolator="@android:interpolator/fast_out_slow_in"
				android:duration="500"
				trans:uiRevealMode="conceal"
				trans:uiCenterGravity="end|bottom"
				trans:uiCenterHorizontalOffset="-44dip"
				trans:uiCenterVerticalOffset="-44dip"
				trans:uiEndVisibility="invisible"
				trans:uiEndRadius="28dip">

		<targets>
			<target android:targetId="@id/reveal_view"/>
		</targets>
	</transition>
</transitionSet>


text:
/*jshint quotmark: false*/

'use strict';

var Promise    = require('../../lib/ext/promise');
var expect     = require('chai').expect;
var assertFile = require('../helpers/assert-file');
var conf       = require('../helpers/conf');
var ember      = require('../helpers/ember');
var fs         = require('fs-extra');
var path       = require('path');
var remove     = Promise.denodeify(fs.remove);
var root       = process.cwd();
var tmp        = require('tmp-sync');
var tmproot    = path.join(root, 'tmp');

var BlueprintNpmTask = require('../helpers/disable-npm-on-blueprint');

describe('Acceptance: ember destroy in-addon', function() {
  this.timeout(20000);

  var tmpdir;

  before(function() {
    BlueprintNpmTask.disableNPM();
    conf.setup();
  });

  after(function() {
    BlueprintNpmTask.restoreNPM();
    conf.restore();
  });

  beforeEach(function() {
    tmpdir = tmp.in(tmproot);
    process.chdir(tmpdir);
  });

  afterEach(function() {
    process.chdir(root);
    return remove(tmproot);
  });

  function initAddon() {
    return ember([
      'addon',
      'my-addon',
      '--skip-npm',
      '--skip-bower'
    ]);
  }

  function generateInAddon(args) {
    var generateArgs = ['generate'].concat(args);

    return initAddon().then(function() {
      return ember(generateArgs);
    });
  }

  function destroy(args) {
    var destroyArgs = ['destroy'].concat(args);
    return ember(destroyArgs);
  }

  function assertFileNotExists(file) {
    var filePath = path.join(process.cwd(), file);
    expect(!fs.existsSync(filePath), 'expected ' + file + ' not to exist');
  }

  function assertFilesExist(files) {
    files.forEach(assertFile);
  }

  function assertFilesNotExist(files) {
    files.forEach(assertFileNotExists);
  }

  function assertDestroyAfterGenerateInAddon(args, files) {
    return initAddon()
      .then(function() {
        return generateInAddon(args);
      })
      .then(function() {
        assertFilesExist(files);
      })
      .then(function() {
        return destroy(args);
      })
      .then(function(result) {
        expect(result, 'destroy command did not exit with errorCode').to.be.an('object');
        assertFilesNotExist(files);
      });
  }

  it('in-addon controller foo', function() {
    var commandArgs = ['controller', 'foo'];
    var files       = [
      'addon/controllers/foo.js',
      'app/controllers/foo.js',
      'tests/unit/controllers/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon controller foo/bar', function() {
    var commandArgs = ['controller', 'foo/bar'];
    var files       = [
      'addon/controllers/foo/bar.js',
      'app/controllers/foo/bar.js',
      'tests/unit/controllers/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon component x-foo', function() {
    var commandArgs = ['component', 'x-foo'];
    var files       = [
      'addon/components/x-foo.js',
      'addon/templates/components/x-foo.hbs',
      'app/components/x-foo.js',
      'tests/unit/components/x-foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon helper foo-bar', function() {
    var commandArgs = ['helper', 'foo-bar'];
    var files       = [
      'addon/helpers/foo-bar.js',
      'app/helpers/foo-bar.js',
      'tests/unit/helpers/foo-bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon helper foo/bar-baz', function() {
    var commandArgs = ['helper', 'foo/bar-baz'];
    var files       = [
      'addon/helpers/foo/bar-baz.js',
      'app/helpers/foo/bar-baz.js',
      'tests/unit/helpers/foo/bar-baz-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon model foo', function() {
    var commandArgs = ['model', 'foo'];
    var files       = [
      'addon/models/foo.js',
      'app/models/foo.js',
      'tests/unit/models/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon model foo/bar', function() {
    var commandArgs = ['model', 'foo/bar'];
    var files       = [
      'addon/models/foo/bar.js',
      'app/models/foo/bar.js',
      'tests/unit/models/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon template foo', function() {
    var commandArgs = ['template', 'foo'];
    var files       = [
      'addon/templates/foo.hbs',
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon template foo/bar', function() {
    var commandArgs = ['template', 'foo/bar'];
    var files       = [
      'addon/templates/foo/bar.hbs',
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon view foo', function() {
    var commandArgs = ['view', 'foo'];
    var files       = [
      'addon/views/foo.js',
      'app/views/foo.js',
      'tests/unit/views/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon view foo/bar', function() {
    var commandArgs = ['view', 'foo/bar'];
    var files       = [
      'addon/views/foo/bar.js',
      'app/views/foo/bar.js',
      'tests/unit/views/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon initializer foo', function() {
    var commandArgs = ['initializer', 'foo'];
    var files       = [
      'addon/initializers/foo.js',
      'app/initializers/foo.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon initializer foo/bar', function() {
    var commandArgs = ['initializer', 'foo/bar'];
    var files       = [
      'addon/initializers/foo/bar.js',
      'app/initializers/foo/bar.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon mixin foo', function() {
    var commandArgs = ['mixin', 'foo'];
    var files       = [
      'addon/mixins/foo.js',
      'tests/unit/mixins/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon mixin foo/bar', function() {
    var commandArgs = ['mixin', 'foo/bar'];
    var files       = [
      'addon/mixins/foo/bar.js',
      'tests/unit/mixins/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon adapter foo', function() {
    var commandArgs = ['adapter', 'foo'];
    var files       = [
      'addon/adapters/foo.js',
      'app/adapters/foo.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon adapter foo/bar', function() {
    var commandArgs = ['adapter', 'foo/bar'];
    var files       = [
      'addon/adapters/foo/bar.js',
      'app/adapters/foo/bar.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon serializer foo', function() {
    var commandArgs = ['serializer', 'foo'];
    var files       = [
      'addon/serializers/foo.js',
      'app/serializers/foo.js',
      'tests/unit/serializers/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon serializer foo/bar', function() {
    var commandArgs = ['serializer', 'foo/bar'];
    var files       = [
      'addon/serializers/foo/bar.js',
      'app/serializers/foo/bar.js',
      'tests/unit/serializers/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon transform foo', function() {
    var commandArgs = ['transform', 'foo'];
    var files       = [
      'addon/transforms/foo.js',
      'app/transforms/foo.js',
      'tests/unit/transforms/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon transform foo/bar', function() {
    var commandArgs = ['transform', 'foo/bar'];
    var files       = [
      'addon/transforms/foo/bar.js',
      'app/transforms/foo/bar.js',
      'tests/unit/transforms/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon util foo-bar', function() {
    var commandArgs = ['util', 'foo-bar'];
    var files       = [
      'addon/utils/foo-bar.js',
      'app/utils/foo-bar.js',
      'tests/unit/utils/foo-bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon util foo-bar/baz', function() {
    var commandArgs = ['util', 'foo/bar-baz'];
    var files       = [
      'addon/utils/foo/bar-baz.js',
      'app/utils/foo/bar-baz.js',
      'tests/unit/utils/foo/bar-baz-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon service foo', function() {
    var commandArgs = ['service', 'foo'];
    var files       = [
      'addon/services/foo.js',
      'app/services/foo.js',
      'tests/unit/services/foo-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

  it('in-addon service foo/bar', function() {
    var commandArgs = ['service', 'foo/bar'];
    var files       = [
      'addon/services/foo/bar.js',
      'app/services/foo/bar.js',
      'tests/unit/services/foo/bar-test.js'
    ];

    return assertDestroyAfterGenerateInAddon(commandArgs, files);
  });

});


text:
/*
Package env handles environment variables in a structured manner.

See the README at https://github.com/peter-edge/go-env/blob/master/README.md for more details.
*/
package env

import (
	"io"
	"reflect"
)

// Decoder decodes an env file.
type Decoder interface {
	Decode() (map[string]string, error)
}

// NewEnvFileDecoder returns a new Decoder that decodes an env file
// of the form key=value.
func NewEnvFileDecoder(reader io.Reader) Decoder {
	return newEnvFileDecoder(reader)
}

// NewJSONDecoder returns a new Decoder that decodes a JSON object.
func NewJSONDecoder(reader io.Reader) Decoder {
	return newJSONDecoder(reader)
}

// PopulateOptions are the options to pass to Populate.
type PopulateOptions struct {
	// RestrictTo is the set of env keys that are allowed
	// to be read by structs. Use at the application level to make sure
	// no env keys are being read that are not made aware of
	RestrictTo []string
	// Decoders is a list of Decoders to use, in order,
	// to read additional env variables.
	Decoders []Decoder
}

// Populate populates an object with environment variables.
// See the test for an example.
func Populate(object interface{}, populateOptions PopulateOptions) error {
	return populate(reflect.ValueOf(object), populateOptions, false)
}


text:
package org.apache.pulsar.functions.runtime;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.converters.StringConverter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.Empty;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.functions.instance.InstanceConfig;
import org.apache.pulsar.functions.proto.Function.FunctionDetails;
import org.apache.pulsar.functions.proto.InstanceCommunication;
import org.apache.pulsar.functions.proto.InstanceControlGrpc;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * A function container implemented using java thread.
 */
@Slf4j
public class JavaInstanceMain {
    @Parameter(names = "--function_classname", description = "Function Class Name\n", required = true)
    protected String className;
    @Parameter(
            names = "--jar",
            description = "Path to Jar\n",
            listConverter = StringConverter.class)
    protected String jarFile;
    @Parameter(names = "--name", description = "Function Name\n", required = true)
    protected String functionName;
    @Parameter(names = "--tenant", description = "Tenant Name\n", required = true)
    protected String tenant;
    @Parameter(names = "--namespace", description = "Namespace Name\n", required = true)
    protected String namespace;

    @Parameter(names = "--output_topic", description = "Output Topic Name\n")
    protected String outputTopicName;

    @Parameter(names = "--custom_serde_input_topics", description = "Input Topics that need custom deserialization\n", required = false)
    protected String customSerdeInputTopics;
    @Parameter(names = "--custom_serde_classnames", description = "Input SerDe\n", required = false)
    protected String customSerdeClassnames;
    @Parameter(names = "--input_topics", description = "Input Topics\n", required = false)
    protected String defaultSerdeInputTopics;

    @Parameter(names = "--output_serde_classname", description = "Output SerDe\n")
    protected String outputSerdeClassName;

    @Parameter(names = "--log_topic", description = "Log Topic")
    protected String logTopic;

    @Parameter(names = "--processing_guarantees", description = "Processing Guarantees\n", required = true)
    protected FunctionDetails.ProcessingGuarantees processingGuarantees;

    @Parameter(names = "--instance_id", description = "Instance Id\n", required = true)
    protected String instanceId;

    @Parameter(names = "--function_id", description = "Function Id\n", required = true)
    protected String functionId;

    @Parameter(names = "--function_version", description = "Function Version\n", required = true)
    protected String functionVersion;

    @Parameter(names = "--pulsar_serviceurl", description = "Pulsar Service Url\n", required = true)
    protected String pulsarServiceUrl;

    @Parameter(names = "--state_storage_serviceurl", description = "State Storage Service Url\n", required= false)
    protected String stateStorageServiceUrl;

    @Parameter(names = "--port", description = "Port to listen on\n", required = true)
    protected int port;

    @Parameter(names = "--max_buffered_tuples", description = "Maximum number of tuples to buffer\n", required = true)
    protected int maxBufferedTuples;

    @Parameter(names = "--user_config", description = "UserConfig\n")
    protected String userConfig;

    @Parameter(names = "--auto_ack", description = "Enable Auto Acking?\n")
    protected String autoAck = "true";

    @Parameter(names = "--subscription_type", description = "What subscription type to use")
    protected FunctionDetails.SubscriptionType subscriptionType;

    private Server server;

    public JavaInstanceMain() { }

    public void start() throws Exception {
        InstanceConfig instanceConfig = new InstanceConfig();
        instanceConfig.setFunctionId(functionId);
        instanceConfig.setFunctionVersion(functionVersion);
        instanceConfig.setInstanceId(instanceId);
        instanceConfig.setMaxBufferedTuples(maxBufferedTuples);
        FunctionDetails.Builder functionDetailsBuilder = FunctionDetails.newBuilder();
        functionDetailsBuilder.setTenant(tenant);
        functionDetailsBuilder.setNamespace(namespace);
        functionDetailsBuilder.setName(functionName);
        functionDetailsBuilder.setClassName(className);
        if (defaultSerdeInputTopics != null) {
            String[] inputTopics = defaultSerdeInputTopics.split(",");
            for (String inputTopic : inputTopics) {
                functionDetailsBuilder.addInputs(inputTopic);
            }
        }
        if (customSerdeInputTopics != null && customSerdeClassnames != null) {
            String[] inputTopics = customSerdeInputTopics.split(",");
            String[] inputSerdeClassNames = customSerdeClassnames.split(",");
            if (inputTopics.length != inputSerdeClassNames.length) {
                throw new RuntimeException("Error specifying inputs");
            }
            for (int i = 0; i < inputTopics.length; ++i) {
                functionDetailsBuilder.putCustomSerdeInputs(inputTopics[i], inputSerdeClassNames[i]);
            }
        }
        if (outputSerdeClassName != null) {
            functionDetailsBuilder.setOutputSerdeClassName(outputSerdeClassName);
        }
        if (outputTopicName != null) {
            functionDetailsBuilder.setOutput(outputTopicName);
        }
        if (logTopic != null) {
            functionDetailsBuilder.setLogTopic(logTopic);
        }
        functionDetailsBuilder.setProcessingGuarantees(processingGuarantees);
        if (autoAck.equals("true")) {
            functionDetailsBuilder.setAutoAck(true);
        } else {
            functionDetailsBuilder.setAutoAck(false);
        }
        functionDetailsBuilder.setSubscriptionType(subscriptionType);
        if (userConfig != null && !userConfig.isEmpty()) {
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> userConfigMap = new Gson().fromJson(userConfig, type);
            functionDetailsBuilder.putAllUserConfig(userConfigMap);
        }
        FunctionDetails functionDetails = functionDetailsBuilder.build();
        instanceConfig.setFunctionDetails(functionDetails);

        ThreadRuntimeFactory containerFactory = new ThreadRuntimeFactory(
                "LocalRunnerThreadGroup",
                pulsarServiceUrl,
                stateStorageServiceUrl);

        RuntimeSpawner runtimeSpawner = new RuntimeSpawner(
                instanceConfig,
                jarFile,
                containerFactory,
                null);

        server = ServerBuilder.forPort(port)
                .addService(new InstanceControlImpl(runtimeSpawner))
                .build()
                .start();
        log.info("JaveInstance Server started, listening on " + port);
        java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                try {
                    server.shutdown();
                    runtimeSpawner.close();
                } catch (Exception ex) {
                    System.err.println(ex);
                }
            }
        });
        log.info("Starting runtimeSpawner");
        runtimeSpawner.start();
        runtimeSpawner.join();
        log.info("RuntimeSpawner quit, shutting down JavaInstance");
        server.shutdown();
    }

    public static void main(String[] args) throws Exception {
        JavaInstanceMain javaInstanceMain = new JavaInstanceMain();
        JCommander jcommander = new JCommander(javaInstanceMain);
        jcommander.setProgramName("JavaInstanceMain");

        // parse args by JCommander
        jcommander.parse(args);
        javaInstanceMain.start();
    }

    static class InstanceControlImpl extends InstanceControlGrpc.InstanceControlImplBase {
        private RuntimeSpawner runtimeSpawner;

        public InstanceControlImpl(RuntimeSpawner runtimeSpawner) {
            this.runtimeSpawner = runtimeSpawner;
        }

        @Override
        public void getFunctionStatus(Empty request, StreamObserver<InstanceCommunication.FunctionStatus> responseObserver) {
            try {
                InstanceCommunication.FunctionStatus response = runtimeSpawner.getFunctionStatus().get();
                responseObserver.onNext(response);
                responseObserver.onCompleted();
            } catch (Exception e) {
                log.error("Exception in JavaInstance doing getFunctionStatus", e);
                throw new RuntimeException(e);
            }
        }

        @Override
        public void getAndResetMetrics(com.google.protobuf.Empty request,
                                       io.grpc.stub.StreamObserver<org.apache.pulsar.functions.proto.InstanceCommunication.MetricsData> responseObserver) {
            Runtime runtime = runtimeSpawner.getRuntime();
            if (runtime != null) {
                try {
                    InstanceCommunication.MetricsData metrics = runtime.getAndResetMetrics().get();
                    responseObserver.onNext(metrics);
                    responseObserver.onCompleted();
                } catch (InterruptedException | ExecutionException e) {
                    log.error("Exception in JavaInstance doing getAndResetMetrics", e);
                    throw new RuntimeException(e);
                }
            }
        }

    }
}


text:
class Patientsaddwardid < ActiveRecord::Migration
  def change
    add_column :patients, :ward_id, :integer

  end
end


text:
USE TSQL_Koans

EXEC tSQLt.NewTestClass 'AboutSelects'
GO

/*
FROM
WHERE
EXISTS
IN
ORDER BY
DISTINCT
TOP
WITH (common table expression?)
HAVING
OVER
CASE
NOT
*/

/*
<SELECT statement> ::=
    [WITH <common_table_expression> [,...n]]
    <query_expression>
    [ ORDER BY { order_by_expression | column_position [ ASC | DESC ] }
  [ ,...n ] ]
    [ <FOR Clause>]
    [ OPTION ( <query_hint> [ ,...n ] ) ]
<query_expression> ::=
    { <query_specification> | ( <query_expression> ) }
    [  { UNION [ ALL ] | EXCEPT | INTERSECT }
        <query_specification> | ( <query_expression> ) [...n ] ]
<query_specification> ::=
SELECT [ ALL | DISTINCT ]
    [TOP ( expression ) [PERCENT] [ WITH TIES ] ]
    < select_list >
    [ INTO new_table ]
    [ FROM { <table_source> } [ ,...n ] ]
    [ WHERE <search_condition> ]
    [ <GROUP BY> ]
    [ HAVING < search_condition > ]
*/


text:
@class SOMotionDetector,CMAttitude;

@protocol SRMotionManagerDelegate <NSObject>

-(void)attitudeHasUpdatedRoll:(CGFloat)roll withYaw:(CGFloat)yaw andPitch:(CGFloat)pitch;

@end

@interface SRMotionManager : NSObject

@property (strong, nonatomic) id<SRMotionManagerDelegate> delegate;
@property (strong, readonly, nonatomic) SOMotionDetector * sharedSODector;
@property (strong, nonatomic) NSString * currentMotionType;

+(instancetype) sharedFondler;
-(void)updateMotionType:(NSString *)motionType;

@end