text:
namespace {

size_t CountSQLItemsOfType(sql::Database* db, const char* type) {
  static const char kTypeSQL[] =
      "SELECT COUNT(*) FROM sqlite_master WHERE type = ?";
  sql::Statement s(db->GetUniqueStatement(kTypeSQL));
  s.BindCString(0, type);
  EXPECT_TRUE(s.Step());
  return s.ColumnInt(0);
}

// Get page size for the database.
bool GetPageSize(sql::Database* db, int* page_size) {
  sql::Statement s(db->GetUniqueStatement("PRAGMA page_size"));
  if (!s.Step())
    return false;
  *page_size = s.ColumnInt(0);
  return true;
}

// Get |name|'s root page number in the database.
bool GetRootPage(sql::Database* db, const char* name, int* page_number) {
  static const char kPageSql[] =
      "SELECT rootpage FROM sqlite_master WHERE name = ?";
  sql::Statement s(db->GetUniqueStatement(kPageSql));
  s.BindString(0, name);
  if (!s.Step())
    return false;
  *page_number = s.ColumnInt(0);
  return true;
}

// Helper for reading a number from the SQLite header.
// See base/big_endian.h.
unsigned ReadBigEndian(unsigned char* buf, size_t bytes) {
  unsigned r = buf[0];
  for (size_t i = 1; i < bytes; i++) {
    r <<= 8;
    r |= buf[i];
  }
  return r;
}

// Helper for writing a number to the SQLite header.
void WriteBigEndian(unsigned val, unsigned char* buf, size_t bytes) {
  for (size_t i = 0; i < bytes; i++) {
    buf[bytes - i - 1] = (val & 0xFF);
    val >>= 8;
  }
}

}  // namespace

namespace sql {
namespace test {

bool CorruptSizeInHeader(const base::FilePath& db_path) {
  // See http://www.sqlite.org/fileformat.html#database_header
  const size_t kHeaderSize = 100;

  unsigned char header[kHeaderSize];

  base::ScopedFILE file(base::OpenFile(db_path, "rb+"));
  if (!file.get())
    return false;

  if (0 != fseek(file.get(), 0, SEEK_SET))
    return false;
  if (1u != fread(header, sizeof(header), 1, file.get()))
    return false;

  int64_t db_size = 0;
  if (!base::GetFileSize(db_path, &db_size))
    return false;

  CorruptSizeInHeaderMemory(header, db_size);

  if (0 != fseek(file.get(), 0, SEEK_SET))
    return false;
  if (1u != fwrite(header, sizeof(header), 1, file.get()))
    return false;

  return true;
}

bool CorruptSizeInHeaderWithLock(const base::FilePath& db_path) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  sql::Database db;
  if (!db.Open(db_path))
    return false;

  // Prevent anyone else from using the database.  The transaction is
  // rolled back when |db| is destroyed.
  if (!db.Execute("BEGIN EXCLUSIVE"))
    return false;

  return CorruptSizeInHeader(db_path);
}

void CorruptSizeInHeaderMemory(unsigned char* header, int64_t db_size) {
  const size_t kPageSizeOffset = 16;
  const size_t kFileChangeCountOffset = 24;
  const size_t kPageCountOffset = 28;
  const size_t kVersionValidForOffset = 92;  // duplicate kFileChangeCountOffset

  const unsigned page_size = ReadBigEndian(header + kPageSizeOffset, 2);

  // One larger than the expected size.
  const unsigned page_count =
      static_cast<unsigned>((db_size + page_size) / page_size);
  WriteBigEndian(page_count, header + kPageCountOffset, 4);

  // Update change count so outstanding readers know the info changed.
  // Both spots must match for the page count to be considered valid.
  unsigned change_count = ReadBigEndian(header + kFileChangeCountOffset, 4);
  WriteBigEndian(change_count + 1, header + kFileChangeCountOffset, 4);
  WriteBigEndian(change_count + 1, header + kVersionValidForOffset, 4);
}

bool CorruptTableOrIndex(const base::FilePath& db_path,
                         const char* tree_name,
                         const char* update_sql) {
  sql::Database db;
  if (!db.Open(db_path))
    return false;

  int page_size = db.page_size();
  if (!GetPageSize(&db, &page_size))
    return false;

  int page_number = 0;
  if (!GetRootPage(&db, tree_name, &page_number))
    return false;

  // SQLite uses 1-based page numbering.
  const long int page_ofs = (page_number - 1) * page_size;
  std::unique_ptr<char[]> page_buf(new char[page_size]);

  // Get the page into page_buf.
  base::ScopedFILE file(base::OpenFile(db_path, "rb+"));
  if (!file.get())
    return false;
  if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    return false;
  if (1u != fread(page_buf.get(), page_size, 1, file.get()))
    return false;

  // Require the page to be a leaf node.  A multilevel tree would be
  // very hard to restore correctly.
  if (page_buf[0] != 0xD && page_buf[0] != 0xA)
    return false;

  // The update has to work, and make changes.
  if (!db.Execute(update_sql))
    return false;
  if (db.GetLastChangeCount() == 0)
    return false;

  // Ensure that the database is fully flushed.
  db.Close();

  // Check that the stored page actually changed.  This catches usage
  // errors where |update_sql| is not related to |tree_name|.
  std::unique_ptr<char[]> check_page_buf(new char[page_size]);
  // The on-disk data should have changed.
  if (0 != fflush(file.get()))
    return false;
  if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    return false;
  if (1u != fread(check_page_buf.get(), page_size, 1, file.get()))
    return false;
  if (!memcmp(check_page_buf.get(), page_buf.get(), page_size))
    return false;

  // Put the original page back.
  if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    return false;
  if (1u != fwrite(page_buf.get(), page_size, 1, file.get()))
    return false;

  return true;
}

size_t CountSQLTables(sql::Database* db) {
  return CountSQLItemsOfType(db, "table");
}

size_t CountSQLIndices(sql::Database* db) {
  return CountSQLItemsOfType(db, "index");
}

size_t CountTableColumns(sql::Database* db, const char* table) {
  // TODO(shess): sql::Database::QuoteForSQL() would make sense.
  std::string quoted_table;
  {
    static const char kQuoteSQL[] = "SELECT quote(?)";
    sql::Statement s(db->GetUniqueStatement(kQuoteSQL));
    s.BindCString(0, table);
    EXPECT_TRUE(s.Step());
    quoted_table = s.ColumnString(0);
  }

  std::string sql = "PRAGMA table_info(" + quoted_table + ")";
  sql::Statement s(db->GetUniqueStatement(sql.c_str()));
  size_t rows = 0;
  while (s.Step()) {
    ++rows;
  }
  EXPECT_TRUE(s.Succeeded());
  return rows;
}

bool CountTableRows(sql::Database* db, const char* table, size_t* count) {
  // TODO(shess): Table should probably be quoted with [] or "".  See
  // http://www.sqlite.org/lang_keywords.html .  Meanwhile, odd names
  // will throw an error.
  std::string sql = "SELECT COUNT(*) FROM ";
  sql += table;
  sql::Statement s(db->GetUniqueStatement(sql.c_str()));
  if (!s.Step())
    return false;

  *count = static_cast<size_t>(s.ColumnInt64(0));
  return true;
}

bool CreateDatabaseFromSQL(const base::FilePath& db_path,
                           const base::FilePath& sql_path) {
  if (base::PathExists(db_path) || !base::PathExists(sql_path))
    return false;

  std::string sql;
  if (!base::ReadFileToString(sql_path, &sql))
    return false;

  sql::Database db;
  if (!db.Open(db_path))
    return false;

  // TODO(shess): Android defaults to auto_vacuum mode.
  // Unfortunately, this makes certain kinds of tests which manipulate
  // the raw database hard/impossible to write.
  // http://crbug.com/307303 is for exploring this test issue.
  ignore_result(db.Execute("PRAGMA auto_vacuum = 0"));

  return db.Execute(sql.c_str());
}

std::string IntegrityCheck(sql::Database* db) {
  sql::Statement statement(db->GetUniqueStatement("PRAGMA integrity_check"));

  // SQLite should always return a row of data.
  EXPECT_TRUE(statement.Step());

  return statement.ColumnString(0);
}

std::string ExecuteWithResult(sql::Database* db, const char* sql) {
  sql::Statement s(db->GetUniqueStatement(sql));
  return s.Step() ? s.ColumnString(0) : std::string();
}

std::string ExecuteWithResults(sql::Database* db,
                               const char* sql,
                               const char* column_sep,
                               const char* row_sep) {
  sql::Statement s(db->GetUniqueStatement(sql));
  std::string ret;
  while (s.Step()) {
    if (!ret.empty())
      ret += row_sep;
    for (int i = 0; i < s.ColumnCount(); ++i) {
      if (i > 0)
        ret += column_sep;
      ret += s.ColumnString(i);
    }
  }
  return ret;
}

int GetPageCount(sql::Database* db) {
  sql::Statement statement(db->GetUniqueStatement("PRAGMA page_count"));
  CHECK(statement.Step());
  return statement.ColumnInt(0);
}

// static
ColumnInfo ColumnInfo::Create(sql::Database* db,
                              const std::string& db_name,
                              const std::string& table_name,
                              const std::string& column_name) {
  sqlite3* const sqlite3_db = db->db(InternalApiToken());

  const char* data_type;
  const char* collation_sequence;
  int not_null;
  int primary_key;
  int auto_increment;
  int status = sqlite3_table_column_metadata(
      sqlite3_db, db_name.c_str(), table_name.c_str(), column_name.c_str(),
      &data_type, &collation_sequence, &not_null, &primary_key,
      &auto_increment);
  CHECK_EQ(status, SQLITE_OK) << "SQLite error: " << sqlite3_errmsg(sqlite3_db);

  // This happens when virtual tables report no type information.
  if (data_type == nullptr)
    data_type = "(nullptr)";

  return {std::string(data_type), std::string(collation_sequence),
          not_null != 0, primary_key != 0, auto_increment != 0};
}

}  // namespace test
}  // namespace sql


text:
package com.google.api.gbase.client;

import com.google.gdata.client.Query;

import java.util.List;
import java.net.URL;

/**
 * Adds support for the "bq" and "max-values" parameters to a gdata query.
 * {@link com.google.gdata.client.Query}.
 */
public class GoogleBaseQuery extends Query {
  private static final String BQ_PARAMETER = "bq";
  private static final String MAX_VALUES_PARAMETER = "max-values";
  private static final String ORDER_BY = "orderby";
  private static final String CROWD_BY = "crowdby";
  private static final String SORT_ORDER = "sortorder";
  private static final String CONTENT = "content";
  private static final String REFINE = "refine";

  /**
   * Creates a Google Base query.
   *
   * @param feedUrl the URL to connect to
   */
  public GoogleBaseQuery(URL feedUrl) {
    super(feedUrl);
  }

  /**
   * Sets the Google Base query to execute.
   *
   * When running queries on Google Base, you have a choice
   * between a Google Base query, which will be interpreted
   * and executed strictly following the Google Base query
   * language, and a Fulltext query (see {@link #setFullTextQuery(String)})
   * which will be interpreted just like a query typed in the
   * search box on the Google Base website - including some
   * user-friendly preprocessing that might be useful or confusing
   * depending on what you're trying to do.
   *
   * You cannot specify both a Google Base query and a Fulltext query.
   *
   * @param query google base query
   * @exception IllegalStateException if a fulltext query
   *   is already set.
   */
  public void setGoogleBaseQuery(String query) {
    overwriteCustomParameter(BQ_PARAMETER, query);
  }

