text:
package com.amazonaws.services.iotsitewise.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreatePortalResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The ID of the created portal.
     *

     */
    private String portalId;
    /**
     *

     * The ARN of the portal,
     * which has the following format.
     *

     *

     * arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     *

     */
    private String portalArn;
    /**
     *

     * The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity Center
     * for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise console to get a
     * URL that you can use to access the portal.
     *

     */
    private String portalStartUrl;
    /**
     *

     * The status of the portal, which contains a state (CREATING after successfully calling this
     * operation) and any error message.
     *

     */
    private PortalStatus portalStatus;
    /**
     *

     * The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     *

     */
    private String ssoApplicationId;

    /**
     *

     * The ID of the created portal.
     *

     *
     * @param portalId
     *        The ID of the created portal.
     */

    public void setPortalId(String portalId) {
        this.portalId = portalId;
    }

    /**
     *

     * The ID of the created portal.
     *

     *
     * @return The ID of the created portal.
     */

    public String getPortalId() {
        return this.portalId;
    }

    /**
     *

     * The ID of the created portal.
     *

     *
     * @param portalId
     *        The ID of the created portal.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreatePortalResult withPortalId(String portalId) {
        setPortalId(portalId);
        return this;
    }

    /**
     *

     * The ARN of the portal,
     * which has the following format.
     *

     *

     * arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     *

     *
     * @param portalArn
     *        The ARN of the
     *        portal, which has the following format.

     *

     *        arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     */

    public void setPortalArn(String portalArn) {
        this.portalArn = portalArn;
    }

    /**
     *

     * The ARN of the portal,
     * which has the following format.
     *

     *

     * arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     *

     *
     * @return The ARN of the
     *         portal, which has the following format.

     *

     *         arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     */

    public String getPortalArn() {
        return this.portalArn;
    }

    /**
     *

     * The ARN of the portal,
     * which has the following format.
     *

     *

     * arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     *

     *
     * @param portalArn
     *        The ARN of the
     *        portal, which has the following format.

     *

     *        arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreatePortalResult withPortalArn(String portalArn) {
        setPortalArn(portalArn);
        return this;
    }

    /**
     *

     * The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity Center
     * for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise console to get a
     * URL that you can use to access the portal.
     *

     *
     * @param portalStartUrl
     *        The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity
     *        Center for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise
     *        console to get a URL that you can use to access the portal.
     */

    public void setPortalStartUrl(String portalStartUrl) {
        this.portalStartUrl = portalStartUrl;
    }

    /**
     *

     * The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity Center
     * for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise console to get a
     * URL that you can use to access the portal.
     *

     *
     * @return The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity
     *         Center for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise
     *         console to get a URL that you can use to access the portal.
     */

    public String getPortalStartUrl() {
        return this.portalStartUrl;
    }

    /**
     *

     * The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity Center
     * for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise console to get a
     * URL that you can use to access the portal.
     *

     *
     * @param portalStartUrl
     *        The URL for the IoT SiteWise Monitor portal. You can use this URL to access portals that use IAM Identity
     *        Center for authentication. For portals that use IAM for authentication, you must use the IoT SiteWise
     *        console to get a URL that you can use to access the portal.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreatePortalResult withPortalStartUrl(String portalStartUrl) {
        setPortalStartUrl(portalStartUrl);
        return this;
    }

    /**
     *

     * The status of the portal, which contains a state (CREATING after successfully calling this
     * operation) and any error message.
     *

     *
     * @param portalStatus
     *        The status of the portal, which contains a state (CREATING after successfully calling this
     *        operation) and any error message.
     */

    public void setPortalStatus(PortalStatus portalStatus) {
        this.portalStatus = portalStatus;
    }

    /**
     *

     * The status of the portal, which contains a state (CREATING after successfully calling this
     * operation) and any error message.
     *

     *
     * @return The status of the portal, which contains a state (CREATING after successfully calling this
     *         operation) and any error message.
     */

    public PortalStatus getPortalStatus() {
        return this.portalStatus;
    }

    /**
     *

     * The status of the portal, which contains a state (CREATING after successfully calling this
     * operation) and any error message.
     *

     *
     * @param portalStatus
     *        The status of the portal, which contains a state (CREATING after successfully calling this
     *        operation) and any error message.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreatePortalResult withPortalStatus(PortalStatus portalStatus) {
        setPortalStatus(portalStatus);
        return this;
    }

    /**
     *

     * The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     *

     *
     * @param ssoApplicationId
     *        The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     */

    public void setSsoApplicationId(String ssoApplicationId) {
        this.ssoApplicationId = ssoApplicationId;
    }

    /**
     *

     * The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     *

     *
     * @return The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     */

    public String getSsoApplicationId() {
        return this.ssoApplicationId;
    }

    /**
     *

     * The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     *

     *
     * @param ssoApplicationId
     *        The associated IAM Identity Center application ID, if the portal uses IAM Identity Center.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreatePortalResult withSsoApplicationId(String ssoApplicationId) {
        setSsoApplicationId(ssoApplicationId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPortalId() != null)
            sb.append("PortalId: ").append(getPortalId()).append(",");
        if (getPortalArn() != null)
            sb.append("PortalArn: ").append(getPortalArn()).append(",");
        if (getPortalStartUrl() != null)
            sb.append("PortalStartUrl: ").append(getPortalStartUrl()).append(",");
        if (getPortalStatus() != null)
            sb.append("PortalStatus: ").append(getPortalStatus()).append(",");
        if (getSsoApplicationId() != null)
            sb.append("SsoApplicationId: ").append(getSsoApplicationId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreatePortalResult == false)
            return false;
        CreatePortalResult other = (CreatePortalResult) obj;
        if (other.getPortalId() == null ^ this.getPortalId() == null)
            return false;
        if (other.getPortalId() != null && other.getPortalId().equals(this.getPortalId()) == false)
            return false;
        if (other.getPortalArn() == null ^ this.getPortalArn() == null)
            return false;
        if (other.getPortalArn() != null && other.getPortalArn().equals(this.getPortalArn()) == false)
            return false;
        if (other.getPortalStartUrl() == null ^ this.getPortalStartUrl() == null)
            return false;
        if (other.getPortalStartUrl() != null && other.getPortalStartUrl().equals(this.getPortalStartUrl()) == false)
            return false;
        if (other.getPortalStatus() == null ^ this.getPortalStatus() == null)
            return false;
        if (other.getPortalStatus() != null && other.getPortalStatus().equals(this.getPortalStatus()) == false)
            return false;
        if (other.getSsoApplicationId() == null ^ this.getSsoApplicationId() == null)
            return false;
        if (other.getSsoApplicationId() != null && other.getSsoApplicationId().equals(this.getSsoApplicationId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getPortalId() == null) ? 0 : getPortalId().hashCode());
        hashCode = prime * hashCode + ((getPortalArn() == null) ? 0 : getPortalArn().hashCode());
        hashCode = prime * hashCode + ((getPortalStartUrl() == null) ? 0 : getPortalStartUrl().hashCode());
        hashCode = prime * hashCode + ((getPortalStatus() == null) ? 0 : getPortalStatus().hashCode());
        hashCode = prime * hashCode + ((getSsoApplicationId() == null) ? 0 : getSsoApplicationId().hashCode());
        return hashCode;
    }

    @Override
    public CreatePortalResult clone() {
        try {
            return (CreatePortalResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_FSWATCHER

#include "wx/fswatcher.h"
#include "wx/private/fswatcher.h"

// ============================================================================
// helpers
// ============================================================================

wxDEFINE_EVENT(wxEVT_FSWATCHER, wxFileSystemWatcherEvent);

static wxString GetFSWEventChangeTypeName(int type)
{
    switch (type)
    {
    case wxFSW_EVENT_CREATE:
        return "CREATE";
    case wxFSW_EVENT_DELETE:
        return "DELETE";
    case wxFSW_EVENT_RENAME:
        return "RENAME";
    case wxFSW_EVENT_MODIFY:
        return "MODIFY";
    case wxFSW_EVENT_ACCESS:
        return "ACCESS";
    }

    // should never be reached!
    wxFAIL_MSG("Unknown change type");
    return "INVALID_TYPE";
}

// ============================================================================
// wxFileSystemWatcherEvent implementation
// ============================================================================

wxString wxFileSystemWatcherEvent::ToString() const
{
    return wxString::Format("FSW_EVT type=%d (%s) path='%s'", m_changeType,
            GetFSWEventChangeTypeName(m_changeType), GetPath().GetFullPath());
}

// ============================================================================
// wxFileSystemWatcherEvent implementation
// ============================================================================

wxFileSystemWatcherBase::wxFileSystemWatcherBase() :
    m_service(0), m_owner(this)
{
}

wxFileSystemWatcherBase::~wxFileSystemWatcherBase()
{
    RemoveAll();
    if (m_service)
    {
        delete m_service;
    }
}

bool wxFileSystemWatcherBase::Add(const wxFileName& path, int events)
{
    // args validation & consistency checks
    if (!path.FileExists() && !path.DirExists())
        return false;

    wxString canonical = GetCanonicalPath(path);
    if (canonical.IsEmpty())
        return false;

    wxCHECK_MSG(m_watches.find(canonical) == m_watches.end(), false,
                wxString::Format("Path '%s' is already watched", canonical));

    // adding a path in a platform specific way
    wxFSWatchInfo watch(canonical, events);
    if ( !m_service->Add(watch) )
        return false;

    // on success, add path to our 'watch-list'
    wxFSWatchInfoMap::value_type val(canonical, watch);
    return m_watches.insert(val).second;
}

bool wxFileSystemWatcherBase::Remove(const wxFileName& path)
{
    // args validation & consistency checks
    wxString canonical = GetCanonicalPath(path);
    if (canonical.IsEmpty())
        return false;

    wxFSWatchInfoMap::iterator it = m_watches.find(canonical);
    wxCHECK_MSG(it != m_watches.end(), false,
                wxString::Format("Path '%s' is not watched", canonical));

    // remove from watch-list
    wxFSWatchInfo watch = it->second;
    m_watches.erase(it);

    // remove in a platform specific way
    return m_service->Remove(watch);
}

bool wxFileSystemWatcherBase::AddTree(const wxFileName& path, int events,
                                      const wxString& filter)
{
    if (!path.DirExists())
        return false;

    // OPT could be optimised if we stored information about relationships
    // between paths
    class AddTraverser : public wxDirTraverser
    {
    public:
        AddTraverser(wxFileSystemWatcherBase* watcher, int events) :
            m_watcher(watcher), m_events(events)
        {
        }

        // CHECK we choose which files to delegate to Add(), maybe we should pass
        // all of them to Add() and let it choose? this is useful when adding a
        // file to a dir that is already watched, then not only should we know
        // about that, but Add() should also behave well then
        virtual wxDirTraverseResult OnFile(const wxString& WXUNUSED(filename))
        {
            return wxDIR_CONTINUE;
        }

        virtual wxDirTraverseResult OnDir(const wxString& dirname)
        {
            wxLogTrace(wxTRACE_FSWATCHER, "--- AddTree adding '%s' ---",
                                                                    dirname);
            // we add as much as possible and ignore errors
            m_watcher->Add(wxFileName(dirname), m_events);
            return wxDIR_CONTINUE;
        }

    private:
        wxFileSystemWatcherBase* m_watcher;
        int m_events;
        wxString m_filter;
    };

    wxDir dir(path.GetFullPath());
    AddTraverser traverser(this, events);
    dir.Traverse(traverser, filter);

    return true;
}

bool wxFileSystemWatcherBase::RemoveTree(const wxFileName& path)
{
    if (!path.DirExists())
        return false;

    // OPT could be optimised if we stored information about relationships
    // between paths
    class RemoveTraverser : public wxDirTraverser
    {
    public:
        RemoveTraverser(wxFileSystemWatcherBase* watcher) :
            m_watcher(watcher)
        {
        }

        virtual wxDirTraverseResult OnFile(const wxString& filename)
        {
            m_watcher->Remove(wxFileName(filename));
            return wxDIR_CONTINUE;
        }

        virtual wxDirTraverseResult OnDir(const wxString& dirname)
        {
            m_watcher->RemoveTree(wxFileName(dirname));
            return wxDIR_CONTINUE;
        }

    private:
        wxFileSystemWatcherBase* m_watcher;
    };

    wxDir dir(path.GetFullPath());
    RemoveTraverser traverser(this);
    dir.Traverse(traverser);

    return true;
}

bool wxFileSystemWatcherBase::RemoveAll()
{
    m_service->RemoveAll();
    m_watches.clear();
    return true;
}

int wxFileSystemWatcherBase::GetWatchedPathsCount() const
{
    return m_watches.size();
}

int wxFileSystemWatcherBase::GetWatchedPaths(wxArrayString* paths) const
{
    wxCHECK_MSG( paths != NULL, -1, "Null array passed to retrieve paths");

    wxFSWatchInfoMap::const_iterator it = m_watches.begin();
    for ( ; it != m_watches.end(); ++it)
    {
        paths->push_back(it->first);
    }

    return m_watches.size();
}

#endif // wxUSE_FSWATCHER

redpajama_set_name: RedPajamaGithub


text:
package org.apache.commons.jcs.utils.timing;

/**
 * This is a simple timer utility.
 */
