text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SpecGenerator = (function () {
    function SpecGenerator(metadata, config) {
        this.metadata = metadata;
        this.config = config;
    }
    SpecGenerator.prototype.GetSpec = function () {
        var spec = {
            basePath: this.config.basePath,
            consumes: ['application/json'],
            definitions: this.buildDefinitions(),
            info: {
                title: '',
            },
            paths: this.buildPaths(),
            produces: ['application/json'],
            swagger: '2.0',
        };
        spec.securityDefinitions = this.config.securityDefinitions
            ? this.config.securityDefinitions
            : {};
        if (this.config.name) {
            spec.info.title = this.config.name;
        }
        if (this.config.version) {
            spec.info.version = this.config.version;
        }
        if (this.config.host) {
            spec.host = this.config.host;
        }
        if (this.config.description) {
            spec.info.description = this.config.description;
        }
        if (this.config.license) {
            spec.info.license = { name: this.config.license };
        }
        if (this.config.spec) {
            this.config.specMerging = this.config.specMerging || 'immediate';
            var mergeFuncs = {
                immediate: Object.assign,
                recursive: require('merge').recursive,
            };
            spec = mergeFuncs[this.config.specMerging](spec, this.config.spec);
        }
        return spec;
    };
    SpecGenerator.prototype.buildDefinitions = function () {
        var _this = this;
        var definitions = {};
        Object.keys(this.metadata.referenceTypeMap).map(function (typeName) {
            var referenceType = _this.metadata.referenceTypeMap[typeName];
            // Object definition
            if (referenceType.properties) {
                var required = referenceType.properties.filter(function (p) { return p.required; }).map(function (p) { return p.name; });
                definitions[referenceType.refName] = {
                    description: referenceType.description,
                    properties: _this.buildProperties(referenceType.properties),
                    required: required && required.length > 0 ? Array.from(new Set(required)) : undefined,
                    type: 'object',
                };
                if (referenceType.additionalProperties) {
                    definitions[referenceType.refName].additionalProperties = _this.buildAdditionalProperties(referenceType.additionalProperties);
                }
            }
            // Enum definition
            if (referenceType.enums) {
                definitions[referenceType.refName] = {
                    description: referenceType.description,
                    enum: referenceType.enums,
                    type: 'string',
                };
            }
        });
        return definitions;
    };
    SpecGenerator.prototype.buildPaths = function () {
        var _this = this;
        var paths = {};
        this.metadata.controllers.forEach(function (controller) {
            // construct documentation using all methods except @Hidden
            controller.methods.filter(function (method) { return !method.isHidden; }).forEach(function (method) {
                var path = "" + (controller.path ? "/" + controller.path : '') + method.path;
                paths[path] = paths[path] || {};
                _this.buildMethod(controller.name, method, paths[path]);
            });
        });
        return paths;
    };
    SpecGenerator.prototype.buildMethod = function (controllerName, method, pathObject) {
        var _this = this;
        var pathMethod = pathObject[method.method] = this.buildOperation(controllerName, method);
        pathMethod.description = method.description;
        pathMethod.summary = method.summary;
        pathMethod.tags = method.tags;
        if (method.deprecated) {
            pathMethod.deprecated = method.deprecated;
        }
        if (method.security) {
            var methodSecurity = [];
            for (var _i = 0, _a = method.security; _i < _a.length; _i++) {
                var thisSecurity = _a[_i];
                var security = {};
                security[thisSecurity.name] = thisSecurity.scopes ? thisSecurity.scopes : [];
                methodSecurity.push(security);
            }
            pathMethod.security = methodSecurity;
        }
        pathMethod.parameters = method.parameters
            .filter(function (p) {
            return !(p.in === 'request' || p.in === 'body-prop');
        })
            .map(function (p) { return _this.buildParameter(p); });
        var bodyPropParameter = this.buildBodyPropParameter(controllerName, method);
        if (bodyPropParameter) {
            pathMethod.parameters.push(bodyPropParameter);
        }
        if (pathMethod.parameters.filter(function (p) { return p.in === 'body'; }).length > 1) {
            throw new Error('Only one body parameter allowed per controller method.');
        }
    };
    SpecGenerator.prototype.buildBodyPropParameter = function (controllerName, method) {
        var _this = this;
        var properties = {};
        var required = [];
        method.parameters
            .filter(function (p) { return p.in === 'body-prop'; })
            .forEach(function (p) {
            properties[p.name] = _this.getSwaggerType(p.type);
            properties[p.name].default = p.default;
            properties[p.name].description = p.description;
            // if (!properties[p.name].$ref) {
            // }
            if (p.required) {
                required.push(p.name);
            }
        });
        if (!Object.keys(properties).length) {
            return;
        }
        var parameter = {
            in: 'body',
            name: 'body',
            schema: {
                properties: properties,
                title: this.getOperationId(controllerName, method.name) + "Body",
                type: 'object',
            },
        };
        if (required.length) {
            parameter.schema.required = required;
        }
        return parameter;
    };
    SpecGenerator.prototype.buildParameter = function (source) {
        var parameter = {
            default: source.default,
            description: source.description,
            in: source.in,
            name: source.name,
            required: source.required,
        };
        var parameterType = this.getSwaggerType(source.type);
        if (parameterType.$ref) {
            parameter.schema = parameterType;
        }
        else {
            if (source.type.dataType === 'any') {
                if (source.in === 'body') {
                    parameter.schema = { type: 'object' };
                }
                else {
                    parameter.type = 'string';
                }
            }
            else {
                parameter.type = parameterType.type;
                parameter.items = parameterType.items;
                parameter.enum = parameterType.enum;
            }
        }
        if (parameter.in === 'query' && parameter.type === 'array') {
            parameter.collectionFormat = 'multi';
        }
        if (parameterType.format) {
            parameter.format = parameterType.format;
        }
        Object.keys(source.validators)
            .filter(function (key) {
            return !key.startsWith('is') && key !== 'minDate' && key !== 'maxDate';
        })
            .forEach(function (key) {
            parameter[key] = source.validators[key].value;
        });
        return parameter;
    };
    SpecGenerator.prototype.buildProperties = function (source) {
        var _this = this;
        var properties = {};
        source.forEach(function (property) {
            var swaggerType = _this.getSwaggerType(property.type);
            swaggerType.description = property.description;
            if (!swaggerType.$ref) {
                swaggerType.default = property.default;
                Object.keys(property.validators)
                    .filter(function (key) {
                    return !key.startsWith('is') && key !== 'minDate' && key !== 'maxDate';
                })
                    .forEach(function (key) {
                    swaggerType[key] = property.validators[key].value;
                });
            }
            properties[property.name] = swaggerType;
        });
        return properties;
    };
    SpecGenerator.prototype.buildAdditionalProperties = function (type) {
        return this.getSwaggerType(type);
    };
    SpecGenerator.prototype.buildOperation = function (controllerName, method) {
        var _this = this;
        var swaggerResponses = {};
        method.responses.forEach(function (res) {
            swaggerResponses[res.name] = {
                description: res.description,
            };
            if (res.schema && res.schema.dataType !== 'void') {
                swaggerResponses[res.name].schema = _this.getSwaggerType(res.schema);
            }
            if (res.examples) {
                swaggerResponses[res.name].examples = { 'application/json': res.examples };
            }
        });
        return {
            operationId: this.getOperationId(controllerName, method.name),
            produces: ['application/json'],
            responses: swaggerResponses,
        };
    };
    SpecGenerator.prototype.getOperationId = function (controllerName, methodName) {
        var controllerNameWithoutSuffix = controllerName.replace(new RegExp('Controller$'), '');
        return "" + controllerNameWithoutSuffix + (methodName.charAt(0).toUpperCase() + methodName.substr(1));
    };
    SpecGenerator.prototype.getSwaggerType = function (type) {
        var swaggerType = this.getSwaggerTypeForPrimitiveType(type);
        if (swaggerType) {
            return swaggerType;
        }
        if (type.dataType === 'array') {
            return this.getSwaggerTypeForArrayType(type);
        }
        if (type.dataType === 'enum') {
            return this.getSwaggerTypeForEnumType(type);
        }
        return this.getSwaggerTypeForReferenceType(type);
    };
    SpecGenerator.prototype.getSwaggerTypeForPrimitiveType = function (type) {
        var map = {
            any: { type: 'object' },
            binary: { type: 'string', format: 'binary' },
            boolean: { type: 'boolean' },
            buffer: { type: 'string', format: 'byte' },
            byte: { type: 'string', format: 'byte' },
            date: { type: 'string', format: 'date' },
            datetime: { type: 'string', format: 'date-time' },
            double: { type: 'number', format: 'double' },
            float: { type: 'number', format: 'float' },
            integer: { type: 'integer', format: 'int32' },
            long: { type: 'integer', format: 'int64' },
            object: { type: 'object' },
            string: { type: 'string' },
        };
        return map[type.dataType];
    };
    SpecGenerator.prototype.getSwaggerTypeForArrayType = function (arrayType) {
        return { type: 'array', items: this.getSwaggerType(arrayType.elementType) };
    };
    SpecGenerator.prototype.getSwaggerTypeForEnumType = function (enumType) {
        return { type: 'string', enum: enumType.enums.map(function (member) { return String(member); }) };
    };
    SpecGenerator.prototype.getSwaggerTypeForReferenceType = function (referenceType) {
        return { $ref: "#/definitions/" + referenceType.refName };
    };
    return SpecGenerator;
}());
exports.SpecGenerator = SpecGenerator;
//# sourceMappingURL=specGenerator.js.map


