text:
"""

Author:
    Weichen Shen, weichenswc@163.com

Reference:
    [1] Xiao J, Ye H, He X, et al. Attentional factorization machines: Learning the weight of feature interactions via attention networks[J]. arXiv preprint arXiv:1708.04617, 2017.
    (https://arxiv.org/abs/1708.04617)

"""
from tensorflow.python.keras.models import Model
from ..feature_column import build_input_features, get_linear_logit, DEFAULT_GROUP_NAME, input_from_feature_columns
from ..layers.core import PredictionLayer
from ..layers.interaction import AFMLayer, FM
from ..layers.utils import concat_func, add_func

def AFM(linear_feature_columns, dnn_feature_columns, fm_group=DEFAULT_GROUP_NAME, use_attention=True,
        attention_factor=8,
        l2_reg_linear=1e-5, l2_reg_embedding=1e-5, l2_reg_att=1e-5, afm_dropout=0, seed=1024,
        task='binary'):
    """Instantiates the Attentional Factorization Machine architecture.

    :param linear_feature_columns: An iterable containing all the features used by linear part of the model.
    :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.
    :param fm_group: list, group_name of features that will be used to do feature interactions.
    :param use_attention: bool,whether use attention or not,if set to ``False``.it is the same as **standard Factorization Machine**
    :param attention_factor: positive integer,units in attention net
    :param l2_reg_linear: float. L2 regularizer strength applied to linear part
    :param l2_reg_embedding: float. L2 regularizer strength applied to embedding vector
    :param l2_reg_att: float. L2 regularizer strength applied to attention net
    :param afm_dropout: float in [0,1), Fraction of the attention net output units to dropout.
    :param seed: integer ,to use as random seed.
    :param task: str, ``"binary"`` for  binary logloss or  ``"regression"`` for regression loss
    :return: A Keras model instance.
    """

    features = build_input_features(
        linear_feature_columns + dnn_feature_columns)

    inputs_list = list(features.values())

    group_embedding_dict, _ = input_from_feature_columns(features, dnn_feature_columns, l2_reg_embedding,
                                                         seed, support_dense=False, support_group=True)

    linear_logit = get_linear_logit(features, linear_feature_columns, seed=seed, prefix='linear',
                                    l2_reg=l2_reg_linear)

    if use_attention:
        fm_logit = add_func([AFMLayer(attention_factor, l2_reg_att, afm_dropout,
                                      seed)(list(v)) for k, v in group_embedding_dict.items() if k in fm_group])
    else:
        fm_logit = add_func([FM()(concat_func(v, axis=1))
                             for k, v in group_embedding_dict.items() if k in fm_group])

    final_logit = add_func([linear_logit, fm_logit])
    output = PredictionLayer(task)(final_logit)

    model = Model(inputs=inputs_list, outputs=output)
    return model


text:
<?php
// src\Serialken\BlogBundle\BigBrother

namespace Serialken\BlogBundle\BigBrother;

final class BigBrotherEvents
{
    const onMessagePost = 'serialkenblog.bigbrother.post_message';
}

redpajama_set_name: RedPajamaGithub


text:
package codec

import (
	"github.com/uhoh-itsmaciek/femebe/proto"
)

// GuessOids attemps to guess the Postgres oids for the given data
// values. It assumes that rows is a slice of uniform-length slices
// where each cell corresponds to a column. It returns a slice of oid
// values of the mapped oids, or OID_UNKNOWN where no mapping could
// be determined.
func GuessOids(rows [][]interface{}) (oids []proto.Oid) {
	if len(rows) == 0 {
		// can't really make much of a guess here
		return []proto.Oid{}
	}
	oids = make([]proto.Oid, len(rows[0]))
	for _, row := range rows {
		gotAll := true
		for i := range oids {
			if o := oids[i]; o == 0 || o == proto.OidUnknown {
				oids[i] = MappedOid(row[i])
				if oids[i] == proto.OidUnknown {
					gotAll = false
				}
			}
		}
		if gotAll {
			break
		}
	}
	return oids
}

// Mappedproto.Oid returns the Postgres oid mapped to the type of the given
// value in femebe, or OID_UNKNOWN if no mapping exists.
func MappedOid(val interface{}) proto.Oid {
	switch val.(type) {
	case nil:
		// we can't determine a type here
		return proto.OidUnknown
	case int16:
		return proto.OidInt2
	case int32:
		return proto.OidInt4
	case int64:
		return proto.OidInt8
	case float32:
		return proto.OidFloat4
	case float64:
		return proto.OidFloat8
	case string:
		return proto.OidText
	case bool:
		return proto.OidBool
	default:
		return proto.OidUnknown
	}
}


text:
layout: tag
section-type: tag
title: pattern languages
---
## Tag


