text:
package com.alibaba.otter.canal.common.zookeeper;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.I0Itec.zkclient.IZkConnection;
import org.I0Itec.zkclient.exception.ZkException;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.ClientCnxn;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.client.ConnectStringParser;
import org.apache.zookeeper.client.HostProvider;
import org.apache.zookeeper.client.StaticHostProvider;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

/**
 * 封装了ZooKeeper,使其支持节点的优先顺序,比如美国机房的节点会优先加载美国对应的zk集群列表,都失败后才会选择加载杭州的zk集群列表 *
 *
 * @author jianghang 2012-7-10 下午02:31:42
 * @version 1.0.0
 */
public class ZooKeeperx implements IZkConnection {

    private static final String SERVER_COMMA            = ";";
    private static final Logger logger                  = LoggerFactory.getLogger(ZooKeeperx.class);
    private static final Field  clientCnxnField         = ReflectionUtils.findField(ZooKeeper.class, "cnxn");
    private static final Field  hostProviderField       = ReflectionUtils.findField(ClientCnxn.class, "hostProvider");
    private static final Field  serverAddressesField    = ReflectionUtils.findField(StaticHostProvider.class,
                                                            "serverAddresses");
    private static final int    DEFAULT_SESSION_TIMEOUT = 90000;

    private ZooKeeper           _zk                     = null;
    private Lock                _zookeeperLock          = new ReentrantLock();

    private final List<String>  _servers;
    private final int           _sessionTimeOut;

    public ZooKeeperx(String zkServers){
        this(zkServers, DEFAULT_SESSION_TIMEOUT);
    }

    public ZooKeeperx(String zkServers, int sessionTimeOut){
        _servers = Arrays.asList(StringUtils.split(zkServers, SERVER_COMMA));
        _sessionTimeOut = sessionTimeOut;
    }

    @Override
    public void connect(Watcher watcher) {
        _zookeeperLock.lock();
        try {
            if (_zk != null) {
                throw new IllegalStateException("zk client has already been started");
            }

            try {
                logger.debug("Creating new ZookKeeper instance to connect to " + _servers + ".");
                _zk = new ZooKeeper(_servers.get(0), _sessionTimeOut, watcher);
                configMutliCluster(_zk);
            } catch (IOException e) {
                throw new ZkException("Unable to connect to " + _servers, e);
            }
        } finally {
            _zookeeperLock.unlock();
        }
    }

    public void close() throws InterruptedException {
        _zookeeperLock.lock();
        try {
            if (_zk != null) {
                logger.debug("Closing ZooKeeper connected to " + _servers);
                _zk.close();
                _zk = null;
            }
        } finally {
            _zookeeperLock.unlock();
        }
    }

    public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException {
        return _zk.create(path, data, Ids.OPEN_ACL_UNSAFE, mode);
    }

    public void delete(String path) throws InterruptedException, KeeperException {
        _zk.delete(path, -1);
    }

    public boolean exists(String path, boolean watch) throws KeeperException, InterruptedException {
        return _zk.exists(path, watch) != null;
    }

    public List<String> getChildren(final String path, final boolean watch) throws KeeperException,
                                                                           InterruptedException {
        return _zk.getChildren(path, watch);
    }

    public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException {
        return _zk.getData(path, watch, stat);
    }

    public void writeData(String path, byte[] data) throws KeeperException, InterruptedException {
        writeData(path, data, -1);
    }

    public void writeData(String path, byte[] data, int version) throws KeeperException, InterruptedException {
        _zk.setData(path, data, version);
    }

    public States getZookeeperState() {
        return _zk != null ? _zk.getState() : null;
    }

    public ZooKeeper getZookeeper() {
        return _zk;
    }

    public long getCreateTime(String path) throws KeeperException, InterruptedException {
        Stat stat = _zk.exists(path, false);
        if (stat != null) {
            return stat.getCtime();
        }
        return -1;
    }

    public String getServers() {
        return StringUtils.join(_servers, SERVER_COMMA);
    }

    // ===============================

    public void configMutliCluster(ZooKeeper zk) {
        if (_servers.size() == 1) {
            return;
        }
        String cluster1 = _servers.get(0);
        try {
            if (_servers.size() > 1) {
                // 强制的声明accessible
                ReflectionUtils.makeAccessible(clientCnxnField);
                ReflectionUtils.makeAccessible(hostProviderField);
                ReflectionUtils.makeAccessible(serverAddressesField);

                // 添加第二组集群列表
                for (int i = 1; i < _servers.size(); i++) {
                    String cluster = _servers.get(i);
                    // 强制获取zk中的地址信息
                    ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zk);
                    HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn);
                    List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils.getField(serverAddressesField,
                        hostProvider);
                    // 添加第二组集群列表
                    serverAddrs.addAll(new ConnectStringParser(cluster).getServerAddresses());
                }
            }
        } catch (Exception e) {
            try {
                if (zk != null) {
                    zk.close();
                }
            } catch (InterruptedException ie) {
                // ignore interrupt
            }
            throw new ZkException("zookeeper_create_error, serveraddrs=" + cluster1, e);
        }

    }
}


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

namespace GoogleCloudExtension.StackdriverLogsViewer
{
    /// <summary>
    /// Resource value menu item view mode.
    /// </summary>
    public class ResourceValueItemViewModel : MenuItemViewModel
    {
        /// <summary>
        /// Gets the resource key value.
        /// Example: key is module_id,  the values can be "defaultservice", "my-test-service" etc.
        /// </summary>
        public string ResourceValue { get; }

