text:
package och.util.timer;

import static och.util.ExceptionUtil.*;
import static och.util.Util.*;

import java.util.Timer;
import java.util.TimerTask;

import och.util.model.CallableVoid;

import org.apache.commons.logging.Log;

public class TimerExt extends Timer {

	private Log log = getLog(getClass());
	private String name;

	public TimerExt() {
		super();
	}

	public TimerExt(boolean isDaemon) {
		super(isDaemon);
	}

	public TimerExt(String name, boolean isDaemon) {
		super(name, isDaemon);
		this.name = name;
	}

	public TimerExt(String name) {
		super(name);
		this.name = name;
	}

	public void trySchedule(CallableVoid body, long delay) {
		super.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					body.call();
				}catch(Throwable t){
					log.error(getLogPrefix() + "can't schedule: "+t);
				}
			}
		}, delay);

		log.info(getLogPrefix() + "timer started: delay="+delay);
	}

	public void schedule(CallableVoid body, long delay) {
		super.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					body.call();
				}catch(Exception e){
					throw getRuntimeExceptionOrThrowError(e);
				}
			}
		}, delay);

		log.info(getLogPrefix() + "timer started: delay="+delay);
	}

	public void tryScheduleAtFixedRate(CallableVoid body, long delay, long period) {

		super.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				try {
					body.call();
				}catch(Throwable t){
					log.error(getLogPrefix() + "can't schedule: "+t);
				}
			}
		}, delay, period);

		log.info(getLogPrefix() + "timer started: delay="+delay+", period="+period);
	}

	public void scheduleAtFixedRate(CallableVoid body, long delay, long period) {

		super.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				try {
					body.call();
				}catch(Exception e){
					throw getRuntimeExceptionOrThrowError(e);
				}
			}
		}, delay, period);

		log.info(getLogPrefix() + "timer started: delay="+delay+", period="+period);
	}

	private String getLogPrefix() {
		return name != null? name + ": " : "";
	}

}


text:
require 'spec_helper'
require 'alphonse/config'
require 'alphonse/operator'

describe "Operator" do

  describe "initialised with config" do
    before do
      @config = Alphonse::Config.new(:file_name => 'spec/fonzfiles/default')
      @operator = Alphonse::Operator.new(@config)
    end

    it "should have array of Connections" do
      @operator.send(:hosts).class.should equal(Array)
      @operator.send(:hosts).first.class.should equal(Alphonse::Connection)
    end

    describe "with hosts" do
      before do
        mock_connection!
        @operator.stub(:hosts).and_return([@connection])
      end

      it "should execute setup operation" do
        @operator.execute(:setup).class.should equal(Array)
      end

      it "should execute deploy operation" do
        @operator.execute(:deploy).class.should equal(Array)
      end
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
try:
    from ConfigParser import RawConfigParser
    _boolean_states = RawConfigParser._boolean_states
except ImportError:
    from configparser import RawConfigParser
    _boolean_states = RawConfigParser.BOOLEAN_STATES
from sippy.SipConf import SipConf

SUPPORTED_OPTIONS = { \
 'acct_enable':       ('B', 'enable or disable Radius accounting'), \
 'precise_acct':      ('B', 'do Radius accounting with millisecond precision'), \
 'alive_acct_int':    ('I', 'interval for sending alive Radius accounting in ' \
                             'second (0 to disable alive accounting)'), \
 'config':            ('S', 'load configuration from file (path to file)'), \
 'auth_enable':       ('B', 'enable or disable Radius authentication'), \
 'b2bua_socket':      ('S', 'path to the B2BUA command socket or address to listen ' \
                             'for commands in the format "udp:host[:port]"'), \
 'digest_auth':       ('B', 'enable or disable SIP Digest authentication of ' \
                             'incoming INVITE requests'), \
 'foreground':        ('B', 'run in foreground'), \
 'hide_call_id':      ('B', 'do not pass Call-ID header value from ingress call ' \
                             'leg to egress call leg'), \
 'keepalive_ans':     ('I', 'send periodic "keep-alive" re-INVITE requests on ' \
                             'answering (ingress) call leg and disconnect a call ' \
                             'if the re-INVITE fails (period in seconds, 0 to ' \
                             'disable)'), \
 'keepalive_orig':    ('I', 'send periodic "keep-alive" re-INVITE requests on ' \
                             'originating (egress) call leg and disconnect a call ' \
                             'if the re-INVITE fails (period in seconds, 0 to ' \
                             'disable)'), \
 'logfile':           ('S', 'path to the B2BUA log file'), \
 'max_credit_time':   ('I', 'upper limit of session time for all calls in ' \
                             'seconds'), \
 'max_radiusclients': ('I', 'maximum number of Radius Client helper ' \
                             'processes to start'), \
 'pidfile':           ('S', 'path to the B2BUA PID file'), \
 'radiusclient.conf': ('S', 'path to the radiusclient.conf file'), \
 'sip_address':       ('S', 'local SIP address to listen for incoming SIP requests ' \
                             '("*", "0.0.0.0" or "::" to listen on all IPv4 ' \
                             'or IPv6 interfaces)'),
 'sip_port':          ('I', 'local UDP port to listen for incoming SIP requests'), \
 'start_acct_enable': ('B', 'enable start Radius accounting'), \
 'static_route':      ('S', 'static route for all SIP calls'), \
 'static_tr_in':      ('S', 'translation rule (regexp) to apply to all incoming ' \
                             '(ingress) destination numbers'), \
 'static_tr_out':     ('S', 'translation rule (regexp) to apply to all outgoing ' \
                             '(egress) destination numbers'), \
 'allowed_pts':       ('S', 'list of allowed media (RTP) IANA-assigned payload ' \
                             'types that the B2BUA will pass from input to ' \
                             'output, payload types not in this list will be ' \
                             'filtered out (comma separated list)'), \
 'pass_headers':      ('S', 'list of SIP header field names that the B2BUA will ' \
                             'pass from ingress call leg to egress call leg ' \
                             'unmodified (comma-separated list)'), \
 'accept_ips':        ('S', 'IP addresses that we will only be accepting incoming ' \
                             'calls from (comma-separated list). If the parameter ' \
                             'is not specified, we will accept from any IP and ' \
                             'then either try to authenticate if authentication ' \
                             'is enabled, or just let them to pass through'),
 'digest_auth_only':  ('B', 'only use SIP Digest method to authenticate ' \
                             'incoming INVITE requests. If the option is not ' \
                             'specified or set to "off" then B2BUA will try to ' \
                             'do remote IP authentication first and if that fails '
                             'then send a challenge and re-authenticate when ' \
                             'challenge response comes in'), \
 'rtp_proxy_clients': ('S', 'comma-separated list of paths or addresses of the ' \
                             'RTPproxy control socket. Address in the format ' \
                             '"udp:host[:port]" (comma-separated list)'), \
 'sip_proxy':         ('S', 'address of the helper proxy to handle "REGISTER" ' \
                             'and "SUBSCRIBE" messages. Address in the format ' \
                             '"host[:port]"'),
 'nat_traversal':     ('B', 'enable NAT traversal for signalling'), \
 'xmpp_b2bua_id':     ('I', 'ID passed to the XMPP socket server')}

class MyConfigParser(RawConfigParser):
    _default_section = None
    _private_keys = None

    def __init__(self, default_section = 'general'):
        self._default_section = default_section
        self._private_keys = {}
        RawConfigParser.__init__(self)
        self.add_section(self._default_section)

    def __getitem__(self, key):
        if key.startswith('_'):
            return self._private_keys[key]
        value_type  = SUPPORTED_OPTIONS[key][0]
        if value_type  == 'B':
            return self.getboolean(self._default_section, key)
        elif value_type == 'I':
            return self.getint(self._default_section, key)
        return self.get(self._default_section, key)

    def __setitem__(self, key, value):
        if key.startswith('_'):
            self._private_keys[key] = value
        else:
            self.set(self._default_section, key, str(value))
        return

    def has_key(self, key):
        return self.__contains__(key)

    def __contains__(self, key):
        if key.startswith('_'):
            return key in self._private_keys
        return self.has_option(self._default_section, key)

    def get(self, *args, **kwargs):
        if len(args) == 1:
            return self.__getitem__(args[0])
        return RawConfigParser.get(self, *args, **kwargs)

    def getdefault(self, key, default_value):
        if self.__contains__(key):
            return self.__getitem__(key)
        return default_value

    def get_longopts(self):
        return tuple([x + '=' for x in SUPPORTED_OPTIONS.keys()])

    def read(self, fname):
        RawConfigParser.readfp(self, open(fname))
        for key in tuple(self.options(self._default_section)):
            self.check_and_set(key, RawConfigParser.get(self, \
              self._default_section, key), False)

    def check_and_set(self, key, value, compat = True):
        value = value.strip()
        if compat:
            if key == 'rtp_proxy_client':
                # XXX compatibility option
                if self.has_key('_rtp_proxy_clients'):
                    self['_rtp_proxy_clients'].append(value)
                else:
                    self['_rtp_proxy_clients'] = [value,]
                if self.has_key('rtp_proxy_clients'):
                    self['rtp_proxy_clients'] += ',' + value
                else:
                    self['rtp_proxy_clients'] = value
                return
            elif key == 'pass_header':
                # XXX compatibility option
                if self.has_key('_pass_headers'):
                    self['_pass_headers'].append(value)
                else:
                    self['_pass_headers'] = [value,]
                if self.has_key('pass_headers'):
                    self['pass_headers'] += ',' + value
                else:
                    self['pass_headers'] = value
                return

        value_type  = SUPPORTED_OPTIONS[key][0]
        if value_type == 'B':
            if value.lower() not in _boolean_states:
                raise ValueError('Not a boolean: %s' % value)
        elif value_type == 'I':
            _value = int(value)
        if key in ('keepalive_ans', 'keepalive_orig'):
            if _value < 0:
                raise ValueError('keepalive_ans should be non-negative')
        elif key == 'max_credit_time':
            if _value <= 0:
                raise ValueError('max_credit_time should be more than zero')
        elif key == 'allowed_pts':
            self['_allowed_pts'] = [int(x) for x in value.split(',')]
        elif key in ('accept_ips', 'rtp_proxy_clients'):
            self['_' + key] = [x.strip() for x in value.split(',')]
        elif key == 'pass_headers':
            self['_' + key] = [x.strip().lower() for x in value.split(',')]
        elif key == 'sip_address':
            if 'my' in dir(value):
                self['_sip_address'] = value
                value = '*'
            elif value in ('*', '0.0.0.0', '::'):
                self['_sip_address'] = SipConf.my_address
            else:
                self['_sip_address'] = value
        elif key == 'sip_port':
            if _value <= 0 or _value > 65535:
                raise ValueError('sip_port should be in the range 1-65535')
            self['_sip_port'] = _value
        self[key] = value

    def options_help(self):
        supported_options = sorted(SUPPORTED_OPTIONS.items())
        for option, (value_type, helptext) in supported_options:
            if value_type == 'B':
                value = 'on/off'
            elif value_type == 'I':
                value = 'number'
            else:
                value = '"string"'
            print('--%s=%s\n\t%s\n' % (option, value, helptext))

