text:
/*
* @version 0.1 (auto-set)
*/
// end hide JavaScript

/**
* Filename.......: calendar.js
* Project........: Popup Calendar
* Last Modified..: $Date$
* CVS Revision...: $Revision$
* Copyright......: 2001, 2002 Richard Heyes
*/

/**
* Global variables
*/
        dynCalendar_layers          = new Array();
        dynCalendar_mouseoverStatus = false;
        dynCalendar_mouseX          = 0;
        dynCalendar_mouseY          = 0;

/**
* The calendar constructor
*
* @access public
* @param string objName      Name of the object that you create
* @param string callbackFunc Name of the callback function
* @param string OPTIONAL     Optional layer name
* @param string OPTIONAL     Optional images path
*/
        function dynCalendar(objName, callbackFunc)
        {
                /**
        * Properties
        */
                // Todays date
                this.today          = new Date();
                this.date           = this.today.getDate();
                this.month          = this.today.getMonth();
                this.year           = this.today.getFullYear();

                this.objName        = objName;
                this.callbackFunc   = callbackFunc;
                this.imagesPath     = arguments[2] ? arguments[2] : '<#ROOTHTML#>templates/dateselect/';
                this.layerID        = arguments[3] ? arguments[3] : 'dynCalendar_layer_' + dynCalendar_layers.length;

                this.offsetX        = 5;
                this.offsetY        = 5;

                this.useMonthCombo  = true;
                this.useYearCombo   = true;
                this.yearComboRange = 5;

                this.currentMonth   = this.month;
                this.currentYear    = this.year;

                /**
        * Public Methods
        */
                this.show              = dynCalendar_show;
                this.writeHTML         = dynCalendar_writeHTML;

                // Accessor methods
                this.setOffset         = dynCalendar_setOffset;
                this.setOffsetX        = dynCalendar_setOffsetX;
                this.setOffsetY        = dynCalendar_setOffsetY;
                this.setImagesPath     = dynCalendar_setImagesPath;
                this.setMonthCombo     = dynCalendar_setMonthCombo;
                this.setYearCombo      = dynCalendar_setYearCombo;
                this.setCurrentMonth   = dynCalendar_setCurrentMonth;
                this.setCurrentYear    = dynCalendar_setCurrentYear;
                this.setYearComboRange = dynCalendar_setYearComboRange;

                /**
        * Private methods
        */
                // Layer manipulation
                this._getLayer         = dynCalendar_getLayer;
                this._hideLayer        = dynCalendar_hideLayer;
                this._showLayer        = dynCalendar_showLayer;
                this._setLayerPosition = dynCalendar_setLayerPosition;
                this._setHTML          = dynCalendar_setHTML;

                // Miscellaneous
                this._getDaysInMonth   = dynCalendar_getDaysInMonth;
                this._mouseover        = dynCalendar_mouseover;

                /**
        * Constructor type code
        */
                dynCalendar_layers[dynCalendar_layers.length] = this;
                this.writeHTML();
        }