  /**
   * Gets the Google Base query that will be executed.
   *
   * @return the query or null if none was set
   */
  public String getGoogleBaseQuery() {
    String parameterName = BQ_PARAMETER;
    return getCustomParameterValue(parameterName);
  }

  private String getCustomParameterValue(String parameterName) {
    List<CustomParameter> customParams = getCustomParameters(parameterName);
    if (customParams.isEmpty()) {
      return null;
    }
    return customParams.get(0).getValue();
  }

  private void overwriteCustomParameter(String name, String value) {
    List<CustomParameter> customParams = getCustomParameters();

    // Remove any existing value.
    for (CustomParameter existingValue : getCustomParameters(name)) {
      customParams.remove(existingValue);
    }

    // Add the specified value.
    if (value != null) {
      customParams.add(new CustomParameter(name, value));
    }
  }

  /**
   * Sets the max-values parameter used by histogram feeds
   * to limit the number of unique values to return for one attribute.
   *
   * @param maxValues
   */
  public void setMaxValues(Integer maxValues) {
    String stringValue = maxValues == null ? null:maxValues.toString();
    overwriteCustomParameter(MAX_VALUES_PARAMETER, stringValue);
  }

  /**
   * Gets the current value for the max-values parameter.
   *
   * @return current value or null
   */
  public Integer getMaxValues() {
    String valueAsString = getCustomParameterValue(MAX_VALUES_PARAMETER);
    if (valueAsString == null) {
      return null;
    } else {
      return new Integer(valueAsString);
    }
  }

  /**
   * Enables query refinement.
   *
   * By default results are not refined.
   *
   * @param refine true to enable query refinment
   */
  public void setRefine(boolean refine) {
    overwriteCustomParameter(REFINE, refine ? "true" : "false");
  }

  /**
   * Checks whether the query should be refined.
   *
   * @return true if the query should be refined
   */
  public boolean getRefine() {
    return "true".equals(getCustomParameterValue(REFINE));
  }

  /**
   * Selects what to return, on the customer feed.
   *
   * @param content what should be returned (see documentation)
   */
  public void setContent(String content) {
    overwriteCustomParameter(CONTENT, content);
  }

  /**
   * Gets what will be returned, on the customer feed.
   *
   * @return what will be returned
   */
  public String getContent() {
    return getCustomParameterValue(CONTENT);
  }

  /**
   * Sets the criteria used to sort the results.
   *
   * By default results are ordered by relevancy.
   *
   * @param orderBy sorting criteria (see documentation)
   */
  public void setOrderBy(String orderBy) {
    overwriteCustomParameter(ORDER_BY, orderBy);
  }

  /**
   * Sets the criteria used for crowding the results in groups.
   *
   * @param crowdBy crowding criteria (see documentation)
   */
  public void setCrowdingBy(String crowdBy) {
    overwriteCustomParameter(CROWD_BY, crowdBy);
  }

  /**
   * Gets the criteria that will be used to sort the results.
   *
   * @return criteria or null if no order has been set
   */
  public String getOrderBy() {
    return getCustomParameterValue(ORDER_BY);
  }

  /**
   * Gets the criteria that will be used to crowd the results.
   *
   * @return criteria or null if no crowding has been set
   */
  public String getCrowdBy() {
    return getCustomParameterValue(CROWD_BY);
  }

  /**
   * Changes the order in which results are returned (ascending
   * or descending).
   *
   * Descending order (from the largest value
   * to the smallest value) is the default.
   *
   * @param ascending if true, return the result in ascending
   *   order
   */
  public void setAscendingOrder(boolean ascending) {
    overwriteCustomParameter(SORT_ORDER,
        ascending ? "ascending" : "descending");
  }

  /**
   * Checks whether the results will be returned in ascending
   * order.
   *
   * @return if true, the results will be returned in ascending order,
   *   otherwise they will be returned in descending order
   */
  public boolean isAscendingOrder() {
    return "ascending".equals(getCustomParameterValue(SORT_ORDER));
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PhproTest\SoapClient\Unit\CodeGenerator\Assembler;

use Phpro\SoapClient\CodeGenerator\Assembler\AssemblerInterface;
use Phpro\SoapClient\CodeGenerator\Assembler\PropertyAssembler;
use Phpro\SoapClient\CodeGenerator\Context\PropertyContext;
use Phpro\SoapClient\CodeGenerator\Context\TypeContext;
use Phpro\SoapClient\CodeGenerator\Model\Property;
use Phpro\SoapClient\CodeGenerator\Model\Type;
use Zend\Code\Generator\ClassGenerator;

/**
 * Class PropertyAssemblerTest
 *
 * @package PhproTest\SoapClient\Unit\CodeGenerator\Assembler
 */
class PropertyAssemblerTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @test
     */
    function it_is_an_assembler()
    {
        $assembler = new PropertyAssembler();
        $this->assertInstanceOf(AssemblerInterface::class, $assembler);
    }

    /**
     * @test
     */
    function it_can_assemble_property_context()
    {
        $assembler = new PropertyAssembler();
        $context = $this->createContext();
        $this->assertTrue($assembler->canAssemble($context));
    }

    /**
     * @test
     */
    function it_assembles_a_property()
    {
        $assembler = new PropertyAssembler();
        $context = $this->createContext();
        $assembler->assemble($context);

        $code = $context->getClass()->generate();
        $expected = <<<CODE
namespace MyNamespace;

class MyType
{

    /**
     * @var string
     */
    protected \$prop1 = null;

}

CODE;

        $this->assertEquals($expected, $code);
    }

    /**
     * @return TypeContext
     */
    private function createContext()
    {
        $class = new ClassGenerator('MyType', 'MyNamespace');
        $type = new Type('MyNamespace', 'MyType', [
            'prop1' => 'string',
            'prop2' => 'int'
        ]);
        $property = new Property('prop1', 'string');

        return new PropertyContext($class, $type, $property);
    }
}


text:
class SessionsController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_session, only: [:show, :edit, :update, :destroy]

  # GET /sessions
  # GET /sessions.json
  def index
    activity_id = flash[:activity]
    @sessions = Session.find(:all, :conditions => { :activity_id => activity_id })
  end

  # GET /sessions/1
  # GET /sessions/1.json
  def show
  end

  # GET /sessions/new
  def new
    @session = Session.new
    @activity = Activity.find(params[:activity])

    @session.start_date = Time.now
    @session.end_date = Time.now
    @session.activity_id = @activity.id
  end

  # GET /sessions/1/edit
  def edit
  end

  # POST /sessions
  # POST /sessions.json
  def create
    @session = Session.new(session_params)
    @activity = Activity.find(@session.activity_id)

    respond_to do |format|
      if @session.save
        format.html { redirect_to @activity, notice: 'Session was successfully created.' }
        format.json { render action: 'show', status: :created, location: @session }
      else
        format.html { render action: 'new' }
        format.json { render json: @session.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /sessions/1
  # PATCH/PUT /sessions/1.json
  def update
    @activity = Activity.find(@session.activity_id)

    respond_to do |format|
      if @session.update(session_params)
        format.html { redirect_to @activity, notice: 'Session was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @session.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /sessions/1
  # DELETE /sessions/1.json
  def destroy
    @activity = Activity.find(@session.activity_id)
    @session.destroy
    respond_to do |format|
      format.html { redirect_to @activity }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_session
      @session = Session.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def session_params
      params.require(:session).permit(:activity_id, :start_date, :end_date)
    end
end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

exports.default = function (fn) {
    return (0, _baseRest2.default)(function (args /*..., callback*/) {
        var callback = args.pop();
        fn.call(this, args, callback);
    });
};

var _baseRest = require('lodash/_baseRest');

var _baseRest2 = _interopRequireDefault(_baseRest);

function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {default: obj};
}

module.exports = exports['default'];


text:
var fs = require('fs'),
    path = require('path'),
    querystring = require('querystring'),
    mkdirp = require('mkdirp'),
    request = require('request'),
    Q = require('q'),
    _ = require('lodash');

/**
 * Returns a search (GET var) string based on the @jsonObject
 * Handles nested objects using dot notation
 *
 * ex:
 * {
 *    myParam: 'something',
 *    myOtherParam: {
 *      somethingElse: someValue
 *    }
 * }
 *
 * returns:
 * myParam=something&myOtherParam.somethingElse=someValue
 *
 *
 * @param jsonObject
 * @returns {string}
 */
var jsonToSearchParameterString = function(jsonObject) {
  var getParams = [];

  function _jsonToSearchParameterString(_jsonObject, prefix) {
    //loop over all keys in the object
    _.each(_jsonObject, function(value, key) {
      if (_.isObject(value)) {
        //if the value is an object recurse
        _jsonToSearchParameterString(value, key + '.');
      } else {
        //if the value is not an object then add it to the GET params
        getParams.push(prefix + key + '=' + encodeURIComponent(value));
      }
    });
  }

  _jsonToSearchParameterString(jsonObject, '');

  return getParams.join('&');
};

function handleSmartlingResponse(response, deferred) {
  var smartlingResponse = response.response;
  //console.log('smartlingResponse', smartlingResponse);
  if (smartlingResponse && smartlingResponse.code && smartlingResponse.code === 'SUCCESS') {
    deferred.resolve(smartlingResponse.data);
  } else {
    deferred.reject(response);
  }
}

function getStandardSmartlingRequestHandler(deferred) {
  return function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var data = body;
      if (_.isString(data)) {
        try {
          data = JSON.parse(body);
        } catch (err) {};
      }
      handleSmartlingResponse(data, deferred);
    } else {
      var errorObject = {
        message: "An unknown error occurred"
      };

      if (body && body.response) {
        errorObject = body.response;
      } else if (error) {
        errorObject = error;
      }

      deferred.reject(errorObject);
    }
  };
}

/**
 * Initializes Smartling with the given params
 *
 * @param baseUrl
 * @param apiKey
 * @param projectId
 */
var SmartlingSdk = function (apiBaseUrl, apiKey, projectId) {
  this.config = {
    apiBaseUrl: apiBaseUrl,
    apiKey:     apiKey,
    projectId:  projectId
  };
};

/**
 * Smartling API Base URL constants
 */
SmartlingSdk.API_BASE_URLS = {
  LIVE: 'https://api.smartling.com/v1',
  SANDBOX: 'https://sandbox-api.smartling.com/v1'
};

/**
 * Hash of available Smartling operations
 */
SmartlingSdk.OPERATIONS = {
  UPLOAD: '/file/upload',
  GET: '/file/get',
  LIST: '/file/list',
  STATUS: '/file/status',
  RENAME: '/file/rename',
  DELETE: '/file/delete'
};

/**
 * Returns a URL for a Smartling API Operation
 *
 * @param operation         A SmartlingSdk.OPERATIONS value
 * @param smartlingParams   JSON object containing any Smartling parameters
 * @returns {String}
 */
SmartlingSdk.prototype.getSmartlingRequestPath = function(operation, smartlingParams) {
  // The API key and projectId are always required so
  // provide default settings here
  var params = {
    apiKey: this.config.apiKey,
    projectId: this.config.projectId
  };

  _.extend(params, smartlingParams);

  //assemble the request URL
  var requestUrl = this.config.apiBaseUrl + operation;
  requestUrl += '?' + jsonToSearchParameterString(params);

  //console.log('requestUrl', requestUrl);

  return requestUrl;
};