text:
module Trainyard
  module SiteControl
    def self.included(base)
      base.send :helper_method, :current_site, :site_name, :site_email, :site_email_host, :is_localhost?,
        :default_back_action if base.respond_to? :helper_method
      base.send :before_filter, :add_default_page_actions if base.respond_to? :before_filter
    end

    def current_site
      return @current_site if defined?(@current_site)
      @current_site = Configuration.current_site(request)
      logger.debug "Application domain: #{request.domain} (#{@current_site[:name]})"
      @current_site
    end

    def site_name
      current_site[:name]
    end

    def site_email
      current_site[:email]
    end

    def site_email_host
      current_site[:email_host]
    end

    def is_localhost?
      request.domain == 'localhost'
    end

    def default_back_action
      return @default_back_action if defined?(@default_back_action)
      case action_name
      when 'new', 'edit'
        @default_back_action = @template.link_to_back(t(:cancel)) unless Configuration.hide_cancel_action
      else
        @default_back_action = @template.link_to_back unless Configuration.hide_back_action
      end
    end

    def add_default_page_actions
      page_actions.unshift(default_back_action) unless default_back_action.nil? || page_actions.include?(default_back_action)
    end

    def remove_default_page_actions
      page_actions.delete(default_back_action) if default_back_action
    end
  end
end

ActionController::Base.send(:include, Trainyard::SiteControl) if defined?(ActionController::Base)


text:
$:.unshift(File.dirname(__FILE__)) unless
  $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))

require 'pp'
require 'fileutils'
require 'readline'
require 'irb/input-method'
require 'irb/ruby-lex'

require 'rubish/stub'
require 'rubish/job'
require 'rubish/job_control'
require 'rubish/context'
require 'rubish/repl'
require 'rubish/workspace'
require 'rubish/executable'
require 'rubish/unix_executable'
require 'rubish/batch_executable'
require 'rubish/command'
require 'rubish/command_builder'
require 'rubish/pipe'
require 'rubish/streamer'
require 'rubish/sed'
require 'rubish/awk'


text:
package org.joeyb.undercarriage.core;

import org.joeyb.undercarriage.core.utils.Suppliers;

import java.util.function.Supplier;

/**
 * {@code ConstructorBoundApplicationResolver} is an implementation of {@link ApplicationResolver}. It memoizes the
 * value returned by the given {@link Application} {@link Supplier}.
 */
public class ConstructorBoundApplicationResolver extends ApplicationResolverBase {

    private final Supplier<Application<?>> applicationSupplier;

    public ConstructorBoundApplicationResolver(Supplier<Application<?>> applicationSupplier) {
        this.applicationSupplier = Suppliers.memoize(applicationSupplier);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final Application<?> application() {
        return checkApplication(applicationSupplier.get());
    }
}


text:
/**
 * Logs the Whorl instance everytime a message is sent through.
 */
function log (whorl) {
  console.log('MESSAGE:', whorl.message)
  console.log('MODEL:', whorl.model)

  return whorl
}

module.exports = log


text:
<md-fab-speed-dial md-open="fabOpen" class="md-fab-bottom-right md-scale" style="position: fixed">
	<md-fab-trigger>
		<md-button class="md-fab md-accent" ui-sref="create">
			<md-tooltip md-direction="left">사용자 모임 생성</md-tooltip>
			<md-icon>group_add</md-icon>
		</md-button>
	</md-fab-trigger>
</md-fab-speed-dial>

사용자 모임

	<md-card md-whiteframe="3">
		<cm-search-list
			resource-url="/rest/configuration/userGroups"
			domains="domains"
			search-info="searchInfo"
			sort-items="{
				userGroupId: 'userGroupId',
				name: '이름'
			}"
			default-sorts="'userGroupId,desc'">

			<cm-search-list-filters>
				<md-card-content class="content" layout="column">
					<md-input-container>
						userGroupId
						<input ng-model="searchInfo.userGroupId" />
					</md-input-container>
					<md-input-container>
						이름
						<input ng-model="searchInfo.name" />
					</md-input-container>
					<md-input-container>
						속한 사용자
						<input ng-model="searchInfo.userId" />
					</md-input-container>
					<md-input-container>
						권한
						<input ng-model="searchInfo.authority" />
					</md-input-container>
				</md-card-content>
			</cm-search-list-filters>
			<cm-search-list-items>
				<md-list-item ng-repeat="domain in domains.content" ng-click="goView(domain)">

						<md-icon>group</md-icon>

						{{domain.userGroupId}}

					{{domain.name}}
					{{domain.permission.name}}
					<md-divider ng-if="!$last"></md-divider>
				</md-list-item>
			</cm-search-list-items>
		</cm-search-list>
	</md-card>