if __name__ == '__main__':
    m = MyConfigParser()
    m['_foo'] = 'bar'
    m['b2bua_socket'] = 'bar1'
    m['acct_enable'] = True
    m['auth_enable'] = 'False'
    assert m.has_key('_foo')
    assert m['_foo'] == 'bar'
    assert m['b2bua_socket'] == 'bar1'
    assert m.get('_foo') == 'bar'
    assert m.get('b2bua_socket') == 'bar1'
    assert m.get('general', 'b2bua_socket') == 'bar1'
    assert m.get('acct_enable')
    assert not m.get('auth_enable')
    m.check_and_set('keepalive_ans', '15')
    assert m['keepalive_ans'] == 15
    m.check_and_set('pass_header', 'a')
    m.check_and_set('pass_header', 'b')
    assert m['pass_headers'] == 'a,b'
    assert m['_pass_headers'][0] == 'a'
    assert m['_pass_headers'][1] == 'b'
    m.check_and_set('accept_ips', '1.2.3.4, 5.6.7.8')
    assert m['accept_ips'] == '1.2.3.4, 5.6.7.8'
    assert m['_accept_ips'][0] == '1.2.3.4'
    assert m['_accept_ips'][1] == '5.6.7.8'


text:
var _KeisukeTagami$elm_chart$Native_Utils = function() {

    function log(x) {
        console.log(x);
        return x;
    }

    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttributeNS(null, 'version', '1.1');
    svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
    svg.setAttribute("width", "0");
    svg.setAttribute("height", "0");
    svg.setAttribute("style", "position: fixed;");

    function build(x) {
        switch( x.type ) {
            case "node":
                var e = document.createElementNS(x.namespace, x.tag);
                for( var i in x.children ) {
                    var c = build(x.children[i]);
                    e.appendChild(c);
                }
                return e;
                break;
            case "text":
                return document.createTextNode(x.text);
                break;
        }
        return null;
    }

    function width(x){
        return size(x)._0;
    }

    function height(x){
        return size(x)._1;
    }

    function size(x) {
        var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
        var txtnode = document.createTextNode("100");

        var node = build(x);
        document.body.appendChild(svg);
        svg.appendChild(node);
        var bbox = node.getBBox();
        console.log(x);
        console.log(bbox);
        svg.removeChild(node);
        document.body.removeChild(svg);
        return _elm_lang$core$Native_Utils.Tuple2(bbox.width, bbox.height);
    }

    return {
        log: log,
        width: width,
        height: height,
        size: size
    };
}();


text:
profile information

### Synopsis

List the details for a named profile as well as available profile
configurations found in the .rwctl configuration file.
Defaults to 'default' profile.

```
rwctl profile [profile]
```

### Options

```
      --config string    config file (default is $HOME/.config/roguewave/rwctl.toml)
      --profile string   profile name (default "default")
```

### SEE ALSO
* [rwctl](rwctl.md)	 - Rogue Wave API Platform command-line interface control

###### Auto generated by spf13/cobra on 11-Feb-2017


text:
The repository contains some python scripts for training and inferring test document vectors using paragraph vectors or doc2vec.