public class ElapsedTimer
{
    /** display suffix describing the unit of measure. */
    private static final String SUFFIX = "ms.";

    /**
     * Sets the start time when created.
     */
    private long timeStamp = System.currentTimeMillis();

    /**
     * Gets the time elapsed between the start time and now. The start time is reset to now.
     * Subsequent calls will get the time between then and now.
     *

     * @return the elapsed time
     */
    public long getElapsedTime()
    {
        long now = System.currentTimeMillis();
        long elapsed = now - timeStamp;
        timeStamp = now;
        return elapsed;
    }

    /**
     * Returns the elapsed time with the display suffix.
     *

     * @return formatted elapsed Time
     */
    public String getElapsedTimeString()
    {
        return String.valueOf( getElapsedTime() ) + SUFFIX;
    }
}


text:
package pugbot.core.commands;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import pugbot.Utils;
import pugbot.core.Database;
import pugbot.core.entities.MatchRecord;
import pugbot.core.exceptions.BadArgumentsException;
import pugbot.core.exceptions.InvalidUseException;

public class CmdMatchHistory extends Command {

	private static int recordLimit = 5;
	private static String recordFormat = "%-8s%-15s%-30s%-30s%-10s";
	private static String recordSecondRowOffset = new String(new char[53]).replace('\0', ' ');
	private static String rowSeparator = new String(new char[95]).replace('\0', '_');
	private static String columnTitles = String.format(recordFormat, "Index", "Date", "Queue", "Captains", "Winning Team");

	private List<MatchRecord> recordCache;

	@Override
	public Message execCommand(Member caller, String[] args) {
		if(args.length == 0) {
			recordCache = Database.queryGetServerMatchRecords(server.getId(), recordLimit);
			return generateMatchHistoryMessage();
		}

		if(args.length < 2) {
			throw new BadArgumentsException();
		}

		if(recordCache == null) {
			recordCache = Database.queryGetServerMatchRecords(server.getId(), recordLimit);
		}

		int recordIndex;

		try {
			recordIndex = Integer.valueOf(args[0]);
		} catch (NumberFormatException ex) {
			throw new BadArgumentsException("The row index must be a valid integer");
		}

		if(recordIndex < 1 || recordIndex > recordLimit) {
			throw new InvalidUseException(
					String.format("The row index must be greater than 0 and less than %d", recordLimit));
		}

		MatchRecord record = recordCache.get(recordIndex - 1);
		String resultString = String.join(" ", Arrays.copyOfRange(args, 1, args.length)).toLowerCase();
		Integer resultInteger = null;

		if(resultString.equals("tie")) {
			resultInteger = 0;
		} else if(resultString.equals("cancelled")) {
			resultInteger = null;
		} else {
			if(!record.hasCaptainWithName(resultString)) {
				throw new InvalidUseException(String.format("The name '%s' did not match either captain", resultString));
			}

			for(int i = 0; i < 2; i++) {
				if(record.captainNames[i].toLowerCase().equals(resultString)) {
					resultInteger = i + 1;
					break;
				}
			}
		}

		if(resultInteger == record.getResult()) {
			throw new InvalidUseException("The new result must be different");
		}

		record.updateResult(resultInteger);
		Database.updateGameResult(record.serverId, record.queueId, record.timestamp, record.getResult());

		return Utils.createMessage("`Match record updated`");
	}

