text:
package org.apache.ctakes.ytex.uima.annotators;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ctakes.typesystem.type.textspan.Segment;
import org.apache.ctakes.ytex.uima.ApplicationContextHolder;
import org.apache.ctakes.ytex.uima.dao.SegmentRegexDao;
import org.apache.ctakes.ytex.uima.model.SegmentRegex;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;

import com.google.common.base.Strings;

/**
 * Annotate segments (i.e. sections). Use regexs to find segments. Read the
 * regex-segment id map from the db.
 *
 * @author vhacongarlav
 *
 */
public class SegmentRegexAnnotator extends JCasAnnotator_ImplBase {
	private static final Log log = LogFactory
			.getLog(SegmentRegexAnnotator.class);
	private SegmentRegexDao segmentRegexDao;
	private Map<SegmentRegex, Pattern> regexMap = new HashMap<SegmentRegex, Pattern>();
	private String defaultSegmentId = "DEFAULT";

	/**
	 * Load the regex-segment map from the database using the segmentRegexDao.
	 * Compile all the patterns.
	 */
	public void initialize(UimaContext aContext)
			throws ResourceInitializationException {
		segmentRegexDao = (SegmentRegexDao) ApplicationContextHolder
				.getApplicationContext().getBean("segmentRegexDao");
		List<SegmentRegex> regexList = segmentRegexDao.getSegmentRegexs();
		initRegexMap(regexList);
		String defaultSegmentId = (String) aContext
				.getConfigParameterValue("SegmentID");
		if (!Strings.isNullOrEmpty(defaultSegmentId)) {
			this.defaultSegmentId = defaultSegmentId;
		}
	}

	protected void initRegexMap(List<SegmentRegex> regexList) {
		for (SegmentRegex regex : regexList) {
			if (log.isDebugEnabled())
				log.debug(regex);
			Pattern pat = Pattern.compile(regex.getRegex());
			regexMap.put(regex, pat);
		}
	}

	/**
	 * Add Segment annotations to the cas. First create a list of segments. Then
	 * sort the list according to segment start. For each segment that has no
	 * end, set the end to the [beginning of next segment - 1], or the eof.
	 */
	@Override
	public void process(JCas aJCas) throws AnalysisEngineProcessException {
		String strDocText = aJCas.getDocumentText();
		if (strDocText == null)
			return;
		List<Segment> segmentsAdded = new ArrayList<Segment>();
		// find all the segments, set begin and id, add to list
		for (Map.Entry<SegmentRegex, Pattern> entry : regexMap.entrySet()) {
			if (log.isDebugEnabled()) {
				log.debug("applying regex:" + entry.getKey().getRegex());
			}
			Matcher matcher = entry.getValue().matcher(strDocText);
			while (matcher.find()) {
				Segment seg = new Segment(aJCas);
				if (entry.getKey().isLimitToRegex()
						&& matcher.groupCount() == 1) {
					seg.setBegin(matcher.start(1));
					seg.setEnd(matcher.end(1));
				} else {
					seg.setBegin(matcher.start());
					if (entry.getKey().isLimitToRegex()) {
						seg.setEnd(matcher.end());
					}
				}
				seg.setId(entry.getKey().getSegmentID());
				if (log.isDebugEnabled()) {
					log.debug("found match: id=" + seg.getId() + ", begin="
							+ seg.getBegin());
				}
				segmentsAdded.add(seg);
			}
		}
		if (log.isDebugEnabled()) {
			log.debug("segmentsAdded: " + segmentsAdded.size());
		}
		if (segmentsAdded.size() > 0) {
			// sort the segments by begin
			Collections.sort(segmentsAdded, new Comparator<Segment>() {

				// @Override
				public int compare(Segment o1, Segment o2) {
					return o1.getBegin() < o2.getBegin() ? -1
							: o1.getBegin() > o2.getBegin() ? 1 : 0;
				}

			});
			// set the end for each segment
			for (int i = 0; i < segmentsAdded.size(); i++) {
				Segment seg = segmentsAdded.get(i);
				Segment segNext = (i + 1) < segmentsAdded.size() ? segmentsAdded
						.get(i + 1) : null;
				if (seg.getEnd() <= 0) {
					if (segNext != null) {
						// set end to beginning of next segment
						seg.setEnd(segNext.getBegin() - 1);
					} else {
						// set end to doc end
						seg.setEnd(strDocText.length());
					}
				} else {
					// segments shouldn't overlap
					if (segNext != null && segNext.getBegin() < seg.getEnd()) {
						seg.setEnd(segNext.getBegin() - 1);
					}
				}
				if (log.isDebugEnabled()) {
					log.debug("Adding Segment: segment id=" + seg.getId()
							+ ", begin=" + seg.getBegin() + ", end="
							+ seg.getEnd());
				}
				seg.addToIndexes();
			}
		}
		// ctakes 1.3.2 - anything not in a segment will not be annotated - add
		// text outside segments to the 'default' segment
		int end = 0;
		for (Segment seg : segmentsAdded) {
			if ((seg.getBegin() - 1) > end) {
				addGapSegment(aJCas, end, seg.getBegin() - 1);
			}
			end = seg.getEnd();
		}
		if (end < strDocText.length()) {
			addGapSegment(aJCas, end, strDocText.length());
		}
	}

	private void addGapSegment(JCas aJCas, int begin, int end) {
		Segment segGap = new Segment(aJCas);
		segGap.setBegin(begin);
		segGap.setEnd(end);
		segGap.addToIndexes();
		segGap.setId(defaultSegmentId);
	}
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/devtools/build/v1/build_events.proto

namespace Google\Cloud\Build\V1;

use UnexpectedValueException;

/**
 * The type of console output stream.
 *
 * Protobuf type google.devtools.build.v1.ConsoleOutputStream
 */
class ConsoleOutputStream
{
    /**
     * Unspecified or unknown.
     *
     * Generated from protobuf enum UNKNOWN = 0;
     */
    const UNKNOWN = 0;
    /**
     * Normal output stream.
     *
     * Generated from protobuf enum STDOUT = 1;
     */
    const STDOUT = 1;
    /**
     * Error output stream.
     *
     * Generated from protobuf enum STDERR = 2;
     */
    const STDERR = 2;

    private static $valueToName = [
        self::UNKNOWN => 'UNKNOWN',
        self::STDOUT => 'STDOUT',
        self::STDERR => 'STDERR',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}

redpajama_set_name: RedPajamaGithub


text:
A simple wrapper around the Mozenda api

## Installation

Add this line to your application's Gemfile:

    gem 'mozenda'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mozenda

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
"""
    flaskbb.management.forms
    ~~~~~~~~~~~~~~~~~~~~~~~~

    It provides the forms that are needed for the management views.

    :copyright: (c) 2014 by the FlaskBB Team.
    :license: BSD, see LICENSE for more details.
"""
from flask_wtf import Form
from wtforms import (StringField, TextAreaField, PasswordField, IntegerField,
                     BooleanField, SelectField, SubmitField)
from wtforms.validators import (DataRequired, Optional, Email, regexp, Length,
                                URL, ValidationError)
from wtforms.ext.sqlalchemy.fields import (QuerySelectField,
                                           QuerySelectMultipleField)
from flask_babelex import lazy_gettext as _

from flaskbb.utils.fields import BirthdayField
from flaskbb.utils.widgets import SelectBirthdayWidget
from flaskbb.extensions import db
from flaskbb.forum.models import Forum, Category
from flaskbb.user.models import User, Group

USERNAME_RE = r'^[\w.+-]+$'
is_username = regexp(USERNAME_RE,
                     message=_("You can only use letters, numbers or dashes."))

def selectable_forums():
    return Forum.query.order_by(Forum.position)

def selectable_categories():
    return Category.query.order_by(Category.position)

def select_primary_group():
    return Group.query.filter(Group.guest != True).order_by(Group.id)

class UserForm(Form):
    username = StringField(_("Username"), validators=[
        DataRequired(message=_("A Username is required.")),
        is_username])

    email = StringField(_("E-Mail Address"), validators=[
        DataRequired(message=_("A E-Mail Address is required.")),
        Email(message=_("Invalid E-Mail Address."))])

