text:
/**
 * @fileoverview Classes for all types of block events.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.provide('Blockly.Events.BlockBase');
goog.provide('Blockly.Events.BlockChange');
goog.provide('Blockly.Events.BlockCreate');
goog.provide('Blockly.Events.BlockDelete');
goog.provide('Blockly.Events.BlockMove');
goog.provide('Blockly.Events.Change');  // Deprecated.
goog.provide('Blockly.Events.Create');  // Deprecated.
goog.provide('Blockly.Events.Delete');  // Deprecated.
goog.provide('Blockly.Events.Move');  // Deprecated.

goog.require('Blockly.Events');
goog.require('Blockly.Events.Abstract');
goog.require('Blockly.utils.Coordinate');
goog.require('Blockly.utils.object');
goog.require('Blockly.utils.xml');
// TODO: Fix recursive dependency.
// goog.require('Blockly.Xml');

/**
 * Abstract class for a block event.
 * @param {Blockly.Block} block The block this event corresponds to.
 * @extends {Blockly.Events.Abstract}
 * @constructor
 */
Blockly.Events.BlockBase = function(block) {
  Blockly.Events.BlockBase.superClass_.constructor.call(this);

  /**
   * The block id for the block this event pertains to
   * @type {string}
   */
  this.blockId = block.id;
  this.workspaceId = block.workspace.id;
};
Blockly.utils.object.inherits(Blockly.Events.BlockBase,
    Blockly.Events.Abstract);

/**
 * Encode the event as JSON.
 * @return {!Object} JSON representation.
 */
Blockly.Events.BlockBase.prototype.toJson = function() {
  var json = Blockly.Events.BlockBase.superClass_.toJson.call(this);
  json['blockId'] = this.blockId;
  return json;
};

/**
 * Decode the JSON event.
 * @param {!Object} json JSON representation.
 */
Blockly.Events.BlockBase.prototype.fromJson = function(json) {
  Blockly.Events.BlockBase.superClass_.fromJson.call(this, json);
  this.blockId = json['blockId'];
};

/**
 * Class for a block change event.
 * @param {Blockly.Block} block The changed block.  Null for a blank event.
 * @param {string} element One of 'field', 'comment', 'disabled', etc.
 * @param {?string} name Name of input or field affected, or null.
 * @param {*} oldValue Previous value of element.
 * @param {*} newValue New value of element.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.Change = function(block, element, name, oldValue, newValue) {
  if (!block) {
    return;  // Blank event to be populated by fromJson.
  }
  Blockly.Events.Change.superClass_.constructor.call(this, block);
  this.element = element;
  this.name = name;
  this.oldValue = oldValue;
  this.newValue = newValue;
};
Blockly.utils.object.inherits(Blockly.Events.Change, Blockly.Events.BlockBase);

/**
 * Class for a block change event.
 * @param {Blockly.Block} block The changed block.  Null for a blank event.
 * @param {string} element One of 'field', 'comment', 'disabled', etc.
 * @param {?string} name Name of input or field affected, or null.
 * @param {*} oldValue Previous value of element.
 * @param {*} newValue New value of element.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.BlockChange = Blockly.Events.Change;

/**
 * Type of this event.
 * @type {string}
 */
Blockly.Events.Change.prototype.type = Blockly.Events.CHANGE;

/**
 * Encode the event as JSON.
 * @return {!Object} JSON representation.
 */
Blockly.Events.Change.prototype.toJson = function() {
  var json = Blockly.Events.Change.superClass_.toJson.call(this);
  json['element'] = this.element;
  if (this.name) {
    json['name'] = this.name;
  }
  json['newValue'] = this.newValue;
  return json;
};

/**
 * Decode the JSON event.
 * @param {!Object} json JSON representation.
 */
Blockly.Events.Change.prototype.fromJson = function(json) {
  Blockly.Events.Change.superClass_.fromJson.call(this, json);
  this.element = json['element'];
  this.name = json['name'];
  this.newValue = json['newValue'];
};

/**
 * Does this event record any change of state?
 * @return {boolean} False if something changed.
 */
Blockly.Events.Change.prototype.isNull = function() {
  return this.oldValue == this.newValue;
};

/**
 * Run a change event.
 * @param {boolean} forward True if run forward, false if run backward (undo).
 */
Blockly.Events.Change.prototype.run = function(forward) {
  var workspace = this.getEventWorkspace_();
  var block = workspace.getBlockById(this.blockId);
  if (!block) {
    console.warn("Can't change non-existent block: " + this.blockId);
    return;
  }
  if (block.mutator) {
    // Close the mutator (if open) since we don't want to update it.
    block.mutator.setVisible(false);
  }
  var value = forward ? this.newValue : this.oldValue;
  switch (this.element) {
    case 'field':
      var field = block.getField(this.name);
      if (field) {
        field.setValue(value);
      } else {
        console.warn("Can't set non-existent field: " + this.name);
      }
      break;
    case 'comment':
      block.setCommentText(/** @type {string} */ (value) || null);
      break;
    case 'collapsed':
      block.setCollapsed(!!value);
      break;
    case 'disabled':
      block.setEnabled(!value);
      break;
    case 'inline':
      block.setInputsInline(!!value);
      break;
    case 'mutation':
      var oldMutation = '';
      if (block.mutationToDom) {
        var oldMutationDom = block.mutationToDom();
        oldMutation = oldMutationDom && Blockly.Xml.domToText(oldMutationDom);
      }
      if (block.domToMutation) {
        var dom = Blockly.Xml.textToDom(/** @type {string} */ (value) || '<mutation/>');
        block.domToMutation(dom);
      }
      Blockly.Events.fire(new Blockly.Events.Change(
          block, 'mutation', null, oldMutation, value));
      break;
    default:
      console.warn('Unknown change type: ' + this.element);
  }
};

/**
 * Class for a block creation event.
 * @param {Blockly.Block} block The created block.  Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.Create = function(block) {
  if (!block) {
    return;  // Blank event to be populated by fromJson.
  }
  Blockly.Events.Create.superClass_.constructor.call(this, block);

  if (block.workspace.rendered) {
    this.xml = Blockly.Xml.blockToDomWithXY(block);
  } else {
    this.xml = Blockly.Xml.blockToDom(block);
  }
  this.ids = Blockly.Events.getDescendantIds(block);
};
Blockly.utils.object.inherits(Blockly.Events.Create, Blockly.Events.BlockBase);

/**
 * Class for a block creation event.
 * @param {Blockly.Block} block The created block. Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.BlockCreate = Blockly.Events.Create;

/**
 * Type of this event.
 * @type {string}
 */
Blockly.Events.Create.prototype.type = Blockly.Events.CREATE;

/**
 * Encode the event as JSON.
 * @return {!Object} JSON representation.
 */
Blockly.Events.Create.prototype.toJson = function() {
  var json = Blockly.Events.Create.superClass_.toJson.call(this);
  json['xml'] = Blockly.Xml.domToText(this.xml);
  json['ids'] = this.ids;
  return json;
};

/**
 * Decode the JSON event.
 * @param {!Object} json JSON representation.
 */
Blockly.Events.Create.prototype.fromJson = function(json) {
  Blockly.Events.Create.superClass_.fromJson.call(this, json);
  this.xml = Blockly.Xml.textToDom(json['xml']);
  this.ids = json['ids'];
};

/**
 * Run a creation event.
 * @param {boolean} forward True if run forward, false if run backward (undo).
 */
Blockly.Events.Create.prototype.run = function(forward) {
  var workspace = this.getEventWorkspace_();
  if (forward) {
    var xml = Blockly.utils.xml.createElement('xml');
    xml.appendChild(this.xml);
    Blockly.Xml.domToWorkspace(xml, workspace);
  } else {
    for (var i = 0, id; id = this.ids[i]; i++) {
      var block = workspace.getBlockById(id);
      if (block) {
        block.dispose(false);
      } else if (id == this.blockId) {
        // Only complain about root-level block.
        console.warn("Can't uncreate non-existent block: " + id);
      }
    }
  }
};

/**
 * Class for a block deletion event.
 * @param {Blockly.Block} block The deleted block.  Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.Delete = function(block) {
  if (!block) {
    return;  // Blank event to be populated by fromJson.
  }
  if (block.getParent()) {
    throw Error('Connected blocks cannot be deleted.');
  }
  Blockly.Events.Delete.superClass_.constructor.call(this, block);

  if (block.workspace.rendered) {
    this.oldXml = Blockly.Xml.blockToDomWithXY(block);
  } else {
    this.oldXml = Blockly.Xml.blockToDom(block);
  }
  this.ids = Blockly.Events.getDescendantIds(block);
};
Blockly.utils.object.inherits(Blockly.Events.Delete, Blockly.Events.BlockBase);

/**
 * Class for a block deletion event.
 * @param {Blockly.Block} block The deleted block.  Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.BlockDelete = Blockly.Events.Delete;

/**
 * Type of this event.
 * @type {string}
 */