Requirements
============
* Python2: Pre-trained models and scripts all support Python2 only.
* Gensim: Best to use my [forked version](https://github.com/jhlau/gensim) of gensim; the latest gensim has changed its Doc2Vec methods a little and so would not load the pre-trained models.

Pre-Trained Doc2Vec Models
==========================
* [English Wikipedia DBOW (1.4GB)](https://cloudstor.aarnet.edu.au/plus/s/hpfhUC72NnKDxXw)
* [Associated Press News DBOW (0.6GB)](https://cloudstor.aarnet.edu.au/plus/s/rjJTPBqEueZg1xS)

Pre-Trained Word2Vec Models
===========================
For reproducibility we also released the pre-trained word2vec skip-gram models on Wikipedia and AP News:
* [English Wikipedia Skip-Gram (1.4GB)](https://cloudstor.aarnet.edu.au/plus/s/Ss4E5by3Ukj0JuN)
* [Associated Press News Skip-gram (0.6GB)](https://cloudstor.aarnet.edu.au/plus/s/IfElyGrGbXNfeBh)

Directory Structure and Files
=============================
* train_model.py: example python script to train some toy data
* infer_test.py: example python script to infer test document vectors using trained model
* toy_data: directory containing some toy train/test documents and pre-trained word embeddings

Model Hyper-Parameter Explanation
=================================
* __sample__: this is the sub-sampling threshold to downsample frequent words; 10e-5 is usually good for DBOW, and 10e-6 for DMPV
* __hs__: 1 turns on hierarchical sampling; this is rarely turned on as negative sampling is in general better
* __dm__: 0 = DBOW; 1 = DMPV
* __negative__: number of negative samples; 5 is a good value
* __dbow_words__: 1 turns on updating of word embeddings. In DBOW, word embeddings are technically not learnt (only document embeddings are learnt). To learn word vectors, DBOW runs a step of skip-gram before the DBOW step to update the word embeddings. With dbow_words turned off, this means DBOW will randomly initialise word embeddings and keep them randomly initialised. This is rather bad in practice (as the model does not see relationships between words in the embedding space), so it should be turned on
* __dm_concat__: 1 = concatenate input word vectors for DMPV; 0 = sum/average input word vectors. This setting is only used for DMPV since DBOW has only one input word
* __dm_mean__: 1 = average input word vectors; 0 = sum input word vectors. Again, this setting is only used for DMPV. The original paragraph vector paper concatenates input word vectors for DMPV, and that's the setting we used in our paper
* __iter__: number of iterations/epochs to train the model

Publications
------------
* Jey Han Lau and Timothy Baldwin (2016). [An Empirical Evaluation of doc2vec with Practical Insights into Document Embedding Generation](https://arxiv.org/abs/1607.05368). In Proceedings of the 1st Workshop on Representation Learning for NLP, 2016.


text:
#import "NSObject.h"

// Not exported
@interface MFPStringFormat : NSObject
{
    int mAlignment;
    unsigned short mDigitSubstitutionLanguage;
    int mDigitSubstitutionMethod;
    unsigned int mFormatFlags;
    int mHotkeyPrefix;
    int mLineAlignment;
    float mFirstTabOffset;
    int mTabStopCount;
    float *mTabStops;
    int mTrimming;
}

- (void)setTrimming:(int)arg1;
- (int)trimming;
- (void)setTabStops:(const float *)arg1 count:(int)arg2;
- (const float *)tabStops;
- (int)tabStopCount;
- (void)setFirstTabOffset:(float)arg1;
- (float)firstTabOffset;
- (void)setLineAlignment:(int)arg1;
- (int)lineAlignment;
- (void)setHotkeyPrefix:(int)arg1;
- (int)hotkeyPrefix;
- (void)setFormatFlags:(unsigned int)arg1;
- (unsigned int)formatFlags;
- (void)setDigitSubstitutionMethod:(int)arg1;
- (int)digitSubstitutionMethod;
- (void)setDigitSubstitutionLanguage:(unsigned short)arg1;
- (unsigned short)digitSubstitutionLanguage;
- (void)setAlignment:(int)arg1;
- (int)alignment;
- (void)dealloc;
- (id)init;

@end


text:
import { CdnJsDatasource } from '../../datasource/cdnjs';
import { cloudflareUrlRegex } from '../cdnurl/extract';
import type { PackageDependency, PackageFile } from '../types';

const regex = /<\s*(script|link)\s+[^>]*?\/?>/i;

const integrityRegex = /\s+integrity\s*=\s*("|')(?<currentDigest>[^"']+)/;

export function extractDep(tag: string): PackageDependency | null {
  const match = cloudflareUrlRegex.exec(tag);
  if (!match) {
    return null;
  }
  const { depName, currentValue, asset } = match.groups;
  const dep: PackageDependency = {
    datasource: CdnJsDatasource.id,
    depName,
    lookupName: `${depName}/${asset}`,
    currentValue,
    replaceString: tag,
  };
  const integrityMatch = integrityRegex.exec(tag);
  if (integrityMatch) {
    dep.currentDigest = integrityMatch.groups.currentDigest;
  }
  return dep;
}

export function extractPackageFile(content: string): PackageFile {
  const deps: PackageDependency[] = [];
  let rest = content;
  let match = regex.exec(rest);
  let offset = 0;
  while (match) {
    const [replaceString] = match;
    offset += match.index + replaceString.length;
    rest = content.slice(offset);
    match = regex.exec(rest);
    const dep = extractDep(replaceString);
    if (dep) {
      deps.push(dep);
    }
  }
  if (!deps.length) {
    return null;
  }
  return { deps };
}


text:
package org.corpus_tools.annis.gui.query_references;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ValoTheme;
import com.vaadin.v7.shared.ui.label.ContentMode;
import com.vaadin.v7.ui.Label;
import com.vaadin.v7.ui.TextArea;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.lang3.StringUtils;
import org.corpus_tools.annis.gui.AnnisUI;
import org.corpus_tools.annis.gui.components.ExceptionDialog;
import org.corpus_tools.annis.gui.objects.DisplayedResultQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Thomas Krause {@literal <krauseto@hu-berlin.de>}
 */
public class ShareQueryReferenceWindow extends Window implements Button.ClickListener {

    /**
     *
     */
    private static final long serialVersionUID = 8839761991143179718L;

    private static final Logger log = LoggerFactory.getLogger(ShareQueryReferenceWindow.class);

    private final DisplayedResultQuery query;
    private final boolean shorten;

    private TextArea txtCitation;

    public ShareQueryReferenceWindow(DisplayedResultQuery query, boolean shorten) {
        super("Query reference link");

        this.query = query;
        this.shorten = shorten;

        VerticalLayout wLayout = new VerticalLayout();
        setContent(wLayout);
        wLayout.setSizeFull();
        wLayout.setMargin(true);

        Label lblInfo = new Label(
                "
" + "Share your query: "
                        + "1. Copy the generated link 2. Share this link with your peers. " + "
",
                ContentMode.HTML);
        wLayout.addComponent(lblInfo);
        wLayout.setExpandRatio(lblInfo, 0.0f);

        txtCitation = new TextArea();

        txtCitation.setWidth("100%");
        txtCitation.setHeight("100%");
        txtCitation.addStyleName(ValoTheme.TEXTFIELD_LARGE);
        txtCitation.addStyleName("shared-text");
        txtCitation.setWordwrap(true);
        txtCitation.setReadOnly(true);

        wLayout.addComponent(txtCitation);

        Button btClose = new Button("Close");
        btClose.addClickListener(this);
        btClose.setSizeUndefined();

        wLayout.addComponent(btClose);

        wLayout.setExpandRatio(txtCitation, 1.0f);
        wLayout.setComponentAlignment(btClose, Alignment.BOTTOM_CENTER);

        setWidth("400px");
        setHeight("300px");

    }

    @Override
    public void attach() {
        super.attach();

        String shortURL = "ERROR";
        UI ui = UI.getCurrent();
        if (query != null && ui instanceof AnnisUI) {
          AnnisUI annisUI = (AnnisUI) ui;
            URI appURI = UI.getCurrent().getPage().getLocation();
            String fragment;
            try {
                fragment = StringUtils.join(query.toCitationFragment(), "&");
                URI url = new URI(appURI.getScheme(), null, appURI.getHost(), appURI.getPort(), appURI.getPath(), null,
                        fragment);

                if (shorten) {
                  shortURL = annisUI.getUrlShortener().shortenURL(url, annisUI);
                } else {
                    shortURL = url.toASCIIString();
                }
            } catch (URISyntaxException e) {
                log.error("Could not generate query share link", e);
                ExceptionDialog.show(e, "Could not generate query share link", UI.getCurrent());
            }

        }

        txtCitation.setReadOnly(false);
        txtCitation.setValue(shortURL);
        txtCitation.setReadOnly(true);
    }

    @Override
    public void buttonClick(ClickEvent event) {
        UI.getCurrent().removeWindow(this);
    }
}


text:
package me.kkuai.kuailian.service.socket.protocol;

import me.kkuai.kuailian.log.Log;
import me.kkuai.kuailian.log.LogFactory;
import me.kkuai.kuailian.service.socket.SocketPool;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

public class ChatMsgStatusProtocol implements Protocol {

	private Log log = LogFactory.getLog(ChatMsgStatusProtocol.class);
	private String msgId;
	private String type;
	private String content;

	@Override
	public String getCmd() {
		return null;
	}

	@Override
	public String getFunction() {
		return null;
	}

	@Override
	public byte[] getContentData() {

		return content.getBytes();
	}

	public void setMsgStatus(Context context) {
//		{\"f\":\"setchatmsgstatus\", \"p\":{\"msg_id\":\"%@\",\"type\":\"%d\",\"token\":\"%@\"}
		String token = SocketPool.getInatance(context).getSocketService().getSocketToken();
		content = "{\"f\":\"setchatmsgstatus\", \"p\":{\"msg_id\":\"" + msgId + "\",\"type\":\"" + type + "\",\"token\":\"" + token + "\"}";
	}

	@Override
	public void parseBinary(byte[] data) {
		String str = new String(data);
		str = str.substring(4, str.length());
		try {
			JSONObject obj = new JSONObject(str);
		} catch (JSONException e) {
			log.error("parse ChatMsgStatusProtocol json ", e);
		}
	}

	public String getMsgId() {
		return msgId;
	}

	public void setMsgId(String msgId) {
		this.msgId = msgId;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}


text:
package io.confluent.connect.jdbc.sink.metadata;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DbTable {
  public final String name;
  public final Map<String, DbTableColumn> columns = new HashMap<>();
  public final Set<String> primaryKeyColumnNames = new HashSet<>();

  public DbTable(String name, List<DbTableColumn> columns) {
    this.name = name;
    for (final DbTableColumn column : columns) {
      this.columns.put(column.name, column);
      if (column.isPrimaryKey) {
        primaryKeyColumnNames.add(column.name);
      }
    }
  }

  @Override
  public String toString() {
    return "DbTable{"
           + "name='" + name + '\''
           + ", columns=" + columns
           + '}';
  }
}


text:
class AddTrialEndingToUsers < ActiveRecord::Migration
  def change
    add_column :users, :trial_ending, :datetime
  end
end


text:
#ifndef WEBRTC_MEDIA_ENGINE_WEBRTCVIDEOCAPTURER_H_
#define WEBRTC_MEDIA_ENGINE_WEBRTCVIDEOCAPTURER_H_

#include <memory>
#include <string>
#include <vector>

#include "webrtc/base/asyncinvoker.h"
#include "webrtc/base/messagehandler.h"
#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/media/base/device.h"
#include "webrtc/media/base/videocapturer.h"
#include "webrtc/modules/video_capture/video_capture.h"

namespace cricket {

// Factory to allow injection of a VCM impl into WebRtcVideoCapturer.
// DeviceInfos do not have a Release() and therefore need an explicit Destroy().
class WebRtcVcmFactoryInterface {
 public:
  virtual ~WebRtcVcmFactoryInterface() {}
  virtual rtc::scoped_refptr<webrtc::VideoCaptureModule> Create(
      const char* device) = 0;
  virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo() = 0;
  virtual void DestroyDeviceInfo(
      webrtc::VideoCaptureModule::DeviceInfo* info) = 0;
};

// WebRTC-based implementation of VideoCapturer.
class WebRtcVideoCapturer : public VideoCapturer,
                            public rtc::VideoSinkInterface<webrtc::VideoFrame> {
 public:
  WebRtcVideoCapturer();
  explicit WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory);
  virtual ~WebRtcVideoCapturer();

  bool Init(const Device& device);
  bool Init(const rtc::scoped_refptr<webrtc::VideoCaptureModule>& module);

  // Override virtual methods of the parent class VideoCapturer.
  bool GetBestCaptureFormat(const VideoFormat& desired,
                            VideoFormat* best_format) override;
  CaptureState Start(const VideoFormat& capture_format) override;
  void Stop() override;
  bool IsRunning() override;
  bool IsScreencast() const override { return false; }

 protected:
  void OnSinkWantsChanged(const rtc::VideoSinkWants& wants) override;
  // Override virtual methods of the parent class VideoCapturer.
  bool GetPreferredFourccs(std::vector<uint32_t>* fourccs) override;

 private:
  // Callback when a frame is captured by camera.
  void OnFrame(const webrtc::VideoFrame& frame) override;

  // Used to signal captured frames on the same thread as invoked Start().
  // With WebRTC's current VideoCapturer implementations, this will mean a
  // thread hop, but in other implementations (e.g. Chrome) it will be called
  // directly from OnIncomingCapturedFrame.
  // TODO(tommi): Remove this workaround when we've updated the WebRTC capturers
  // to follow the same contract.
  void SignalFrameCapturedOnStartThread(const webrtc::VideoFrame& frame);

  std::unique_ptr<WebRtcVcmFactoryInterface> factory_;
  rtc::scoped_refptr<webrtc::VideoCaptureModule> module_;
  int captured_frames_;
  std::vector<uint8_t> capture_buffer_;
  rtc::Thread* start_thread_;  // Set in Start(), unset in Stop();

  std::unique_ptr<rtc::AsyncInvoker> async_invoker_;
};

}  // namespace cricket

#endif  // WEBRTC_MEDIA_WEBRTC_WEBRTCVIDEOCAPTURER_H_


text:
package org.kuali.rice.krad.maintenance;

import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.bo.DocumentHeader;
import org.kuali.rice.krad.document.MaintenanceDocument;
import org.kuali.rice.krad.document.MaintenanceLock;
import org.kuali.rice.krad.uif.service.ViewHelperService;

import java.util.List;
import java.util.Map;

/**
 * Provides contract for implementing a maintenance object within the maintenance framework
 *
 *
 Currently the Maintainable serves many purposes. First since all maintenance documents share the
 * same document class MaintenanceDocumentBase certain document callbacks such as workflow post processing
 * are invoked on the maintainable. Second the maintainable provides a hook for custom actions on the maintenance view.
 * Finally since the maintainable extends ViewHelperService it is used to customize View
 * configuration for MaintenanceView instances

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface Maintainable extends ViewHelperService, java.io.Serializable {

    /**
     * Sets the document number on this maintainable for referencing back to the containing
     * MaintenanceDocument
     *
     * @param documentNumber - document number for the containing maintenance document
     */
    public void setDocumentNumber(String documentNumber);

    /**
     * Invoked when setting the title for the document instance in workflow (doc search results)
     * to customize the title
     *
     * @param document - maintenance document instance to build title for
     * @return String document title
     */
    public String getDocumentTitle(MaintenanceDocument document);

    /**
     * Returns instance of the data object that is being maintained
     *
     * @return Object data object instance
     */
    public Object getDataObject();

    /**
     * Sets an instance of a data object that should be maintained
     *
     * @param object - data object instance
     */
    public void setDataObject(Object object);

    /**
     * Returns the class for the data object being maintained
     *
     * @return Class data object class
     */
    public Class getDataObjectClass();

    /**
     * Sets the class for the data object that will be maintained
     *
     * @param dataObjectClass - class for maintenance data object
     */
    public void setDataObjectClass(Class dataObjectClass);

    /**
     * Returns the type of maintenance action this maintainable has been configured with
     *
     * @return String maintenance action string
     */
    public String getMaintenanceAction();

    /**
     * Sets the type of maintenance action to be performed (new, edit, or copy)
     *
     * @param maintenanceAction - string identifying the action type
     */
    public void setMaintenanceAction(String maintenanceAction);

    /**
     * Invoked to generating the list of maintenance locks used to block other edits
     * of the same data object record
     *
     * @return the locking representation(s) of this document, which are reproducible
     *         given the same keys and the same maintainable object
     */
    public List<MaintenanceLock> generateMaintenanceLocks();

    /**
     * Invoked to persist changes to the data object being maintained
     *
     *

     * Called after the maintenance document has become final indicating
     * the changes should be applied
     *

     */
    public void saveDataObject();

    /**
     * Invokes to delete the data object being maintained
     *
     *

     * Called after the maintenance document has become final indicating
     * the changes should be applied
     *

     */
    public void deleteDataObject();

    /**
     * Invoked do perform custom processing when the route status for the containing
     * maintenance document changes
     *
     *

     * Usually used for determining when the document has become final so further actions
     * can take place in addition to the usual persistence of the object changes
     *

     *
     * @param documentHeader - document header instance for containing maintenance document which
     * can be used to check the new status
     */
    public void doRouteStatusChange(DocumentHeader documentHeader);

    /**
     * Retrieves the locking document id for the maintainable which is used to create the
     * maintenance lock string
     *
     * @return String locking id
     */
    public String getLockingDocumentId();

    /**
     * Return an array of document ids to lock prior to processing this document
     * in the workflow engine
     *
     * @return List<Long> list of document ids
     */
    public List<Long> getWorkflowEngineDocumentIdsToLock();

    /**
     * Indicates whether or not this maintainable supports custom lock
     * descriptors for pessimistic locking.
     *
     * @return boolean true if the maintainable can generate custom lock descriptors,
     *         false otherwise
     * @see #getCustomLockDescriptor(Map, org.kuali.rice.kim.api.identity.Person)
     */
    public boolean useCustomLockDescriptors();

    /**
     * Generates a custom lock descriptor for pessimistic locking. This method
     * should not be called unless {@link #useCustomLockDescriptors()} returns
     * true
     *
     * @param user - the user trying to establish the lock
     * @return String representing the lock descriptor
     * @see #useCustomLockDescriptors()
     * @see org.kuali.rice.krad.service.PessimisticLockService
     * @see org.kuali.rice.krad.service.impl.PessimisticLockServiceImpl
     */
    public String getCustomLockDescriptor(Person user);

    /**
     * Indicates whether this maintainable supports notes on the maintenance object
     *
     *

     * Note this is only applicable if the data object is an instance of BusinessObject
     *

     *
     * @return boolean true if notes are supported, false if they are not supported
     */
    public boolean isNotesEnabled();

    /**
     * Indicates whether the object being maintained is an instance of ExternalizableBusinessObject
     *
     *

     * For the case when we want to maintain a business object that doesn't
     * necessarily map to a single table in the database or may doesn't map to a
     * database at all
     *

     *
     * @return boolean true if the data object is an external business object, false if not
     */
    public boolean isExternalBusinessObject();

    /**
     * Invoked to prepare a new BusinessObject instance that is external
     *
     * @param businessObject - new business object instance to prepare
     */
    public void prepareExternalBusinessObject(BusinessObject businessObject);

    /**
     * Indicates whether their is an old data object for the maintainable
     *
     * @return boolean true if old data object exists, false if not
     */
    public boolean isOldDataObjectInDocument();

    /**
     * Hook for performing any custom processing before the maintenance object is saved
     */
    public void prepareForSave();

    /**
     * Hook for performing any custom processing after the maintenance object is retrieved from persistence storage
     */
    public void processAfterRetrieve();

    /**
     * Called during setupMaintenanceObject to retrieve the original dataObject that is being
     * edited or copied.  Override this method for non BusinessObject external persistence,
     * Maintainable objects that extend BO should override isExternalBusinessObject and
     * prepareBusinessObject instead.
     *
     * Do not override this method and isExternalBusinessObject.
     *
     * @param document document instance for the maintenance object
     * @param dataObjectKeys Map of keys for the requested object
     * @return the object identified by the dataObjectKeys
     */
    public Object retrieveObjectForEditOrCopy(MaintenanceDocument document, Map<String, String> dataObjectKeys);

    /**
     * Performs the setting of some attributes that might be necessary
     * if we're creating a new business object using on an existing business object.
     * For example, create a division Vendor based on an existing parent Vendor.
     * (Please see VendorMaintainableImpl.java)
     *
     * @param document - maintenance document instance this maintainable belong to
     * @param requestParameters - map of request parameters sent for the request
     */
    public void setupNewFromExisting(MaintenanceDocument document, Map<String, String[]> parameters);

    /**
     * Hook for performing any custom processing after the maintenance object has been setup for a copy action
     *
     * @param document - maintenance document instance this maintainable belong to
     * @param requestParameters - map of request parameters sent for the copy request
     */
    public void processAfterCopy(MaintenanceDocument document, Map<String, String[]> requestParameters);

    /**
     * Hook for performing any custom processing after the maintenance object has been setup for a edit action
     *
     * @param document - maintenance document instance this maintainable belong to
     * @param requestParameters - map of request parameters sent for the copy request
     */
    public void processAfterEdit(MaintenanceDocument document, Map<String, String[]> requestParameters);

    /**
     * Hook for performing any custom processing after the maintenance object has been setup for a new action
     *
     * @param document - maintenance document instance this maintainable belong to
     * @param requestParameters - map of request parameters sent for the copy request
     */
    public void processAfterNew(MaintenanceDocument document, Map<String, String[]> requestParameters);

    /**
     * Hook for performing any custom processing after each posting of the maintenance document (for various actions
     * like add line, refresh)
     *
     * @param document - maintenance document instance this maintainable belong to
     * @param requestParameters - map of request parameters from the post
     */
    public void processAfterPost(MaintenanceDocument document, Map<String, String[]> requestParameters);
}


text:
package scheduler

// This file tests the VolumeScheduling feature.

import (
	"fmt"
	"os"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/golang/glog"

	"k8s.io/api/core/v1"
	storagev1 "k8s.io/api/storage/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/rand"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/wait"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/client-go/informers"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/pkg/controller/volume/persistentvolume"
	persistentvolumeoptions "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/options"
	"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
	"k8s.io/kubernetes/pkg/volume"
	volumetest "k8s.io/kubernetes/pkg/volume/testing"
	imageutils "k8s.io/kubernetes/test/utils/image"
)

type testConfig struct {
	client   clientset.Interface
	ns       string
	stop     <-chan struct{}
	teardown func()
}

var (
	// Delete API objects immediately
	deletePeriod = int64(0)
	deleteOption = &metav1.DeleteOptions{GracePeriodSeconds: &deletePeriod}

	modeWait      = storagev1.VolumeBindingWaitForFirstConsumer
	modeImmediate = storagev1.VolumeBindingImmediate

	classWait      = "wait"
	classImmediate = "immediate"
	classDynamic   = "dynamic"

	sharedClasses = map[storagev1.VolumeBindingMode]*storagev1.StorageClass{
		modeImmediate: makeStorageClass(classImmediate, &modeImmediate),
		modeWait:      makeStorageClass(classWait, &modeWait),
	}
)

const (
	node1                 = "node-1"
	node2                 = "node-2"
	podLimit              = 100
	volsPerPod            = 5
	nodeAffinityLabelKey  = "kubernetes.io/hostname"
	provisionerPluginName = "kubernetes.io/mock-provisioner"
)

type testPV struct {
	name        string
	scMode      storagev1.VolumeBindingMode
	preboundPVC string
	node        string
}

type testPVC struct {
	name       string
	scMode     storagev1.VolumeBindingMode
	preboundPV string
}

func TestVolumeBinding(t *testing.T) {
	features := map[string]bool{
		"VolumeScheduling":       true,
		"PersistentLocalVolumes": true,
	}
	config := setupCluster(t, "volume-scheduling-", 2, features, 0, 0, false)
	defer config.teardown()

	cases := map[string]struct {
		pod  *v1.Pod
		pvs  []*testPV
		pvcs []*testPVC
		// Create these, but they should not be bound in the end
		unboundPvcs []*testPVC
		unboundPvs  []*testPV
		shouldFail  bool
	}{
		"immediate can bind": {
			pod:  makePod("pod-i-canbind", config.ns, []string{"pvc-i-canbind"}),
			pvs:  []*testPV{{"pv-i-canbind", modeImmediate, "", node1}},
			pvcs: []*testPVC{{"pvc-i-canbind", modeImmediate, ""}},
		},
		"immediate cannot bind": {
			pod:         makePod("pod-i-cannotbind", config.ns, []string{"pvc-i-cannotbind"}),
			unboundPvcs: []*testPVC{{"pvc-i-cannotbind", modeImmediate, ""}},
			shouldFail:  true,
		},
		"immediate pvc prebound": {
			pod:  makePod("pod-i-pvc-prebound", config.ns, []string{"pvc-i-prebound"}),
			pvs:  []*testPV{{"pv-i-pvc-prebound", modeImmediate, "", node1}},
			pvcs: []*testPVC{{"pvc-i-prebound", modeImmediate, "pv-i-pvc-prebound"}},
		},
		"immediate pv prebound": {
			pod:  makePod("pod-i-pv-prebound", config.ns, []string{"pvc-i-pv-prebound"}),
			pvs:  []*testPV{{"pv-i-prebound", modeImmediate, "pvc-i-pv-prebound", node1}},
			pvcs: []*testPVC{{"pvc-i-pv-prebound", modeImmediate, ""}},
		},
		"wait can bind": {
			pod:  makePod("pod-w-canbind", config.ns, []string{"pvc-w-canbind"}),
			pvs:  []*testPV{{"pv-w-canbind", modeWait, "", node1}},
			pvcs: []*testPVC{{"pvc-w-canbind", modeWait, ""}},
		},
		"wait cannot bind": {
			pod:         makePod("pod-w-cannotbind", config.ns, []string{"pvc-w-cannotbind"}),
			unboundPvcs: []*testPVC{{"pvc-w-cannotbind", modeWait, ""}},
			shouldFail:  true,
		},
		"wait pvc prebound": {
			pod:  makePod("pod-w-pvc-prebound", config.ns, []string{"pvc-w-prebound"}),
			pvs:  []*testPV{{"pv-w-pvc-prebound", modeWait, "", node1}},
			pvcs: []*testPVC{{"pvc-w-prebound", modeWait, "pv-w-pvc-prebound"}},
		},
		"wait pv prebound": {
			pod:  makePod("pod-w-pv-prebound", config.ns, []string{"pvc-w-pv-prebound"}),
			pvs:  []*testPV{{"pv-w-prebound", modeWait, "pvc-w-pv-prebound", node1}},
			pvcs: []*testPVC{{"pvc-w-pv-prebound", modeWait, ""}},
		},
		"wait can bind two": {
			pod: makePod("pod-w-canbind-2", config.ns, []string{"pvc-w-canbind-2", "pvc-w-canbind-3"}),
			pvs: []*testPV{
				{"pv-w-canbind-2", modeWait, "", node2},
				{"pv-w-canbind-3", modeWait, "", node2},
			},
			pvcs: []*testPVC{
				{"pvc-w-canbind-2", modeWait, ""},
				{"pvc-w-canbind-3", modeWait, ""},
			},
			unboundPvs: []*testPV{
				{"pv-w-canbind-5", modeWait, "", node1},
			},
		},
		"wait cannot bind two": {
			pod: makePod("pod-w-cannotbind-2", config.ns, []string{"pvc-w-cannotbind-1", "pvc-w-cannotbind-2"}),
			unboundPvcs: []*testPVC{
				{"pvc-w-cannotbind-1", modeWait, ""},
				{"pvc-w-cannotbind-2", modeWait, ""},
			},
			unboundPvs: []*testPV{
				{"pv-w-cannotbind-1", modeWait, "", node2},
				{"pv-w-cannotbind-2", modeWait, "", node1},
			},
			shouldFail: true,
		},
		"mix immediate and wait": {
			pod: makePod("pod-mix-bound", config.ns, []string{"pvc-w-canbind-4", "pvc-i-canbind-2"}),
			pvs: []*testPV{
				{"pv-w-canbind-4", modeWait, "", node1},
				{"pv-i-canbind-2", modeImmediate, "", node1},
			},
			pvcs: []*testPVC{
				{"pvc-w-canbind-4", modeWait, ""},
				{"pvc-i-canbind-2", modeImmediate, ""},
			},
		},
	}

	for name, test := range cases {
		glog.Infof("Running test %v", name)

		// Create two StorageClasses
		suffix := rand.String(4)
		classes := map[storagev1.VolumeBindingMode]*storagev1.StorageClass{}
		classes[modeImmediate] = makeStorageClass(fmt.Sprintf("immediate-%v", suffix), &modeImmediate)
		classes[modeWait] = makeStorageClass(fmt.Sprintf("wait-%v", suffix), &modeWait)
		for _, sc := range classes {
			if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
				t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
			}
		}

		// Create PVs
		for _, pvConfig := range test.pvs {
			pv := makePV(pvConfig.name, classes[pvConfig.scMode].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
			if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
				t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
			}
		}

		for _, pvConfig := range test.unboundPvs {
			pv := makePV(pvConfig.name, classes[pvConfig.scMode].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
			if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
				t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
			}
		}

		// Create PVCs
		for _, pvcConfig := range test.pvcs {
			pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scMode].Name, pvcConfig.preboundPV)
			if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
				t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
			}
		}
		for _, pvcConfig := range test.unboundPvcs {
			pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scMode].Name, pvcConfig.preboundPV)
			if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
				t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
			}
		}

		// Create Pod
		if _, err := config.client.CoreV1().Pods(config.ns).Create(test.pod); err != nil {
			t.Fatalf("Failed to create Pod %q: %v", test.pod.Name, err)
		}
		if test.shouldFail {
			if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
				t.Errorf("Pod %q was not unschedulable: %v", test.pod.Name, err)
			}
		} else {
			if err := waitForPodToSchedule(config.client, test.pod); err != nil {
				t.Errorf("Failed to schedule Pod %q: %v", test.pod.Name, err)
			}
		}

		// Validate PVC/PV binding
		for _, pvc := range test.pvcs {
			validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimBound)
		}
		for _, pvc := range test.unboundPvcs {
			validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimPending)
		}
		for _, pv := range test.pvs {
			validatePVPhase(t, config.client, pv.name, v1.VolumeBound)
		}
		for _, pv := range test.unboundPvs {
			validatePVPhase(t, config.client, pv.name, v1.VolumeAvailable)
		}

		// Force delete objects, but they still may not be immediately removed
		deleteTestObjects(config.client, config.ns, deleteOption)
	}
}