    password = PasswordField("Password", validators=[
        Optional()])

    birthday = BirthdayField(_("Birthday"), format="%d %m %Y",
                             widget=SelectBirthdayWidget(),
                             validators=[Optional()])

    gender = SelectField(_("Gender"), default="None", choices=[
        ("None", ""),
        ("Male", _("Male")),
        ("Female", _("Female"))])

    location = StringField(_("Location"), validators=[
        Optional()])

    website = StringField(_("Website"), validators=[
        Optional(), URL()])

    avatar = StringField(_("Avatar"), validators=[
        Optional(), URL()])

    signature = TextAreaField(_("Forum Signature"), validators=[
        Optional(), Length(min=0, max=250)])

    notes = TextAreaField(_("Notes"), validators=[
        Optional(), Length(min=0, max=5000)])

    primary_group = QuerySelectField(
        _("Primary Group"),
        query_factory=select_primary_group,
        get_label="name")

    secondary_groups = QuerySelectMultipleField(
        _("Secondary Groups"),
        # TODO: Template rendering errors "NoneType is not callable"
        #       without this, figure out why.
        query_factory=select_primary_group,
        get_label="name")

    submit = SubmitField(_("Save"))

    def validate_username(self, field):
        if hasattr(self, "user"):
            user = User.query.filter(
                db.and_(
                    User.username.like(field.data),
                    db.not_(User.id == self.user.id)
                )
            ).first()
        else:
            user = User.query.filter(User.username.like(field.data)).first()

        if user:
            raise ValidationError(_("This Username is already taken."))

    def validate_email(self, field):
        if hasattr(self, "user"):
            user = User.query.filter(
                db.and_(
                    User.email.like(field.data),
                    db.not_(User.id == self.user.id)
                )
            ).first()
        else:
            user = User.query.filter(User.email.like(field.data)).first()

        if user:
            raise ValidationError(_("This E-Mail Address is already taken."))

    def save(self):
        user = User(**self.data)
        return user.save()

class AddUserForm(UserForm):
    pass

class EditUserForm(UserForm):
    def __init__(self, user, *args, **kwargs):
        self.user = user
        kwargs['obj'] = self.user
        super(UserForm, self).__init__(*args, **kwargs)

class GroupForm(Form):
    name = StringField(_("Group Name"), validators=[
        DataRequired(message=_("A Group name is required."))])

    description = TextAreaField(_("Description"), validators=[
        Optional()])

    admin = BooleanField(
        _("Is Admin Group?"),
        description=_("With this option the group has access to "
                      "the admin panel.")
    )
    super_mod = BooleanField(
        _("Is Super Moderator Group?"),
        description=_("Check this if the users in this group are allowed to "
                      "moderate every forum.")
    )
    mod = BooleanField(
        _("Is Moderator Group?"),
        description=_("Check this if the users in this group are allowed to "
                      "moderate specified forums.")
    )
    banned = BooleanField(
        _("Is Banned Group?"),
        description=_("Only one Banned group is allowed.")
    )
    guest = BooleanField(
        _("Is Guest Group?"),
        description=_("Only one Guest group is allowed.")
    )
    editpost = BooleanField(
        _("Can edit posts"),
        description=_("Check this if the users in this group can edit posts.")
    )
    deletepost = BooleanField(
        _("Can delete posts"),
        description=_("Check this is the users in this group can delete posts.")
    )
    deletetopic = BooleanField(
        _("Can delete topics"),
        description=_("Check this is the users in this group can delete "
                      "topics.")
    )
    posttopic = BooleanField(
        _("Can create topics"),
        description=_("Check this is the users in this group can create "
                      "topics.")
    )
    postreply = BooleanField(
        _("Can post replies"),
        description=_("Check this is the users in this group can post replies.")
    )

    mod_edituser = BooleanField(
        _("Moderators can edit user profiles"),
        description=_("Allow moderators to edit a another users profile "
                      "including password and email changes.")
    )

    mod_banuser = BooleanField(
        _("Moderators can ban users"),
        description=_("Allow moderators to ban other users.")
    )

    submit = SubmitField(_("Save"))

    def validate_name(self, field):
        if hasattr(self, "group"):
            group = Group.query.filter(
                db.and_(
                    Group.name.like(field.data),
                    db.not_(Group.id == self.group.id)
                )
            ).first()
        else:
            group = Group.query.filter(Group.name.like(field.data)).first()

        if group:
            raise ValidationError(_("This Group name is already taken."))

    def validate_banned(self, field):
        if hasattr(self, "group"):
            group = Group.query.filter(
                db.and_(
                    Group.banned,
                    db.not_(Group.id == self.group.id)
                )
            ).count()
        else:
            group = Group.query.filter_by(banned=True).count()

        if field.data and group > 0:
            raise ValidationError(_("There is already a Banned group."))

    def validate_guest(self, field):
        if hasattr(self, "group"):
            group = Group.query.filter(
                db.and_(
                    Group.guest,
                    db.not_(Group.id == self.group.id)
                )
            ).count()
        else:
            group = Group.query.filter_by(guest=True).count()

        if field.data and group > 0:
            raise ValidationError(_("There is already a Guest group."))

    def save(self):
        group = Group(**self.data)
        return group.save()

class EditGroupForm(GroupForm):
    def __init__(self, group, *args, **kwargs):
        self.group = group
        kwargs['obj'] = self.group
        super(GroupForm, self).__init__(*args, **kwargs)

class AddGroupForm(GroupForm):
    pass

class ForumForm(Form):
    title = StringField(
        _("Forum Title"),
        validators=[DataRequired(message=_("A Forum Title is required."))]
    )

    description = TextAreaField(
        _("Description"),
        validators=[Optional()],
        description=_("You can format your description with BBCode.")
    )

    position = IntegerField(
        _("Position"),
        default=1,
        validators=[DataRequired(message=_("The Forum Position is required."))]
    )

    category = QuerySelectField(
        _("Category"),
        query_factory=selectable_categories,
        allow_blank=False,
        get_label="title",
        description=_("The category that contains this forum.")
    )

    external = StringField(
        _("External Link"),
        validators=[Optional(), URL()],
        description=_("A link to a website i.e. 'http://flaskbb.org'.")
    )

    moderators = StringField(
        _("Moderators"),
        description=_("Comma seperated usernames. Leave it blank if you do not "
                      "want to set any moderators.")
    )

    show_moderators = BooleanField(
        _("Show Moderators"),
        description=_("Do you want show the moderators on the index page?")
    )

    locked = BooleanField(
        _("Locked?"),
        description=_("Disable new posts and topics in this forum.")
    )

    submit = SubmitField(_("Save"))

    def validate_external(self, field):
        if hasattr(self, "forum"):
            if self.forum.topics:
                raise ValidationError(_("You cannot convert a forum that "
                                        "contain topics in a external link."))

    def validate_show_moderators(self, field):
        if field.data and not self.moderators.data:
            raise ValidationError(_("You also need to specify some "
                                    "moderators."))

    def validate_moderators(self, field):
        approved_moderators = list()

        if field.data:
            # convert the CSV string in a list
            moderators = field.data.split(",")
            # remove leading and ending spaces
            moderators = [mod.strip() for mod in moderators]
            for moderator in moderators:
                # Check if the usernames exist
                user = User.query.filter_by(username=moderator).first()

                # Check if the user has the permissions to moderate a forum
                if user:
                    if not (user.get_permissions()["mod"] or
                            user.get_permissions()["admin"] or
                            user.get_permissions()["super_mod"]):
                        raise ValidationError(
                            _("%(user)s is not in a moderators group.",
                              user=user.username)
                        )
                    else:
                        approved_moderators.append(user)
                else:
                    raise ValidationError(_("User %(moderator)s not found.",
                                            moderator=moderator))
            field.data = approved_moderators

        else:
            field.data = approved_moderators

    def save(self):
        forum = Forum(title=self.title.data,
                      description=self.description.data,
                      position=self.position.data,
                      external=self.external.data,
                      show_moderators=self.show_moderators.data,
                      locked=self.locked.data)

        if self.moderators.data:
            # is already validated
            forum.moderators = self.moderators.data