/**
 * Uploads original source content to Smartling (20MB limit for docx and pptx, 10MB limit for all others).
 *
 * https://docs.smartling.com/display/docs/Files+API#FilesAPI-/file/upload(POST)
 *
 * @param file (required)  The file path or file contents to upload.
 * @param fileUri (required)  Value that uniquely identifies the uploaded file. This ID can be used to request the file back.
 *        We recommend you use file path + file name, similar to how version control systems identify the file.
 *        Example: /myproject/i18n/ui.properties.
 * @param fileType (required)
 *        Identifiers: android, ios, gettext, html, javaProperties, yaml, xliff, xml, json, docx, pptx, xlsx, idml
 * @param options (optional)
 * @param options.approved (optional)
 *        This value, either true or false (default), determines whether content in the file is 'approved' (available for translation)
 *        upon submitting the file via the Smartling Dashboard. An error message will return if there are insufficient translation
 *        funds and approved is set to true.
 *        Note: Setting this parameter to true both approves all new content and overrides any locale-specific or global exclusions.
 *        If your workflow includes content exclusions, use this parameter with caution.
 * @param options.smartling.[command] (optional)  Provides custom parser configuration for supported file types. See Supported File Types for more details.
 * @param options.callbackUrl (optional)  A GET request that creates a callback to a URL when a file is 100% published for a locale.
 *        The callback includes these parameters:
 *          fileUri
 *          locale
 *        If you upload another file without a callback URL, it will remove any previous callbackUrl for that file.
 *
 * @return {promise}
 */
SmartlingSdk.prototype.upload = function (filePath, fileUri, fileType, options) {
  //console.log('upload:filePath', filePath);
  //create a defered object to return
  var deferred = Q.defer();

  //setup default request params
  var smartlingParams = {
    fileUri: fileUri,
    fileType: fileType,
    approved: false
  };

  //extend the request params with any options passed in by user
  _.extend(smartlingParams, options);

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.UPLOAD, smartlingParams);

  fs.stat(filePath, function (err, stat) {
    if (err) {
      //failed to get file stats
      deferred.reject(err);
    } else {
      var req = request.post({
        url: requestUrl
      }, getStandardSmartlingRequestHandler(deferred));

      var form = req.form();
      form.append('file', fs.createReadStream(filePath));
    }
  });

  //return the promise
  return deferred.promise;
};

/**
 * Downloads the requested file (@fileUri) from Smartling.
 *
 * https://docs.smartling.com/display/docs/Files+API#FilesAPI-/file/get(GET)
 *
 * @param fileUri (required)  Value that uniquely identifies the downloaded file.
 *
 * @param options
 * @param options.locale (optional)  A locale identifier as specified in project setup. If no locale is specified, original content is returned. You can find the list of locales for your project on the Smartling dashboard at https://dashboard.smartling.com/settings/api.
 * @param options.retrievalType (optional)
 *          Allowed values: pending, published, pseudo
 *
 *          pending indicates that Smartling returns any translations (including non-published translations)
 *          published indicates that Smartling returns only published/pre-published translations
 *          pseudo indicates that Smartling returns a modified version of the original text with certain characters transformed and the text expanded. For example, the uploaded string "This is a sample string", will return as "T~hís ~ís á s~ámpl~é str~íñg". Pseudo translations enable you to test how a longer string integrates into your application.
 *          If you do not specify a value, Smartling assumes published.
 * @param options.IncludeOriginalStrings (optional) Allowed values: true, false  For gettext, xml, or json files only.
 *
 * @return {promise}
 */
SmartlingSdk.prototype.get = function (fileUri, filepath, options) {
  //create a defered object to return
  var defered = Q.defer();

  //setup default request params
  var smartlingParams = {
    fileUri: fileUri
  };

  //extend the request params with any options passed in by user
  _.extend(smartlingParams, options);

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.GET, smartlingParams);

  var requestParams = {
    url: requestUrl,
    json: true
  };

  //Make the request
  if (filepath) {
    mkdirp(path.dirname(filepath), function(err) {
      if (err) {
        console.log(err);
        defered.reject(err);
      } else {
        //create a new writestream for the file
        var fileStream = fs.createWriteStream(filepath);
        //handle any error writing to the stream
        fileStream.on('error', function(err) {
          defered.reject(error);
        });

        //create a request and pipe the response to a file
        var req = request.get(requestParams).pipe(fileStream);
        req.on('close', function(error) {
          if (error) {
            defered.reject(error);
          } else {
            defered.resolve();
          }
        });
      }
    });
  } else {
    request.get(requestParams, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        defered.resolve(body);
      } else {
        defered.reject(body);
      }
    });
  }

  //return the promise
  return defered.promise;
};

/**
 * Lists recently uploaded files. Returns a maximum of 500 files.
 *
 * https://docs.smartling.com/display/docs/Files+API#FilesAPI-/file/list(GET)
 *
 * @param options
 * @param options.locale (optional)  If not specified, the Smartling Files API will return a listing of the original files matching the specified criteria. When the locale is not specified, completedStringCount will be "0".
 * @param options.uriMask (optional)  SQL like syntax (ex '%.strings').
 * @param options.fileTypes (optional)  Identifiers: android, ios, gettext, javaProperties, xliff, yaml. File types are combined using the logical 'OR'.
 * @param options.lastUploadedAfter (optional)
 *  Return all files uploaded after the specified date. See Date Format for more details.
 *  lastUploadedBefore (optional)  Return all files uploaded before the specified date. See  Date Format for more details.
 *  offset (optional)  For result set returns, the offset is a number indicating the distance from the beginning of the list; for example, for a result set of "50" files, you can set the offset at 10 to return files 10 - 50.
 *  limit (optional)  For result set returns, limits the number of files returned; for example, for a result set of 50 files, a limit of "10" would return files 0 - 10.
 *  conditions (optional)  An array of the following conditions: haveAtLeastOneUnapproved, haveAtLeastOneApproved, haveAtLeastOneTranslated, haveAllTranslated, haveAllApproved, haveAllUnapproved. Conditions are combined using the logical 'OR'.
 * @param options.orderBy (optional)
 *  Choices: names of any return parameters; for example, fileUri, stringCount, wordCount, approvedStringCount, completedStringCount, lastUploaded and fileType. You can specify ascending or descending with each parameter by adding "_asc" or "_desc"; for example, "fileUri_desc". If you do not specify ascending or descending, the default is ascending.
 *
 * @returns {promise}
 */
SmartlingSdk.prototype.list = function (options) {
  //create a defered object to return
  var deferred = Q.defer();

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.LIST, options);

  var requestParams = {
    url: requestUrl,
    json: true
  };

  //Make the request
  request.get(requestParams, getStandardSmartlingRequestHandler(deferred));

  //return the promise
  return deferred.promise;
};

/**
 * Gets status of translations for @fileUri in @locale
 *
 * https://docs.smartling.com/display/docs/Files+API#FilesAPI-/file/status(GET)
 *
 * @param fileUri (required)  Value that uniquely identifies the file.
 * @param locale (required)  A locale identifier as specified in project setup.
 *               You can find the list of locales for your project on the Smartling
 *               dashboard at https://dashboard.smartling.com/settings/api.
 *
 * @returns {promise}
 */
SmartlingSdk.prototype.status = function (fileUri, locale) {
  //create a defered object to return
  var deferred = Q.defer();

  //setup default request params
  var smartlingParams = {
    fileUri: fileUri,
    locale: locale
  };

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.STATUS, smartlingParams);

  var requestParams = {
    url: requestUrl,
    json: true
  };

  //Make the request
  request.get(requestParams, getStandardSmartlingRequestHandler(deferred));

  //return the promise
  return deferred.promise;
};

/**
 * Renames an uploaded file @fileUri to @newFileUri. After renaming the file, the file will only be identified by the @newFileUri you provide.
 *
 * https://docs.smartling.com/display/docs/Files+API#FilesAPI-/file/rename(POST)
 *
 * @param fileUri (required)  Value that uniquely identifies the file to rename.
 * @param newFileUri (required) Value that uniquely identifies the new file. We recommend
 *        that you use file path + file name, similar to how version control systems identify
 *        the file. Example: /myproject/i18n/ui.properties.
 *        This must be a fileUri that does not exist in the Smartling database.
 *
 * @returns {promise}
 */
SmartlingSdk.prototype.rename = function (fileUri, newFileUri) {
  //create a defered object to return
  var deferred = Q.defer();

  //setup default request params
  var smartlingParams = {
    fileUri: fileUri,
    newFileUri: newFileUri
  };

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.RENAME, smartlingParams);

  var requestParams = {
    url: requestUrl,
    body: smartlingParams,
    json: true
  };

  //Make the request
  request.post(requestParams, getStandardSmartlingRequestHandler(deferred));

  //return the promise
  return deferred.promise;
};

/**
 * Removes the file from Smartling. The file will no longer be available for download.
 * Any complete translations for the file remain available for use within the system.
 *
 * Note: Smartling deletes files asynchronously and it typically takes a few minutes to complete.
 * While deleting a file, you can not upload a file with the same fileUri.
 *
 * @param fileUri (required)  Value that uniquely identifies the file.
 * @returns {promise}
 */
SmartlingSdk.prototype.delete = function (fileUri) {
  //console.log('_delete:', fileUri);
  //create a defered object to return
  var deferred = Q.defer();

  //setup default request params
  var smartlingParams = {
    fileUri: fileUri
  };

  //assemble the request URL
  var requestUrl = this.getSmartlingRequestPath(SmartlingSdk.OPERATIONS.DELETE, smartlingParams);

  var requestParams = {
    url: requestUrl,
    body: smartlingParams,
    json: true
  };

  //Make the request
  request.del(requestParams, getStandardSmartlingRequestHandler(deferred));

  //return the promise
  return deferred.promise;
};

//Export the SmartlingSdk Class
module.exports = SmartlingSdk;


text:
<?php

namespace OdinsHat\FreeAgentApiV2\FreeagentApi;

class Contacts extends FreeAgentApiV2
{

    public function all()
    {

    }

    public function active()
    {

    }

    public function clients()
    {

    }

    public function suppliers()
    {

    }

    public function getContact()
    {

    }

    public function create()
    {

    }

    public function update()
    {

    }

    public function delete()
    {

    }
}


text:
package ast

import (
	"reflect"
	"testing"

	"github.com/elliotchance/c2go/util"
)

func TestArrayFiller(t *testing.T) {
	expected := &ArrayFiller{
		ChildNodes: []Node{},
	}
	actual := Parse(`array filler`)

	if !reflect.DeepEqual(expected, actual) {
		t.Errorf("%s", util.ShowDiff(formatMultiLine(expected),
			formatMultiLine(actual)))
	}
}


text:
package com.octo.android.robospice.persistence.springandroid.json.jackson;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import android.app.Application;

import com.octo.android.robospice.persistence.exception.CacheCreationException;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.CacheSavingException;
import com.octo.android.robospice.persistence.springandroid.SpringAndroidObjectPersister;

public final class JacksonObjectPersister<T> extends SpringAndroidObjectPersister<T> {

    // ============================================================================================
    // ATTRIBUTES
    // ============================================================================================

    private final ObjectMapper mJsonMapper;

    // ============================================================================================
    // CONSTRUCTOR
    // ============================================================================================

    public JacksonObjectPersister(Application application, Class<T> clazz, File cacheFolder)
        throws CacheCreationException {
        super(application, clazz, cacheFolder);
        this.mJsonMapper = new ObjectMapper();
    }

    public JacksonObjectPersister(Application application, Class<T> clazz) throws CacheCreationException {
        this(application, clazz, null);
    }

    // ============================================================================================
    // METHODS
    // ============================================================================================

    @Override
    protected T deserializeData(String json) throws CacheLoadingException {
        try {
            return mJsonMapper.readValue(json, getHandledClass());
        } catch (Exception e) {
            throw new CacheLoadingException(e);
        }
    }