Blockly.Events.Delete.prototype.type = Blockly.Events.DELETE;

/**
 * Encode the event as JSON.
 * @return {!Object} JSON representation.
 */
Blockly.Events.Delete.prototype.toJson = function() {
  var json = Blockly.Events.Delete.superClass_.toJson.call(this);
  json['ids'] = this.ids;
  return json;
};

/**
 * Decode the JSON event.
 * @param {!Object} json JSON representation.
 */
Blockly.Events.Delete.prototype.fromJson = function(json) {
  Blockly.Events.Delete.superClass_.fromJson.call(this, json);
  this.ids = json['ids'];
};

/**
 * Run a deletion event.
 * @param {boolean} forward True if run forward, false if run backward (undo).
 */
Blockly.Events.Delete.prototype.run = function(forward) {
  var workspace = this.getEventWorkspace_();
  if (forward) {
    for (var i = 0, id; id = this.ids[i]; i++) {
      var block = workspace.getBlockById(id);
      if (block) {
        block.dispose(false);
      } else if (id == this.blockId) {
        // Only complain about root-level block.
        console.warn("Can't delete non-existent block: " + id);
      }
    }
  } else {
    var xml = Blockly.utils.xml.createElement('xml');
    xml.appendChild(this.oldXml);
    Blockly.Xml.domToWorkspace(xml, workspace);
  }
};

/**
 * Class for a block move event.  Created before the move.
 * @param {Blockly.Block} block The moved block.  Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.Move = function(block) {
  if (!block) {
    return;  // Blank event to be populated by fromJson.
  }
  Blockly.Events.Move.superClass_.constructor.call(this, block);
  var location = this.currentLocation_();
  this.oldParentId = location.parentId;
  this.oldInputName = location.inputName;
  this.oldCoordinate = location.coordinate;
};
Blockly.utils.object.inherits(Blockly.Events.Move, Blockly.Events.BlockBase);

/**
 * Class for a block move event.  Created before the move.
 * @param {Blockly.Block} block The moved block.  Null for a blank event.
 * @extends {Blockly.Events.BlockBase}
 * @constructor
 */
Blockly.Events.BlockMove = Blockly.Events.Move;

/**
 * Type of this event.
 * @type {string}
 */
Blockly.Events.Move.prototype.type = Blockly.Events.MOVE;

/**
 * Encode the event as JSON.
 * @return {!Object} JSON representation.
 */
Blockly.Events.Move.prototype.toJson = function() {
  var json = Blockly.Events.Move.superClass_.toJson.call(this);
  if (this.newParentId) {
    json['newParentId'] = this.newParentId;
  }
  if (this.newInputName) {
    json['newInputName'] = this.newInputName;
  }
  if (this.newCoordinate) {
    json['newCoordinate'] = Math.round(this.newCoordinate.x) + ',' +
        Math.round(this.newCoordinate.y);
  }
  return json;
};

/**
 * Decode the JSON event.
 * @param {!Object} json JSON representation.
 */
Blockly.Events.Move.prototype.fromJson = function(json) {
  Blockly.Events.Move.superClass_.fromJson.call(this, json);
  this.newParentId = json['newParentId'];
  this.newInputName = json['newInputName'];
  if (json['newCoordinate']) {
    var xy = json['newCoordinate'].split(',');
    this.newCoordinate =
        new Blockly.utils.Coordinate(Number(xy[0]), Number(xy[1]));
  }
};

/**
 * Record the block's new location.  Called after the move.
 */
Blockly.Events.Move.prototype.recordNew = function() {
  var location = this.currentLocation_();
  this.newParentId = location.parentId;
  this.newInputName = location.inputName;
  this.newCoordinate = location.coordinate;
};

/**
 * Returns the parentId and input if the block is connected,
 *   or the XY location if disconnected.
 * @return {!Object} Collection of location info.
 * @private
 */
Blockly.Events.Move.prototype.currentLocation_ = function() {
  var workspace = this.getEventWorkspace_();
  var block = workspace.getBlockById(this.blockId);
  var location = {};
  var parent = block.getParent();
  if (parent) {
    location.parentId = parent.id;
    var input = parent.getInputWithBlock(block);
    if (input) {
      location.inputName = input.name;
    }
  } else {
    location.coordinate = block.getRelativeToSurfaceXY();
  }
  return location;
};

/**
 * Does this event record any change of state?
 * @return {boolean} False if something changed.
 */
Blockly.Events.Move.prototype.isNull = function() {
  return this.oldParentId == this.newParentId &&
      this.oldInputName == this.newInputName &&
      Blockly.utils.Coordinate.equals(this.oldCoordinate, this.newCoordinate);
};

/**
 * Run a move event.
 * @param {boolean} forward True if run forward, false if run backward (undo).
 */
Blockly.Events.Move.prototype.run = function(forward) {
  var workspace = this.getEventWorkspace_();
  var block = workspace.getBlockById(this.blockId);
  if (!block) {
    console.warn("Can't move non-existent block: " + this.blockId);
    return;
  }
  var parentId = forward ? this.newParentId : this.oldParentId;
  var inputName = forward ? this.newInputName : this.oldInputName;
  var coordinate = forward ? this.newCoordinate : this.oldCoordinate;
  var parentBlock = null;
  if (parentId) {
    parentBlock = workspace.getBlockById(parentId);
    if (!parentBlock) {
      console.warn("Can't connect to non-existent block: " + parentId);
      return;
    }
  }
  if (block.getParent()) {
    block.unplug();
  }
  if (coordinate) {
    var xy = block.getRelativeToSurfaceXY();
    block.moveBy(coordinate.x - xy.x, coordinate.y - xy.y);
  } else {
    var blockConnection = block.outputConnection || block.previousConnection;
    var parentConnection;
    if (inputName) {
      var input = parentBlock.getInput(inputName);
      if (input) {
        parentConnection = input.connection;
      }
    } else if (blockConnection.type == Blockly.PREVIOUS_STATEMENT) {
      parentConnection = parentBlock.nextConnection;
    }
    if (parentConnection) {
      blockConnection.connect(parentConnection);
    } else {
      console.warn("Can't connect to non-existent input: " + inputName);
    }
  }
};


text:
namespace IoT {
namespace NetworkEnvironment {

NetworkEnvironmentService::NetworkEnvironmentService()
{
}

NetworkEnvironmentService::~NetworkEnvironmentService()
{
}

} } // namespace IoT::NetworkEnvironment

redpajama_set_name: RedPajamaGithub


text:
USING_NS_CC;

bool Bird::init()
{
    if (!Sprite::init()) {
        return false;
    }

    visibleSize = Director::getInstance()->getVisibleSize();
    velocity = 0.0f;
    gravity = 18.0f;
    state = State::Normal;

    // setAnchorPoint(Point(0.5f, 1.0f));

    auto animation = Animation::create();
    int which = rand() % 3;
    for (int i = 0; i < 3; ++i) {
        auto imageName = String::createWithFormat(IMAGES_DIR "bird%d_%d.png", which, i);
        animation->addSpriteFrameWithFile(imageName->getCString());
    }

    animation->setDelayPerUnit(0.2f);
    animation->setRestoreOriginalFrame(false);
    animation->setLoops(-1);

    normalAnimation = Animate::create(animation);
    runAction(normalAnimation);

    // fallAnimation = EaseOut::create(RotateTo::create(0.6f, 90.0f), 0.4f);
    fallAnimation = RotateTo::create(0.6f, 90.0f);
    fallAnimation->retain();

    flyAnimation = Sequence::create(
        EaseOut::create(RotateTo::create(0.15f, 0), 0.4f),
        EaseIn::create(RotateTo::create(0.25f, -30), 0.4f),
        // RotateTo::create(0.15f, 0),
        // RotateTo::create(0.25f, -30),
        nullptr
    );
    flyAnimation->retain();

    return true;
}

void Bird::update(float dt)
{
    float y = getPositionY() - velocity * dt;
    if (y > visibleSize.height) {
        y = visibleSize.height;
    }
    setPositionY(y);
    if (velocity < 0 && velocity + gravity >= 0) {
        fall();
    }
    velocity += gravity;
}