// TestVolumeBindingRescheduling tests scheduler will retry scheduling when needed.
func TestVolumeBindingRescheduling(t *testing.T) {
	features := map[string]bool{
		"VolumeScheduling":       true,
		"PersistentLocalVolumes": true,
	}
	config := setupCluster(t, "volume-scheduling-", 2, features, 0, 0, false)
	defer config.teardown()

	storageClassName := "local-storage"

	cases := map[string]struct {
		pod        *v1.Pod
		pvcs       []*testPVC
		pvs        []*testPV
		trigger    func(config *testConfig)
		shouldFail bool
	}{
		"reschedule on WaitForFirstConsumer dynamic storage class add": {
			pod: makePod("pod-reschedule-onclassadd-dynamic", config.ns, []string{"pvc-reschedule-onclassadd-dynamic"}),
			pvcs: []*testPVC{
				{"pvc-reschedule-onclassadd-dynamic", "", ""},
			},
			trigger: func(config *testConfig) {
				sc := makeDynamicProvisionerStorageClass(storageClassName, &modeWait)
				if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
					t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
				}
			},
			shouldFail: false,
		},
		"reschedule on WaitForFirstConsumer static storage class add": {
			pod: makePod("pod-reschedule-onclassadd-static", config.ns, []string{"pvc-reschedule-onclassadd-static"}),
			pvcs: []*testPVC{
				{"pvc-reschedule-onclassadd-static", "", ""},
			},
			trigger: func(config *testConfig) {
				sc := makeStorageClass(storageClassName, &modeWait)
				if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
					t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
				}
				// Create pv for this class to mock static provisioner behavior.
				pv := makePV("pv-reschedule-onclassadd-static", storageClassName, "", "", node1)
				if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
					t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
				}
			},
			shouldFail: false,
		},
		"reschedule on delay binding PVC add": {
			pod: makePod("pod-reschedule-onpvcadd", config.ns, []string{"pvc-reschedule-onpvcadd"}),
			pvs: []*testPV{
				{
					name:   "pv-reschedule-onpvcadd",
					scMode: modeWait,
					node:   node1,
				},
			},
			trigger: func(config *testConfig) {
				pvc := makePVC("pvc-reschedule-onpvcadd", config.ns, &classWait, "")
				if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
					t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
				}
			},
			shouldFail: false,
		},
	}

	for name, test := range cases {
		glog.Infof("Running test %v", name)

		if test.pod == nil {
			t.Fatal("pod is required for this test")
		}

		// Create unbound pvc
		for _, pvcConfig := range test.pvcs {
			pvc := makePVC(pvcConfig.name, config.ns, &storageClassName, "")
			if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
				t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
			}
		}

		// Create PVs
		for _, pvConfig := range test.pvs {
			pv := makePV(pvConfig.name, sharedClasses[pvConfig.scMode].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
			if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
				t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
			}
		}

		// Create pod
		if _, err := config.client.CoreV1().Pods(config.ns).Create(test.pod); err != nil {
			t.Fatalf("Failed to create Pod %q: %v", test.pod.Name, err)
		}

		// Wait for pod is unschedulable.
		glog.Infof("Waiting for pod is unschedulable")
		if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
			t.Errorf("Failed as Pod %s was not unschedulable: %v", test.pod.Name, err)
		}

		// Trigger
		test.trigger(config)

		// Wait for pod is scheduled or unscheduable.
		if !test.shouldFail {
			glog.Infof("Waiting for pod is scheduled")
			if err := waitForPodToSchedule(config.client, test.pod); err != nil {
				t.Errorf("Failed to schedule Pod %q: %v", test.pod.Name, err)
			}
		} else {
			glog.Infof("Waiting for pod is unschedulable")
			if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
				t.Errorf("Failed as Pod %s was not unschedulable: %v", test.pod.Name, err)
			}
		}

		// Force delete objects, but they still may not be immediately removed
		deleteTestObjects(config.client, config.ns, deleteOption)
	}
}