	private Message generateMatchHistoryMessage() {
		StringBuilder sb = new StringBuilder();

		sb.append("```\n");
		sb.append(columnTitles);
		sb.append('\n');
		sb.append(rowSeparator);
		sb.append('\n');
		sb.append('\n');

		for(int i = 0; i < recordCache.size(); i++) {
			MatchRecord record = recordCache.get(i);
			String date = String.format("%tF", new Date(record.timestamp));
			String[] captains = record.captainNames;
			String translatedResult = new String();

			if(record.getResult() == null) {
				translatedResult = "Cancelled";
			} else if(record.getResult() == 0) {
				translatedResult = "Tie";
			} else {
				translatedResult = captains[record.getResult() - 1];
			}

			String row = String.format(recordFormat,
					i + 1,
					date,
					record.queueName,
					captains[0],
					translatedResult);

			sb.append(row);
			sb.append('\n');
			sb.append(recordSecondRowOffset);
			sb.append(captains[1]);
			sb.append('\n');
			sb.append(rowSeparator);
			sb.append('\n');
			sb.append('\n');
		}

		sb.append("```");

		return Utils.createMessage(sb.toString());
	}

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

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

	@Override
	public String getName() {
		return "MatchHistory";
	}

	@Override
	public String getDescription() {
		return "Lists past games with the ability to amend results";
	}

	@Override
	public String getHelp() {
		return getBaseCommand() + " - Lists past matches and their results\n"
				+ getBaseCommand() + " <record index> <new result (captain name/tie/cancelled)> - Updates a match record";
	}

}


text:
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.jstestdriver.server.handlers;

import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.servlet.RequestParameters;
import com.google.jstestdriver.CapturedBrowsers;
import com.google.jstestdriver.SlaveBrowser;
import com.google.jstestdriver.requesthandlers.RequestHandler;

import org.mortbay.jetty.MimeTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * Used by the client to know if the browser is alive.
 *
 * @author jeremiele@google.com (Jeremie Lenfant-Engelmann)
 */
class HeartbeatGetHandler implements RequestHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(
      HeartbeatGetHandler.class);

  private final CapturedBrowsers capturedBrowsers;
  private final Map<String, String[]> parameters;
  private final Gson gson;

  private final HttpServletResponse response;

  @Inject
  public HeartbeatGetHandler(
      CapturedBrowsers capturedBrowsers,
      @RequestParameters Map<String, String[]> parameters,
      Gson gson,
      HttpServletResponse response) {
    this.capturedBrowsers = capturedBrowsers;
    this.parameters = parameters;
    this.gson = gson;
    this.response = response;
  }

  public void handleIt() throws IOException {
    response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8);
    String[] ids = parameters.get("id");
    final PrintWriter writer = response.getWriter();
    if (ids != null && ids[0] != null) {
      String id = ids[0];
      SlaveBrowser browser = capturedBrowsers.getBrowser(id);
      if (browser != null) {
        LOGGER.debug("requesting " + browser);
        if (!browser.isAlive()) {
          capturedBrowsers.removeSlave(id);
          writer.write("DEAD:" + gson.toJson(browser.getBrowserInfo()));
        } else {
          writer.write("OK");
        }
      } else {
        LOGGER.debug("heartbeat " + id + "with no browser.");
        writer.write("DEAD: can't find browser.");
      }
    } else {
      LOGGER.debug("no heartbeat, no browser.");
      writer.write("DEAD");
    }
    writer.flush();
  }
}


text:
package target_verifier

import (
	"github.com/cloudfoundry-incubator/lattice/ltc/receptor_client"
	"github.com/cloudfoundry-incubator/receptor"
)

//go:generate counterfeiter -o fake_target_verifier/fake_target_verifier.go . TargetVerifier
type TargetVerifier interface {
	VerifyTarget(name string) (up bool, auth bool, err error)
}

func New(receptorClientCreator receptor_client.Creator) TargetVerifier {
	return &targetVerifier{receptorClientCreator}
}

type targetVerifier struct {
	receptorClientCreator receptor_client.Creator
}

func (t *targetVerifier) VerifyTarget(target string) (up, auth bool, err error) {
	receptorClient := t.receptorClientCreator.CreateReceptorClient(target)
	_, err = receptorClient.DesiredLRPs()

	if err != nil {
		receptorErr, ok := err.(receptor.Error)

		if !ok {
			return false, false, err
		}

		if receptorErr.Type == receptor.Unauthorized {
			return true, false, nil
		} else {
			// TODO: poor interface for return values: "true, false, err"
			return true, false, err
		}
	}

	return true, true, nil
}


text:
package io.quarkus.bootstrap.workspace;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import io.quarkus.paths.EmptyPathTree;
import io.quarkus.paths.MultiRootPathTree;
import io.quarkus.paths.PathTree;

public interface ArtifactSources {

    String MAIN = "";
    String TEST = "tests";

    static ArtifactSources main(SourceDir sources, SourceDir resources) {
        return new DefaultArtifactSources(MAIN, List.of(sources), List.of(resources));
    }

    static ArtifactSources test(SourceDir sources, SourceDir resources) {
        return new DefaultArtifactSources(TEST, List.of(sources), List.of(resources));
    }

    String getClassifier();

    Collection<SourceDir> getSourceDirs();

    Collection<SourceDir> getResourceDirs();

    default boolean isOutputAvailable() {
        for (SourceDir src : getSourceDirs()) {
            if (src.isOutputAvailable()) {
                return true;
            }
        }
        for (SourceDir src : getResourceDirs()) {
            if (src.isOutputAvailable()) {
                return true;
            }
        }
        return false;
    }

    default PathTree getOutputTree() {
        final Collection<SourceDir> sourceDirs = getSourceDirs();
        final Collection<SourceDir> resourceDirs = getResourceDirs();
        final List<PathTree> trees = new ArrayList<>(sourceDirs.size() + resourceDirs.size());
        for (SourceDir src : sourceDirs) {
            final PathTree outputTree = src.getOutputTree();
            if (outputTree != null && !outputTree.isEmpty() && !trees.contains(outputTree)) {
                trees.add(outputTree);
            }
        }
        for (SourceDir src : resourceDirs) {
            final PathTree outputTree = src.getOutputTree();
            if (outputTree != null && !outputTree.isEmpty() && !trees.contains(outputTree)) {
                trees.add(outputTree);
            }
        }
        if (trees.isEmpty()) {
            return EmptyPathTree.getInstance();
        }
        if (trees.size() == 1) {
            return trees.get(0);
        }
        return new MultiRootPathTree(trees.toArray(new PathTree[0]));
    }
}


text:
<!doctype html>

    <title>Code coverage report for src\components\main\mainReducer.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / src/components/main/ mainReducer.js

        91.67%
        Statements
        33/36

        73.91%
        Branches
        17/23

        100%
        Functions
        4/4

        85%
        Lines
        17/20

        6 statements, 1 function, 3 branches
        Ignored

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56	1×

1×

1×

1×

6×
6×

6×

6×
6×

6×

6×
6×

1×

5×

1×

1×

import {combineReducers} from 'redux'

const initial_followers = {
	followers: {}
}

const initial_articles = {
	articles: {},
	searchKeyword: '',
	avatars: {}
}