text:
module ApplicationHelper

  MD_EXTENSIONS = {
    autolink:           true,
    superscript:        true,
    fenced_code_blocks: true,
    disable_indented_code_blocks: true,
    lax_spacing:        true,
    strikethrough:      true,
    highlight:          true
  }

  def markdown(text)
    text ||= ''

    unless @markdown
      options = {
        filter_html:     true,
        safe_links_only:  true,
        hard_wrap:       true,
        no_images:       true,
        no_styles:       true,
        prettify:        true,
        link_attributes: { rel: 'nofollow', target: '_blank' },
        space_after_headers: true
      }

      renderer = Redcarpet::Render::HTML.new(options)
      @markdown = Redcarpet::Markdown.new(renderer, MD_EXTENSIONS)
    end

    @markdown.render(text).html_safe
  end

  def markdown_unsafe(text)
    text ||= ''

    unless @markdown_unsafe
      options = {
        filter_html:     false,
        safe_links_only:  true,
        hard_wrap:       true,
        prettify:        true,
        link_attributes: { rel: 'nofollow', target: '_blank' },
        space_after_headers: true
      }

      renderer = Redcarpet::Render::HTML.new(options)
      @markdown_unsafe = Redcarpet::Markdown.new(renderer, MD_EXTENSIONS)
    end

    @markdown_unsafe.render(text)
  end

  def markdown_wiki(text)
    text ||= ''

    unless @markdown_wiki
      options = {
        filter_html:     true,
        safe_links_only:  true,
        no_images:       false,
        hard_wrap:       true,
        prettify:        true,
        link_attributes: { rel: 'nofollow', target: '_blank' },
        space_after_headers: true
      }

      renderer = Redcarpet::Render::HTML.new(options)
      @markdown_wiki = Redcarpet::Markdown.new(renderer, MD_EXTENSIONS)
    end

    @markdown_wiki.render(text).html_safe
  end
end


text:
function hireForm(groupNum){
	var task_id =getEventJSONIndex(groupNum);
	logActivity("hireForm(groupNum)",'Clicked Hire Button on Task', new Date().getTime(), current_user, chat_name, team_id, flashTeamsJSON["events"][getEventJSONIndex(groupNum)]);

	var url = task_id +'/hire_form';
    window.open(url);
}


text:
package cn.zhangls.android.weibo.ui.weibo.content;

/**
 * Created by zhangls{github.com/zhangls2014} on 2017/4/5.
 * <p>
 * RecyclerView Item Empty
 */
public class ItemEmpty {

}


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

import org.apache.log4j.Logger;
import org.apache.jackrabbit.webdav.xml.XmlSerializable;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.lock.ActiveLock;
import org.apache.jackrabbit.webdav.lock.LockDiscovery;
import org.apache.jackrabbit.webdav.observation.Subscription;
import org.apache.jackrabbit.webdav.observation.SubscriptionDiscovery;
import org.apache.jackrabbit.webdav.observation.EventDiscovery;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.ServletOutputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.ByteArrayOutputStream;
import java.util.Locale;

/**
 * WebdavResponseImpl implements the WebdavResponse interface.
 */
public class WebdavResponseImpl implements WebdavResponse {

    private static Logger log = Logger.getLogger(WebdavResponseImpl.class);

    private static final DocumentBuilderFactory BUILDER_FACTORY = DocumentBuilderFactory.newInstance();

    private HttpServletResponse httpResponse;

    /**
     * Create a new WebdavResponse
     *
     * @param httpResponse
     */
    public WebdavResponseImpl(HttpServletResponse httpResponse) {
        this(httpResponse, false);
    }

    /**
     * Create a new WebdavResponse
     *
     * @param httpResponse
     * @param noCache
     */
    public WebdavResponseImpl(HttpServletResponse httpResponse, boolean noCache) {
        this.httpResponse = httpResponse;
        if (noCache) {
            /* set cache control headers */
        addHeader("Pragma", "No-cache");  // http1.0
        addHeader("Cache-Control", "no-cache"); // http1.1
    }
    }

    /**
     * If the specifid exception provides an error condition an Xml response body
     * is sent providing more detailed information about the error. Otherwise only
     * the error code and status phrase is sent back.
     *
     * @param exception
     * @throws IOException
     * @see DavServletResponse#sendError(org.apache.jackrabbit.webdav.DavException)
     * @see #sendError(int, String)
     * @see #sendXmlResponse(XmlSerializable, int)
     */
    public void sendError(DavException exception) throws IOException {
        if (!exception.hasErrorCondition()) {
            httpResponse.sendError(exception.getErrorCode(), exception.getStatusPhrase());
        } else {
            sendXmlResponse(exception, exception.getErrorCode());
        }
    }