        forum.category_id = self.category.data.id

        return forum.save()

class EditForumForm(ForumForm):
    def __init__(self, forum, *args, **kwargs):
        self.forum = forum
        kwargs['obj'] = self.forum
        super(ForumForm, self).__init__(*args, **kwargs)

class AddForumForm(ForumForm):
    pass

class CategoryForm(Form):
    title = StringField(_("Category Title"), validators=[
        DataRequired(message=_("A Category Title is required."))])

    description = TextAreaField(
        _("Description"),
        validators=[Optional()],
        description=_("You can format your description with BBCode.")
    )

    position = IntegerField(
        _("Position"),
        default=1,
        validators=[DataRequired(message=_("The Category Position is "
                                           "required."))]
    )

    submit = SubmitField(_("Save"))

    def save(self):
        category = Category(**self.data)
        return category.save()


text:
package schwift

// Version contains the version number of Schwift.
const Version = "1.0.0"


text:
@interface CCEffectNode : CCRenderTexture <CCEffectProtocol>

-(id)initWithWidth:(int)w height:(int)h;

@end
#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Lowering Co2 Emission and Making Concrete More Environmentally Friendly by Adding Limestone|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2014-10-15" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Lowering Co2 Emission and Making Concrete More Environmentally Friendly by Adding Limestone

    EPA Grant Number: SU835707

    Title: Lowering Co2 Emission and Making Concrete More Environmentally Friendly by Adding Limestone

    Investigators:
     Abdel-Mohti, Ahmed
        ,  Barnhart, James
        ,  Boulanger, Bryan

    Institution:

      Ohio Northern University

    	EPA Project Officer:

           Lank, Gregory

        Phase: I

      Project Period:
      August 15, 2014 through
        August 14, 2015

        Project Amount:

          $15,000

      RFA:
      P3 Awards: A National Student Design Competition for Sustainability Focusing on People, Prosperity and the Planet (2014)

        		RFA Text |
          Recipients Lists

      Research Category:

          Pollution Prevention/Sustainable Development
          ,
          P3 Challenge Area - Materials & Chemicals
          ,
          P3 Awards
          ,
          Sustainability

Description:

      	The goal of our proposal, "Lowering CO2 Emission and Making Concrete More Environmentally Friendly by Adding Limestone", is to produce a more sustainable concrete by engaging a team of undergraduate civil engineering students to address challenges associated with incorporating limestone in the concrete mixture and measuring the amount of CO2 emission.

Objective:

        The primary objective of this proposal is to test materials performance and carbonation capacity of Portland limestone concrete (PLC) mixtures. A successfully developed product will meet the existing technical specifications for material performance while demonstrating higher carbonation capacity (the ability of the concrete to sequester carbon dioxide). U.S. standards currently authorize the use of up to 5% limestone, but incorporating higher levels of limestone (potentially up to 35% limestone) will improve the environmental benefit. Limestone incorporation lowers the embodied CO2 within the production process, while increasing carbonation within the matrix. By one estimate replacing 25 to 35% of cement with limestone in the concrete mixture decreases thermal energy demand by 0.22 to 0.60 GJ/t-cement and reduces direct and indirect CO2 emission up to 140 t CO2/t-cement. However, the material performance at higher levels of limestone remains under-characterized.

Approach:

        Working within a team of students, an industry partner, and faculty with expertise in environmental analysis and structural concrete, team members will be involved in research designed to innovate, create, and evaluate a more sustainable concrete product. Team members will create concrete products that incorporate varying percentages of limestone. These sample products will be evaluated to determine whether or not a developed Portland Limestone Concrete meets existing criteria for concrete material design and has less impact on the environment by measuring carbonation.

Expected Results:

        The experimental results of this project will inform decision-making concerning the performance of PLC. Specifically, the project's expected results will determine the effect of adding more than 5% limestone on the performance of fresh and hardened concrete. Also, the impact of the produced concrete on the environment will be evaluated and compared to that of the conventional concrete through carbonation depth testing in a seal chamber environment. Phase I research will focus on evaluating the performance against the existing technical specifications and measuring carbonation depth against Portland cement concrete. In phase II, the optimal percentages of limestone incorporation will be tested. In addition, the durability of PLC samples will be evaluated and the embodied CO2 of PLC will be determined through life cycle analysis.

Supplemental Keywords:

      concrete, pavement, CO2 emission, sustainability, limestone

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Wednesday, October 15, 2014


text:
package main

type ShardLocation struct {
	Node  string
	Local bool
}

func newShardLocation(node string, local bool) *ShardLocation {
	return &ShardLocation{
		Node:  node,
		Local: local,
	}
}


text:
package de.slikey.game.event;

import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;

import de.slikey.game.Game;

public class GamePauseEvent extends GameEvent implements Cancellable {

	private static final HandlerList handlers = new HandlerList();
	private boolean cancelled = false;

	protected boolean paused;

	public GamePauseEvent(Game game, boolean paused) {
		super(game);
		paused = true;
	}

	public void setPaused(boolean paused) {
		this.paused = paused;
	}

	public boolean isPaused() {
		return paused;
	}

	@Override
	public HandlerList getHandlers() {
		return handlers;
	}

	public static HandlerList getHandlerList() {
		return handlers;
	}

	@Override
	public boolean isCancelled() {
		return cancelled;
	}