// TestVolumeBindingStress creates <podLimit> pods, each with <volsPerPod> unbound PVCs.
// PVs are precreated.
func TestVolumeBindingStress(t *testing.T) {
	testVolumeBindingStress(t, 0, false, 0)
}

// Like TestVolumeBindingStress but with scheduler resync. In real cluster,
// scheduler will schedule failed pod frequently due to various events, e.g.
// service/node update events.
// This is useful to detect possible race conditions.
func TestVolumeBindingStressWithSchedulerResync(t *testing.T) {
	testVolumeBindingStress(t, time.Second, false, 0)
}

// Like TestVolumeBindingStress but with fast dynamic provisioning
func TestVolumeBindingDynamicStressFast(t *testing.T) {
	testVolumeBindingStress(t, 0, true, 0)
}

// Like TestVolumeBindingStress but with slow dynamic provisioning
func TestVolumeBindingDynamicStressSlow(t *testing.T) {
	testVolumeBindingStress(t, 0, true, 30)
}

func testVolumeBindingStress(t *testing.T, schedulerResyncPeriod time.Duration, dynamic bool, provisionDelaySeconds int) {
	features := map[string]bool{
		"VolumeScheduling":       true,
		"PersistentLocalVolumes": true,
	}
	config := setupCluster(t, "volume-binding-stress-", 1, features, schedulerResyncPeriod, provisionDelaySeconds, false)
	defer config.teardown()

	// Set max volume limit to the number of PVCs the test will create
	// TODO: remove when max volume limit allows setting through storageclass
	if err := os.Setenv(predicates.KubeMaxPDVols, fmt.Sprintf("%v", podLimit*volsPerPod)); err != nil {
		t.Fatalf("failed to set max pd limit: %v", err)
	}
	defer os.Unsetenv(predicates.KubeMaxPDVols)

	scName := &classWait
	if dynamic {
		scName = &classDynamic
		sc := makeDynamicProvisionerStorageClass(*scName, &modeWait)
		if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
			t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
		}
	}

	// Create enough PVs and PVCs for all the pods
	pvs := []*v1.PersistentVolume{}
	pvcs := []*v1.PersistentVolumeClaim{}
	for i := 0; i < podLimit*volsPerPod; i++ {
		// Don't create pvs for dynamic provisioning test
		if !dynamic {
			pv := makePV(fmt.Sprintf("pv-stress-%v", i), *scName, "", "", node1)
			if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
				t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
			}
			pvs = append(pvs, pv)
		}

		pvc := makePVC(fmt.Sprintf("pvc-stress-%v", i), config.ns, scName, "")
		if pvc, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
			t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
		}
		pvcs = append(pvcs, pvc)
	}

	pods := []*v1.Pod{}
	for i := 0; i < podLimit; i++ {
		// Generate string of all the PVCs for the pod
		podPvcs := []string{}
		for j := i * volsPerPod; j < (i+1)*volsPerPod; j++ {
			podPvcs = append(podPvcs, pvcs[j].Name)
		}

		pod := makePod(fmt.Sprintf("pod%03d", i), config.ns, podPvcs)
		if pod, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
			t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
		}
		pods = append(pods, pod)
	}

	// Validate Pods scheduled
	for _, pod := range pods {
		// Use increased timeout for stress test because there is a higher chance of
		// PV sync error
		if err := waitForPodToScheduleWithTimeout(config.client, pod, 2*time.Minute); err != nil {
			t.Errorf("Failed to schedule Pod %q: %v", pod.Name, err)
		}
	}

	// Validate PVC/PV binding
	for _, pvc := range pvcs {
		validatePVCPhase(t, config.client, pvc.Name, config.ns, v1.ClaimBound)
	}
	for _, pv := range pvs {
		validatePVPhase(t, config.client, pv.Name, v1.VolumeBound)
	}
}