    @Override
    protected void saveData(T data, Object cacheKey) throws IOException, CacheSavingException {
        String resultJson;
        // transform the content in json to store it in the cache
        resultJson = mJsonMapper.writeValueAsString(data);

        // finally store the json in the cache
        if (!StringUtils.isEmpty(resultJson)) {
            FileUtils.writeStringToFile(getCacheFile(cacheKey), resultJson, CharEncoding.UTF_8);
        } else {
            throw new CacheSavingException("Data was null and could not be serialized in json");
        }
    }

}


text:
package com.zjl.javawork;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;

import javax.swing.JButton;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Swing extends JFrame {

	static Color c = null;

	static JButton jb1 = null;
	static JButton jb2 = null;
	static JButton jb3 = null;

   public void launchFrame(){

		setLayout(new GridLayout(3, 1));
		setBounds(200, 200, 200, 200);

		jb1 = new JButton("°´Å¥1");
		jb2 = new JButton("°´Å¥2");
		jb3 = new JButton("°´Å¥3");

		add(jb1);
		add(jb2);
		add(jb3);

		setVisible(true);
		jb1.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				c = jb1.getBackground();
				jb1.setBackground(Color.green);
			}

			public void mouseExited(MouseEvent e) {
				jb1.setBackground(c);
			}
		});

		jb2.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				c = jb2.getBackground();
				jb2.setBackground(Color.red);
			}

			public void mouseExited(MouseEvent e) {
				jb2.setBackground(c);
			}
		});

		jb3.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				c = jb3.getBackground();
				jb3.setBackground(Color.blue);
			}

			public void mouseExited(MouseEvent e) {
				jb3.setBackground(c);
			}
		});
		this.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {

				System.exit(0);
			}
		});
   }

	public static void main(String[] args) {
				new Swing().launchFrame();

	}

}


text:
module ngX {

    "use strict";

    class AuthorizationInterceptor {

        constructor(private securityStore:any) {

        }

        public static instance = (securityStore: any) => {
            return new AuthorizationInterceptor(securityStore);
        }

        public request = (config) => {
            if (this.securityStore.token) {
                config.headers.Authorization = "Bearer " + this.securityStore.token;
            }

            return config;
        }
    }

    angular.module("ngX")
        .factory("authorizationInterceptor", ["securityStore", AuthorizationInterceptor.instance])
        .config([
            "$httpProvider", ($httpProvider) => {
                $httpProvider.interceptors.push("authorizationInterceptor");
            }
        ]);

}


text:
using System.Collections.Generic;
using Autodesk.DesignScript.Runtime;

namespace DynaShape.Goals
{
    [IsVisibleInDynamoLibrary(false)]
    public class ConstantPressureGoal : Goal
    {
        public float Pressure;

        public ConstantPressureGoal(Triple nodePosition1, Triple nodePosition2, Triple nodePosition3, float pressure, float weight = 1000f)
        {
            Weight = weight;
            Pressure = pressure;
            StartingPositions = new[] { nodePosition1, nodePosition2, nodePosition3 };
            Moves = new Triple[3];
            Weights = new float[3];
        }

        internal override void Compute(List<Node> allNodes)
        {
            Triple n = (allNodes[NodeIndices[1]].Position - allNodes[NodeIndices[0]].Position)
                .Cross(allNodes[NodeIndices[2]].Position - allNodes[NodeIndices[0]].Position);

            Moves[0] = Moves[1] = Moves[2] = n * Pressure * 0.16666666666666666666666f;
            Weights[0] = Weights[1] = Weights[2] = Weight;
        }
    }
}


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0015_auto_20170805_1827'),
    ]

    operations = [
        migrations.AlterField(
            model_name='demographicdata',
            name='child_birthdays',
            field=django.contrib.postgres.fields.ArrayField(base_field=models.DateField(), blank=True, size=None, verbose_name="children's birthdays"),
        ),
    ]


text:
<?php

namespace Emonkak\Waf\Utils;

/**
 * Utilities for reflection.
 */
class ReflectionUtils
{
    /**
     * @codeCoverageIgnore
     */
    private function __construct()
    {
    }

    /**
     * @param \ReflectionFunctionAbstract $func
     * @param integer                     $num
     * @return boolean
     */
    public static function matchesNumberOfArguments(\ReflectionFunctionAbstract $func, $num)
    {
        return $func->getNumberOfRequiredParameters() <= $num
            && $func->getNumberOfParameters() >= $num;
    }
}


text:
Factory.define(:ad_format) do |ad_format|
  ad_format.name "Leaderboard"
  ad_format.width "728px"
  ad_format.height "90px"
end


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8" />

      <link rel="stylesheet" href="css/full_list.css" type="text/css" media="screen" />

      <link rel="stylesheet" href="css/common.css" type="text/css" media="screen" />

    <title>Method List</title>
    <base id="base_target" target="_parent" />

Method List

              Classes

              Methods

              Files

Search: <input type="text" />

      #call
      Inquery::Query::Chainable

      #call
      Inquery::Query

      call
      Inquery::Query

      call
      Inquery::Query::Chainable

      #connection
      Inquery::Query

      #connection
      Inquery::Query::Chainable

      #initialize
      Inquery::Query::Chainable

      #initialize
      Inquery::Query

      #osparams
      Inquery::Query

      #params
      Inquery::Query

      #process
      Inquery::Query

      #relation
      Inquery::Query::Chainable

      #relation
      Inquery::Mixins::RelationValidation::ClassMethods

      #run
      Inquery::Query

      run
      Inquery::Query

      #schema
      Inquery::Mixins::SchemaValidation::ClassMethods

      #schema2
      Inquery::Mixins::SchemaValidation::ClassMethods

      #schema3
      Inquery::Mixins::SchemaValidation::ClassMethods

      #validate_relation!
      Inquery::Mixins::RelationValidation


text:
<!DOCTYPE html>
<title>activate-portal.html</title>
<script>
  window.onportalactivate = e => {
    document.body.appendChild(e.adoptPredecessor());
  };
</script>


text:
from twisted.words.protocols.jabber import jid, client, component
from twisted.application import internet, service
from twisted.internet import interfaces, defer
from twisted.python import usage
from twisted.words.xish import domish, xpath

from zope.interface import Interface, implements

class IStorage(Interface):

    """
    The backend class for multi-user chat
    """

    def createRoom(self, room, user):
        """
        Create a multi-user chat room
        """

    def deleteRoom(self, room, user):
        """
        Delete a multi-user chat room
        """

    def setRoomSubject(self, room, subject):
        """
        """

    def getRoomSubject(self, room, subject):
        """
        """


text:
@interface WDECItinerary : NSObject

@property (strong, nonatomic) WDECSegment *segment;

@end


text:
#include "audio/dsp/testing_util.h"

#include <cmath>
#include <complex>
#include <deque>
#include <initializer_list>
#include <list>

#include "gmock/gmock.h"
#include "absl/types/span.h"

#include "audio/dsp/porting.h"  // auto-added.