	@Override
	public void setCancelled(boolean cancelled) {
		this.cancelled = cancelled;
	}

}


text:
package edu.cmu.cs.stage3.alice.core.response.stack;

import edu.cmu.cs.stage3.alice.core.property.StackProperty;

public class StackResponse extends edu.cmu.cs.stage3.alice.core.Response {
	public final StackProperty stack = new StackProperty( this, "stack", null );
	public class RuntimeStackResponse extends RuntimeResponse {
        protected edu.cmu.cs.stage3.alice.core.Stack getStack() {
            return StackResponse.this.stack.getStackValue();
        }
	}
}


text:
<?php

/**
 * Resolves references (like short commit names, branch names, tag names, etc.)
 * into canonical, stable commit identifiers. This query works for all
 * repository types.
 */
final class DiffusionLowLevelResolveRefsQuery
  extends DiffusionLowLevelQuery {

  private $refs;

  public function withRefs(array $refs) {
    $this->refs = $refs;
    return $this;
  }

  public function executeQuery() {
    if (!$this->refs) {
      return array();
    }

    switch ($this->getRepository()->getVersionControlSystem()) {
      case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
        $result = $this->resolveGitRefs();
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
        $result = $this->resolveMercurialRefs();
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
        $result = $this->resolveSubversionRefs();
        break;
      default:
        throw new Exception('Unsupported repository type!');
    }

    return $result;
  }

  private function resolveGitRefs() {
    $repository = $this->getRepository();

    $future = $repository->getLocalCommandFuture('cat-file --batch-check');
    $future->write(implode("\n", $this->refs));
    list($stdout) = $future->resolvex();

    $lines = explode("\n", rtrim($stdout, "\n"));
    if (count($lines) !== count($this->refs)) {
      throw new Exception('Unexpected line count from `git cat-file`!');
    }

    $hits = array();
    $tags = array();

    $lines = array_combine($this->refs, $lines);
    foreach ($lines as $ref => $line) {
      $parts = explode(' ', $line);
      if (count($parts) < 2) {
        throw new Exception("Failed to parse `git cat-file` output: {$line}");
      }
      list($identifier, $type) = $parts;

      if ($type == 'missing') {
        // This is either an ambiguous reference which resolves to several
        // objects, or an invalid reference. For now, always treat it as
        // invalid. It would be nice to resolve all possibilities for
        // ambiguous references at some point, although the strategy for doing
        // so isn't clear to me.
        continue;
      }

      switch ($type) {
        case 'commit':
          break;
        case 'tag':
          $tags[] = $identifier;
          break;
        default:
          throw new Exception(
            "Unexpected object type from `git cat-file`: {$line}");
      }

      $hits[] = array(
        'ref' => $ref,
        'type' => $type,
        'identifier' => $identifier,
      );
    }

    $tag_map = array();
    if ($tags) {
      // If some of the refs were tags, just load every tag in order to figure
      // out which commits they map to. This might be somewhat inefficient in
      // repositories with a huge number of tags.
      $tag_refs = id(new DiffusionLowLevelGitRefQuery())
        ->setRepository($repository)
        ->withIsTag(true)
        ->executeQuery();
      foreach ($tag_refs as $tag_ref) {
        $tag_map[$tag_ref->getShortName()] = $tag_ref->getCommitIdentifier();
      }
    }

    $results = array();
    foreach ($hits as $hit) {
      $type = $hit['type'];
      $ref = $hit['ref'];

      $alternate = null;
      if ($type == 'tag') {
        $alternate = $identifier;
        $identifier = idx($tag_map, $ref);
        if (!$identifier) {
          throw new Exception("Failed to look up tag '{$ref}'!");
        }
      }

      $result = array(
        'type' => $type,
        'identifier' => $identifier,
      );

      if ($alternate !== null) {
        $result['alternate'] = $alternate;
      }

      $results[$ref][] = $result;
    }

    return $results;
  }

  private function resolveMercurialRefs() {
    $repository = $this->getRepository();

    $futures = array();
    foreach ($this->refs as $ref) {
      $futures[$ref] = $repository->getLocalCommandFuture(
        'log --template=%s --rev %s',
        '{node}',
        hgsprintf('%s', $ref));
    }

    $results = array();
    foreach (Futures($futures) as $ref => $future) {
      try {
        list($stdout) = $future->resolvex();
      } catch (CommandException $ex) {
        if (preg_match('/ambiguous identifier/', $ex->getStdErr())) {
          // This indicates that the ref ambiguously matched several things.
          // Eventually, it would be nice to return all of them, but it is
          // unclear how to best do that. For now, treat it as a miss instead.
          continue;
        }
        throw $ex;
      }

      // It doesn't look like we can figure out the type (commit/branch/rev)
      // from this output very easily. For now, just call everything a commit.
      $type = 'commit';

      $results[$ref][] = array(
        'type' => $type,
        'identifier' => trim($stdout),
      );
    }

    return $results;
  }

  private function resolveSubversionRefs() {
    $repository = $this->getRepository();

    $max_commit = id(new PhabricatorRepositoryCommit())
      ->loadOneWhere(
        'repositoryID = %d ORDER BY epoch DESC, id DESC LIMIT 1',
        $repository->getID());
    if (!$max_commit) {
      // This repository is empty or hasn't parsed yet, so none of the refs are
      // going to resolve.
      return array();
    }

    $max_commit_id = (int)$max_commit->getCommitIdentifier();

    $results = array();
    foreach ($this->refs as $ref) {
      if ($ref == 'HEAD') {
        // Resolve "HEAD" to mean "the most recent commit".
        $results[$ref][] = array(
          'type' => 'commit',
          'identifier' => $max_commit_id,
        );
        continue;
      }

      if (!preg_match('/^\d+$/', $ref)) {
        // This ref is non-numeric, so it doesn't resolve to anything.
        continue;
      }

      // Resolve other commits if we can deduce their existence.

      // TODO: When we import only part of a repository, we won't necessarily
      // have all of the smaller commits. Should we fail to resolve them here
      // for repositories with a subpath? It might let us simplify other things
      // elsewhere.
      if ((int)$ref <= $max_commit_id) {
        $results[$ref][] = array(
          'type' => 'commit',
          'identifier' => (int)$ref,
        );
      }
    }

    return $results;
  }

}


text:
QAmqpClientPrivate::QAmqpClientPrivate(QAmqpClient *q)
    : port(AMQP_PORT),
      host(AMQP_HOST),
      virtualHost(AMQP_VHOST),
      autoReconnect(false),
      timeout(0),
      connecting(false),
      useSsl(false),
      socket(0),
      closed(false),
      connected(false),
      channelMax(0),
      heartbeatDelay(0),
      frameMax(AMQP_FRAME_MAX),
      error(QAMQP::NoError),
      q_ptr(q)
{
}

QAmqpClientPrivate::~QAmqpClientPrivate()
{
}

void QAmqpClientPrivate::init()
{
    Q_Q(QAmqpClient);
    initSocket();
    heartbeatTimer = new QTimer(q);
    QObject::connect(heartbeatTimer, SIGNAL(timeout()), q, SLOT(_q_heartbeat()));

    authenticator = QSharedPointer<QAmqpAuthenticator>(
        new QAmqpPlainAuthenticator(QString::fromLatin1(AMQP_LOGIN), QString::fromLatin1(AMQP_PSWD)));
}

void QAmqpClientPrivate::initSocket()
{
    Q_Q(QAmqpClient);
    socket = new QSslSocket(q);
    QObject::connect(socket, SIGNAL(connected()), q, SLOT(_q_socketConnected()));
    QObject::connect(socket, SIGNAL(disconnected()), q, SLOT(_q_socketDisconnected()));
    QObject::connect(socket, SIGNAL(readyRead()), q, SLOT(_q_readyRead()));
    QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                          q, SLOT(_q_socketError(QAbstractSocket::SocketError)));
    QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                          q, SIGNAL(socketError(QAbstractSocket::SocketError)));
    QObject::connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
                          q, SIGNAL(sslErrors(QList<QSslError>)));
}

void QAmqpClientPrivate::setUsername(const QString &username)
{
    QAmqpAuthenticator *auth = authenticator.data();
    if (auth && auth->type() == QLatin1String("AMQPLAIN")) {
        QAmqpPlainAuthenticator *a = static_cast<QAmqpPlainAuthenticator*>(auth);
        a->setLogin(username);
    }
}

void QAmqpClientPrivate::setPassword(const QString &password)
{
    QAmqpAuthenticator *auth = authenticator.data();
    if (auth && auth->type() == QLatin1String("AMQPLAIN")) {
        QAmqpPlainAuthenticator *a = static_cast<QAmqpPlainAuthenticator*>(auth);
        a->setPassword(password);
    }
}

void QAmqpClientPrivate::parseConnectionString(const QString &uri)
{
#if QT_VERSION > 0x040801
    QUrl connectionString = QUrl::fromUserInput(uri);
#else
    QUrl connectionString(uri, QUrl::TolerantMode);
#endif

    if (connectionString.scheme() != AMQP_SCHEME &&
        connectionString.scheme() != AMQP_SSL_SCHEME) {
        qAmqpDebug() << Q_FUNC_INFO << "invalid scheme: " << connectionString.scheme();
        return;
    }

    useSsl = (connectionString.scheme() == AMQP_SSL_SCHEME);
    port = connectionString.port((useSsl ? AMQP_SSL_PORT : AMQP_PORT));
    host = connectionString.host();

    QString vhost = connectionString.path();
    if (vhost.startsWith("/") && vhost.size() > 1)
        vhost = vhost.mid(1);
#if QT_VERSION <= 0x050200
    virtualHost = QUrl::fromPercentEncoding(vhost.toUtf8());
    setPassword(QUrl::fromPercentEncoding(connectionString.password().toUtf8()));
    setUsername(QUrl::fromPercentEncoding(connectionString.userName().toUtf8()));
#else
    virtualHost = vhost;
    setPassword(connectionString.password());
    setUsername(connectionString.userName());
#endif
}

void QAmqpClientPrivate::_q_connect()
{
    if (socket->state() != QAbstractSocket::UnconnectedState) {
        qAmqpDebug() << Q_FUNC_INFO << "socket already connected, disconnecting..";
        _q_disconnect();
    }

    qAmqpDebug() << "connecting to host: " << host << ", port: " << port;
    if (useSsl)
        socket->connectToHostEncrypted(host, port);
    else
        socket->connectToHost(host, port);
}

void QAmqpClientPrivate::_q_disconnect()
{
    if (socket->state() == QAbstractSocket::UnconnectedState) {
        qAmqpDebug() << Q_FUNC_INFO << "already disconnected";
        return;
    }

    buffer.clear();
    close(200, "client disconnect");
}

// private slots
void QAmqpClientPrivate::_q_socketConnected()
{
    timeout = 0;
    char header[8] = {'A', 'M', 'Q', 'P', 0, 0, 9, 1};
    socket->write(header, 8);
}

