text:
require File.dirname(__FILE__) + '/test_web_service'

class WebServiceWithServiceNameSet < TestWebService
    service_name :FooService
end


text:
package main.java.de.frigerius.frostbot.commands;

import com.github.theholywaffle.teamspeak3.api.wrapper.Client;

import main.java.de.frigerius.frostbot.ServerInfo;

public class ServerGroupInfoCommand extends BaseCommand
{

	public ServerGroupInfoCommand(int cmdPwr)
	{
		super("getsginfo", cmdPwr);
	}

	@Override
	protected CommandResult handleIntern(Client c, String[] args)
	{
		ServerInfo.getServerGroups();
		return CommandResult.NoErrors;
	}

	@Override
	public boolean hasClientRights(Client c,int cmdPwr)
	{
		return true;
	}

	@Override
	public String getArguments()
	{
		return "";
	}

	@Override
	public String getDescription()
	{
		return "";
	}

	@Override
	protected String getDetails()
	{
		return "";
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>LYFCB:登录</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<link href="../assets/common/bootstrap.css" rel="stylesheet"	type="text/css" />
<link href="../assets/common/bootstrap.responsive.css" rel="stylesheet"	type="text/css" />

		<form class="form-vertical login-form">

后台管理系统

				账户:

				<input type="text" class="form-control" id="login_username" style="background-color: #F9F9F9;">

				密码:

				<input type="password" class="form-control" id="login_password" style="background-color: #F9F9F9;">

				<button type="button" class="btn" style="background-color: #89D44E; margin: 25px 35% 0 35%; width: 30%; height: 45px;"
					onclick="doLogin()">
					登录
				</button>

注:建议使用Chrome|Safari|Firefox|Opera等浏览器访问此网站,暂不建议使用IE.

		</form>


text:
package io.crate.rest.action;

import io.crate.action.sql.DescribeResult;
import io.crate.action.sql.ResultReceiver;
import io.crate.action.sql.SQLOperations;
import io.crate.action.sql.Session;
import io.crate.action.sql.SessionContext;
import io.crate.action.sql.parser.SQLRequestParseContext;
import io.crate.action.sql.parser.SQLRequestParser;
import io.crate.auth.AuthSettings;
import io.crate.auth.user.AccessControl;
import io.crate.auth.user.User;
import io.crate.auth.user.UserLookup;
import io.crate.breaker.BlockBasedRamAccounting;
import io.crate.breaker.RamAccounting;
import io.crate.breaker.RowAccountingWithEstimators;
import io.crate.exceptions.SQLExceptions;
import io.crate.expression.symbol.Symbol;
import io.crate.expression.symbol.Symbols;
import io.crate.protocols.http.Headers;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.http.netty4.cors.Netty4CorsConfig;
import org.elasticsearch.http.netty4.cors.Netty4CorsHandler;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
import org.elasticsearch.transport.netty4.Netty4Utils;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

import static io.crate.action.sql.Session.UNNAMED;
import static io.crate.breaker.BlockBasedRamAccounting.MAX_BLOCK_SIZE_IN_BYTES;
import static io.crate.protocols.http.Headers.isCloseConnection;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;

public class SqlHttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger LOGGER = LogManager.getLogger(SqlHttpHandler.class);
    private static final String REQUEST_HEADER_USER = "User";
    private static final String REQUEST_HEADER_SCHEMA = "Default-Schema";

    private final Settings settings;
    private final SQLOperations sqlOperations;
    private final Function<String, CircuitBreaker> circuitBreakerProvider;
    private final UserLookup userLookup;
    private final Function<SessionContext, AccessControl> getAccessControl;
    private final Netty4CorsConfig corsConfig;

    private Session session;

    SqlHttpHandler(Settings settings,
                   SQLOperations sqlOperations,
                   Function<String, CircuitBreaker> circuitBreakerProvider,
                   UserLookup userLookup,
                   Function<SessionContext, AccessControl> getAccessControl,
                   Netty4CorsConfig corsConfig) {
        super(false);
        this.settings = settings;
        this.sqlOperations = sqlOperations;
        this.circuitBreakerProvider = circuitBreakerProvider;
        this.userLookup = userLookup;
        this.getAccessControl = getAccessControl;
        this.corsConfig = corsConfig;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
        if (request.uri().startsWith("/_sql")) {
            Session session = ensureSession(request);
            Map<String, List<String>> parameters = new QueryStringDecoder(request.uri()).parameters();
            ByteBuf content = request.content();
            handleSQLRequest(session, content, paramContainFlag(parameters, "types"))
                .whenComplete((result, t) -> {
                    try {
                        sendResponse(session, ctx, request, parameters, result, t);
                    } catch (Throwable ex) {
                        LOGGER.error("Error sending response", ex);
                        throw ex;
                    } finally {
                        request.release();
                    }
                });
        } else {
            ctx.fireChannelRead(request);
        }
    }

    /**
     * @return true if the parameters contains a flag entry (e.g. "/_sql?flag" or "/_sql?flag=true")
     */
    private static boolean paramContainFlag(Map<String, List<String>> parameters, String flag) {
        List<String> values = parameters.get(flag);
        return values != null && (values.equals(singletonList("")) || values.equals(singletonList("true")));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        if (session != null) {
            session.close();
            session = null;
        }
        super.channelUnregistered(ctx);
    }

    private void sendResponse(Session session,
                              ChannelHandlerContext ctx,
                              FullHttpRequest request,
                              Map<String, List<String>> parameters,
                              XContentBuilder result,
                              @Nullable Throwable t) {
        final HttpVersion httpVersion = request.protocolVersion();
        final DefaultFullHttpResponse resp;
        final ByteBuf content;
        if (t == null) {
            content = Netty4Utils.toByteBuf(BytesReference.bytes(result));
            resp = new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.OK, content);
            resp.headers().add(HttpHeaderNames.CONTENT_TYPE, result.contentType().mediaType());
        } else {
            var throwable = SQLExceptions.prepareForClientTransmission(getAccessControl.apply(session.sessionContext()), t);
            HttpError httpError = HttpError.fromThrowable(throwable);
            String mediaType;
            boolean includeErrorTrace = paramContainFlag(parameters, "error_trace");
            try (XContentBuilder contentBuilder = httpError.toXContent(includeErrorTrace)) {
                content = Netty4Utils.toByteBuf(BytesReference.bytes(contentBuilder));
                mediaType = contentBuilder.contentType().mediaType();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            resp = new DefaultFullHttpResponse(
                httpVersion,
                httpError.httpResponseStatus(),
                content
            );
            resp.headers().add(HttpHeaderNames.CONTENT_TYPE, mediaType);
        }
        Netty4CorsHandler.setCorsResponseHeaders(request, resp, corsConfig);
        resp.headers().add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(content.readableBytes()));
        boolean closeConnection = isCloseConnection(request);
        ChannelPromise promise = ctx.newPromise();
        if (closeConnection) {
            promise.addListener(ChannelFutureListener.CLOSE);
        } else {
            Headers.setKeepAlive(httpVersion, resp);
        }
        ctx.writeAndFlush(resp, promise);
    }

    private CompletableFuture<XContentBuilder> handleSQLRequest(Session session, ByteBuf content, boolean includeTypes) {
        SQLRequestParseContext parseContext;
        try {
            parseContext = SQLRequestParser.parseSource(Netty4Utils.toBytesReference(content));
        } catch (Throwable t) {
            return CompletableFuture.failedFuture(t);
        }
        List<Object> args = parseContext.args();
        List<List<Object>> bulkArgs = parseContext.bulkArgs();
        if (bothProvided(args, bulkArgs)) {
            return CompletableFuture.failedFuture(new IllegalArgumentException(
                "request body contains args and bulk_args. It's forbidden to provide both"));
        }
        try {
            if (args != null || bulkArgs == null) {
                return executeSimpleRequest(session, parseContext.stmt(), args, includeTypes);
            } else {
                return executeBulkRequest(session, parseContext.stmt(), bulkArgs);
            }
        } catch (Throwable t) {
            return CompletableFuture.failedFuture(t);
        }
    }

    private Session ensureSession(FullHttpRequest request) {
        String defaultSchema = request.headers().get(REQUEST_HEADER_SCHEMA);
        User authenticatedUser = userFromAuthHeader(request.headers().get(HttpHeaderNames.AUTHORIZATION));
        Session session = this.session;
        if (session == null) {
            session = sqlOperations.createSession(defaultSchema, authenticatedUser);
        } else if (session.sessionContext().authenticatedUser().equals(authenticatedUser) == false) {
            session.close();
            session = sqlOperations.createSession(defaultSchema, authenticatedUser);
        } else {
            // We don't want to keep "set session" settings across requests yet to not mess with clients doing
            // per request round-robin
            SessionContext sessionContext = session.sessionContext();
            sessionContext.resetToDefaults();
            if (defaultSchema != null) {
                sessionContext.setSearchPath(defaultSchema);
            }
        }
        this.session = session;
        return session;
    }

    private CompletableFuture<XContentBuilder> executeSimpleRequest(Session session,
                                                                    String stmt,
                                                                    List<Object> args,
                                                                    boolean includeTypes) throws IOException {
        long startTimeInNs = System.nanoTime();
        session.parse(UNNAMED, stmt, emptyList());
        session.bind(UNNAMED, UNNAMED, args == null ? emptyList() : args, null);
        DescribeResult description = session.describe('P', UNNAMED);
        List<Symbol> resultFields = description.getFields();
        ResultReceiver<XContentBuilder> resultReceiver;
        if (resultFields == null) {
            resultReceiver = new RestRowCountReceiver(JsonXContent.contentBuilder(), startTimeInNs, includeTypes);
        } else {
            CircuitBreaker breaker = circuitBreakerProvider.apply(HierarchyCircuitBreakerService.QUERY);
            RamAccounting ramAccounting = new BlockBasedRamAccounting(
                b -> breaker.addEstimateBytesAndMaybeBreak(b, "http-result"),
                MAX_BLOCK_SIZE_IN_BYTES);
            resultReceiver = new RestResultSetReceiver(
                JsonXContent.contentBuilder(),
                resultFields,
                startTimeInNs,
                new RowAccountingWithEstimators(
                    Symbols.typeView(resultFields),
                    ramAccounting
                ),
                includeTypes
            );
            resultReceiver.completionFuture().whenComplete((result, error) -> ramAccounting.close());
        }
        session.execute(UNNAMED, 0, resultReceiver);
        return session.sync()
            .thenCompose(ignored -> resultReceiver.completionFuture());
    }