void Bird::flyUp()
{
    velocity = -360.0f;
    if (state != State::FlyingUp) {
        if (state == State::Falling) {
            stopAction(fallAnimation);
        }
        runAction(flyAnimation);
        state = State::FlyingUp;
    }
}

void Bird::fall()
{
    if (state == State::FlyingUp) {
        stopAction(flyAnimation);
        runAction(fallAnimation);
        state = State::Falling;
    }
}

void Bird::die()
{
    stopAllActions();
}


text:
RSpec.describe "and_wrap_original" do
  context "on a partial double" do
    let(:klass) do
      Class.new do
        def results
          (1..100).to_a
        end
      end
    end

    let(:instance) { klass.new }

    shared_examples "using and_wrap_original" do
      it "allows us to modify the results of the original method" do
        expect {
          allow_it.to receive(:results).and_wrap_original do |m|
            m.call.first(10)
          end
        }.to change { instance.results.size }.from(100).to(10)
      end

      it "raises a name error if the method does not exist" do
        expect {
          allow_it.to receive(:no_results).and_wrap_original { |m| m.call }
          instance.no_results
        }.to raise_error NameError
      end

      it "passes in the original method" do
        value = nil
        original_method = instance.method(:results)
        allow_it.to receive(:results).and_wrap_original { |m| value = m }
        instance.results
        expect(value).to eq original_method
      end

      it "passes along the message arguments" do
        values = nil
        allow_it.to receive(:results).and_wrap_original { |_, *args| values  = args }
        instance.results(1, 2, 3)
        expect(values).to eq [1, 2, 3]
      end

      it "passes along any supplied block" do
        value = nil
        allow_it.to receive(:results).and_wrap_original { |&b| value = b }
        instance.results(&(block = proc {}))
        expect(value).to eq block
      end

      it "ignores previous stubs" do
        allow_it.to receive(:results) { "results" }
        allow_it.to receive(:results).and_wrap_original { |m| m.call }
        expect(instance.results).to_not eq "results"
      end

      it "can be constrained by specific arguments" do
        allow_it.to receive(:results) { :all }
        allow_it.to receive(:results).with(5).and_wrap_original { |m, n| m.call.first(n) }
        expect(instance.results 5).to eq [1,2,3,4,5]
        expect(instance.results).to eq :all
      end
    end

    describe "allow(...).to receive(...).and_wrap_original" do
      it_behaves_like "using and_wrap_original" do
        let(:allow_it) { allow(instance) }
      end
    end

    describe "allow_any_instance_of(...).to receive(...).and_wrap_original" do
      it_behaves_like "using and_wrap_original" do
        let(:allow_it) { allow_any_instance_of(klass) }
      end
    end
  end
end


text:
from __future__ import print_function

from pyspark.sql import SparkSession
# $example on:schema_merging$
from pyspark.sql import Row
# $example off:schema_merging$

"""
A simple example demonstrating Spark SQL data sources.
Run with:
  ./bin/spark-submit examples/src/main/python/sql/datasource.py
"""

def basic_datasource_example(spark):
    # $example on:generic_load_save_functions$
    df = spark.read.load("examples/src/main/resources/users.parquet")
    df.select("name", "favorite_color").write.save("namesAndFavColors.parquet")
    # $example off:generic_load_save_functions$

    # $example on:manual_load_options$
    df = spark.read.load("examples/src/main/resources/people.json", format="json")
    df.select("name", "age").write.save("namesAndAges.parquet", format="parquet")
    # $example off:manual_load_options$

    # $example on:direct_sql$
    df = spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")
    # $example off:direct_sql$

def parquet_example(spark):
    # $example on:basic_parquet_example$
    peopleDF = spark.read.json("examples/src/main/resources/people.json")

    # DataFrames can be saved as Parquet files, maintaining the schema information.
    peopleDF.write.parquet("people.parquet")

    # Read in the Parquet file created above.
    # Parquet files are self-describing so the schema is preserved.
    # The result of loading a parquet file is also a DataFrame.
    parquetFile = spark.read.parquet("people.parquet")

    # Parquet files can also be used to create a temporary view and then used in SQL statements.
    parquetFile.createOrReplaceTempView("parquetFile")
    teenagers = spark.sql("SELECT name FROM parquetFile WHERE age >= 13 AND age <= 19")
    teenagers.show()
    # +------+
    # |  name|
    # +------+
    # |Justin|
    # +------+
    # $example off:basic_parquet_example$

def parquet_schema_merging_example(spark):
    # $example on:schema_merging$
    # spark is from the previous example.
    # Create a simple DataFrame, stored into a partition directory
    sc = spark.sparkContext

    squaresDF = spark.createDataFrame(sc.parallelize(range(1, 6))
                                      .map(lambda i: Row(single=i, double=i ** 2)))
    squaresDF.write.parquet("data/test_table/key=1")

    # Create another DataFrame in a new partition directory,
    # adding a new column and dropping an existing column
    cubesDF = spark.createDataFrame(sc.parallelize(range(6, 11))
                                    .map(lambda i: Row(single=i, triple=i ** 3)))
    cubesDF.write.parquet("data/test_table/key=2")

    # Read the partitioned table
    mergedDF = spark.read.option("mergeSchema", "true").parquet("data/test_table")
    mergedDF.printSchema()

    # The final schema consists of all 3 columns in the Parquet files together
    # with the partitioning column appeared in the partition directory paths.
    # root
    #  |-- double: long (nullable = true)
    #  |-- single: long (nullable = true)
    #  |-- triple: long (nullable = true)
    #  |-- key: integer (nullable = true)
    # $example off:schema_merging$

def json_dataset_example(spark):
    # $example on:json_dataset$
    # spark is from the previous example.
    sc = spark.sparkContext

    # A JSON dataset is pointed to by path.
    # The path can be either a single text file or a directory storing text files
    path = "examples/src/main/resources/people.json"
    peopleDF = spark.read.json(path)

    # The inferred schema can be visualized using the printSchema() method
    peopleDF.printSchema()
    # root
    #  |-- age: long (nullable = true)
    #  |-- name: string (nullable = true)

    # Creates a temporary view using the DataFrame
    peopleDF.createOrReplaceTempView("people")

    # SQL statements can be run by using the sql methods provided by spark
    teenagerNamesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")
    teenagerNamesDF.show()
    # +------+
    # |  name|
    # +------+
    # |Justin|
    # +------+

    # Alternatively, a DataFrame can be created for a JSON dataset represented by
    # an RDD[String] storing one JSON object per string
    jsonStrings = ['{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}']
    otherPeopleRDD = sc.parallelize(jsonStrings)
    otherPeople = spark.read.json(otherPeopleRDD)
    otherPeople.show()
    # +---------------+----+
    # |        address|name|
    # +---------------+----+
    # |[Columbus,Ohio]| Yin|
    # +---------------+----+
    # $example off:json_dataset$

def jdbc_dataset_example(spark):
    # $example on:jdbc_dataset$
    jdbcDF = spark.read \
        .format("jdbc") \
        .option("url", "jdbc:postgresql:dbserver") \
        .option("dbtable", "schema.tablename") \
        .option("user", "username") \
        .option("password", "password") \
        .load()
    # $example off:jdbc_dataset$

if __name__ == "__main__":
    spark = SparkSession \
        .builder \
        .appName("Python Spark SQL data source example") \
        .getOrCreate()

    basic_datasource_example(spark)
    parquet_example(spark)
    parquet_schema_merging_example(spark)
    json_dataset_example(spark)
    jdbc_dataset_example(spark)

    spark.stop()


text:
package skip

import (
	"reflect"
	"testing"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/github/fakegithub"
)