void QAmqpClientPrivate::_q_socketDisconnected()
{
    Q_Q(QAmqpClient);
    buffer.clear();
    if (connected) {
        connected = false;
        Q_EMIT q->disconnected();
    }
}

void QAmqpClientPrivate::_q_heartbeat()
{
    QAmqpHeartbeatFrame frame;
    sendFrame(frame);
}

void QAmqpClientPrivate::_q_socketError(QAbstractSocket::SocketError error)
{
    Q_Q(QAmqpClient);
    if (timeout <= 0) {
        timeout = 1000;
    } else {
        if (timeout < 120000)
            timeout *= 5;
    }

    switch (error) {
    case QAbstractSocket::ConnectionRefusedError:
    case QAbstractSocket::RemoteHostClosedError:
    case QAbstractSocket::SocketTimeoutError:
    case QAbstractSocket::NetworkError:
    case QAbstractSocket::ProxyConnectionClosedError:
    case QAbstractSocket::ProxyConnectionRefusedError:
    case QAbstractSocket::ProxyConnectionTimeoutError:

    default:
        qAmqpDebug() << "socket error: " << socket->errorString();
        break;
    }

    // per spec, on any error we need to close the socket immediately
    // and send no more data;
    socket->close();
    errorString = socket->errorString();

    if (autoReconnect) {
        qAmqpDebug() << "trying to reconnect after: " << timeout << "ms";
        QTimer::singleShot(timeout, q, SLOT(_q_connect()));
    }
}

void QAmqpClientPrivate::_q_readyRead()
{
    while (socket->bytesAvailable() >= QAmqpFrame::HEADER_SIZE) {
        unsigned char headerData[QAmqpFrame::HEADER_SIZE];
        socket->peek((char*)headerData, QAmqpFrame::HEADER_SIZE);
        const quint32 payloadSize = qFromBigEndian<quint32>(headerData + 3);
        const qint64 readSize = QAmqpFrame::HEADER_SIZE + payloadSize + QAmqpFrame::FRAME_END_SIZE;

        if (socket->bytesAvailable() < readSize)
            return;

        buffer.resize(readSize);
        socket->read(buffer.data(), readSize);
        const char *bufferData = buffer.constData();
        const quint8 type = *(quint8*)&bufferData[0];
        const quint8 magic = *(quint8*)&bufferData[QAmqpFrame::HEADER_SIZE + payloadSize];
        if (Q_UNLIKELY(magic != QAmqpFrame::FRAME_END)) {
            close(QAMQP::UnexpectedFrameError, "wrong end of frame");
            return;
        }

        QDataStream streamB(&buffer, QIODevice::ReadOnly);
        switch (static_cast<QAmqpFrame::FrameType>(type)) {
        case QAmqpFrame::Method:
        {
            QAmqpMethodFrame frame;
            streamB >> frame;

            if (Q_UNLIKELY(frame.size() > frameMax)) {
                close(QAMQP::FrameError, "frame size too large");
                return;
            }

            if (frame.methodClass() == QAmqpFrame::Connection) {
                _q_method(frame);
            } else {
                foreach (QAmqpMethodFrameHandler *methodHandler, methodHandlersByChannel[frame.channel()])
                    methodHandler->_q_method(frame);
            }
        }
            break;
        case QAmqpFrame::Header:
        {
            QAmqpContentFrame frame;
            streamB >> frame;

            if (Q_UNLIKELY(frame.size() > frameMax)) {
                close(QAMQP::FrameError, "frame size too large");
                return;
            } else if (Q_UNLIKELY(frame.channel() <= 0)) {
                close(QAMQP::ChannelError, "channel number must be greater than zero");
                return;
            }

            foreach (QAmqpContentFrameHandler *methodHandler, contentHandlerByChannel[frame.channel()])
                methodHandler->_q_content(frame);
        }
            break;
        case QAmqpFrame::Body:
        {
            QAmqpContentBodyFrame frame;
            streamB >> frame;

            if (Q_UNLIKELY(frame.size() > frameMax)) {
                close(QAMQP::FrameError, "frame size too large");
                return;
            } else if (Q_UNLIKELY(frame.channel() <= 0)) {
                close(QAMQP::ChannelError, "channel number must be greater than zero");
                return;
            }

            foreach (QAmqpContentBodyFrameHandler *methodHandler, bodyHandlersByChannel[frame.channel()])
                methodHandler->_q_body(frame);
        }
            break;
        case QAmqpFrame::Heartbeat:
        {
            QAmqpMethodFrame frame;
            streamB >> frame;

            if (Q_UNLIKELY(frame.channel() != 0)) {
                close(QAMQP::FrameError, "heartbeat must have channel id zero");
                return;
            }

            qAmqpDebug("AMQP: Heartbeat");
        }
            break;
        default:
            qAmqpDebug() << "AMQP: Unknown frame type: " << type;
            close(QAMQP::FrameError, "invalid frame type");
            return;
        }
    }
}

void QAmqpClientPrivate::sendFrame(const QAmqpFrame &frame)
{
    if (socket->state() != QAbstractSocket::ConnectedState) {
        qAmqpDebug() << Q_FUNC_INFO << "socket not connected: " << socket->state();
        return;
    }

    QDataStream stream(socket);
    stream << frame;
}

bool QAmqpClientPrivate::_q_method(const QAmqpMethodFrame &frame)
{
    Q_ASSERT(frame.methodClass() == QAmqpFrame::Connection);
    if (frame.methodClass() != QAmqpFrame::Connection)
        return false;

    qAmqpDebug() << "Connection:";
    if (closed) {
        if (frame.id() == QAmqpClientPrivate::miCloseOk)
            closeOk(frame);
        return false;
    }

    switch (QAmqpClientPrivate::MethodId(frame.id())) {
    case QAmqpClientPrivate::miStart:
        start(frame);
        break;
    case QAmqpClientPrivate::miSecure:
        secure(frame);
        break;
    case QAmqpClientPrivate::miTune:
        tune(frame);
        break;
    case QAmqpClientPrivate::miOpenOk:
        openOk(frame);
        break;
    case QAmqpClientPrivate::miClose:
        close(frame);
        break;
    case QAmqpClientPrivate::miCloseOk:
        closeOk(frame);
        break;
    default:
        qAmqpDebug("Unknown method-id %d", frame.id());
    }

    return true;
}

void QAmqpClientPrivate::start(const QAmqpMethodFrame &frame)
{
    Q_Q(QAmqpClient);
    qAmqpDebug(">> Start");
    QByteArray data = frame.arguments();
    QDataStream stream(&data, QIODevice::ReadOnly);

    quint8 version_major = 0;
    quint8 version_minor = 0;
    stream >> version_major >> version_minor;

    QAmqpTable table;
    stream >> table;

    QStringList mechanisms =
        QAmqpFrame::readAmqpField(stream, QAmqpMetaType::LongString).toString().split(' ');
    QString locales = QAmqpFrame::readAmqpField(stream, QAmqpMetaType::LongString).toString();

    qAmqpDebug(">> version_major: %d", version_major);
    qAmqpDebug(">> version_minor: %d", version_minor);

    // NOTE: replace with qDebug overload
    // QAmqpFrame::print(table);

    qAmqpDebug() << ">> mechanisms: " << mechanisms;
    qAmqpDebug(">> locales: %s", qPrintable(locales));

    if (!mechanisms.contains(authenticator->type())) {
        socket->disconnectFromHost();
        Q_EMIT q->disconnected();
        return;
    }

    startOk();
}

void QAmqpClientPrivate::secure(const QAmqpMethodFrame &frame)
{
    Q_UNUSED(frame)
    qAmqpDebug() << Q_FUNC_INFO << "called!";
}