    private CompletableFuture<XContentBuilder> executeBulkRequest(Session session,
                                                                  String stmt,
                                                                  List<List<Object>> bulkArgs) {
        final long startTimeInNs = System.nanoTime();
        session.parse(UNNAMED, stmt, emptyList());
        final RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[bulkArgs.size()];
        for (int i = 0; i < bulkArgs.size(); i++) {
            session.bind(UNNAMED, UNNAMED, bulkArgs.get(i), null);
            ResultReceiver resultReceiver = new RestBulkRowCountReceiver(results, i);
            session.execute(UNNAMED, 0, resultReceiver);
        }
        if (results.length > 0) {
            DescribeResult describeResult = session.describe('P', UNNAMED);
            if (describeResult.getFields() != null) {
                return CompletableFuture.failedFuture(new UnsupportedOperationException(
                            "Bulk operations for statements that return result sets is not supported"));
            }
        }
        return session.sync()
            .thenApply(ignored -> {
                try {
                    return ResultToXContentBuilder.builder(JsonXContent.contentBuilder())
                        .cols(emptyList())
                        .duration(startTimeInNs)
                        .bulkRows(results)
                        .build();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
    }

    User userFromAuthHeader(@Nullable String authHeaderValue) {
        String username = Headers.extractCredentialsFromHttpBasicAuthHeader(authHeaderValue).v1();
        // Fallback to trusted user from configuration
        if (username == null || username.isEmpty()) {
            username = AuthSettings.AUTH_TRUST_HTTP_DEFAULT_HEADER.setting().get(settings);
        }
        return userLookup.findUser(username);
    }

    private static boolean bothProvided(@Nullable List<Object> args, @Nullable List<List<Object>> bulkArgs) {
        return args != null && !args.isEmpty() && bulkArgs != null && !bulkArgs.isEmpty();
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/modules/plugin/base/public/nsIPluginStreamListener.idl
 */

#ifndef __gen_nsIPluginStreamListener_h__
#define __gen_nsIPluginStreamListener_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nspluginroot_h__
#include "nspluginroot.h"
#endif

#ifndef __gen_nsIPluginStreamInfo_h__
#include "nsIPluginStreamInfo.h"
#endif

#ifndef __gen_nsIInputStream_h__
#include "nsIInputStream.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
#include "npapi.h"

/* starting interface:    nsIPluginStreamListener */
#define NS_IPLUGINSTREAMLISTENER_IID_STR "02c9dad7-d9dd-4f36-bd5e-93ca404a31bc"

#define NS_IPLUGINSTREAMLISTENER_IID \
  {0x02c9dad7, 0xd9dd, 0x4f36, \
    { 0xbd, 0x5e, 0x93, 0xca, 0x40, 0x4a, 0x31, 0xbc }}

/**
 * The nsIPluginStreamListener interface defines the minimum set of functionality that
 * the browser will support if it allows plugins. Plugins can call QueryInterface
 * to determine if a plugin manager implements more specific APIs or other
 * browser interfaces for the plugin to use (e.g. nsINetworkManager).
 */
class NS_NO_VTABLE nsIPluginStreamListener : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPLUGINSTREAMLISTENER_IID)

  /**
     * Notify the observer that the URL has started to load.  This method is
     * called only once, at the beginning of a URL load.

   *
   * @param aPluginInfo  - plugin stream info
   * @return             - the return value is currently ignored, in the future
   * it may be used to cancel the URL load..
     */
  /* void onStartBinding (in nsIPluginStreamInfo aPluginInfo); */
  NS_IMETHOD OnStartBinding(nsIPluginStreamInfo *aPluginInfo) = 0;

  /**
     * Notify the client that data is available in the input stream.  This
     * method is called whenver data is written into the input stream by the
     * networking library...

     *
   * @param aPluginInfo  - plugin stream info
   * @param aInputStream - the input stream containing the data. This stream can
     * be either a blocking or non-blocking stream.
   * @param aLength      - the amount of data that was just pushed into the stream.
   * @return             - the return value is currently ignored.
     */
  /* void onDataAvailable (in nsIPluginStreamInfo aPluginInfo, in nsIInputStream aInputStream, in unsigned long aLength); */
  NS_IMETHOD OnDataAvailable(nsIPluginStreamInfo *aPluginInfo, nsIInputStream *aInputStream, PRUint32 aLength) = 0;

  /**
   * Notify the client that data is available in the file.
   *
   * @param aPluginInfo - plugin stream info
   * @param aFileName   - the name of the file containing the data
   * @return            - the return value is currently ignored.
   */
  /* void onFileAvailable (in nsIPluginStreamInfo aPluginInfo, in string aFileName); */
  NS_IMETHOD OnFileAvailable(nsIPluginStreamInfo *aPluginInfo, const char *aFileName) = 0;

  /**
     * Notify the observer that the URL has finished loading.  This method is
     * called once when the networking library has finished processing the
   * URL transaction initiatied via the nsINetService::Open(...) call.

     *
     * This method is called regardless of whether the URL loaded successfully.

     *
   * @param aPluginInfo - plugin stream info
   * @param aStatus     - reason why the stream has been terminated
   * @return            - the return value is currently ignored.
     */
  /* void onStopBinding (in nsIPluginStreamInfo aPluginInfo, in nsresult aStatus); */
  NS_IMETHOD OnStopBinding(nsIPluginStreamInfo *aPluginInfo, nsresult aStatus) = 0;

  /**
   * Gets the type of the stream
   *
   * @param aStreamType - the type of the stream
   */
  /* readonly attribute PRInt32 streamType; */
  NS_IMETHOD GetStreamType(PRInt32 *aStreamType) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIPluginStreamListener, NS_IPLUGINSTREAMLISTENER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIPLUGINSTREAMLISTENER \
  NS_IMETHOD OnStartBinding(nsIPluginStreamInfo *aPluginInfo); \
  NS_IMETHOD OnDataAvailable(nsIPluginStreamInfo *aPluginInfo, nsIInputStream *aInputStream, PRUint32 aLength); \
  NS_IMETHOD OnFileAvailable(nsIPluginStreamInfo *aPluginInfo, const char *aFileName); \
  NS_IMETHOD OnStopBinding(nsIPluginStreamInfo *aPluginInfo, nsresult aStatus); \
  NS_IMETHOD GetStreamType(PRInt32 *aStreamType);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIPLUGINSTREAMLISTENER(_to) \
  NS_IMETHOD OnStartBinding(nsIPluginStreamInfo *aPluginInfo) { return _to OnStartBinding(aPluginInfo); } \
  NS_IMETHOD OnDataAvailable(nsIPluginStreamInfo *aPluginInfo, nsIInputStream *aInputStream, PRUint32 aLength) { return _to OnDataAvailable(aPluginInfo, aInputStream, aLength); } \
  NS_IMETHOD OnFileAvailable(nsIPluginStreamInfo *aPluginInfo, const char *aFileName) { return _to OnFileAvailable(aPluginInfo, aFileName); } \
  NS_IMETHOD OnStopBinding(nsIPluginStreamInfo *aPluginInfo, nsresult aStatus) { return _to OnStopBinding(aPluginInfo, aStatus); } \
  NS_IMETHOD GetStreamType(PRInt32 *aStreamType) { return _to GetStreamType(aStreamType); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIPLUGINSTREAMLISTENER(_to) \
  NS_IMETHOD OnStartBinding(nsIPluginStreamInfo *aPluginInfo) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnStartBinding(aPluginInfo); } \
  NS_IMETHOD OnDataAvailable(nsIPluginStreamInfo *aPluginInfo, nsIInputStream *aInputStream, PRUint32 aLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnDataAvailable(aPluginInfo, aInputStream, aLength); } \
  NS_IMETHOD OnFileAvailable(nsIPluginStreamInfo *aPluginInfo, const char *aFileName) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnFileAvailable(aPluginInfo, aFileName); } \
  NS_IMETHOD OnStopBinding(nsIPluginStreamInfo *aPluginInfo, nsresult aStatus) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnStopBinding(aPluginInfo, aStatus); } \
  NS_IMETHOD GetStreamType(PRInt32 *aStreamType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStreamType(aStreamType); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsPluginStreamListener : public nsIPluginStreamListener
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIPLUGINSTREAMLISTENER

  nsPluginStreamListener();

private:
  ~nsPluginStreamListener();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsPluginStreamListener, nsIPluginStreamListener)

nsPluginStreamListener::nsPluginStreamListener()
{
  /* member initializers and constructor code */
}

nsPluginStreamListener::~nsPluginStreamListener()
{
  /* destructor code */
}

/* void onStartBinding (in nsIPluginStreamInfo aPluginInfo); */
NS_IMETHODIMP nsPluginStreamListener::OnStartBinding(nsIPluginStreamInfo *aPluginInfo)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void onDataAvailable (in nsIPluginStreamInfo aPluginInfo, in nsIInputStream aInputStream, in unsigned long aLength); */
NS_IMETHODIMP nsPluginStreamListener::OnDataAvailable(nsIPluginStreamInfo *aPluginInfo, nsIInputStream *aInputStream, PRUint32 aLength)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void onFileAvailable (in nsIPluginStreamInfo aPluginInfo, in string aFileName); */
NS_IMETHODIMP nsPluginStreamListener::OnFileAvailable(nsIPluginStreamInfo *aPluginInfo, const char *aFileName)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void onStopBinding (in nsIPluginStreamInfo aPluginInfo, in nsresult aStatus); */
NS_IMETHODIMP nsPluginStreamListener::OnStopBinding(nsIPluginStreamInfo *aPluginInfo, nsresult aStatus)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute PRInt32 streamType; */
NS_IMETHODIMP nsPluginStreamListener::GetStreamType(PRInt32 *aStreamType)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIPluginStreamListener_h__ */


text:
package jp.sourceforge.ea2ddl.dao.bsentity;

import java.io.Serializable;
import java.util.*;

import org.seasar.dbflute.Entity;
import org.seasar.dbflute.dbmeta.DBMeta;
import jp.sourceforge.ea2ddl.dao.allcommon.DBMetaInstanceHandler;

/**
 * The entity of t_xref that the type is TABLE.

 *

 * [primary-key]
 *
 *
 * [column]
 *     XrefID, Name, Type, Visibility, Namespace, Requirement, Constraint, Behavior, Partition, Description, Client, Supplier, Link
 *
 * [sequence]
 *
 *
 * [identity]
 *
 *
 * [version-no]
 *
 *
 * [foreign-table]
 *
 *
 * [referrer-table]
 *
 *
 * [foreign-property]
 *
 *
 * [referrer-property]
 *
 *

 * @author DBFlute(AutoGenerator)
 */
public abstract class BsTXref implements Entity, Serializable {

    // ===================================================================================
    //                                                                          Definition
    //                                                                          ==========
    /** Serial version UID. (Default) */
    private static final long serialVersionUID = 1L;

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    // -----------------------------------------------------
    //                                                Column
    //                                                ------
    /** XrefID: {UQ : VARCHAR(255)} */
    protected String _xrefid;

    /** Name: {VARCHAR(255)} */
    protected String _name;

    /** Type: {VARCHAR(255)} */
    protected String _type;

    /** Visibility: {VARCHAR(255)} */
    protected String _visibility;

    /** Namespace: {VARCHAR(255)} */
    protected String _namespace;

    /** Requirement: {VARCHAR(255)} */
    protected String _requirement;

    /** Constraint: {VARCHAR(255)} */
    protected String _constraint;

    /** Behavior: {VARCHAR(255)} */
    protected String _behavior;

    /** Partition: {VARCHAR(255)} */
    protected String _partition;

    /** Description: {LONGCHAR(2147483647)} */
    protected String _description;

    /** Client: {VARCHAR(255)} */
    protected String _client;

    /** Supplier: {VARCHAR(255)} */
    protected String _supplier;

    /** Link: {VARCHAR(255)} */
    protected String _link;

    // -----------------------------------------------------
    //                                              Internal
    //                                              --------
    /** The attribute of entity modified properties. (for S2Dao) */
    protected EntityModifiedProperties _modifiedProperties = newEntityModifiedProperties();

    // ===================================================================================
    //                                                                          Table Name
    //                                                                          ==========
    public String getTableDbName() {
        return "t_xref";
    }

    public String getTablePropertyName() { // as JavaBeansRule
        return "TXref";
    }

    // ===================================================================================
    //                                                                              DBMeta
    //                                                                              ======
    public DBMeta getDBMeta() {
        return DBMetaInstanceHandler.findDBMeta(getTableDbName());
    }

    // ===================================================================================
    //                                                          Classification Classifying
    //                                                          ==========================
    // ===================================================================================
    //                                                        Classification Determination
    //                                                        ============================
    // ===================================================================================
    //                                                           Classification Name/Alias
    //                                                           =========================
    // ===================================================================================
    //                                                                    Foreign Property
    //                                                                    ================
    // ===================================================================================
    //                                                                   Referrer Property
    //                                                                   =================
    // ===================================================================================
    //                                                                       Determination
    //                                                                       =============
    public boolean hasPrimaryKeyValue() {
        return false;
    }

    // ===================================================================================
    //                                                                 Modified Properties
    //                                                                 ===================
    public Set<String> getModifiedPropertyNames() {
        return _modifiedProperties.getPropertyNames();
    }

    protected EntityModifiedProperties newEntityModifiedProperties() {
        return new EntityModifiedProperties();
    }

    public void clearModifiedPropertyNames() {
        _modifiedProperties.clear();
    }

    public boolean hasModification() {
        return !_modifiedProperties.isEmpty();
    }

    // ===================================================================================
    //                                                                      Basic Override
    //                                                                      ==============
    /**
     * If the all-column value of the other is same as this one, returns true.
     * @param other Other entity. (Nullable)
     * @return Comparing result. If other is null, returns false.
     */
    public boolean equals(Object other) {
        if (other == null || !(other instanceof BsTXref)) { return false; }
        final BsTXref otherEntity = (BsTXref)other;
        if (!helpComparingValue(getXrefid(), otherEntity.getXrefid())) { return false; }
        if (!helpComparingValue(getName(), otherEntity.getName())) { return false; }
        if (!helpComparingValue(getType(), otherEntity.getType())) { return false; }
        if (!helpComparingValue(getVisibility(), otherEntity.getVisibility())) { return false; }
        if (!helpComparingValue(getNamespace(), otherEntity.getNamespace())) { return false; }
        if (!helpComparingValue(getRequirement(), otherEntity.getRequirement())) { return false; }
        if (!helpComparingValue(getConstraint(), otherEntity.getConstraint())) { return false; }
        if (!helpComparingValue(getBehavior(), otherEntity.getBehavior())) { return false; }
        if (!helpComparingValue(getPartition(), otherEntity.getPartition())) { return false; }
        if (!helpComparingValue(getDescription(), otherEntity.getDescription())) { return false; }
        if (!helpComparingValue(getClient(), otherEntity.getClient())) { return false; }
        if (!helpComparingValue(getSupplier(), otherEntity.getSupplier())) { return false; }
        if (!helpComparingValue(getLink(), otherEntity.getLink())) { return false; }
        return true;
    }

    protected boolean helpComparingValue(Object value1, Object value2) {
        if (value1 == null && value2 == null) { return true; }
        return value1 != null && value2 != null && value1.equals(value2);
    }

    /**
     * Calculates hash-code from all columns.
     * @return Hash-code from all-columns.
     */
    public int hashCode() {
        int result = 17;
        if (this.getXrefid() != null) { result = result + this.getXrefid().hashCode(); }
        if (this.getName() != null) { result = result + this.getName().hashCode(); }
        if (this.getType() != null) { result = result + this.getType().hashCode(); }
        if (this.getVisibility() != null) { result = result + this.getVisibility().hashCode(); }
        if (this.getNamespace() != null) { result = result + this.getNamespace().hashCode(); }
        if (this.getRequirement() != null) { result = result + this.getRequirement().hashCode(); }
        if (this.getConstraint() != null) { result = result + this.getConstraint().hashCode(); }
        if (this.getBehavior() != null) { result = result + this.getBehavior().hashCode(); }
        if (this.getPartition() != null) { result = result + this.getPartition().hashCode(); }
        if (this.getDescription() != null) { result = result + this.getDescription().hashCode(); }
        if (this.getClient() != null) { result = result + this.getClient().hashCode(); }
        if (this.getSupplier() != null) { result = result + this.getSupplier().hashCode(); }
        if (this.getLink() != null) { result = result + this.getLink().hashCode(); }
        return result;
    }

    /**
     * @return The view string of columns. (NotNull)
     */
    public String toString() {
        String delimiter = ",";
        StringBuilder sb = new StringBuilder();
        sb.append(delimiter).append(getXrefid());
        sb.append(delimiter).append(getName());
        sb.append(delimiter).append(getType());
        sb.append(delimiter).append(getVisibility());
        sb.append(delimiter).append(getNamespace());
        sb.append(delimiter).append(getRequirement());
        sb.append(delimiter).append(getConstraint());
        sb.append(delimiter).append(getBehavior());
        sb.append(delimiter).append(getPartition());
        sb.append(delimiter).append(getDescription());
        sb.append(delimiter).append(getClient());
        sb.append(delimiter).append(getSupplier());
        sb.append(delimiter).append(getLink());
        if (sb.length() > 0) { sb.delete(0, delimiter.length()); }
        sb.insert(0, "{").append("}");
        return sb.toString();
    }

    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    /**
     * XrefID: {UQ : VARCHAR(255)}

     * @return The value of the column 'XrefID'. (Nullable)
     */
    public String getXrefid() {
        return _xrefid;
    }

    /**
     * XrefID: {UQ : VARCHAR(255)}

     * @param xrefid The value of the column 'XrefID'. (Nullable)
     */
    public void setXrefid(String xrefid) {
        _modifiedProperties.addPropertyName("xrefid");
        this._xrefid = xrefid;
    }

    /**
     * Name: {VARCHAR(255)}

     * @return The value of the column 'Name'. (Nullable)
     */
    public String getName() {
        return _name;
    }

    /**
     * Name: {VARCHAR(255)}

     * @param name The value of the column 'Name'. (Nullable)
     */
    public void setName(String name) {
        _modifiedProperties.addPropertyName("name");
        this._name = name;
    }

    /**
     * Type: {VARCHAR(255)}

     * @return The value of the column 'Type'. (Nullable)
     */
    public String getType() {
        return _type;
    }

    /**
     * Type: {VARCHAR(255)}

     * @param type The value of the column 'Type'. (Nullable)
     */
    public void setType(String type) {
        _modifiedProperties.addPropertyName("type");
        this._type = type;
    }

    /**
     * Visibility: {VARCHAR(255)}

     * @return The value of the column 'Visibility'. (Nullable)
     */
    public String getVisibility() {
        return _visibility;
    }

    /**
     * Visibility: {VARCHAR(255)}

     * @param visibility The value of the column 'Visibility'. (Nullable)
     */
    public void setVisibility(String visibility) {
        _modifiedProperties.addPropertyName("visibility");
        this._visibility = visibility;
    }

    /**
     * Namespace: {VARCHAR(255)}

     * @return The value of the column 'Namespace'. (Nullable)
     */
    public String getNamespace() {
        return _namespace;
    }

    /**
     * Namespace: {VARCHAR(255)}

     * @param namespace The value of the column 'Namespace'. (Nullable)
     */
    public void setNamespace(String namespace) {
        _modifiedProperties.addPropertyName("namespace");
        this._namespace = namespace;
    }

    /**
     * Requirement: {VARCHAR(255)}

     * @return The value of the column 'Requirement'. (Nullable)
     */
    public String getRequirement() {
        return _requirement;
    }

    /**
     * Requirement: {VARCHAR(255)}

     * @param requirement The value of the column 'Requirement'. (Nullable)
     */
    public void setRequirement(String requirement) {
        _modifiedProperties.addPropertyName("requirement");
        this._requirement = requirement;
    }

    /**
     * Constraint: {VARCHAR(255)}

     * @return The value of the column 'Constraint'. (Nullable)
     */
    public String getConstraint() {
        return _constraint;
    }

    /**
     * Constraint: {VARCHAR(255)}

     * @param constraint The value of the column 'Constraint'. (Nullable)
     */
    public void setConstraint(String constraint) {
        _modifiedProperties.addPropertyName("constraint");
        this._constraint = constraint;
    }

    /**
     * Behavior: {VARCHAR(255)}

     * @return The value of the column 'Behavior'. (Nullable)
     */
    public String getBehavior() {
        return _behavior;
    }

    /**
     * Behavior: {VARCHAR(255)}

     * @param behavior The value of the column 'Behavior'. (Nullable)
     */
    public void setBehavior(String behavior) {
        _modifiedProperties.addPropertyName("behavior");
        this._behavior = behavior;
    }

    /**
     * Partition: {VARCHAR(255)}

     * @return The value of the column 'Partition'. (Nullable)
     */
    public String getPartition() {
        return _partition;
    }

    /**
     * Partition: {VARCHAR(255)}

     * @param partition The value of the column 'Partition'. (Nullable)
     */
    public void setPartition(String partition) {
        _modifiedProperties.addPropertyName("partition");
        this._partition = partition;
    }

    /**
     * Description: {LONGCHAR(2147483647)}

     * @return The value of the column 'Description'. (Nullable)
     */
    public String getDescription() {
        return _description;
    }

    /**
     * Description: {LONGCHAR(2147483647)}

     * @param description The value of the column 'Description'. (Nullable)
     */
    public void setDescription(String description) {
        _modifiedProperties.addPropertyName("description");
        this._description = description;
    }

    /**
     * Client: {VARCHAR(255)}

     * @return The value of the column 'Client'. (Nullable)
     */
    public String getClient() {
        return _client;
    }

    /**
     * Client: {VARCHAR(255)}

     * @param client The value of the column 'Client'. (Nullable)
     */
    public void setClient(String client) {
        _modifiedProperties.addPropertyName("client");
        this._client = client;
    }

    /**
     * Supplier: {VARCHAR(255)}

     * @return The value of the column 'Supplier'. (Nullable)
     */
    public String getSupplier() {
        return _supplier;
    }

    /**
     * Supplier: {VARCHAR(255)}

     * @param supplier The value of the column 'Supplier'. (Nullable)
     */
    public void setSupplier(String supplier) {
        _modifiedProperties.addPropertyName("supplier");
        this._supplier = supplier;
    }

    /**
     * Link: {VARCHAR(255)}

     * @return The value of the column 'Link'. (Nullable)
     */
    public String getLink() {
        return _link;
    }

    /**
     * Link: {VARCHAR(255)}

     * @param link The value of the column 'Link'. (Nullable)
     */
    public void setLink(String link) {
        _modifiedProperties.addPropertyName("link");
        this._link = link;
    }
}


text:
class CAffect : public CExpression
{
public:
	const CIdentifier& ident;
	int type;
	int opType;
	CInteger& param;
	CExpression& ov1;
	CExpression& ov2;
	llvm::Value* tmpResult;
	llvm::Value* ov1Val;
	llvm::Value* ov2Val;
	static CInteger emptyParam;

	CAffect(CIdentifier& ident, int type) : ident(ident), type(type), param(emptyParam), ov1(ident), ov2(ident) { }
	CAffect(CIdentifier& ident, int type, CInteger& param) : ident(ident), type(type), param(param), ov1(ident), ov2(ident) { }
	CAffect(CIdentifier& ident, int type, CExpression& ov1, CExpression& ov2, CInteger& param) : ident(ident), type(type), opType(type), param(param), ov1(ov1), ov2(ov2) { }

	llvm::Value* codeGenCarry(CodeGenContext& context, llvm::Value* exprResult, llvm::Value* lhs, llvm::Value* rhs, int type);
	llvm::Value* codeGenFinal(CodeGenContext& context, llvm::Value* exprResult);
};


text:
require "cases/helper"
require "models/book"
require "models/post"
require "models/author"
require "models/event"

module ActiveRecord
  class AdapterTest < ActiveRecord::TestCase
    def setup
      @connection = ActiveRecord::Base.connection
    end

    ##
    # PostgreSQL does not support null bytes in strings
    unless current_adapter?(:PostgreSQLAdapter) ||
        (current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.connection.prepared_statements)
      def test_update_prepared_statement
        b = Book.create(name: "my \x00 book")
        b.reload
        assert_equal "my \x00 book", b.name
        b.update(name: "my other \x00 book")
        b.reload
        assert_equal "my other \x00 book", b.name
      end
    end

    def test_create_record_with_pk_as_zero
      Book.create(id: 0)
      assert_equal 0, Book.find(0).id
      assert_nothing_raised { Book.destroy(0) }
    end

    def test_valid_column
      @connection.native_database_types.each_key do |type|
        assert @connection.valid_type?(type)
      end
    end

    def test_invalid_column
      assert_not @connection.valid_type?(:foobar)
    end

    def test_tables
      tables = @connection.tables
      assert_includes tables, "accounts"
      assert_includes tables, "authors"
      assert_includes tables, "tasks"
      assert_includes tables, "topics"
    end

    def test_table_exists?
      assert @connection.table_exists?("accounts")
      assert @connection.table_exists?(:accounts)
      assert_not @connection.table_exists?("nonexistingtable")
      assert_not @connection.table_exists?("'")
      assert_not @connection.table_exists?(nil)
    end

    def test_data_sources
      data_sources = @connection.data_sources
      assert_includes data_sources, "accounts"
      assert_includes data_sources, "authors"
      assert_includes data_sources, "tasks"
      assert_includes data_sources, "topics"
    end

    def test_data_source_exists?
      assert @connection.data_source_exists?("accounts")
      assert @connection.data_source_exists?(:accounts)
      assert_not @connection.data_source_exists?("nonexistingtable")
      assert_not @connection.data_source_exists?("'")
      assert_not @connection.data_source_exists?(nil)
    end

    def test_indexes
      idx_name = "accounts_idx"

      indexes = @connection.indexes("accounts")
      assert_empty indexes

      @connection.add_index :accounts, :firm_id, name: idx_name
      indexes = @connection.indexes("accounts")
      assert_equal "accounts", indexes.first.table
      assert_equal idx_name, indexes.first.name
      assert_not indexes.first.unique
      assert_equal ["firm_id"], indexes.first.columns
    ensure
      @connection.remove_index(:accounts, name: idx_name) rescue nil
    end

    def test_remove_index_when_name_and_wrong_column_name_specified
      index_name = "accounts_idx"

      @connection.add_index :accounts, :firm_id, name: index_name
      assert_raises ArgumentError do
        @connection.remove_index :accounts, name: index_name, column: :wrong_column_name
      end
    ensure
      @connection.remove_index(:accounts, name: index_name)
    end

    def test_current_database
      if @connection.respond_to?(:current_database)
        assert_equal ARTest.connection_config["arunit"]["database"], @connection.current_database
      end
    end

    if current_adapter?(:Mysql2Adapter)
      def test_charset
        assert_not_nil @connection.charset
        assert_not_equal "character_set_database", @connection.charset
        assert_equal @connection.show_variable("character_set_database"), @connection.charset
      end

      def test_collation
        assert_not_nil @connection.collation
        assert_not_equal "collation_database", @connection.collation
        assert_equal @connection.show_variable("collation_database"), @connection.collation
      end

      def test_show_nonexistent_variable_returns_nil
        assert_nil @connection.show_variable("foo_bar_baz")
      end

      def test_not_specifying_database_name_for_cross_database_selects
        begin
          assert_nothing_raised do
            ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["arunit"].except(:database))