text:
namespace content {

EmptyNetworkManager::EmptyNetworkManager(rtc::NetworkManager* network_manager)
    : network_manager_(network_manager), weak_ptr_factory_(this) {
  DCHECK(network_manager);
  thread_checker_.DetachFromThread();
  set_enumeration_permission(ENUMERATION_BLOCKED);
  network_manager_->SignalNetworksChanged.connect(
      this, &EmptyNetworkManager::OnNetworksChanged);
}

EmptyNetworkManager::~EmptyNetworkManager() {
  DCHECK(thread_checker_.CalledOnValidThread());
}

void EmptyNetworkManager::StartUpdating() {
  DCHECK(thread_checker_.CalledOnValidThread());
  ++start_count_;
  network_manager_->StartUpdating();
}

void EmptyNetworkManager::StopUpdating() {
  DCHECK(thread_checker_.CalledOnValidThread());
  network_manager_->StopUpdating();
  --start_count_;
  DCHECK_GE(start_count_, 0);
}

void EmptyNetworkManager::GetNetworks(NetworkList* networks) const {
  DCHECK(thread_checker_.CalledOnValidThread());
  networks->clear();
}

bool EmptyNetworkManager::GetDefaultLocalAddress(
    int family,
    rtc::IPAddress* ipaddress) const {
  return network_manager_->GetDefaultLocalAddress(family, ipaddress);
}

void EmptyNetworkManager::OnNetworksChanged() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (!start_count_)
    return;