void QAmqpClientPrivate::tune(const QAmqpMethodFrame &frame)
{
    qAmqpDebug(">> Tune");
    QByteArray data = frame.arguments();
    QDataStream stream(&data, QIODevice::ReadOnly);

    qint16 channel_max = 0,
           heartbeat_delay = 0;
    qint32 frame_max = 0;

    stream >> channel_max;
    stream >> frame_max;
    stream >> heartbeat_delay;

    if (!frameMax)
        frameMax = frame_max;
    channelMax = !channelMax ? channel_max : qMax(channel_max, channelMax);
    heartbeatDelay = !heartbeatDelay ? heartbeat_delay: qMax(heartbeat_delay, heartbeatDelay);

    qAmqpDebug(">> channel_max: %d", channelMax);
    qAmqpDebug(">> frame_max: %d", frameMax);
    qAmqpDebug(">> heartbeat: %d", heartbeatDelay);

    if (heartbeatTimer) {
        heartbeatTimer->setInterval(heartbeatDelay * 1000);
        if (heartbeatTimer->interval())
            heartbeatTimer->start();
        else
            heartbeatTimer->stop();
    }

    tuneOk();
    open();
}

void QAmqpClientPrivate::openOk(const QAmqpMethodFrame &frame)
{
    Q_Q(QAmqpClient);
    Q_UNUSED(frame)
    qAmqpDebug(">> OpenOK");
    connected = true;
    Q_EMIT q->connected();
}

void QAmqpClientPrivate::closeOk(const QAmqpMethodFrame &frame)
{
    Q_Q(QAmqpClient);
    Q_UNUSED(frame)
    qAmqpDebug() << Q_FUNC_INFO << "received";
    connected = false;
    if (heartbeatTimer)
        heartbeatTimer->stop();
    socket->disconnectFromHost();
    Q_EMIT q->disconnected();
}

void QAmqpClientPrivate::close(const QAmqpMethodFrame &frame)
{
    Q_Q(QAmqpClient);
    qAmqpDebug(">> CLOSE");
    QByteArray data = frame.arguments();
    QDataStream stream(&data, QIODevice::ReadOnly);
    qint16 code = 0, classId, methodId;
    stream >> code;
    QString text = QAmqpFrame::readAmqpField(stream, QAmqpMetaType::ShortString).toString();
    stream >> classId;
    stream >> methodId;

    QAMQP::Error checkError = static_cast<QAMQP::Error>(code);
    if (checkError != QAMQP::NoError) {
        error = checkError;
        errorString = qPrintable(text);
        Q_EMIT q->error(error);
    }

    qAmqpDebug(">> code: %d", code);
    qAmqpDebug(">> text: %s", qPrintable(text));
    qAmqpDebug(">> class-id: %d", classId);
    qAmqpDebug(">> method-id: %d", methodId);
    connected = false;
    Q_EMIT q->disconnected();

    // complete handshake
    QAmqpMethodFrame closeOkFrame(QAmqpFrame::Connection, QAmqpClientPrivate::miCloseOk);
    sendFrame(closeOkFrame);
}

void QAmqpClientPrivate::startOk()
{
    QAmqpMethodFrame frame(QAmqpFrame::Connection, QAmqpClientPrivate::miStartOk);
    QByteArray arguments;
    QDataStream stream(&arguments, QIODevice::WriteOnly);

    QAmqpTable clientProperties;
    clientProperties["version"] = QString(QAMQP_VERSION);
    clientProperties["platform"] = QString("Qt %1").arg(qVersion());
    clientProperties["product"] = QString("QAMQP");
    clientProperties.unite(customProperties);
    stream << clientProperties;

    authenticator->write(stream);
    QAmqpFrame::writeAmqpField(stream, QAmqpMetaType::ShortString, QLatin1String("en_US"));

    frame.setArguments(arguments);
    sendFrame(frame);
}

void QAmqpClientPrivate::secureOk()
{
    qAmqpDebug() << Q_FUNC_INFO;
}

void QAmqpClientPrivate::tuneOk()
{
    QAmqpMethodFrame frame(QAmqpFrame::Connection, QAmqpClientPrivate::miTuneOk);
    QByteArray arguments;
    QDataStream stream(&arguments, QIODevice::WriteOnly);

    stream << qint16(channelMax);
    stream << qint32(frameMax);
    stream << qint16(heartbeatDelay);

    frame.setArguments(arguments);
    sendFrame(frame);
}

void QAmqpClientPrivate::open()
{
    QAmqpMethodFrame frame(QAmqpFrame::Connection, QAmqpClientPrivate::miOpen);
    QByteArray arguments;
    QDataStream stream(&arguments, QIODevice::WriteOnly);

    QAmqpFrame::writeAmqpField(stream, QAmqpMetaType::ShortString, virtualHost);

    stream << qint8(0);
    stream << qint8(0);

    frame.setArguments(arguments);
    sendFrame(frame);
}

void QAmqpClientPrivate::close(int code, const QString &text, int classId, int methodId)
{
    QByteArray arguments;
    QDataStream stream(&arguments, QIODevice::WriteOnly);
    stream << qint16(code);
    QAmqpFrame::writeAmqpField(stream, QAmqpMetaType::ShortString, text);
    stream << qint16(classId);
    stream << qint16(methodId);

    QAmqpMethodFrame frame(QAmqpFrame::Connection, QAmqpClientPrivate::miClose);
    frame.setArguments(arguments);
    sendFrame(frame);
}

//////////////////////////////////////////////////////////////////////////

QAmqpClient::QAmqpClient(QObject *parent)
    : QObject(parent),
      d_ptr(new QAmqpClientPrivate(this))
{
    Q_D(QAmqpClient);
    d->init();
}

QAmqpClient::QAmqpClient(QAmqpClientPrivate *dd, QObject *parent)
    : QObject(parent),
      d_ptr(dd)
{
}

QAmqpClient::~QAmqpClient()
{
    Q_D(QAmqpClient);
    if (d->connected)
        d->_q_disconnect();
}

bool QAmqpClient::isConnected() const
{
    Q_D(const QAmqpClient);
    return d->connected;
}

quint16 QAmqpClient::port() const
{
    Q_D(const QAmqpClient);
    return d->port;
}

void QAmqpClient::setPort(quint16 port)
{
    Q_D(QAmqpClient);
    d->port = port;
}

QString QAmqpClient::host() const
{
    Q_D(const QAmqpClient);
    return d->host;
}

void QAmqpClient::setHost(const QString &host)
{
    Q_D(QAmqpClient);
    d->host = host;
}

QString QAmqpClient::virtualHost() const
{
    Q_D(const QAmqpClient);
    return d->virtualHost;
}

void QAmqpClient::setVirtualHost(const QString &virtualHost)
{
    Q_D(QAmqpClient);
    d->virtualHost = virtualHost;
}

QString QAmqpClient::username() const
{
    Q_D(const QAmqpClient);
    const QAmqpAuthenticator *auth = d->authenticator.data();
    if (auth && auth->type() == QLatin1String("AMQPLAIN")) {
        const QAmqpPlainAuthenticator *a = static_cast<const QAmqpPlainAuthenticator*>(auth);
        return a->login();
    }

    return QString();
}

void QAmqpClient::setUsername(const QString &username)
{
    Q_D(QAmqpClient);
    d->setUsername(username);
}

QString QAmqpClient::password() const
{
    Q_D(const QAmqpClient);
    const QAmqpAuthenticator *auth = d->authenticator.data();
    if (auth && auth->type() == QLatin1String("AMQPLAIN")) {
        const QAmqpPlainAuthenticator *a = static_cast<const QAmqpPlainAuthenticator*>(auth);
        return a->password();
    }

    return QString();
}

void QAmqpClient::setPassword(const QString &password)
{
    Q_D(QAmqpClient);
    d->setPassword(password);
}

//ivan: QAmqpExchange *QAmqpClient::createExchange(int channelNumber)
QObject *QAmqpClient::createExchange(int channelNumber)
{
    return createExchange(QString(), channelNumber);
}

//ivan: QAmqpExchange *QAmqpClient::createExchange(const QString &name, int channelNumber)
QObject *QAmqpClient::createExchange(const QString &name, int channelNumber)
{
    Q_D(QAmqpClient);
    QAmqpExchange *exchange = new QAmqpExchange(channelNumber, this);
    d->methodHandlersByChannel[exchange->channelNumber()].append(exchange->d_func());
    connect(this, SIGNAL(connected()), exchange, SLOT(_q_open()));
    connect(this, SIGNAL(disconnected()), exchange, SLOT(_q_disconnected()));
    exchange->d_func()->open();

    if (!name.isEmpty())
        exchange->setName(name);
    return exchange;
}