func TestSkipStatus(t *testing.T) {
	tests := []struct {
		name string

		presubmits     []config.Presubmit
		sha            string
		event          *github.GenericCommentEvent
		prChanges      map[int][]github.PullRequestChange
		existing       []github.Status
		combinedStatus string
		expected       []github.Status
	}{
		{
			name: "required contexts should not be skipped regardless of their state",

			presubmits: []config.Presubmit{
				{
					Reporter: config.Reporter{
						Context: "passing-tests",
					},
				},
				{
					Reporter: config.Reporter{
						Context: "failed-tests",
					},
				},
				{
					Reporter: config.Reporter{
						Context: "pending-tests",
					},
				},
			},
			sha: "shalala",
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body:       "/skip",
				Number:     1,
				Repo:       github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{
				{
					Context: "passing-tests",
					State:   github.StatusSuccess,
				},
				{
					Context: "failed-tests",
					State:   github.StatusFailure,
				},
				{
					Context: "pending-tests",
					State:   github.StatusPending,
				},
			},

			expected: []github.Status{
				{
					Context: "passing-tests",
					State:   github.StatusSuccess,
				},
				{
					Context: "failed-tests",
					State:   github.StatusFailure,
				},
				{
					Context: "pending-tests",
					State:   github.StatusPending,
				},
			},
		},
		{
			name: "optional contexts that have failed or are pending should be skipped",

			presubmits: []config.Presubmit{
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "failed-tests",
					},
				},
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "pending-tests",
					},
				},
			},
			sha: "shalala",
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body:       "/skip",
				Number:     1,
				Repo:       github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{
				{
					State:   github.StatusFailure,
					Context: "failed-tests",
				},
				{
					State:   github.StatusPending,
					Context: "pending-tests",
				},
			},

			expected: []github.Status{
				{
					State:       github.StatusSuccess,
					Description: "Skipped",
					Context:     "failed-tests",
				},
				{
					State:       github.StatusSuccess,
					Description: "Skipped",
					Context:     "pending-tests",
				},
			},
		},
		{
			name: "optional contexts that have not posted a context should not be skipped",

			presubmits: []config.Presubmit{
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "untriggered-tests",
					},
				},
			},
			sha: "shalala",
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body:       "/skip",
				Number:     1,
				Repo:       github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{},

			expected: []github.Status{},
		},
		{
			name: "optional contexts that have succeeded should not be skipped",

			presubmits: []config.Presubmit{
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "succeeded-tests",
					},
				},
			},
			sha: "shalala",
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body:       "/skip",
				Number:     1,
				Repo:       github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{
				{
					State:   github.StatusSuccess,
					Context: "succeeded-tests",
				},
			},

			expected: []github.Status{
				{
					State:   github.StatusSuccess,
					Context: "succeeded-tests",
				},
			},
		},
		{
			name: "optional tests that have failed but will be handled by trigger should not be skipped",

			presubmits: []config.Presubmit{
				{
					Optional:     true,
					Trigger:      `(?m)^/test (?:.*? )?job(?: .*?)?$`,
					RerunCommand: "/test job",
					Reporter: config.Reporter{
						Context: "failed-tests",
					},
				},
			},
			sha: "shalala",
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body: `/skip
/test job`,
				Number: 1,
				Repo:   github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{
				{
					State:   github.StatusFailure,
					Context: "failed-tests",
				},
			},
			expected: []github.Status{
				{
					State:   github.StatusFailure,
					Context: "failed-tests",
				},
			},
		},
		{
			name: "no contexts should be skipped if the combined status is success",

			presubmits: []config.Presubmit{
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "failed-tests",
					},
				},
				{
					Optional: true,
					Reporter: config.Reporter{
						Context: "pending-tests",
					},
				},
			},
			sha:            "shalala",
			combinedStatus: github.StatusSuccess,
			event: &github.GenericCommentEvent{
				IsPR:       true,
				IssueState: "open",
				Action:     github.GenericCommentActionCreated,
				Body:       "/skip",
				Number:     1,
				Repo:       github.Repo{Owner: github.User{Login: "org"}, Name: "repo"},
			},
			existing: []github.Status{
				{
					State:   github.StatusFailure,
					Context: "failed-tests",
				},
				{
					State:   github.StatusPending,
					Context: "pending-tests",
				},
			},
			expected: []github.Status{
				{
					State:   github.StatusFailure,
					Context: "failed-tests",
				},
				{
					State:   github.StatusPending,
					Context: "pending-tests",
				},
			},
		},
	}
	for _, test := range tests {
		if err := config.SetPresubmitRegexes(test.presubmits); err != nil {
			t.Fatalf("%s: could not set presubmit regexes: %v", test.name, err)
		}

		fghc := &fakegithub.FakeClient{
			IssueComments: make(map[int][]github.IssueComment),
			PullRequests: map[int]*github.PullRequest{
				test.event.Number: {
					Head: github.PullRequestBranch{
						SHA: test.sha,
					},
				},
			},
			PullRequestChanges: test.prChanges,
			CreatedStatuses: map[string][]github.Status{
				test.sha: test.existing,
			},
			CombinedStatuses: map[string]*github.CombinedStatus{
				test.sha: {
					State:    test.combinedStatus,
					Statuses: test.existing,
				},
			},
		}
		l := logrus.WithField("plugin", pluginName)

		c := &config.Config{
			JobConfig: config.JobConfig{
				PresubmitsStatic: map[string][]config.Presubmit{"org/repo": test.presubmits},
			},
		}

		if err := handle(fghc, l, test.event, c, nil, true); err != nil {
			t.Errorf("%s: unexpected error: %v", test.name, err)
			continue
		}

		// Check that the correct statuses have been updated.
		created := fghc.CreatedStatuses[test.sha]
		if len(test.expected) != len(created) {
			t.Errorf("%s: status mismatch: expected:\n%+v\ngot:\n%+v", test.name, test.expected, created)
			continue
		}
		for _, got := range created {
			var found bool
			for _, exp := range test.expected {
				if exp.Context == got.Context {
					found = true
					if !reflect.DeepEqual(exp, got) {
						t.Errorf("%s: expected status: %v, got: %v", test.name, exp, got)
					}
				}
			}
			if !found {
				t.Errorf("%s: expected context %q in the results: %v", test.name, got.Context, created)
				break
			}
		}
	}
}


text:
using System;
using System.Collections.Generic;

namespace Twilio.TaskRouter
{
    /// <summary>
    /// Workspace statistics.
    /// </summary>
    public class WorkspaceStatistics : TwilioBase
    {
        /// <summary>
        /// Gets or sets the account sid.
        /// </summary>
        public string AccountSid { get; set; }
        /// <summary>
        /// Gets or sets the workspace sid.
        /// </summary>
        public string WorkspaceSid { get; set; }
        /// <summary>
        /// Gets or sets the realtime.
        /// </summary>
        public RealtimeStatistics Realtime { get; set; }
        /// <summary>
        /// Gets or sets the cumulative.
        /// </summary>
        public CumulativeStatistics Cumulative { get; set; }

        /// <summary>
        /// Activity statistics.
        /// </summary>
        public class ActivityStatistics
        {
            /// <summary>
            /// Gets or sets the sid.
            /// </summary>
            public string Sid { get; set; }
            /// <summary>
            /// Gets or sets the name of the friendly.
            /// </summary>
            public string FriendlyName { get; set; }
            /// <summary>
            /// Gets or sets the workers.
            /// </summary>
            public int? Workers { get; set; }
        }

        /// <summary>
        /// Cumulative statistics.
        /// </summary>
        public class CumulativeStatistics
        {
            /// <summary>
            /// Gets or sets the start time.
            /// </summary>
            public DateTimeOffset? StartTime { get; set; }
            /// <summary>
            /// Gets or sets the end time.
            /// </summary>
            public DateTimeOffset? EndTime { get; set; }
            /// <summary>
            /// Gets or sets the reservations accepted.
            /// </summary>
            public int? ReservationsAccepted { get; set; }
            /// <summary>
            /// Gets or sets the reservations rejected.
            /// </summary>
            public int? ReservationsRejected { get; set; }
            /// <summary>
            /// Gets or sets the reservations timed out.
            /// </summary>
            public int? ReservationsTimedOut { get; set; }
            /// <summary>
            /// Gets or sets the tasks created.
            /// </summary>
            public int? TasksCreated { get; set; }
            /// <summary>
            /// Gets or sets the tasks canceled.
            /// </summary>
            public int? TasksCanceled { get; set; }
            /// <summary>
            /// Gets or sets the tasks moved.
            /// </summary>
            public int? TasksMoved { get; set; }
            /// <summary>
            /// Gets or sets the tasks timed out in workflow.
            /// </summary>
            public int? TasksTimedOutInWorkflow { get; set; }
            /// <summary>
            /// Gets or sets the avg task acceptance time.
            /// </summary>
            public decimal? AvgTaskAcceptanceTime { get; set; }

        }

        /// <summary>
        /// Realtime statistics.
        /// </summary>
        public class RealtimeStatistics
        {
            /// <summary>
            /// Gets or sets the longest task waiting sid.
            /// </summary>
            public string LongestTaskWaitingSid { get; set; }
            /// <summary>
            /// Gets or sets the longest task waiting age.
            /// </summary>
            public int? LongestTaskWaitingAge { get; set; }
            /// <summary>
            /// Gets or sets the total tasks.
            /// </summary>
            public int? TotalTasks { get; set; }
            /// <summary>
            /// Gets or sets the total workers.
            /// </summary>
            public int? TotalWorkers { get; set; }
            /// <summary>
            /// Gets or sets the tasks by status.
            /// </summary>
            public TasksByStatus TasksByStatus { get; set; }
            /// <summary>
            /// Gets or sets the activity statistics.
            /// </summary>
            public List<ActivityStatistics> ActivityStatistics { get; set; }
        }