func testVolumeBindingWithAffinity(t *testing.T, anti bool, numNodes, numPods, numPVsFirstNode int) {
	features := map[string]bool{
		"VolumeScheduling":       true,
		"PersistentLocalVolumes": true,
	}
	// TODO: disable equivalence cache until kubernetes/kubernetes#67680 is fixed
	config := setupCluster(t, "volume-pod-affinity-", numNodes, features, 0, 0, true)
	defer config.teardown()

	pods := []*v1.Pod{}
	pvcs := []*v1.PersistentVolumeClaim{}
	pvs := []*v1.PersistentVolume{}

	// Create PVs for the first node
	for i := 0; i < numPVsFirstNode; i++ {
		pv := makePV(fmt.Sprintf("pv-node1-%v", i), classWait, "", "", node1)
		if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
			t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
		}
		pvs = append(pvs, pv)
	}

	// Create 1 PV per Node for the remaining nodes
	for i := 2; i <= numNodes; i++ {
		pv := makePV(fmt.Sprintf("pv-node%v-0", i), classWait, "", "", fmt.Sprintf("node-%v", i))
		if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
			t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
		}
		pvs = append(pvs, pv)
	}

	// Create pods
	for i := 0; i < numPods; i++ {
		// Create one pvc per pod
		pvc := makePVC(fmt.Sprintf("pvc-%v", i), config.ns, &classWait, "")
		if pvc, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
			t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
		}
		pvcs = append(pvcs, pvc)

		// Create pod with pod affinity
		pod := makePod(fmt.Sprintf("pod%03d", i), config.ns, []string{pvc.Name})
		pod.Spec.Affinity = &v1.Affinity{}
		affinityTerms := []v1.PodAffinityTerm{
			{
				LabelSelector: &metav1.LabelSelector{
					MatchExpressions: []metav1.LabelSelectorRequirement{
						{
							Key:      "app",
							Operator: metav1.LabelSelectorOpIn,
							Values:   []string{"volume-binding-test"},
						},
					},
				},
				TopologyKey: nodeAffinityLabelKey,
			},
		}
		if anti {
			pod.Spec.Affinity.PodAntiAffinity = &v1.PodAntiAffinity{
				RequiredDuringSchedulingIgnoredDuringExecution: affinityTerms,
			}
		} else {
			pod.Spec.Affinity.PodAffinity = &v1.PodAffinity{
				RequiredDuringSchedulingIgnoredDuringExecution: affinityTerms,
			}
		}

		if pod, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
			t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
		}
		pods = append(pods, pod)
	}

	// Validate Pods scheduled
	scheduledNodes := sets.NewString()
	for _, pod := range pods {
		if err := waitForPodToSchedule(config.client, pod); err != nil {
			t.Errorf("Failed to schedule Pod %q: %v", pod.Name, err)
		} else {
			// Keep track of all the nodes that the Pods were scheduled on
			pod, err = config.client.CoreV1().Pods(config.ns).Get(pod.Name, metav1.GetOptions{})
			if err != nil {
				t.Fatalf("Failed to get Pod %q: %v", pod.Name, err)
			}
			if pod.Spec.NodeName == "" {
				t.Fatalf("Pod %q node name unset after scheduling", pod.Name)
			}
			scheduledNodes.Insert(pod.Spec.NodeName)
		}
	}

	// Validate the affinity policy
	if anti {
		// The pods should have been spread across different nodes
		if scheduledNodes.Len() != numPods {
			t.Errorf("Pods were scheduled across %v nodes instead of %v", scheduledNodes.Len(), numPods)
		}
	} else {
		// The pods should have been scheduled on 1 node
		if scheduledNodes.Len() != 1 {
			t.Errorf("Pods were scheduled across %v nodes instead of %v", scheduledNodes.Len(), 1)
		}
	}

	// Validate PVC binding
	for _, pvc := range pvcs {
		validatePVCPhase(t, config.client, pvc.Name, config.ns, v1.ClaimBound)
	}
}

func TestVolumeBindingWithAntiAffinity(t *testing.T) {
	numNodes := 10
	// Create as many pods as number of nodes
	numPods := numNodes
	// Create many more PVs on node1 to increase chance of selecting node1
	numPVsFirstNode := 10 * numNodes

	testVolumeBindingWithAffinity(t, true, numNodes, numPods, numPVsFirstNode)
}

func TestVolumeBindingWithAffinity(t *testing.T) {
	numPods := 10
	// Create many more nodes to increase chance of selecting a PV on a different node than node1
	numNodes := 10 * numPods
	// Create numPods PVs on the first node
	numPVsFirstNode := numPods

	testVolumeBindingWithAffinity(t, true, numNodes, numPods, numPVsFirstNode)
}