/**
* Shows the calendar, or updates the layer if
* already visible.
*
* @access public
* @param integer month Optional month number (0-11)
* @param integer year  Optional year (YYYY format)
*/
        function dynCalendar_show()
        {
                // Variable declarations to prevent globalisation
                var month, year, monthnames, numdays, thisMonth, firstOfMonth;
                var ret, row, i, cssClass, linkHTML, previousMonth, previousYear;
                var nextMonth, nextYear, prevImgHTML, prevLinkHTML, nextImgHTML, nextLinkHTML;
                var monthComboOptions, monthCombo, yearComboOptions, yearCombo, html;

                this.currentMonth = month = arguments[0] != null ? arguments[0] : this.currentMonth;
                this.currentYear  = year  = arguments[1] != null ? arguments[1] : this.currentYear;

                monthnames = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
                numdays    = this._getDaysInMonth(month, year);

                thisMonth    = new Date(year, month, 1);
                firstOfMonth = thisMonth.getDay();

                // First few blanks up to first day
                ret = new Array(new Array());
                for(i=0; i<firstOfMonth; i++){
                        ret[0][ret[0].length] = ' 	';
                }

                // Main body of calendar
                row = 0;
                i   = 1;
                while(i <= numdays){
                        if(ret[row].length == 7){
                                ret[++row] = new Array();
                        }

                        /**
            * Generate this cells' HTML
            */
                        cssClass = (i == this.date && month == this.month && year == this.year) ? 'dynCalendar_today' : 'dynCalendar_day';
                        linkHTML = sprintf('%s',
                                           this.callbackFunc,
                                                           i,
                                                           Number(month) + 1,
                                                           year,
                                                           this.objName,
                                                           i++);

                        ret[row][ret[row].length] = sprintf('%s	', cssClass, linkHTML);
                }

                // Format the HTML
                for(i=0; i<ret.length; i++){
                        ret[i] = ret[i].join('\n') + '\n';
                }

                previousYear  = thisMonth.getFullYear();
                previousMonth = thisMonth.getMonth() - 1;
                if(previousMonth < 0){
                        previousMonth = 11;
                        previousYear--;
                }

                nextYear  = thisMonth.getFullYear();
                nextMonth = thisMonth.getMonth() + 1;
                if(nextMonth > 11){
                        nextMonth = 0;
                        nextYear++;
                }

                prevImgHTML  = sprintf('<img src="%s/prev.gif" alt="<<" border="0" />', this.imagesPath);
                prevLinkHTML = sprintf('%s',  this.objName, previousMonth, previousYear, prevImgHTML);
                nextImgHTML  = sprintf('<img src="%s/next.gif" alt="<<" border="0" />', this.imagesPath);
                nextLinkHTML = sprintf('%s',  this.objName, nextMonth, nextYear, nextImgHTML);

                /**
        * Build month combo
        */
                if (this.useMonthCombo) {
                        monthComboOptions = '';
                        for (i=0; i<12; i++) {
                                selected = (i == thisMonth.getMonth() ? 'selected="selected"' : '');
                                monthComboOptions += sprintf('<option value="%s" %s>%s</option>', i, selected, monthnames[i]);
                        }
                        monthCombo = sprintf('<select name="months" onchange="%s.show(this.options[this.selectedIndex].value, %s.currentYear)">%s</select>', this.objName, this.objName, monthComboOptions);
                } else {
                        monthCombo = monthnames[thisMonth.getMonth()];
                }

                /**
        * Build year combo
        */
                if (this.useYearCombo) {
                        yearComboOptions = '';
                        for (i = thisMonth.getFullYear() - this.yearComboRange; i <= (thisMonth.getFullYear() + this.yearComboRange); i++) {
                                selected = (i == thisMonth.getFullYear() ? 'selected="selected"' : '');
                                yearComboOptions += sprintf('<option value="%s" %s>%s</option>', i, selected, i);
                        }
                        yearCombo = sprintf('<select style="border: 1px groove" name="years" onchange="%s.show(%s.currentMonth, this.options[this.selectedIndex].value)">%s</select>', this.objName, this.objName, yearComboOptions);
                } else {
                        yearCombo = thisMonth.getFullYear();
                }

                html = '
';
                html += sprintf('
%s	%s %s	%s
', prevLinkHTML, monthCombo, yearCombo, nextLinkHTML);
                html += '
';
                html += 'Su	';
                html += 'Mo	';
                html += 'Tu	';
                html += 'We	';
                html += 'Th	';
                html += 'Fr	';
                html += 'Sa
';
                html += '
' + ret.join('
\n
') + '
';
                html += '
';

                this._setHTML(html);
                if (!arguments[0] && !arguments[1]) {
                        this._showLayer();
                        this._setLayerPosition();
                }
        }

/**
* Writes HTML to document for layer
*
* @access public
*/
        function dynCalendar_writeHTML()
        {
                if (is_ie5up || is_nav6up || is_gecko) {
                        document.write(sprintf('', this.objName, this.imagesPath));
                        document.write(sprintf('

', this.layerID, this.objName, this.objName));
                }
        }

/**
* Sets the offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Xoffset Number of pixels for vertical
*                        offset from mouse position
* @param integer Yoffset Number of pixels for horizontal
*                        offset from mouse position
*/
        function dynCalendar_setOffset(Xoffset, Yoffset)
        {
                this.setOffsetX(Xoffset);
                this.setOffsetY(Yoffset);
        }

/**
* Sets the X offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Xoffset Number of pixels for horizontal
*                        offset from mouse position
*/
        function dynCalendar_setOffsetX(Xoffset)
        {
                this.offsetX = Xoffset;
        }

/**
* Sets the Y offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Yoffset Number of pixels for vertical
*                        offset from mouse position
*/
        function dynCalendar_setOffsetY(Yoffset)
        {
                this.offsetY = Yoffset;
        }

/**
* Sets the images path
*
* @access public
* @param string path Path to use for images
*/
        function dynCalendar_setImagesPath(path)
        {
                this.imagesPath = path;
        }

/**
* Turns on/off the month dropdown
*
* @access public
* @param boolean useMonthCombo Whether to use month dropdown or not
*/
        function dynCalendar_setMonthCombo(useMonthCombo)
        {
                this.useMonthCombo = useMonthCombo;
        }

/**
* Turns on/off the year dropdown
*
* @access public
* @param boolean useYearCombo Whether to use year dropdown or not
*/
        function dynCalendar_setYearCombo(useYearCombo)
        {
                this.useYearCombo = useYearCombo;
        }

/**
* Sets the current month being displayed
*
* @access public
* @param boolean month The month to set the current month to
*/
        function dynCalendar_setCurrentMonth(month)
        {
                this.currentMonth = month;
        }

/**
* Sets the current month being displayed
*
* @access public
* @param boolean year The year to set the current year to
*/
        function dynCalendar_setCurrentYear(year)
        {
                this.currentYear = year;
        }

/**
* Sets the range of the year combo. Displays this number of
* years either side of the year being displayed.
*
* @access public
* @param integer range The range to set
*/
        function dynCalendar_setYearComboRange(range)
        {
                this.yearComboRange = range;
        }

/**
* Returns the layer object
*
* @access private
*/
        function dynCalendar_getLayer()
        {
                var layerID = this.layerID;

                if (document.getElementById(layerID)) {

                        return document.getElementById(layerID);

                } else if (document.all(layerID)) {
                        return document.all(layerID);
                }
        }

/**
* Hides the calendar layer
*
* @access private
*/
        function dynCalendar_hideLayer()
        {
                this._getLayer().style.visibility = 'hidden';
        }

/**
* Shows the calendar layer
*
* @access private
*/
        function dynCalendar_showLayer()
        {
                this._getLayer().style.visibility = 'visible';
        }

/**
* Sets the layers position
*
* @access private
*/
        function dynCalendar_setLayerPosition()
        {
                this._getLayer().style.top  = (dynCalendar_mouseY + this.offsetY) + 'px';
                this._getLayer().style.left = (dynCalendar_mouseX + this.offsetX) + 'px';
        }

/**
* Sets the innerHTML attribute of the layer
*
* @access private
*/
        function dynCalendar_setHTML(html)
        {
                this._getLayer().innerHTML = html;
        }

/**
* Returns number of days in the supplied month
*
* @access private
* @param integer month The month to get number of days in
* @param integer year  The year of the month in question
*/
        function dynCalendar_getDaysInMonth(month, year)
        {
                monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                if (month != 1) {
                        return monthdays[month];
                } else {
                        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28);
                }
        }

/**
* onMouse(Over|Out) event handler
*
* @access private
* @param boolean status Whether the mouse is over the
*                       calendar or not
*/
        function dynCalendar_mouseover(status)
        {
                dynCalendar_mouseoverStatus = status;
                return true;
        }

/**
* onMouseMove event handler
*/
        if (!mouseMoveEventAssigned) {
                dynCalendar_oldOnmousemove = document.onmousemove ? document.onmousemove : new Function;

                document.onmousemove = function ()
                {
                        if (arguments[0]) {
                                dynCalendar_mouseX = arguments[0].pageX;
                                dynCalendar_mouseY = arguments[0].pageY;
                        } else {
                                dynCalendar_mouseX = event.clientX + document.body.scrollLeft;
                                dynCalendar_mouseY = event.clientY + document.body.scrollTop;
                                arguments[0] = null;
                        }

                        dynCalendar_oldOnmousemove(arguments[0]);
                }

                var mouseMoveEventAssigned = true;
        }

/**
* Callbacks for document.onclick
*/
        if (!clickEventAssigned) {
                dynCalendar_oldOnclick = document.onclick ? document.onclick : new Function;

                document.onclick = function ()
                {
                        if(!dynCalendar_mouseoverStatus){
                                for(i=0; i<dynCalendar_layers.length; ++i){
                                        dynCalendar_layers[i]._hideLayer();
                                }
                        }

                        dynCalendar_oldOnclick(arguments[0] ? arguments[0] : null);
                }
                var clickEventAssigned = true;
        }

/**
* Javascript mini implementation of sprintf()
*/
        function sprintf(strInput)
        {
                var strOutput  = '';
                var currentArg = 1;

                for (var i=0; i<strInput.length; i++) {
                        if (strInput.charAt(i) == '%' && i != (strInput.length - 1) && typeof(arguments[currentArg]) != 'undefined') {
                                switch (strInput.charAt(++i)) {
                                        case 's':
                                                strOutput += arguments[currentArg];
                                                break;
                                        case '%':
                                                strOutput += '%';
                                                break;
                                }
                                currentArg++;
                        } else {
                                strOutput += strInput.charAt(i);
                        }
                }

                return strOutput;
        }


text:
package io.github.xiaolei.transaction.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;

import java.util.List;

import io.github.xiaolei.transaction.R;

/**
 * TODO: add comment
 */
public abstract class BaseEditorFragment extends BaseFragment implements Validator.ValidationListener {
    private Validator mValidator;

    protected abstract void readArguments(Bundle args);

    protected abstract void load(long id) throws Exception;

    protected abstract void bind();

    protected abstract void preSave();

    protected abstract void save() throws Exception;

    protected abstract long getEntityId();

    protected abstract void onSaveCompleted(boolean success, Exception error);

    protected abstract Object getViewHolder();

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mValidator = new Validator(getViewHolder());
        mValidator.setValidationListener(this);

        Bundle args = getArguments();
        if (args != null) {
            readArguments(args);
        }

        loadAsync(getEntityId());
    }

    public void loadAsync(final long id) {
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... voids) {
                try {
                    load(id);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result == true) {
                    bind();
                } else {
                }
            }
        };
        task.execute();
    }

    public void validateThenSave() {
        mValidator.validate();
    }

    protected void saveAsync() {
        hideSoftKeyboard();
        final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", getActivity().getString(R.string.saving));
        preSave();
        AsyncTask<Void, Void, Exception> task = new AsyncTask<Void, Void, Exception>() {
            @Override
            protected Exception doInBackground(Void... voids) {
                Exception result = null;
                try {
                    save();
                } catch (Exception e) {
                    result = e;
                    e.printStackTrace();
                }

                return result;
            }

            @Override
            protected void onPostExecute(Exception error) {
                dialog.dismiss();
                onSaveCompleted(error != null ? false : true, error);
            }
        };
        task.execute();
    }

    @Override
    public int getActionBarTitle() {
        return R.string.app_name;
    }

    @Override
    public void onValidationSucceeded() {
        saveAsync();
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(getActivity());

            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            } else {
                Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @file
 * Contains Drupal\Core\Database\Driver\fake\FakeSelect.
 */

namespace Drupal\Core\Database\Driver\fake;

use Drupal\Component\Utility\String;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Database\Query\PlaceholderInterface;
use Drupal\Core\Database\Query\Select;
use Drupal\Core\Database\Query\SelectInterface;

class FakeSelect extends Select {

  /**
   * Contents of the pseudo-database.
   *
   * Keys are table names and values are arrays of rows in the table.
   * Every row there contains all table field values keyed by field name.
   *
   * @code
   * array(
   *   'user' => array(
   *     array(
   *       'uid' => 1,
   *       'name' => 'admin',
   *     ),
   *     array(
   *       'uid' => 2,
   *       'name' => 'alice',
   *     ),
   *   ),
   *   'node' => array(
   *     array(
   *       'nid' => 1,
   *     )
   *   )
   * )
   * @endcode
   *
   * @var array
   */
  protected $databaseContents;

  protected $countQuery = FALSE;
  protected $fieldsWithTable = array();

  /**
   * Constructs a new FakeSelect.
   *
   * @param array $database_contents
   *   An array of mocked database content.
   * @param string $table
   *   The base table name used within fake select.
   * @param string $alias
   *   The base table alias used within fake select.
   * @param string $conjunction
   *   The operator to use to combine conditions: 'AND' or 'OR'.
   */
  public function __construct(array $database_contents, $table, $alias, $conjunction = 'AND') {
    $this->databaseContents = $database_contents;
    $this->addJoin(NULL, $table, $alias);
    $this->where = new Condition($conjunction);
    $this->having = new Condition($conjunction);
  }

  /**
   * {@inheritdoc}
   */
  public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
    return $this->addJoin('LEFT', $table, $alias, $condition, $arguments);
  }

  /**
   * {@inheritdoc}
   */
  public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array()) {
    if ($table instanceof SelectInterface) {
      // @todo implement this.
      throw new \Exception('Subqueries are not supported at this moment.');
    }
    $alias = parent::addJoin($type, $table, $alias, $condition, $arguments);
    if (isset($type)) {
      if ($type != 'INNER' && $type != 'LEFT') {
        throw new \Exception(sprintf('%s type not supported, only INNER and LEFT.', $type));
      }
      if (!preg_match('/^(\w+\.)?(\w+)\s*=\s*(\w+)\.(\w+)$/', $condition, $matches)) {
        throw new \Exception('Only x.field1 = y.field2 conditions are supported.' . $condition);
      }
      if (!$matches[1] && count($this->tables) == 2) {
        $aliases = array_keys($this->tables);
        $matches[1] = $aliases[0];
      }
      else {
        $matches[1] = substr($matches[1], 0, -1);
      }
      if (!$matches[1]) {
        throw new \Exception('Only x.field1 = y.field2 conditions are supported.' . $condition);
      }
      if ($matches[1] == $alias) {
        $this->tables[$alias] += array(
          'added_field' => $matches[2],
          'original_table_alias' => $matches[3],
          'original_field' => $matches[4],
        );
      }
      elseif ($matches[3] == $alias) {
        $this->tables[$alias] += array(
          'added_field' => $matches[4],
          'original_table_alias' => $matches[1],
          'original_field' => $matches[2],
        );
      }
      else {
        throw new \Exception('The JOIN condition does not contain the alias of the joined table.');
      }
    }
    return $alias;
  }

  /**
   * {@inheritdoc}
   */
  public function execute() {
    // @todo: Implement distinct() handling.

    // Single table count queries often do not contain fields which this class
    // does not support otherwise, so add a shortcut.
    if (count($this->tables) == 1 && $this->countQuery) {
      $table_info = reset($this->tables);
      $where = $this->where;
      if (!empty($this->databaseContents[$table_info['table']])) {
        $results = array_filter($this->databaseContents[$table_info['table']], function ($row_array) use ($where) {
          return ConditionResolver::matchGroup(new DatabaseRow($row_array), $where);
        });
      }
      else {
        $results = array();
      }
    }
    else {
      $all_rows = $this->executeJoins();
      $all_rows = $this->resolveConditions($this->where, $all_rows);
      if (!empty($this->order)) {
        usort($all_rows, array($this, 'sortCallback'));
      }
      // Now flatten the rows so that each row becomes a field alias => value
      // array.
      $results = array();
      foreach ($all_rows as $table_rows) {
        $result_row = array();
        foreach ($table_rows as $row) {
          $result_row += $row['result'];
        }
        $results[] = $result_row;
      }
    }
    if (!empty($this->range)) {
      $results = array_slice($results, $this->range['start'], $this->range['length']);
    }
    if ($this->countQuery) {
      $results = array(array(count($results)));
    }
    return new FakeStatement($results);
  }

  /**
   * Create an initial result set by executing the joins and picking fields.
   *
   * @return array
   *   A multidimensional array, the first key are table aliases, the second
   *   are field aliases, the values are the database contents or NULL in case
   *   of JOINs.
   */
  protected function executeJoins() {
    $fields = array();
    foreach ($this->fields as $field_info) {
      $this->fieldsWithTable[$field_info['table'] . '.' . $field_info['field']] = $field_info;
      $fields[$field_info['table']][$field_info['field']] = NULL;
    }
    foreach ($this->tables as $alias => $table_info) {
      if ($table = reset($this->databaseContents[$table_info['table']])) {
        foreach (array_keys($table) as $field) {
          if (!isset($this->fields[$field])) {
            $this->fieldsWithTable[$field] = array(
              'table' => $alias,
              'field' => $field,
            );
            $this->fieldsWithTable["$alias.$field"] = array(
              'table' => $alias,
              'field' => $field,
            );
          }
        }
      }
    }
    // This will contain a multiple dimensional array. The first key will be a
    // table alias, the second either result or all, the third will be a field
    // alias. all contains every field in the table with the original field
    // names while result contains only the fields requested. This allows for
    // filtering on fields that were not added via addField().
    $results = array();
    foreach ($this->tables as $table_alias => $table_info) {
      // The base table for this query.
      if (empty($table_info['join type'])) {
        foreach ($this->databaseContents[$table_info['table']] as $candidate_row) {
          $results[] = $this->getNewRow($table_alias, $fields, $candidate_row);
        }
      }
      else {
        $new_rows = array();

        // Dynamically build a set of joined rows. Check existing rows and see
        // if they can be joined with incoming rows.
        foreach ($results as $row) {
          $joined = FALSE;
          foreach ($this->databaseContents[$table_info['table']] as $candidate_row) {
            if ($row[$table_info['original_table_alias']]['result'][$table_info['original_field']] == $candidate_row[$table_info['added_field']]) {
              $joined = TRUE;
              $new_rows[] = $this->getNewRow($table_alias, $fields, $candidate_row, $row);
            }
          }
          if (!$joined && $table_info['join type'] == 'LEFT') {
            // Because PHP doesn't scope their foreach statements,
            // $candidate_row may contain the last value assigned to it from the
            // previous statement.
            // @TODO: empty tables? Those are a problem.
            $keys = array_keys($candidate_row);
            $values = array_fill(0, count($keys), NULL);
            $new_row = array(
              'result' => $fields[$table_alias],
              'all' => array_combine($keys, $values),
            );
            $new_rows[] = array($table_alias => $new_row) + $row;
          }
        }
        $results = $new_rows;
      }
    }
    return $results;
  }

  /**
   * Retrieves a new row.
   *
   * @param string $table_alias
   * @param array $fields
   * @param array $candidate_row
   * @param array $row
   *
   * @return array
   */
  protected function getNewRow($table_alias, $fields, $candidate_row, $row = array()) {
    $new_row[$table_alias]['all'] = $candidate_row;
    foreach ($fields[$table_alias] as $field => $v) {
      $new_row[$table_alias]['result'][$field] = $candidate_row[$field];
    }
    return $new_row + $row;
  }

  /**
   * {@inheritdoc}
   */
  public function countQuery() {
    $query = clone $this;
    return $query->setCountQuery();
  }

  /**
   * Set this query to be a count query.
   */
  protected function setCountQuery() {
    $this->countQuery = TRUE;
    return $this;
  }

  /**
   * usort callback to order the results.
   */
  protected function sortCallback($a, $b) {
    $a_row = new DatabaseRowSelect($a, $this->fieldsWithTable, $this->fields);
    $b_row = new DatabaseRowSelect($b, $this->fieldsWithTable, $this->fields);
    foreach ($this->order as $field => $direction) {
      $a_value = $a_row->getValue($field);
      $b_value = $b_row->getValue($field);
      if ($a_value != $b_value) {
        return (($a_value < $b_value) == ($direction == 'ASC')) ? -1 : 1;
      }
    }
    return 0;
  }

  /**
   * Resolves conditions by removing non-matching rows.
   *
   * @param \Drupal\Core\Database\Query\Condition $condition_group
   *   The condition group to check.
   * @param array $rows
   *   An array of rows excluding non-matching rows.
   *
   * @return \Drupal\Core\Database\Driver\fake\ConditionResolver
   *   The condition resolver object.
   */
  protected function resolveConditions(Condition $condition_group, array &$rows) {
    $fields_with_table = $this->fieldsWithTable;
    $fields = $this->fields;
    return array_filter($rows, function ($row_array) use ($condition_group, $fields_with_table, $fields) {
      $row = new DatabaseRowSelect($row_array, $fields_with_table, $fields);
      return ConditionResolver::matchGroup($row, $condition_group);
    });
  }

  /**
   * {@inheritdoc}
   */
  public function orderBy($field, $direction = 'ASC') {
    $this->order[$field] = strtoupper($direction);
    return $this;
  }

  // ================== we could support these.
  /**
   * {@inheritdoc}
   */
  public function groupBy($field) {
    // @todo: Implement groupBy() method.
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function havingCondition($field, $value = NULL, $operator = NULL) {
    // @todo: Implement havingCondition() method.
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function uniqueIdentifier() {
    // TODO: Implement uniqueIdentifier() method.
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  // ================== the rest won't be supported, ever.
  /**
   * {@inheritdoc}
   */
  public function nextPlaceholder() {
    // TODO: Implement nextPlaceholder() method.
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function isPrepared() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function preExecute(SelectInterface $query = NULL) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function where($snippet, $args = array()) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function extend($extender_name) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getExpressions() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getGroupBy() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getUnion() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function forUpdate($set = TRUE) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &conditions() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function orderRandom() {
    // We could implement this but why bother.
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function union(SelectInterface $query, $type = '') {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function addExpression($expression, $alias = NULL, $arguments = array()) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getTables() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function getArguments(PlaceholderInterface $query_place_holder = NULL) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getOrderBy() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function &getFields() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function exists(SelectInterface $select) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function notExists(SelectInterface $select) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function arguments() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function compile(Connection $connection, PlaceholderInterface $query_place_holder) {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function compiled() {
    throw new \Exception(sprintf('Method "%s" is not supported', __METHOD__));
  }

  /**
   * {@inheritdoc}
   */
  public function fields($table_alias, array $fields = array()) {
    if (!$fields) {
      $table = $this->tables[$table_alias]['table'];
      if (!empty($this->databaseContents[$table])) {
        $fields = array_keys(reset($this->databaseContents[$table]));
      }
      else {
        throw new \Exception(String::format('All fields on empty table @table is not supported.', array('@table' => $table)));
      }
    }
    return parent::fields($table_alias, $fields);
  }
}


text:
@(title: String)(content: Html)
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">

        <title>@title</title>

        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon-32x32.png")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon-194x194.png")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon-96x96.png")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon-16x16.png")">

        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/app.min.1.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/app.min.2.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/app.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/jgrid.min.css")">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    </head>
    <body>

        @content

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/jgrid.min.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/jgrid-local-en.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/functions.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/fontawesome-markers.min.js")" type="text/javascript"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD0Zah3ZV_Pae3UfFM2S-rx7NyiWqhjTaI&callback=initMap" async defer></script>
        <script src="@routes.Assets.versioned("javascripts/flot/jquery.flot.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/flot/jquery.flot.resize.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/flot/jquery.flot.pie.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/flot/jquery.flot.tooltip.min.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/flot/jquery.flot.orderBars.js")" type="text/javascript"></script>
        <script src="@routes.Assets.versioned("javascripts/flot/curvedLines.js")" type="text/javascript"></script>
    </body>
</html>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../syn/struct.TypeGroup.html">
    <title>Redirection</title>

Redirecting to ../../syn/struct.TypeGroup.html...


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. reipubl. popularis sin. 38:76. 1986

#### Original name
null

### Remarks
null


text:
/*! tagged-infinite-scroll - v1.1.1 - 2015-07-17 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular'], factory);
  } else {
    // Browser globals
    root.taggedInfiniteScroll = factory(root.angular);
  }
}(this, function (angular) {
  "use strict";

  // Allows a container to support infinite scroll
  // Based on: http://binarymuse.github.io/ngInfiniteScroll/
  var module = angular.module('tagged.directives.infiniteScroll', []);

  module.directive('taggedInfiniteScroll', ['$window', '$timeout', function($window, $timeout) {
    return {
      scope: {
        callback: '&taggedInfiniteScroll',
        distance: '=taggedInfiniteScrollDistance',
        disabled: '=taggedInfiniteScrollDisabled'
      },
      link: function(scope, elem, attrs) {
        var win = angular.element($window);

        var onScroll = function(oldValue, newValue) {
          // Do nothing if infinite scroll has been disabled
          if (scope.disabled) {
            return;
          }
          var windowHeight = win[0].innerHeight;
          var elementBottom = elem[0].offsetTop + elem[0].offsetHeight;
          var windowBottom = windowHeight + (win[0].scrollY || win[0].pageYOffset);
          var remaining = elementBottom - windowBottom;
          var shouldGetMore = (remaining - parseInt(scope.distance || 0, 10) <= 0);

          if (shouldGetMore) {
            $timeout(scope.callback);
          }
        };

        // Check immediately if we need more items upon reenabling.
        scope.$watch('disabled', function(isDisabled){
            if (false === isDisabled) onScroll();
        });

        win.bind('scroll', onScroll);

        // Remove window scroll handler when this element is removed.
        scope.$on('$destroy', function() {
          win.unbind('scroll', onScroll);
        });

        // Check on next event loop to give the browser a moment to paint.
        // Otherwise, the calculations may be off.
        $timeout(onScroll);
      }
    };
  }]);

  // Just return a value to define the module export.
  // This example returns an object, but the module
  // can return a function as the exported value.
  return module;
}));


text:
#include "logicalObject.h"

using namespace qrRepo::details;

LogicalObject::LogicalObject(const qReal::Id &id)
	: Object(id)
{
}

LogicalObject::LogicalObject(const QDomElement &element)
	: Object(element)
{
}

Object *LogicalObject::createClone() const
{
	return new LogicalObject(mId.sameTypeId());
}

bool LogicalObject::isLogicalObject() const
{
	return true;
}


text:
package org.apache.hc.client5.http.impl.cache;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

import org.apache.hc.client5.http.cache.HttpCacheEntry;
import org.apache.hc.client5.http.cache.Resource;
import org.apache.hc.core5.util.Args;

class ResourceReference extends PhantomReference<HttpCacheEntry> {

    private final Resource resource;

    public ResourceReference(final HttpCacheEntry entry, final ReferenceQueue<HttpCacheEntry> q) {
        super(entry, q);
        Args.notNull(entry.getResource(), "Resource");
        this.resource = entry.getResource();
    }

    public Resource getResource() {
        return this.resource;
    }

    @Override
    public int hashCode() {
        return this.resource.hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        return this.resource.equals(obj);
    }

}


text:
package wire

import (
	"context"
	"errors"
	"fmt"
	"reflect"
	"sort"
	"time"

	"github.com/google/uuid"
	"google.golang.org/grpc"

	vkit "cloud.google.com/go/pubsublite/apiv1"
	pb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1"
)

// PartitionSet is a set of partition numbers.
type PartitionSet map[int]struct{}

// NewPartitionSet creates a partition set initialized from the given partition
// numbers.
func NewPartitionSet(partitions []int) PartitionSet {
	var void struct{}
	partitionSet := make(map[int]struct{})
	for _, p := range partitions {
		partitionSet[p] = void
	}
	return partitionSet
}

func newPartitionSet(assignmentpb *pb.PartitionAssignment) PartitionSet {
	var partitions []int
	for _, p := range assignmentpb.GetPartitions() {
		partitions = append(partitions, int(p))
	}
	return NewPartitionSet(partitions)
}

// Ints returns the partitions contained in this set as an unsorted slice.
func (ps PartitionSet) Ints() (partitions []int) {
	for p := range ps {
		partitions = append(partitions, p)
	}
	return
}

// SortedInts returns the partitions contained in this set as a sorted slice.
func (ps PartitionSet) SortedInts() (partitions []int) {
	partitions = ps.Ints()
	sort.Ints(partitions)
	return
}

// Contains returns true if this set contains the specified partition.
func (ps PartitionSet) Contains(partition int) bool {
	_, exists := ps[partition]
	return exists
}

// A function that generates a 16-byte UUID.
type generateUUIDFunc func() (uuid.UUID, error)

// partitionAssignmentReceiver must enact the received partition assignment from
// the server, or otherwise return an error, which will break the stream.
type partitionAssignmentReceiver func(PartitionSet) error

// assigner wraps the partition assignment stream and notifies a receiver when
// the server sends a new set of partition assignments for a subscriber.
type assigner struct {
	// Immutable after creation.
	assignmentClient  *vkit.PartitionAssignmentClient
	subscription      string
	initialReq        *pb.PartitionAssignmentRequest
	receiveAssignment partitionAssignmentReceiver
	metadata          pubsubMetadata

	// Fields below must be guarded with mu.
	stream *retryableStream

	abstractService
}

func newAssigner(ctx context.Context, assignmentClient *vkit.PartitionAssignmentClient, genUUID generateUUIDFunc, settings ReceiveSettings, subscriptionPath string, receiver partitionAssignmentReceiver) (*assigner, error) {
	clientID, err := genUUID()
	if err != nil {
		return nil, fmt.Errorf("pubsublite: failed to generate client UUID: %w", err)
	}

	a := &assigner{
		assignmentClient: assignmentClient,
		subscription:     subscriptionPath,
		initialReq: &pb.PartitionAssignmentRequest{
			Request: &pb.PartitionAssignmentRequest_Initial{
				Initial: &pb.InitialPartitionAssignmentRequest{
					Subscription: subscriptionPath,
					ClientId:     clientID[:],
				},
			},
		},
		receiveAssignment: receiver,
		metadata:          newPubsubMetadata(),
	}
	a.stream = newRetryableStream(ctx, a, settings.Timeout, 10*time.Minute, reflect.TypeOf(pb.PartitionAssignment{}))
	a.metadata.AddClientInfo(settings.Framework)
	return a, nil
}

func (a *assigner) Start() {
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.unsafeUpdateStatus(serviceStarting, nil) {
		a.stream.Start()
	}
}

func (a *assigner) Stop() {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.unsafeInitiateShutdown(serviceTerminating, nil)
}

func (a *assigner) newStream(ctx context.Context) (grpc.ClientStream, error) {
	return a.assignmentClient.AssignPartitions(a.metadata.AddToContext(ctx))
}

func (a *assigner) initialRequest() (interface{}, initialResponseRequired) {
	return a.initialReq, initialResponseRequired(false)
}

func (a *assigner) validateInitialResponse(_ interface{}) error {
	// Should not be called as initialResponseRequired=false above.
	return errors.New("pubsublite: unexpected initial response")
}

func (a *assigner) onStreamStatusChange(status streamStatus) {
	a.mu.Lock()
	defer a.mu.Unlock()

	switch status {
	case streamConnected:
		a.unsafeUpdateStatus(serviceActive, nil)
	case streamTerminated:
		a.unsafeInitiateShutdown(serviceTerminated, a.stream.Error())
	}
}

func (a *assigner) onResponse(response interface{}) {
	assignment, _ := response.(*pb.PartitionAssignment)
	err := a.receiveAssignment(newPartitionSet(assignment))

	a.mu.Lock()
	defer a.mu.Unlock()
	if a.status >= serviceTerminating {
		return
	}
	if err != nil {
		a.unsafeInitiateShutdown(serviceTerminated, err)
		return
	}
	a.stream.Send(&pb.PartitionAssignmentRequest{
		Request: &pb.PartitionAssignmentRequest_Ack{
			Ack: &pb.PartitionAssignmentAck{},
		},
	})
}

func (a *assigner) unsafeInitiateShutdown(targetStatus serviceStatus, err error) {
	if !a.unsafeUpdateStatus(targetStatus, wrapError("assigner", a.subscription, err)) {
		return
	}
	// No data to send. Immediately terminate the stream.
	a.stream.Stop()
}


text:
using System;
using System.Runtime.Serialization;
using Multitouch.Contracts;

namespace Multitouch.Service.Logic.ExternalInterfaces
{
	[DataContract]
	public class ImageData
	{
		internal ImageData(Image image)
		{
			Width = image.Width;
			Height = image.Height;
			Stride = image.Stride;
			BitsPerPixel = image.BitsPerPixel;
			Type = image.Type;
			Data = image.Data;
		}

		[DataMember]
		public int Width { get; private set; }
		[DataMember]
		public int Height { get; private set; }
		[DataMember]
		public int Stride { get; private set; }
		[DataMember]
		public int BitsPerPixel { get; private set; }
		[DataMember]
		public ImageType Type { get; private set; }
		[DataMember]
		public byte[] Data { get; private set; }
	}
}


text:
package com.vsked.util;

import java.util.regex.Pattern;

public class ValidateUtils {
	public static String isNumberReg="^0|[0-9]\\d*(\\.\\d+)?$";

	public static boolean isNumber(String s){
		Pattern pattern = Pattern.compile(isNumberReg);
		return (s!=null) && (!"".equals(s)) && (pattern.matcher(s).matches());
	}

	public static boolean isEmpty(String s){
		return "".equals(s);
	}

	public static boolean isNull(String s){
		return s==null;
	}

	public static boolean isNullOrIsEmpty(String s){
		return isNull(s)||isEmpty(s);
	}

}


text:
package variable

import (
	"fmt"
	"os/exec"
	"strings"

	"github.com/lmika/shellwords"
)

const (
	// GitCmd 获取最近一次git commit id函数
	GitCmd = `git rev-parse HEAD` //git log --pretty=format:"%H" -1
	// DefaultGitCommitExpr 默认git commit变量表达式
	DefaultGitCommitExpr = "{{.GitCommit}}"
)

var (
	// DefaultGitCommitVar 默认git commit变量
	DefaultGitCommitVar, _ = NewGitCommitVar(GitCmd, DefaultGitCommitExpr)
)

// GitCommitVar git commit变量
type GitCommitVar struct {
	cmd  string
	expr string
}

// NewGitCommitVar 实例化git commit变量
func NewGitCommitVar(cmd, expr string) (v *GitCommitVar, err error) {
	if expr == "" {
		return nil, ErrExprEmpty
	}
	if cmd == "" {
		return nil, ErrCmdEmpty
	}

	return &GitCommitVar{
		cmd:  cmd,
		expr: expr,
	}, nil
}

// Eval 表达式变量求值
func (v *GitCommitVar) Eval(_ string, debug bool) (val string, err error) {
	return v.headCommit(debug)
}

// Match 表达式是否可以使用当前变量求值
func (v *GitCommitVar) Match(expr string) (matched bool) {
	return v.expr == expr
}

func (v *GitCommitVar) headCommit(debug bool) (commit string, err error) {
	var cmd *exec.Cmd
	cmdAndArgs := shellwords.Split(v.cmd)
	if len(cmdAndArgs) == 1 {
		cmd = exec.Command(cmdAndArgs[0])
	} else if len(cmdAndArgs) >= 2 {
		cmd = exec.Command(cmdAndArgs[0], cmdAndArgs[1:]...)
	} else {
		panic("unreachable")
	}
	if debug {
		fmt.Println("==>", v.cmd)
	}
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(output)), nil
}


text:
$_QE.prototype.PlayerMenuTeleport = function(player, world, parent_row) {
    this.parent_row = parent_row;
    this.__init__(player);

    parent_row._interactive_tail._object.add_attachment(this, true, false);
    this.set_offset_horizontal(0, .5 + parent_row._interactive_tail._object.width / this.width, 0);
    this.set_offset_vertical(0, -.5);
    this.set_offset_depth(10);

    this.number_of_rows = 0;
};

Object.assign(
    $_QE.prototype.PlayerMenuTeleport.prototype,
    $_QE.prototype.PlayerMenuAbstract.prototype,
    {
        register_world: function(world) {
            let r = new $_QE.prototype.PlayerMenuRow();
            let self = this;
            r.__init__(this, world.world_icon, world.world_name, function() {
                QE.manager_world.set_current_world(world);
            }, true, true);

            this.number_of_rows++;

            if (this.number_of_rows > 1) {
                this.set_offset_vertical(0, -.5 + (((32 / 128) / 2) * (this.number_of_rows - 1)));
            }
        },

        //_open: function() {},

    }
);


text:
function sys=islinear(x)
%ISLINEAR Check if variable is linear
%
% p = islinear(X)
%
% X : SDPVAR object
% p : boolean 0/1

% Author Johan Löfberg
% $Id: islinear.m,v 1.1 2006-08-10 18:00:20 joloef Exp $

try
    sys = is(x,'linear');
catch
    disp('I have messed up something internally in YALMIP. Sorry...')
    disp('Type yalmip(''clear'') and re-define the problem.');
    disp(' ')
    disp('This problem typically occurs if you have SDPVAR variables in');
    disp('work-space, and call a function where you are using ')
    disp('the command yalmip(''clear''). When control is returned to');
    disp('the work-space, things are messed up...');
    error('Internal problems in YALMIP');
end


text:
Obvious Data
============

[![Gem Version](https://badge.fury.io/rb/obvious_data.svg)](https://rubygems.org/gems/obvious_data)
[![Build Status](https://travis-ci.org/enova/obvious_data.svg?branch=master)](https://travis-ci.org/enova/obvious_data)
[![Coverage Status](https://coveralls.io/repos/github/enova/obvious_data/badge.svg?branch=master)](https://coveralls.io/github/enova/obvious_data?branch=master)

Rails gem to treat DB functions, triggers, etc more like code, and make them more discoverable

Premise
=======
Database functions, triggers, and views can be very powerful when used in the right circumstances, but they lack the discoverability and versioning of source code. Short of logging into your databases, it is difficult to tell what versions of functions and triggers are active, nevermind getting a good picture of what are all the custom functions and triggers in place in your application.

Obvious Data improves this by creating directories for you to place these constructs, treating them more like code and instantly making them greppable, and adding helper methods where you can easily use these files from your migrations.

Usage
=====

### Creating directories
```
$ bin/rails generate obvious_data_directories
```

This will generate empty `db/functions`, `db/views`, and `db/triggers` directories for you to use.

### Adding functions
Say you want to add a function called `one()`. You should create a file called `one.sql` in `db/functions/` with the SQL that's needed to add that function. Thus:

_db/functions/one.sql_:

```
CREATE OR REPLACE FUNCTION one() RETURNS integer AS $$
  SELECT 1 AS result;
$$ LANGUAGE SQL;
```

Then, from a migration you can add this function like:

*db/migrate/20140724185749_create_one_function.rb*

```ruby
class CreateDummyTable < ActiveRecord::Migration
  def up
    execute_function_file 'one'
  end

  def down
    drop_function 'one()'
  end
end
```

Run your migration and your function should be operational!

### Changing functions
Say it is suddenly decreed that the numeric representation of "one" is now 99. To keep the active version of your function discoverable, you are expected to change the same function file you created in the above section in place, and updating it through a new migration. So:

*db/functions/one.sql*:

```
CREATE OR REPLACE FUNCTION one() RETURNS integer AS $$
  SELECT 99 AS result;
$$ LANGUAGE SQL;
```

*db/migrate/20140724185750_one_function_to_99.rb*

```ruby
class CreateDummyTable < ActiveRecord::Migration
  def up
    execute_function_file 'one'
  end

  def down
    # Unfortunately there's currently no easy way to revert this situation
  end
end
```

### Dropping functions
What do you do when you no longer want to use a class from your source code? You delete it! Which is the same thing we'll do here. In the migration, make sure to use the full function signature instead of just the function name.

*db/functions/one.sql: *deleted**

*db/migrate/20140724185751_drop_one_function.rb:*

```ruby
class CreateDummyTable < ActiveRecord::Migration
  def up
    drop_function 'one()'
  end

  def down
    # Unfortunately there's currently no easy way to revert this situation
  end
end
```

### Adding/changing/dropping views and triggers
Practically the same as adding and changing functions. The available migration helpers are:

- `execute_view_file(view_name)`
- `drop_view(view_name)`
- `execute_trigger_file(trigger_name)`
- `drop_trigger(trigger_name, table_trigger_is_on)`

Supported Databases etc
=======================

- Currently the only database supported is PostgreSQL, but no reason that other DBs can't also be supported
- Rails version 3.2.x through 4.2.x
- Ruby versions 1.9.3, 2.1.x, and rubinius 2.2+

Contributing
============
Make sure you run the tests before and after making changes. Here's how:

- Ensure PostgreSQL is installed
- Run `bundle install`
- Run `bundle exec rake app:db:create`
- Run `bundle exec rake app:db:setup app:db:migrate app:db:test:prepare`
- Run `bundle exec rspec`


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Support;
using Hl7.Fhir.XPath;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace Hl7.Fhir.Specification.Tests
{
    [TestClass]
    public class JsonNavigatorTests
    {
        [TestMethod]
        public void TestConstruct()
        {
            var nav = buildNav();

            // At root;
            Assert.AreEqual(XPathNodeType.Root,nav.NodeType);
            Assert.IsFalse(nav.IsEmptyElement);
            Assert.AreEqual(String.Empty, nav.Name);
            Assert.AreEqual(String.Empty, nav.LocalName);
            Assert.AreEqual(String.Empty, nav.NamespaceURI);
            Assert.AreEqual(String.Empty, nav.Prefix);
            Assert.IsTrue(nav.Value.StartsWith("MRN2001-05-06Acme Healthcareusualurn:oid:1.2.36.146.595.217.0.112345Organization/1http://hl7.org/fhir/example-do-not-use#recordStatusarchivedPeterJamesofficialChalmersJimusualhttp://hl7.org/fhir/example-do-not-use#Patient.avatar#pic1Duck imageurn:example-do-not-use:pi3.141592653589793http://hl7.org/fhir/v3/AdministrativeGenderMMale1974-12http://hl7.org/fhir/example-do-not-use#DateTime.calendargregoriantruehome534 Erewhon StPleasantVilleVic3999ASKUhttp://hl7.org/fhir/Profileiso-21090#nullFlavor3generated
"));
        }

        [TestMethod]
        public void TestRootToChild()
        {
            var nav = buildNav();
            Assert.IsTrue(nav.MoveToFirstChild());
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.IsFalse(nav.IsEmptyElement);
            Assert.AreEqual("f:Patient", nav.Name);
            Assert.AreEqual("Patient", nav.LocalName);
            Assert.AreEqual(XmlNs.FHIR , nav.NamespaceURI);
            Assert.AreEqual(JsonXPathNavigator.FHIR_PREFIX, nav.Prefix);
        }

        [TestMethod]
        public void TestMoveToChild()
        {
            var nav = buildNav();
            Assert.IsTrue(nav.MoveToFirstChild());      // Patient
            Assert.IsTrue(nav.MoveToFirstChild());      // identifier
            Assert.IsTrue(nav.MoveToFirstChild());      // label

            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.IsFalse(nav.IsEmptyElement);
            Assert.AreEqual("f:label", nav.Name);

            Assert.IsFalse(nav.MoveToFirstChild());      // No child
            Assert.IsTrue(nav.MoveToFirstAttribute());  // value attribute
            Assert.AreEqual(XPathNodeType.Attribute, nav.NodeType);
            Assert.AreEqual("MRN", nav.Value);

            Assert.IsFalse(nav.MoveToNextAttribute());       // no other attributes
            Assert.AreEqual(XPathNodeType.Attribute, nav.NodeType);  // should not have moved
            Assert.AreEqual("MRN", nav.Value);

            Assert.IsTrue(nav.MoveToParent());      // move up to label
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:label", nav.Name);

            Assert.IsTrue(nav.MoveToNext());
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:period", nav.Name);

            Assert.IsTrue(nav.MoveToNext());
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:assigner", nav.Name);
            Assert.IsTrue(nav.MoveToFirstChild());
            Assert.AreEqual("f:display", nav.Name);

            Assert.IsTrue(nav.MoveToParent());      // back to assigner

            Assert.IsTrue(nav.MoveToNext());        // move to use
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:use", nav.Name);

            Assert.IsTrue(nav.MoveToNext());        // move to system
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:system", nav.Name);

            Assert.IsTrue(nav.MoveToNext());        // move to value
            Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
            Assert.AreEqual("f:value", nav.Name);

            Assert.IsFalse(nav.MoveToNext());
            Assert.IsTrue(nav.MoveToParent());  // identifier
            Assert.IsTrue(nav.MoveToParent());  // whole resource
            Assert.IsTrue(nav.MoveToParent()); // root
            Assert.IsFalse(nav.MoveToParent()); // root
        }

        [TestMethod]
        public void AttributeWithAppendix()
        {
            var nav = buildNav();
            Assert.IsTrue(nav.MoveToFirstChild());      // Patient

            Assert.IsTrue(nav.MoveToChild("contact", XmlNs.FHIR));
            Assert.IsTrue(nav.MoveToChild("name", XmlNs.FHIR));

            Assert.IsTrue(nav.MoveToFirstChild());  // family #1 - null
            Assert.AreEqual("f:family", nav.Name);
            Assert.IsFalse(nav.MoveToFirstAttribute()); // no value (null)
            Assert.IsTrue(nav.MoveToFirstChild());  // extension
            Assert.AreEqual("f:extension", nav.Name);
            nav.MoveToParent();

            Assert.IsTrue(nav.MoveToNext());        // family #2  - du
            Assert.AreEqual("f:family", nav.Name);

            Assert.IsTrue(nav.MoveToFirstAttribute()); // @value="du"
            Assert.AreEqual("du", nav.Value);
            Assert.AreEqual("value", nav.Name);
            Assert.IsTrue(nav.MoveToNextAttribute()); // @id="a2"
            Assert.AreEqual("a2", nav.Value);
            Assert.AreEqual("id", nav.Name);
            nav.MoveToParent();

            Assert.IsTrue(nav.MoveToNext());        // family #3  - null
            Assert.IsTrue(nav.MoveToNext());        // family #4  - Marché
            Assert.IsTrue(nav.MoveToNext());        // family #5  - null

            Assert.IsTrue(nav.MoveToNext());
            Assert.AreEqual("f:given", nav.Name);
        }

        [TestMethod]
        public void DivXhtmlNamespace()
        {
            var nav = buildNav();
            Assert.IsTrue(nav.MoveToFirstChild());      // Patient

            Assert.IsTrue(nav.MoveToChild("text", XmlNs.FHIR)); // Move to narrative
            Assert.IsTrue(nav.MoveToChild("div", XmlNs.XHTML)); // Move to narrative
            Assert.IsTrue(nav.Value.StartsWith("<div xmlns=\"http://www.w3.org/1999/xhtml\""));

        }

        [TestMethod]
        public void ForwardBackwards()
        {
            var nav = buildNav();
            Assert.IsTrue(nav.MoveToFirstChild());
            Assert.IsTrue(nav.MoveToFirstChild());
            Assert.IsTrue(nav.MoveToNext());
            Assert.IsTrue(nav.MoveToNext());
            Assert.IsTrue(nav.MoveToPrevious());
            Assert.IsTrue(nav.MoveToPrevious());

            Assert.IsFalse(nav.MoveToPrevious());  // one time too many
        }

        [TestMethod]
        public void CloneIsAtSamePosition()
        {
            Assert.IsNotNull(EqualityComparer<NavigatorState>.Default);

            var nav = buildNav();
            var nav2 = buildNav();
            Assert.IsTrue(nav.IsSamePosition(nav2));

            Assert.IsTrue(nav.MoveToFirstChild());
            Assert.IsTrue(nav.MoveToFirstChild()); // nodeA

            // Just checking, it should NOT be the same position
            Assert.IsFalse(nav.IsSamePosition(nav2));

            Assert.IsTrue(nav.MoveToNext()); // nodeB[0]
            Assert.IsTrue(nav.MoveToNext()); // nodeB[1]

            // Navigate the same with nav2
            Assert.IsTrue(nav2.MoveToFirstChild());
            Assert.IsTrue(nav2.MoveToFirstChild()); // nodeA
            Assert.IsTrue(nav2.MoveToNext()); // nodeB[0]
            Assert.IsTrue(nav2.MoveToNext()); // nodeB[1]

            // Now, they should have arrived at the same position
            Assert.IsTrue(nav.IsSamePosition(nav2));

            var nav3 = new JsonXPathNavigator(nav);
            Assert.IsTrue(nav.IsSamePosition(nav3));
            Assert.IsTrue(nav2.IsSamePosition(nav3));
        }

        [TestMethod]
        public void TestSelect()
        {
            var nav = buildNav();
            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("f", XmlNs.FHIR);

            var result = nav.Select("/f:Patient/f:telecom", mgr);
            Assert.AreEqual(2, result.Count);

            var text = nav.SelectSingleNode("/f:Patient/f:telecom[2]/f:use/@value", mgr);
            Assert.AreEqual("work", text.Value);

            text = nav.SelectSingleNode("/f:Patient/f:birthDate/@value", mgr);
            Assert.AreEqual("1974-12", text.Value);

            text = nav.SelectSingleNode("/f:Patient/f:birthDate/f:extension[@url='http://hl7.org/fhir/example-do-not-use#DateTime.calendar']/f:valueCode/@value", mgr);
            Assert.AreEqual("gregorian", text.Value);
        }

        [TestMethod]
        public void TestSelectContained()
        {
            var nav = buildNav();
            var mgr = new XmlNamespaceManager(nav.NameTable);
            mgr.AddNamespace("f", XmlNs.FHIR);

            var contained = nav.Select("/f:Patient/f:contained", mgr);
            Assert.IsNotNull(contained);
            Assert.AreEqual(2, contained.Count);

            var result = nav.SelectSingleNode("/f:Patient/f:contained/f:Organization/f:identifier/f:system/@value", mgr);
            Assert.AreEqual("urn:ietf:rfc:3986", result.Value);

            // Test special contentType attr of Binary
            result = nav.SelectSingleNode("/f:Patient/f:contained/f:Binary/@contentType", mgr);
            Assert.AreEqual("image/gif", result.Value);

            // Test special text node of Binary
            result = nav.SelectSingleNode("/f:Patient/f:contained/f:Binary/text()", mgr);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Value.StartsWith("R0lGODlhEwARAPcAAAAAAAAA"));
        }

        [TestMethod]
        public void TestTransform()
        {
            string identityTransform = @"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" +
                    @"<xsl:template match=""@*|node()"">" +
                    @"<xsl:copy>" +
                            @"<xsl:apply-templates select=""@*""/>" +
                            @"<xsl:apply-templates select=""node()""/>" +
                        @"</xsl:copy>" +
                    @"</xsl:template>" +
                    @"</xsl:stylesheet>";

            IXPathNavigable navCreator = buildNav();
            var nav = navCreator.CreateNavigator();
            Assert.IsNotNull(nav);
            Assert.AreEqual(XPathNodeType.Root, nav.NodeType);

            StringWriter sw = new StringWriter();
            XmlWriter xmlw = XmlWriter.Create(sw);
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(XmlReader.Create(new StringReader(identityTransform)));
            xslt.Transform(navCreator, xmlw);
            xmlw.Flush();

            Assert.IsTrue(sw.ToString().StartsWith("<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                "<f:Patient xmlns:f=\"http://hl7.org/fhir\"><f:identifier><f:label value=\"MRN\" />" +
                "<f:period><f:start value=\"2001-05-06\" /></f:period>"));
        }

        private static JsonXPathNavigator buildNav()
        {
            var json = File.ReadAllText(@"TestData\TestPatient.json");
            var reader = new StringReader(json);
            return new JsonXPathNavigator(new JsonTextReader(reader));
        }
    }
}


text:
#ifndef FREERDP_CHANNEL_RAIL_CLIENT_RAIL_H
#define FREERDP_CHANNEL_RAIL_CLIENT_RAIL_H

#include <freerdp/api.h>
#include <freerdp/types.h>

#include <freerdp/rail.h>
#include <freerdp/message.h>
#include <freerdp/channels/rail.h>

/**
 * Client Interface
 */

typedef struct _rail_client_context RailClientContext;

typedef UINT (*pcRailOnOpen)(RailClientContext* context, BOOL* sendHandshake);

typedef UINT (*pcRailClientExecute)(RailClientContext* context, const RAIL_EXEC_ORDER* exec);
typedef UINT (*pcRailClientActivate)(RailClientContext* context,
                                     const RAIL_ACTIVATE_ORDER* activate);
typedef UINT (*pcRailClientSystemParam)(RailClientContext* context,
                                        const RAIL_SYSPARAM_ORDER* sysparam);
typedef UINT (*pcRailServerSystemParam)(RailClientContext* context,
                                        const RAIL_SYSPARAM_ORDER* sysparam);
typedef UINT (*pcRailClientSystemCommand)(RailClientContext* context,
                                          const RAIL_SYSCOMMAND_ORDER* syscommand);
typedef UINT (*pcRailClientHandshake)(RailClientContext* context,
                                      const RAIL_HANDSHAKE_ORDER* handshake);
typedef UINT (*pcRailServerHandshake)(RailClientContext* context,
                                      const RAIL_HANDSHAKE_ORDER* handshake);
typedef UINT (*pcRailServerHandshakeEx)(RailClientContext* context,
                                        const RAIL_HANDSHAKE_EX_ORDER* handshakeEx);
typedef UINT (*pcRailClientNotifyEvent)(RailClientContext* context,
                                        const RAIL_NOTIFY_EVENT_ORDER* notifyEvent);
typedef UINT (*pcRailClientWindowMove)(RailClientContext* context,
                                       const RAIL_WINDOW_MOVE_ORDER* windowMove);
typedef UINT (*pcRailServerLocalMoveSize)(RailClientContext* context,
                                          const RAIL_LOCALMOVESIZE_ORDER* localMoveSize);
typedef UINT (*pcRailServerMinMaxInfo)(RailClientContext* context,
                                       const RAIL_MINMAXINFO_ORDER* minMaxInfo);
typedef UINT (*pcRailClientInformation)(RailClientContext* context,
                                        const RAIL_CLIENT_STATUS_ORDER* clientStatus);
typedef UINT (*pcRailClientSystemMenu)(RailClientContext* context,
                                       const RAIL_SYSMENU_ORDER* sysmenu);
typedef UINT (*pcRailServerTaskBarInfo)(RailClientContext* context,
                                        const RAIL_TASKBAR_INFO_ORDER* taskBarInfo);
typedef UINT (*pcRailClientLanguageBarInfo)(RailClientContext* context,
                                            const RAIL_LANGBAR_INFO_ORDER* langBarInfo);
typedef UINT (*pcRailServerLanguageBarInfo)(RailClientContext* context,
                                            const RAIL_LANGBAR_INFO_ORDER* langBarInfo);
typedef UINT (*pcRailClientLanguageIMEInfo)(RailClientContext* context,
                                            const RAIL_LANGUAGEIME_INFO_ORDER* langImeInfo);
typedef UINT (*pcRailServerExecuteResult)(RailClientContext* context,
                                          const RAIL_EXEC_RESULT_ORDER* execResult);
typedef UINT (*pcRailClientGetAppIdRequest)(RailClientContext* context,
                                            const RAIL_GET_APPID_REQ_ORDER* getAppIdReq);
typedef UINT (*pcRailServerGetAppIdResponse)(RailClientContext* context,
                                             const RAIL_GET_APPID_RESP_ORDER* getAppIdResp);
typedef UINT (*pcRailServerZOrderSync)(RailClientContext* context, const RAIL_ZORDER_SYNC* zorder);
typedef UINT (*pcRailServerCloak)(RailClientContext* context, const RAIL_CLOAK* cloak);
typedef UINT (*pcRailClientCloak)(RailClientContext* context, const RAIL_CLOAK* cloak);
typedef UINT (*pcRailServerPowerDisplayRequest)(RailClientContext* context,
                                                const RAIL_POWER_DISPLAY_REQUEST* power);
typedef UINT (*pcRailClientSnapArrange)(RailClientContext* context, const RAIL_SNAP_ARRANGE* snap);
typedef UINT (*pcRailServerGetAppidResponseExtended)(RailClientContext* context,
                                                     const RAIL_GET_APPID_RESP_EX* id);
typedef UINT (*pcRailClientCompartmentInfo)(RailClientContext* context,
                                            const RAIL_COMPARTMENT_INFO_ORDER* compartmentInfo);

struct _rail_client_context
{
	void* handle;
	void* custom;

	pcRailClientExecute ClientExecute;
	pcRailClientActivate ClientActivate;
	pcRailClientSystemParam ClientSystemParam;
	pcRailServerSystemParam ServerSystemParam;
	pcRailClientSystemCommand ClientSystemCommand;
	pcRailClientHandshake ClientHandshake;
	pcRailServerHandshake ServerHandshake;
	pcRailServerHandshakeEx ServerHandshakeEx;
	pcRailClientNotifyEvent ClientNotifyEvent;
	pcRailClientWindowMove ClientWindowMove;
	pcRailServerLocalMoveSize ServerLocalMoveSize;
	pcRailServerMinMaxInfo ServerMinMaxInfo;
	pcRailClientInformation ClientInformation;
	pcRailClientSystemMenu ClientSystemMenu;
	pcRailServerTaskBarInfo ServerTaskBarInfo;
	pcRailClientLanguageBarInfo ClientLanguageBarInfo;
	pcRailServerLanguageBarInfo ServerLanguageBarInfo;
	pcRailClientLanguageIMEInfo ClientLanguageIMEInfo;
	pcRailServerExecuteResult ServerExecuteResult;
	pcRailClientGetAppIdRequest ClientGetAppIdRequest;
	pcRailServerGetAppIdResponse ServerGetAppIdResponse;
	pcRailServerZOrderSync ServerZOrderSync;
	pcRailClientCloak ClientCloak;
	pcRailServerCloak ServerCloak;
	pcRailServerPowerDisplayRequest ServerPowerDisplayRequest;
	pcRailClientSnapArrange ClientSnapArrange;
	pcRailServerGetAppidResponseExtended ServerGetAppidResponseExtended;
	pcRailClientCompartmentInfo ClientCompartmentInfo;
	pcRailOnOpen OnOpen;
};

#endif /* FREERDP_CHANNEL_RAIL_CLIENT_RAIL_H */


text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.core;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.Operands;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TFloat32;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.family.TType;

/**
 * Read an element from the TensorArray into output {@code value}.
 *
 * @param <T> data type for {@code value} output
 */
@OpMetadata(
    opType = TensorArrayRead.OP_NAME,
    inputsClass = TensorArrayRead.Inputs.class
)
@Operator
public final class TensorArrayRead<T extends TType> extends RawOp implements Operand<T> {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "TensorArrayReadV3";

  private Output<T> value;

  public TensorArrayRead(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    value = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new TensorArrayReadV3 operation.
   *
   * @param scope current scope
   * @param handle The handle to a TensorArray.
   * @param index The index value
   * @param flowIn A float scalar that enforces proper chaining of operations.
   * @param dtype The type of the elem that is returned.
   * @param <T> data type for {@code TensorArrayReadV3} output and operands
   * @return a new instance of TensorArrayRead
   */
  @Endpoint(
      describeByClass = true
  )
  public static <T extends TType> TensorArrayRead<T> create(Scope scope,
      Operand<? extends TType> handle, Operand<TInt32> index, Operand<TFloat32> flowIn,
      Class<T> dtype) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "TensorArrayRead");
    opBuilder.addInput(handle.asOutput());
    opBuilder.addInput(index.asOutput());
    opBuilder.addInput(flowIn.asOutput());
    opBuilder.setAttr("dtype", Operands.toDataType(dtype));
    return new TensorArrayRead<>(opBuilder.build());
  }

  /**
   * Gets value.
   * The tensor that is read from the TensorArray.
   * @return value.
   */
  public Output<T> value() {
    return value;
  }

  @Override
  public Output<T> asOutput() {
    return value;
  }

  @OpInputsMetadata(
      outputsClass = TensorArrayRead.class
  )
  public static class Inputs extends RawOpInputs<TensorArrayRead<?>> {
    /**
     * The handle to a TensorArray.
     */
    public final Operand<? extends TType> handle;

    /**
     * The index input
     */
    public final Operand<TInt32> index;

    /**
     * A float scalar that enforces proper chaining of operations.
     */
    public final Operand<TFloat32> flowIn;

    /**
     * The type of the elem that is returned.
     */
    public final DataType dtype;

    public Inputs(GraphOperation op) {
      super(new TensorArrayRead<>(op), op, Arrays.asList("dtype"));
      int inputIndex = 0;
      handle = (Operand<? extends TType>) op.input(inputIndex++);
      index = (Operand<TInt32>) op.input(inputIndex++);
      flowIn = (Operand<TFloat32>) op.input(inputIndex++);
      dtype = op.attributes().getAttrType("dtype");
    }
  }
}


text:
class AddCourseIdToRegistrations < ActiveRecord::Migration
  def change
    add_column :registrations, :course_id, :integer
  end
end


text:
package org.apache.wicket.security.util;

import java.util.Set;

import junit.framework.TestCase;

/**
 * @author marrink
 *
 */
public class ManyToManyMapTest extends TestCase
{

	/**
	 * @param name
	 */
	public ManyToManyMapTest(String name)
	{
		super(name);
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#add(java.lang.Object, java.lang.Object)}
	 * .
	 */
	public void testAdd()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		map.add("A.2", "A");
		map.add("A.1", "AB");
		map.add("A.2", "AB");
		map.add("B.1", "B");
		map.add("B.2", "B");
		map.add("B.1", "AB");
		map.add("B.2", "AB");
		map.add("C.1", "C");
		assertEquals(9, map.size());
		Set<String> manys = map.getRight("A.1");
		assertEquals(2, manys.size());
		assertTrue(manys.contains("A"));
		assertTrue(manys.contains("AB"));
		manys = map.getLeft("A");
		assertEquals(2, manys.size());
		assertTrue(manys.contains("A.1"));
		assertTrue(manys.contains("A.2"));
		manys = map.getLeft("AB");
		assertEquals(4, manys.size());
		assertTrue(manys.contains("A.1"));
		assertTrue(manys.contains("A.2"));
		assertTrue(manys.contains("B.1"));
		assertTrue(manys.contains("B.2"));
		manys = map.getLeft("C");
		assertEquals(1, manys.size());
		assertTrue(manys.contains("C.1"));
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#remove(java.lang.Object, java.lang.Object)}
	 * .
	 */
	public void testRemove()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		map.add("A.2", "A");
		assertEquals(3, map.size());
		assertTrue(map.remove("A.1", "A"));
		assertEquals(2, map.size());
		map.add("A.1", "A");
		assertEquals(3, map.size());

		map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		assertEquals(2, map.size());
		map.remove("A.1", "A");
		assertEquals(0, map.size());
		assertTrue(map.isEmpty());
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#removeAllMappingsForLeft(Object)}
	 * and right.
	 */
	public void testRemoveAllMappings()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		map.add("A.2", "A");
		Set<String> manys = map.removeAllMappingsForRight("A");
		assertEquals(0, map.size());
		assertTrue(manys.contains("A.1"));
		assertTrue(manys.contains("A.2"));

		map.add("A.1", "A");
		map.add("A.2", "A");
		map.add("A.2", "B");
		manys = map.removeAllMappingsForLeft("A.1");
		assertEquals(3, map.size());
		assertTrue(manys.contains("A"));
		assertFalse(manys.contains("B"));
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#getLeft(java.lang.Object)} .
	 */
	public void testGet()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		map.add("A.2", "A");
		Set<String> manys = map.getLeft("B");
		assertNotNull(manys);
		assertTrue(manys.isEmpty());
		manys = map.getLeft("A");
		assertFalse(manys.isEmpty());
		assertEquals(2, manys.size());
	}

	/**
	 * Test method for {@link org.apache.wicket.security.util.ManyToManyMap#size()}.
	 */
	public void testSize()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		assertEquals(0, map.size());
		map.add("A.1", "A");
		map.add("A.2", "A");
		assertEquals(3, map.size());
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#numberOfmappingsForLeft(Object)}
	 * and right.
	 */
	public void testNumberOfmappings()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		map.add("A.2", "A");
		assertEquals(2, map.numberOfmappingsForRight("A"));
		assertEquals(1, map.numberOfmappingsForLeft("A.1"));
		assertEquals(0, map.numberOfmappingsForRight("B"));
	}

	/**
	 * Test method for
	 * {@link org.apache.wicket.security.util.ManyToManyMap#containsLeft(Object)} and
	 * right.
	 */
	public void testContains()
	{
		ManyToManyMap<String, String> map = new ManyToManyMap<String, String>();
		map.add("A.1", "A");
		assertTrue(map.containsRight("A"));
		assertTrue(map.containsLeft("A.1"));
		assertFalse(map.containsLeft("A.2"));
	}

	/**
	 * Test method for {@link org.apache.wicket.security.util.ManyToManyMap#isEmpty()}.
	 */
	public void testIsEmpty()
	{
		assertTrue(new ManyToManyMap<String, String>().isEmpty());
	}

	/**
	 * Test method for {@link org.apache.wicket.security.util.ManyToManyMap#clear()}.
	 */
	public void testClear()
	{
		ManyToManyMap<Integer, Integer> map = new ManyToManyMap<Integer, Integer>();
		map.add(1, 10);
		assertFalse(map.isEmpty());
		map.clear();
		assertTrue(map.isEmpty());
	}

}


text: Rails.application.config.session_store :cookie_store, key: '_legislately_session'


text:
    <material-Panel>
        <material-row addStyleNames="code" height="1000px">
            <material-title title="Basic"
                            description="A pushpinned element has 3 states. One above (TOP) and below (BELOW) the scrolling threshold, and the pinned state where the element becomes fixed (OFFSET)."/>
            <material-row>
                <material-Panel data-field="source" grid="s12 m12 l12" backgroundColor="BLUE" paddingTop="50" shadow="1"
                                height="200px" width="200px">
                    <material-label textColor="WHITE" text="Pinned Options top at 300, offset at 64 (navbar's height)"/>
                </material-Panel>
            </material-row>

            MaterialPushpin.apply(source, 300.0, 64.0);

        </material-row>
    </material-Panel>


text:
.leaflet-control-loading {
    background: url(images/loading.gif);
}

.leaflet-control-loading,
.leaflet-control-zoom a.leaflet-control-loading ,
.leaflet-control-zoomslider a.leaflet-control-loading {
    display: none;
}

.leaflet-control-loading.is-loading,
.leaflet-control-zoom a.leaflet-control-loading.is-loading,
.leaflet-control-zoomslider a.leaflet-control-loading.is-loading  {
    display: block;
}

/* Necessary for display consistency in Leaflet >= 0.6 */
.leaflet-bar-part-bottom {
    border-bottom: medium none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
}


text:
El PaaS elejido es Heroku, por lo que para ello vamos a hacer una configuración específica para ese PaaS, como es el archivo Procfile, y el segundo paso se encuentra en el código donde se tiene que especificar a la aplicación express tanto IP como PORT a los que atiende.

Empezemos con la configuración del archivo **Procfile**.
Archivo simple de configurar en nuestro caso, donde se especifica una tarea, en concreto la necesaria para hecharla a andar

![ejer7_img1](http://googledrive.com/host/0B5Yam2FWqtZPOUY1RGEyY1ZKLXM/Ejercicio7_1.png)

Para terminar configuramos **IP** y **PORT**

![ejer7_img2](http://googledrive.com/host/0B5Yam2FWqtZPOUY1RGEyY1ZKLXM/Ejercicio7_2.png)

Para ello asignamos puerto e ip a la aplicación (Express) para más delante utilizarlos en la función 'listen' e indicar las ip y en que puerto.


text:
package com.conveyal.r5.transit;

import com.conveyal.gtfs.model.Frequency;
import com.conveyal.gtfs.model.Trip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * This represents the arrival and departure times of a single GTFS trip within a TripPattern.
 * If this is a frequency trip, it also records the different headways throughout the day, and when those headways
 * begin and end.
 */
public class TripSchedule implements Serializable, Comparable<TripSchedule>, Cloneable {

    private static final Logger LOG = LoggerFactory.getLogger(TripSchedule.class);

    public String tripId;

    public int[] arrivals;
    public int[] departures;

    /** if null, this trip is not frequency based */
    public int[] headwaySeconds = null;

    /** start times for frequency entries */
    public int[] startTimes = null;

    /** end times for frequency entries */
    public int[] endTimes = null;

    /** IDs for frequency entries */
    public String[] frequencyEntryIds;

    public int flags;
    public int serviceCode;
    public TripSchedule nextInBlock = null;

    // Phasing information: how does this frequency-based trip schedule interact with others?

    /**
     * Frequency entry each frequency entry on this trip is phased from. If the array is null, no entries are phased;
     * if any entry is null, that entry is not phased.
     */
    public String[] phaseFromId;

    /**
     * Scoped stop ID on this trip where this the phase is applied.
     */
    public String[] phaseAtStop;

    /** Scoped stop ID on source (phased-from) trip where the phase is applied */
    public String[] phaseFromStop;

    /**
     * Phase between trips. Applied to departure time except at last stop, where it is applied to arrival time.
     *
     * If the from and to trips have the same frequency, this is pretty straightforward. If they do not, it is slightly
     * more complicated, and the guarantee of phasing is weaker. We will make it so that one of the trips on this frequency
     * entry passes phaseSeconds after one of the trips on the other entry. We will also ensure that the headway of this
     * frequency entry is a factor or constant multiple of the headway of the other.
     *
     * TODO this works in the abstract, however what happens when the time windows of frequency entries are small and do
     * not start at the same time? I think there's a possibility that no trip would "fall into place" during the active
     * period of the frequency entry.
     */
    public int[] phaseSeconds;

    /**
     * The stop sequences of this trip in the GTFS. Unfortunately we need to store this at the trip level as every
     * trip on a pattern could have different stop sequence numbers. We need to save the sequence numbers so we can
     * uniquely identify stop positions in patterns in SetPhasing modifications (this could potentially be ripped out
     * when we change how setting phasing is done, for example by not allowing changing phasing on existing routes at all)
     *
     * TODO phasing now works differently, is this still needed?
     */
    public int[] stopSequences;

    /**
     * Static factory method, allowing us to return null for invalid inputs (unlike the constructor).
     * This is used when building a TransitLayer from GTFS, or when applying an AddTrips modification.
     *
     * @param frequencies "pure" frequency entries - the exact_times field is currently ignored, and exact_times
     *                    frequency expansion must be done before creating the TripSchedule.
     */
    public static TripSchedule create (Trip trip, int[] arrivals, int[] departures, Collection<Frequency> frequencies, int[] stopSequences, int serviceCode) {
        // ensure that trip times are monotonically increasing, otherwise throw them out
        for (int i = 0; i < arrivals.length; i++) {
            if (departures[i] < arrivals[i]) {
                LOG.error("Trip {} departs stop before it arrives, excluding this trip.", trip.trip_id);
                return null;
            }
            if (i > 0 && arrivals[i] < departures[i - 1]) {
                LOG.error("Trip {} arrives at a stop before departing the previous stop, excluding this trip.", trip.trip_id);
                return null;
            }
        }
        if (frequencies != null && !frequencies.isEmpty()) {
            if (frequencies.stream().allMatch(f -> f.end_time < f.start_time)) {
                LOG.error("All frequency entries on trip {} have end time before start time, excluding this trip.", trip.trip_id);
                return null;
            }
        }
        return new TripSchedule(trip, arrivals, departures, frequencies, stopSequences, serviceCode);
    }

    /**
     * TODO handle exact_times frequency entries from GTFS
     * @param frequencies "pure" frequency entries - the exact_times field is currently ignored, and exact_times
     *                    frequency expansion must be done before creating the TripSchedule.
     */
    private TripSchedule(Trip trip, int[] arrivals, int[] departures, Collection<Frequency> frequencies, int[] stopSequences, int serviceCode) {
        String scopedTripId = String.join(":", trip.feed_id, trip.trip_id);
        this.tripId = scopedTripId;
        if (trip.bikes_allowed == 1) {
            setFlag(TripFlag.BICYCLE);
        }
        if (trip.wheelchair_accessible == 1) {
            setFlag(TripFlag.WHEELCHAIR);
        }
        this.arrivals = arrivals;
        this.departures = departures;
        this.stopSequences = stopSequences;
        this.serviceCode = serviceCode;

        if (frequencies != null && !frequencies.isEmpty()) {

            // filter to valid frequencies
            // TODO some trips may have no service after this filter is applied
            frequencies = frequencies.stream().filter(f -> {
                boolean valid = f.start_time <= f.end_time;
                if (!valid) {
                    LOG.warn("Frequency entry for trip {} has end time before start time; it will not be used. " +
                            "Perhaps this is an issue with overnight service?", trip.trip_id);
                }
                return valid;
            }).collect(Collectors.toList());

            if (!frequencies.isEmpty()) {
                // this is a frequency-based trip
                this.headwaySeconds = new int[frequencies.size()];
                this.startTimes = new int[frequencies.size()];
                this.endTimes = new int[frequencies.size()];
                this.frequencyEntryIds = new String[frequencies.size()];
                // Shift all arrival and departure times to be zero-based on frequency-based trips
                if (arrivals.length > 0) {
                    int firstArrival = arrivals[0];
                    for (int i = 0; i < arrivals.length; i++) {
                        arrivals[i] -= firstArrival;
                    }
                    for (int i = 0; i < departures.length; i++) {
                        departures[i] -= firstArrival;
                    }
                }
                // TODO: Verify whether is is necessary or advantageous to sort frequency entries.
                int fidx = 0;
                for (Frequency f : frequencies) {
                    if (f.exact_times == 1) {
                        LOG.warn("GTFS frequency entries with exact_times are not supported, treating as inexact!");
                    }
                    this.headwaySeconds[fidx] = f.headway_secs;
                    this.endTimes[fidx] = f.end_time;
                    this.startTimes[fidx] = f.start_time;
                    // feed scope frequency IDs
                    this.frequencyEntryIds[fidx] = String.join(":", trip.feed_id, f.getId());
                    fidx++;
                }
            }
        }
    }

    public void setFlag (TripFlag tripFlag) {
        flags |= tripFlag.flag;
    }

    public boolean getFlag (TripFlag tripFlag) {
        return (flags & tripFlag.flag) != 0;
    }

    @Override
    public int compareTo(TripSchedule other) {
        return this.departures[0] - other.departures[0];
    }

    @Override
    public TripSchedule clone() {
        try {
            return (TripSchedule) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }

    /** return whether it makes sense for the supplied trip to be served by the same vehicle as this trip. */
    public void chainTo (TripSchedule that) {
        // Check that chain is temporally coherent
        if (arrivals[arrivals.length - 1] <= that.departures[0]) {
            // FIXME need to resolve ambiguity around service dates + block IDs.
            // nextInBlock = that;
        } else {
            // FIXME this error is extremely common in Portland because block IDs are recycled across service days.
            LOG.debug("Trip {} arrives at terminus after the next trip in its block departs.", tripId);
        }

    }

    /**
     * I can't think of any reason we need to use the first arrivals and last departure,
     * rather than the first departure and last arrival, given that we don't currently support interlining.
     * Once we support interlining, this will matter, as you might arrive at the first stop on an interline just inside the time window.
     *
     * @return whether any part of this occurs during the given time range (expressed in seconds after midnight).
     * TODO -- frequencies --
     */
    public boolean overlapsTimeRange (int fromTime, int toTime) {
        int firstStopTime, lastStopTime;

        if (this.headwaySeconds != null) {
            firstStopTime = Integer.MAX_VALUE;
            lastStopTime = Integer.MIN_VALUE;

            if (this.headwaySeconds.length == 0) {
                LOG.warn("Frequency trip has no frequency entries!");
                return false;
            }

            for (int i = 0; i < this.headwaySeconds.length; i++) {
                firstStopTime = Math.min(firstStopTime, this.startTimes[i]);
                // NB the last stop time on a frequency entry is the end time plus the travel time, as start/end times
                // represent the behavior at the first stop.
                lastStopTime = Math.max(lastStopTime, this.endTimes[i] + this.arrivals[this.arrivals.length - 1]);
            }
        }
        else {
            firstStopTime = departures[0];
            lastStopTime = arrivals[arrivals.length - 1];
        }

        return firstStopTime <= toTime && lastStopTime >= fromTime;
    }

    public int getNStops() {
        return arrivals.length;
    }

    public int nFrequencyEntries() {
        return headwaySeconds.length;
    }

}


text:
from bs4 import *
from urllib.request import urlopen
import re

url = input("Enter url:")
html = urlopen(url).read()
soup = BeautifulSoup(html)

sum = 0
spans = soup("span")
for span in spans:
    span = str(span)
    nums = re.findall(">([0-9]+)<",span)
    for num in nums:
        sum = sum + int(num)

print (sum)


text:
You can link to your Zulip organization from the web with a Zulip
[shields.io](https://github.com/badges/shields) badge:

[![Zulip chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://chat.zulip.org)

Good places for the badge include your project's landing page, support
pages, and/or GitHub homepage.

To embed a Zulip badge, copy and paste the following, replacing
`https://chat.zulip.org` with the URL of your Zulip organization:

Markdown
```
[![project chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://chat.zulip.org)
```

HTML
```
<a href="https://chat.zulip.org"><img src="https://img.shields.io/badge/zulip-join_chat-brightgreen.svg" /></a>
```

## Related articles

* [Link to a message or conversation](/help/link-to-a-message-or-conversation)