        /// <summary>
        /// Tasks by status.
        /// </summary>
        public class TasksByStatus
        {
            /// <summary>
            /// Gets or sets the pending.
            /// </summary>
            public int? Pending { get; set; }
            /// <summary>
            /// Gets or sets the assigned.
            /// </summary>
            public int? Assigned { get; set; }
            /// <summary>
            /// Gets or sets the reserved.
            /// </summary>
            public int? Reserved { get; set; }
        }
    }
}


text:
import Ember from 'ember';
import {computed} from '@ember/object';

export default Ember.Component.extend({
  navi: Ember.inject.service('gallery-ui-navigation'),

  topbar: computed('navi.topbar', function () {
    return this.get('navi').topbar;
  }),
});


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

<title>Windows (Quarks v0.4.0)</title>
<meta name="date" content="2016-03-07">
<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

quarks.window

Class Windows

java.lang.Object

quarks.window.Windows

public class Windows
extends java.lang.Object

Factory to create Window implementations.

Constructor Summary

Constructors

Constructor and Description

Windows()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static <T,K> Window<T,K,java.util.LinkedList<T>>
lastNProcessOnInsert(int count,
                    Function<T,K> keyFunction)

Return a window that maintains the last count tuples inserted
 with processing triggered on every insert.

static <T,K,L extends java.util.List<T>>
Window<T,K,L>
window(BiFunction<Partition<T,K,L>,T,java.lang.Boolean> insertionPolicy,
      BiConsumer<Partition<T,K,L>,T> contentsPolicy,
      Consumer<Partition<T,K,L>> evictDeterminer,
      BiConsumer<Partition<T,K,L>,T> triggerPolicy,
      Function<T,K> keyFunction,
      Supplier<L> listSupplier)

Create a window using the passed in policies.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Windows

public Windows()

Method Detail

window

public static <T,K,L extends java.util.List<T>> Window<T,K,L> window(BiFunction<Partition<T,K,L>,T,java.lang.Boolean> insertionPolicy,
                                                                     BiConsumer<Partition<T,K,L>,T> contentsPolicy,
                                                                     Consumer<Partition<T,K,L>> evictDeterminer,
                                                                     BiConsumer<Partition<T,K,L>,T> triggerPolicy,
                                                                     Function<T,K> keyFunction,
                                                                     Supplier<L> listSupplier)

Create a window using the passed in policies.

Parameters:

insertionPolicy - Policy indicating if a tuple should be inserted
 into the window.

contentsPolicy - Contents policy called prior to insertion of a tuple.

evictDeterminer - Policy that determines action to take when
 Partition.evict() is called.

triggerPolicy - Trigger policy that is invoked after the insertion
 of a tuple into a partition.

keyFunction - Function that gets the partition key from a tuple.

listSupplier - Supplier function for the List that holds
 tuples within a partition.

Returns:

Window using the passed in policies.

lastNProcessOnInsert

public static <T,K> Window<T,K,java.util.LinkedList<T>> lastNProcessOnInsert(int count,
                                                                             Function<T,K> keyFunction)

Return a window that maintains the last count tuples inserted
 with processing triggered on every insert. This provides
 a continuous processing, where processing is invoked every
 time the window changes. Since insertion drives eviction
 there is no need to process on eviction, thus once the window
 has reached count tuples, each insertion results in an
 eviction followed by processing of count tuples
 including the tuple just inserted, which is the definition of
 the window.

Type Parameters:

T - Tuple type.

K - Key type.

Parameters:

count - Number of tuple to maintain per partition

keyFunction - Tuple partitioning key function

Returns:

window that maintains the last count tuples on a stream

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

quarks-edge community @ github.com

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright IBM 2015,2016 - 2f6ad0e-20160307-0902


text:
import template from './applicationQuestionsForm.html';
import controller from './applicationQuestionsForm.controller';
import './applicationQuestionsForm.styl';

let applicationQuestionsFormComponent = {
  restrict: 'E',
  bindings: {appId:'=', schoolId:'=', isValid:'=', appType:'=' },
  template,
  controller
};

export default applicationQuestionsFormComponent;


text:
#ifndef _HISTORY_H_
#define _HISTORY_H_

static inline void add_history(const char *c)
{
}

#endif


text:
// __BEGIN_LICENSE__
//  Copyright (c) 2006-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is licensed under the Apache License,
//  Version 2.0 (the "License"); you may not use this file except in
//  compliance with the License. You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// __END_LICENSE__

#include <vw/Plate/ToastPlateManager.h>
#include <vw/Image/Filter.h>
#include <vw/Image/Algorithms.h>
#include <vw/Cartography/GeoReference.h>
#include <vw/Cartography/ToastTransform.h>

using namespace vw::platefile;
using namespace vw;

template <class PixelT>
void ToastPlateManager<PixelT>::transform_image(
                     cartography::GeoReference const& georef,
                     ImageViewRef<PixelT>& image,
                     TransformRef& txref, int& level ) const {
  // Compute the pyramid level at which to store this image.  The
  // number of required levels is broken down so that the very top
  // of the pyramid covers the entire globe and has a size of
  // tile_size.
  int tile_size = this->m_platefile->default_tile_size();
  Vector2 p0 = georef.pixel_to_lonlat(Vector2(image.cols()/2,
                                              image.rows()/2));
  Vector2 p1 = georef.pixel_to_lonlat(Vector2(image.cols()/2+1,
                                              image.rows()/2));
  Vector2 p2 = georef.pixel_to_lonlat(Vector2(image.cols()/2,
                                              image.rows()/2+1));
  double degrees_per_pixel = sqrt(pow(p1.y()-p0.y(),2)+pow(p2.y()-p0.y(),2));
  level = static_cast<int>(round(log(360/degrees_per_pixel/(tile_size-1)) / log(2)));

  // Compute the resolution of the TOAST output space at the given
  // pyramid_level.  The formula below was carefully chosen to
  // ensure that the output space at each level is sized just
  // slightly shy of an even power of two; therby allowing for the
  // slight overlap of one line of pixels on the right and the
  // bottom of a toast tile.  This overlap is necessary for proper
  // positioning when these tiles are rendered as texture in a 3D
  // graphics environment.
  int resolution = (1<<level)*(tile_size-1)+1;

  // Set up the toast transform and compute the bounding box of this
  // image in the toast projection space.
  cartography::ToastTransform toast_tx( georef, resolution );
  BBox2i output_bbox = toast_tx.forward_bbox(bounding_box(image));

  VW_OUT(InfoMessage, "platefile")
    << "\t    Placing image at level " << level
    << " with bbox " << output_bbox << "\n"
    << "\t    (Total TOAST resolution at this level =  "
    << resolution << " pixels.)\n";

  ImageViewRef<PixelT> holding =
    transform( image, toast_tx, ZeroEdgeExtension(),
               BicubicInterpolation() );
  image = holding;
  txref = TransformRef(toast_tx);
}

template <class PixelT>
cartography::GeoReference
ToastPlateManager<PixelT>::georeference( int /*level*/ ) const {
  vw_throw( NoImplErr() << "Toast Plate Manager can not provide a georeference object." );
}

template <class PixelT>
ImageView<PixelT>
ToastPlateManager<PixelT>::fetch_child_tile(int x, int y, int level,
                                            TransactionOrNeg transaction_id) const {
  int32 num_tiles = 1 << level;
  if ( x==-1 ) {
    if ( y==-1 )
      return fetch_child_tile(num_tiles-1, num_tiles-1, level, transaction_id);
    if ( y==num_tiles )
      return fetch_child_tile(num_tiles-1, 0, level, transaction_id);
    ImageView<PixelT> tile =
      fetch_child_tile(0, num_tiles-1-y, level, transaction_id);
    if ( tile ) return rotate_180(tile);
    else return tile;
  }
  if ( x==num_tiles ) {
    if ( y==-1 )
      return fetch_child_tile(0, num_tiles-1, level, transaction_id);
    if ( y==num_tiles )
      return fetch_child_tile(0, 0, level, transaction_id);
    ImageView<PixelT> tile =
      fetch_child_tile(num_tiles-1, num_tiles-1-y, level, transaction_id);
    if ( tile ) return rotate_180(tile);
    else return tile;
  }
  if ( y==-1 ) {
    ImageView<PixelT> tile =
      fetch_child_tile(num_tiles-1-x, 0, level, transaction_id);
    if( tile ) return rotate_180(tile);
    else return tile;
  }
  if ( y==num_tiles ) {
    ImageView<PixelT> tile =
      fetch_child_tile(num_tiles-1-x, num_tiles-1, level, transaction_id);
    if( tile ) return rotate_180(tile);
    else return tile;
  }

  ImageView<PixelT> tile;
  try {
    this->m_platefile->read(tile, x, y, level, transaction_id, true); // exact_transaction_match == true
  } catch (const TileNotFoundErr& e) { /* No Op */ }

  // Regardless of what happened above, we return the tile here.  If
  // the read failed, the tile will be an empty image.
  return tile;
}