func TestPVAffinityConflict(t *testing.T) {
	features := map[string]bool{
		"VolumeScheduling":       true,
		"PersistentLocalVolumes": true,
	}
	config := setupCluster(t, "volume-scheduling-", 3, features, 0, 0, false)
	defer config.teardown()

	pv := makePV("local-pv", classImmediate, "", "", node1)
	pvc := makePVC("local-pvc", config.ns, &classImmediate, "")

	// Create PV
	if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
		t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
	}

	// Create PVC
	if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
		t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
	}

	// Wait for PVC bound
	if err := waitForPVCBound(config.client, pvc); err != nil {
		t.Fatalf("PVC %q failed to bind: %v", pvc.Name, err)
	}

	nodeMarkers := []interface{}{
		markNodeAffinity,
		markNodeSelector,
	}
	for i := 0; i < len(nodeMarkers); i++ {
		podName := "local-pod-" + strconv.Itoa(i+1)
		pod := makePod(podName, config.ns, []string{"local-pvc"})
		nodeMarkers[i].(func(*v1.Pod, string))(pod, "node-2")
		// Create Pod
		if _, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
			t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
		}
		// Give time to shceduler to attempt to schedule pod
		if err := waitForPodUnschedulable(config.client, pod); err != nil {
			t.Errorf("Failed as Pod %s was not unschedulable: %v", pod.Name, err)
		}
		// Check pod conditions
		p, err := config.client.CoreV1().Pods(config.ns).Get(podName, metav1.GetOptions{})
		if err != nil {
			t.Fatalf("Failed to access Pod %s status: %v", podName, err)
		}
		if strings.Compare(string(p.Status.Phase), "Pending") != 0 {
			t.Fatalf("Failed as Pod %s was in: %s state and not in expected: Pending state", podName, p.Status.Phase)
		}
		if strings.Compare(p.Status.Conditions[0].Reason, "Unschedulable") != 0 {
			t.Fatalf("Failed as Pod %s reason was: %s but expected: Unschedulable", podName, p.Status.Conditions[0].Reason)
		}
		if !strings.Contains(p.Status.Conditions[0].Message, "node(s) didn't match node selector") || !strings.Contains(p.Status.Conditions[0].Message, "node(s) had volume node affinity conflict") {
			t.Fatalf("Failed as Pod's %s failure message does not contain expected message: node(s) didn't match node selector, node(s) had volume node affinity conflict. Got message %q", podName, p.Status.Conditions[0].Message)
		}
		// Deleting test pod
		if err := config.client.CoreV1().Pods(config.ns).Delete(podName, &metav1.DeleteOptions{}); err != nil {
			t.Fatalf("Failed to delete Pod %s: %v", podName, err)
		}
	}
}

func setupCluster(t *testing.T, nsName string, numberOfNodes int, features map[string]bool, resyncPeriod time.Duration, provisionDelaySeconds int, disableEquivalenceCache bool) *testConfig {
	oldFeatures := make(map[string]bool, len(features))
	for feature := range features {
		oldFeatures[feature] = utilfeature.DefaultFeatureGate.Enabled(utilfeature.Feature(feature))
	}
	// Set feature gates
	utilfeature.DefaultFeatureGate.SetFromMap(features)

	controllerCh := make(chan struct{})

	context := initTestSchedulerWithOptions(t, initTestMaster(t, nsName, nil), controllerCh, false, nil, false, disableEquivalenceCache, resyncPeriod)

	clientset := context.clientSet
	ns := context.ns.Name
	// Informers factory for controllers, we disable resync period for testing.
	informerFactory := informers.NewSharedInformerFactory(context.clientSet, 0)

	// Start PV controller for volume binding.
	host := volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)
	plugin := &volumetest.FakeVolumePlugin{
		PluginName:             provisionerPluginName,
		Host:                   host,
		Config:                 volume.VolumeConfig{},
		LastProvisionerOptions: volume.VolumeOptions{},
		ProvisionDelaySeconds:  provisionDelaySeconds,
		NewAttacherCallCount:   0,
		NewDetacherCallCount:   0,
		Mounters:               nil,
		Unmounters:             nil,
		Attachers:              nil,
		Detachers:              nil,
	}
	plugins := []volume.VolumePlugin{plugin}

	controllerOptions := persistentvolumeoptions.NewPersistentVolumeControllerOptions()
	params := persistentvolume.ControllerParameters{
		KubeClient:                clientset,
		SyncPeriod:                controllerOptions.PVClaimBinderSyncPeriod,
		VolumePlugins:             plugins,
		Cloud:                     nil,
		ClusterName:               "volume-test-cluster",
		VolumeInformer:            informerFactory.Core().V1().PersistentVolumes(),
		ClaimInformer:             informerFactory.Core().V1().PersistentVolumeClaims(),
		ClassInformer:             informerFactory.Storage().V1().StorageClasses(),
		PodInformer:               informerFactory.Core().V1().Pods(),
		NodeInformer:              informerFactory.Core().V1().Nodes(),
		EnableDynamicProvisioning: true,
	}
	ctrl, err := persistentvolume.NewController(params)
	if err != nil {
		t.Fatalf("Failed to create PV controller: %v", err)
	}
	go ctrl.Run(controllerCh)
	// Start informer factory after all controllers are configured and running.
	informerFactory.Start(controllerCh)
	informerFactory.WaitForCacheSync(controllerCh)

	// Create shared objects
	// Create nodes
	for i := 0; i < numberOfNodes; i++ {
		testNode := &v1.Node{
			ObjectMeta: metav1.ObjectMeta{
				Name:   fmt.Sprintf("node-%d", i+1),
				Labels: map[string]string{nodeAffinityLabelKey: fmt.Sprintf("node-%d", i+1)},
			},
			Spec: v1.NodeSpec{Unschedulable: false},
			Status: v1.NodeStatus{
				Capacity: v1.ResourceList{
					v1.ResourcePods: *resource.NewQuantity(podLimit, resource.DecimalSI),
				},
				Conditions: []v1.NodeCondition{
					{
						Type:              v1.NodeReady,
						Status:            v1.ConditionTrue,
						Reason:            fmt.Sprintf("schedulable condition"),
						LastHeartbeatTime: metav1.Time{Time: time.Now()},
					},
				},
			},
		}
		if _, err := clientset.CoreV1().Nodes().Create(testNode); err != nil {
			t.Fatalf("Failed to create Node %q: %v", testNode.Name, err)
		}
	}

	// Create SCs
	for _, sc := range sharedClasses {
		if _, err := clientset.StorageV1().StorageClasses().Create(sc); err != nil {
			t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
		}
	}

	return &testConfig{
		client: clientset,
		ns:     ns,
		stop:   controllerCh,
		teardown: func() {
			deleteTestObjects(clientset, ns, nil)
			cleanupTest(t, context)
			// Restore feature gates
			utilfeature.DefaultFeatureGate.SetFromMap(oldFeatures)
		},
	}
}

func deleteTestObjects(client clientset.Interface, ns string, option *metav1.DeleteOptions) {
	client.CoreV1().Pods(ns).DeleteCollection(option, metav1.ListOptions{})
	client.CoreV1().PersistentVolumeClaims(ns).DeleteCollection(option, metav1.ListOptions{})
	client.CoreV1().PersistentVolumes().DeleteCollection(option, metav1.ListOptions{})
	client.StorageV1().StorageClasses().DeleteCollection(option, metav1.ListOptions{})
}

func makeStorageClass(name string, mode *storagev1.VolumeBindingMode) *storagev1.StorageClass {
	return &storagev1.StorageClass{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Provisioner:       "kubernetes.io/no-provisioner",
		VolumeBindingMode: mode,
	}
}

func makeDynamicProvisionerStorageClass(name string, mode *storagev1.VolumeBindingMode) *storagev1.StorageClass {
	return &storagev1.StorageClass{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Provisioner:       provisionerPluginName,
		VolumeBindingMode: mode,
	}
}

func makePV(name, scName, pvcName, ns, node string) *v1.PersistentVolume {
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name:        name,
			Annotations: map[string]string{},
		},
		Spec: v1.PersistentVolumeSpec{
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): resource.MustParse("5Gi"),
			},
			AccessModes: []v1.PersistentVolumeAccessMode{
				v1.ReadWriteOnce,
			},
			StorageClassName: scName,
			PersistentVolumeSource: v1.PersistentVolumeSource{
				Local: &v1.LocalVolumeSource{
					Path: "/test-path",
				},
			},
			NodeAffinity: &v1.VolumeNodeAffinity{
				Required: &v1.NodeSelector{
					NodeSelectorTerms: []v1.NodeSelectorTerm{
						{
							MatchExpressions: []v1.NodeSelectorRequirement{
								{
									Key:      nodeAffinityLabelKey,
									Operator: v1.NodeSelectorOpIn,
									Values:   []string{node},
								},
							},
						},
					},
				},
			},
		},
	}

	if pvcName != "" {
		pv.Spec.ClaimRef = &v1.ObjectReference{Name: pvcName, Namespace: ns}
	}

	return pv
}

func makePVC(name, ns string, scName *string, volumeName string) *v1.PersistentVolumeClaim {
	return &v1.PersistentVolumeClaim{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: ns,
		},
		Spec: v1.PersistentVolumeClaimSpec{
			AccessModes: []v1.PersistentVolumeAccessMode{
				v1.ReadWriteOnce,
			},
			Resources: v1.ResourceRequirements{
				Requests: v1.ResourceList{
					v1.ResourceName(v1.ResourceStorage): resource.MustParse("5Gi"),
				},
			},
			StorageClassName: scName,
			VolumeName:       volumeName,
		},
	}
}

func makePod(name, ns string, pvcs []string) *v1.Pod {
	volumes := []v1.Volume{}
	for i, pvc := range pvcs {
		volumes = append(volumes, v1.Volume{
			Name: fmt.Sprintf("vol%v", i),
			VolumeSource: v1.VolumeSource{
				PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
					ClaimName: pvc,
				},
			},
		})
	}

	return &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: ns,
			Labels: map[string]string{
				"app": "volume-binding-test",
			},
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:    "write-pod",
					Image:   imageutils.GetE2EImage(imageutils.BusyBox),
					Command: []string{"/bin/sh"},
					Args:    []string{"-c", "while true; do sleep 1; done"},
				},
			},
			Volumes: volumes,
		},
	}
}