    /**
     * Send a multistatus response.
     *
     * @param multistatus
     * @throws IOException
     * @see DavServletResponse#sendMultiStatus(org.apache.jackrabbit.webdav.MultiStatus)
     */
    public void sendMultiStatus(MultiStatus multistatus) throws IOException {
        sendXmlResponse(multistatus, SC_MULTI_STATUS);
    }

    /**
     * Send response body for a lock request intended to create a new lock.
     *
     * @param lock
     * @throws java.io.IOException
     * @see DavServletResponse#sendLockResponse(org.apache.jackrabbit.webdav.lock.ActiveLock)
     */
    public void sendLockResponse(ActiveLock lock) throws IOException {
        httpResponse.setHeader(DavConstants.HEADER_LOCK_TOKEN, "<" + lock.getToken() + ">");
	DavPropertySet propSet = new DavPropertySet();
        propSet.add(new LockDiscovery(lock));
        sendXmlResponse(propSet, SC_OK);
    }

    /**
     * Send response body for a lock request that was intended to refresh one
     * or several locks.
     *
     * @param locks
     * @throws java.io.IOException
     * @see DavServletResponse#sendRefreshLockResponse(org.apache.jackrabbit.webdav.lock.ActiveLock[])
     */
    public void sendRefreshLockResponse(ActiveLock[] locks) throws IOException {
        DavPropertySet propSet = new DavPropertySet();
        propSet.add(new LockDiscovery(locks));
        sendXmlResponse(propSet, SC_OK);
    }

    /**
     * Send Xml response body.
     *
     * @param serializable
     * @param status
     * @throws IOException
     * @see DavServletResponse#sendXmlResponse(XmlSerializable, int);
     */
    public void sendXmlResponse(XmlSerializable serializable, int status) throws IOException {
        httpResponse.setStatus(status);
        if (serializable != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                Document doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
                doc.appendChild(serializable.toXml(doc));

                OutputFormat format = new OutputFormat("xml", "UTF-8", true);
                XMLSerializer serializer = new XMLSerializer(out, format);
                serializer.setNamespaces(true);
                serializer.asDOMSerializer().serialize(doc);

            byte[] bytes = out.toByteArray();
            httpResponse.setContentType("text/xml; charset=UTF-8");
            httpResponse.setContentLength(bytes.length);
            httpResponse.getOutputStream().write(bytes);

            } catch (ParserConfigurationException e) {
                log.error(e.getMessage());
                throw new IOException(e.getMessage());
            }
        }
    }

    //----------------------------< ObservationDavServletResponse Interface >---
    /**
     *
     * @param subscription
     * @throws IOException
     * @see org.apache.jackrabbit.webdav.observation.ObservationDavServletResponse#sendSubscriptionResponse(org.apache.jackrabbit.webdav.observation.Subscription)
     */
    public void sendSubscriptionResponse(Subscription subscription) throws IOException {
	DavPropertySet propSet = new DavPropertySet();
        propSet.add(new SubscriptionDiscovery(subscription));
        sendXmlResponse(propSet, SC_OK);
    }

    /**
     *
     * @param eventDiscovery
     * @throws IOException
     * @see org.apache.jackrabbit.webdav.observation.ObservationDavServletResponse#sendPollResponse(org.apache.jackrabbit.webdav.observation.EventDiscovery)
     */
    public void sendPollResponse(EventDiscovery eventDiscovery) throws IOException {
        sendXmlResponse(eventDiscovery, SC_OK);
    }

    //--------------------------------------< HttpServletResponse interface >---
    public void addCookie(Cookie cookie) {
        httpResponse.addCookie(cookie);
    }

    public boolean containsHeader(String s) {
        return httpResponse.containsHeader(s);
    }

    public String encodeURL(String s) {
        return httpResponse.encodeRedirectURL(s);
    }

    public String encodeRedirectURL(String s) {
        return httpResponse.encodeRedirectURL(s);
    }

    public String encodeUrl(String s) {
        return httpResponse.encodeUrl(s);
    }

    public String encodeRedirectUrl(String s) {
        return httpResponse.encodeRedirectURL(s);
    }

    public void sendError(int i, String s) throws IOException {
        httpResponse.sendError(i, s);
    }

    public void sendError(int i) throws IOException {
        httpResponse.sendError(i);
    }

    public void sendRedirect(String s) throws IOException {
        httpResponse.sendRedirect(s);
    }

    public void setDateHeader(String s, long l) {
        httpResponse.setDateHeader(s, l);
    }

    public void addDateHeader(String s, long l) {
        httpResponse.addDateHeader(s, l);
    }

    public void setHeader(String s, String s1) {
        httpResponse.setHeader(s, s1);
    }

    public void addHeader(String s, String s1) {
        httpResponse.addHeader(s, s1);
    }

    public void setIntHeader(String s, int i) {
        httpResponse.setIntHeader(s, i);
    }

    public void addIntHeader(String s, int i) {
        httpResponse.addIntHeader(s, i);
    }

    public void setStatus(int i) {
        httpResponse.setStatus(i);
    }

    public void setStatus(int i, String s) {
        httpResponse.setStatus(i, s);
    }

    public String getCharacterEncoding() {
        return httpResponse.getCharacterEncoding();
    }

    public ServletOutputStream getOutputStream() throws IOException {
        return httpResponse.getOutputStream();
    }

    public PrintWriter getWriter() throws IOException {
        return httpResponse.getWriter();
    }

    public void setContentLength(int i) {
        httpResponse.setContentLength(i);
    }

    public void setContentType(String s) {
        httpResponse.setContentType(s);
    }

    public void setBufferSize(int i) {
        httpResponse.setBufferSize(i);
    }

    public int getBufferSize() {
        return httpResponse.getBufferSize();
    }

    public void flushBuffer() throws IOException {
        httpResponse.flushBuffer();
    }

    public void resetBuffer() {
        httpResponse.resetBuffer();
    }

    public boolean isCommitted() {
        return httpResponse.isCommitted();
    }

    public void reset() {
        httpResponse.reset();
    }

    public void setLocale(Locale locale) {
        httpResponse.setLocale(locale);
    }

    public Locale getLocale() {
        return httpResponse.getLocale();
    }

    public void setCharacterEncoding(String charset) {
        httpResponse.setCharacterEncoding(charset);
    }

    public String getContentType() {
        return httpResponse.getContentType();
    }
}