            config = ARTest.connection_config
            ActiveRecord::Base.connection.execute(
              "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \
              "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses"
            )
          end
        ensure
          ActiveRecord::Base.establish_connection :arunit
        end
      end
    end

    def test_table_alias
      def @connection.test_table_alias_length() 10; end
      class << @connection
        alias_method :old_table_alias_length, :table_alias_length
        alias_method :table_alias_length,     :test_table_alias_length
      end

      assert_equal "posts",      @connection.table_alias_for("posts")
      assert_equal "posts_comm", @connection.table_alias_for("posts_comments")
      assert_equal "dbo_posts",  @connection.table_alias_for("dbo.posts")

      class << @connection
        remove_method :table_alias_length
        alias_method :table_alias_length, :old_table_alias_length
      end
    end

    def test_uniqueness_violations_are_translated_to_specific_exception
      @connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
      error = assert_raises(ActiveRecord::RecordNotUnique) do
        @connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
      end

      assert_not_nil error.cause
    end

    def test_not_null_violations_are_translated_to_specific_exception
      error = assert_raises(ActiveRecord::NotNullViolation) do
        Post.create
      end

      assert_not_nil error.cause
    end

    unless current_adapter?(:SQLite3Adapter)
      def test_value_limit_violations_are_translated_to_specific_exception
        error = assert_raises(ActiveRecord::ValueTooLong) do
          Event.create(title: "abcdefgh")
        end