namespace audio_dsp {
namespace {

using ::Eigen::ColMajor;
using ::Eigen::Dynamic;
using ::Eigen::RowMajor;
using ::absl::Span;
using ::std::complex;
using ::testing::DoubleEq;
using ::testing::FloatEq;
using ::testing::Matcher;
using ::testing::Not;

TEST(FloatArrayNearTest, TypicalUse) {
  std::vector<double> test_vector({0.998, -1.414, 3.142});
  std::vector<double> reference_vector({1.0, -M_SQRT2, M_PI});
  EXPECT_THAT(test_vector, FloatArrayNear(reference_vector, 1e-2));
  EXPECT_THAT(test_vector, Not(FloatArrayNear(reference_vector, 1e-4)));
}

template <typename ContainerType>
class FloatArrayNearContainerTypeTest : public ::testing::Test {};

typedef ::testing::Types<std::vector<float>, std::deque<float>,
                         std::list<float>, Span<const float>>
    TestContainerTypes;
TYPED_TEST_SUITE(FloatArrayNearContainerTypeTest, TestContainerTypes);

TYPED_TEST(FloatArrayNearContainerTypeTest, MatchesApproximately) {
  typedef TypeParam ContainerType;
  auto test_values = {0.505f, 1.0f, -0.992f, 1.995f};
  ContainerType test_container(test_values);
  auto reference_values = {0.5f, 1.0f, -1.0f, 2.0f};
  ContainerType reference_container(reference_values);

  const Matcher<ContainerType> m1 = FloatArrayNear(reference_container, 1e-2);
  EXPECT_TRUE(m1.Matches(test_container));
  const Matcher<ContainerType> m2 = FloatArrayNear(reference_container, 1e-3);
  EXPECT_FALSE(m2.Matches(test_container));
}

TYPED_TEST(FloatArrayNearContainerTypeTest, DoesNotMatchWrongSize) {
  typedef TypeParam ContainerType;
  EXPECT_THAT(ContainerType({1.0f, 2.0f}),
              Not(FloatArrayNear(ContainerType({1.0f, 2.0f, 3.0f}), 1e-2)));
}

TYPED_TEST(FloatArrayNearContainerTypeTest, DoesNotMatchWrongOrder) {
  typedef TypeParam ContainerType;
  EXPECT_THAT(ContainerType({1.0f, 3.0f, 2.0f}),
              Not(FloatArrayNear(ContainerType({1.0f, 2.0f, 3.0f}), 1e-2)));
}

TYPED_TEST(FloatArrayNearContainerTypeTest, DoesNotMatchNaNs) {
  typedef TypeParam ContainerType;
  auto test_values = {1.0f, MathLimits<float>::kNaN};
  ContainerType test_container(test_values);

  EXPECT_THAT(test_container,
              Not(FloatArrayNear(ContainerType({1.0f, 2.0f}), 1e0)));
  EXPECT_THAT(test_container,
              Not(FloatArrayNear(test_container, 1e0)));
}

TEST(FloatArrayNearTest, WithComplexElements) {
  std::vector<complex<float>> test_vector({{5, 0}, {6, 0}, {6, 1}});
  std::vector<complex<float>> reference_vector({{5, 0}, {5, 0}, {5, 0}});

  const Matcher<std::vector<complex<float>>> m1 =
      FloatArrayNear(reference_vector, 1.5);
  EXPECT_TRUE(m1.Matches(test_vector));
  const Matcher<std::vector<complex<float>>> m2 =
      FloatArrayNear(reference_vector, 1.0);
  EXPECT_FALSE(m2.Matches(test_vector));
}

TEST(FloatArrayNearTest, WithIntegerElements) {
  std::vector<int> test_vector({505, 1000, -992, 1990});
  std::vector<int> reference_vector({500, 1000, -1000, 2000});

  const Matcher<std::vector<int>> m1 = FloatArrayNear(reference_vector, 10);
  EXPECT_TRUE(m1.Matches(test_vector));
  const Matcher<std::vector<int>> m2 = FloatArrayNear(reference_vector, 1);
  EXPECT_FALSE(m2.Matches(test_vector));
}

TEST(FloatArrayEqTest, TypicalUse) {
  std::vector<float> reference_vector({1e6, -M_SQRT2, M_PI});
  // Values are within 4 ULPs.
  std::vector<float> test_vector({1e6 + 0.25, -1.41421323, 3.14159262});
  EXPECT_THAT(test_vector, FloatArrayEq(reference_vector));
  // Create a difference of 5 ULPs in the first element.
  test_vector[0] = 1e6 + 0.3125;
  EXPECT_THAT(test_vector, Not(FloatArrayEq(reference_vector)));
}

template <typename ContainerType>
class FloatArrayEqContainerTypeTest : public ::testing::Test {};

TYPED_TEST_SUITE(FloatArrayEqContainerTypeTest, TestContainerTypes);

TYPED_TEST(FloatArrayEqContainerTypeTest, MatchesApproximately) {
  typedef TypeParam ContainerType;
  auto reference_values = {-1e6f, 0.0f, 1.0f};
  ContainerType reference_container(reference_values);
  const Matcher<ContainerType> m = FloatArrayEq(reference_container);
  EXPECT_TRUE(m.Matches(reference_container));
  EXPECT_TRUE(m.Matches(ContainerType({-1e6 + 0.25, 5e-45, 1.0000002})));
  EXPECT_TRUE(m.Matches(ContainerType({-1e6 - 0.25, -5e-45, 0.9999998})));
  EXPECT_FALSE(m.Matches(ContainerType({-1e6 + 0.3125, 0.0, 1.0})));
  EXPECT_FALSE(m.Matches(ContainerType({-1e6, 1e-44, 1.0})));
  EXPECT_FALSE(m.Matches(ContainerType({-1e6, 0.0, 1.0000006})));
}

TYPED_TEST(FloatArrayEqContainerTypeTest, DoesNotMatchWrongSize) {
  typedef TypeParam ContainerType;
  EXPECT_THAT(ContainerType({1.0f, 2.0f}),
              Not(FloatArrayEq(ContainerType({1.0f, 2.0f, 3.0f}))));
}

TYPED_TEST(FloatArrayEqContainerTypeTest, DoesNotMatchWrongOrder) {
  typedef TypeParam ContainerType;
  EXPECT_THAT(ContainerType({1.0f, 3.0f, 2.0f}),
              Not(FloatArrayEq(ContainerType({1.0f, 2.0f, 3.0f}))));
}

TYPED_TEST(FloatArrayEqContainerTypeTest, DoesNotMatchNaNs) {
  typedef TypeParam ContainerType;
  auto reference_values = {1.0f, MathLimits<float>::kNaN};
  ContainerType reference_container(reference_values);
  const Matcher<ContainerType> m = FloatArrayEq(reference_container);
  EXPECT_FALSE(m.Matches(reference_container));
  EXPECT_FALSE(m.Matches(ContainerType({1.0f, 2.0f})));
}

TYPED_TEST(FloatArrayEqContainerTypeTest, HandlesInfinities) {
  typedef TypeParam ContainerType;
  auto reference_values =
      {1.0f, MathLimits<float>::kPosInf, MathLimits<float>::kNegInf};
  ContainerType reference_container(reference_values);
  const Matcher<ContainerType> m = FloatArrayEq(reference_container);
  EXPECT_TRUE(m.Matches(reference_container));
  EXPECT_FALSE(m.Matches(ContainerType({1.0f, 2.0f, 3.0f})));
}

TEST(FloatArrayEqContainerTypeTest, WithComplexElements) {
  const std::vector<complex<float>> reference_vector(
      {{1e6, -1}, {M_SQRT2, M_PI}});
  const Matcher<std::vector<complex<float>>> m = FloatArrayEq(reference_vector);
  EXPECT_TRUE(m.Matches(reference_vector));
  EXPECT_TRUE(m.Matches(std::vector<complex<float>>(
      {{1e6 + 0.25, -1.0000002}, {1.41421323, 3.14159266}})));
  EXPECT_FALSE(m.Matches(std::vector<complex<float>>(
      {{1e6 + 0.3125, -1}, {M_SQRT2, M_PI}})));
  EXPECT_FALSE(m.Matches(std::vector<complex<float>>(
      {{1e6, -1.0000006}, {M_SQRT2, M_PI}})));
}

static const double kEps = 1e-6;

TEST(EigenArrayNearTest, ArrayXd) {
  const Eigen::ArrayXd expected = Eigen::ArrayXd::Random(4);
  Eigen::ArrayXd actual = expected;
  EXPECT_THAT(actual, EigenArrayNear(expected, kEps));
  EXPECT_THAT(actual, EigenArrayNear(expected, 1e-100));

  actual += 100;
  EXPECT_THAT(actual, Not(EigenArrayNear(expected, kEps)));
  // Wrong shape.
  actual.resize(2);
  EXPECT_THAT(actual, Not(EigenArrayNear(expected, kEps)));
}

TEST(EigenArrayNearTest, ArrayXdInlinedValues) {
  Eigen::ArrayXd actual(3);
  actual << 1.0, 2.0, 3.0;
  EXPECT_THAT(actual, EigenArrayNear<double>({1.0, 2.0, 3.0}, kEps));
  EXPECT_THAT(actual,
              EigenArrayNear<double>({1.0, 2.0 + 0.5 * kEps, 3.0}, kEps));

  EXPECT_THAT(actual, Not(EigenArrayNear<double>({1.0, 2.0, 5.0}, kEps)));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayNear<double>({1.0, 2.0}, kEps)));
}

TEST(EigenArrayNearTest, EmptyArrayX) {
  const Eigen::ArrayXi empty;
  EXPECT_THAT(empty, EigenArrayNear(empty, kEps));
  // Can pass in an Eigen expression type.
  EXPECT_THAT(empty, EigenArrayNear(Eigen::ArrayXi(), kEps));

  EXPECT_THAT(empty, Not(EigenArrayNear<int>({1, 2}, kEps)));
  EXPECT_THAT(empty, Not(EigenArrayNear(Eigen::ArrayXi::Zero(3), kEps)));
}

TEST(EigenArrayNearTest, ArrayXXf) {
  const Eigen::ArrayXXf expected = Eigen::ArrayXXf::Random(4, 5);
  Eigen::ArrayXXf actual = expected;
  EXPECT_THAT(actual, EigenArrayNear(expected, kEps));
  EXPECT_THAT(actual, EigenArrayNear(expected, 1e-100));

  actual.row(2) += 100;
  EXPECT_THAT(actual, Not(EigenArrayNear(expected, kEps)));
  // Wrong shape.
  EXPECT_THAT(expected, Not(EigenArrayNear(expected.transpose(), kEps)));
  actual.resize(4, 3);
  EXPECT_THAT(actual, Not(EigenArrayNear(expected, kEps)));

  // Expression type.
  actual.resize(3, 2);
  actual.col(0) << 1.0, 2.0, 3.0;
  actual.col(1) << 4.0, 5.0, 6.0;
  std::vector<float> expected_vector({1.0, 2.0, 3.0, 4.0, 5.0, 6.0});
  EXPECT_THAT(actual, EigenArrayNear(Eigen::Map<Eigen::ArrayXXf>(
                                         &expected_vector[0], 3 /* rows */,
                                         2 /* columns */),
                                     kEps));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayNear(Eigen::Map<Eigen::ArrayXXf>(
                                             &expected_vector[0], 3 /* rows */,
                                             1 /* columns */),
                                         kEps)));
}

TEST(EigenArrayNearTest, DifferentMajor) {
  Eigen::Array<float, Dynamic, Dynamic, ColMajor> col_major(2, 3);
  col_major << 1.0, 2.0, 3.0,
               4.0, 5.0, 6.0;
  Eigen::Array<float, Dynamic, Dynamic, RowMajor> row_major(2, 3);
  row_major << 1.0, 2.0, 3.0,
               4.0, 5.0, 6.0;
  CHECK_EQ(col_major(1, 0), row_major(1, 0));

  EXPECT_THAT(row_major, EigenArrayNear(col_major, 0.0));
  EXPECT_THAT(row_major, EigenArrayNear<float>({{1.0, 2.0, 3.0},
                                                {4.0, 5.0, 6.0}}, 0.0));
  EXPECT_THAT(col_major, EigenArrayNear(row_major, 0.0));
  EXPECT_THAT(col_major, EigenArrayNear<float>({{1.0, 2.0, 3.0},
                                                {4.0, 5.0, 6.0}}, 0.0));
}

TEST(EigenArrayNearTest, ArrayXXfInlinedValues) {
  Eigen::ArrayXXf actual(2, 3);
  actual.row(0) << 1.0, 2.0, 3.0;
  actual.row(1) << 4.0, -5.0, -6.0;

  EXPECT_THAT(actual, EigenArrayNear<float>({{1.0, 2.0, 3.0},  //
                                             {4.0, -5.0, -6.0}},
                                            kEps));
  EXPECT_THAT(actual, EigenArrayNear<float>(
                          {{1.0, 2.0, 3.0},
                           {4.0, -5.0, static_cast<float>(-6.0 - 0.9 * kEps)}},
                          kEps));
  EXPECT_THAT(actual, Not(EigenArrayNear<float>({{1.0, 2.0, 3.0},  //
                                                 {4.0, -5.0, -8.0}},
                                                kEps)));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayNear<float>({{1.0, 2.0, 3.0}}, kEps)));
}

TEST(EigenArrayEqTest, ArrayXd) {
  const Eigen::ArrayXd expected = Eigen::ArrayXd::Random(4);
  Eigen::ArrayXd actual = expected;
  EXPECT_THAT(actual, EigenArrayEq(expected));

  actual += 100;
  EXPECT_THAT(actual, Not(EigenArrayEq(expected)));
  // Wrong shape.
  actual.resize(2);
  EXPECT_THAT(actual, Not(EigenArrayEq(expected)));
}

TEST(EigenArrayEqTest, ArrayXdInlinedValues) {
  Eigen::ArrayXd actual(3);
  actual << 1.0, 2.0, 3.0;
  EXPECT_THAT(actual, EigenArrayEq<double>({1.0, 2.0, 3.0}));
  EXPECT_THAT(actual, EigenArrayEq<double>({1.0, 2.0 + 5e-7, 3.0}));

  EXPECT_THAT(actual, Not(EigenArrayEq<double>({1.0, 2.0, 5.0})));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayEq<double>({1.0, 2.0})));
}

TEST(EigenArrayEqTest, EmptyArrayX) {
  const Eigen::ArrayXi empty;
  EXPECT_THAT(empty, EigenArrayEq(empty));
  // Can pass in an Eigen expression type.
  EXPECT_THAT(empty, EigenArrayEq(Eigen::ArrayXi()));

  EXPECT_THAT(empty, Not(EigenArrayEq<int>({1, 2})));
  EXPECT_THAT(empty, Not(EigenArrayEq(Eigen::ArrayXi::Zero(3))));
}

TEST(EigenArrayEqTest, ArrayXXf) {
  const Eigen::ArrayXXf expected = Eigen::ArrayXXf::Random(4, 5);
  Eigen::ArrayXXf actual = expected;
  EXPECT_THAT(actual, EigenArrayEq(expected));

  actual.row(2) += 100;
  EXPECT_THAT(actual, Not(EigenArrayEq(expected)));
  // Wrong shape.
  EXPECT_THAT(expected, Not(EigenArrayEq(expected.transpose())));
  actual.resize(4, 3);
  EXPECT_THAT(actual, Not(EigenArrayEq(expected)));

  // Expression type.
  actual.resize(3, 2);
  actual.col(0) << 1.0, 2.0, 3.0;
  actual.col(1) << 4.0, 5.0, 6.0;
  std::vector<float> expected_vector({1.0, 2.0, 3.0, 4.0, 5.0, 6.0});
  EXPECT_THAT(actual, EigenArrayEq(Eigen::Map<Eigen::ArrayXXf>(
                                         &expected_vector[0], 3 /* rows */,
                                         2 /* columns */)));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayEq(Eigen::Map<Eigen::ArrayXXf>(
                                             &expected_vector[0], 3 /* rows */,
                                             1 /* columns */))));
}