const initial_headline={
    headline: ''
}

//reducer of the main page
export function followers(state = initial_followers, action) {
    switch(action.type) {
        case 'FOLLOWER_UPDATE':
            return { ...state, followers: action.followers };
        default:
            return state;
    }
}

export function articles(state = initial_articles, action) {
    switch(action.type) {
        case 'UPDATE_ARTICLES':
            return { ...state, articles: action.articles };
        default:
            return state;
    }
}

export function headlines(state = initial_headline, action) {
     switch(action.type) {
        case 'UPDATE_HEADLINE':
            return {...state, headline: action.headline};
        case 'GET_HEADLINE':{
            return {...state, headline: action.headline};
        }
        default:
            return state;
    }
}

const mainReducer = combineReducers({
	followers, articles, headlines
})

export default mainReducer

  Code coverage
  generated by istanbul at Tue Apr 04 2017 23:12:31 GMT-0500 (中部夏令时)


text:
package org.apache.sentry.tests.e2e.hive;

import static org.junit.Assert.assertFalse;

import java.io.File;
import java.io.FileOutputStream;
import java.security.CodeSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.sentry.provider.file.PolicyFile;
import org.junit.Before;
import org.junit.Test;

import com.google.common.io.Resources;

public class TestPrivilegesAtFunctionScope extends AbstractTestWithStaticConfiguration {
  private final String SINGLE_TYPE_DATA_FILE_NAME = "kv1.dat";
  private File dataDir;
  private File dataFile;
  private PolicyFile policyFile;

  @Before
  public void setup() throws Exception {
    dataDir = context.getDataDir();
    dataFile = new File(dataDir, SINGLE_TYPE_DATA_FILE_NAME);
    FileOutputStream to = new FileOutputStream(dataFile);
    Resources.copy(Resources.getResource(SINGLE_TYPE_DATA_FILE_NAME), to);
    to.close();
    policyFile = PolicyFile.setAdminOnServer1(ADMINGROUP);
    policyFile.setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
  }

  /**
   * admin should be able to create/drop temp functions
   * user with db level access should be able to create/drop temp functions
   * user with table level access should be able to create/drop temp functions
   * user with no privilege should NOT be able to create/drop temp functions
   */
  @Test
  public void testFuncPrivileges1() throws Exception {
    String tableName1 = "tb_1";
    String udfClassName = "org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf";
    CodeSource udfSrc = Class.forName(udfClassName).getProtectionDomain().getCodeSource();
    String udfLocation = System.getProperty(EXTERNAL_HIVE_LIB);
    if(udfLocation == null) {
      udfLocation = udfSrc.getLocation().getPath();
    }
    Connection connection = context.createConnection(ADMIN1);
    Statement statement = context.createStatement(connection);
    statement.execute("DROP DATABASE IF EXISTS " + DB1 + " CASCADE");
    statement.execute("CREATE DATABASE " + DB1);
    statement.execute("USE " + DB1);
    statement.execute("create table " + DB1 + "." + tableName1
        + " (under_col int comment 'the under column', value string)");
    statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE "
        + DB1 + "." + tableName1);
    statement.execute("DROP TEMPORARY FUNCTION IF EXISTS printf_test");
    statement.execute("DROP TEMPORARY FUNCTION IF EXISTS printf_test_2");
    context.close();

    policyFile
        .addRolesToGroup(USERGROUP1, "db1_all", "UDF_JAR", "data_read")
        .addRolesToGroup(USERGROUP2, "db1_tab1", "UDF_JAR")
        .addRolesToGroup(USERGROUP3, "db1_tab1")
        .addPermissionsToRole("db1_all", "server=server1->db=" + DB1)
        .addPermissionsToRole("db1_tab1", "server=server1->db=" + DB1 + "->table=" + tableName1)
        .addPermissionsToRole("UDF_JAR", "server=server1->uri=file://" + udfLocation)
        .addPermissionsToRole("data_read", "server=server1->URI=" + "file:///tmp");
    writePolicyFile(policyFile);

    // user1 should be able create/drop temp functions
    connection = context.createConnection(USER1_1);
    statement = context.createStatement(connection);
    statement.execute("USE " + DB1);
    statement.execute(
        "CREATE TEMPORARY FUNCTION printf_test AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
    statement.execute("SELECT printf_test(value) FROM " + tableName1);
    statement.execute("DROP TEMPORARY FUNCTION printf_test");

    statement.execute(
        "CREATE FUNCTION printf_test_perm AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf' ");
    statement.execute("SELECT printf_test_perm(value) FROM " + tableName1);
    statement.execute("DROP FUNCTION printf_test_perm");

    // test perm UDF with 'using file' syntax
    statement
        .execute("CREATE FUNCTION printf_test_perm AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf' "
            + " using file 'file:///tmp'");
    statement.execute("DROP FUNCTION printf_test_perm");

    context.close();

    // user2 has select privilege on one of the tables in db1, should be able create/drop temp functions
    connection = context.createConnection(USER2_1);
    statement = context.createStatement(connection);
    statement.execute("USE " + DB1);
    statement.execute(
        "CREATE TEMPORARY FUNCTION printf_test_2 AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
    statement.execute("SELECT printf_test_2(value) FROM " + tableName1);
    statement.execute("DROP TEMPORARY FUNCTION printf_test_2");

    statement.execute(
        "CREATE FUNCTION " + DB1 + ".printf_test_2_perm AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
    statement.execute("SELECT printf_test_2_perm(value) FROM " + tableName1);
    statement.execute("DROP FUNCTION printf_test_2_perm");

    // USER2 doesn't have URI perm on dataFile
    try {
      statement
          .execute("CREATE FUNCTION "
              + DB1
              + ".printf_test_2_perm AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'"
              + " using file '" + "file://" + dataFile.getPath() + "'");
      assertFalse("CREATE TEMPORARY FUNCTION should fail for user3", true);
    } catch (SQLException e) {
      context.verifyAuthzException(e);
    }

    context.close();

    // user3 shouldn't be able to create/drop temp functions since it doesn't have permission for jar
    connection = context.createConnection(USER3_1);
    statement = context.createStatement(connection);
    statement.execute("USE " + DB1);
    try {
      statement.execute(
      "CREATE TEMPORARY FUNCTION printf_test_bad AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
      assertFalse("CREATE TEMPORARY FUNCTION should fail for user3", true);
    } catch (SQLException e) {
      context.verifyAuthzException(e);
    }

    try {
      statement.execute(
      "CREATE FUNCTION printf_test_perm_bad AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
      assertFalse("CREATE FUNCTION should fail for user3", true);
    } catch (SQLException e) {
      context.verifyAuthzException(e);
    }

    context.close();

    // user4 (not part of any group ) shouldn't be able to create/drop temp functions
    connection = context.createConnection(USER4_1);
    statement = context.createStatement(connection);
    try {
      statement.execute("USE default");
      statement.execute(
      "CREATE TEMPORARY FUNCTION printf_test_bad AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFPrintf'");
      assertFalse("CREATE TEMPORARY FUNCTION should fail for user4", true);
    } catch (SQLException e) {
      context.verifyAuthzException(e);
    }
    context.close();

  }

  @Test
  public void testUdfWhiteList () throws Exception {
    String tableName1 = "tab1";

    policyFile
        .addRolesToGroup(USERGROUP1, "db1_all", "UDF_JAR")
        .addRolesToGroup(USERGROUP2, "db1_tab1", "UDF_JAR")
        .addRolesToGroup(USERGROUP3, "db1_tab1")
        .addPermissionsToRole("db1_all", "server=server1->db=" + DB1)
        .addPermissionsToRole("db1_tab1", "server=server1->db=" + DB1 + "->table=" + tableName1)
        .addPermissionsToRole("UDF_JAR", "server=server1->uri=file://${user.home}/.m2");
    writePolicyFile(policyFile);

    Connection connection = context.createConnection(ADMIN1);
    Statement statement = connection.createStatement();
    statement.execute("DROP DATABASE IF EXISTS " + DB1 + " CASCADE");
    statement.execute("CREATE DATABASE " + DB1);
    statement.execute("USE " + DB1);
    statement.execute("create table " + tableName1
        + " (under_col int comment 'the under column', value string)");
    statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE "
        + DB1 + "." + tableName1);
    statement.execute("SELECT rand(), concat(value, '_foo') FROM " + tableName1);

    context.assertAuthzException(statement,
        "SELECT  reflect('java.net.URLDecoder', 'decode', 'http://www.apache.org', 'utf-8'), value FROM " + tableName1);
    context.assertAuthzException(statement,
        "SELECT  java_method('java.net.URLDecoder', 'decode', 'http://www.apache.org', 'utf-8'), value FROM " + tableName1);
    statement.close();
    connection.close();
  }
}


text:
 (function (window) {

    QUnit.module("Noop Trip Invoker Facts");

    QUnit.test("Actions are not triggered prior to trip.", function () {
        var triggered = false,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered = true;
            });

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();
        tripInvoker.Invoke();
        tripInvoker.Invoke();

        QUnit.equal(triggered, false);
    });

    QUnit.test("Actions are not instantly triggered after trip.", function () {
        var triggered = false,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered = true;
            });

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();

        QUnit.equal(triggered, false);

        tripInvoker.Trip();

        QUnit.equal(triggered, false);
    });