//ivan: QAmqpQueue *QAmqpClient::createQueue(int channelNumber)
QObject *QAmqpClient::createQueue(int channelNumber)
{
    return createQueue(QString(), channelNumber);
}

//ivan: QAmqpQueue *QAmqpClient::createQueue(const QString &name, int channelNumber)
QObject *QAmqpClient::createQueue(const QString &name, int channelNumber)
{
    Q_D(QAmqpClient);
    QAmqpQueue *queue = new QAmqpQueue(channelNumber, this);
    d->methodHandlersByChannel[queue->channelNumber()].append(queue->d_func());
    d->contentHandlerByChannel[queue->channelNumber()].append(queue->d_func());
    d->bodyHandlersByChannel[queue->channelNumber()].append(queue->d_func());
    connect(this, SIGNAL(connected()), queue, SLOT(_q_open()));
    connect(this, SIGNAL(disconnected()), queue, SLOT(_q_disconnected()));
    queue->d_func()->open();

    if (!name.isEmpty())
        queue->setName(name);
    return queue;
}

void QAmqpClient::setAuth(QAmqpAuthenticator *authenticator)
{
    Q_D(QAmqpClient);
    d->authenticator = QSharedPointer<QAmqpAuthenticator>(authenticator);
}

QAmqpAuthenticator *QAmqpClient::auth() const
{
    Q_D(const QAmqpClient);
    return d->authenticator.data();
}

bool QAmqpClient::autoReconnect() const
{
    Q_D(const QAmqpClient);
    return d->autoReconnect;
}

void QAmqpClient::setAutoReconnect(bool value)
{
    Q_D(QAmqpClient);
    d->autoReconnect = value;
}

qint16 QAmqpClient::channelMax() const
{
    Q_D(const QAmqpClient);
    return d->channelMax;
}

void QAmqpClient::setChannelMax(qint16 channelMax)
{
    Q_D(QAmqpClient);
    if (d->connected) {
        qAmqpDebug() << Q_FUNC_INFO << "can't modify value while connected";
        return;
    }

    d->channelMax = channelMax;
}

qint32 QAmqpClient::frameMax() const
{
    Q_D(const QAmqpClient);
    return d->frameMax;
}

void QAmqpClient::setFrameMax(qint32 frameMax)
{
    Q_D(QAmqpClient);
    if (d->connected) {
        qAmqpDebug() << Q_FUNC_INFO << "can't modify value while connected";
        return;
    }

    d->frameMax = qMax(frameMax, AMQP_FRAME_MIN_SIZE);
}

qint16 QAmqpClient::heartbeatDelay() const
{
    Q_D(const QAmqpClient);
    return d->heartbeatDelay;
}

void QAmqpClient::setHeartbeatDelay(qint16 delay)
{
    Q_D(QAmqpClient);
    if (d->connected) {
        qAmqpDebug() << Q_FUNC_INFO << "can't modify value while connected";
        return;
    }

    d->heartbeatDelay = delay;
}

void QAmqpClient::addCustomProperty(const QString &name, const QString &value)
{
    Q_D(QAmqpClient);
    d->customProperties.insert(name, value);
}

QString QAmqpClient::customProperty(const QString &name) const
{
    Q_D(const QAmqpClient);
    return d->customProperties.value(name).toString();
}

QAbstractSocket::SocketError QAmqpClient::socketError() const
{
    Q_D(const QAmqpClient);
    return d->socket->error();
}

// ivan: add :
QString QAmqpClient::socketErrorString() const
{
    Q_D(const QAmqpClient);
    switch (d->socket->error()) {
        case QAbstractSocket::ConnectionRefusedError: return QString("ConnectionRefusedError : The connection was refused by the peer (or timed out).");
        case QAbstractSocket::RemoteHostClosedError: return QString("RemoteHostClosedError : The remote host closed the connection.");
        case QAbstractSocket::HostNotFoundError: return QString("HostNotFoundError : The host address was not found.");
        case QAbstractSocket::SocketAccessError: return QString("SocketAccessError : The socket operation failed because the application lacked the required privileges.");
        case QAbstractSocket::SocketResourceError: return QString("SocketResourceError : The local system ran out of resources (e.g., too many sockets).");
        case QAbstractSocket::SocketTimeoutError: return QString("SocketTimeoutError : The socket operation timed out.");
        case QAbstractSocket::DatagramTooLargeError: return QString("DatagramTooLargeError : The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).");
        case QAbstractSocket::NetworkError: return QString("NetworkError : An error occurred with the network (e.g., the network cable was accidentally plugged out).");
        case QAbstractSocket::AddressInUseError: return QString("AddressInUseError : The address specified to QUdpSocket::bind() is already in use and was set to be exclusive.");
        case QAbstractSocket::SocketAddressNotAvailableError: return QString("SocketAddressNotAvailableError : The address specified to QUdpSocket::bind() does not belong to the host.");
        case QAbstractSocket::UnsupportedSocketOperationError: return QString("UnsupportedSocketOperationError : The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).");
        case QAbstractSocket::ProxyAuthenticationRequiredError: return QString("ProxyAuthenticationRequiredError : The socket is using a proxy, and the proxy requires authentication.");
        case QAbstractSocket::SslHandshakeFailedError: return QString("SslHandshakeFailedError : The SSL/TLS handshake failed, so the connection was closed.");
        case QAbstractSocket::UnfinishedSocketOperationError: return QString("UnfinishedSocketOperationError : Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).");
        case QAbstractSocket::ProxyConnectionRefusedError: return QString("ProxyConnectionRefusedError : Could not contact the proxy server because the connection to that server was denied");
        case QAbstractSocket::ProxyConnectionClosedError: return QString("ProxyConnectionClosedError : The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)");
        case QAbstractSocket::ProxyConnectionTimeoutError: return QString("ProxyConnectionTimeoutError : The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.");
        case QAbstractSocket::ProxyNotFoundError: return QString("ProxyNotFoundError : The proxy address set with setProxy() (or the application proxy) was not found.");
        case QAbstractSocket::ProxyProtocolError: return QString("ProxyProtocolError : The connection negotiation with the proxy server because the response from the proxy server could not be understood.");
        case QAbstractSocket::UnknownSocketError: return QString("UnknownSocketError : An unidentified error occurred.");
        default: return QString("");
    }
}

QAMQP::Error QAmqpClient::error() const
{
    Q_D(const QAmqpClient);
    return d->error;
}

QString QAmqpClient::errorString() const
{
    Q_D(const QAmqpClient);
    return d->errorString;
}

QSslConfiguration QAmqpClient::sslConfiguration() const
{
    Q_D(const QAmqpClient);
    return d->socket->sslConfiguration();
}

void QAmqpClient::setSslConfiguration(const QSslConfiguration &config)
{
    Q_D(QAmqpClient);
    if (!config.isNull()) {
        d->useSsl = true;
        d->port = AMQP_SSL_PORT;
        d->socket->setSslConfiguration(config);
    }
}

void QAmqpClient::ignoreSslErrors(const QList<QSslError> &errors)
{
    Q_D(QAmqpClient);
    d->socket->ignoreSslErrors(errors);
}

void QAmqpClient::connectToHost(const QString &uri)
{
    Q_D(QAmqpClient);
    if (uri.isEmpty()) {
        d->_q_connect();
        return;
    }

    d->parseConnectionString(uri);
    d->_q_connect();
}

void QAmqpClient::connectToHost(const QHostAddress &address, quint16 port)
{
    Q_D(QAmqpClient);
    d->host = address.toString();
    d->port = port;
    d->_q_connect();
}

void QAmqpClient::disconnectFromHost()
{
    Q_D(QAmqpClient);
    d->_q_disconnect();
}

#include "moc_qamqpclient.cpp"


text:
import jobConfigLanguage from 'travis/utils/job-config-language';

import { module, test } from 'qunit';