text:
package org.waveprotocol.wave.model.supplement;

import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.util.ValueUtils;

import java.util.Comparator;

/**
 * The result of a single evaluation by an agent about whether this wavelet is
 * wanted.
 *
 */
public interface WantedEvaluation extends Comparable<WantedEvaluation> {

  /**
   * Utility class for implementers of WantedEvaluations.
   */
  class ImplementationHelper {
    /** How equality between two WantedEvaluations should be implemented. */
    static boolean calculateEqual(WantedEvaluation one, WantedEvaluation other) {
      return ValueUtils.equal(one.getWaveletId(), other.getWaveletId()) // \u2620
          && one.getAdderAddress().equals(other.getAdderAddress()) // \u2620
          && one.isWanted() == other.isWanted() // \u2620
          && one.getCertainty() == other.getCertainty() // \u2620
          && one.getComment().equals(other.getComment()) // \u2620
          && one.getTimestamp() == other.getTimestamp() // \u2620
          && one.isIgnored() == other.isIgnored() // \u2620
          && one.getAgentIdentity().equals(other.getAgentIdentity());
    }

    /** How hashcode ought to be implemented by WantedEvaluations. */
    static int calculateHashCode(WantedEvaluation eval) {
      int result = 17;
      result *= 37 + (eval.getWaveletId() == null ? 1 : eval.getWaveletId().hashCode());
      result *= 37 + (eval.getAdderAddress().hashCode());
      result *= 37 + (eval.isWanted() ? 1 : 0);
      result *= 37 + Double.valueOf(eval.getCertainty()).hashCode();
      result *= 37 + eval.getComment().hashCode();
      result *= 37 + eval.getTimestamp();
      result *= 37 + (eval.isIgnored() ? 1 : 0);
      result *= 37 + eval.getAgentIdentity().hashCode();
      return result;
    }

    /** Disallow construction. */
    private ImplementationHelper() {
    }

    /** Calculates human-readable toString. */
    static String calculateToString(WantedEvaluation eval) {
      return eval.getTypeName() + "(" + eval.getWaveletId() + ", " + eval.getAdderAddress() + ", "
          + eval.isWanted() + ", " + eval.getCertainty() + ", " + eval.getTimestamp() + ", "
          + eval.getAgentIdentity() + ", " + eval.isIgnored() + ", " + eval.getComment() + ")";
    }
  }

  /**
   * Canonical implementation for WantedEvaluation.compareTo().
   *
   * Compares WantedEvaluations according to the canonical rules for finding the
   * most certain and relevant WantedEvaluation from a WantedEvaluationSet.
   */
  static final Comparator<WantedEvaluation> COMPARATOR = new Comparator<WantedEvaluation>() {
    @Override
    public int compare(WantedEvaluation wanted1, WantedEvaluation wanted2) {
      int result =
          Long.signum(Math.round(Math.signum(wanted1.getCertainty() - wanted2.getCertainty())));
      if (result == 0) {
        result = Long.signum(wanted1.getTimestamp() - wanted2.getTimestamp());
      }
      if (result == 0) {
        // Breaks ties on evaluations that are similar but different
        result = wanted1.hashCode() - wanted2.hashCode();
      }
      return result;
    }
  };

  /** Gets the address of the account that added the user to this wave */
  String getAdderAddress();

  /** Gets the agent's identity string (informational, for debugging.) */
  String getAgentIdentity();