  if (!sent_first_update_)
    ReportIPPermissionStatus(PERMISSION_NOT_REQUESTED);

  sent_first_update_ = true;
  SignalNetworksChanged();
}

}  // namespace content

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.streaming

import scala.collection.JavaConverters._

import org.apache.spark.annotation.{Experimental, InterfaceStability}
import org.apache.spark.sql.{AnalysisException, Dataset, ForeachWriter}
import org.apache.spark.sql.catalyst.streaming.InternalOutputModes
import org.apache.spark.sql.execution.command.DDLUtils
import org.apache.spark.sql.execution.datasources.DataSource
import org.apache.spark.sql.execution.streaming.{ForeachSink, MemoryPlan, MemorySink}

/**
 * :: Experimental ::
 * Interface used to write a streaming `Dataset` to external storage systems (e.g. file systems,
 * key-value stores, etc). Use `Dataset.writeStream` to access this.
 *
 * @since 2.0.0
 */
@Experimental
@InterfaceStability.Evolving
final class DataStreamWriter[T] private[sql](ds: Dataset[T]) {

  private val df = ds.toDF()

  /**
   * Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
   *   - `OutputMode.Append()`: only the new rows in the streaming DataFrame/Dataset will be
   *                            written to the sink
   *   - `OutputMode.Complete()`: all the rows in the streaming DataFrame/Dataset will be written
   *                              to the sink every time these is some updates
   *   - `OutputMode.Update()`: only the rows that were updated in the streaming DataFrame/Dataset
   *                            will be written to the sink every time there are some updates. If
   *                            the query doesn't contain aggregations, it will be equivalent to
   *                            `OutputMode.Append()` mode.
   *
   * @since 2.0.0
   */
  def outputMode(outputMode: OutputMode): DataStreamWriter[T] = {
    this.outputMode = outputMode
    this
  }