template <class PixelT>
void ToastPlateManager<PixelT>::generate_mipmap_tile(
    ImageView<PixelT>& dest, int col, int row, int level,
    TransactionOrNeg transaction_id, bool preblur) const
{
  // Create an image large enough to store all of the child nodes
  int tile_size = this->m_platefile->default_tile_size();
  ImageView<PixelT> super(4*tile_size-3, 4*tile_size-3);

  bool found = false;

  // Iterate over the children, gathering them and (recursively)
  // regenerating them if necessary.
  for ( int j=-1; j<3; ++j ) {
    for ( int i=-1; i<3; ++i ) {
      ImageView<PixelT> child = fetch_child_tile(2*col+i, 2*row+j, level+1, transaction_id);
      if (child) {
        crop(super,(tile_size-1)*(i+1),(tile_size-1)*(j+1), tile_size,tile_size) = child;
        found = true;
      }
    }
  }

  if (!found) {
    dest.reset();
    return;
  }

  // In the WWT implementation of TOAST the pixel centers
  // (rather than the than pixel corners) are grid-aligned, so
  // we need to use an odd-sized antialiasing kernel instead of
  // the usual 2x2 box filter.  The following 5-pixel kernel was
  // optimized to avoid the extra blurring associated with using
  // a kernel wider than 2 pixels.  Math was involved.
  std::vector<float> kernel(5);
  kernel[0] = kernel[4] = -0.0344f;
  kernel[1] = kernel[3] = 0.2135f;
  kernel[2] = 0.6418f;

  if (preblur)
    dest = subsample(
             crop(
               separable_convolution_filter(super, kernel, kernel, NoEdgeExtension() ),
               tile_size-1, tile_size-1, 2*tile_size, 2*tile_size ), 2);
  else
    dest = subsample( crop( super, tile_size-1, tile_size-1, 2*tile_size, 2*tile_size ), 2 );
}

template <class PixelT>
void ToastPlateManager<PixelT>::mipmap(uint32 /*starting_level*/, BBox2i const& /*region*/, TransactionOrNeg /*read_transaction_id*/, bool /*preblur*/, const ProgressCallback& /*progress_callback*/) const
{
  vw_throw(NoImplErr() << "ToastPlateManager: new mipmap isn't implemented yet");
}

// Explicit template instatiation
namespace vw {
namespace platefile {

#define VW_INSTANTIATE_TOAST_PLATEMANAGER_TYPES(PIXELT)                 \
  template void                                                                \
  ToastPlateManager<PIXELT >::mipmap(uint32 starting_level, BBox2i const& bbox,     \
                                TransactionOrNeg transaction_id,               \
                                bool preblur,                                  \
                                const ProgressCallback &progress_callback) const; \
  template void                                                         \
  ToastPlateManager<PIXELT >::transform_image(                          \
                               cartography::GeoReference const& georef, \
                               ImageViewRef<PIXELT >& image,            \
                               TransformRef& txref, int& level ) const; \
template void                                                           \
ToastPlateManager<PIXELT >::generate_mipmap_tile(                       \
    ImageView<PIXELT>& dest, int col, int row, int level,               \
    TransactionOrNeg transaction_id, bool preblur) const;               \
                                                                        \
  template cartography::GeoReference                                    \
  ToastPlateManager<PIXELT >::georeference( int level ) const;          \
  template ImageView<PIXELT >                                           \
  ToastPlateManager<PIXELT >::fetch_child_tile(                         \
      int col, int row, int level, TransactionOrNeg transaction_id) const; \

  VW_INSTANTIATE_TOAST_PLATEMANAGER_TYPES(PixelGrayA<uint8>)
  VW_INSTANTIATE_TOAST_PLATEMANAGER_TYPES(PixelGrayA<int16>)
  VW_INSTANTIATE_TOAST_PLATEMANAGER_TYPES(PixelGrayA<float32>)
  VW_INSTANTIATE_TOAST_PLATEMANAGER_TYPES(PixelRGBA<uint8>)
}}


text:
execfile("version.py")

import datetime

today = datetime.date.today().strftime("%Y%m%d")

cmd = "git archive --format=tar.gz --prefix=iVisDesigner-%s/ -o dist/iVisDesigner-%s-%s-r%s.tar.gz HEAD" % \
    (IV_version, IV_version, today, IV_rev)
print cmd
commands.getoutput(cmd)


text:
<?php

namespace LeKoala\DebugBar\Test\Messages;

use LeKoala\DebugBar\Messages\LogFormatter;
use SilverStripe\Dev\SapphireTest;

class LogFormatterTest extends SapphireTest
{
    public function testFormat()
    {
        $this->assertSame(
            'I am a log message',
            (new LogFormatter)->format(['foo' => 'bar', 'message_level' => 'blah', 'message' => 'I am a log message'])
        );
    }

    public function testFormatBatch()
    {
        $this->assertSame(
            "foo\nbar\nbaz",
            (new LogFormatter)->formatBatch([
                ['message' => 'foo'],
                ['message' => 'bar'],
                ['message' => 'baz'],
            ])
        );
    }
}


text:
package com.novacloud.data.adblock;

import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Set;

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

public class EasyListRuleSetTest {
	final static RuleSet ruleSet = new EasyListRuleSet(false);
	@BeforeClass
	public static void init(){
		ruleSet.load();
	}
	@Test
	public void filter() {

		boolean match = ruleSet.matchesBlacklist("http://cbjs.baidu.com/a.js");
		assertTrue(match);
	}

	@Test
	public  void testSelector(){

		Set<String> elementSelectors = ruleSet.getAdElementSelectors();
		int i=0;
		for (String elementSelector : elementSelectors) {

			System.err.printf("%d: %s\n",++i,elementSelector);
		}
		assertEquals(15581,elementSelectors.size());
		assertTrue(elementSelectors.contains("#top_ad"));
	}
}


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

<TITLE>
AFAdSDK
</TITLE>

<META NAME="date" CONTENT="2014-06-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      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

com.appsfire.adUnitJAR.sdk

Interface AFAdSDK

All Known Implementing Classes:
DefaultAFAdSDK

public interface AFAdSDK

Nested Class Summary

static class
AFAdSDK.AFAdSDKError

          Error returned by the SDK

static class
AFAdSDK.AFAdSDKModalType

          Defines the type of possible modal ads
 AFAdSDKModalTypeSushi: A native fullscreen ad
 AFAdSDKModalTypeUraMaki: An interstitial ad (like in task manager of iOS7), except it happens within the publisher app

static class
AFAdSDK.AFAdSDKSashimiFormat

          Defines the type of possible sashimi ads

static class
AFAdSDK.AFAdSize

          In-stream ad size returned by a AFAdSizeProvider()

static interface
AFAdSDK.AFAdSizeProvider

          Interface for providing an in-stream ad size

static class
AFAdSDK.AFSDKFeature

          Features that your app uses

  \note By specifying us the list of features you plan using, you'll allow us to optimize the user experience and the web-services calls.

Method Summary

 boolean
areAdsLoaded()

          Poll to ask if the ad payload has been downloaded yet and if ads are available

 boolean
cancelAllPendingAdRequests(AFAdSDK.AFAdSDKModalType modalType)

          Cancel any pending modal ad requests

 java.lang.String
getAPIKey()

          Gets the API key you set for your app

 Context
getContext(java.lang.String contextClassName)

          Get app context registered with registerContext()

 AFAdSDKEventsDelegate
getEventsDelegate()

          Get the instance of the events delegate class that you set for your app

 boolean
isAModalAdOfTypeAvailable(AFAdSDK.AFAdSDKModalType modalType)

          Poll to ask if ads are loaded and if there is at least one modal ad available.

 boolean
isDebugModeEnabled()

          Check if the debug mode is enabled or not, as set by setDebugModeEnabled()

 boolean