module('jobConfigLanguage', function () {
  test('an empty config returns an empty string', (assert) => {
    assert.equal(jobConfigLanguage({}), '', 'expected an empty config to return an empty string');
  });

  test('a job with an RVM value returns Ruby with its version', (assert) => {
    assert.equal(jobConfigLanguage({ rvm: '2.2' }), 'Ruby: 2.2');
  });

  test('a Ruby job with no RVM value returns Ruby alone', (assert) => {
    assert.equal(jobConfigLanguage({ language: 'ruby' }), 'Ruby');
  });

  test('a job with two language-related keys returns both languages', (assert) => {
    assert.equal(jobConfigLanguage({ rvm: '2.1', node_js: '5.3' }), 'Node.js: 5.3 Ruby: 2.1');
  });

  test('a job with a Gemfile and an env shows the Gemfile', (assert) => {
    assert.equal(jobConfigLanguage({ gemfile: 'Hellofile', env: 'yes' }), 'Gemfile: Hellofile');
  });

  test('the Gemfile is shown after the languages', (assert) => {
    assert.equal(jobConfigLanguage({ gemfile: 'Hellofile', env: 'yes', node_js: '6.0' }), 'Node.js: 6.0 Gemfile: Hellofile');
  });

  test('a job with a Gemfile without an env does not show the Gemfile', (assert) => {
    assert.equal(jobConfigLanguage({ gemfile: 'Nofile' }), '', 'expected a Gemfile-only config to return an empty string');
  });

  test('a job with an Android components array shows no version', (assert) => {
    assert.equal(jobConfigLanguage({ android: { components: ['dumont', 'riel'] } }), 'Android');
  });

  test('a job with Android components and Android language only has Android once', (assert) => {
    assert.equal(jobConfigLanguage({ language: 'android', android: { components: ['dumont', 'riel'] } }), 'Android');
  });

  test('an incorrectly-structured config doesn't print [object Object]', assert => {
    assert.equal(jobConfigLanguage({ osx_image: { osx_image: 'xcode10' }}), 'Xcode');
  });
});


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class UsersTableRenameGroupColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table) {
            $table->renameColumn('group', 'group_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function($table) {
            $table->renameColumn('group_id', 'group');
        });
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanora badia f. pallescens Zahlbr.

### Remarks
null


text:
<?php

namespace AerialShip\SamlSPBundle\State\Request;

use Symfony\Component\HttpFoundation\Session\SessionInterface;

class SessionStore implements RequestStateStoreInterface
{
    /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface  */
    protected $session;

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

    /**
     * @param SessionInterface $session
     * @param string $providerID
     */
    function __construct(SessionInterface $session, $providerID) {
        $this->session = $session;
        $this->providerID = $providerID;
    }

    /**
     * @param RequestState $state
     * @throws \InvalidArgumentException
     * @return void
     */
    function set(RequestState $state) {
        $key = "saml_state_{$this->providerID}";
        $arr = $this->session->get($key, array());
        $arr[$state->getId()] = $state;
        $this->session->set($key, $arr);
    }

    /**
     * @param string $id
     * @return RequestState|null
     */
    function get($id) {
        $result = null;
        $key = "saml_state_{$this->providerID}";
        $arr = $this->session->get($key);
        if (!is_array($arr)) {
            $arr = array();
            $this->session->set($key, $arr);
        }
        if (isset($arr[$id])) {
            $result = $arr[$id];
        }
        if ($result instanceof RequestState) {
            return $result;
        }
        return null;
    }

    /**
     * @param RequestState $state
     * @return bool
     */
    public function remove(RequestState $state)
    {
        $key = "saml_state_{$this->providerID}";
        $arr = $this->session->get($key, array());
        $result = isset($arr[$state->getId()]);
        unset($arr[$state->getId()]);
        $this->session->set($key, $arr);
        return $result;
    }

    /**
     * @return void
     */
    public function clear() {
        $key = "saml_state_{$this->providerID}";
        $this->session->set($key, array());
    }

}


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

@Component({
  selector: 'error',
  templateUrl: './404.html',
  styleUrls: ['./404.scss']
})
export class Page404 implements OnInit {

  constructor() {
    // Do stuff
  }

  ngOnInit() {
    console.log('Hello About');
  }

}


text:
import buildMediaQuery from '../src/buildMediaQuery';

test('should build minWidth query', () => {
  expect(buildMediaQuery({ minWidth: '10em' })).toEqual('(min-width: 10em)');
});

test('should build maxWidth query', () => {
  expect(buildMediaQuery({ maxWidth: '20em' })).toEqual('(max-width: 20em)');
});

test('should build minWidth/maxWidth query', () => {
  expect(buildMediaQuery({ minWidth: '10em', maxWidth: '20em' })).toEqual(
    '(min-width: 10em) and (max-width: 20em)'
  );
});

test('should build minWidth/not query', () => {
  expect(buildMediaQuery({ minWidth: '10em' }, true)).toEqual(
    'not all and (min-width: 10em)'
  );
});

test('should build maxWidth/not query', () => {
  expect(buildMediaQuery({ maxWidth: '20em' }, true)).toEqual(
    'not all and (max-width: 20em)'
  );
});

test('should build minWidth/maxWidth/not query', () => {
  expect(buildMediaQuery({ minWidth: '10em', maxWidth: '20em' }, true)).toEqual(
    'not all and (min-width: 10em) and (max-width: 20em)'
  );
});


text:
package com.android.robot;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.ImageObserver;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import javax.swing.ImageIcon;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Keypad {

    private Shell parent = null;
    private Label lblWarning = null;
    private Shell shell  = null;
    private Display display = null;
    String result = "";
    /**
     * @wbp.parser.entryPoint
     */
    public Keypad(Shell parent){
    	this.parent = parent;
    }

    public Keypad(){}

	/**
	 * Open the window.
	 */
	public String open() {
		display = Display.getDefault();
		shell = new Shell(parent);//parent
		shell.open();
		shell.setSize(350, 200);
		shell.setText("字符串自动录入");
		shell.setLayout(new GridLayout(1,false));
		//new Label(shell,SWT.CENTER);
		//new Label(shell,SWT.CENTER);
		//

		lblWarning = new Label(shell,SWT.CENTER);
		//lblWarning.setText("输入内容不能为空!");
		new Label(shell,SWT.CENTER);

		Composite composite1 = new Composite(shell, SWT.NONE);
		composite1.setLayoutData(new GridData(350, 50));
		composite1.setLayout(new GridLayout(2,false));

		//Label
		Label lbText = new Label(composite1, SWT.CENTER);
		lbText.setText("     输入字符串:      ");

		//Text
		final Text txtInput = new Text(composite1, SWT.BORDER);
		GridData gd_Input = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_Input.heightHint = 15;
		gd_Input.widthHint = 180;
		txtInput.setLayoutData(gd_Input);

		Composite composite2 = new Composite(shell, SWT.NONE);
		composite2.setLayoutData(new GridData(350, 100));
		composite2.setLayout(new GridLayout(14,false));

		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);
		new Label(composite2,SWT.CENTER);

		Button btnOK = new Button(composite2,SWT.NONE);
		GridData gd_btnOK = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
		gd_btnOK.heightHint = 32;
		gd_btnOK.widthHint = 96;
		btnOK.setLayoutData(gd_btnOK);
		btnOK.setText("生成脚本");

		btnOK.addListener(SWT.Selection, new Listener() {
	      public void handleEvent(Event event) {
		        if(event.detail == 0) {
		        	String msg = txtInput.getText();
		        	if(!msg.equals("")){
		        		result = msg;
		        		shell.dispose();
		        	}
		        }
		  }
		});

		Button btnCancel = new Button(composite2,SWT.NONE);
		GridData gd_btnCancel = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
		gd_btnCancel.heightHint = 32;
		gd_btnCancel.widthHint = 96;
		btnCancel.setLayoutData(gd_btnCancel);
		btnCancel.setText("取消");
		btnCancel.addListener(SWT.Selection, new Listener() {
		      public void handleEvent(Event event) {
			        if(event.detail == 0) {
			        	result = "";
			        	shell.dispose();
			        }
			  }
			});

		shell.layout();
		while (shell!=null&&!shell.isDisposed()) {
			if (display!=null&&!display.readAndDispatch()) {
				display.sleep();
			}
		}

		return result;
	}
}