        assert_not_nil error.cause
      end

      def test_numeric_value_out_of_ranges_are_translated_to_specific_exception
        error = assert_raises(ActiveRecord::RangeError) do
          Book.connection.create("INSERT INTO books(author_id) VALUES (9223372036854775808)")
        end

        assert_not_nil error.cause
      end
    end

    def test_exceptions_from_notifications_are_not_translated
      original_error = StandardError.new("This StandardError shouldn't get translated")
      subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") { raise original_error }
      actual_error = assert_raises(StandardError) do
        @connection.execute("SELECT * FROM posts")
      end

      assert_equal original_error, actual_error

    ensure
      ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
    end

    def test_database_related_exceptions_are_translated_to_statement_invalid
      error = assert_raises(ActiveRecord::StatementInvalid) do
        @connection.execute("This is a syntax error")
      end

      assert_instance_of ActiveRecord::StatementInvalid, error
      assert_kind_of Exception, error.cause
    end

    def test_select_all_always_return_activerecord_result
      result = @connection.select_all "SELECT * FROM posts"
      assert result.is_a?(ActiveRecord::Result)
    end

    if ActiveRecord::Base.connection.prepared_statements
      def test_select_all_with_legacy_binds
        post = Post.create!(title: "foo", body: "bar")
        expected = @connection.select_all("SELECT * FROM posts WHERE id = #{post.id}")
        result = @connection.select_all("SELECT * FROM posts WHERE id = #{Arel::Nodes::BindParam.new(nil).to_sql}", nil, [[nil, post.id]])
        assert_equal expected.to_hash, result.to_hash
      end

      def test_insert_update_delete_with_legacy_binds
        binds = [[nil, 1]]
        bind_param = Arel::Nodes::BindParam.new(nil)

        id = @connection.insert("INSERT INTO events(id) VALUES (#{bind_param.to_sql})", nil, nil, nil, nil, binds)
        assert_equal 1, id