        /// <summary>
        /// Initializes an instance of <seealso cref="ResourceValueItemViewModel"/> class.
        /// </summary>
        /// <param name="resourceKeyValue">The resource value.</param>
        /// <param name="parent">The parent menu item.</param>
        /// <param name="displayName">
        /// The display name of the resource key value.
        /// Example:  instance_id value is integer as string.  The display name is the instance name.
        /// </param>
        public ResourceValueItemViewModel(
            string resourceKeyValue,
            MenuItemViewModel parent,
            string displayName = null) : base(parent)
        {
            ResourceValue = resourceKeyValue;
            Header = displayName ?? ResourceValue;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
To execute the tests with your specific JSON config, set its name (without file suffix) via the `apiman.gateway-test.config` system property. It should reside within the `test-configs` directory.

For example:
  - `apiman.gateway-test.config=servlet-es`
  - `apiman.gateway-test.config=vertx3-mem`

If left unset, `default` will be assumed.


text:
package no.rosbach.jcoru.security;

import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;

public abstract class WhitelistTestBase<T> {

  protected AccessManager<T> whitelist(T... entries) {
    return createAccessManager(new HashSet<T>(Arrays.asList(entries)));
  }

  protected ArrayNode getWhitelistJson(final String resource) {
    try (InputStream fixtureStream = getClass().getClassLoader().getResourceAsStream(resource)) {
      ObjectMapper mapper = new ObjectMapper();
      return mapper.readValue(fixtureStream, ArrayNode.class);
    } catch (IOException e) {
      throw new Error("Failed to read whitelist fixture: " + resource, e);
    }
  }

  protected abstract AccessManager<T> whitelistFromJson(String json);

  protected abstract T[] getTwoDistinctEntries();

  protected abstract AccessManager<T> createAccessManager(HashSet<T> entries);

  @Test
  public void extendReturnsNewInstance() {
    AccessManager<T> whitelist = createAccessManager(new HashSet<>());

    AccessManager<T> extended = whitelist.extend(new HashSet<>());
    assertNotSame(whitelist, extended);
  }

  @Test
  public void extendReturnsUnionOfWhitelists() {
    T[] entries = getTwoDistinctEntries();
    AccessManager<T> whitelist = createAccessManager(new HashSet<>(Arrays.asList(entries[0])));

    AccessManager<T> extended = whitelist.extend(new HashSet<>(Arrays.asList(entries[1])));
    assertTrue(extended.hasAccess(entries[0]));
    assertTrue(extended.hasAccess(entries[1]));
  }
}


text:
//
//package firehose;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.symphonyoss.client.SymphonyClient;
//import org.symphonyoss.client.SymphonyClientConfig;
//import org.symphonyoss.client.SymphonyClientFactory;
//import org.symphonyoss.client.events.SymEvent;
//import org.symphonyoss.client.exceptions.DataFeedException;
//import org.symphonyoss.client.services.FirehoseListener;
//import org.symphonyoss.client.services.FirehoseService;
//
//
///**
// * Firehose example requires Agent Server 1.49 or higher
// *

// * Bot user requires elevated privs
// *

// *

// *

// *

// * REQUIRED VM Arguments or System Properties:
// *

// * -Dtruststore.file=
// * -Dtruststore.password=password
// * -Dsessionauth.url=https://(hostname)/sessionauth
// * -Dkeyauth.url=https://(hostname)/keyauth
// * -Duser.call.home=frank.tarsillo@markit.com
// * -Duser.cert.password=password
// * -Duser.cert.file=bot.user2.p12
// * -Duser.email=bot.user2@domain.com
// * -Dpod.url=https://(pod host)/pod
// * -Dagent.url=https://(agent server host)/agent
// * -Dreceiver.email=bot.user2@markit.com or bot user email
// *
// * @author Frank Tarsillo
// */
////NOSONAR
//public class FirehoseExample implements FirehoseListener {
//
//
//    private final Logger logger = LoggerFactory.getLogger(FirehoseExample.class);
//
//    private SymphonyClient symClient;
//
//    public FirehoseExample() {
//
//
//        init();
//
//
//    }
//
//    public static void main(String[] args) {
//
//        new FirehoseExample();
//
//    }
//
//    public void init() {
//
//
//        try {
//
//            SymphonyClientConfig symphonyClientConfig = new SymphonyClientConfig(true);
//
//
//
//            //Create an initialized client
//            symClient = SymphonyClientFactory.getClient(
//                    SymphonyClientFactory.TYPE.V4, symphonyClientConfig);
//
//            FirehoseService firehoseService = new FirehoseService(symClient);
//            firehoseService.addFirehoseListener(this);
//            firehoseService.init();
//
//
//        } catch (DataFeedException e) {
//            logger.error("error", e);
//        }
//
//    }
//
//
//    //Chat sessions callback method.
//    //@Override
//    public void onEvent(SymEvent symEvent) {
//
//        logger.info("{}", symEvent.toString());
//
//
//    }
//
//
//}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<string name="leave_this_page">"Deze pagina verlaten"</string>
<string name="stay_on_this_page">"Op deze pagina blijven"</string>
<string name="reload_this_page">"Deze pagina opnieuw laden"</string>
<string name="dont_reload_this_page">"Niet opnieuw laden"</string>
<string name="js_modal_dialog_confirm">"OK"</string>
<string name="js_modal_dialog_cancel">"Annuleren"</string>
<string name="suppress_js_modal_dialogs">"Voorkomen dat deze pagina extra dialoogvensters weergeeft"</string>
<string name="accessibility_js_modal_dialog_prompt">"Prompt"</string>
<string name="certtitle">"Certificaatweergave"</string>
<string name="sync_error_generic">"Synchronisatiefout"</string>
<string name="sync_error_ga">"Werk je inloggegevens bij."</string>
<string name="sync_error_connection">"Kan geen verbinding maken met synchronisatieserver."</string>
<string name="sync_error_domain">"De synchronisatieservice is niet beschikbaar voor je domein."</string>
<string name="sync_error_service_unavailable">"De service is niet beschikbaar. Probeer het later opnieuw."</string>
<string name="policy_dialog_title">"Inloggen bevestigen"</string>
<string name="policy_dialog_message">"Dit account wordt beheerd door %1$s.

Je logt in met een beheerd account en geeft de beheerder controle over je Chrome-profiel. Je Chrome-gegevens worden permanent gekoppeld aan dit account. Als je dit account loskoppelt, worden de lokale Chrome-gegevens verwijderd."</string>
<string name="policy_dialog_proceed">"Accepteren en inloggen"</string>
<string name="policy_dialog_cancel">"Annuleren"</string>
<string name="wiping_profile_data_title">"Accountgegevens wissen"</string>
<string name="wiping_profile_data_message">"Even geduld..."</string>
<string name="infobar_close">"Sluiten"</string>
<string name="translate_infobar_text">"This page is in ^1. Translate it to ^2?"</string>
<string name="translate_infobar_change_languages">"Change languages"</string>
<string name="translate_infobar_translation_done">"Translated to %1$s."</string>
<string name="translate_infobar_translation_more_options">"More"</string>
<string name="translate_infobar_translating">"Translating page to %1$s..."</string>
<string name="translate_infobar_error">"Oops. This page could not be translated."</string>
<string name="translate_always_text">"Always translate %1$s"</string>
<string name="translate_never_translate_message_text">"Would you like Google Chrome to offer to translate %1$s pages from this site next time?"</string>
<string name="translate_button">"Translate"</string>
<string name="translate_nope">"Nope"</string>
<string name="translate_show_original">"Show original"</string>
<string name="translate_retry">"Try again"</string>
<string name="translate_options_source_hint">"Page Language: ^1"</string>
<string name="translate_options_target_hint">"Translation Language: ^1"</string>
<string name="translate_button_done">"Done"</string>
<string name="translate_never_translate_site">"Never translate this site"</string>
<string name="translate_never_translate_language">"Never translate %1$s"</string>
</resources>


text:
package st.gravel.support.compiler.jvm;

/*
	This file is automatically generated from typed smalltalk source. Do not edit by hand.
	(C) AG5.com
*/

import java.math.BigInteger;
import st.gravel.support.jvm.NonLocalReturn;
import st.gravel.support.compiler.jvm.WhileLoop;
import st.gravel.support.compiler.jvm.WhileLoop.WhileLoop_Factory;
import st.gravel.support.compiler.jvm.JVMStack;
import st.gravel.support.compiler.jvm.JVMInstruction;
import st.gravel.support.compiler.jvm.Frame;
import st.gravel.support.compiler.jvm.JVMType;

public class WhileIntCompLoop extends WhileLoop implements Cloneable {

	public static WhileIntCompLoop_Factory factory = new WhileIntCompLoop_Factory();

	public static class WhileIntCompLoop_Factory extends WhileLoop_Factory {

		public WhileIntCompLoop basicNew() {
			WhileIntCompLoop newInstance = new WhileIntCompLoop();
			newInstance.initialize();
			return newInstance;
		}
	}

	public WhileIntCompLoop copy() {
		try {
			WhileIntCompLoop _temp1 = (WhileIntCompLoop) this.clone();
			_temp1.postCopy();
			return _temp1;
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public JVMInstruction effectStack_(final JVMStack _aJVMStack) {
		super.effectStack_(_aJVMStack);
		st.gravel.support.jvm.ObjectExtensions.assert_(this, st.gravel.support.jvm.IntegerExtensions.equals_(_testFrame.endStack().size(), 2));
		st.gravel.support.jvm.ObjectExtensions.assert_(this, _testFrame.endStack().peek().isIntType());
		st.gravel.support.jvm.ObjectExtensions.assert_(this, _testFrame.endStack().peek_(2).isIntType());
		return this;
	}

	public WhileIntCompLoop_Factory factory() {
		return factory;
	}

	@Override
	public WhileIntCompLoop initializeTestFrame_doFrame_(final Frame _aFrame, final Frame _aFrame2) {
		_testFrame = _aFrame;
		_doFrame = _aFrame2;
		this.initialize();
		return this;
	}

	@Override
	public WhileIntCompLoop printOn_(final StringBuilder _aStream) {
		final String _title;
		_title = this.factory().toString();
		_aStream.append(st.gravel.support.jvm.CharacterExtensions.isVowel(_title.charAt(0)) ? "an " : "a ");
		_aStream.append(_title);
		_aStream.append('[');
		this.sourceOn_(_aStream);
		_aStream.append(']');
		return this;
	}

	@Override
	public WhileIntCompLoop sourceOn_(final StringBuilder _aStream) {
		return this;
	}

	@Override
	public WhileIntCompLoop withReturnType_(final JVMType _aType) {
		if (st.gravel.support.jvm.ObjectExtensions.equals_(this.type(), _aType)) {
			return WhileIntCompLoop.this;
		}
		throw new RuntimeException("niy");
	}
}


text:
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from own.models import TimeBottleModel
import time
import datetime

def index(request):
    return render_to_response("timeBottle/index.html")

def get(request):
    objs = TimeBottleModel.objects.order_by("-id").filter(uid=request.session['user'], targetTime=datetime.date.today())
    if not objs:
        return HttpResponse("")

    r = list()
    for obj in objs:
        data = dict()
        data['content'] = obj.content
        data['createTime'] = obj.createTime.strftime("%Y年%m月%d日 %H时%M分%S秒")

        temp_obj = datetime.date.today() - datetime.datetime.strptime(str(obj.createTime), "%Y-%m-%d %H:%M:%S").date()
        days = temp_obj.days
        if days == 0:
            data['time'] = "今天"
        elif days == 1:
            data['time'] = "昨天"
        elif days == 2:
            data['time'] = "前天"
        else:
            data['time'] = str(days) + "天前"

        r.append(data)

    return render_to_response("timeBottle/get.html", {'objs' : r})

def make(request):
    "制作瓶子"
    if request.method == "GET":
        return render_to_response("timeBottle/make.html")
    else:
        content = request.POST.get('content', None)
        target_time = request.POST.get('targetTime', None)
        obj = TimeBottleModel(content=content, targetTime=target_time, createTime=datetime.datetime.now(), status=0, uid=request.session['user'])
        obj.save()
        return HttpResponseRedirect("/time/")


text:
"""
Run Processes in parallel.
Requires Python 3.5 or greater
"""
import asyncio
import configparser

from TM1py.Services import TM1Service

config = configparser.ConfigParser()
# storing the credentials in a file is not recommended for purposes other than testing.
# it's better to setup CAM with SSO or use keyring to store credentials in the windows credential manager. Sample:
# Samples/credentials_best_practice.py
config.read(r'..\config.ini')

regions = ['DE', 'UK', 'US', 'BE', 'AU', 'JP', 'CN', 'NZ', 'FR', 'PL']
process = 'import_actuals'

# Define Function
def run_process(tm1, region):
    print("run process with parameter pRegion: " + region)
    parameters = {
        'Parameters': [{
            'Name': "pRegion",
            'Value': region
        }]
    }
    tm1.processes.execute(process, parameters)
    print("Done running Process for Region : " + region)

# Fire requests asynchronously
async def main():
    loop = asyncio.get_event_loop()
    # Connect to TM1
    with TM1Service(**config['tm1srv01']) as tm1:
        # Fire of different process executions though 'run_process' function.
        futures = [loop.run_in_executor(None, run_process, tm1, 'pRegion ' + regions[num])
                   for num
                   in range(1, 10)]
        # Await the executions
        for future in futures:
            await future

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


text:
package com.onegravity.rteditor.effects;

import com.onegravity.rteditor.RTEditText;
import com.onegravity.rteditor.fonts.RTTypeface;
import com.onegravity.rteditor.spans.AbsoluteSizeSpan;
import com.onegravity.rteditor.spans.BackgroundColorSpan;
import com.onegravity.rteditor.spans.BoldSpan;
import com.onegravity.rteditor.spans.ForegroundColorSpan;
import com.onegravity.rteditor.spans.ItalicSpan;
import com.onegravity.rteditor.spans.LinkSpan;
import com.onegravity.rteditor.spans.StrikethroughSpan;
import com.onegravity.rteditor.spans.SubscriptSpan;
import com.onegravity.rteditor.spans.SuperscriptSpan;
import com.onegravity.rteditor.spans.TypefaceSpan;
import com.onegravity.rteditor.spans.UnderlineSpan;

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

public class Effects {
    // character effects
    public static final Effect<Boolean, BoldSpan> BOLD = new BoldEffect();                             // boolean effect
    public static final Effect<Boolean, ItalicSpan> ITALIC = new ItalicEffect();                       // boolean effect
    public static final Effect<Boolean, UnderlineSpan> UNDERLINE = new UnderlineEffect();              // boolean effect
    public static final Effect<Boolean, StrikethroughSpan> STRIKETHROUGH = new StrikethroughEffect();  // boolean effect
    public static final Effect<Boolean, SuperscriptSpan> SUPERSCRIPT = new SuperscriptEffect();        // boolean effect
    public static final Effect<Boolean, SubscriptSpan> SUBSCRIPT = new SubscriptEffect();              // boolean effect
    public static final Effect<Integer, AbsoluteSizeSpan> FONTSIZE = new AbsoluteSizeEffect();         // non-boolean effect
    public static final Effect<Integer, ForegroundColorSpan> FONTCOLOR = new ForegroundColorEffect();  // non-boolean effect
    public static final Effect<Integer, BackgroundColorSpan> BGCOLOR = new BackgroundColorEffect();    // non-boolean effect
    public static final Effect<RTTypeface, TypefaceSpan> TYPEFACE = new TypefaceEffect();              // non-boolean effect
    public static final Effect<String, LinkSpan> LINK = new LinkEffect();                              // non-boolean effect

    // paragraph effects
    public static final BulletEffect BULLET = new BulletEffect();                                      // boolean effect
    public static final NumberEffect NUMBER = new NumberEffect();                                      // boolean effect
    public static final IndentationEffect INDENTATION = new IndentationEffect();                       // non-boolean effect
    public static final AlignmentEffect ALIGNMENT = new AlignmentEffect();                             // non-boolean effect

    /*
     * ALL_EFFECTS is a list of all defined effects, for simpler iteration over all effects.
     */
    public static final List<Effect> ALL_EFFECTS = new ArrayList<>();

    static {
        // character effects
        ALL_EFFECTS.add(BOLD);
        ALL_EFFECTS.add(ITALIC);
        ALL_EFFECTS.add(UNDERLINE);
        ALL_EFFECTS.add(STRIKETHROUGH);
        ALL_EFFECTS.add(SUPERSCRIPT);
        ALL_EFFECTS.add(SUBSCRIPT);
        ALL_EFFECTS.add(FONTSIZE);
        ALL_EFFECTS.add(FONTCOLOR);
        ALL_EFFECTS.add(BGCOLOR);
        ALL_EFFECTS.add(TYPEFACE);
        ALL_EFFECTS.add(LINK);

        // paragraph effects
        ALL_EFFECTS.add(BULLET);
        ALL_EFFECTS.add(NUMBER);
        ALL_EFFECTS.add(INDENTATION);
        ALL_EFFECTS.add(ALIGNMENT);
    }

    /*
     * FORMATTING_EFFECTS is a list of all effects which will be removed when the formatting is removed from the text.
     */
    public static final List<Effect> FORMATTING_EFFECTS = new ArrayList<>();

    static {
        // character effects
        FORMATTING_EFFECTS.add(BOLD);
        FORMATTING_EFFECTS.add(ITALIC);
        FORMATTING_EFFECTS.add(UNDERLINE);
        FORMATTING_EFFECTS.add(STRIKETHROUGH);
        FORMATTING_EFFECTS.add(SUPERSCRIPT);
        FORMATTING_EFFECTS.add(SUBSCRIPT);
        FORMATTING_EFFECTS.add(FONTSIZE);
        FORMATTING_EFFECTS.add(FONTCOLOR);
        FORMATTING_EFFECTS.add(BGCOLOR);
        FORMATTING_EFFECTS.add(TYPEFACE);
        FORMATTING_EFFECTS.add(LINK);

        // paragraph effects
        FORMATTING_EFFECTS.add(BULLET);
        FORMATTING_EFFECTS.add(NUMBER);
        FORMATTING_EFFECTS.add(INDENTATION);
        FORMATTING_EFFECTS.add(ALIGNMENT);
    }

    /**
     * This important method makes sure that all paragraph effects are applied to whole paragraphs.
     * While it's optimized for performance it's still an expensive operation so it shouldn't be
     * called too often.
     *
     * @param exclude if an Effect has just been applied, there's no need to cleanup that Effect.
     */
    public static void cleanupParagraphs(RTEditText editor, Effect...exclude) {
        cleanupParagraphs(editor, Effects.ALIGNMENT, exclude);
        cleanupParagraphs(editor, Effects.INDENTATION, exclude);
        cleanupParagraphs(editor, Effects.BULLET, exclude);
        cleanupParagraphs(editor, Effects.NUMBER, exclude);
    }

    private static void cleanupParagraphs(RTEditText editor, ParagraphEffect effect, Effect...exclude) {
        for (Effect e : exclude) {
            if (effect == e) {
                return;
            }
        }

        effect.applyToSelection(editor, null, null);
    }

}


text:
- Attachments! Sandpass now allows you to add and remove files from entries.
  ([#13][])

[#13]: https://github.com/zombiezen/sandpass/issues/13

### Changed
- Sessions are now persistent across grain restarts ([#31][]). This means less
  master password typing for long sessions.
- The passphrase generator word list has changed and is now vendored.
- Builds are now using Go modules and [docker-spk][].

[#31]: https://github.com/zombiezen/sandpass/issues/31
[docker-spk]: https://github.com/zenhack/docker-spk

### Fixed
- Address potential database data loss issue ([#23][])
- Fix bold font rendering issue on ChromeOS.
- Updated Go libraries.

[#23]: https://github.com/zombiezen/sandpass/issues/23

## v1.0.0

* New new icons (thanks again, @neynah. You rock.)
* Search
  * Multi-word searches match individual words instead of literal phrases
  * Searches happen over entry notes, not just titles
  * Show entry's group in results page
* Security Precautions
  * Pages are marked as uncacheable to avoid the user agent potentially storing
    credentials in clear text
  * Disabled autocomplete on entry form fields for similar reasons.
  * Added basic XSRF protection.  Defense in depth here, as Sandstorm protects
    against XSRF attacks anyway.
* Minor visual tweaks

## v1.0.0-rc1

* Features
  * Search (#3)
  * Password generation (#11)
  * Deletion of entries (#5)
  * Deletion of entire database (#8)
  * Moving entities and groups between groups (#15)
  * Creating, editing, and deleting groups (#4)
  * Separate out management role (#18)
* Bug Fixes
  * Preserve attachments in existing KeePass databases (#12)
  * Clear sessions from memory shortly after expiring (#14)

## v0.2.2

* New icon (thanks @neynah)
* Store derived key in sessions instead of password/keyfile (improves request
  performance)
* Security: generate random IV for every write

## v0.2.1

* Basic styling
* Actually bump version number

## v0.2.0

* Allow toggling password visibility
* Direct copy of passwords
* Bypass credentials page if database is not encrypted
* Add breadcrumb navigation
* Update Sandstorm shell paths and titles on page navigation

## v0.1.0

Initial public release.


text:
package installation

import (
	"fmt"

	bosherr "github.com/cloudfoundry/bosh-utils/errors"

	"github.com/cloudfoundry/bosh-init/installation/tarball"
	boshrel "github.com/cloudfoundry/bosh-init/release"
	"github.com/cloudfoundry/bosh-init/release/manifest"
	"github.com/cloudfoundry/bosh-init/ui"
)

type ReleaseFetcher struct {
	tarballProvider tarball.Provider
	releaseReader   boshrel.Reader
	releaseManager  ReleaseManager
}

func NewReleaseFetcher(
	tarballProvider tarball.Provider,
	releaseReader boshrel.Reader,
	releaseManager ReleaseManager,
) ReleaseFetcher {
	return ReleaseFetcher{
		tarballProvider: tarballProvider,
		releaseReader:   releaseReader,
		releaseManager:  releaseManager,
	}
}

func (f ReleaseFetcher) DownloadAndExtract(releaseRef manifest.ReleaseRef, stage ui.Stage) error {
	releasePath, err := f.tarballProvider.Get(releaseRef, stage)
	if err != nil {
		return err
	}

	err = stage.Perform(fmt.Sprintf("Validating release '%s'", releaseRef.Name), func() error {
		release, err := f.releaseReader.Read(releasePath)
		if err != nil {
			return bosherr.WrapErrorf(err, "Extracting release '%s'", releasePath)
		}

		if release.Name() != releaseRef.Name {
			errMsg := "Release name '%s' does not match the name in release tarball '%s'"
			return bosherr.Errorf(errMsg, releaseRef.Name, release.Name())
		}

		f.releaseManager.Add(release)

		return nil
	})

	return err
}


text:
This inspection reports the copying of array contents to a collection where each element
is added individually using a for loop. Such constructs may be replaced by a call to
Collection.addAll(Arrays.asList()).

This inspection provides a quick fix.

Powered by InspectionGadgets


text:
require 'rails_helper'

RSpec.describe Spree::Promotion, type: :model do
  let(:promotion) { Spree::Promotion.new }

  describe "validations" do
    before :each do
      @valid_promotion = Spree::Promotion.new name: "A promotion"
    end

    it "valid_promotion is valid" do
      expect(@valid_promotion).to be_valid
    end

    it "validates usage limit" do
      @valid_promotion.usage_limit = -1
      expect(@valid_promotion).not_to be_valid

      @valid_promotion.usage_limit = 100
      expect(@valid_promotion).to be_valid
    end

    it "validates name" do
      @valid_promotion.name = nil
      expect(@valid_promotion).not_to be_valid
    end
  end

  describe ".applied" do
    it "scopes promotions that have been applied to an order only" do
      promotion = Spree::Promotion.create! name: "test"
      expect(Spree::Promotion.applied).to be_empty

      promotion.orders << create(:order)
      expect(Spree::Promotion.applied.first).to eq promotion
    end
  end

  describe ".advertised" do
    let(:promotion) { create(:promotion) }
    let(:advertised_promotion) { create(:promotion, advertise: true) }

    it "only shows advertised promotions" do
      advertised = Spree::Promotion.advertised
      expect(advertised).to include(advertised_promotion)
      expect(advertised).not_to include(promotion)
    end
  end

  describe ".coupons" do
    let(:promotion_code) { create(:promotion_code) }
    let!(:promotion_with_code) { promotion_code.promotion }
    let!(:another_promotion_code) { create(:promotion_code, promotion: promotion_with_code) }
    let!(:promotion_without_code) { create(:promotion) }

    subject { described_class.coupons }

    it "returns only distinct promotions with a code associated" do
      expect(subject).to eq [promotion_with_code]
    end
  end

  describe "#apply_automatically" do
    subject { build(:promotion) }

    it "defaults to false" do
      expect(subject.apply_automatically).to eq(false)
    end

    context "when set to true" do
      before { subject.apply_automatically = true }

      it "should remain valid" do
        expect(subject).to be_valid
      end

      it "invalidates the promotion when it has a path" do
        subject.path = "foo"
        expect(subject).to_not be_valid
        expect(subject.errors).to include(:apply_automatically)
      end
    end
  end

  describe "#save" do
    let(:promotion) { Spree::Promotion.create(name: "delete me") }

    before(:each) do
      promotion.actions << Spree::Promotion::Actions::CreateAdjustment.new
      promotion.rules << Spree::Promotion::Rules::FirstOrder.new
      promotion.save!
    end

    it "should deeply autosave records and preferences" do
      promotion.actions[0].calculator.preferred_flat_percent = 10
      promotion.save!
      expect(Spree::Calculator.first.preferred_flat_percent).to eq(10)
    end
  end

  describe "#activate" do
    let(:promotion) { create(:promotion) }

    before do
      @action1 = Spree::Promotion::Actions::CreateAdjustment.create!
      @action2 = Spree::Promotion::Actions::CreateAdjustment.create!
      allow(@action1).to receive_messages perform: true
      allow(@action2).to receive_messages perform: true

      promotion.promotion_actions = [@action1, @action2]
      promotion.created_at = 2.days.ago

      @user = create(:user)
      @order = create(:order, user: @user, created_at: Time.current)
      @payload = { order: @order, user: @user }
    end

    it "should check path if present" do
      promotion.path = 'content/cvv'
      @payload[:path] = 'content/cvv'
      expect(@action1).to receive(:perform).with(hash_including(@payload))
      expect(@action2).to receive(:perform).with(hash_including(@payload))
      promotion.activate(@payload)
    end

    it "does not perform actions against an order in a finalized state" do
      expect(@action1).not_to receive(:perform)

      @order.state = 'complete'
      promotion.activate(@payload)

      @order.state = 'awaiting_return'
      promotion.activate(@payload)

      @order.state = 'returned'
      promotion.activate(@payload)
    end

    it "does activate if newer then order" do
      expect(@action1).to receive(:perform).with(hash_including(@payload))
      promotion.created_at = Time.current + 2
      expect(promotion.activate(@payload)).to be true
    end

    context "keeps track of the orders" do
      context "when activated" do
        it "assigns the order" do
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.first).to eql @order
        end

        it 'keeps in-memory associations updated' do
          # load all the relevant associations into memory
          promotion.order_promotions.to_a
          promotion.orders.to_a
          @order.order_promotions.to_a
          @order.promotions.to_a

          expect(promotion.order_promotions.size).to eq(0)
          expect(promotion.orders.size).to eq(0)
          expect(@order.order_promotions.size).to eq(0)
          expect(@order.promotions.size).to eq(0)

          expect(
            promotion.activate(@payload)
          ).to eq(true)

          aggregate_failures do
            expect(promotion.order_promotions.size).to eq(1)
            expect(promotion.orders.size).to eq(1)
            expect(@order.order_promotions.size).to eq(1)
            expect(@order.promotions.size).to eq(1)
          end
        end
      end
      context "when not activated" do
        it "will not assign the order" do
          @order.state = 'complete'
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be_falsey
          expect(promotion.orders).to be_empty
        end
      end
      context "when the order is already associated" do
        before do
          expect(promotion.orders).to be_empty
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.to_a).to eql [@order]
        end

        it "will not assign the order again" do
          expect(promotion.activate(@payload)).to be true
          expect(promotion.orders.reload.to_a).to eql [@order]
        end
      end
    end

    context "when there is a code" do
      let(:promotion_code) { create(:promotion_code) }
      let(:promotion) { promotion_code.promotion }

      it "assigns the code" do
        expect(promotion.activate(order: @order, promotion_code: promotion_code)).to be true
        expect(promotion.order_promotions.map(&:promotion_code)).to eq [promotion_code]
      end
    end
  end

  describe '#remove_from' do
    let(:promotion) { create(:promotion, :with_line_item_adjustment) }
    let(:order) { create(:order_with_line_items) }

    before do
      promotion.activate(order: order)
    end

    it 'removes the promotion' do
      expect(order.promotions).to include(promotion)
      expect(order.line_items.flat_map(&:adjustments)).to be_present

      promotion.remove_from(order)

      expect(order.promotions).to be_empty
      expect(order.line_items.flat_map(&:adjustments)).to be_empty
    end
  end

  describe "#usage_limit_exceeded?" do
    subject { promotion.usage_limit_exceeded? }

    shared_examples "it should" do
      context "when there is a usage limit" do
        context "and the limit is not exceeded" do
          let(:usage_limit) { 10 }
          it { is_expected.to be_falsy }
        end
        context "and the limit is exceeded" do
          let(:usage_limit) { 1 }
          context "on a different order" do
            before do
              FactoryBot.create(
                :completed_order_with_promotion,
                promotion: promotion
              )
              promotion.actions.first.adjustments.update_all(eligible: true)
            end
            it { is_expected.to be_truthy }
          end
          context "on the same order" do
            it { is_expected.to be_falsy }
          end
        end
      end
      context "when there is no usage limit" do
        let(:usage_limit) { nil }
        it { is_expected.to be_falsy }
      end
    end

    context "with an order-level adjustment" do
      let(:promotion) do
        FactoryBot.create(
          :promotion,
          :with_order_adjustment,
          code: "discount",
          usage_limit: usage_limit
        )
      end
      let(:promotable) do
        FactoryBot.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
      end
      it_behaves_like "it should"
    end

    context "with an item-level adjustment" do
      let(:promotion) do
        FactoryBot.create(
          :promotion,
          :with_line_item_adjustment,
          code: "discount",
          usage_limit: usage_limit
        )
      end
      before do
        promotion.actions.first.perform({
          order: order,
          promotion: promotion,
          promotion_code: promotion.codes.first
        })
      end
      context "when there are multiple line items" do
        let(:order) { FactoryBot.create(:order_with_line_items, line_items_count: 2) }
        describe "the first item" do
          let(:promotable) { order.line_items.first }
          it_behaves_like "it should"
        end
        describe "the second item" do
          let(:promotable) { order.line_items.last }
          it_behaves_like "it should"
        end
      end
      context "when there is a single line item" do
        let(:order) { FactoryBot.create(:order_with_line_items) }
        let(:promotable) { order.line_items.first }
        it_behaves_like "it should"
      end
    end
  end

  describe "#usage_count" do
    let(:promotion) do
      FactoryBot.create(
        :promotion,
        :with_order_adjustment,
        code: "discount"
      )
    end

    subject { promotion.usage_count }

    context "when the code is applied to a non-complete order" do
      let(:order) { FactoryBot.create(:order_with_line_items) }
      before { promotion.activate(order: order, promotion_code: promotion.codes.first) }
      it { is_expected.to eq 0 }
    end
    context "when the code is applied to a complete order" do
      let!(:order) do
        FactoryBot.create(
          :completed_order_with_promotion,
          promotion: promotion
        )
      end
      context "and the promo is eligible" do
        it { is_expected.to eq 1 }
      end
      context "and the promo is ineligible" do
        before { order.adjustments.promotion.update_all(eligible: false) }
        it { is_expected.to eq 0 }
      end
    end
  end

  context "#inactive" do
    it "should not be exipired" do
      expect(promotion).not_to be_inactive
    end

    it "should be inactive if it hasn't started yet" do
      promotion.starts_at = Time.current + 1.day
      expect(promotion).to be_inactive
    end

    it "should be inactive if it has already ended" do
      promotion.expires_at = Time.current - 1.day
      expect(promotion).to be_inactive
    end

    it "should not be inactive if it has started already" do
      promotion.starts_at = Time.current - 1.day
      expect(promotion).not_to be_inactive
    end

    it "should not be inactive if it has not ended yet" do
      promotion.expires_at = Time.current + 1.day
      expect(promotion).not_to be_inactive
    end

    it "should not be inactive if current time is within starts_at and expires_at range" do
      promotion.starts_at = Time.current - 1.day
      promotion.expires_at = Time.current + 1.day
      expect(promotion).not_to be_inactive
    end
  end

  describe '#not_started?' do
    let(:promotion) { Spree::Promotion.new(starts_at: starts_at) }
    subject { promotion.not_started? }

    context 'no starts_at date' do
      let(:starts_at) { nil }
      it { is_expected.to be_falsey }
    end

    context 'when starts_at date is in the past' do
      let(:starts_at) { Time.current - 1.day }
      it { is_expected.to be_falsey }
    end

    context 'when starts_at date is not already reached' do
      let(:starts_at) { Time.current + 1.day }
      it { is_expected.to be_truthy }
    end
  end

  describe '#started?' do
    let(:promotion) { Spree::Promotion.new(starts_at: starts_at) }
    subject { promotion.started? }

    context 'when no starts_at date' do
      let(:starts_at) { nil }
      it { is_expected.to be_truthy }
    end

    context 'when starts_at date is in the past' do
      let(:starts_at) { Time.current - 1.day }
      it { is_expected.to be_truthy }
    end

    context 'when starts_at date is not already reached' do
      let(:starts_at) { Time.current + 1.day }
      it { is_expected.to be_falsey }
    end
  end

  describe '#expired?' do
    let(:promotion) { Spree::Promotion.new(expires_at: expires_at) }
    subject { promotion.expired? }

    context 'when no expires_at date' do
      let(:expires_at) { nil }
      it { is_expected.to be_falsey }
    end

    context 'when expires_at date is not already reached' do
      let(:expires_at) { Time.current + 1.day }
      it { is_expected.to be_falsey }
    end

    context 'when expires_at date is in the past' do
      let(:expires_at) { Time.current - 1.day }
      it { is_expected.to be_truthy }
    end
  end

  describe '#not_expired?' do
    let(:promotion) { Spree::Promotion.new(expires_at: expires_at) }
    subject { promotion.not_expired? }

    context 'when no expired_at date' do
      let(:expires_at) { nil }
      it { is_expected.to be_truthy }
    end

    context 'when expires_at date is not already reached' do
      let(:expires_at) { Time.current + 1.day }
      it { is_expected.to be_truthy }
    end

    context 'when expires_at date is in the past' do
      let(:expires_at) { Time.current - 1.day }
      it { is_expected.to be_falsey }
    end
  end

  context "#active" do
    it "should be active" do
      expect(promotion.active?).to eq(true)
    end

    it "should not be active if it hasn't started yet" do
      promotion.starts_at = Time.current + 1.day
      expect(promotion.active?).to eq(false)
    end

    it "should not be active if it has already ended" do
      promotion.expires_at = Time.current - 1.day
      expect(promotion.active?).to eq(false)
    end

    it "should be active if it has started already" do
      promotion.starts_at = Time.current - 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if it has not ended yet" do
      promotion.expires_at = Time.current + 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if current time is within starts_at and expires_at range" do
      promotion.starts_at = Time.current - 1.day
      promotion.expires_at = Time.current + 1.day
      expect(promotion.active?).to eq(true)
    end

    it "should be active if there are no start and end times set" do
      promotion.starts_at = nil
      promotion.expires_at = nil
      expect(promotion.active?).to eq(true)
    end
  end

  context "#usage_count" do
    let!(:promotion) do
      create(
        :promotion,
        name: "Foo",
        code: "XXX"
      )
    end

    let!(:action) do
      calculator = Spree::Calculator::FlatRate.new
      action_params = { promotion: promotion, calculator: calculator }
      action = Spree::Promotion::Actions::CreateAdjustment.create(action_params)
      promotion.actions << action
      action
    end

    let!(:adjustment) do
      order = create(:order)
      Spree::Adjustment.create!(
        order:      order,
        adjustable: order,
        source:     action,
        promotion_code: promotion.codes.first,
        amount:     10,
        label:      'Promotional adjustment'
      )
    end

    it "counts eligible adjustments" do
      adjustment.update_column(:eligible, true)
      expect(promotion.usage_count).to eq(0)
    end

    # Regression test for https://github.com/spree/spree/issues/4112
    it "does not count ineligible adjustments" do
      adjustment.update_column(:eligible, false)
      expect(promotion.usage_count).to eq(0)
    end
  end

  context "#products" do
    let(:promotion) { create(:promotion) }

    context "when it has product rules with products associated" do
      let(:promotion_rule) { Spree::Promotion::Rules::Product.new }

      before do
        promotion_rule.promotion = promotion
        promotion_rule.products << create(:product)
        promotion_rule.save
      end

      it "should have products" do
        expect(promotion.reload.products.size).to eq(1)
      end
    end

    context "when there's no product rule associated" do
      it "should not have products but still return an empty array" do
        expect(promotion.products).to be_blank
      end
    end
  end

  context "#eligible?" do
    subject do
      promotion.eligible?(promotable, promotion_code: promotion.codes.first)
    end

    shared_examples "a promotable" do
      context "when empty" do
        it { is_expected.to be true }
      end

      context "when promotion is expired" do
        before { promotion.expires_at = Time.current - 10.days }

        it { is_expected.to be false }
      end

      context "when promotion's usage limit is exceeded" do
        before do
          promotion.usage_limit = 1
          create(:completed_order_with_promotion, promotion: promotion)
        end

        it { is_expected.to be false }
      end

      context "when promotion code's usage limit is exceeded" do
        before do
          promotion.per_code_usage_limit = 1
          create(:completed_order_with_promotion, promotion: promotion)
          promotion.codes.first.adjustments.update_all(eligible: true)
        end

        it { is_expected.to be false }
      end

      context "when promotion is at last usage on the same order" do
        let(:order) { create(:completed_order_with_promotion, promotion: promotion) }
        let(:promotable) { order }

        before do
          promotion.usage_limit = 1
        end

        it { is_expected.to be true }
      end

      context "when promotion code is at last usage on the same order" do
        let(:order) { create(:completed_order_with_promotion, promotion: promotion) }
        let(:promotable) { order }

        before do
          promotion.per_code_usage_limit = 1
        end

        it { is_expected.to be true }
      end
    end

    context "when promotable is a Spree::Order" do
      let(:promotion) { create(:promotion, :with_order_adjustment) }
      let(:promotable) { create :order }

      it_behaves_like "a promotable"

      context "when it contains items" do
        let!(:line_item) { create(:line_item, order: promotable) }
        let!(:line_item2) { create(:line_item, order: promotable) }

        context "and at least one item is non-promotionable" do
          before do
            line_item.product.update_column(:promotionable, false)
          end

          it { is_expected.to be false }
        end

        context "and the items are all non-promotionable" do
          before do
            line_item.product.update_column(:promotionable, false)
            line_item2.product.update_column(:promotionable, false)
          end

          it { is_expected.to be false }
        end

        context "and at least one item is promotionable" do
          it { is_expected.to be true }
        end
      end
    end

    context "when promotable is a Spree::LineItem" do
      let(:promotion) { create(:promotion, :with_line_item_adjustment) }
      let(:promotable) { create(:line_item) }

      it_behaves_like "a promotable"

      context "and product is promotionable" do
        before { promotable.product.promotionable = true }

        it { is_expected.to be true }
      end

      context "and product is not promotionable" do
        before { promotable.product.promotionable = false }

        it { is_expected.to be false }
      end
    end

    context "when promotable is a Spree::Shipment" do
      let(:promotion) { create(:promotion, :with_free_shipping) }
      let(:promotable) { create(:shipment) }

      it_behaves_like "a promotable"
    end
  end

  context "#eligible_rules" do
    let(:promotable) { double('Promotable') }
    it "true if there are no rules" do
      expect(promotion.eligible_rules(promotable)).to eq []
    end

    it "true if there are no applicable rules" do
      promotion.promotion_rules = [stub_model(Spree::PromotionRule, eligible?: true, applicable?: false)]
      allow(promotion.promotion_rules).to receive(:for).and_return([])
      expect(promotion.eligible_rules(promotable)).to eq []
    end

    context "with 'all' match policy" do
      let(:rule1) { Spree::PromotionRule.create!(promotion: promotion) }
      let(:rule2) { Spree::PromotionRule.create!(promotion: promotion) }

      before { promotion.match_policy = 'all' }

      context "when all rules are eligible" do
        before do
          allow(rule1).to receive_messages(eligible?: true, applicable?: true)
          allow(rule2).to receive_messages(eligible?: true, applicable?: true)

          promotion.promotion_rules = [rule1, rule2]
          allow(promotion).to receive_message_chain(:rules, :none?).and_return(false)
          allow(promotion).to receive_message_chain(:rules, :for).and_return(promotion.promotion_rules)
        end
        it "returns the eligible rules" do
          expect(promotion.eligible_rules(promotable)).to eq [rule1, rule2]
        end
        it "does set anything to eligiblity errors" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to be_nil
        end
      end

      context "when any of the rules is not eligible" do
        let(:errors) { double ActiveModel::Errors, empty?: false }
        before do
          allow(rule1).to receive_messages(eligible?: true, applicable?: true, eligibility_errors: nil)
          allow(rule2).to receive_messages(eligible?: false, applicable?: true, eligibility_errors: errors)

          promotion.promotion_rules = [rule1, rule2]
          allow(promotion).to receive_message_chain(:rules, :none?).and_return(false)
          allow(promotion).to receive_message_chain(:rules, :for).and_return(promotion.promotion_rules)
        end
        it "returns nil" do
          expect(promotion.eligible_rules(promotable)).to be_nil
        end
        it "sets eligibility errors to the first non-nil one" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to eq errors
        end
      end
    end

    context "with 'any' match policy" do
      let(:promotable) { double('Promotable') }

      before do
        promotion.match_policy = 'any'
      end

      it "should have eligible rules if any of the rules are eligible" do
        true_rule = mock_model(Spree::PromotionRule, eligible?: true, applicable?: true)
        promotion.promotion_rules = [true_rule]
        allow(promotion.rules).to receive(:for) { promotion.rules }
        expect(promotion.eligible_rules(promotable)).to eq [true_rule]
      end

      context "when none of the rules are eligible" do
        let(:rule) { Spree::PromotionRule.create!(promotion: promotion) }
        let(:errors) { double ActiveModel::Errors, empty?: false }
        before do
          allow(rule).to receive_messages(eligible?: false, applicable?: true, eligibility_errors: errors)

          promotion.promotion_rules = [rule]
          allow(promotion).to receive_message_chain(:rules, :for).and_return(promotion.promotion_rules)
          allow(promotion).to receive_message_chain(:rules, :none?).and_return(false)
        end
        it "returns nil" do
          expect(promotion.eligible_rules(promotable)).to be_nil
        end
        it "sets eligibility errors to the first non-nil one" do
          promotion.eligible_rules(promotable)
          expect(promotion.eligibility_errors).to eq errors
        end
      end
    end
  end

  describe '#line_item_actionable?' do
    let(:order) { double Spree::Order }
    let(:line_item) { double Spree::LineItem }
    let(:true_rule) { mock_model Spree::PromotionRule, eligible?: true, applicable?: true, actionable?: true }
    let(:false_rule) { mock_model Spree::PromotionRule, eligible?: true, applicable?: true, actionable?: false }
    let(:rules) { [] }

    before do
      promotion.promotion_rules = rules
      allow(promotion.rules).to receive(:for) { rules }
    end

    subject { promotion.line_item_actionable? order, line_item }

    context 'when the order is eligible for promotion' do
      context 'when there are no rules' do
        it { is_expected.to be }
      end

      context 'when there are rules' do
        context 'when the match policy is all' do
          before { promotion.match_policy = 'all' }

          context 'when all rules allow action on the line item' do
            let(:rules) { [true_rule] }
            it { is_expected.to be }
          end

          context 'when at least one rule does not allow action on the line item' do
            let(:rules) { [true_rule, false_rule] }
            it { is_expected.not_to be }
          end
        end

        context 'when the match policy is any' do
          before { promotion.match_policy = 'any' }

          context 'when at least one rule allows action on the line item' do
            let(:rules) { [true_rule, false_rule] }
            it { is_expected.to be }
          end

          context 'when no rules allow action on the line item' do
            let(:rules) { [false_rule] }
            it { is_expected.not_to be }
          end
        end

        context 'when the line item has an non-promotionable product' do
          let(:rules) { [true_rule] }
          let(:line_item) { build(:line_item) { |li| li.product.promotionable = false } }
          it { is_expected.not_to be }
        end
      end
    end

    context 'when the order is not eligible for the promotion' do
      context "due to promotion expiration" do
        before { promotion.starts_at = Time.current + 2.days }
        it { is_expected.not_to be }
      end

      context "due to promotion code not being eligible" do
        let(:order) { create(:order) }
        let(:promotion) { create(:promotion, per_code_usage_limit: 0) }
        let(:promotion_code) { create(:promotion_code, promotion: promotion) }

        subject { promotion.line_item_actionable? order, line_item, promotion_code: promotion_code }

        it "returns false" do
          expect(subject).to eq false
        end
      end
    end
  end

  # regression for https://github.com/spree/spree/issues/4059
  # admin form posts the code and path as empty string
  describe "normalize blank values for path" do
    it "will save blank value as nil value instead" do
      promotion = Spree::Promotion.create(name: "A promotion", path: "")
      expect(promotion.path).to be_nil
    end
  end

  describe '#used_by?' do
    subject { promotion.used_by? user, [excluded_order] }

    let(:promotion) { create :promotion, :with_order_adjustment }
    let(:user) { create :user }
    let(:order) { create :order_with_line_items, user: user }
    let(:excluded_order) { create :order_with_line_items, user: user }

    before do
      order.user_id = user.id
      order.save!
    end

    context 'when the user has used this promo' do
      before do
        promotion.activate(order: order)
        order.recalculate
        order.completed_at = Time.current
        order.save!
      end

      context 'when the order is complete' do
        it { is_expected.to be true }

        context 'when the promotion was not eligible' do
          let(:adjustment) { order.adjustments.first }

          before do
            adjustment.eligible = false
            adjustment.save!
          end

          it { is_expected.to be false }
        end

        context 'when the only matching order is the excluded order' do
          let(:excluded_order) { order }
          it { is_expected.to be false }
        end
      end

      context 'when the order is not complete' do
        let(:order) { create :order, user: user }

        # The before clause above sets the completed at
        # value for this order
        before { order.update completed_at: nil }

        it { is_expected.to be false }
      end
    end

    context 'when the user has not used this promo' do
      it { is_expected.to be false }
    end
  end

  describe "adding items to the cart" do
    let(:order) { create :order }
    let(:line_item) { create :line_item, order: order }
    let(:promo) { create :promotion_with_item_adjustment, adjustment_rate: 5, code: 'promo' }
    let(:promotion_code) { promo.codes.first }
    let(:variant) { create :variant }

    it "updates the promotions for new line items" do
      expect(line_item.adjustments).to be_empty
      expect(order.adjustment_total).to eq 0

      promo.activate order: order, promotion_code: promotion_code
      order.recalculate

      expect(line_item.adjustments.size).to eq(1)
      expect(order.adjustment_total).to eq(-5)

      other_line_item = order.contents.add(variant, 1, currency: order.currency)

      expect(other_line_item).not_to eq line_item
      expect(other_line_item.adjustments.size).to eq(1)
      expect(order.adjustment_total).to eq(-10)
    end
  end
end


text:
INCLUDE(SetDefault)
INCLUDE(PrintVar)

#
# @MACRO: SET_DEFAULT_AND_FROM_ENV()
#
# Set a default value for a local variable and override from an environment
# variable of the same name if it is set.
#
# Usage::
#
#   SET_DEFAULT_AND_FROM_ENV(<varName> <defaultVal>)
#
# First calls ``SET_DEFAULT(<varName> <defaultVal>)`` and then looks for an
# environment variable named ``<varName>``, and if non-empty then overrides
# the value of the local variable ``<varName>``.
#
# This macro is primarily used in CTest code to provide a way to pass in the
# value of CMake variables.  Older versions of ``ctest`` did not support the
# option ``-D <var>:<type>=<value>`` to allow variables to be set through the
# command-line like ``cmake`` always allowed.
#
MACRO(SET_DEFAULT_AND_FROM_ENV  VAR  DEFAULT_VAL)

  SET_DEFAULT(${VAR} "${DEFAULT_VAL}")

  SET(ENV_${VAR} $ENV{${VAR}})
  IF (NOT "${ENV_${VAR}}" STREQUAL "")
    PRINT_VAR(ENV_${VAR})
    SET(${VAR} ${ENV_${VAR}})
  ENDIF()

  PRINT_VAR(${VAR})

ENDMACRO()


text:
package org.compass.gps.device.jpa.embedded.toplink;

import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import oracle.toplink.essentials.sessions.Session;
import oracle.toplink.essentials.sessions.SessionEvent;
import oracle.toplink.essentials.sessions.SessionEventAdapter;
import oracle.toplink.essentials.sessions.UnitOfWork;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.compass.core.Compass;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.gps.device.jpa.embedded.JpaCompassGps;

/**
 * A TopLink SessionEventListener that uses the transaction callback methods
 * to sync between them and Compass transaction mechanism.
 *
 * @author kimchy
 */
public class CompassSessionEventListener extends SessionEventAdapter {

    private static final Log log = LogFactory.getLog(CompassSessionEventListener.class);

    private Compass compass;

    private JpaCompassGps jpaCompassGps;

    private Properties indexSettings;

    private boolean commitBeforeCompletion;

    private boolean toplinkControlledTransaction;

    private ConcurrentHashMap<Session, CompassSessionHolder> sessionsHolders = new ConcurrentHashMap<Session, CompassSessionHolder>();

    public CompassSessionEventListener(Compass compass, JpaCompassGps jpaCompassGps,
                                       boolean commitBeforeCompletion, boolean toplinkControlledTransaction,
                                       Properties indexSettings) {
        this.compass = compass;
        this.jpaCompassGps = jpaCompassGps;
        this.commitBeforeCompletion = commitBeforeCompletion;
        this.toplinkControlledTransaction = toplinkControlledTransaction;
        this.indexSettings = indexSettings;
    }

    public Compass getCompass() {
        return compass;
    }

    public JpaCompassGps getJpaCompassGps() {
        return jpaCompassGps;
    }

    public Properties getIndexSettings() {
        return indexSettings;
    }

    public CompassSession getCurrentCompassSession(Session session) {
        if (session.isUnitOfWork()) {
            Session parentSession = ((UnitOfWork) session).getParent();
            CompassSessionHolder sessionHolder = sessionsHolders.get(parentSession);
            if (sessionHolder != null) {
                return sessionHolder.session;
            } else {
                return beginCompassSessionAndTx(parentSession).session;
            }
        } else {
            CompassSessionHolder sessionHolder = sessionsHolders.get(session);
            if (sessionHolder != null) {
                return sessionHolder.session;
            } else {
                return beginCompassSessionAndTx(session).session;
            }
        }
    }

    public void postBeginTransaction(SessionEvent event) {
        Session session = findSession(event);
        beginCompassSessionAndTx(session);
    }

    public void preCommitTransaction(SessionEvent event) {
        if (commitBeforeCompletion) {
            commit(findSession(event));
        }
    }

    public void postCommitTransaction(SessionEvent event) {
        if (!commitBeforeCompletion) {
            commit(findSession(event));
        }
    }

    public void postRollbackTransaction(SessionEvent event) {
        rollback(findSession(event));
    }

    private CompassSessionHolder beginCompassSessionAndTx(Session session) {
        CompassSession compassSession = compass.openSession();
        CompassTransaction tr = compassSession.beginTransaction();
        CompassSessionHolder sessionHolder = new CompassSessionHolder(compassSession, tr);
        sessionsHolders.put(session, sessionHolder);
        return sessionHolder;
    }

    private void commit(Session session) {
        CompassSessionHolder holder = sessionsHolders.remove(session);
        if (toplinkControlledTransaction) {
            try {
                holder.tr.commit();
            } finally {
                holder.session.close();
            }
        }
    }

    private void rollback(Session session) {
        CompassSessionHolder holder = sessionsHolders.remove(session);
        if (holder == null) {
            return;
        }
        if (toplinkControlledTransaction) {
            try {
                holder.tr.rollback();
            } finally {
                holder.session.close();
            }
        }
    }

    private Session findSession(SessionEvent event) {
        return event.getSession();
    }

    protected void finalize() throws Throwable {
        super.finalize();
        //TODO: is there a better place to close this?
        if (log.isInfoEnabled()) {
            log.info("Compass embedded TopLink shutting down");
        }
        if (jpaCompassGps.isRunning()) {
            jpaCompassGps.stop();
        }
        compass.close();
    }

    private class CompassSessionHolder {

        CompassSession session;

        CompassTransaction tr;

        public CompassSessionHolder(CompassSession session, CompassTransaction tr) {
            this.session = session;
            this.tr = tr;
        }
    }
}


text:
namespace base {
class Value;
class CommandLine;
}  // namespace base

// A collection of functions designed for use with unit and browser tests.

namespace content {

class RenderFrameHost;
class TestServiceManagerContext;

// Turns on nestable tasks, runs the message loop, then resets nestable tasks
// to what they were originally. Prefer this over MessageLoop::Run for in
// process browser tests that need to block until a condition is met.
void RunMessageLoop();

// Variant of RunMessageLoop that takes RunLoop.
void RunThisRunLoop(base::RunLoop* run_loop);

// Turns on nestable tasks, runs all pending tasks in the message loop,
// then resets nestable tasks to what they were originally. Prefer this
// over MessageLoop::RunAllPending for in process browser tests to run
// all pending tasks. Can only be called from the UI thread.
void RunAllPendingInMessageLoop();

// Blocks the current thread until all the pending messages in the loop of the
// thread |thread_id| have been processed. Can only be called from the UI
// thread.
void RunAllPendingInMessageLoop(BrowserThread::ID thread_id);

// Runs until both the blocking pool and the current message loop are empty
// (have no more scheduled tasks) and no tasks are running.
void RunAllBlockingPoolTasksUntilIdle();

// Get task to quit the given RunLoop. It allows a few generations of pending
// tasks to run as opposed to run_loop->QuitClosure().
base::Closure GetQuitTaskForRunLoop(base::RunLoop* run_loop);

// Executes the specified JavaScript in the specified frame, and runs a nested
// MessageLoop. When the result is available, it is returned.
// This should not be used; the use of the ExecuteScript functions in
// browser_test_utils is preferable.
std::unique_ptr<base::Value> ExecuteScriptAndGetValue(
    RenderFrameHost* render_frame_host,
    const std::string& script);

// Returns true if all sites are isolated. Typically used to bail from a test
// that is incompatible with --site-per-process.
bool AreAllSitesIsolatedForTesting();

// Appends --site-per-process to the command line, enabling tests to exercise
// site isolation and cross-process iframes. This must be called early in
// the test; the flag will be read on the first real navigation.
void IsolateAllSitesForTesting(base::CommandLine* command_line);

#if defined(OS_ANDROID)
// Registers content/browser JNI bindings necessary for some types of tests.
bool RegisterJniForTesting(JNIEnv* env);
#endif

// Helper class to Run and Quit the message loop. Run and Quit can only happen
// once per instance. Make a new instance for each use. Calling Quit after Run
// has returned is safe and has no effect.
class MessageLoopRunner : public base::RefCounted<MessageLoopRunner> {
 public:
  MessageLoopRunner();

  // Run the current MessageLoop unless the quit closure
  // has already been called.
  void Run();

  // Quit the matching call to Run (nested MessageLoops are unaffected).
  void Quit();

  // Hand this closure off to code that uses callbacks to notify completion.
  // Example:
  //   scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner;
  //   kick_off_some_api(runner->QuitClosure());
  //   runner->Run();
  base::Closure QuitClosure();

  bool loop_running() const { return loop_running_; }

 private:
  friend class base::RefCounted<MessageLoopRunner>;
  ~MessageLoopRunner();

  // True when the message loop is running.
  bool loop_running_;

  // True after closure returned by |QuitClosure| has been called.
  bool quit_closure_called_;

  base::RunLoop run_loop_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(MessageLoopRunner);
};

// A WindowedNotificationObserver allows code to wait until a condition is met.
// Simple conditions are specified by providing a |notification_type| and a
// |source|. When a notification of the expected type from the expected source
// is received, the condition is met.
// More complex conditions can be specified by providing a |notification_type|
// and a |callback|. The callback is called whenever the notification is fired.
// If the callback returns |true|, the condition is met. Otherwise, the
// condition is not yet met and the callback will be invoked again every time a
// notification of the expected type is received until the callback returns
// |true|. For convenience, two callback types are defined, one that is provided
// with the notification source and details, and one that is not.
//
// This helper class exists to avoid the following common pattern in tests:
//   PerformAction()
//   WaitForCompletionNotification()
// The pattern leads to flakiness as there is a window between PerformAction
// returning and the observers getting registered, where a notification will be
// missed.
//
// Rather, one can do this:
//   WindowedNotificationObserver signal(...)
//   PerformAction()
//   signal.Wait()
class WindowedNotificationObserver : public NotificationObserver {
 public:
  // Callback invoked on notifications. Should return |true| when the condition
  // being waited for is met. For convenience, there is a choice between two
  // callback types, one that is provided with the notification source and
  // details, and one that is not.
  typedef base::Callback<bool(const NotificationSource&,
                              const NotificationDetails&)>
      ConditionTestCallback;
  typedef base::Callback<bool(void)>
      ConditionTestCallbackWithoutSourceAndDetails;

  // Set up to wait for a simple condition. The condition is met when a
  // notification of the given |notification_type| from the given |source| is
  // received. To accept notifications from all sources, specify
  // NotificationService::AllSources() as |source|.
  WindowedNotificationObserver(int notification_type,
                               const NotificationSource& source);

  // Set up to wait for a complex condition. The condition is met when
  // |callback| returns |true|. The callback is invoked whenever a notification
  // of |notification_type| from any source is received.
  WindowedNotificationObserver(int notification_type,
                               const ConditionTestCallback& callback);
  WindowedNotificationObserver(
      int notification_type,
      const ConditionTestCallbackWithoutSourceAndDetails& callback);

  ~WindowedNotificationObserver() override;

  // Adds an additional notification type to wait for. The condition will be met
  // if any of the registered notification types from their respective sources
  // is received.
  void AddNotificationType(int notification_type,
                           const NotificationSource& source);

  // Wait until the specified condition is met. If the condition is already met
  // (that is, the expected notification has already been received or the
  // given callback returns |true| already), Wait() returns immediately.
  void Wait();

  // Returns NotificationService::AllSources() if we haven't observed a
  // notification yet.
  const NotificationSource& source() const {
    return source_;
  }

  const NotificationDetails& details() const {
    return details_;
  }

  // NotificationObserver:
  void Observe(int type,
               const NotificationSource& source,
               const NotificationDetails& details) override;

 private:
  bool seen_;
  bool running_;
  NotificationRegistrar registrar_;

  ConditionTestCallback callback_;

  NotificationSource source_;
  NotificationDetails details_;
  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(WindowedNotificationObserver);
};

// Unit tests can use code which runs in the utility process by having it run on
// an in-process utility thread. This eliminates having two code paths in
// production code to deal with unit tests, and also helps with the binary
// separation on Windows since chrome.dll doesn't need to call into Blink code
// for some utility code to handle the single process case.
// Include this class as a member variable in your test harness if you take
// advantage of this functionality to ensure that the in-process utility thread
// is torn down correctly. See http://crbug.com/316919 for more information.
// Note: this class should be declared after the TestBrowserThreadBundle and
// ShadowingAtExitManager (if it exists) as it will need to be run before they
// are torn down.
class InProcessUtilityThreadHelper : public BrowserChildProcessObserver {
 public:
  InProcessUtilityThreadHelper();
  ~InProcessUtilityThreadHelper() override;

 private:
  void BrowserChildProcessHostConnected(const ChildProcessData& data) override;
  void BrowserChildProcessHostDisconnected(
      const ChildProcessData& data) override;

  int child_thread_count_;
  scoped_refptr<MessageLoopRunner> runner_;
  std::unique_ptr<TestServiceManagerContext> shell_context_;

  DISALLOW_COPY_AND_ASSIGN(InProcessUtilityThreadHelper);
};

// This observer keeps track of the last deleted RenderFrame to avoid
// accessing it and causing use-after-free condition.
class RenderFrameDeletedObserver : public WebContentsObserver {
 public:
  RenderFrameDeletedObserver(RenderFrameHost* rfh);
  ~RenderFrameDeletedObserver() override;

  // Overridden WebContentsObserver methods.
  void RenderFrameDeleted(RenderFrameHost* render_frame_host) override;

  void WaitUntilDeleted();
  bool deleted();

 private:
  int process_id_;
  int routing_id_;
  bool deleted_;
  std::unique_ptr<base::RunLoop> runner_;

  DISALLOW_COPY_AND_ASSIGN(RenderFrameDeletedObserver);
};

// Watches a WebContents and blocks until it is destroyed.
class WebContentsDestroyedWatcher : public WebContentsObserver {
 public:
  explicit WebContentsDestroyedWatcher(WebContents* web_contents);
  ~WebContentsDestroyedWatcher() override;

  // Waits until the WebContents is destroyed.
  void Wait();

 private:
  // Overridden WebContentsObserver methods.
  void WebContentsDestroyed() override;

  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(WebContentsDestroyedWatcher);
};

}  // namespace content

#endif  // CONTENT_PUBLIC_TEST_TEST_UTILS_H_


text:
package edu.northwestern.bioinformatics.studycalendar.domain;

import junit.framework.TestCase;

/**
 * @author Rhett Sutphin
 */
public class SiteTest extends TestCase {
    private Site site;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        site = new Site();
    }

    public void testGetStudySiteForUnaffiliatedStudy() throws Exception {
        Study s2 = Fixtures.createSingleEpochStudy("S2", "E");
        site.addStudySite(Fixtures.createStudySite(Fixtures.createSingleEpochStudy("S3", "E"), site));
        site.addStudySite(Fixtures.createStudySite(Fixtures.createSingleEpochStudy("S4", "E"), site));

        assertNull(site.getStudySite(s2));
    }

    public void testAssignedIdentifierDefaultsToName() throws Exception {
        site.setName("arb");
        site.setAssignedIdentifier(null);
        assertEquals("arb", site.getAssignedIdentifier());
    }

    public void testExplicitAssignedIdentifierTrumps() throws Exception {
        site.setName("foo");
        site.setAssignedIdentifier("bar");
        assertEquals("bar", site.getAssignedIdentifier());
    }

    public void testGetStudySiteForAffiliatedStudy() throws Exception {
        Study s3 = Fixtures.createSingleEpochStudy("S3", "E");
        site.addStudySite(Fixtures.createStudySite(s3, site));
        site.addStudySite(Fixtures.createStudySite(Fixtures.createSingleEpochStudy("S4", "E"), site));

        assertNotNull(site.getStudySite(s3));
        assertSame(s3, site.getStudySite(s3).getStudy());
        assertSame(site, site.getStudySite(s3).getSite());
    }

    public void testAddManagedStudyAddsTheStudy() throws Exception {
        Study s = new Study();
        site.addManagedStudy(s);
        assertTrue(site.getManagedStudies().contains(s));
    }

    public void testAddManagedStudyMaintainsTheBidirectionalRelationship() throws Exception {
        Study s = new Study();
        site.addManagedStudy(s);
        assertTrue(s.getManagingSites().contains(site));
    }

    public void testRemoveManagedStudyRemovesTheStudy() throws Exception {
        Study s = new Study();
        site.addManagedStudy(s);
        site.removeManagedStudy(s);
        assertFalse(site.getManagedStudies().contains(s));
    }

    public void testAddManagedStudyRemovesTheBidirectionalRelationship() throws Exception {
        Study s = new Study();
        site.addManagedStudy(s);
        site.removeManagedStudy(s);
        assertFalse(s.getManagingSites().contains(site));
    }

    public void testToString() throws Exception {
        site.setId(49);
        site.setName("An Area");
        site.setAssignedIdentifier("51");
        assertEquals("Wrong string rep",
            "Site[id=49; name=An Area; assignedIdentifier=51]",
            site.toString());
    }

    public void testIsNameEditableWithoutProvider() {
        assertTrue("Should be editable", site.isNameEditable());
    }

    public void testIsNameEditableWithProvider() {
        site.setProvider("orb");
        assertFalse("Should not be editable", site.isNameEditable());
    }

    public void testIsAssignedIdentifierEditableWithoutProvider() {
        assertTrue("Should be editable", site.isAssignedIdentifierEditable());
    }

    public void testIsAssignedIdentifierEditableWithProvider() {
        site.setProvider("orb");
        assertFalse("Should not be editable", site.isAssignedIdentifierEditable());
    }
}


text:
#ifndef FSLUTIL_##NAMESPACE_NAME!##_EXCEPTIONS_HPP
#define FSLUTIL_##NAMESPACE_NAME!##_EXCEPTIONS_HPP

// ##AG_TOOL_STATEMENT##
// Auto generation template based on RapidVulkan https://github.com/Unarmed1000/RapidVulkan with permission.

#include <FslGraphics/Exceptions.hpp>
#include <string>
#include <vulkan/vulkan.h>

namespace Fsl
{
  namespace Vulkan
  {
    class VulkanException : public std::runtime_error
    {
      std::string m_fileName;
      int m_lineNumber;
    public:
      explicit VulkanException(const std::string& whatArg)
        : std::runtime_error(whatArg)
        , m_fileName()
        , m_lineNumber(0)
      {
      }

      explicit VulkanException(const std::string& whatArg, const std::string& fileName, const int lineNumber)
        : std::runtime_error(whatArg)
        , m_fileName(fileName)
        , m_lineNumber(lineNumber)
      {
      }

      std::string GetFileName() const
      {
        return m_fileName;
      }

      int GetLineNumber() const
      {
        return m_lineNumber;
      }
    };

    class VulkanErrorException : public VulkanException
    {
      VkResult m_result;
    public:
      explicit VulkanErrorException(const std::string& whatArg, const VkResult result)
        : VulkanException(whatArg)
        , m_result(result)
      {
      }

      explicit VulkanErrorException(const std::string& whatArg, const VkResult result, const std::string& fileName, const int lineNumber)
        : VulkanException(whatArg, fileName, lineNumber)
        , m_result(result)
      {
      }

      VkResult GetResult() const
      {
        return m_result;
      }
    };

    class UnsupportedVulkanPixelFormatException : public VulkanException
    {
      VkFormat m_pixelFormat;
    public:
      UnsupportedVulkanPixelFormatException(const std::string& str, const VkFormat pixelFormat)
        : VulkanException(str)
        , m_pixelFormat(pixelFormat)
      {
      }

      UnsupportedVulkanPixelFormatException(const VkFormat pixelFormat)
        : VulkanException("Unsupported pixel format")
        , m_pixelFormat(pixelFormat)
      {
      }
    };

  }
}

#endif


text:
package org.jtwig.parser.parboiled.expression;

import org.jtwig.model.expression.ConstantExpression;
import org.jtwig.parser.parboiled.ParserContext;
import org.parboiled.Rule;

public class ConstantExpressionParser extends ExpressionParser<ConstantExpression> {
    public ConstantExpressionParser(ParserContext context) {
        super(ConstantExpressionParser.class, context);
    }

    @Override
    public Rule ExpressionRule() {
        return FirstOf(
                parserContext().parser(BooleanExpressionParser.class).ExpressionRule(),
                parserContext().parser(NumberExpressionParser.class).ExpressionRule(),
                parserContext().parser(StringExpressionParser.class).ExpressionRule(),
                parserContext().parser(ComprehensionListExpressionParser.class).ExpressionRule(),
                parserContext().parser(EnumerationListExpressionParser.class).ExpressionRule(),
                parserContext().parser(MapExpressionParser.class).ExpressionRule()
        );
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin-uptodate-flatten-it</artifactId>
  <version>1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>UpToDate Flatten</name>
  <description>Tests that uptodate-property with flatten mapping works</description>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>test.properties</exclude>
        </excludes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>test.properties</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>@project.groupId@</groupId>
        <artifactId>@project.artifactId@</artifactId>
        <version>@project.version@</version>
        <executions>
          <execution>
            <goals>
              <goal>uptodate-property</goal>
            </goals>
            <configuration>
              <name>propname-flatten</name>
              <value>uptodate</value>
              <else>outofdate</else>
              <fileSet>
                <directory>src/main/resources/source</directory>
                <outputDirectory>src/main/resources/target</outputDirectory>
                <includes>
                  <include>dir*/**</include>
                </includes>
                <excludes>
                  <exclude>**/*X*</exclude>
                  <exclude>**/*Y/**</exclude>
                </excludes>
                <mapper>
                  <type>flatten</type>
                </mapper>
              </fileSet>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
package com.netflix.spectator.metrics5;

import com.netflix.spectator.api.AbstractRegistry;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Timer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.dropwizard.metrics5.MetricName;

/** Registry implementation that maps spectator types to the metrics5 library. */
public class MetricsRegistry extends AbstractRegistry {

  private final io.dropwizard.metrics5.MetricRegistry impl;
  private final Map<MetricName, DoubleGauge> registeredGauges;

  /** Create a new instance. */
  public MetricsRegistry() {
    this(Clock.SYSTEM, new io.dropwizard.metrics5.MetricRegistry());
  }

  /** Create a new instance. */
  public MetricsRegistry(Clock clock, io.dropwizard.metrics5.MetricRegistry impl) {
    super(clock);
    this.impl = impl;
    this.registeredGauges = new ConcurrentHashMap<>();
  }

  @Override protected Counter newCounter(Id id) {
    return new MetricsCounter(clock(), id, impl.meter(toMetricName(id)));
  }

  @Override protected DistributionSummary newDistributionSummary(Id id) {
    return new MetricsDistributionSummary(clock(), id, impl.histogram(toMetricName(id)));
  }

  @Override protected Timer newTimer(Id id) {
    return new MetricsTimer(clock(), id, impl.timer(toMetricName(id)));
  }

  @Override protected Gauge newGauge(Id id) {
    final MetricName name = toMetricName(id);
    DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
      DoubleGauge g = new DoubleGauge();
      impl.register(name, g);
      return g;
    });
    return new MetricsGauge(clock(), id, gauge);
  }

  @Override protected Gauge newMaxGauge(Id id) {
    final MetricName name = toMetricName(id);
    DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
      DoubleMaxGauge g = new DoubleMaxGauge();
      impl.register(name, g);
      return g;
    });
    return new MetricsGauge(clock(), id, gauge);
  }

  private static MetricName toMetricName(final Id id) {
    return new MetricName(id.name(), buildTagMap(id));
  }

  private static Map<String, String> buildTagMap(final Id id) {
    Map<String, String> result = new HashMap<>();
    for (Tag tag : id.tags()) {
      result.put(tag.key(), tag.value());
    }
    return result;
  }

}


text:
require 'test_helper'

class ShowWriterTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package com.google.cloud.bigtable.data.v2.models;

import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS;
import static com.google.common.truth.Truth.assertThat;

import com.google.bigtable.v2.ReadRowsRequest;
import com.google.bigtable.v2.ReadRowsRequest.Builder;
import com.google.bigtable.v2.RowFilter;
import com.google.bigtable.v2.RowRange;
import com.google.bigtable.v2.RowSet;
import com.google.cloud.bigtable.data.v2.internal.ByteStringComparator;
import com.google.cloud.bigtable.data.v2.internal.NameUtil;
import com.google.cloud.bigtable.data.v2.internal.RequestContext;
import com.google.cloud.bigtable.data.v2.models.Range.ByteStringRange;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.protobuf.ByteString;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.SortedSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class QueryTest {
  private static final String PROJECT_ID = "fake-project";
  private static final String INSTANCE_ID = "fake-instance";
  private static final String TABLE_ID = "fake-table";
  private static final String APP_PROFILE_ID = "fake-profile-id";
  private RequestContext requestContext;

  @Rule public ExpectedException expect = ExpectedException.none();

  @Before
  public void setUp() {
    requestContext = RequestContext.create(PROJECT_ID, INSTANCE_ID, APP_PROFILE_ID);
  }

  @Test
  public void requestContextTest() {
    Query query = Query.create(TABLE_ID);

    ReadRowsRequest proto = query.toProto(requestContext);
    assertThat(proto).isEqualTo(expectedProtoBuilder().build());
  }

  @Test
  public void rowKeysTest() {
    Query query =
        Query.create(TABLE_ID)
            .rowKey("simple-string")
            .rowKey(ByteString.copyFromUtf8("byte-string"));

    ReadRowsRequest.Builder expectedProto = expectedProtoBuilder();
    expectedProto
        .getRowsBuilder()
        .addRowKeys(ByteString.copyFromUtf8("simple-string"))
        .addRowKeys(ByteString.copyFromUtf8("byte-string"));

    ReadRowsRequest actualProto = query.toProto(requestContext);
    assertThat(actualProto).isEqualTo(expectedProto.build());
  }

  @Test
  public void rowRangeTest() {
    Query query =
        Query.create(TABLE_ID)
            .range("simple-begin", "simple-end")
            .range(ByteString.copyFromUtf8("byte-begin"), ByteString.copyFromUtf8("byte-end"))
            .range(ByteStringRange.create("range-begin", "range-end"));

    Builder expectedProto = expectedProtoBuilder();
    expectedProto
        .getRowsBuilder()
        .addRowRanges(
            RowRange.newBuilder()
                .setStartKeyClosed(ByteString.copyFromUtf8("simple-begin"))
                .setEndKeyOpen(ByteString.copyFromUtf8("simple-end")))
        .addRowRanges(
            RowRange.newBuilder()
                .setStartKeyClosed(ByteString.copyFromUtf8("byte-begin"))
                .setEndKeyOpen(ByteString.copyFromUtf8("byte-end")))
        .addRowRanges(
            RowRange.newBuilder()
                .setStartKeyClosed(ByteString.copyFromUtf8("range-begin"))
                .setEndKeyOpen(ByteString.copyFromUtf8("range-end")));

    ReadRowsRequest actualProto = query.toProto(requestContext);
    assertThat(actualProto).isEqualTo(expectedProto.build());
  }

  @Test
  public void filterTest() {
    Query query = Query.create(TABLE_ID).filter(FILTERS.key().regex(".*"));

    Builder expectedProto =
        expectedProtoBuilder()
            .setFilter(RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(".*")));

    ReadRowsRequest actualProto = query.toProto(requestContext);
    assertThat(actualProto).isEqualTo(expectedProto.build());
  }

  @Test
  public void limitTest() {
    Query query = Query.create(TABLE_ID).limit(10);

    Builder expectedProto = expectedProtoBuilder().setRowsLimit(10);

    ReadRowsRequest actualProto = query.toProto(requestContext);
    assertThat(actualProto).isEqualTo(expectedProto.build());
  }

  @Test
  public void serializationTest() throws IOException, ClassNotFoundException {
    Query expected = Query.create(TABLE_ID).filter(FILTERS.key().regex(".*"));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(expected);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));

    Query actual = (Query) ois.readObject();
    assertThat(actual.toProto(requestContext)).isEqualTo(expected.toProto(requestContext));
  }

  @Test
  public void shardTestSplitPoints() {
    Query query = Query.create(TABLE_ID).range("a", "z");

    SortedSet<ByteString> splitPoints =
        ImmutableSortedSet.orderedBy(ByteStringComparator.INSTANCE)
            .add(ByteString.copyFromUtf8("j"))
            .build();

    List<Query> subQueries = query.shard(splitPoints);

    assertThat(subQueries).hasSize(2);
    assertThat(subQueries.get(0).toProto(requestContext))
        .isEqualTo(
            ReadRowsRequest.newBuilder()
                .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
                .setAppProfileId(APP_PROFILE_ID)
                .setRows(
                    RowSet.newBuilder()
                        .addRowRanges(
                            RowRange.newBuilder()
                                .setStartKeyClosed(ByteString.copyFromUtf8("a"))
                                .setEndKeyClosed(ByteString.copyFromUtf8("j"))))
                .build());
    assertThat(subQueries.get(1).toProto(requestContext))
        .isEqualTo(
            ReadRowsRequest.newBuilder()
                .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
                .setAppProfileId(APP_PROFILE_ID)
                .setRows(
                    RowSet.newBuilder()
                        .addRowRanges(
                            RowRange.newBuilder()
                                .setStartKeyOpen(ByteString.copyFromUtf8("j"))
                                .setEndKeyOpen(ByteString.copyFromUtf8("z"))))
                .build());
  }

  @Test
  public void shardTestKeyOffsets() {
    Query query = Query.create(TABLE_ID).range("a", "z");

    List<KeyOffset> keyOffsets =
        ImmutableList.of(
            KeyOffset.create(ByteString.copyFromUtf8("j"), 10),
            KeyOffset.create(ByteString.EMPTY, 100));

    List<Query> subQueries = query.shard(keyOffsets);

    assertThat(subQueries).hasSize(2);
    assertThat(subQueries.get(0).toProto(requestContext))
        .isEqualTo(
            ReadRowsRequest.newBuilder()
                .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
                .setAppProfileId(APP_PROFILE_ID)
                .setRows(
                    RowSet.newBuilder()
                        .addRowRanges(
                            RowRange.newBuilder()
                                .setStartKeyClosed(ByteString.copyFromUtf8("a"))
                                .setEndKeyClosed(ByteString.copyFromUtf8("j"))))
                .build());
    assertThat(subQueries.get(1).toProto(requestContext))
        .isEqualTo(
            ReadRowsRequest.newBuilder()
                .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
                .setAppProfileId(APP_PROFILE_ID)
                .setRows(
                    RowSet.newBuilder()
                        .addRowRanges(
                            RowRange.newBuilder()
                                .setStartKeyOpen(ByteString.copyFromUtf8("j"))
                                .setEndKeyOpen(ByteString.copyFromUtf8("z"))))
                .build());
  }

  private static ReadRowsRequest.Builder expectedProtoBuilder() {
    return ReadRowsRequest.newBuilder()
        .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
        .setAppProfileId(APP_PROFILE_ID);
  }

  @Test
  public void testFromProto() {
    ReadRowsRequest request =
        ReadRowsRequest.newBuilder()
            .setTableName(NameUtil.formatTableName(PROJECT_ID, INSTANCE_ID, TABLE_ID))
            .setAppProfileId(APP_PROFILE_ID)
            .setFilter(RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(".*")))
            .setRows(
                RowSet.newBuilder()
                    .addRowKeys(ByteString.copyFromUtf8("row-key"))
                    .addRowRanges(
                        RowRange.newBuilder()
                            .setStartKeyClosed(ByteString.copyFromUtf8("j"))
                            .setEndKeyClosed(ByteString.copyFromUtf8("z"))))
            .build();
    Query query = Query.fromProto(request);

    assertThat(query.toProto(requestContext)).isEqualTo(request);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testFromProtoWithEmptyTableId() {
    Query.fromProto(ReadRowsRequest.getDefaultInstance());

    expect.expect(IllegalArgumentException.class);
    expect.expectMessage("Invalid table name:");
  }
}


text:
package com.gufengxiachen.designpattern.Creational.prototype;

import java.awt.Point;

public class CircleTable extends AbstractFurniture{
	protected Point center;

	public void setCenter(Point center){
		this.center = center;
	}

	protected Object clone() throws CloneNotSupportedException{
		Object o = super.clone();
		if(this.center != null){
			((CircleTable)o).center = (Point)center.clone();
		}
		return o;
	}

	public void draw() {

		System.out.println("\t圆桌\t中心:(" + center.getX()
                + ", " + center.getY()+ ")");
	}

}