TEST(EigenArrayEqTest, ArrayXXfInlinedValues) {
  Eigen::ArrayXXf actual(2, 3);
  actual.row(0) << 1.0, 2.0, 3.0;
  actual.row(1) << 4.0, -5.0, -6.0;

  EXPECT_THAT(actual, EigenArrayEq<float>({{1.0, 2.0, 3.0},
                                           {4.0, -5.0, -6.0}}));
  EXPECT_THAT(actual, EigenArrayEq<float>({{1.0, 2.0, 3.0},
                                           {4.0, -5.0, -6.0 - 1e-6}}));
  EXPECT_THAT(actual, Not(EigenArrayEq<float>({{1.0, 2.0, 3.0},
                                               {4.0, -5.0, -8.0}})));
  // Wrong shape.
  EXPECT_THAT(actual, Not(EigenArrayEq<float>({{1.0, 2.0, 3.0}})));
}

TEST(EigenEach, ArrayX) {
  {  // EigenEach matches empty array.
    EXPECT_THAT(Eigen::ArrayXf(), EigenEach(FloatEq(-1234)));
  }
  {  // With ArrayXf as the LHS type.
    Eigen::ArrayXf actual = Eigen::ArrayXf::Constant(4, 33.3);
    EXPECT_THAT(actual, EigenEach(FloatEq(33.3)));
    actual[2] += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(FloatEq(33.3))));
  }
  {  // With complex-valued ArrayXcf, and using ComplexFloatEq.
    Eigen::ArrayXcf actual = Eigen::ArrayXcf::Constant(4, {-8.1, 1.6});
    EXPECT_THAT(actual, EigenEach(ComplexFloatEq(
        complex<float>(-8.1, 1.6))));
    actual[2] += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(ComplexFloatEq(
        complex<float>(-8.1, 1.6)))));
  }
  {  // With ArrayXd.
    Eigen::ArrayXd actual = Eigen::ArrayXd::Constant(4, 33.3);
    EXPECT_THAT(actual, EigenEach(DoubleEq(33.3)));
    actual[2] += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(DoubleEq(33.3))));
  }
  {  // With ArrayXcd.
    Eigen::ArrayXcd actual = Eigen::ArrayXcd::Constant(4, {-8.1, 1.6});
    EXPECT_THAT(actual, EigenEach(ComplexDoubleEq(
        complex<double>(-8.1, 1.6))));
    actual[2] += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(ComplexDoubleEq(
        complex<double>(-8.1, 1.6)))));
  }
}

TEST(EigenEach, ArrayXX) {
  {
    Eigen::ArrayXXf actual = Eigen::ArrayXXf::Constant(2, 3, 42.0);
    EXPECT_THAT(actual, EigenEach(testing::FloatEq(42.0)));
    actual(1, 2) += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(testing::FloatEq(42.0))));
  }
  {
    Eigen::ArrayXXcf actual = Eigen::ArrayXXcf::Constant(2, 3, {42.0, -5.7});
    EXPECT_THAT(actual, EigenEach(ComplexFloatEq(
        complex<float>(42.0, -5.7))));
    actual(1, 2) += 0.1;
    EXPECT_THAT(actual, Not(EigenEach(ComplexFloatEq(
        complex<float>(42.0, -5.7)))));
  }
}

}  // namespace
}  // namespace audio_dsp


text:
<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode,
    Doctrine\ORM\Query\Lexer;

class Acos extends FunctionNode
{
    public $arithmeticExpression;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'ACOS(' . $sqlWalker->walkSimpleArithmeticExpression(
                $this->arithmeticExpression
        ) . ')';
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->arithmeticExpression = $parser->SimpleArithmeticExpression();

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}


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

namespace Joy.Core.Encoding
{
	public class StatusMachine<Ti, Ts>
	{
		public delegate void CacheFullHandler(Ti[] Cache, Ts[] Status);
		public delegate bool RoleProcessHandler(Ti[] Cache, Ts[] Status);

		protected event CacheFullHandler OnCacheFull;
		protected List<RoleProcessHandler> RoleProcessors = new List<RoleProcessHandler>();
		const int cachesize = 3;
		protected Ti[] Cache = new Ti[3];
		protected Ts[] Status = new Ts[3];
		protected char Regist;
		protected void Read(Ti i)
		{
			ShiftLeft();
			Cache[2] = i;
		}

		protected void ApplyRoles()
		{
			foreach (RoleProcessHandler p in RoleProcessors)
			{
				if (p(Cache, Status))
				{
					break;
				}
			}
		}
		protected void ShiftLeft()
		{
			if (!object.Equals(default(Ti), Cache[0]))
			{
				if (OnCacheFull != null)
				{
					OnCacheFull(Cache, Status);
				}
			}
			for (int i = 0; i < Cache.Length - 1; i++)
			{
				Cache[i] = Cache[i + 1];
				Status[i] = Status[i + 1];
			}
		}
	}
	public class HtmlStatusMachine : StatusMachine<char, StatusCode>
	{
		int limit = 100;
		protected StringBuilder b = new StringBuilder();
		public HtmlStatusMachine()
		{
			OnCacheFull += new CacheFullHandler(HtmlStatusMac_OnCacheFull);
			RoleProcessors.Add(new RoleProcessHandler(delegate(char[] cache, StatusCode[] status)
			{
				if (object.Equals(default(char), cache[1]))
				{
					return false;
				}
				if (cache[1] == '<')
				{
					if (status[0] == StatusCode.EndTag || status[0] == StatusCode.Content || status[0] == StatusCode.Unknown)
					{
						status[1] = StatusCode.BeginTag;
					}
					else
					{
						status[1] = status[0];
					}
				}
				else if (cache[1] == '>')
				{
					if (status[0] == StatusCode.Unknown || status[0] == StatusCode.Content)
					{
						status[1] = StatusCode.Content;
					}
					else if (status[0] == StatusCode.BeginStr || status[0] == StatusCode.Str)
					{
						status[1] = StatusCode.Str;
					}
				}
				else if (cache[1] == '"')
				{
					if (status[0] == StatusCode.Content || (Regist == '\'' && status[0] == StatusCode.Str))
					{
						status[1] = status[0];
					}
					else if (status[0] == StatusCode.BeginStr)
					{
						if (Regist != '"')
						{
							status[1] = StatusCode.Str;
						}
						else
						{
							status[1] = StatusCode.EndStr;
						}
					}
					else if (status[0] == StatusCode.EndStr)
					{
						status[1] = StatusCode.BeginStr;
						Regist = cache[1];
					}
				}
				else if (cache[1] == '\'')
				{
					if (status[0] == StatusCode.Content || (Regist == '"' && status[0] == StatusCode.Str))
					{
						status[1] = status[0];
					}
					else if (status[0] == StatusCode.BeginStr)
					{
						if (Regist != '\'')
						{
							status[1] = StatusCode.Str;
						}
						else
						{
							status[1] = StatusCode.EndStr;
						}
					}
					else if (status[0] == StatusCode.EndStr)
					{
						status[1] = StatusCode.BeginStr;
						Regist = cache[1];
					}
				}
				else
				{
					if (status[0] == StatusCode.EndStr || status[0] == StatusCode.Tag || status[0] == StatusCode.BeginTag)
					{
						status[1] = StatusCode.Tag;
					}
					else if (status[0] == StatusCode.BeginStr || status[0] == StatusCode.Str)
					{
						status[1] = StatusCode.Str;
					}
					else if (status[0] == StatusCode.EndTag || status[0] == StatusCode.Unknown || status[0] == StatusCode.Content)
					{
						status[1] = StatusCode.Content;
					}
				}
				return true;
			}));
		}

		void HtmlStatusMac_OnCacheFull(char[] Cache, StatusCode[] Status)
		{
			char c = Cache[0];
			StatusCode s = Status[0];
			if (s == StatusCode.Content && b.Length < limit)
			{
				b.Append(c);
			}
		}
		public void Parse(string html)
		{
			for (int i = 0; i < html.Length; i++)
			{
				char c = html[i];
				Read(c);
				ApplyRoles();
			}
			Flush();
		}
		public override string ToString()
		{
			return b.ToString();
		}
		protected void Flush()
		{
			for (int i = 1; i <= 3; i++)
			{
				ShiftLeft();
				ApplyRoles();
			}
		}
	}
	public enum StatusCode : int
	{
		Unknown,
		BeginStr,
		Str,
		EndStr,
		BeginTag,
		Tag,
		EndTag,
		Content
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Make Me Elvis - Send Email</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>

<?php
  $from = 'elmer@makemeelvis.com';
  $subject = $_POST['subject'];
  $text = $_POST['elvismail'];

  $dbc = mysqli_connect('data.makemeelvis.com', 'elmer', 'theking', 'elvis_store')
    or die('Error connecting to MySQL server.');

  $query = "SELECT * FROM email_list";
  $result = mysqli_query($dbc, $query)
    or die('Error querying database.');

  while ($row = mysqli_fetch_array($result)){
    $to = $row['email'];
    $first_name = $row['first_name'];
    $last_name = $row['last_name'];
    $msg = "Dear $first_name $last_name,\n$text";
    mail($to, $subject, $msg, 'From:' . $from);
    echo 'Email sent to: ' . $to . '<br />';
  }

  mysqli_close($dbc);
?>

</body>
</html>


text:
import random
import string
import sys
import time
import socket

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor, error
from twisted.internet import task
from twisted.web.http import datetimeToString

from coherence import log, SERVER_ID
from coherence.upnp.core import utils
import coherence.extern.louie as louie

SSDP_PORT = 1900
SSDP_ADDR = '239.255.255.250'

class SSDPServer(DatagramProtocol, log.Loggable):
    """A class implementing a SSDP server.  The notifyReceived and
    searchReceived methods are called when the appropriate type of
    datagram is received by the server."""
    logCategory = 'ssdp'

    def __init__(self, test=False, interface=''):
        # Create SSDP server
        log.Loggable.__init__(self)
        self._known = {}
        self._callbacks = {}
        self.__test = test
        self.active_calls = []
        self._resend_notify_loop = None
        self._expire_loop = None
        self._port = None
        if not self.__test:
            try:
                self._port = reactor.listenMulticast(SSDP_PORT, self,
                                                    listenMultiple=True)
                #self.port.setLoopbackMode(1)
                self._port.joinGroup(SSDP_ADDR, interface=interface)
            except error.CannotListenError, err:
                self.error("Error starting the SSDP-server: %s", err)
                self.error("There seems to already be a SSDP server "
                           "running on this host, no need starting a "
                           "second one.")

            self._resend_notify_loop = task.LoopingCall(self._resendNotify)
            # notify every 777 seconds (~ 13 Minutes)
            self._resend_notify_loop.start(777.0, now=False)

            self._expire_loop = task.LoopingCall(self._expire)
            # expire every 333 seconds (~ 5.5 Minutes)
            self._expire_loop.start(333.0, now=False)

    def stopNotifying(self):
        if self._resend_notify_loop and self._resend_notify_loop.running:
            self._resend_notify_loop.stop()
        if self._port:
            self._port.stopListening()

    def shutdown(self):
        for call in reactor.getDelayedCalls():
            if call.func == self.__send__discovery_request:
                call.cancel()
        if not self.__test:
            self.stopNotifying()
            if self._expire_loop.running:
                self._expire_loop.stop()
            # Make sure we send out the byebye notifications.
            for st in self._known:
                if self._known[st]['MANIFESTATION'] == 'local':
                    self.doByebye(st)