    QUnit.test("Actions are triggered once tripped and Invoke is called.", function () {
        var triggered = false,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered = true;
            });

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();

        QUnit.equal(triggered, false);

        tripInvoker.Trip();

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();

        QUnit.equal(triggered, true);

        triggered = false;

        tripInvoker.Invoke();

        QUnit.equal(triggered, true);
    });

    QUnit.test("Actions are still triggered if trip is called more than once.", function () {
        var triggered = false,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered = true;
            });

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();

        QUnit.equal(triggered, false);

        tripInvoker.Trip();
        tripInvoker.Trip();
        tripInvoker.Trip();

        QUnit.equal(triggered, false);

        tripInvoker.Invoke();

        QUnit.equal(triggered, true);

        triggered = false;

        tripInvoker.Trip();
        tripInvoker.Trip();
        tripInvoker.Trip();

        tripInvoker.Invoke();

        QUnit.equal(triggered, true);
    });

    QUnit.test("Invoke Once doesn't allow multiple invokes", function () {
        var triggered = 0,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered++;
            });

        QUnit.equal(triggered, 0);

        tripInvoker.Trip();

        tripInvoker.InvokeOnce();
        tripInvoker.Invoke();
        tripInvoker.InvokeOnce();
        tripInvoker.Invoke();

        QUnit.equal(triggered, 1);

        tripInvoker.Trip();

        tripInvoker.Invoke();
        tripInvoker.Invoke();
        tripInvoker.InvokeOnce()
        tripInvoker.Invoke();

        QUnit.equal(triggered, 4);
    });

    QUnit.test("Constructor trip argument causes object to already be tripped.", function () {
        var triggered = 0,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered++;
            }, true);

        QUnit.equal(triggered, 0);

        tripInvoker.InvokeOnce();
        tripInvoker.Invoke();
        tripInvoker.InvokeOnce();
        tripInvoker.Invoke();

        QUnit.equal(triggered, 1);

        tripInvoker.Trip();

        tripInvoker.Invoke();
        tripInvoker.Invoke();
        tripInvoker.InvokeOnce()
        tripInvoker.Invoke();

        QUnit.equal(triggered, 4);
    });

    QUnit.test("Constructor trip argument causes object to already be tripped.", function () {
        var triggered = 0,
            tripInvoker = new eg._.Utilities.NoopTripInvoker(function () {
                triggered++;
            }, true);

        QUnit.equal(triggered, 0);

        tripInvoker.Invoke();
        tripInvoker.Invoke();

        QUnit.equal(triggered, 2);

        tripInvoker.Reset();

        tripInvoker.Invoke();
        tripInvoker.Invoke();
        tripInvoker.InvokeOnce()
        tripInvoker.Invoke();

        QUnit.equal(triggered, 2);

        tripInvoker.Trip();

        tripInvoker.InvokeOnce();
        tripInvoker.Invoke();

        QUnit.equal(triggered, 3);
    });

})(window);


text:
require 'tempfile'
require 'mime/types'
require 'cgi'
require 'netrc'
require 'set'