  /**
   * Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
   *   - `append`:   only the new rows in the streaming DataFrame/Dataset will be written to
   *                 the sink
   *   - `complete`: all the rows in the streaming DataFrame/Dataset will be written to the sink
   *                 every time these is some updates
   *   - `update`:   only the rows that were updated in the streaming DataFrame/Dataset will
   *                 be written to the sink every time there are some updates. If the query doesn't
   *                 contain aggregations, it will be equivalent to `append` mode.
   * @since 2.0.0
   */
  def outputMode(outputMode: String): DataStreamWriter[T] = {
    this.outputMode = InternalOutputModes(outputMode)
    this
  }

  /**
   * Set the trigger for the stream query. The default value is `ProcessingTime(0)` and it will run
   * the query as fast as possible.
   *
   * Scala Example:
   * {{{
   *   df.writeStream.trigger(ProcessingTime("10 seconds"))
   *
   *   import scala.concurrent.duration._
   *   df.writeStream.trigger(ProcessingTime(10.seconds))
   * }}}
   *
   * Java Example:
   * {{{
   *   df.writeStream().trigger(ProcessingTime.create("10 seconds"))
   *
   *   import java.util.concurrent.TimeUnit
   *   df.writeStream().trigger(ProcessingTime.create(10, TimeUnit.SECONDS))
   * }}}
   *
   * @since 2.0.0
   */
  def trigger(trigger: Trigger): DataStreamWriter[T] = {
    this.trigger = trigger
    this
  }

  /**
   * Specifies the name of the [[StreamingQuery]] that can be started with `start()`.
   * This name must be unique among all the currently active queries in the associated SQLContext.
   *
   * @since 2.0.0
   */
  def queryName(queryName: String): DataStreamWriter[T] = {
    this.extraOptions += ("queryName" -> queryName)
    this
  }

  /**
   * Specifies the underlying output data source.
   *
   * @since 2.0.0
   */
  def format(source: String): DataStreamWriter[T] = {
    this.source = source
    this
  }

  /**
   * Partitions the output by the given columns on the file system. If specified, the output is
   * laid out on the file system similar to Hive's partitioning scheme. As an example, when we
   * partition a dataset by year and then month, the directory layout would look like:
   *
   *   - year=2016/month=01/
   *   - year=2016/month=02/
   *
   * Partitioning is one of the most widely used techniques to optimize physical data layout.
   * It provides a coarse-grained index for skipping unnecessary data reads when queries have
   * predicates on the partitioned columns. In order for partitioning to work well, the number
   * of distinct values in each column should typically be less than tens of thousands.
   *
   * @since 2.0.0
   */
  @scala.annotation.varargs
  def partitionBy(colNames: String*): DataStreamWriter[T] = {
    this.partitioningColumns = Option(colNames)
    this
  }

  /**
   * Adds an output option for the underlying data source.
   *
   * You can set the following option(s):
   *

   *
`timeZone` (default session local timezone): sets the string that indicates a timezone
   * to be used to format timestamps in the JSON/CSV datasources or partition values.

   *

   *
   * @since 2.0.0
   */
  def option(key: String, value: String): DataStreamWriter[T] = {
    this.extraOptions += (key -> value)
    this
  }

  /**
   * Adds an output option for the underlying data source.
   *
   * @since 2.0.0
   */
  def option(key: String, value: Boolean): DataStreamWriter[T] = option(key, value.toString)

  /**
   * Adds an output option for the underlying data source.
   *
   * @since 2.0.0
   */
  def option(key: String, value: Long): DataStreamWriter[T] = option(key, value.toString)

  /**
   * Adds an output option for the underlying data source.
   *
   * @since 2.0.0
   */
  def option(key: String, value: Double): DataStreamWriter[T] = option(key, value.toString)

  /**
   * (Scala-specific) Adds output options for the underlying data source.
   *
   * You can set the following option(s):
   *

   *
`timeZone` (default session local timezone): sets the string that indicates a timezone
   * to be used to format timestamps in the JSON/CSV datasources or partition values.

   *

   *
   * @since 2.0.0
   */
  def options(options: scala.collection.Map[String, String]): DataStreamWriter[T] = {
    this.extraOptions ++= options
    this
  }

  /**
   * Adds output options for the underlying data source.
   *
   * You can set the following option(s):
   *

   *
`timeZone` (default session local timezone): sets the string that indicates a timezone
   * to be used to format timestamps in the JSON/CSV datasources or partition values.

   *

   *
   * @since 2.0.0
   */
  def options(options: java.util.Map[String, String]): DataStreamWriter[T] = {
    this.options(options.asScala)
    this
  }