    def datagramReceived(self, data, (host, port)):
        """Handle a received multicast datagram."""
        cmd, headers, content = utils.parse_http_response(data)
        cmd = cmd[:2] # we are interested in only the first two elements
        del content # we do not need the content
        self.info('SSDP command %s %s - from %s:%d', cmd[0], cmd[1], host, port)
        self.debug('with headers: %s', headers)
        if cmd == ['M-SEARCH', '*']:
            # SSDP discovery
            self._discoveryRequest(headers, (host, port))
        elif cmd == ['NOTIFY', '*']:
            # SSDP presence
            self._notifyReceived(headers, (host, port))
        else:
            self.warning('Unknown SSDP command %s %s', *cmd)

        # make raw data available
        # send out the signal after we had a chance to register the device
        louie.send('UPnP.SSDP.datagram_received', None, data, host, port)

    def register(self, manifestation, usn, st, location,
                        server=SERVER_ID,
                        cache_control='max-age=1800',
                        silent=False,
                        host=None):
        """Register a service or device that this SSDP server will
        respond to."""

        self.info('Registering %s (%s)', st, location)

        self._known[usn] = {
            'USN': usn, # Unique Service Name
            'LOCATION': location,
            'ST': st, # Service Type
            'EXT': '',
            'SERVER': server,
            'CACHE-CONTROL': cache_control,
            'MANIFESTATION': manifestation,
            'SILENT': silent,
            'HOST': host,
            'last-seen': time.time(),
            }
        self.debug('%r', self._known[usn])

        if manifestation == 'local':
            self.doNotify(usn)

        if st == 'upnp:rootdevice':
            louie.send('Coherence.UPnP.SSDP.new_device', None,
                       device_type=st, infos=self._known[usn])
            #self.callback("new_device", st, self._known[usn])

    def unRegister(self, usn):
        if not self._isKnown(usn):
            return
        self.info("Un-registering %s", usn)
        st = self._known[usn]['ST']
        if st == 'upnp:rootdevice':
            louie.send('Coherence.UPnP.SSDP.removed_device', None,
                       device_type=st, infos=self._known[usn])
            #self.callback("removed_device", st, self._known[usn])
        del self._known[usn]

    def isKnown(self, usn):
        return self._known.has_key(usn)

    def service_seen(self, host, service_type, headers):
        """
        Mark a service as been seen. If the service is not yet known,
        automatically register it.

        Returns True, if the service was unknown.
        """
        try:
            self._known[headers['usn']]['last-seen'] = time.time()
        except KeyError:
            self.register('remote', headers['usn'], service_type,
                          headers['location'], headers['server'],
                          headers['cache-control'], host=host)
            return True
        else:
            self.debug('updating last-seen for %r', headers['usn'])
            return False

    def _notifyReceived(self, headers, (host, port)):
        """Process a presence announcement.  We just remember the
        details of the SSDP service announced."""

        self.info('Notification from (%s,%d) for %s', host, port, headers['nt'])
        self.debug('Notification headers: %s', headers)

        if headers['nts'] == 'ssdp:alive':
            self.service_seen(host, headers['nt'], headers)
        elif headers['nts'] == 'ssdp:byebye':
            self.unRegister(headers['usn'])
        else:
            self.warning('Unknown subtype %s for notification type %s',
                         headers['nts'], headers['nt'])
        louie.send('Coherence.UPnP.Log', None, 'SSDP', host,
                   'Notify %s for %s' % (headers['nts'], headers['usn']))

    def __send__discovery_request(self, response, destination, delay, usn):
        self.info('send discovery response delayed by %ds for %s to %r',
                  delay, usn, destination)
        try:
            self.transport.write(response, destination)
        except (AttributeError, socket.error), msg:
            self.info("failure sending out byebye notification: %r", msg)

    def _discoveryRequest(self, headers, (host, port)):
        """Process a discovery request.  The response must be sent to
        the address specified by (host, port)."""

        self.info('Discovery request from (%s,%d) for %s',
                  host, port, headers['st'])
        louie.send('Coherence.UPnP.Log', None, 'SSDP', host,
                   'M-Search for %s' % headers['st'])
        # Do we know about this service?
        for known in self._known.values():
            if known['MANIFESTATION'] == 'remote':
                continue
            elif known['SILENT'] and headers['st'] == 'ssdp:all':
                continue
            elif (headers['st'] == known['ST'] or
                  headers['st'] == 'ssdp:all'):
                response = []
                response.append('HTTP/1.1 200 OK')
                for k, v in known.iteritems():
                    if k not in ('MANIFESTATION', 'SILENT', 'HOST'):
                        response.append('%s: %s' % (k, v))
                response.append('DATE: %s' % datetimeToString())
                response.extend(('', ''))
                response = '\r\n'.join(response)

                delay = random.randint(0, int(headers['mx']))
                reactor.callLater(delay, self.__send__discovery_request,
                                  response, (host, port), delay, known['USN'])

    def __build_response(self, cmd, usn):
        resp = ['NOTIFY * HTTP/1.1',
            'HOST: %s:%d' % (SSDP_ADDR, SSDP_PORT),
            'NTS: %s' % cmd,
            ]
        stcpy = self._known[usn].copy()
        stcpy['NT'] = stcpy['ST']
        for k in ('ST', 'MANIFESTATION', 'SILENT', 'HOST', 'last-seen'):
            try:
                # :fixme: this keys should always exist as we build the entry
                del stcpy[k]
            except:
                pass
        resp.extend(': '.join(x) for x in stcpy.iteritems())
        resp.extend(('', ''))
        return '\r\n'.join(resp)

    def doNotify(self, usn):
        """Do notification"""
        if self._known[usn]['SILENT']:
            return
        self.info('Sending alive notification for %s', usn)
        resp = self.__build_response('ssdp:alive', usn)
        self.debug('doNotify content %s', resp)
        try:
            # :fixme: why is this sent twice?
            self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
            self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
        except (AttributeError, socket.error), msg:
            self.info("failure sending out alive notification: %r", msg)

    def doByebye(self, usn):
        """Do byebye"""
        # :todo: unite with doNotify(). Why are there differences at all?
        self.info('Sending byebye notification for %s', usn)
        resp = self.__build_response('ssdp:byebye', usn)
        self.debug('doByebye content %s', resp)
        if self.transport:
            try:
                self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
            except (AttributeError, socket.error), msg:
                self.info("failure sending out byebye notification: %r",
                          msg)

    def _resendNotify(self):
        for usn, entry in self._known.iteritems():
            if entry['MANIFESTATION'] == 'local':
                self.doNotify(usn)

    def _expire(self):
        """ check if the discovered devices are still ok, or
            if we haven't received a new discovery response
        """
        self.debug("Checking devices/services are still valid")
        removable = []
        for usn, entry in self._known.iteritems():
            if entry['MANIFESTATION'] == 'local':
                continue
            expiry = int(entry['CACHE-CONTROL'].split('=')[1])
            now = time.time()
            last_seen = entry['last-seen']
            self.debug("Checking if %r is still valid - "
                       "last seen %d (+%d), now %d",
                       entry['USN'], last_seen, expiry, now)
            if last_seen + expiry + 30 < now:
                self.debug("Expiring: %r", entry)
                if entry['ST'] == 'upnp:rootdevice':
                    louie.send('Coherence.UPnP.SSDP.removed_device', None,
                               device_type=entry['ST'], infos=entry)
                removable.append(usn)
        for usn in removable:
            del self._known[usn]

    def subscribe(self, name, callback):
        self._callbacks.setdefault(name, []).append(callback)

    def unsubscribe(self, name, callback):
        callbacks = self._callbacks.get(name, [])
        if callback in callbacks:
            callbacks.remove(callback)
        self._callbacks[name] = callbacks

    def callback(self, name, *args):
        for callback in self._callbacks.get(name, []):
            callback(*args)


text:
The query result is always tabular. Even though ADO.NET allows to execute many SQL commands at once, their in-memory representation form much more complex, hierarchical structures.

Fortunately, queries are functions and as such, they can be composed with other functions using `>>` and `|>` operators.
Thus, result transformations are functions too:
* one group is explicit but rather verbose
* another group, based on conventions, uses reflection and code generation to access key fields, etc...

Most transformations fall into four categories.

## Join two or more tabular results by some key

Function, returning two results, must return tuple:
```fsharp
let getPostsWithTags: int -> AsyncDb<Post list * Tag list> =
    sql "select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id;

         select t.postId, t.name
         from tag t join post p on t.postId = p.id
         where p.blogId = @id"
```
The result can be transformed with the `join` function:

```fsharp
let getPostsWithTags: int -> AsyncDb<Post list> =
    sql "select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id;

         select t.postId, t.name
         from tag t join post p on t.postId = p.id
         where p.blogId = @id"
    >> AsyncDb.map (join (fun p -> p.id)
                         (fun t -> t.postId)
                         (fun p t -> { p with tags = t }))
```
Note, that we can not simply compose two functions, since the result is wrapped in the AsyncDb type.
For this reason, the transformation is passed to `AsyncDb.map` function.

## Join by convention

When following some simple naming conventions, i.e.
* the join key has `Id`, `<Parent>Id` or '<Parent>_id` name in parent record (case insensitive),
* the join key has `<Parent>Id` or `<Parent>_id` in child record (case insensitive),
* exactly one proprty of `<Child>` list type exists in parent record,

the more concise join version can be used:
```fsharp
let getPostsWithTags: int -> Post list AsyncDb =
    sql "select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id;

         select t.postId, t.name
         from tag t join post p on t.postId = p.id
         where p.blogId = @id"
    >> AsyncDb.map join<_, Tag>
```

## Group rows of one denormalized result by some columns

The result, that is a product, can be represented as a list of tuples:

```fsharp
let getPostsWithTags: int -> (Post * Tag) list AsyncDb =
    sql "select p.id, p.blogId, p.name, p.title, p.content, p.author,
                p.createdAt, p.modifiedAt, p.modifiedBy, p.status,
                t.postId as item_postId, t.name as item_name
         from post p left join tag t on t.postId = p.id
         where p.id = @id"
```
It can be transformed using grouping by first item of a tuple:
```fsharp
let getPostsWithTags: int -> Post list AsyncDb =
    sql "select p.id, p.blogId, p.name, p.title, p.content, p.author,
                p.createdAt, p.modifiedAt, p.modifiedBy, p.status,
                t.postId as item_postId, t.name as item_name
         from post p left join tag t on t.postId = p.id
         where p.id = @id"
    >> AsyncDb.map (group (fun p t -> { p with tags = aliasedAsItem t }))
```
In the example above, there are two 'name' columns. To make it possible to use aliasing, we use `aliasedAsItem` function, that allows to use item_{column name} aliases for detail data. There are also `group3` and `group4` functions.

## Group by convention

There is, of course, convention-based approach, that works when no tranformation of child list is needed and only one child list collection appears in a parent record:
```fsharp
let getPostsWithTags: int -> Post list AsyncDb =
    sql "select p.id, p.blogId, p.name, p.title, p.content, p.author,
                p.createdAt, p.modifiedAt, p.modifiedBy, p.status,
                t.postId, t.name as tagName
         from post p left join tag t on t.postId = p.id
         where p.id = @id"
    >> AsyncDb.map group<_, Tag>
```
## Consolidate many results to one root object

When reading one object and some detail data, no joining or grouping is needed. In this case, we can use ordinary function:
```fsharp
let getBlogWithPosts: int -> Blog AsyncDb =
    sql "select id, name, title, description, owner,
                createdAt, modifiedAt, modifiedBy
         from Blog
         where id = @id;

         select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id"
    >> AsyncDb.map (fun b p -> { b with posts = p })
```
## Consolidate by convention

As with join, when exactly one property of `<Child> list` exists, more concise way can be used:
```fsharp
let getBlogWithPosts: int -> Blog AsyncDb =
    sql "select id, name, title, description, owner,
                createdAt, modifiedAt, modifiedBy
         from Blog
         where id = @id;

         select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id"
    >> AsyncDb.map combine<_, Post>
```
## Combining many transformations

Sometimes more, than two results should be joined. In this case we can use a mechanism, that combine joins:
```fsharp
let getPostsWithTagsAndComments: int -> Post list AsyncDb =
    sql "select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id;

         select t.postId, t.name
         from tag t join post p on t.postId = p.id
         where p.blogId = @id;

         select c.id, c.postId, c.parentId, c.content, c.author, c.createdAt
         from comment c join post p on c.postId = p.id
         where p.blogId = @id"
    >> AsyncDb.map (join<_, Tag> >-> join<_, Comment>)
```
The `>->` operator combines two functions by passing result of the first one as a first argument of the second one:
```fsharp
let (>->) f g = fun (t1, t2) -> g(f t1, t2)
```
It allows to build a chain of functions, that subsequently transform result of the same type.

There is also another operator: `>>-`, that passes result of the second function as a second argument of the first function:
```fsharp
let (>>-) f g = fun (t1, t2) -> f(t1, g(t2))
```
It allows to define deep hierarchies.
In the example below the `>>-` operator is used to build nested hierarchy of posts with tags and comments, then add them to a blog:
```fsharp
let getBlogWithPostsWithTagsAndComments: int -> Blog AsyncDb =
    sql "select id, name, title, description, owner,
                createdAt, modifiedAt, modifiedBy
         from Blog
         where id = @id

         select id, blogId, name, title, content, author,
                createdAt, modifiedAt, modifiedBy, status
         from post
         where blogId = @id;

         select t.postId, t.name
         from tag t join post p on t.postId = p.id
         where p.blogId = @id;

         select c.id, c.postId, c.parentId, c.content, c.author, c.createdAt
         from comment c join post p on c.postId = p.id
         where p.blogId = @id"
    >> AsyncDb.map (combine<_, Post> >>- (join<_, Tag> >-> join<_, Comment>))
```
It's also possible to mix joins, groups and updates in one result transformation.

## Transforming stored procedure result tuples

There are two functions transforming tuples, returned from stored procedures:
```fsharp
resultOnly (_: int, (), result: 't)
```
that ignores return code and output parameters, and returns query results with possible mapping function, and:
```fsharp
outParamsOnly (_: int, outParams, ())
```
that ignores return code and results, and returns output parameters.
They can be called the same way, as other transformations:

```fsharp
let findPosts: (PostCriteria * SignatureCriteria) -> Post list AsyncDb =
    proc "FindPosts"
    >> AsyncDb.map resultOnly
```


text:
using Sofia.Domain.Categorias.Entities;
using Sofia.Infrastructure.Categorias.Mappings;
using System.Data.Entity;

namespace Sofia.Infrastructure.Categorias
{
    public class CategoriasContext : DbContextBase<CategoriasContext>
    {