isInitialized()

          Ask if the ADUnit SDK is initialized

 boolean
isModalAdDisplayingNow()

          Poll to ask if a modal ad is being displayed right now by the Ad SDK.

 int
numberOfSashimiAdsAvailableForFormat(AFAdSDK.AFAdSDKSashimiFormat format)

          Check the number of Sashimi (in-stream) ads currently ready for display

 void
onStart(Context c)

          Tell the ad SDK that your activity is started

 void
onStop()

          Tell the ad SDK that your activity is stopped

 void
prepare(Context c)

          Tell the library to initialize itself and pre-load data, before loading ads.

 void
registerContext(Context c)

          Register app context so that it can be retrieved with getContext()

 void
releaseSashimiView(AFAdSDKSashimiView view)

          Release sashimi ad assets.

 void
requestModalAd(AFAdSDK.AFAdSDKModalType modalType,
               Context c)

          Display modal ad now or as soon as possible.

 AFAdSDKSashimiView
sashimiViewForFormat(AFAdSDK.AFAdSDKSashimiFormat format,
                     AFAdSDK.AFAdSizeProvider sizeProvider,
                     Context c)

          Get a sashimi ad view ready to be inserted into an Android layout, from a template format

 AFAdSDKSashimiView
sashimiViewForSubclass(java.lang.Class<?> subclass,
                       AFAdSDK.AFAdSizeProvider sizeProvider,
                       Context c)

          Get a sashimi ad view ready to be inserted into an Android layout, from a custom view subclass

 AFAdSDK
setAPIKey(java.lang.String apiKey)

          Sets your app's API key to be used by the ad SDK

 AFAdSDK
setDebugModeEnabled(boolean use)

          Specify if the library should be used in debug mode.

 AFAdSDK
setEventsDelegate(AFAdSDKEventsDelegate delegate)

          Specify a delegate class which will receive events and handle various interactions with the library

 AFAdSDK
setFeatures(java.util.List<AFAdSDK.AFSDKFeature> features)

          Define the features you want to use in Appsfire SDK.

 void
unRegisterContext(Context c)

          Unregister app context registered with registerContext()

Method Detail

isInitialized

boolean isInitialized()

Ask if the ADUnit SDK is initialized

Returns:
true if the library is initialized, false if it isn't yet

setAPIKey

AFAdSDK setAPIKey(java.lang.String apiKey)

Sets your app's API key to be used by the ad SDK

Parameters:
apiKey - API key

getAPIKey

java.lang.String getAPIKey()

Gets the API key you set for your app

Returns:
API key

setDebugModeEnabled

AFAdSDK setDebugModeEnabled(boolean use)

Specify if the library should be used in debug mode. When this mode is enabled, the ad sdk will provide uncapped test
 ads. By default, this mode is disabled and should be disabled when submitting your app to Google Play or other appstores

Parameters:
use - true if the debug mode should be enabled, false if production mode should be enabled

Returns:
this ad sdk instance

isDebugModeEnabled

boolean isDebugModeEnabled()

Check if the debug mode is enabled or not, as set by setDebugModeEnabled()

Returns:
true if debug mode is enabled, false if not

setFeatures

AFAdSDK setFeatures(java.util.List<AFAdSDK.AFSDKFeature> features)

Define the features you want to use in Appsfire SDK. Call before prepare()

 \note Defining this property will allow us to avoid unnecessary library process and web-services calls.
 For example, if you only use the Monetization SDK (AppsfireAdSDK), then you could set `AFSDKFeatureMonetization`.

 \warning Don't use this call if you aren't 100% sure about what you're doing.

Parameters:
features - list of features. You can enable one or more features. By default AFSDKFeatureEngage and AFSDKFeatureMonetization features are enabled.

Returns:
this ad sdk instance

setEventsDelegate

AFAdSDK setEventsDelegate(AFAdSDKEventsDelegate delegate)

Specify a delegate class which will receive events and handle various interactions with the library

Parameters:
delegate - instance of custom class (inherited from AFAdSDKEventsDelegate) that will handle the library events

Returns:
this ad sdk instance

getEventsDelegate

AFAdSDKEventsDelegate getEventsDelegate()

Get the instance of the events delegate class that you set for your app

Returns:
the instance of the event delegate class

prepare

void prepare(Context c)

Tell the library to initialize itself and pre-load data, before loading ads. If not already done, this method is automatically
 called when requesting a modal ad.

Parameters:
c - application context

onStart

void onStart(Context c)

Tell the ad SDK that your activity is started

Parameters:
c - application context

onStop

void onStop()

Tell the ad SDK that your activity is stopped

areAdsLoaded

boolean areAdsLoaded()

Poll to ask if the ad payload has been downloaded yet and if ads are available

Returns:
true if there are ads available in the downloaded payload, false if not

cancelAllPendingAdRequests

boolean cancelAllPendingAdRequests(AFAdSDK.AFAdSDKModalType modalType)

Cancel any pending modal ad requests

Returns:
true if a modal as was canceled (modalAdRequestDidFailWithError will be called in the delegate), false if not
 Cancels any pending ad modal request made in the past.

isModalAdDisplayingNow

boolean isModalAdDisplayingNow()

Poll to ask if a modal ad is being displayed right now by the Ad SDK.

Returns:
true if a modal ad is being displayed, false otherwise

isAModalAdOfTypeAvailable

boolean isAModalAdOfTypeAvailable(AFAdSDK.AFAdSDKModalType modalType)

Poll to ask if ads are loaded and if there is at least one modal ad available. The ad SDK also calls
 AFAdSDKEventsDelegate.onModalAdAvailable() to let the app know that modal ads are now ready for use.

Parameters:
modalType - the type of modal ad to check availability (AFAdSDKModalTypeSushi, AFAdSDKModalTypeUraMaki..)

Returns:
true if ads are loaded and if there is at least one modal ad of the requested type available, false otherwise

requestModalAd

void requestModalAd(AFAdSDK.AFAdSDKModalType modalType,
                    Context c)

Display modal ad now or as soon as possible. A new request will cancel out a previous one if the previous one hasn't
 been handled yet

Parameters:
modalType - the type of modal ad to display (AFAdSDKModalTypeSushi, AFAdSDKModalTypeUraMaki..)
c - application context

numberOfSashimiAdsAvailableForFormat

int numberOfSashimiAdsAvailableForFormat(AFAdSDK.AFAdSDKSashimiFormat format)

Check the number of Sashimi (in-stream) ads currently ready for display

Parameters:
format - sashimi (in-stream) ad format to get the available count of

Returns:
number of ads available

sashimiViewForFormat

AFAdSDKSashimiView sashimiViewForFormat(AFAdSDK.AFAdSDKSashimiFormat format,
                                        AFAdSDK.AFAdSizeProvider sizeProvider,
                                        Context c)

Get a sashimi ad view ready to be inserted into an Android layout, from a template format

Parameters:
format - sashimi (in-stream) ad template format to create a view for
sizeProvider - instance of a AFAdSizeProvider that provides the size in pixels for this ad when created and when the screen size changes
c - application context

Returns:
a view containing an ad which can be inserted and displayed right now, null if no ad of the type is available

sashimiViewForSubclass

AFAdSDKSashimiView sashimiViewForSubclass(java.lang.Class<?> subclass,
                                          AFAdSDK.AFAdSizeProvider sizeProvider,
                                          Context c)

Get a sashimi ad view ready to be inserted into an Android layout, from a custom view subclass

Parameters:
subclass - the custom view subclass, such as MySashimiView.class
sizeProvider - instance of a AFAdSizeProvider that provides the size in pixels for this ad when created and when the screen size changes
c - application context

Returns:
a view containing an ad which can be inserted and displayed right now, null if no ad of the type is available

releaseSashimiView

void releaseSashimiView(AFAdSDKSashimiView view)

Release sashimi ad assets. Call this method after removing the view from your layout

Parameters:
view - sashimi ad view to be cleaned up after removal

registerContext

void registerContext(Context c)

Register app context so that it can be retrieved with getContext()

Parameters:
c - context to register

unRegisterContext

void unRegisterContext(Context c)

Unregister app context registered with registerContext()

Parameters:
c - context to unregister

getContext

Context getContext(java.lang.String contextClassName)

Get app context registered with registerContext()

Parameters:
contextClassName - class name of context to retrieve

Returns:
context, null if not found

      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


text:
package akka.persistence.query.journal.redis

import akka.persistence.PersistentActor
import akka.actor.Props

object TestActor {
  def props(persistenceId: String): Props =
    Props(new TestActor(persistenceId))