  /**
   * Starts the execution of the streaming query, which will continually output results to the given
   * path as new data arrives. The returned [[StreamingQuery]] object can be used to interact with
   * the stream.
   *
   * @since 2.0.0
   */
  def start(path: String): StreamingQuery = {
    option("path", path).start()
  }

  /**
   * Starts the execution of the streaming query, which will continually output results to the given
   * path as new data arrives. The returned [[StreamingQuery]] object can be used to interact with
   * the stream.
   *
   * @since 2.0.0
   */
  def start(): StreamingQuery = {
    if (source.toLowerCase == DDLUtils.HIVE_PROVIDER) {
      throw new AnalysisException("Hive data source can only be used with tables, you can not " +
        "write files of Hive data source directly.")
    }

    if (source == "memory") {
      assertNotPartitioned("memory")
      if (extraOptions.get("queryName").isEmpty) {
        throw new AnalysisException("queryName must be specified for memory sink")
      }
      val sink = new MemorySink(df.schema, outputMode)
      val resultDf = Dataset.ofRows(df.sparkSession, new MemoryPlan(sink))
      val chkpointLoc = extraOptions.get("checkpointLocation")
      val recoverFromChkpoint = outputMode == OutputMode.Complete()
      val query = df.sparkSession.sessionState.streamingQueryManager.startQuery(
        extraOptions.get("queryName"),
        chkpointLoc,
        df,
        sink,
        outputMode,
        useTempCheckpointLocation = true,
        recoverFromCheckpointLocation = recoverFromChkpoint,
        trigger = trigger)
      resultDf.createOrReplaceTempView(query.name)
      query
    } else if (source == "foreach") {
      assertNotPartitioned("foreach")
      val sink = new ForeachSink[T](foreachWriter)(ds.exprEnc)
      df.sparkSession.sessionState.streamingQueryManager.startQuery(
        extraOptions.get("queryName"),
        extraOptions.get("checkpointLocation"),
        df,
        sink,
        outputMode,
        useTempCheckpointLocation = true,
        trigger = trigger)
    } else {
      val (useTempCheckpointLocation, recoverFromCheckpointLocation) =
        if (source == "console") {
          (true, false)
        } else {
          (false, true)
        }
      val dataSource =
        DataSource(
          df.sparkSession,
          className = source,
          options = extraOptions.toMap,
          partitionColumns = normalizedParCols.getOrElse(Nil))
      df.sparkSession.sessionState.streamingQueryManager.startQuery(
        extraOptions.get("queryName"),
        extraOptions.get("checkpointLocation"),
        df,
        dataSource.createSink(outputMode),
        outputMode,
        useTempCheckpointLocation = useTempCheckpointLocation,
        recoverFromCheckpointLocation = recoverFromCheckpointLocation,
        trigger = trigger)
    }
  }

  /**
   * Starts the execution of the streaming query, which will continually send results to the given
   * `ForeachWriter` as new data arrives. The `ForeachWriter` can be used to send the data
   * generated by the `DataFrame`/`Dataset` to an external system.
   *
   * Scala example:
   * {{{
   *   datasetOfString.writeStream.foreach(new ForeachWriter[String] {
   *
   *     def open(partitionId: Long, version: Long): Boolean = {
   *       // open connection
   *     }
   *
   *     def process(record: String) = {
   *       // write string to connection
   *     }
   *
   *     def close(errorOrNull: Throwable): Unit = {
   *       // close the connection
   *     }
   *   }).start()
   * }}}
   *
   * Java example:
   * {{{
   *  datasetOfString.writeStream().foreach(new ForeachWriter<String>() {
   *
   *    @Override
   *    public boolean open(long partitionId, long version) {
   *      // open connection
   *    }
   *
   *    @Override
   *    public void process(String value) {
   *      // write string to connection
   *    }
   *
   *    @Override
   *    public void close(Throwable errorOrNull) {
   *      // close the connection
   *    }
   *  }).start();
   * }}}
   *
   * @since 2.0.0
   */
  def foreach(writer: ForeachWriter[T]): DataStreamWriter[T] = {
    this.source = "foreach"
    this.foreachWriter = if (writer != null) {
      ds.sparkSession.sparkContext.clean(writer)
    } else {
      throw new IllegalArgumentException("foreach writer cannot be null")
    }
    this
  }

  private def normalizedParCols: Option[Seq[String]] = partitioningColumns.map { cols =>
    cols.map(normalize(_, "Partition"))
  }