module RestClient
  # This class is used internally by RestClient to send the request, but you can also
  # call it directly if you'd like to use a method not supported by the
  # main API.  For example:
  #
  #   RestClient::Request.execute(:method => :head, :url => 'http://example.com')
  #
  # Mandatory parameters:
  # * :method
  # * :url
  # Optional parameters (have a look at ssl and/or uri for some explanations):
  # * :headers a hash containing the request headers
  # * :cookies will replace possible cookies in the :headers
  # * :user and :password for basic auth, will be replaced by a user/password available in the :url
  # * :block_response call the provided block with the HTTPResponse as parameter
  # * :raw_response return a low-level RawResponse instead of a Response
  # * :max_redirects maximum number of redirections (default to 10)
  # * :verify_ssl enable ssl verification, possible values are constants from
  #     OpenSSL::SSL::VERIFY_*, defaults to OpenSSL::SSL::VERIFY_PEER
  # * :timeout and :open_timeout are how long to wait for a response and to
  #     open a connection, in seconds. Pass nil to disable the timeout.
  # * :ssl_client_cert, :ssl_client_key, :ssl_ca_file, :ssl_ca_path,
  #     :ssl_cert_store, :ssl_verify_callback, :ssl_verify_callback_warnings
  # * :ssl_version specifies the SSL version for the underlying Net::HTTP connection
  # * :ssl_ciphers sets SSL ciphers for the connection. See
  #     OpenSSL::SSL::SSLContext#ciphers=
  class Request

    attr_reader :method, :url, :headers, :cookies,
                :payload, :user, :password, :timeout, :max_redirects,
                :open_timeout, :raw_response, :processed_headers, :args,
                :ssl_opts

    def self.execute(args, & block)
      new(args).execute(& block)
    end

    # This is similar to the list now in ruby core, but adds HIGH and RC4-MD5
    # for better compatibility (similar to Firefox) and moves AES-GCM cipher
    # suites above DHE/ECDHE CBC suites (similar to Chromium).
    # https://github.com/ruby/ruby/commit/699b209cf8cf11809620e12985ad33ae33b119ee
    #
    # This list will be used by default if the Ruby global OpenSSL default
    # ciphers appear to be a weak list.
    DefaultCiphers = %w{
      !aNULL
      !eNULL
      !EXPORT
      !SSLV2
      !LOW

      ECDHE-ECDSA-AES128-GCM-SHA256
      ECDHE-RSA-AES128-GCM-SHA256
      ECDHE-ECDSA-AES256-GCM-SHA384
      ECDHE-RSA-AES256-GCM-SHA384
      DHE-RSA-AES128-GCM-SHA256
      DHE-DSS-AES128-GCM-SHA256
      DHE-RSA-AES256-GCM-SHA384
      DHE-DSS-AES256-GCM-SHA384
      AES128-GCM-SHA256
      AES256-GCM-SHA384
      ECDHE-ECDSA-AES128-SHA256
      ECDHE-RSA-AES128-SHA256
      ECDHE-ECDSA-AES128-SHA
      ECDHE-RSA-AES128-SHA
      ECDHE-ECDSA-AES256-SHA384
      ECDHE-RSA-AES256-SHA384
      ECDHE-ECDSA-AES256-SHA
      ECDHE-RSA-AES256-SHA
      DHE-RSA-AES128-SHA256
      DHE-RSA-AES256-SHA256
      DHE-RSA-AES128-SHA
      DHE-RSA-AES256-SHA
      DHE-DSS-AES128-SHA256
      DHE-DSS-AES256-SHA256
      DHE-DSS-AES128-SHA
      DHE-DSS-AES256-SHA
      AES128-SHA256
      AES256-SHA256
      AES128-SHA
      AES256-SHA
      ECDHE-ECDSA-RC4-SHA
      ECDHE-RSA-RC4-SHA
      RC4-SHA

      HIGH
      +RC4
      RC4-MD5
    }.join(":")

    # A set of weak default ciphers that we will override by default.
    WeakDefaultCiphers = Set.new([
      "ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW",
    ])

    SSLOptionList = %w{client_cert client_key ca_file ca_path cert_store
                       version ciphers verify_callback verify_callback_warnings}

    def initialize args
      @method = args[:method] or raise ArgumentError, "must pass :method"
      @headers = args[:headers] || {}
      if args[:url]
        @url = process_url_params(args[:url], headers)
      else
        raise ArgumentError, "must pass :url"
      end
      @cookies = @headers.delete(:cookies) || args[:cookies] || {}
      @payload = Payload.generate(args[:payload])
      @user = args[:user]
      @password = args[:password]
      if args.include?(:timeout)
        @timeout = args[:timeout]
      end
      if args.include?(:open_timeout)
        @open_timeout = args[:open_timeout]
      end
      @block_response = args[:block_response]
      @raw_response = args[:raw_response] || false

      @ssl_opts = {}

      if args.include?(:verify_ssl)
        v_ssl = args.fetch(:verify_ssl)
        if v_ssl
          if v_ssl == true
            # interpret :verify_ssl => true as VERIFY_PEER
            @ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_PEER
          else
            # otherwise pass through any truthy values
            @ssl_opts[:verify_ssl] = v_ssl
          end
        else
          # interpret all falsy :verify_ssl values as VERIFY_NONE
          @ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_NONE
        end
      else
        # if :verify_ssl was not passed, default to VERIFY_PEER
        @ssl_opts[:verify_ssl] = OpenSSL::SSL::VERIFY_PEER
      end

      SSLOptionList.each do |key|
        source_key = ('ssl_' + key).to_sym
        if args.has_key?(source_key)
          @ssl_opts[key.to_sym] = args.fetch(source_key)
        end
      end

      # If there's no CA file, CA path, or cert store provided, use default
      if !ssl_ca_file && !ssl_ca_path && !@ssl_opts.include?(:cert_store)
        @ssl_opts[:cert_store] = self.class.default_ssl_cert_store
      end

      unless @ssl_opts.include?(:ciphers)
        # If we're on a Ruby version that has insecure default ciphers,
        # override it with our default list.
        if WeakDefaultCiphers.include?(
             OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.fetch(:ciphers))
          @ssl_opts[:ciphers] = DefaultCiphers
        end
      end

      @tf = nil # If you are a raw request, this is your tempfile
      @max_redirects = args[:max_redirects] || 10
      @processed_headers = make_headers headers
      @args = args
    end

    def execute & block
      uri = parse_url_with_auth(url)
      transmit uri, net_http_request_class(method).new(uri.request_uri, processed_headers), payload, & block
    ensure
      payload.close if payload
    end

    # SSL-related options
    def verify_ssl
      @ssl_opts.fetch(:verify_ssl)
    end
    SSLOptionList.each do |key|
      define_method('ssl_' + key) do
        @ssl_opts[key.to_sym]
      end
    end

    # Extract the query parameters and append them to the url
    def process_url_params url, headers
      url_params = {}
      headers.delete_if do |key, value|
        if 'params' == key.to_s.downcase && value.is_a?(Hash)
          url_params.merge! value
          true
        else
          false
        end
      end
      unless url_params.empty?
        query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
        url + "?#{query_string}"
      else
        url
      end
    end

    def make_headers user_headers
      unless @cookies.empty?

        # Validate that the cookie names and values look sane. If you really
        # want to pass scary characters, just set the Cookie header directly.
        # RFC6265 is actually much more restrictive than we are.
        @cookies.each do |key, val|
          unless valid_cookie_key?(key)
            raise ArgumentError.new("Invalid cookie name: #{key.inspect}")
          end
          unless valid_cookie_value?(val)
            raise ArgumentError.new("Invalid cookie value: #{val.inspect}")
          end
        end

        user_headers[:cookie] = @cookies.map { |key, val| "#{key}=#{val}" }.sort.join('; ')
      end
      headers = stringify_headers(default_headers).merge(stringify_headers(user_headers))
      headers.merge!(@payload.headers) if @payload
      headers
    end

    # Do some sanity checks on cookie keys.
    #
    # Properly it should be a valid TOKEN per RFC 2616, but lots of servers are
    # more liberal.
    #
    # Disallow the empty string as well as keys containing control characters,
    # equals sign, semicolon, comma, or space.
    #
    def valid_cookie_key?(string)
      return false if string.empty?

      ! Regexp.new('[\x0-\x1f\x7f=;, ]').match(string)
    end

    # Validate cookie values. Rather than following RFC 6265, allow anything
    # but control characters, comma, and semicolon.
    def valid_cookie_value?(value)
      ! Regexp.new('[\x0-\x1f\x7f,;]').match(value)
    end

    def net_http_class
      if RestClient.proxy
        proxy_uri = URI.parse(RestClient.proxy)
        Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
      else
        Net::HTTP
      end
    end

    def net_http_request_class(method)
      Net::HTTP.const_get(method.to_s.capitalize)
    end

    def net_http_do_request(http, req, body=nil, &block)
      if body != nil && body.respond_to?(:read)
        req.body_stream = body
        return http.request(req, nil, &block)
      else
        return http.request(req, body, &block)
      end
    end

    def parse_url(url)
      url = "http://#{url}" unless url.match(/^http/)
      URI.parse(url)
    end

    def parse_url_with_auth(url)
      uri = parse_url(url)
      @user = CGI.unescape(uri.user) if uri.user
      @password = CGI.unescape(uri.password) if uri.password
      if !@user && !@password
        @user, @password = Netrc.read[uri.host]
      end
      uri
    end

    def process_payload(p=nil, parent_key=nil)
      unless p.is_a?(Hash)
        p
      else
        @headers[:content_type] ||= 'application/x-www-form-urlencoded'
        p.keys.map do |k|
          key = parent_key ? "#{parent_key}[#{k}]" : k
          if p[k].is_a? Hash
            process_payload(p[k], key)
          else
            value = parser.escape(p[k].to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
            "#{key}=#{value}"
          end
        end.join("&")
      end
    end

    # Return a certificate store that can be used to validate certificates with
    # the system certificate authorities. This will probably not do anything on
    # OS X, which monkey patches OpenSSL in terrible ways to insert its own
    # validation. On most *nix platforms, this will add the system certifcates
    # using OpenSSL::X509::Store#set_default_paths. On Windows, this will use
    # RestClient::Windows::RootCerts to look up the CAs trusted by the system.
    #
    # @return [OpenSSL::X509::Store]
    #
    def self.default_ssl_cert_store
      cert_store = OpenSSL::X509::Store.new
      cert_store.set_default_paths

      # set_default_paths() doesn't do anything on Windows, so look up
      # certificates using the win32 API.
      if RestClient::Platform.windows?
        RestClient::Windows::RootCerts.instance.to_a.uniq.each do |cert|
          begin
            cert_store.add_cert(cert)
          rescue OpenSSL::X509::StoreError => err
            # ignore duplicate certs
            raise unless err.message == 'cert already in hash table'
          end
        end
      end

      cert_store
    end

    def print_verify_callback_warnings
      warned = false
      if RestClient::Platform.mac_mri?
        warn('warning: ssl_verify_callback return code is ignored on OS X')
        warned = true
      end
      if RestClient::Platform.jruby?
        warn('warning: SSL verify_callback may not work correctly in jruby')
        warn('see https://github.com/jruby/jruby/issues/597')
        warned = true
      end
      warned
    end

    def transmit uri, req, payload, & block
      setup_credentials req

      net = net_http_class.new(uri.host, uri.port)
      net.use_ssl = uri.is_a?(URI::HTTPS)
      net.ssl_version = ssl_version if ssl_version
      net.ciphers = ssl_ciphers if ssl_ciphers

      net.verify_mode = verify_ssl

      net.cert = ssl_client_cert if ssl_client_cert
      net.key = ssl_client_key if ssl_client_key
      net.ca_file = ssl_ca_file if ssl_ca_file
      net.ca_path = ssl_ca_path if ssl_ca_path
      net.cert_store = ssl_cert_store if ssl_cert_store

      # We no longer rely on net.verify_callback for the main SSL verification
      # because it's not well supported on all platforms (see comments below).
      # But do allow users to set one if they want.
      if ssl_verify_callback
        net.verify_callback = ssl_verify_callback

        # Hilariously, jruby only calls the callback when cert_store is set to
        # something, so make sure to set one.
        # https://github.com/jruby/jruby/issues/597
        if RestClient::Platform.jruby?
          net.cert_store ||= OpenSSL::X509::Store.new
        end

        if ssl_verify_callback_warnings != false
          if print_verify_callback_warnings
            warn('pass :ssl_verify_callback_warnings => false to silence this')
          end
        end
      end

      if OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE
        warn('WARNING: OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE')
        warn('This dangerous monkey patch leaves you open to MITM attacks!')
        warn('Try passing :verify_ssl => false instead.')
      end

      if defined? @timeout
        if @timeout == -1
          warn 'To disable read timeouts, please set timeout to nil instead of -1'
          @timeout = nil
        end
        net.read_timeout = @timeout
      end
      if defined? @open_timeout
        if @open_timeout == -1
          warn 'To disable open timeouts, please set open_timeout to nil instead of -1'
          @open_timeout = nil
        end
        net.open_timeout = @open_timeout
      end

      RestClient.before_execution_procs.each do |before_proc|
        before_proc.call(req, args)
      end

      log_request

      net.start do |http|
        if @block_response
          net_http_do_request(http, req, payload ? payload.to_s : nil,
                              &@block_response)
        else
          res = net_http_do_request(http, req, payload ? payload.to_s : nil) \
            { |http_response| fetch_body(http_response) }
          log_response res
          process_result res, & block
        end
      end
    rescue EOFError
      raise RestClient::ServerBrokeConnection
    rescue Timeout::Error, Errno::ETIMEDOUT
      raise RestClient::RequestTimeout

    rescue OpenSSL::SSL::SSLError => error
      # TODO: deprecate and remove RestClient::SSLCertificateNotVerified and just
      # pass through OpenSSL::SSL::SSLError directly.
      #
      # Exceptions in verify_callback are ignored [1], and jruby doesn't support
      # it at all [2]. RestClient has to catch OpenSSL::SSL::SSLError and either
      # re-throw it as is, or throw SSLCertificateNotVerified based on the
      # contents of the message field of the original exception.
      #
      # The client has to handle OpenSSL::SSL::SSLError exceptions anyway, so
      # we shouldn't make them handle both OpenSSL and RestClient exceptions.
      #
      # [1] https://github.com/ruby/ruby/blob/89e70fe8e7/ext/openssl/ossl.c#L238
      # [2] https://github.com/jruby/jruby/issues/597

      if error.message.include?("certificate verify failed")
        raise SSLCertificateNotVerified.new(error.message)
      else
        raise error
      end
    end

    def setup_credentials(req)
      req.basic_auth(user, password) if user
    end

    def fetch_body(http_response)
      if @raw_response
        # Taken from Chef, which as in turn...
        # Stolen from http://www.ruby-forum.com/topic/166423
        # Kudos to _why!
        @tf = Tempfile.new("rest-client")
        @tf.binmode
        size, total = 0, http_response.header['Content-Length'].to_i
        http_response.read_body do |chunk|
          @tf.write chunk
          size += chunk.size
          if RestClient.log
            if size == 0
              RestClient.log << "%s %s done (0 length file)\n" % [@method, @url]
            elsif total == 0
              RestClient.log << "%s %s (zero content length)\n" % [@method, @url]
            else
              RestClient.log << "%s %s %d%% done (%d of %d)\n" % [@method, @url, (size * 100) / total, size, total]
            end
          end
        end
        @tf.close
        @tf
      else
        http_response.read_body
      end
      http_response
    end

    def process_result res, & block
      if @raw_response
        # We don't decode raw requests
        response = RawResponse.new(@tf, res, args, self)
      else
        response = Response.create(Request.decode(res['content-encoding'], res.body), res, args, self)
      end

      if block_given?
        block.call(response, self, res, & block)
      else
        response.return!(self, res, & block)
      end

    end

    def self.decode content_encoding, body
      if (!body) || body.empty?
        body
      elsif content_encoding == 'gzip'
        Zlib::GzipReader.new(StringIO.new(body)).read
      elsif content_encoding == 'deflate'
        begin
          Zlib::Inflate.new.inflate body
        rescue Zlib::DataError
          # No luck with Zlib decompression. Let's try with raw deflate,
          # like some broken web servers do.
          Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate body
        end
      else
        body
      end
    end

    def log_request
      return unless RestClient.log

      out = []
      sanitized_url = begin
        uri = URI.parse(url)
        uri.password = "REDACTED" if uri.password
        uri.to_s
      rescue URI::InvalidURIError
        # An attacker may be able to manipulate the URL to be
        # invalid, which could force discloure of a password if
        # we show any of the un-parsed URL here.
        "[invalid uri]"
      end

      out << "RestClient.#{method} #{sanitized_url.inspect}"
      out << payload.short_inspect if payload
      out << processed_headers.to_a.sort.map { |(k, v)| [k.inspect, v.inspect].join("=>") }.join(", ")
      RestClient.log << out.join(', ') + "\n"
    end

    def log_response res
      return unless RestClient.log

      size = if @raw_response
               File.size(@tf.path)
             else
               res.body.nil? ? 0 : res.body.size
             end

      RestClient.log << "# => #{res.code} #{res.class.to_s.gsub(/^Net::HTTP/, '')} | #{(res['Content-type'] || '').gsub(/;.*$/, '')} #{size} bytes\n"
    end

    # Return a hash of headers whose keys are capitalized strings
    def stringify_headers headers
      headers.inject({}) do |result, (key, value)|
        if key.is_a? Symbol
          key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
        end
        if 'CONTENT-TYPE' == key.upcase
          result[key] = maybe_convert_extension(value.to_s)
        elsif 'ACCEPT' == key.upcase
          # Accept can be composed of several comma-separated values
          if value.is_a? Array
            target_values = value
          else
            target_values = value.to_s.split ','
          end
          result[key] = target_values.map { |ext|
            maybe_convert_extension(ext.to_s.strip)
          }.join(', ')
        else
          result[key] = value.to_s
        end
        result
      end
    end

    def default_headers
      {:accept => '*/*; q=0.5, application/xml', :accept_encoding => 'gzip, deflate'}
    end

    private

    def parser
      URI.const_defined?(:Parser) ? URI::Parser.new : URI
    end

    # Given a MIME type or file extension, return either a MIME type or, if
    # none is found, the input unchanged.
    #
    #     >> maybe_convert_extension('json')
    #     => 'application/json'
    #
    #     >> maybe_convert_extension('unknown')
    #     => 'unknown'
    #
    #     >> maybe_convert_extension('application/xml')
    #     => 'application/xml'
    #
    # @param ext [String]
    #
    # @return [String]
    #
    def maybe_convert_extension(ext)
      unless ext =~ /\A[a-zA-Z0-9_@-]+\z/
        # Don't look up strings unless they look like they could be a file
        # extension known to mime-types.
        #
        # There currently isn't any API public way to look up extensions
        # directly out of MIME::Types, but the type_for() method only strips
        # off after a period anyway.
        return ext
      end

      types = MIME::Types.type_for(ext)
      if types.empty?
        ext
      else
        types.first.content_type
      end
    end
  end
end


text:
// Copyright 2005-2009 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// On some platforms std::limits gives incorrect values for long double.
// This tries to work around them.

#if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_LIMITS_HEADER)
#define BOOST_FUNCTIONAL_HASH_DETAIL_LIMITS_HEADER

#include <boost/config.hpp>
#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif

#include <boost/limits.hpp>

// On OpenBSD, numeric_limits is not reliable for long doubles, but
// the macros defined in <float.h> are and support long double when STLport
// doesn't.

#if defined(__OpenBSD__) || defined(_STLP_NO_LONG_DOUBLE)
#include <float.h>
#endif

namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
{
    namespace hash_detail
    {
        template <class T>
        struct limits : std::numeric_limits<T> {};

#if defined(__OpenBSD__) || defined(_STLP_NO_LONG_DOUBLE)
        template <>
        struct limits<long double>
             : std::numeric_limits<long double>
        {
            static long double epsilon() {
                return LDBL_EPSILON;
            }

            static long double (max)() {
                return LDBL_MAX;
            }

            static long double (min)() {
                return LDBL_MIN;
            }

            BOOST_STATIC_CONSTANT(int, digits = LDBL_MANT_DIG);
            BOOST_STATIC_CONSTANT(int, max_exponent = LDBL_MAX_EXP);
            BOOST_STATIC_CONSTANT(int, min_exponent = LDBL_MIN_EXP);
#if defined(_STLP_NO_LONG_DOUBLE)
            BOOST_STATIC_CONSTANT(int, radix = FLT_RADIX);
#endif
        };
#endif // __OpenBSD__
    }
}

#endif


text:
require 'puppet/face'
require 'puppet/parser'

Puppet::Face.define(:parser, '0.0.1') do
  copyright "Puppet Labs", 2011
  license   "Apache 2 license; see COPYING"

  summary "Interact directly with the parser."

  action :validate do
    summary "Validate the syntax of one or more Puppet manifests."
    arguments "[<manifest>] [<manifest> ...]"
    returns "Nothing, or the first syntax error encountered."
    description <<-'EOT'
      This action validates Puppet DSL syntax without compiling a catalog or
      syncing any resources. If no manifest files are provided, it will
      validate the default site manifest.

      When validating with --parser current, the validation stops after the first
      encountered issue.

      When validating with --parser future, multiple issues per file are reported up
      to the settings of max_error, and max_warnings. The processing stops
      after having reported issues for the first encountered file with errors.
    EOT
    examples <<-'EOT'
      Validate the default site manifest at /etc/puppet/manifests/site.pp:

      $ puppet parser validate

      Validate two arbitrary manifest files:

      $ puppet parser validate init.pp vhost.pp

      Validate from STDIN:

      $ cat init.pp | puppet parser validate
    EOT
    when_invoked do |*args|
      args.pop
      files = args
      if files.empty?
        if not STDIN.tty?
          Puppet[:code] = STDIN.read
          validate_manifest
        else
          manifest = Puppet.lookup(:current_environment).manifest
          files << manifest
          Puppet.notice "No manifest specified. Validating the default manifest #{manifest}"
        end
      end
      missing_files = []
      files.each do |file|
        if Puppet::FileSystem.exist?(file)
          validate_manifest(file)
        else
          missing_files << file
        end
      end
      unless missing_files.empty?
        raise Puppet::Error, "One or more file(s) specified did not exist:\n#{missing_files.collect {|f| " " * 3 + f + "\n"}}"
      end
      nil
    end
  end

  action (:dump) do
    summary "Outputs a dump of the internal parse tree for debugging"
    arguments "-e <source>| [<manifest> ...] "
    returns "A dump of the resulting AST model unless there are syntax or validation errors."
    description <<-'EOT'
      This action parses and validates the Puppet DSL syntax without compiling a catalog
      or syncing any resources. It automatically turns on the future parser for the parsing.

      The command accepts one or more manifests (.pp) files, or an -e followed by the puppet
      source text.
      If no arguments are given, the stdin is read (unless it is attached to a terminal)

      The output format of the dumped tree is not API, it may change from time to time.
    EOT

    option "--e <source>" do
      default_to { nil }
      summary "dump one source expression given on the command line."
    end

    option("--[no-]validate") do
      summary "Whether or not to validate the parsed result, if no-validate only syntax errors are reported"
    end

    when_invoked do |*args|
      require 'puppet/pops'
      options = args.pop
      if options[:e]
        dump_parse(options[:e], 'command-line-string', options, false)
      elsif args.empty?
        if ! STDIN.tty?
          dump_parse(STDIN.read, 'stdin', options, false)
        else
          raise Puppet::Error, "No input to parse given on command line or stdin"
        end
      else
        missing_files = []
        files = args
        available_files = files.select do |file|
          Puppet::FileSystem.exist?(file)
        end
        missing_files = files - available_files

        dumps = available_files.collect do |file|
          dump_parse(File.read(file), file, options)
        end.join("")

        if missing_files.empty?
          dumps
        else
          dumps + "One or more file(s) specified did not exist:\n" + missing_files.collect { |f| "   #{f}" }.join("\n")
        end
      end
    end
  end

  def dump_parse(source, filename, options, show_filename = true)
    output = ""
    dumper = Puppet::Pops::Model::ModelTreeDumper.new
    evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new
    begin
      if options[:validate]
        parse_result = evaluating_parser.parse_string(source, filename)
      else
        # side step the assert_and_report step
        parse_result = evaluating_parser.parser.parse_string(source)
      end
      if show_filename
        output << "--- #{filename}"
      end
      output << dumper.dump(parse_result) << "\n"
    rescue Puppet::ParseError => detail
      if show_filename
        Puppet.err("--- #{filename}")
      end
      Puppet.err(detail.message)
      ""
    end
  end

  # @api private
  def validate_manifest(manifest = nil)
    env = Puppet.lookup(:current_environment)
    validation_environment = manifest ? env.override_with(:manifest => manifest) : env

    validation_environment.check_for_reparse
    validation_environment.known_resource_types.clear

  rescue => detail
    Puppet.log_exception(detail)
    exit(1)
  end
end


text:
import csv
import itertools
import argparse
import importlib
import sys

from csvgroup.common import dump_as_csv

def cast_to_type(type, values):
    return [type(value) for value in values if value]

def aggregate(function, values, type):
    cast_values = cast_to_type(type, values)

    return function(cast_values) if cast_values else None

def get_values(column, items):
    return [item.get(column) for item in items]

def process(items, group, columns, function, type):
    def key(item):
        return [item.get(column) for column in group]

    def groups(items, key):
        return (
            (group_key, list(generator))
            for group_key, generator in itertools.groupby(
                sorted(items, key=key),
                key
            )
        )

    fieldnames = group + columns

    yield fieldnames

    for group_key, group_items in groups(items, key):
        yield (
            group_key + [
                aggregate(
                    function,
                    get_values(column, group_items),
                    type
                )
                for column in columns
            ]
        )

def arguments():
    parser = argparse.ArgumentParser(
        description="Perform group-by aggregation on CSV files"
    )
    parser.add_argument(
        "--group",
        "-g",
        help="list of columns to group by, separated by comma")
    parser.add_argument(
        "--import-module",
        "-i",
        help="module to import for the operation")
    parser.add_argument(
        "--type",
        "-t",
        default="float",
        help="type of columns to aggregate (default: float)")
    parser.add_argument(
        "columns",
        help="list of columns to perform aggregation on, separated by comma")
    parser.add_argument(
        "function",
        help=("Python function that performs aggregation (e.g., 'sum' "
              + "or 'lambda v: 1. * sum(v) / len(v)')"))

    return parser.parse_args()

def main():
    args = arguments()

    environment = dict()

    if args.import_module:
        module = importlib.import_module(args.import_module)
        environment[module.__name__] = module

    group = args.group.split(",") if args.group else []
    columns = args.columns.split(",")
    function = eval(args.function, environment)
    type = eval(args.type, environment)

    dump_as_csv(
        process(
            csv.DictReader(sys.stdin),
            group,
            columns,
            function,
            type
        )
    )

if __name__ == "__main__":
    main()