  case class DeleteCmd(toSeqNr: Long = Long.MaxValue)
}

class TestActor(override val persistenceId: String) extends PersistentActor {

  import TestActor.DeleteCmd

  val receiveRecover: Receive = {
    case evt: String =>
  }

  val receiveCommand: Receive = {
    case DeleteCmd(toSeqNr) =>

      deleteMessages(toSeqNr)
      sender() ! s"$toSeqNr-deleted"

    case cmd: String =>
      persist(cmd) { evt =>
        sender() ! evt + "-done"
      }
  }

}


text:
using System;
using System.Threading.Tasks;

public class AsyncException : Scenario
{
    public override void Run()
    {
        DoAsyncTest();
    }

    private async void DoAsyncTest()
    {
        throw new Exception("AsyncException");
        await Task.Yield();
    }
}


text:
package com.qycloud.oatos.server.test.logic;

import org.junit.Test;

import com.qycloud.oatos.server.test.BaseTest;

public class SequenceLogicTest extends BaseTest {

	@Test
	public void getNextId() {
		long start = System.currentTimeMillis();
		long count = 10000;
		for (long i = 0; i < count; i++) {
			sequence.getNextId();
		}
		long c = System.currentTimeMillis() - start;
		System.out.println(c);
		System.out.println(1000 * ((float)count) / c);
	}
}


text:
package org.elasticsearch.hadoop.serialization;

import java.io.InputStream;
import java.util.Collections;

import org.elasticsearch.hadoop.serialization.Parser.Token;
import org.elasticsearch.hadoop.serialization.json.JacksonJsonParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class JsonPathTest {

    private Parser parser;
    private Parser nestedJsonParser;

    @Before
    public void before() {
        InputStream in = getClass().getResourceAsStream("parser-test.json");
        parser = new JacksonJsonParser(in);
        nestedJsonParser = new JacksonJsonParser(getClass().getResourceAsStream("nested-fields.json"));
    }

    @After
    public void after() {
        parser.close();
        nestedJsonParser.close();
    }

    @Test
    public void testNoPath() throws Exception {
        assertNull(ParsingUtils.seek(parser, (String) null));
        assertNull(parser.currentToken());
        assertNull(ParsingUtils.seek(parser, ""));
        assertNull(parser.currentToken());
        assertNull(ParsingUtils.seek(parser, " "));
        assertNull(parser.currentToken());
    }

    @Test
    public void testNonExistingToken() throws Exception {
        assertNull(ParsingUtils.seek(parser, "nosuchtoken"));
        assertNull(parser.nextToken());
    }

    @Test
    public void testFieldName() throws Exception {
        assertNotNull(ParsingUtils.seek(parser, "age"));
        assertEquals(Token.VALUE_NUMBER, parser.currentToken());
        assertEquals("age", parser.currentName());
    }

    @Test
    public void testOneLevelNestedField() throws Exception {
        assertNotNull(ParsingUtils.seek(parser, "address.state"));
        assertEquals(Token.VALUE_STRING, parser.currentToken());
        assertEquals("state", parser.currentName());
    }

    @Test
    public void testFieldNestedButNotOnFirstLevel() throws Exception {
        assertNull(ParsingUtils.seek(parser, "state"));
        assertNull(parser.nextToken());
        assertNull(parser.currentToken());
    }

    @Test
    public void testNestedFieldSeek() throws Exception {
        Token seek = ParsingUtils.seek(nestedJsonParser, "nested.field");
        assertNotNull(seek);
    }

    @Test
    public void testNestedFieldValue() throws Exception {
        assertEquals(Collections.singletonList("value"), ParsingUtils.values(nestedJsonParser, "nested.field"));
    }

    @Test
    public void testNestedSecondFieldValue() throws Exception {
        assertEquals(Collections.singletonList(1), ParsingUtils.values(nestedJsonParser, "nested.foo"));
    }

    @Test
    public void testNested2FieldValue() throws Exception {
        assertEquals(Collections.singletonList("halen"), ParsingUtils.values(nestedJsonParser, "nested2.van"));
    }
}


text:
package sjph.life.authentication.user;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import sjph.life.authentication.client.PersonRestTemplateClient;
import sjph.life.model.user.User;
import sjph.life.model.user.UserRole;
import sjph.life.model.user.UserState;

/**
 * @author shaohuiguo
 *
 */
@Service("lifeUserDetailsService")
public class LifeUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(LifeUserDetailsService.class);

    @Autowired(required = true)
    private PersonRestTemplateClient         personRestTemplateClient;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = personRestTemplateClient.findUserByEmail(email);
        if (user != null) {
            logger.info(">>>>>>>>>>>Found User: " + user.toString());
        }
        else {
            logger.error("User not found");
            throw new UsernameNotFoundException("User not found");
        }

        List<GrantedAuthority> result = buildUserAuthority(user.getId());
        AuthenticatedUser authenticatedUser = buildUserForAuthentication(user, result);
        logger.debug(">>>>>>>>>>>Build AuthenticatedUser: " + authenticatedUser.toString());
        return authenticatedUser;
    }

    // private List<GrantedAuthority> buildUserAuthority(Long userId, Set<UserRole> userRoles) {
    private List<GrantedAuthority> buildUserAuthority(Long userId) {
        Set<GrantedAuthority> setAuths = new HashSet<>();

        // Build user's authorities
        // for (UserRole userRole : userRoles) {
        // setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        // }
        setAuths.add(new SimpleGrantedAuthority("ROLE_" + UserRole.Role.USER.toString()));

        // TODO will refine in the future
        if (userId == 1) {
            setAuths.add(new SimpleGrantedAuthority("ROLE_" + UserRole.Role.ADMIN.toString()));
        }
        // End

        List<GrantedAuthority> authorities = new ArrayList<>(setAuths);
        logger.info(">>>>>>>>>>>authorities : {}", authorities);
        return authorities;
    }

    private AuthenticatedUser buildUserForAuthentication(User user,
            List<GrantedAuthority> result) {
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        if (user.getUserState().equals(UserState.INACTIVE)) {
            enabled = false;
        }
        if (user.getUserState().equals(UserState.EXPIRED)) {
            accountNonExpired = false;
        }
        if (user.getUserState().equals(UserState.LOCKED)) {
            accountNonLocked = false;
        }
        if (user.getUserState().equals(UserState.CREDENTIAL_EXPIRED)) {
            credentialsNonExpired = false;
        }
        AuthenticatedUser authenticatedUser = new AuthenticatedUser(user.getEmail(),
                user.getPassword(), enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, result, user);
        return authenticatedUser;
    }
}


text:
import Immutable from 'seamless-immutable';
import {
  SKETCH_SET_ACTIVE_COMPONENT,
} from '../actions/actionTypes';

export default function status(state = Immutable({
  activeComponent: null,
}), action) {
  const { payload } = action;
  switch (action.type) {
    case SKETCH_SET_ACTIVE_COMPONENT:
      return state.merge({
        activeComponent: payload,
      });
    default:
      return state;
  }
}


text:
namespace Watcher.Service.Services.Notifiers
{
    public class UserNotification
    {
        public string Destination { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }
}


text:
'use strict';
var es = require('event-stream'),
	_ = require('lodash'),
	utils = require('gulp-util'),
	processorUtils = require('./lib/utils/processor-utils'),
	Library = require('./lib/utils/library');

var classLibrary,
	idLibrary;

module.exports = {
	run: run,
	minify: run,
	info: info
};

function run(processors, ignores) {
	//initialize ignores
	ignores = _.extend({classes: [], ids: []}, ignores);

	//ensure processor names are set as expected
	processors = processorUtils.extendDefaults(processors);

	//build new libraries to use
	classLibrary = new Library(ignores.classes || []);
	idLibrary = new Library(ignores.ids || []);

	/**
	 * Main task for mini selectors uglify classes. Processes files based on type.
	 *
	 * @param file Stream from es.map
	 * @param callback for es.map
	 */
	function miniSelectors(file, callback) {
		var extensions = file.path.split('.'),
			extension = extensions[extensions.length - 1],
			reducedFile = String(file.contents);

		processorUtils.getForExtension(processors, extension).forEach(function(processor) {
			reducedFile = processor(reducedFile, classLibrary, idLibrary);
		});

		file.contents = new Buffer(reducedFile);
		callback(null, file);
	}

	return es.map(miniSelectors);
}

function info() {
	return es.map(function(file, callback) {
		utils.log(file.history[0]);
		utils.log('Class library:', classLibrary.stats());
		utils.log('ID library:', idLibrary.stats());
		callback(null, file);
	});
}