  /** The degree of certainty (0 .. 1.0) in the evaluation. */
  double getCertainty();

  /** Gets a human-readable comment (informational, for debugging.) */
  String getComment();

  /** Timestamp - Java time. */
  long getTimestamp();

  /**
   * Gets name of the implementation type, for use in
   * {@link ImplementationHelper#calculateToString(WantedEvaluation)}
   */
  String getTypeName();

  /** True if the user has ignored this wave */
  boolean isIgnored();

  /** Whether this evaluation is that the wave is wanted, or not wanted. */
  boolean isWanted();

  /**
   * The ID of the wavelet this evaluation is for. A null waveletId indicates
   * that this is an invalid evaluation, and should be ignored.
   */
  WaveletId getWaveletId();
}


text:
# -*- coding: utf-8 -*-
require 'rails/version'

def using_rails_api?
  ENV["TEST_RAILS_API"] == true
end

def request_id_available?
  Gem::Version.new(Rails::VERSION::STRING) >= Gem::Version.new('3.2')
end

def active_job_available?
  Gem::Version.new(Rails::VERSION::STRING) >= Gem::Version.new('4.2')
end

require "minitest/autorun"
require 'mocha/test_unit'
require 'logger'
require 'pp'
require 'active_record'
require 'action_controller'

if request_id_available?
  require 'action_dispatch/middleware/request_id'
end

if active_job_available?
  require 'active_job'
end

if using_rails_api?
  require 'rails-api/action_controller/api'
end

# Shim for compatibility with older versions of MiniTest
MiniTest::Test = MiniTest::Unit::TestCase unless defined?(MiniTest::Test)

# From version 4.1, ActiveRecord expects `Rails.env` to be
# defined if `Rails` is defined
if defined?(Rails) && !defined?(Rails.env)
  module Rails
    def self.env
    end
  end
end

require 'marginalia'
RAILS_ROOT = File.expand_path(File.dirname(__FILE__))

ActiveRecord::Base.establish_connection({
  :adapter  => ENV["DRIVER"] || "mysql",
  :host     => "localhost",
  :username => ENV["DB_USERNAME"] || "root",
  :database => "marginalia_test"
})

class Post < ActiveRecord::Base
end

class PostsController < ActionController::Base
  def driver_only
    ActiveRecord::Base.connection.execute "select id from posts"
    render :nothing => true
  end
end

module API
  module V1
    class PostsController < ::PostsController
    end
  end
end

if active_job_available?
  class PostsJob < ActiveJob::Base
    def perform
      Post.first
    end
  end
end

if using_rails_api?
  class PostsApiController < ActionController::API
    def driver_only
      ActiveRecord::Base.connection.execute "select id from posts"
      head :no_content
    end
  end
end

unless Post.table_exists?
  ActiveRecord::Schema.define do
    create_table "posts", :force => true do |t|
    end
  end
end

Marginalia::Railtie.insert