  /**
   * The given column name may not be equal to any of the existing column names if we were in
   * case-insensitive context. Normalize the given column name to the real one so that we don't
   * need to care about case sensitivity afterwards.
   */
  private def normalize(columnName: String, columnType: String): String = {
    val validColumnNames = df.logicalPlan.output.map(_.name)
    validColumnNames.find(df.sparkSession.sessionState.analyzer.resolver(_, columnName))
      .getOrElse(throw new AnalysisException(s"$columnType column $columnName not found in " +
        s"existing columns (${validColumnNames.mkString(", ")})"))
  }

  private def assertNotPartitioned(operation: String): Unit = {
    if (partitioningColumns.isDefined) {
      throw new AnalysisException(s"'$operation' does not support partitioning")
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////////
  // Builder pattern config options
  ///////////////////////////////////////////////////////////////////////////////////////

  private var source: String = df.sparkSession.sessionState.conf.defaultDataSourceName

  private var outputMode: OutputMode = OutputMode.Append

  private var trigger: Trigger = ProcessingTime(0L)

  private var extraOptions = new scala.collection.mutable.HashMap[String, String]

  private var foreachWriter: ForeachWriter[T] = null

  private var partitioningColumns: Option[Seq[String]] = None
}


text:
Create a function that will take a string argument and display a star box around it. For example, if the user inputs
"Hello", it should print the following:
```bash
*********
* Hello *
*********
```
Hint: Remember the len() function!


text:
class AddRateCalculatedToFees < ActiveRecord::Migration[5.0]
  def change
    add_column :fees, :rate_calculated, :boolean, default: false
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>StatementSupplier (Edgent v1.0.0)</title>
<meta name="date" content="2016-11-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.edgent.connectors.jdbc

Interface StatementSupplier

Functional Interface:

This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface
public interface StatementSupplier

Function that supplies a JDBC SQL PreparedStatement.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

java.sql.PreparedStatement
get(java.sql.Connection cn)

Create a JDBC SQL PreparedStatement containing 0 or more parameters.

Method Detail

get

java.sql.PreparedStatement get(java.sql.Connection cn)
                        throws java.sql.SQLException

Create a JDBC SQL PreparedStatement containing 0 or more parameters.

 Sample use:

 StatementSupplier ss =
     (cn) -> cn.prepareStatement("SELECT id, firstname, lastname"
                                  + " FROM persons WHERE id = ?");

Parameters:

cn - JDBC connection

Returns:

the PreparedStatement

Throws:

java.sql.SQLException - on failure

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Apache Edgent (incubating)

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation. All Rights Reserved - 73539fa-20161119-2136


text:
require "testing_env"
require "tab"
require "formula"

class TabTests < Homebrew::TestCase
  def setup
    @used = Options.create(%w[--with-foo --without-bar])
    @unused = Options.create(%w[--with-baz --without-qux])

    @tab = Tab.new("used_options"         => @used.as_flags,
                   "unused_options"       => @unused.as_flags,
                   "built_as_bottle"      => false,
                   "poured_from_bottle"   => true,
                   "time"                 => nil,
                   "source_modified_time" => 0,
                   "HEAD"                 => TEST_SHA1,
                   "compiler"             => "clang",
                   "stdlib"               => "libcxx",
                   "source"               => {
                     "tap" => "homebrew/core",
                     "path" => nil,
                     "spec" => "stable"
                   })
  end

  def test_defaults
    tab = Tab.empty
    assert_empty tab.unused_options
    assert_empty tab.used_options
    refute_predicate tab, :built_as_bottle
    refute_predicate tab, :poured_from_bottle
    assert_predicate tab, :stable?
    refute_predicate tab, :devel?
    refute_predicate tab, :head?
    assert_nil tab.tap
    assert_nil tab.time
    assert_nil tab.HEAD
    assert_equal DevelopmentTools.default_compiler, tab.cxxstdlib.compiler
    assert_nil tab.cxxstdlib.type
  end

  def test_include?
    assert_includes @tab, "with-foo"
    assert_includes @tab, "without-bar"
  end

  def test_with?
    assert @tab.with?("foo")
    assert @tab.with?("qux")
    refute @tab.with?("bar")
    refute @tab.with?("baz")
  end

  def test_universal?
    tab = Tab.new(:used_options => %w[--universal])
    assert_predicate tab, :universal?
  end

  def test_cxxstdlib
    assert_equal :clang, @tab.cxxstdlib.compiler
    assert_equal :libcxx, @tab.cxxstdlib.type
  end

  def test_other_attributes
    assert_equal TEST_SHA1, @tab.HEAD
    assert_equal "homebrew/core", @tab.tap.name
    assert_nil @tab.time
    refute_predicate @tab, :built_as_bottle
    assert_predicate @tab, :poured_from_bottle
  end

  def test_from_old_version_file
    path = Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt_old.json")
    tab = Tab.from_file(path)

    assert_equal @used.sort, tab.used_options.sort
    assert_equal @unused.sort, tab.unused_options.sort
    refute_predicate tab, :built_as_bottle
    assert_predicate tab, :poured_from_bottle
    assert_predicate tab, :stable?
    refute_predicate tab, :devel?
    refute_predicate tab, :head?
    assert_equal "homebrew/core", tab.tap.name
    assert_equal :stable, tab.spec
    refute_nil tab.time
    assert_equal TEST_SHA1, tab.HEAD
    assert_equal :clang, tab.cxxstdlib.compiler
    assert_equal :libcxx, tab.cxxstdlib.type
  end

  def test_from_file
    path = Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt.json")
    tab = Tab.from_file(path)

    assert_equal @used.sort, tab.used_options.sort
    assert_equal @unused.sort, tab.unused_options.sort
    refute_predicate tab, :built_as_bottle
    assert_predicate tab, :poured_from_bottle
    assert_predicate tab, :stable?
    refute_predicate tab, :devel?
    refute_predicate tab, :head?
    assert_equal "homebrew/core", tab.tap.name
    assert_equal :stable, tab.spec
    refute_nil tab.time
    assert_equal TEST_SHA1, tab.HEAD
    assert_equal :clang, tab.cxxstdlib.compiler
    assert_equal :libcxx, tab.cxxstdlib.type
  end

  def test_to_json
    tab = Tab.new(Utils::JSON.load(@tab.to_json))
    assert_equal @tab.used_options.sort, tab.used_options.sort
    assert_equal @tab.unused_options.sort, tab.unused_options.sort
    assert_equal @tab.built_as_bottle, tab.built_as_bottle
    assert_equal @tab.poured_from_bottle, tab.poured_from_bottle
    assert_equal @tab.tap, tab.tap
    assert_equal @tab.spec, tab.spec
    assert_equal @tab.time, tab.time
    assert_equal @tab.HEAD, tab.HEAD
    assert_equal @tab.compiler, tab.compiler
    assert_equal @tab.stdlib, tab.stdlib
  end

  def test_remap_deprecated_options
    deprecated_options = [DeprecatedOption.new("with-foo", "with-foo-new")]
    remapped_options = Tab.remap_deprecated_options(deprecated_options, @tab.used_options)
    assert_includes remapped_options, Option.new("without-bar")
    assert_includes remapped_options, Option.new("with-foo-new")
  end
end

class TabLoadingTests < Homebrew::TestCase
  def setup
    @f = formula { url "foo-1.0" }
    @f.prefix.mkpath
    @path = @f.prefix.join(Tab::FILENAME)
    @path.write Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt.json").read
  end

  def teardown
    @f.rack.rmtree
  end

  def test_for_keg
    tab = Tab.for_keg(@f.prefix)
    assert_equal @path, tab.tabfile
  end

  def test_for_keg_nonexistent_path
    @path.unlink
    tab = Tab.for_keg(@f.prefix)
    assert_nil tab.tabfile
  end

  def test_for_formula
    tab = Tab.for_formula(@f)
    assert_equal @path, tab.tabfile
  end

  def test_for_formula_nonexistent_path
    @path.unlink
    tab = Tab.for_formula(@f)
    assert_nil tab.tabfile
  end

  def test_for_formula_multiple_kegs
    f2 = formula { url "foo-2.0" }
    f2.prefix.mkpath

    assert_equal @f.rack, f2.rack
    assert_equal 2, @f.installed_prefixes.length

    tab = Tab.for_formula(@f)
    assert_equal @path, tab.tabfile
  end

  def test_for_formula_outdated_keg
    f2 = formula { url "foo-2.0" }

    assert_equal @f.rack, f2.rack
    assert_equal 1, @f.installed_prefixes.length

    tab = Tab.for_formula(f2)
    assert_equal @path, tab.tabfile
  end
end