        @connection.update("UPDATE events SET title = 'foo' WHERE id = #{bind_param.to_sql}", nil, binds)
        result = @connection.select_all("SELECT * FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        assert_equal({ "id" => 1, "title" => "foo" }, result.first)

        @connection.delete("DELETE FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        result = @connection.select_all("SELECT * FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        assert_nil result.first
      end

      def test_insert_update_delete_with_binds
        binds = [Relation::QueryAttribute.new("id", 1, Type.default_value)]
        bind_param = Arel::Nodes::BindParam.new(nil)

        id = @connection.insert("INSERT INTO events(id) VALUES (#{bind_param.to_sql})", nil, nil, nil, nil, binds)
        assert_equal 1, id

        @connection.update("UPDATE events SET title = 'foo' WHERE id = #{bind_param.to_sql}", nil, binds)
        result = @connection.select_all("SELECT * FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        assert_equal({ "id" => 1, "title" => "foo" }, result.first)

        @connection.delete("DELETE FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        result = @connection.select_all("SELECT * FROM events WHERE id = #{bind_param.to_sql}", nil, binds)
        assert_nil result.first
      end
    end

    def test_select_methods_passing_a_association_relation
      author = Author.create!(name: "john")
      Post.create!(author: author, title: "foo", body: "bar")
      query = author.posts.where(title: "foo").select(:title)
      assert_equal({ "title" => "foo" }, @connection.select_one(query))
      assert @connection.select_all(query).is_a?(ActiveRecord::Result)
      assert_equal "foo", @connection.select_value(query)
      assert_equal ["foo"], @connection.select_values(query)
    end

    def test_select_methods_passing_a_relation
      Post.create!(title: "foo", body: "bar")
      query = Post.where(title: "foo").select(:title)
      assert_equal({ "title" => "foo" }, @connection.select_one(query))
      assert @connection.select_all(query).is_a?(ActiveRecord::Result)
      assert_equal "foo", @connection.select_value(query)
      assert_equal ["foo"], @connection.select_values(query)
    end

    test "type_to_sql returns a String for unmapped types" do
      assert_equal "special_db_type", @connection.type_to_sql(:special_db_type)
    end

    unless current_adapter?(:PostgreSQLAdapter)
      def test_log_invalid_encoding
        error = assert_raises RuntimeError do
          @connection.send :log, "SELECT 'ы' FROM DUAL" do
            raise "ы".dup.force_encoding(Encoding::ASCII_8BIT)
          end
        end

        assert_equal "ы", error.message
      end
    end

    def test_supports_multi_insert_is_deprecated
      assert_deprecated { @connection.supports_multi_insert? }
    end
  end

  class AdapterForeignKeyTest < ActiveRecord::TestCase
    self.use_transactional_tests = false

    fixtures :fk_test_has_pk

    def setup
      @connection = ActiveRecord::Base.connection
    end

    def test_foreign_key_violations_are_translated_to_specific_exception_with_validate_false
      klass_has_fk = Class.new(ActiveRecord::Base) do
        self.table_name = "fk_test_has_fk"
      end

      error = assert_raises(ActiveRecord::InvalidForeignKey) do
        has_fk = klass_has_fk.new
        has_fk.fk_id = 1231231231
        has_fk.save(validate: false)
      end

      assert_not_nil error.cause
    end

    def test_foreign_key_violations_on_insert_are_translated_to_specific_exception
      error = assert_raises(ActiveRecord::InvalidForeignKey) do
        insert_into_fk_test_has_fk
      end

      assert_not_nil error.cause
    end

    def test_foreign_key_violations_on_delete_are_translated_to_specific_exception
      insert_into_fk_test_has_fk fk_id: 1

      error = assert_raises(ActiveRecord::InvalidForeignKey) do
        @connection.execute "DELETE FROM fk_test_has_pk WHERE pk_id = 1"
      end

      assert_not_nil error.cause
    end

    def test_disable_referential_integrity
      assert_nothing_raised do
        @connection.disable_referential_integrity do
          insert_into_fk_test_has_fk
          # should delete created record as otherwise disable_referential_integrity will try to enable constraints
          # after executed block and will fail (at least on Oracle)
          @connection.execute "DELETE FROM fk_test_has_fk"
        end
      end
    end

    private
      def insert_into_fk_test_has_fk(fk_id: 0)
        # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
        if @connection.prefetch_primary_key?
          id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id"))
          @connection.execute "INSERT INTO fk_test_has_fk (id,fk_id) VALUES (#{id_value},#{fk_id})"
        else
          @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (#{fk_id})"
        end
      end
  end

  class AdapterTestWithoutTransaction < ActiveRecord::TestCase
    self.use_transactional_tests = false

    class Klass < ActiveRecord::Base
    end

    def setup
      Klass.establish_connection :arunit
      @connection = Klass.connection
    end

    teardown do
      Klass.remove_connection
    end

    unless in_memory_db?
      test "transaction state is reset after a reconnect" do
        @connection.begin_transaction
        assert_predicate @connection, :transaction_open?
        @connection.reconnect!
        assert_not_predicate @connection, :transaction_open?
      end

      test "transaction state is reset after a disconnect" do
        @connection.begin_transaction
        assert_predicate @connection, :transaction_open?
        @connection.disconnect!
        assert_not_predicate @connection, :transaction_open?
      end
    end

    # test resetting sequences in odd tables in PostgreSQL
    if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
      require "models/movie"
      require "models/subscriber"

      def test_reset_empty_table_with_custom_pk
        Movie.delete_all
        Movie.connection.reset_pk_sequence! "movies"
        assert_equal 1, Movie.create(name: "fight club").id
      end

      def test_reset_table_with_non_integer_pk
        Subscriber.delete_all
        Subscriber.connection.reset_pk_sequence! "subscribers"
        sub = Subscriber.new(name: "robert drake")
        sub.id = "bob drake"
        assert_nothing_raised { sub.save! }
      end
    end
  end
end


text:
$GUID = [guid]::NewGuid().guid

#region create config on Pull Server
configuration telnet {
    param (
        $GUID
    )
    node $GUID {
        WindowsFeature telnetclient {
            Ensure = 'Present'
            Name = 'Telnet-Client'
        }
    }
}
telnet -GUID $GUID -OutputPath 'C:\Program Files\WindowsPowerShell\DscService\Configuration\'
New-DSCCheckSum -ConfigurationPath "C:\Program Files\WindowsPowerShell\DscService\Configuration\$GUID.mof"
#endregion create config on Pull Server

#region Configure LCM on dscclient01
configuration LCM {
    param (
        [Parameter(Mandatory)]
        [String] $GUID,

        [Parameter(Mandatory)]
        [String] $PullServerURL,

        [Parameter(Mandatory)]
        [String] $PullServerPort,

        [Parameter(Mandatory)]
        [Bool] $AllowUnsecureConnection,

        [Parameter(Mandatory)]
        [String] $Node
    )

    [String]$AllowUnsecure = $AllowUnsecureConnection.ToString($_)
    node $Node {
        LocalConfigurationManager {
            RefreshMode = 'Pull'
            ConfigurationMode = 'ApplyAndAutoCorrect'
            ConfigurationID = $GUID
            ActionAfterReboot = 'ContinueConfiguration'
            DownloadManagerCustomData = @{
                                        ServerUrl = "$PullServerURL`:$PullServerPort/PSDSCPullServer.svc";
				                        AllowUnsecureConnection = $AllowUnsecure;
                                        }
            DownloadManagerName = 'WebDownloadManager'
            ConfigurationModeFrequencyMins = 15
            RefreshFrequencyMins = 30
            RebootNodeIfNeeded = $true
            DebugMode = 'All'
        }
    }
}
$LCMHTTPArgs = @{
    OutputPath = 'c:\Configs\LCM';
    GUID = $GUID;
    PullServerURL = "http://$env:computername";
    PullServerPort = '8080';
    AllowUnsecureConnection = $true;
    Node = 'DSCClient01';
}

LCM @LCMHTTPArgs
$C = New-CimSession -ComputerName dscclient01
Get-DscLocalConfigurationManager -CimSession $c
Set-DscLocalConfigurationManager -CimSession $c -Path C:\Configs\LCM -Verbose
Get-DscLocalConfigurationManager -CimSession $c
Get-DscLocalConfigurationManager -CimSession $c | % DownloadManagerCustomData
#endregion Configure LCM on dscclient01

#region pull
Update-DscConfiguration -CimSession $c -Wait -Verbose
#endregion pull

#region cleanup
$C | Remove-CimSession
#endregion cleanup


text:
@implementation ZWDatabase

- (FMResultSet *)executeZWQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments{
    FMResultSet *result = [super executeQuery:sql withArgumentsInArray:arguments];
    return result;
}

- (BOOL)executeZWUpdate:(NSString *)sql withArgumentsInArray:(NSArray *)arguments{
    return [super executeUpdate:sql withArgumentsInArray:arguments];
}

- (BOOL)executeZWUpdate:(NSString *)sql{
    return [super executeUpdate:sql];
}

- (BOOL)executeZWStatements:(NSString *)sql{
    return [super executeStatements:sql];
}

@end


text:
<!doctype html>

  <title>v2</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="style2.css">

  <meta id="head-node"></meta>


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 3, 2015 4:33:50 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="ssd.app.model.Appointment" table="APPOINTMENT" lazy="false">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="created" type="java.util.Date">
            <column name="CREATED" />
        </property>
        <property name="modified" type="java.util.Date">
            <column name="MODIFIED" />
        </property>
        <property name="duration" type="double">
            <column name="DURATION" />
        </property>
        <many-to-one name="patient" class="ssd.app.model.Patient" fetch="join">
            <column name="PATIENT" />
        </many-to-one>
        <property name="description" type="java.lang.String">
            <column name="DESCRIPTION" />
        </property>
        <property name="calUID" type="java.lang.String">
            <column name="CALUID" />
        </property>
        <many-to-one name="service" class="ssd.app.model.Service" fetch="join">
            <column name="SERVICE" />
        </many-to-one>
        <property name="paid" type="java.lang.Boolean">
            <column name="PAID" default="FALSE"/>
        </property>
        <property name="date" type="java.sql.Timestamp">
            <column name="DATE" />
        </property>
        <many-to-one name="invoice" class="ssd.app.model.Invoice" fetch="join">
            <column name="INVOICE" not-null="false" />
        </many-to-one>
    </class>
</hibernate-mapping>


text:
module RablRails
  class Railtie < Rails::Railtie
    initializer 'rabl.actionview' do
      ActionView::Template.register_template_handler :rabl, RablRails::Handlers::Rabl
    end
    config.after_initialize do
      ActionController::Base.responder = RablRails::Responder if RablRails.configuration.use_custom_responder
    end
  end
end


text:
package org.apache.kafka.message;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

public final class ApiMessageTypeGenerator {
    private final HeaderGenerator headerGenerator;
    private final CodeBuffer buffer;
    private final TreeMap<Short, ApiData> apis;

    private static final class ApiData {
        short apiKey;
        MessageSpec requestSpec;
        MessageSpec responseSpec;

        ApiData(short apiKey) {
            this.apiKey = apiKey;
        }

        String name() {
            if (requestSpec != null) {
                return MessageGenerator.stripSuffix(requestSpec.name(),
                    MessageGenerator.REQUEST_SUFFIX);
            } else if (responseSpec != null) {
                return MessageGenerator.stripSuffix(responseSpec.name(),
                    MessageGenerator.RESPONSE_SUFFIX);
            } else {
                throw new RuntimeException("Neither requestSpec nor responseSpec is defined " +
                    "for API key " + apiKey);
            }
        }

        String requestSchema() {
            if (requestSpec == null) {
                return "null";
            } else {
                return String.format("%sData.SCHEMAS", requestSpec.name());
            }
        }

        String responseSchema() {
            if (responseSpec == null) {
                return "null";
            } else {
                return String.format("%sData.SCHEMAS", responseSpec.name());
            }
        }
    }

    public ApiMessageTypeGenerator(String packageName) {
        this.headerGenerator = new HeaderGenerator(packageName);
        this.apis = new TreeMap<>();
        this.buffer = new CodeBuffer();
    }

    public boolean hasRegisteredTypes() {
        return !apis.isEmpty();
    }

    public void registerMessageType(MessageSpec spec) {
        switch (spec.type()) {
            case REQUEST: {
                short apiKey = spec.apiKey().get();
                ApiData data = apis.get(apiKey);
                if (!apis.containsKey(apiKey)) {
                    data = new ApiData(apiKey);
                    apis.put(apiKey, data);
                }
                if (data.requestSpec != null) {
                    throw new RuntimeException("Found more than one request with " +
                        "API key " + spec.apiKey().get());
                }
                data.requestSpec = spec;
                break;
            }
            case RESPONSE: {
                short apiKey = spec.apiKey().get();
                ApiData data = apis.get(apiKey);
                if (!apis.containsKey(apiKey)) {
                    data = new ApiData(apiKey);
                    apis.put(apiKey, data);
                }
                if (data.responseSpec != null) {
                    throw new RuntimeException("Found more than one response with " +
                        "API key " + spec.apiKey().get());
                }
                data.responseSpec = spec;
                break;
            }
            default:
                // do nothing
                break;
        }
    }

    public void generate() {
        buffer.printf("public enum ApiMessageType {%n");
        buffer.incrementIndent();
        generateEnumValues();
        buffer.printf("%n");
        generateInstanceVariables();
        buffer.printf("%n");
        generateEnumConstructor();
        buffer.printf("%n");
        generateFromApiKey();
        buffer.printf("%n");
        generateNewApiMessageMethod("request");
        buffer.printf("%n");
        generateNewApiMessageMethod("response");
        buffer.printf("%n");
        generateAccessor("apiKey", "short");
        buffer.printf("%n");
        generateAccessor("requestSchemas", "Schema[]");
        buffer.printf("%n");
        generateAccessor("responseSchemas", "Schema[]");
        buffer.printf("%n");
        generateToString();
        buffer.printf("%n");
        generateHeaderVersion("request");
        buffer.printf("%n");
        generateHeaderVersion("response");
        buffer.decrementIndent();
        buffer.printf("}%n");
        headerGenerator.generate();
    }

    private void generateEnumValues() {
        int numProcessed = 0;
        for (Map.Entry<Short, ApiData> entry : apis.entrySet()) {
            ApiData apiData = entry.getValue();
            String name = apiData.name();
            numProcessed++;
            buffer.printf("%s(\"%s\", (short) %d, %s, %s)%s%n",
                MessageGenerator.toSnakeCase(name).toUpperCase(Locale.ROOT),
                MessageGenerator.capitalizeFirst(name),
                entry.getKey(),
                apiData.requestSchema(),
                apiData.responseSchema(),
                (numProcessed == apis.size()) ? ";" : ",");
        }
    }

    private void generateInstanceVariables() {
        buffer.printf("private final String name;%n");
        buffer.printf("private final short apiKey;%n");
        buffer.printf("private final Schema[] requestSchemas;%n");
        buffer.printf("private final Schema[] responseSchemas;%n");
        headerGenerator.addImport(MessageGenerator.SCHEMA_CLASS);
    }

    private void generateEnumConstructor() {
        buffer.printf("ApiMessageType(String name, short apiKey, " +
            "Schema[] requestSchemas, Schema[] responseSchemas) {%n");
        buffer.incrementIndent();
        buffer.printf("this.name = name;%n");
        buffer.printf("this.apiKey = apiKey;%n");
        buffer.printf("this.requestSchemas = requestSchemas;%n");
        buffer.printf("this.responseSchemas = responseSchemas;%n");
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    private void generateFromApiKey() {
        buffer.printf("public static ApiMessageType fromApiKey(short apiKey) {%n");
        buffer.incrementIndent();
        buffer.printf("switch (apiKey) {%n");
        buffer.incrementIndent();
        for (Map.Entry<Short, ApiData> entry : apis.entrySet()) {
            ApiData apiData = entry.getValue();
            String name = apiData.name();
            buffer.printf("case %d:%n", entry.getKey());
            buffer.incrementIndent();
            buffer.printf("return %s;%n", MessageGenerator.toSnakeCase(name).toUpperCase(Locale.ROOT));
            buffer.decrementIndent();
        }
        buffer.printf("default:%n");
        buffer.incrementIndent();
        headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
        buffer.printf("throw new UnsupportedVersionException(\"Unsupported API key \"" +
            " + apiKey);%n");
        buffer.decrementIndent();
        buffer.decrementIndent();
        buffer.printf("}%n");
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    private void generateNewApiMessageMethod(String type) {
        headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS);
        buffer.printf("public ApiMessage new%s() {%n",
            MessageGenerator.capitalizeFirst(type));
        buffer.incrementIndent();
        buffer.printf("switch (apiKey) {%n");
        buffer.incrementIndent();
        for (Map.Entry<Short, ApiData> entry : apis.entrySet()) {
            buffer.printf("case %d:%n", entry.getKey());
            buffer.incrementIndent();
            buffer.printf("return new %s%sData();%n",
                entry.getValue().name(),
                MessageGenerator.capitalizeFirst(type));
            buffer.decrementIndent();
        }
        buffer.printf("default:%n");
        buffer.incrementIndent();
        headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
        buffer.printf("throw new UnsupportedVersionException(\"Unsupported %s API key \"" +
            " + apiKey);%n", type);
        buffer.decrementIndent();
        buffer.decrementIndent();
        buffer.printf("}%n");
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    private void generateAccessor(String name, String type) {
        buffer.printf("public %s %s() {%n", type, name);
        buffer.incrementIndent();
        buffer.printf("return this.%s;%n", name);
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    private void generateToString() {
        buffer.printf("@Override%n");
        buffer.printf("public String toString() {%n");
        buffer.incrementIndent();
        buffer.printf("return this.name();%n");
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    private void generateHeaderVersion(String type) {
        buffer.printf("public short %sHeaderVersion(short _version) {%n", type);
        buffer.incrementIndent();
        buffer.printf("switch (apiKey) {%n");
        buffer.incrementIndent();
        for (Map.Entry<Short, ApiData> entry : apis.entrySet()) {
            short apiKey = entry.getKey();
            buffer.printf("case %d:%n", apiKey);
            buffer.incrementIndent();
            if (type.equals("response") && apiKey == 18) {
                // ApiVersionsResponse always includes a v0 header.
                // See KIP-511 for details.
                buffer.printf("return (short) 0;%n");
                buffer.decrementIndent();
                continue;
            }
            if (type.equals("request") && apiKey == 7) {
                // Version 0 of ControlledShutdownRequest has a non-standard request header
                // which does not include clientId.  Version 1 of ControlledShutdownRequest
                // and later use the standard request header.
                buffer.printf("if (_version == 0) {%n");
                buffer.incrementIndent();
                buffer.printf("return (short) 0;%n");
                buffer.decrementIndent();
                buffer.printf("}%n");
            }
            ApiData data = entry.getValue();
            MessageSpec spec = null;
            if (type.equals("request")) {
                spec = data.requestSpec;
            } else if (type.equals("response")) {
                spec = data.responseSpec;
            } else {
                throw new RuntimeException("Invalid type " + type + " for generateHeaderVersion");
            }
            if (spec == null) {
                throw new RuntimeException("failed to find " + type + " for API key " + apiKey);
            }
            VersionConditional.forVersions(spec.flexibleVersions(),
                spec.validVersions()).
                ifMember(__ -> {
                    if (type.equals("request")) {
                        buffer.printf("return (short) 2;%n");
                    } else {
                        buffer.printf("return (short) 1;%n");
                    }
                }).
                ifNotMember(__ -> {
                    if (type.equals("request")) {
                        buffer.printf("return (short) 1;%n");
                    } else {
                        buffer.printf("return (short) 0;%n");
                    }
                }).generate(buffer);
            buffer.decrementIndent();
        }
        buffer.printf("default:%n");
        buffer.incrementIndent();
        headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
        buffer.printf("throw new UnsupportedVersionException(\"Unsupported API key \"" +
            " + apiKey);%n");
        buffer.decrementIndent();
        buffer.decrementIndent();
        buffer.printf("}%n");
        buffer.decrementIndent();
        buffer.printf("}%n");
    }

    public void write(BufferedWriter writer) throws IOException {
        headerGenerator.buffer().write(writer);
        buffer.write(writer);
    }
}


text: NewBalance Shop


text:
"""Test the TcEx Utils Module."""
# first-party
from tcex.utils import Utils

# pylint: disable=no-self-use
class TestStandardizeAsn:
    """Test the TcEx Utils Module."""

    def test_standardize_asn(self):
        """Test Case"""
        assert Utils().standardize_asn('1234') == 'ASN1234'
        assert Utils().standardize_asn('AS1234') == 'ASN1234'
        assert Utils().standardize_asn('AS 1234') == 'ASN1234'
        assert Utils().standardize_asn('ASN1234') == 'ASN1234'
        assert Utils().standardize_asn('ASN 1234') == 'ASN1234'
        assert Utils().standardize_asn('foo') == 'foo'


text:
# GeoLint

Validate Ordnance Survey GB & NI (OS/OSGB/OSNI) GML and NTF geospatial data files

### What does GeoLint do?

This tool...

### What are the benefits for the end user?

A list of benefits GeoLint brings to the end user:

* GML data files can be validated against Ordnance Survey Schema (http://www.ordnancesurvey.co.uk/xml/schema/)
* NTF data files are opened and parsed to ensure that they can be read successfully, using the GDAL/OGR library

### Who is the intended audience?

GeoLint is for:

* Those who wish to validate NTF/GML files, and checksum others

## Features and roadmap

### Version 0.0.1

* Validate

## How to install and use

### Requirements

To install you need:

* Xerces Java 2.11 XML Schema 1.1 beta
* GDAL/OGR library with JNI jar. Target architecture for GDAL/OGR  must match your JVM (i.e. Windows/Linux & 32/64-bit)
* OS schema from here: http://www.ordnancesurvey.co.uk/xml/schema/ (tested with v7 & v8)(extract zip into "src/main/resources/schema")

You will need to build your own GDAL/OGR libraries. Installation instructions for these files are contained within the pom.xml file.

Read the instructions contained within the directories under ./src/main/resources/ for information on what to place in there.

### Use

To use the tool, you can try the following command:
```bash
$ java -jar binary.jar --help
Synopsys: java -jar binary.jar ...
...
```

## More information

### Licence

GeoLint is released under [Apache version 2.0 license](LICENSE.txt).

It includes a file from GDAL with the following license:

```
 ```

### Acknowledgements

Part of this work was supported by the European Union in the 7th Framework Program, IST, through the SCAPE project, Contract 270137.

## Develop

Patches welcome

### Requirements

To build you require:

* Git client
* Apache Maven
* Java Developers Kit (e.g. OpenJDK 6)

Additionally, to build the GDAL/OGR dependency you need:

* Microsoft Visual C/C++
* SWIG (http://www.swig.org/)
* Apache Ant

Build instructions are here: http://trac.osgeo.org/gdal/wiki/GdalOgrInJavaBuildInstructions

Some additional tips for building GDAL/OGR are:

 * Ensure no spaces or trailing slashes in environment variables you set
 * Ensure no spaces are contained in in JAVA_HOME
 * ANT_HOME is not the bin/ directory, use the parent of the bin/ directory
 * "Program Files\Visual Studio\VC\bin\vsvars32.bat" sets up MSVC for 32-bit builds on Windows - ensure architecture matches the JVM!
 * "Program Files\Visual Studio\VC\vcvarsall.bat amd64" sets up MSVC for amd64 builds on Windows - ensure architecture matches the JVM!

### Build

To compile go to the sources folder and execute the command:

```bash
$ mvn clean install
```

After successful compile the binary will be available at `target/binary.jar`.

### Deploy

To deploy do ...

### Contribute

1. [Fork the GitHub project](https://help.github.com/articles/fork-a-repo)
2. Change the code and push into the forked project
3. [Submit a pull request](https://help.github.com/articles/using-pull-requests)

To increase the changes of you code being accepted and merged into the official source here's a checklist of things to go over before submitting a contribution. For example:

* Has unit tests (that covers at least 80% of the code)
* Has documentation (at least 80% of public API)
* Agrees to contributor license agreement, certifying that any contributed code is original work and that the copyright is turned over to the project


text:
from __future__ import division

import threading
import multiprocessing
import logging
from time import time
from bisect import bisect_left

from feemodel.util import logexceptions

ITERSCHUNK = 100
PROCESS_COMPLETE = 'process_complete'

logger = logging.getLogger(__name__)

def transientsim_core(sim, init_entries, feepoints):
    """Transient wait time generator.

    Each iteration yields one realization of the wait time random vector.
    feepoints should be sorted, and should not include any feerates lower than
    sim.stablefeerate.
    """
    if min(feepoints) < sim.stablefeerate:
        raise ValueError("All feepoints must be >= sim.stablefeerate.")
    waittimes = [None]*len(feepoints)
    min_sfr_idx = len(feepoints)
    for block in sim.run(init_entries=init_entries):
        sfr_idx = bisect_left(feepoints, block.sfr)
        for i in range(sfr_idx, min_sfr_idx):
            waittimes[i] = sim.simtime
        if sfr_idx == 0:
            yield waittimes[:]
            min_sfr_idx = len(feepoints)
            sim.simtime = 0
            sim.mempool.reset()
        else:
            min_sfr_idx = min(sfr_idx, min_sfr_idx)

def transientsim(sim, feepoints=None, init_entries=None,
                 miniters=1000, maxiters=10000, maxtime=60,
                 numprocesses=None, stopflag=None):
    """A multiprocessing wrapper for transientsim_core."""
    starttime = time()
    if init_entries is None:
        init_entries = {}
    if not feepoints:
        feepoints = get_default_feepoints(sim)
    else:
        feepoints = filter(lambda feerate: feerate >= sim.stablefeerate,
                           sorted(set(feepoints)))
        if not feepoints:
            raise ValueError("No feepoints >= stablefeerate.")
    if numprocesses is None:
        numprocesses = multiprocessing.cpu_count()

    resultqueue = multiprocessing.Queue()
    process_stopflag = multiprocessing.Event()
    target = transientsim_process
    args = (sim, init_entries, feepoints, resultqueue, process_stopflag)
    if numprocesses > 1:
        processes = [multiprocessing.Process(target=target, args=args)
                     for i in range(numprocesses)]
    else:
        # Use a thread instead
        processes = [threading.Thread(target=target, args=args)]
    for process in processes:
        process.start()
    logger.debug("Subprocesses started ({} total)".format(numprocesses))

    starttime = time()
    elapsedtime = 0
    waitvectors = []
    while len(waitvectors) < maxiters and (
            len(waitvectors) < miniters or elapsedtime <= maxtime) and (
            stopflag is None or not stopflag.is_set()):
        waitvectors.extend(resultqueue.get())
        elapsedtime = time() - starttime
    process_stopflag.set()
    logger.debug("Subprocesses sent stop signal.")

    num_process_complete = 0
    while num_process_complete < numprocesses:
        res = resultqueue.get()
        if res == PROCESS_COMPLETE:
            num_process_complete += 1
        else:
            waitvectors.extend(res)
    logger.debug("Received PROCESS_COMPLETE from all subprocesses.")

    for process in processes:
        process.join()
    if stopflag and stopflag.is_set():
        raise StopIteration
    logger.debug("Subprocesses joined and completed.")

    waittimes = zip(*waitvectors)
    return feepoints, waittimes

@logexceptions
def transientsim_process(sim, init_entries, feepoints, resultqueue,
                         stopflag):
    waitvectors = []
    for waitvector in transientsim_core(sim, init_entries, feepoints):
        waitvectors.append(waitvector)
        if stopflag.is_set():
            resultqueue.put(waitvectors)
            resultqueue.put(PROCESS_COMPLETE)
            break
        if len(waitvectors) == ITERSCHUNK:
            resultqueue.put(waitvectors)
            waitvectors = []

def get_default_feepoints(sim, numpoints=20):
    """Returns a list of sensible default feepoints.

    This is basically equispaced feerates from stablefeerate to 0.05
    utilization.
    """
    minfeepoint = sim.stablefeerate
    maxfeepoint = sim.cap.inv_util(0.05)
    assert maxfeepoint >= minfeepoint
    spacing = int((maxfeepoint - minfeepoint) / numpoints)
    if spacing == 0:
        return [maxfeepoint]
    return range(minfeepoint, maxfeepoint+spacing, spacing)


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>

#include "base/strings/strcat.h"
#include "base/test/test_mock_time_task_runner.h"
#include "components/drive/drive_notification_manager.h"
#include "components/drive/drive_notification_observer.h"
#include "components/invalidation/impl/fake_invalidation_service.h"
#include "components/invalidation/public/topic_invalidation_map.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drive {

namespace {

const syncer::Topic kDefaultCorpusTopic = "Drive";

struct ShutdownHelper {
  template <typename T>
  void operator()(T* object) const {
    if (object) {
      object->Shutdown();
      delete object;
    }
  }
};

class FakeDriveNotificationObserver : public DriveNotificationObserver {
 public:
  ~FakeDriveNotificationObserver() override {}

  // DriveNotificationObserver overrides
  void OnNotificationReceived(
      const std::map<std::string, int64_t>& ids) override {
    notification_ids_ = ids;
  }
  void OnNotificationTimerFired() override {}
  void OnPushNotificationEnabled(bool enabled) override {}

  const std::map<std::string, int64_t> GetNotificationIds() const {
    return notification_ids_;
  }

  void ClearNotificationIds() { notification_ids_.clear(); }

 private:
  std::map<std::string, int64_t> notification_ids_;
};

syncer::Topic CreateTeamDriveInvalidationTopic(
    const std::string& team_drive_id) {
  return base::StrCat({"team-drive-", team_drive_id});
}

}  // namespace

class DriveNotificationManagerTest : public testing::Test {
 protected:
  void SetUp() override {
    task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>(
        base::TestMockTimeTaskRunner::Type::kBoundToThread);
    fake_invalidation_service_ =
        std::make_unique<invalidation::FakeInvalidationService>();
    drive_notification_observer_ =
        std::make_unique<FakeDriveNotificationObserver>();

    // Can't use make_unique with a custom deleter.
    drive_notification_manager_.reset(
        new DriveNotificationManager(fake_invalidation_service_.get()));

    drive_notification_manager_->AddObserver(
        drive_notification_observer_.get());
  }

  void TearDown() override {
    drive_notification_manager_->RemoveObserver(
        drive_notification_observer_.get());
  }

  scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
  std::unique_ptr<invalidation::FakeInvalidationService>
      fake_invalidation_service_;
  std::unique_ptr<FakeDriveNotificationObserver> drive_notification_observer_;
  std::unique_ptr<DriveNotificationManager, ShutdownHelper>
      drive_notification_manager_;
};

TEST_F(DriveNotificationManagerTest, RegisterTeamDrives) {
  // By default, we should have registered for default corpus notifications on
  // initialization.
  auto subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                               .GetAllSubscribedTopics();

  // TODO(crbug.com/1029698): replace syncer::Topics with syncer::TopicSet once
  // |is_public| become the part of dedicated syncer::Topic struct. This should
  // simplify this test.
  syncer::Topics expected_topics;
  expected_topics.emplace(kDefaultCorpusTopic,
                          syncer::TopicMetadata{/*is_public=*/false});
  EXPECT_EQ(expected_topics, subscribed_topics);

  const std::string team_drive_id_1 = "td_id_1";
  const auto team_drive_1_topic =
      CreateTeamDriveInvalidationTopic(team_drive_id_1);

  // Add the team drive
  drive_notification_manager_->UpdateTeamDriveIds({team_drive_id_1}, {});
  subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                          .GetAllSubscribedTopics();

  expected_topics.emplace(team_drive_1_topic,
                          syncer::TopicMetadata{/*is_public=*/true});
  EXPECT_EQ(expected_topics, subscribed_topics);

  // Remove the team drive.
  drive_notification_manager_->UpdateTeamDriveIds({}, {team_drive_id_1});
  subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                          .GetAllSubscribedTopics();

  expected_topics.erase(team_drive_1_topic);
  EXPECT_EQ(expected_topics, subscribed_topics);

  const std::string team_drive_id_2 = "td_id_2";
  const auto team_drive_2_topic =
      CreateTeamDriveInvalidationTopic(team_drive_id_2);

  // Add two team drives.
  drive_notification_manager_->UpdateTeamDriveIds(
      {team_drive_id_1, team_drive_id_2}, {});
  subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                          .GetAllSubscribedTopics();

  expected_topics.emplace(team_drive_1_topic,
                          syncer::TopicMetadata{/*is_public=*/true});
  expected_topics.emplace(team_drive_2_topic,
                          syncer::TopicMetadata{/*is_public=*/true});
  EXPECT_EQ(expected_topics, subscribed_topics);

  // Remove the first team drive.
  drive_notification_manager_->UpdateTeamDriveIds({}, {team_drive_id_1});
  subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                          .GetAllSubscribedTopics();

  expected_topics.erase(team_drive_1_topic);
  EXPECT_EQ(expected_topics, subscribed_topics);

  // Remove a team drive that doesn't exists with no changes.
  const std::string team_drive_id_3 = "td_id_3";
  drive_notification_manager_->UpdateTeamDriveIds({}, {team_drive_id_3});
  subscribed_topics = fake_invalidation_service_->invalidator_registrar()
                          .GetAllSubscribedTopics();

  EXPECT_EQ(expected_topics, subscribed_topics);
}

TEST_F(DriveNotificationManagerTest, TestBatchInvalidation) {
  // By default we'll be registered for the default change notification.

  // Emitting an invalidation should not call our observer until the timer
  // expires.
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::InitUnknownVersion(kDefaultCorpusTopic));
  EXPECT_TRUE(drive_notification_observer_->GetNotificationIds().empty());

  task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(30));

  // Default corpus is has the id "" when sent to observers.
  std::map<std::string, int64_t> expected_ids = {{"", -1}};
  EXPECT_EQ(expected_ids, drive_notification_observer_->GetNotificationIds());
  drive_notification_observer_->ClearNotificationIds();

  // Register a team drive for notifications
  const std::string team_drive_id_1 = "td_id_1";
  const auto team_drive_1_topic =
      CreateTeamDriveInvalidationTopic(team_drive_id_1);
  drive_notification_manager_->UpdateTeamDriveIds({team_drive_id_1}, {});

  // Emit invalidation for default corpus, should not emit a team drive
  // invalidation.
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::Init(kDefaultCorpusTopic, 1, ""));
  EXPECT_TRUE(drive_notification_observer_->GetNotificationIds().empty());

  task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(30));

  // Default corpus is has the id "" when sent to observers.
  expected_ids = {{"", 2}};
  EXPECT_EQ(expected_ids, drive_notification_observer_->GetNotificationIds());
  drive_notification_observer_->ClearNotificationIds();

  // Emit team drive invalidation
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::Init(team_drive_1_topic, 2, ""));
  EXPECT_TRUE(drive_notification_observer_->GetNotificationIds().empty());

  task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(30));
  expected_ids = {{team_drive_id_1, 2}};
  EXPECT_EQ(expected_ids, drive_notification_observer_->GetNotificationIds());
  drive_notification_observer_->ClearNotificationIds();

  // Emit both default corpus and team drive.
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::Init(kDefaultCorpusTopic, 1, ""));
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::Init(team_drive_1_topic, 2, ""));

  // Emit with an earlier version. This should be ignored.
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::Init(kDefaultCorpusTopic, 0, ""));

  // Emit without a version. This should be ignored too.
  fake_invalidation_service_->EmitInvalidationForTest(
      syncer::Invalidation::InitUnknownVersion(kDefaultCorpusTopic));

  EXPECT_TRUE(drive_notification_observer_->GetNotificationIds().empty());

  task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(30));
  expected_ids = {{"", 2}, {team_drive_id_1, 2}};
  EXPECT_EQ(expected_ids, drive_notification_observer_->GetNotificationIds());
}

}  // namespace drive


text:
<?php

namespace AppBundle\Validator\Constraints\ProfDeputyCostsEstimate;

use AppBundle\Entity\Report\ProfDeputyEstimateCost;
use AppBundle\Entity\Report\Report;
use AppBundle\Entity\ReportInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class CostBreakdownNotGreaterThanTotalValidatorTest extends TestCase
{
    /** @var ConstraintValidator */
    private $sut;

    /** @var ExecutionContextInterface | \PHPUnit_Framework_MockObject_MockObject */
    private $context;

    /** @var ReportInterface */
    private $data;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->data = new Report();

        $this->context = $this->getMock(ExecutionContextInterface::class);
        $this->sut = new CostBreakdownNotGreaterThanTotalValidator();
        $this->sut->initialize($this->context);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testThrowsExceptionOnIncorrectDataType()
    {
        $this->sut->validate(new \stdClass(), new CostBreakdownNotGreaterThanTotal());
    }

    public function testValidatorAddsConstraintIfBreakdownTotalGreaterThanAmountItCanExceed()
    {
        $this
            ->setTotalCostEstimate(43)
            ->setIndividualBreakdownCosts(30, 13.01)
            ->assertConstraintWillBeApplied()
            ->invokeTest();
    }

    /**
     * @dataProvider breakdownCostVariations
     */
    public function testValidatorIgnoresConstraintIfBreakdownTotalNotGreaterThanAmountItCanExceed($costVariation)
    {
        $this
            ->setTotalCostEstimate(43)
            ->setIndividualBreakdownCosts(30, $costVariation)
            ->assertConstraintWillNotBeApplied()
            ->invokeTest();
    }

    /**
     * @return array
     */
    public function breakdownCostVariations()
    {
        return [
            ['costVariation' => 12.99],
            ['costVariation' => 13.00]
        ];
    }

    /**
     * @param $totalCost
     * @return $this
     */
    private function setTotalCostEstimate($totalCost)
    {
        $this->data->setProfDeputyManagementCostAmount($totalCost);

        return $this;
    }

    /**
     * @param $costAlpha
     * @param $costBeta
     * @return CostBreakdownNotGreaterThanTotalValidatorTest
     */
    private function setIndividualBreakdownCosts($costAlpha, $costBeta)
    {
        $breakdownAlpha = new ProfDeputyEstimateCost(1, $costAlpha, false, null);
        $breakdownBeta = new ProfDeputyEstimateCost(2, $costBeta, false, null);

        $this->data->setProfDeputyEstimateCosts([$breakdownAlpha, $breakdownBeta]);

        return $this;
    }

    /**
     * @return $this
     */
    private function assertConstraintWillBeApplied()
    {
        $this
            ->context
            ->expects($this->once())
            ->method('addViolation');

        return $this;
    }

    /**
     * @return $this
     */
    private function assertConstraintWillNotBeApplied()
    {
        $this
            ->context
            ->expects($this->never())
            ->method('addViolation');

        return $this;
    }

    private function invokeTest()
    {
        $this->sut->validate($this->data, new CostBreakdownNotGreaterThanTotal());
    }
}


text:
VM_PATH=../../

echo Preparing the execution environment for the fuzz tool.
sleep 1

# Set compiler and core dumping method so that it is usable by afl-fuzz.
if [ "$(uname)" = "Darwin" ]; then
    CC=afl-clang
    launchctl unload -w /System/Library/LaunchAgents/com.apple.ReportCrash.plist
    sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist
elif [ "$(uname)" = "Linux" ]; then
    CC=afl-gcc
    sudo bash -c "echo core >/proc/sys/kernel/core_pattern"
fi

make -C $VM_PATH CC=$CC \
  DEFINES+="-DVM_HEAP_SIZE=10000000 -DVM_OBJECT_POOL_SIZE=10000000" clean vm

command -v afl-fuzz > /dev/null 2>&1 || \
  { echo "afl-fuzz must be installed to run this script" >&2; exit 1; }

afl-fuzz -i test-cases -o results -- $VM_PATH/bin/vm @@


text:
@interface CCMServerMonitor : NSObject
{
	IBOutlet CCMUserDefaultsManager		*defaultsManager;
	NSNotificationCenter				*notificationCenter;
	CCMBuildNotificationFactory			*notificationFactory;

	NSMutableArray                      *connections;
    NSMutableArray                      *projects;

	NSMutableArray						*serverConnectionPairs;
	NSTimer								*timer;
}

- (void)setDefaultsManager:(CCMUserDefaultsManager *)manager;
- (void)setNotificationCenter:(NSNotificationCenter *)center;
- (void)setNotificationFactory:(CCMBuildNotificationFactory *)factory;

- (void)setupFromUserDefaults;

- (NSArray *)projects;
- (NSArray *)connections;

- (void)start;
- (void)stop;

- (void)pollServers:(id)sender;

- (void)connection:(CCMConnection *)connection didReceiveServerStatus:(NSArray *)projectInfoList;
- (void)connection:(CCMConnection *)connection hadTemporaryError:(NSString *)errorString;

@end

extern NSString *CCMProjectStatusUpdateNotification;


text:
//---------------------------------------------------------------------
// <copyright file="ReusableStream.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.OData.Framework.TestProviders.OptionalProviders
{
    using System;
    using System.IO;

    /// <summary>
    /// Memory stream that can be reused after disposing, which will simply set the position back to the start
    /// </summary>
    internal class ReusableStream : MemoryStream, IDisposable
    {
        /// <summary>
        /// Implementation of the Dispose() function
        /// </summary>
        void IDisposable.Dispose()
        {
            // Resets the stream
            this.Position = 0;
        }

        /// <summary>
        /// Resets the stream
        /// </summary>
        /// <param name="disposing">Whether or not to dispose managed resources</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2215: Dispose methods should call base class dispose", Justification = "Not necessary to call base.Dispose() in this implementation")]
        protected override void Dispose(bool disposing)
        {
            ((IDisposable)this).Dispose();
        }
    }
}


text:
- Array declaration and use
- Encanced `for` loop
- Two-dimentional arrays
- Passing arrays and array elements as parameters
- Arrays of objects
- The `ArrayList` class
- Searching and sorting