class MarginaliaTest < MiniTest::Test
  def setup
    @queries = []
    ActiveSupport::Notifications.subscribe "sql.active_record" do |*args|
      @queries << args.last[:sql]
    end
    @env = Rack::MockRequest.env_for('/')
  end

  def test_double_annotate
    ActiveRecord::Base.connection.expects(:annotate_sql).returns("select id from posts").once
    ActiveRecord::Base.connection.send(:select, "select id from posts")
  ensure
    ActiveRecord::Base.connection.unstub(:annotate_sql)
  end

  def test_query_commenting_on_mysql_driver_with_no_action
    ActiveRecord::Base.connection.execute "select id from posts"
    assert_match %r{select id from posts /\*application:rails\*/$}, @queries.first
  end

  if ENV["DRIVER"] =~ /^mysql/
    def test_query_commenting_on_mysql_driver_with_binary_chars
      ActiveRecord::Base.connection.execute "select id from posts /* \x81\x80\u0010\ */"
      assert_equal "select id from posts /* \x81\x80\u0010 */ /*application:rails*/", @queries.first
    end
  end

  def test_query_commenting_on_mysql_driver_with_action
    PostsController.action(:driver_only).call(@env)
    assert_match %r{select id from posts /\*application:rails,controller:posts,action:driver_only\*/$}, @queries.first

    if using_rails_api?
      PostsApiController.action(:driver_only).call(@env)
      assert_match %r{select id from posts /\*application:rails,controller:posts_api,action:driver_only\*/$}, @queries.second
    end
  end

  def test_configuring_application
    Marginalia.application_name = "customapp"
    PostsController.action(:driver_only).call(@env)
    assert_match %r{/\*application:customapp,controller:posts,action:driver_only\*/$}, @queries.first

    if using_rails_api?
      PostsApiController.action(:driver_only).call(@env)
      assert_match %r{/\*application:customapp,controller:posts_api,action:driver_only\*/$}, @queries.second
    end
  end

  def test_configuring_query_components
    Marginalia::Comment.components = [:controller]
    PostsController.action(:driver_only).call(@env)
    assert_match %r{/\*controller:posts\*/$}, @queries.first

    if using_rails_api?
      PostsApiController.action(:driver_only).call(@env)
      assert_match %r{/\*controller:posts_api\*/$}, @queries.second
    end
  end

  def test_last_line_component
    Marginalia::Comment.components = [:line]
    PostsController.action(:driver_only).call(@env)

    # Because "lines_to_ignore" by default includes "marginalia" and "gem", the
    # extracted line line will be from the line in this file that actually
    # triggers the query.
    assert_match %r{/\*line:test/query_comments_test.rb:[0-9]+:in `driver_only'\*/$}, @queries.first
  end

  def test_last_line_component_with_lines_to_ignore
    Marginalia::Comment.lines_to_ignore = /foo bar/
    Marginalia::Comment.components = [:line]
    PostsController.action(:driver_only).call(@env)
    # Because "lines_to_ignore" does not include "marginalia", the extracted
    # line will be from marginalia/comment.rb.
    assert_match %r{/\*line:.*lib/marginalia/comment.rb:[0-9]+}, @queries.first
  end

  def test_hostname_and_pid
    Marginalia::Comment.components = [:hostname, :pid]
    PostsController.action(:driver_only).call(@env)
    assert_match %r{/\*hostname:#{Socket.gethostname},pid:#{Process.pid}\*/$}, @queries.first
  end

  def test_controller_with_namespace
    Marginalia::Comment.components = [:controller_with_namespace]
    API::V1::PostsController.action(:driver_only).call(@env)
    assert_match %r{/\*controller_with_namespace:API::V1::PostsController}, @queries.first
  end

  if request_id_available?
    def test_request_id
      @env["action_dispatch.request_id"] = "some-uuid"
      Marginalia::Comment.components = [:request_id]
      PostsController.action(:driver_only).call(@env)
      assert_match %r{/\*request_id:some-uuid.*}, @queries.first

      if using_rails_api?
        PostsApiController.action(:driver_only).call(@env)
        assert_match %r{/\*request_id:some-uuid.*}, @queries.second
      end
    end

  else
    def test_request_id_is_noop_on_old_rails
      @env["action_dispatch.request_id"] = "some-uuid"
      Marginalia::Comment.components = [:request_id]
      PostsController.action(:driver_only).call(@env)
      assert_match %r{^select id from posts$}, @queries.first
    end
  end

  if active_job_available?
    def test_active_job
      Marginalia::Comment.components = [:job]
      PostsJob.perform_later
      assert_match %{job:PostsJob}, @queries.first

      Post.first
      refute_match %{job:PostsJob}, @queries.last
    end
  end

  def teardown
    Marginalia.application_name = nil
    Marginalia::Comment.lines_to_ignore = nil
    Marginalia::Comment.components = [:application, :controller, :action]
    ActiveSupport::Notifications.unsubscribe "sql.active_record"
  end
end


text:
package com.github.gdefacci.briscola.spec

import scalaz.{ -\/, \/, \/- }
import com.github.gdefacci.ddd._

import com.github.gdefacci.bdd._

trait EventsTestState[S, E, Err] {
  def result: Err \/ (Seq[E], S)

}

trait EventsSteps[TS <: EventsTestState[S, E, Err], S, E, Err] extends BDD[TS, String] {

  def `events contain`(event: E => Boolean): Expectation = expectation { state =>
    state.result match {
      case -\/(err) => Fail(err.toString)
      case \/-((events, _)) =>
        if (events.exists(event)) Ok else Fail(s"expecting $event inside ${events.mkString}, but was not")
    }
  }

  def `error is`(error: Err => Boolean): Expectation = expectation { state =>
    state.result match {
      case -\/(err) => if (error(err)) Ok else Fail(s"expecting error $error but got error $err")
      case \/-((_, _)) =>
        Fail(s"expecting error $error but no error happened")
    }
  }

  def `the final state`(predicate: S => Boolean): Expectation = expectation { state =>
    state.result match {
      case -\/(err) => Fail(err.toString)
      case \/-((_, newState)) =>
        if (predicate(newState)) Ok else Fail(s"expecting state ${predicate.toString} but got ${newState}")
    }
  }

}


text:
use item::Item;
use types::Gold;

/// A single slot of the inventory
#[derive(Debug)]
pub struct InventorySlot {
    item: Item,
    amount: usize,
}

/// An inventory holding items
#[derive(Debug)]
pub struct Inventory {
    contents: Vec<InventorySlot>,
    gold: Gold,
    max_size: usize,
}

impl Inventory {
    /// Creates a new instance of `Inventory`
    pub fn new(max_size: usize) -> Inventory {
        Inventory {
            contents: Vec::new(),
            max_size: max_size,
            gold: 0,
        }
    }

    /// Adds an item to the inventory. If the inventory is full, the item won't be added to the
    /// inventory and a `Err(Item)` is returned.
    pub fn add_item(&mut self, new_item: Item) -> Result<(), Item> {
        for slot in &mut self.contents {
            if slot.item == new_item {
                if slot.item.stack_size > slot.amount {
                    slot.amount += 1;
                    return Ok(());
                }
            }
        }

        if self.contents.len() < self.max_size {
            self.contents.push(InventorySlot {
                item: new_item,
                amount: 1,
            });
        } else {
            return Err(new_item);
        }

        Ok(())
    }

    /// Returns `true` it the inventory is full
    pub fn is_full(&self) -> bool {
        self.contents.len() == self.max_size
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use item_generator;
    use item::ItemType;

    #[test]
    fn inventory_full() {
        let mut inv_1 = Inventory::new(30);

        for _ in 0..40 {
            let random_item =
                item_generator::ItemGenerator::new().item_type(ItemType::ArmorHead).gen();
            if let Err(_) = inv_1.add_item(random_item) {
                assert!(inv_1.is_full());
            }
        }
    }

    #[test]
    fn stackability() {
        let mut inv = Inventory::new(30);

        let random_item_1 =
            item_generator::ItemGenerator::new().item_type(ItemType::ConsumablePotion).gen();
        for _ in 0..random_item_1.stack_size {
            let _ = inv.add_item(random_item_1.clone());
        }

        assert_eq!(inv.contents[0].amount, random_item_1.stack_size);

        for _ in 0..(random_item_1.stack_size / 4) {
            let _ = inv.add_item(random_item_1.clone());
        }

        assert_eq!(inv.contents[1].amount, random_item_1.stack_size / 4);
    }
}


text:
Options view like the one seen in the Spotify app for iOS.

## CocoaPods

Simply add the following in your Podfile:

```ruby
pod "TSROptionsView", :git => "https://github.com/tonsser/ios-options-selector"
```

We'll publish it to the CocoaPods repo once we feel it's stable enough for production use.

## Usage

```objective-c
@implementation YourViewController

// ...

- (void)askTheUser {
  TSROptionsView *options = [TSROptionsView withTitle:@"Will it blend?" delegate:self otherButtonTitles:@"Yes", @"No", @"Maybe ...", nil];

  options.tintColor   = [UIColor yellowColor];
  options.choicesFont = [UIFont fontWithName:@"Georgia" size:17.f];

  [self presentOptionsView:options];
}

// ...

@end
```

## Methods

```objective-c
+ (TSROptionsView *)withTitle:(NSString *)title delegate:(id<TSROptionsViewDelegate>)delegate otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;

+ (TSROptionsView *)withTitle:(NSString *)title delegate:(id<TSROptionsViewDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;

- (void)addOptionWithTitle:(NSString *)title;
- (void)addOptionWithTitle:(NSString *)title icon:(UIImage *)icon;
- (void)addOptionWithTitle:(NSString *)title icon:(UIImage *)icon selected:(BOOL)selected;

- (NSString *)titleForButtonWithIndex:(NSInteger)index;
```

## Properties

TSROptionsView

    cancelButtonTitle
    NSString*
    Set or get the title of the cancel button. nil will hide the cancel button.

    tintColor
    UIColor*
    Set or get the tint color.

    textColor
    UIColor*
    Set or get the text color.

    checkmarkColor
    UIColor*
    Set or get the checkmark color.

    titleFont
    UIFont*
    Set or get the font of the title.

    choicesFont
    UIFont*
    Set or get the font of the choices.

    tintColorAlphaModifier
    CGFloat
    Set or get the alpha modifier used for the blurring. Default is .85f.

    animationDuration
    CGFloat
    Duration of the animation in seconds (per animation, there's a total of 2).

    animationDelay
    CGFloat
    Delay, in number of seconds, between the two animations.

    startOffsetPercentage
    CGFloat
    The start offset/inset of the first button, in percents. (1 = 100%, 0.5 = 50%, 0 = 0%).

## Credits

TSROptionsView is brought to you by Nicolai Persson and the Tonsser team.

* Nicolai Persson ([GitHub](http://www.github.com/spookd))

Support is provided by the following organizations:

* [Tonsser](http://www.github.com/tonsser)

## License

TSROptionsView is licensed under the terms of the [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). Please see the [LICENSE](LICENSE) file for full details.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bulletin de la Société des Sciences naturelles et physiques du Maroc 55: 8 (1975)

#### Original name
Lecidea pantherina var. fallax Werner

### Remarks
null