        public DbSet<Categoria> Categorias { get; set; }
        public DbSet<Tecnologia> Tecnologias { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CategoriaMap());
            modelBuilder.Configurations.Add(new TecnologiaMap());
        }
    }
}


text:
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * Construct objects from configuration instructions.
 *
 * @author Bryan Davis <bd808@wikimedia.org>
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
 */
class ObjectFactory {

	/**
	 * Instantiate an object based on a specification array.
	 *
	 * The specification array must contain a 'class' key with string value
	 * that specifies the class name to instantiate or a 'factory' key with
	 * a callable (is_callable() === true). It can optionally contain
	 * an 'args' key that provides arguments to pass to the
	 * constructor/callable.
	 *
	 * Values in the arguments collection which are Closure instances will be
	 * expanded by invoking them with no arguments before passing the
	 * resulting value on to the constructor/callable. This can be used to
	 * pass IDatabase instances or other live objects to the
	 * constructor/callable. This behavior can be suppressed by adding
	 * closure_expansion => false to the specification.
	 *
	 * The specification may also contain a 'calls' key that describes method
	 * calls to make on the newly created object before returning it. This
	 * pattern is often known as "setter injection". The value of this key is
	 * expected to be an associative array with method names as keys and
	 * argument lists as values. The argument list will be expanded (or not)
	 * in the same way as the 'args' key for the main object.
	 *
	 * @param array $spec Object specification
	 * @return object
	 * @throws InvalidArgumentException when object specification does not
	 * contain 'class' or 'factory' keys
	 * @throws ReflectionException when 'args' are supplied and 'class'
	 * constructor is non-public or non-existent
	 */
	public static function getObjectFromSpec( $spec ) {
		$args = isset( $spec['args'] ) ? $spec['args'] : [];
		$expandArgs = !isset( $spec['closure_expansion'] ) ||
			$spec['closure_expansion'] === true;

		if ( $expandArgs ) {
			$args = static::expandClosures( $args );
		}

		if ( isset( $spec['class'] ) ) {
			$clazz = $spec['class'];
			if ( !$args ) {
				$obj = new $clazz();
			} else {
				$obj = static::constructClassInstance( $clazz, $args );
			}
		} elseif ( isset( $spec['factory'] ) ) {
			$obj = call_user_func_array( $spec['factory'], $args );
		} else {
			throw new InvalidArgumentException(
				'Provided specification lacks both factory and class parameters.'
			);
		}

		if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) {
			// Call additional methods on the newly created object
			foreach ( $spec['calls'] as $method => $margs ) {
				if ( $expandArgs ) {
					$margs = static::expandClosures( $margs );
				}
				call_user_func_array( [ $obj, $method ], $margs );
			}
		}

		return $obj;
	}

	/**
	 * Iterate a list and call any closures it contains.
	 *
	 * @param array $list List of things
	 * @return array List with any Closures replaced with their output
	 */
	protected static function expandClosures( $list ) {
		return array_map( function ( $value ) {
			if ( is_object( $value ) && $value instanceof Closure ) {
				// If $value is a Closure, call it.
				return $value();
			} else {
				return $value;
			}
		}, $list );
	}

	/**
	 * Construct an instance of the given class using the given arguments.
	 *
	 * PHP's `call_user_func_array()` doesn't work with object construction so
	 * we have to use other measures. Starting with PHP 5.6.0 we could use the
	 * "splat" operator (`...`) to unpack the array into an argument list.
	 * Sadly there is no way to conditionally include a syntax construct like
	 * a new operator in a way that allows older versions of PHP to still
	 * parse the file. Instead, we will try a loop unrolling technique that
	 * works for 0-10 arguments. If we are passed 11 or more arguments we will
	 * take the performance penalty of using
	 * `ReflectionClass::newInstanceArgs()` to construct the desired object.
	 *
	 * @param string $clazz Class name
	 * @param array $args Constructor arguments
	 * @return mixed Constructed instance
	 */
	public static function constructClassInstance( $clazz, $args ) {
		// $args should be a non-associative array; show nice error if that's not the case
		if ( $args && array_keys( $args ) !== range( 0, count( $args ) - 1 ) ) {
			throw new InvalidArgumentException( __METHOD__ . ': $args cannot be an associative array' );
		}

		// TODO: when PHP min version supported is >=5.6.0 replace this
		// with `return new $clazz( ... $args );`.
		$obj = null;
		switch ( count( $args ) ) {
			case 0:
				$obj = new $clazz();
				break;
			case 1:
				$obj = new $clazz( $args[0] );
				break;
			case 2:
				$obj = new $clazz( $args[0], $args[1] );
				break;
			case 3:
				$obj = new $clazz( $args[0], $args[1], $args[2] );
				break;
			case 4:
				$obj = new $clazz( $args[0], $args[1], $args[2], $args[3] );
				break;
			case 5:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4]
				);
				break;
			case 6:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4],
					$args[5]
				);
				break;
			case 7:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4],
					$args[5], $args[6]
				);
				break;
			case 8:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4],
					$args[5], $args[6], $args[7]
				);
				break;
			case 9:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4],
					$args[5], $args[6], $args[7], $args[8]
				);
				break;
			case 10:
				$obj = new $clazz(
					$args[0], $args[1], $args[2], $args[3], $args[4],
					$args[5], $args[6], $args[7], $args[8], $args[9]
				);
				break;
			default:
				// Fall back to using ReflectionClass and curse the developer
				// who decided that 11+ args was a reasonable method
				// signature.
				$ref = new ReflectionClass( $clazz );
				$obj = $ref->newInstanceArgs( $args );
		}
		return $obj;
	}
}


text:
package cn.gyyx.supervisor.model;

public class Page {
    private String draw;
    private String order_column;
    private String order_dir;
    private Integer start;
    private Integer length;
    private String username;
    private String  email;
	public Page(String draw, String order_column, String order_dir, Integer start, Integer length, String username,
			String email) {
		super();
		this.draw = draw;
		this.order_column = order_column;
		this.order_dir = order_dir;
		this.start = start;
		this.length = length;
		this.username = username;
		this.email = email;
	}
	public Page() {
		super();
	}
	public String getDraw() {
		return draw;
	}
	public void setDraw(String draw) {
		this.draw = draw;
	}
	public String getOrder_column() {
		return order_column;
	}
	public void setOrder_column(String order_column) {
		this.order_column = order_column;
	}
	public String getOrder_dir() {
		return order_dir;
	}
	public void setOrder_dir(String order_dir) {
		this.order_dir = order_dir;
	}
	public Integer getStart() {
		return start;
	}
	public void setStart(Integer start) {
		this.start = start;
	}
	public Integer getLength() {
		return length;
	}
	public void setLength(Integer length) {
		this.length = length;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}

}


text:
package io.fabric8.openshift.client.creators;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.ResourceCreator;
import io.fabric8.openshift.api.model.Template;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.openshift.client.dsl.internal.TemplateOperationsImpl;

public class TemplateCreator implements ResourceCreator<Template> {
  @Override
  public Class<Template> getKind() {
    return Template.class;
  }

  @Override
  public Template create(KubernetesClient client, String namespace, Template item) {
    try (OpenShiftClient osClient = client.adapt(OpenShiftClient.class)) {
      return new TemplateOperationsImpl(osClient, namespace, null, true, item).create();
    }
  }
}


text:
package kata.domain;
import java.sql.Timestamp;

public class Task extends TaskAbstract
{
	public Task(Timestamp processingDate
	)
	{
		super(processingDate
		);
		// You must not modify this constructor. Mithra calls this internally.
		// You can call this constructor. You can also add new constructors.
	}

	public Task()
	{
		this(kata.util.TimestampProvider.getInfinityDate());
	}
}


text:
define(function (require) {
  return require('ui/registry/_registry')({
    name: 'savedObjects',
    index: ['loaderProperties.name'],
    order: ['loaderProperties.name']
  });
});


text:
namespace IECoreMaya
{

/// A ParameterHandler which deals with a variety of Imath::Box types
template<typename T>
class IECOREMAYA_API BoxParameterHandler : public ParameterHandler
{
	protected:
		virtual MPlug doCreate( IECore::ConstParameterPtr parameter, const MString &plugName, MObject &node ) const;
		virtual MStatus doUpdate( IECore::ConstParameterPtr parameter, MPlug &plug ) const;
		virtual MStatus doSetValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const;
		virtual MStatus doSetValue( const MPlug &plug, IECore::ParameterPtr parameter ) const;
};

} // namespace IECoreMaya

#endif // IE_COREMAYA_BOXPARAMETERHANDLER_H