func validatePVCPhase(t *testing.T, client clientset.Interface, pvcName string, ns string, phase v1.PersistentVolumeClaimPhase) {
	claim, err := client.CoreV1().PersistentVolumeClaims(ns).Get(pvcName, metav1.GetOptions{})
	if err != nil {
		t.Errorf("Failed to get PVC %v/%v: %v", ns, pvcName, err)
	}

	if claim.Status.Phase != phase {
		t.Errorf("PVC %v/%v phase not %v, got %v", ns, pvcName, phase, claim.Status.Phase)
	}
}

func validatePVPhase(t *testing.T, client clientset.Interface, pvName string, phase v1.PersistentVolumePhase) {
	pv, err := client.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{})
	if err != nil {
		t.Errorf("Failed to get PV %v: %v", pvName, err)
	}

	if pv.Status.Phase != phase {
		t.Errorf("PV %v phase not %v, got %v", pvName, phase, pv.Status.Phase)
	}
}

func waitForPVCBound(client clientset.Interface, pvc *v1.PersistentVolumeClaim) error {
	return wait.Poll(time.Second, 30*time.Second, func() (bool, error) {
		claim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{})
		if err != nil {
			return false, err
		}
		if claim.Status.Phase == v1.ClaimBound {
			return true, nil
		}
		return false, nil
	})
}

func markNodeAffinity(pod *v1.Pod, node string) {
	affinity := &v1.Affinity{
		NodeAffinity: &v1.NodeAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
				NodeSelectorTerms: []v1.NodeSelectorTerm{
					{
						MatchExpressions: []v1.NodeSelectorRequirement{
							{
								Key:      nodeAffinityLabelKey,
								Operator: v1.NodeSelectorOpIn,
								Values:   []string{node},
							},
						},
					},
				},
			},
		},
	}
	pod.Spec.Affinity = affinity
}

func markNodeSelector(pod *v1.Pod, node string) {
	ns := map[string]string{
		nodeAffinityLabelKey: node,
	}
	pod.Spec.NodeSelector = ns
}


text:
require 'spec_helper'

require 'cod/channel'

describe Cod::Channel do
  let(:channel) { described_class.new }
  describe '#interact' do
    it "should issue a put, followed by a get" do
      flexmock(channel).
        should_receive(:put).with(:msg).once.ordered.
        should_receive(:get).and_return(:result).once.ordered

      channel.interact(:msg).assert == :result
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--  LegendShop 版权所有 2009-2011,并保留所有权利。 -->
<hibernate-mapping>
    <class name="com.legendshop.model.entity.Sort" table="ls_sort">
        	<!--
	 <cache usage="read-write"/>
	  -->
        <id name="sortId" type="java.lang.Long">
            <column name="sort_id" />
            <generator class="native" />
        </id>
        <property name="sortName" type="java.lang.String">
            <column name="sort_name">
                <comment>分类名称</comment>
            </column>
        </property>
        <property name="picture" type="java.lang.String">
            <column name="picture">
                <comment>分类的显示图片</comment>
            </column>
        </property>
        <property name="seq" type="java.lang.Integer">
            <column name="seq">
                <comment>商品分类顺序</comment>
            </column>
        </property>
        <property name="status" type="java.lang.Integer">
            <column name="status">
                <comment>默认是1,表示正常状态,0为下线状态</comment>
            </column>
        </property>
         <property name="sortType" type="java.lang.String">
            <column name="sort_type">
                <comment>产品分类类型</comment>
            </column>
        </property>
        <property name="userId" type="java.lang.String">
            <column name="user_id">
                <comment>用户ID</comment>
            </column>
        </property>
        <property name="userName" type="java.lang.String">
            <column name="user_name">
                <comment>用户名称</comment>
            </column>
        </property>
        <property name="headerMenu" type="java.lang.Integer">
            <column name="header_menu">
                <comment>分类状态,1:首页菜单展示,0:首页菜单不展示</comment>
            </column>
        </property>
        <property name="navigationMenu" type="java.lang.Integer">
            <column name="navigation_menu">
                <comment>分类状态,1:首页菜单展示,0:首页菜单不展示</comment>
            </column>
        </property>
    </class>
</hibernate-mapping>


text:
#ifndef VIO_STRINGS_H
#define VIO_STRINGS_H

#include "context.h"
#include "error.h"

vio_err_t vio_strcat(vio_ctx *ctx);

vio_err_t vio_strsplit(vio_ctx *ctx);

/* various edit distance functions (levenshtein and sift4) */
uint32_t vio_sift4_dist(uint32_t alen, const char *a, uint32_t blen, const char *b, int maxoff, int maxdist);

vio_err_t vio_edit_dist(vio_ctx *ctx);
vio_err_t vio_approx_edit_dist(vio_ctx *ctx);

/* sorted suffix array */
vio_err_t vio_sorted_sufarray(vio_ctx *ctx);

/* longest common substring */
vio_err_t vio_lcss(vio_ctx *ctx);

/* burrows-wheeler transform */
vio_err_t vio_bwtransform(vio_ctx *ctx);

#endif


text:
using System;

namespace _4._1
{
    /// <summary>
    /// исключение, возникающее при вводе некорректного выражения
    /// </summary>
    [Serializable]
    public class IncorrectExpressionException : Exception
    {
        public IncorrectExpressionException() { }
        public IncorrectExpressionException(string message) : base(message) { }
        public IncorrectExpressionException(string message, Exception inner) : base(message, inner) { }
        protected IncorrectExpressionException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
    }
}


text:
<?php

namespace openvidsys\Http\Controllers\Universal;

use Validator;
use Hash;
use DB;
use File;
use Response;
use Storage;

use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Auth;

use openvidsys\User;
use openvidsys\Model\Attachment;
use openvidsys\Http\Controllers\Controller;

/**
 * Controller for file manager related methods
 */
class FileController extends Controller
{
  /**
   * User model instance
   *
   * @var User
   */
  protected $user;

  /**
   * For Guard
   *
   * @var Authenticator
   */
  protected $auth;

  /**
   * Create a new controller instance.
   *
   * @param Guard $auth
   * @param User $user
   *
   * @return void
   */
  public function __construct(Guard $auth, User $user)
  {
      $this->user = $user;
      $this->auth = $auth;
  }

  /**
   * GET To download file after matching filetoken
   *
   * @param  string $filetoken
   *
   * @return Response
   */
  public function getFile($filetoken){
    $entry = Attachment::where('file_token', '=', $filetoken)->firstOrFail();
    $storagePath = storage_path().'/app/userfiles/uploads/'.$entry->user->username.'/'.$entry->file_name;
    return response()->download($storagePath);
  }
}


text:
package org.nd4j.linalg.api.ops.impl.transforms.comparison;

import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseTransformOp;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.indexing.conditions.Condition;

/**
 * Element-wise Compare-and-Replace implementation as Op
 * Basically this op does the same as Compare-and-Set, but op.X is checked against Condition instead
 *
 * @author raver119@gmail.com
 */
public class CompareAndReplace extends BaseTransformOp {

    private double compare;
    private double set;
    private double eps;
    private int mode;

    public CompareAndReplace() {

    }

    /**
     * With this constructor, op will check each X element against given Condition, and if condition met, element Z will be set to Y value, and X otherwise
     *
     * PLEASE NOTE: X will be modified inplace.
     *
     * Pseudocode:
     * z[i] = condition(x[i]) ? y[i] : x[i];
     *
     * @param x
     * @param y
     * @param condition
     */
    public CompareAndReplace(INDArray x, INDArray y, Condition condition) {
        this(x, y, x, condition);
    }

    /**
     * With this constructor, op will check each X element against given Condition, and if condition met, element Z will be set to Y value, and X otherwise
     *
     * Pseudocode:
     * z[i] = condition(x[i]) ? y[i] : x[i];
     *
     * @param x
     * @param y
     * @param z
     * @param condition
     */
    public CompareAndReplace(INDArray x, INDArray y, INDArray z, Condition condition) {
        super(x, y, z, x.lengthLong());
        this.compare = condition.getValue();
        this.set = 0;
        this.mode = condition.condtionNum();
        init(x, y, z, x.lengthLong());
    }

    @Override
    public int opNum() {
        return 46;
    }

    @Override
    public String name() {
        return "car";
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, double other) {
        return null;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, float other) {
        return null;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, IComplexNumber other) {
        return null;
    }

    @Override
    public float op(float origin, float other) {
        return 0;
    }

    @Override
    public double op(double origin, double other) {
        return 0;
    }

    @Override
    public double op(double origin) {
        return 0;
    }

    @Override
    public float op(float origin) {
        return 0;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin) {
        return null;

    }

    /**
     * A copy of this operation for a particular dimension of the input
     *
     * @param index     the index of the op to iterate over
     * @param dimension the dimension to ge the input for
     * @return the operation for that dimension
     */
    @Override
    public Op opForDimension(int index, int dimension) {
        return null;
    }

    /**
     * A copy of this operation for a particular dimension of the input
     *
     * @param index     the index of the op to iterate over
     * @param dimension the dimension to ge the input for
     * @return the operation for that dimension
     */
    @Override
    public Op opForDimension(int index, int... dimension) {
        return null;
    }

    @Override
    public void init(INDArray x, INDArray y, INDArray z, long n) {
        super.init(x, y, z, n);
        this.extraArgs = new Object[] {compare, set, eps, (double) mode};
    }
}