text:
'use strict';

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

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Table = require('material-ui/Table');

var _ClickAwayListener = require('material-ui/internal/ClickAwayListener');

var _ClickAwayListener2 = _interopRequireDefault(_ClickAwayListener);

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

var DataTablesTableBody = function (_TableBody) {
  (0, _inherits3.default)(DataTablesTableBody, _TableBody);

  function DataTablesTableBody() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, DataTablesTableBody);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = DataTablesTableBody.__proto__ || (0, _getPrototypeOf2.default)(DataTablesTableBody)).call.apply(_ref, [this].concat(args))), _this), _this.onCellDoubleClick = function (event, rowNumber, columnNumber) {
      event.stopPropagation();
      if (_this.props.onCellDoubleClick) {
        _this.props.onCellDoubleClick(rowNumber, _this.getColumnId(columnNumber), event);
      }
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(DataTablesTableBody, [{
    key: 'createRows',
    value: function createRows() {
      // console.log('value: function createRows() {, this', this);
      var _this2 = this;

      var numChildren = _react2.default.Children.count(this.props.children);
      var rowNumber = 0;
      var handlers = {
        onCellClick: this.onCellClick,
        onCellDoubleClick: this.onCellDoubleClick,
        onCellHover: this.onCellHover,
        onCellHoverExit: this.onCellHoverExit,
        onRowHover: this.onRowHover,
        onRowHoverExit: this.onRowHoverExit,
        onRowClick: this.onRowClick
      };

      return _react2.default.Children.map(this.props.children, function (child) {
        // console.log('return _react2.default.Children.map(this.props.children, function (child) {, child', child);
        if (_react2.default.isValidElement(child)) {
          // console.log('if (_react2.default.isValidElement(child)) {, child', child);
          // console.log('if (_react2.default.isValidElement(child)) {, rowNumber', rowNumber);
          // console.log('if (_react2.default.isValidElement(child)) {, _this2.isRowSelected', _this2.isRowSelected);
          // console.log('if (_react2.default.isValidElement(child)) {, _this2', _this2);
          var props = {
            hoverable: _this2.props.showRowHover,
            // selected: _this2.isRowSelected(rowNumber),
            selected: _this2.props.children[rowNumber].props.selected,
            striped: _this2.props.stripedRows && rowNumber % 2 === 0,
            rowNumber: rowNumber++
          };

          if (rowNumber === numChildren) {
            props.displayBorder = false;
          }

          // console.log('return _react2.default.Children.map(this.props.children, function (child) {, props', props);
          // console.log('return _react2.default.Children.map(this.props.children, function (child) {, _this2.isRowSelected', _this2.isRowSelected);

          var children = [_this2.createRowCheckboxColumn(props)];

          _react2.default.Children.forEach(child.props.children, function (child) {
            children.push(child);
          });

          return _react2.default.cloneElement(child, (0, _extends3.default)({}, props, handlers), children);
        }
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          style = _props.style,
          allRowsSelected = _props.isAllRowsSelected ? _props.allRowsSelected : undefined,
          // allRowsSelected = _props.isAllRowsSelected ? _props.allRowsSelected : _props.isAllRowsSelected,
          multiSelectable = _props.multiSelectable,
          onCellClick = _props.onCellClick,
          onCellDoubleClick = _props.onCellDoubleClick,
          onCellHover = _props.onCellHover,
          onCellHoverExit = _props.onCellHoverExit,
          onRowHover = _props.onRowHover,
          onRowHoverExit = _props.onRowHoverExit,
          onRowSelection = _props.onRowSelection,
          selectable = _props.selectable,
          deselectOnClickaway = _props.deselectOnClickaway,
          showRowHover = _props.showRowHover,
          stripedRows = _props.stripedRows,
          displayRowCheckbox = _props.displayRowCheckbox,
          preScanRows = _props.preScanRows,
          isAllRowsSelected = _props.isAllRowsSelected,
          other = (0, _objectWithoutProperties3.default)(_props, ['style', 'allRowsSelected', 'multiSelectable', 'onCellClick', 'onCellDoubleClick', 'onCellHover', 'onCellHoverExit', 'onRowHover', 'onRowHoverExit', 'onRowSelection', 'selectable', 'deselectOnClickaway', 'showRowHover', 'stripedRows', 'displayRowCheckbox', 'preScanRows', 'isAllRowsSelected']);
      var prepareStyles = this.context.muiTheme.prepareStyles;

      console.log(
          // 'allRowsSelected = _props.isAllRowsSelected ? _props.allRowsSelected : _props.isAllRowsSelected,',
          // '\n_props.isAllRowsSelected', _props.isAllRowsSelected,
          // '\n_props.allRowsSelected', _props.allRowsSelected,
          // '\nallRowsSelected', allRowsSelected,
      );

      return _react2.default.createElement(
        _ClickAwayListener2.default,
        { onClickAway: this.handleClickAway },
        _react2.default.createElement(
          'tbody',
          (0, _extends3.default)({ style: prepareStyles((0, _assign2.default)({}, style)) }, other),
          this.createRows()
        )
      );
    }
  }]);
  return DataTablesTableBody;
}(_Table.TableBody);

DataTablesTableBody.muiName = 'TableBody';
DataTablesTableBody.propTypes = {
  /**
   * @ignore
   * Set to true to indicate that all rows should be selected.
   */
  allRowsSelected: _propTypes2.default.bool,
  /**
   * Children passed to table body.
   */
  children: _propTypes2.default.node,
  /**
   * The css class name of the root element.
   */
  className: _propTypes2.default.string,
  /**
   * Controls whether or not to deselect all selected
   * rows after clicking outside the table.
   */
  deselectOnClickaway: _propTypes2.default.bool,
  /**
   * Controls the display of the row checkbox. The default value is true.
   */
  displayRowCheckbox: _propTypes2.default.bool,
  /**
   * @ignore
   * If true, multiple table rows can be selected.
   * CTRL/CMD+Click and SHIFT+Click are valid actions.
   * The default value is false.
   */
  multiSelectable: _propTypes2.default.bool,
  /**
   * @ignore
   * Callback function for when a cell is clicked.
   */
  onCellClick: _propTypes2.default.func,
  /**
   * @ignore
   * Customized handler
   * Callback function for when a cell is double clicked.
   */
  onCellDoubleClick: _propTypes2.default.func,
  /**
   * @ignore
   * Called when a table cell is hovered. rowNumber
   * is the row number of the hovered row and columnId
   * is the column number or the column key of the cell.
   */
  onCellHover: _propTypes2.default.func,
  /**
   * @ignore
   * Called when a table cell is no longer hovered.
   * rowNumber is the row number of the row and columnId
   * is the column number or the column key of the cell.
   */
  onCellHoverExit: _propTypes2.default.func,
  /**
   * @ignore
   * Called when a table row is hovered.
   * rowNumber is the row number of the hovered row.
   */
  onRowHover: _propTypes2.default.func,
  /**
   * @ignore
   * Called when a table row is no longer
   * hovered. rowNumber is the row number of the row
   * that is no longer hovered.
   */
  onRowHoverExit: _propTypes2.default.func,
  /**
   * @ignore
   * Called when a row is selected. selectedRows is an
   * array of all row selections. IF all rows have been selected,
   * the string "all" will be returned instead to indicate that
   * all rows have been selected.
   */
  onRowSelection: _propTypes2.default.func,
  /**
   * Controls whether or not the rows are pre-scanned to determine
   * initial state. If your table has a large number of rows and
   * you are experiencing a delay in rendering, turn off this property.
   */
  preScanRows: _propTypes2.default.bool,
  /**
   * @ignore
   * If true, table rows can be selected. If multiple
   * row selection is desired, enable multiSelectable.
   * The default value is true.
   */
  selectable: _propTypes2.default.bool,
  /**
   * If true, table rows will be highlighted when
   * the cursor is hovering over the row. The default
   * value is false.
   */
  showRowHover: _propTypes2.default.bool,
  /**
   * If true, every other table row starting
   * with the first row will be striped. The default value is false.
   */
  stripedRows: _propTypes2.default.bool,
  /**
   * Override the inline-styles of the root element.
   */
  style: _propTypes2.default.object
};
exports.default = DataTablesTableBody;


text:
layout: post
title: "Tests should read like prose"
description: ""
category: programming
tags: [software,programming]
---
{% include JB/setup %}

Expressing solutions to problems is at the heart of programming.
Cognitive load slows you down.
Not using natural language adds to the cognitive load.
Writing software benefits from using natural language.
This is something I think of very often in my work.

When using [JUnit](http://junit.org/) I use the Junit4 API `assertThat` whenever possible.
This enables me to write

```
assertThat(result, is(expected))
```

Compare this to Junit3

```
assertEquals(expected, result)
```

Junit5 is in development.
It surprised me to see that they are using what I perceived as "Junit3 syntax".
In the
[user guide](http://junit.org/junit5/docs/current/user-guide/#third-party-assertion-libraries)
we find the explanation.
The `assertThat` API is reserved for third party assertion libraries like hamcrest or assertj.
The more powerful API is open to extension and pluggable.

An excellent choice.

{% include share.html %}

redpajama_set_name: RedPajamaGithub


text:
Vim plugins are managed through vundle. You'll need to install vundle to get them.

`$ git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle`

Run :BundleInstall in vim.


text:
- [Open Source Automation Tools](https://opensource.com/life/16/3/5-open-source-home-automation-tools)

## Home Assistant Io

```sh
root@edison:~# source activate homeassistant
prepending /home/root/miniconda3/envs/homeassistant/bin to PATH
(homeassistant) root@edison:~#
```

```sh
(homeassistant) root@edison:~# pip install homeassistant
Collecting homeassistant
  Using cached homeassistant-0.22.1-py2.py3-none-any.whl
Collecting pyyaml<4,>=3.11 (from homeassistant)
  Using cached PyYAML-3.11.zip
Collecting eventlet==0.19.0 (from homeassistant)
  Using cached eventlet-0.19.0-py2.py3-none-any.whl
Collecting pytz>=2016.4 (from homeassistant)
  Using cached pytz-2016.4-py2.py3-none-any.whl
Collecting voluptuous==0.8.9 (from homeassistant)
  Using cached voluptuous-0.8.9.tar.gz
Collecting requests<3,>=2 (from homeassistant)
  Downloading requests-2.10.0-py2.py3-none-any.whl (506kB)
    100% |################################| 512kB 106kB/s
Requirement already satisfied (use --upgrade to upgrade): pip>=7.0.0 in ./minic)
Collecting jinja2>=2.8 (from homeassistant)
  Using cached Jinja2-2.8-py2.py3-none-any.whl
Collecting greenlet>=0.3 (from eventlet==0.19.0->homeassistant)
  Using cached greenlet-0.4.10.zip
Requirement already satisfied (use --upgrade to upgrade): setuptools>=0.6b1 in )
Collecting MarkupSafe (from jinja2>=2.8->homeassistant)
  Using cached MarkupSafe-0.23.tar.gz
Building wheels for collected packages: pyyaml, voluptuous, greenlet, MarkupSafe
  Running setup.py bdist_wheel for pyyaml ... done
  Stored in directory: /home/root/.cache/pip/wheels/4a/bf/14/d79994d19a59d4f73e6
  Running setup.py bdist_wheel for voluptuous ... done
  Stored in directory: /home/root/.cache/pip/wheels/7b/11/c5/b483b7bf53ce439854c
  Running setup.py bdist_wheel for greenlet ... done
  Stored in directory: /home/root/.cache/pip/wheels/e0/f2/33/6e4a562e7497e939311
  Running setup.py bdist_wheel for MarkupSafe ... done
  Stored in directory: /home/root/.cache/pip/wheels/a3/fa/dc/0198eed9ad95489b8a8
Successfully built pyyaml voluptuous greenlet MarkupSafe
Installing collected packages: pyyaml, greenlet, eventlet, pytz, voluptuous, ret
Successfully installed MarkupSafe-0.23 eventlet-0.19.0 greenlet-0.4.10 homeassi9
```

```sh
root@edison:~# hass
Home Assistant requires at least Python 3.4
```

```sh
root@edison:~# hass
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        Hello, and welcome to Home Assistant!

        We'll hope that we can make all your dreams come true.

        Here are some resources to get started:

         - Configuring Home Assistant:
           https://home-assistant.io/getting-started/configuration/

         - Available components:
           https://home-assistant.io/components/

         - Troubleshooting your configuration:
           https://home-assistant.io/getting-started/troubleshooting-configuration/

         - Getting help:
           https://home-assistant.io/help/

        This message is generated by the introduction component. You can
        disable it in configuration.yaml.

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package XrefMapper::CoreInfo;
use strict;
use warnings;

use vars '@ISA';
@ISA = qw{ XrefMapper::BasicMapper };

use XrefMapper::BasicMapper;

use Cwd;
use DBI;
use File::Basename;
use IPC::Open3;

# Get info from the core database.

# Need to load tables:-
#
# gene_transcript_translation
# gene_stable_id
# transcript_stable_id
# translation_stable_id

sub new {
  my($class, $mapper) = @_;

  my $self ={};
  bless $self,$class;
  $self->core($mapper->core);
  $self->xref($mapper->xref);
  $self->verbose($mapper->verbose);
  return $self;
}

sub get_core_data {
  my $self = shift;

  # gene_transcript_translation
  # gene_stable_id
  # transcript_stable_id
  # translation_stable_id

  # load table gene_transcript_translation

  $self->load_gene_transcript_translation();

  # load table xxx_stable_id

  $self->load_stable_ids();

  my $sth = $self->xref->dbc->prepare("insert into process_status (status, date) values('core_data_loaded',now())");
  $sth->execute();
  $sth->finish;

  return;
}

sub load_gene_transcript_translation{
  my ($self) = shift;

  my $ins_sth =  $self->xref->dbc->prepare("insert ignore into gene_transcript_translation (gene_id, transcript_id, translation_id) values (?, ?, ?)");

  my $sql = "select tn.gene_id, tn.transcript_id, tl.translation_id from transcript tn left join translation tl on tl.transcript_id = tn.transcript_id";
  my $sth = $self->core->dbc->prepare($sql);
  $sth->execute();
  my  ($gene_id, $transcript_id, $translation_id);
  $sth->bind_columns(\$gene_id, \$transcript_id, \$translation_id);
  while($sth->fetch()){
    $ins_sth->execute($gene_id, $transcript_id, $translation_id);
  }
  $ins_sth->finish;
  $sth->finish;
  return;
}

sub load_stable_ids{
  my ($self) = shift;

  my ($id, $stable_id, $biotype);
  foreach my $table (qw(gene translation)){

    my $sth = $self->core->dbc->prepare("select ".$table."_id, stable_id from ".$table);
    my $ins_sth = $self->xref->dbc->prepare("insert ignore into ".$table."_stable_id (internal_id, stable_id) values(?, ?)");
    $sth->execute();
    $sth->bind_columns(\$id, \$stable_id);
    while($sth->fetch){
      $ins_sth->execute($id, $stable_id);
    }
    $ins_sth->finish;
    $sth->finish;
  }

  #populate transcript_stable_id table incuding the biotype column
  my $table = "transcript";
  my $sth = $self->core->dbc->prepare("select ".$table."_id, stable_id, biotype from ".$table);
  my $ins_sth = $self->xref->dbc->prepare("insert ignore into ".$table."_stable_id (internal_id, stable_id, biotype) values(?, ?, ?)");
  $sth->execute();
  $sth->bind_columns(\$id, \$stable_id, \$biotype);
  while($sth->fetch){
    $ins_sth->execute($id, $stable_id, $biotype);
  }
  $ins_sth->finish;
  $sth->finish;

  return;
}
1;


text:
package com.me.diankun.aidlserver;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.me.diankun.firstcode.service.MyAIDLService;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private Button btn_access_aidlservice;

    //访问其他进程中的Service
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyAIDLService service = MyAIDLService.Stub.asInterface(iBinder);
            try {
                int result = service.plus(5, 10);
                String str = service.toUpperCase("welcome to use aidl");
                Log.i(TAG, "result = " + result + "\t str = " + str);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LayoutInflater.from(this);

        btn_access_aidlservice = (Button) findViewById(R.id.btn_access_aidlservice);
        btn_access_aidlservice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent("com.me.diankun.aidlservice.service.AIDLService2");
                //指定package
                i.setPackage("com.me.diankun.firstcode");
                bindService(i, conn, BIND_AUTO_CREATE);
            }
        });
    }
}


text:
package org.eigenbase.sql;

import java.util.Collection;
import java.util.EnumSet;
import java.util.Set;

/**
 * Enumerates the possible types of {@link SqlNode}.
 *
 *
The values are immutable, canonical constants, so you can use Kinds to
 * find particular types of expressions quickly. To identity a call to a common
 * operator such as '=', use {@link org.eigenbase.sql.SqlNode#isA}:
 *
 *

 *
exp.{@link org.eigenbase.sql.SqlNode#isA isA}({@link #EQUALS})

 *

 *
 *
Only commonly-used nodes have their own type; other nodes are of type
 * {@link #OTHER}. Some of the values, such as {@link #SET_QUERY}, represent
 * aggregates.

 *
 *
To identify a category of expressions, you can use
 * {@link org.eigenbase.sql.SqlNode#isA} with
 * an aggregate SqlKind. The following expression will return true
 * for calls to '=' and '>=', but false for the constant '5', or
 * a call to '+':

 *
 *

 *
exp.{@link org.eigenbase.sql.SqlNode#isA isA}({@link #COMPARISON SqlKind.Comparison})

 *

 *
 *
To quickly choose between a number of options, use a switch statement:

 *
 *

 *
switch (exp.getKind()) {
 * case {@link #EQUALS}:
 *     ...;
 * case {@link #NOT_EQUALS}:
 *     ...;
 * default:
 *     throw {@link org.eigenbase.util.Util#unexpected Util.unexpected}(exp.getKind());
 * }

 *

 */
public enum SqlKind {
  //~ Static fields/initializers ---------------------------------------------

  // the basics

  /**
   * Expression not covered by any other {@link SqlKind} value.
   *
   * @see #OTHER_FUNCTION
   */
  OTHER,

  /**
   * SELECT statement or sub-query.
   */
  SELECT,

  /**
   * JOIN operator or compound FROM clause.
   *
   *
A FROM clause with more than one table is represented as if it were a
   * join. For example, "FROM x, y, z" is represented as "JOIN(x, JOIN(x,
   * y))".

   */
  JOIN,

  /**
   * Identifier
   */
  IDENTIFIER,

  /**
   * A literal.
   */
  LITERAL,

  /**
   * Function that is not a special function.
   *
   * @see #FUNCTION
   */
  OTHER_FUNCTION,

  /**
   * EXPLAIN statement
   */
  EXPLAIN,

  /**
   * INSERT statement
   */
  INSERT,

  /**
   * DELETE statement
   */
  DELETE,

  /**
   * UPDATE statement
   */
  UPDATE,

  /**
   * "ALTER scope SET option = value" statement.
   */
  SET_OPTION,

  /**
   * A dynamic parameter.
   */
  DYNAMIC_PARAM,

  /**
   * ORDER BY clause.
   *
   * @see #DESCENDING
   * @see #NULLS_FIRST
   * @see #NULLS_LAST
   */
  ORDER_BY,

  /** WITH clause. */
  WITH,

  /** Item in WITH clause. */
  WITH_ITEM,

  /**
   * Union
   */
  UNION,

  /**
   * Except
   */
  EXCEPT,

  /**
   * Intersect
   */
  INTERSECT,

  /**
   * AS operator
   */
  AS,

  /**
   * OVER operator
   */
  OVER,

  /**
   * Window specification
   */
  WINDOW,

  /**
   * MERGE statement
   */
  MERGE,

  /**
   * TABLESAMPLE operator
   */
  TABLESAMPLE,

  // binary operators

  /**
   * The arithmetic multiplication operator, "*".
   */
  TIMES,

  /**
   * The arithmetic division operator, "/".
   */
  DIVIDE,

  /**
   * The arithmetic plus operator, "+".
   *
   * @see #PLUS_PREFIX
   */
  PLUS,

  /**
   * The arithmetic minus operator, "-".
   *
   * @see #MINUS_PREFIX
   */
  MINUS,

  // comparison operators

  /**
   * The "IN" operator.
   */
  IN,

  /**
   * The less-than operator, "<".
   */
  LESS_THAN,

  /**
   * The greater-than operator, ">".
   */
  GREATER_THAN,

  /**
   * The less-than-or-equal operator, "<=".
   */
  LESS_THAN_OR_EQUAL,

  /**
   * The greater-than-or-equal operator, ">=".
   */
  GREATER_THAN_OR_EQUAL,

  /**
   * The equals operator, "=".
   */
  EQUALS,

  /**
   * The not-equals operator, "!=" or "<>".
   */
  NOT_EQUALS,

  /**
   * The is-distinct-from operator.
   */
  IS_DISTINCT_FROM,

  /**
   * The is-not-distinct-from operator.
   */
  IS_NOT_DISTINCT_FROM,

  /**
   * The logical "OR" operator.
   */
  OR,

  /**
   * The logical "AND" operator.
   */
  AND,

  // other infix

  /**
   * Dot
   */
  DOT,

  /**
   * The "OVERLAPS" operator.
   */
  OVERLAPS,

  /**
   * The "LIKE" operator.
   */
  LIKE,

  /**
   * The "SIMILAR" operator.
   */
  SIMILAR,

  /**
   * The "BETWEEN" operator.
   */
  BETWEEN,

  /**
   * A "CASE" expression.
   */
  CASE,

  // prefix operators

  /**
   * The logical "NOT" operator.
   */
  NOT,

  /**
   * The unary plus operator, as in "+1".
   *
   * @see #PLUS
   */
  PLUS_PREFIX,

  /**
   * The unary minus operator, as in "-1".
   *
   * @see #MINUS
   */
  MINUS_PREFIX,

  /**
   * The "EXISTS" operator.
   */
  EXISTS,

  /**
   * The "VALUES" operator.
   */
  VALUES,

  /**
   * Explicit table, e.g. select * from (TABLE t) or TABLE
   * t. See also {@link #COLLECTION_TABLE}.
   */
  EXPLICIT_TABLE,

  /**
   * Scalar query; that is, a subquery used in an expression context, and
   * returning one row and one column.
   */
  SCALAR_QUERY,

  /**
   * ProcedureCall
   */
  PROCEDURE_CALL,

  /**
   * NewSpecification
   */
  NEW_SPECIFICATION,

  // postfix operators

  /**
   * DESC in ORDER BY. A parse tree, not a true expression.
   */
  DESCENDING,

  /**
   * NULLS FIRST clause in ORDER BY. A parse tree, not a true expression.
   */
  NULLS_FIRST,

  /**
   * NULLS LAST clause in ORDER BY. A parse tree, not a true expression.
   */
  NULLS_LAST,

  /**
   * The "IS TRUE" operator.
   */
  IS_TRUE,

  /**
   * The "IS FALSE" operator.
   */
  IS_FALSE,

  /**
   * The "IS UNKNOWN" operator.
   */
  IS_UNKNOWN,

  /**
   * The "IS NULL" operator.
   */
  IS_NULL,

  /**
   * The "PRECEDING" qualifier of an interval end-point in a window
   * specification.
   */
  PRECEDING,

  /**
   * The "FOLLOWING" qualifier of an interval end-point in a window
   * specification.
   */
  FOLLOWING,

  /**
   * The field access operator, ".".
   *
   *
(Only used at the RexNode level; at
   * SqlNode level, a field-access is part of an identifier.)

   */
  FIELD_ACCESS,

  /**
   * Reference to an input field.
   *
   *
(Only used at the RexNode level.)

   */
  INPUT_REF,

  /**
   * Reference to a sub-expression computed within the current relational
   * operator.
   *
   *
(Only used at the RexNode level.)

   */
  LOCAL_REF,

  /**
   * Reference to correlation variable.
   *
   *
(Only used at the RexNode level.)

   */
  CORREL_VARIABLE,

  // functions

  /**
   * The row-constructor function. May be explicit or implicit:
   * {@code VALUES 1, ROW (2)}.
   */
  ROW,

  /**
   * The non-standard constructor used to pass a
   * COLUMN_LIST parameter to a user-defined transform.
   */
  COLUMN_LIST,

  /**
   * The "CAST" operator.
   */
  CAST,

  /**
   * The "TRIM" function.
   */
  TRIM,

  /**
   * Call to a function using JDBC function syntax.
   */
  JDBC_FN,

  /**
   * The MULTISET value constructor.
   */
  MULTISET_VALUE_CONSTRUCTOR,

  /**
   * The MULTISET query constructor.
   */
  MULTISET_QUERY_CONSTRUCTOR,

  /**
   * The "UNNEST" operator.
   */
  UNNEST,

  /**
   * The "LATERAL" qualifier to relations in the FROM clause.
   */
  LATERAL,

  /**
   * Table operator which converts user-defined transform into a relation, for
   * example, select * from TABLE(udx(x, y, z)). See also the
   * {@link #EXPLICIT_TABLE} prefix operator.
   */
  COLLECTION_TABLE,

  /**
   * Array Value Constructor, e.g. {@code Array[1, 2, 3]}.
   */
  ARRAY_VALUE_CONSTRUCTOR,

  /**
   * Array Query Constructor, e.g. {@code Array(select deptno from dept)}.
   */
  ARRAY_QUERY_CONSTRUCTOR,

  /**
   * Map Value Constructor, e.g. {@code Map['washington', 1, 'obama', 44]}.
   */
  MAP_VALUE_CONSTRUCTOR,

  /**
   * Map Query Constructor, e.g. {@code MAP (SELECT empno, deptno FROM emp)}.
   */
  MAP_QUERY_CONSTRUCTOR,

  /**
   * CURSOR constructor, for example, select * from
   * TABLE(udx(CURSOR(select ...), x, y, z))
   */
  CURSOR,

  // internal operators (evaluated in validator) 200-299

  /**
   * Literal chain operator (for composite string literals).
   * An internal operator that does not appear in SQL syntax.
   */
  LITERAL_CHAIN,

  /**
   * Escape operator (always part of LIKE or SIMILAR TO expression).
   * An internal operator that does not appear in SQL syntax.
   */
  ESCAPE,

  /**
   * The internal REINTERPRET operator (meaning a reinterpret cast).
   * An internal operator that does not appear in SQL syntax.
   */
  REINTERPRET;

  //~ Static fields/initializers ---------------------------------------------

  // Most of the static fields are categories, aggregating several kinds into
  // a set.

  /**
   * Category consisting of set-query node types.
   *
   *
Consists of:
   * {@link #EXCEPT},
   * {@link #INTERSECT},
   * {@link #UNION}.
   */
  public static final EnumSet<SqlKind> SET_QUERY =
      EnumSet.of(UNION, INTERSECT, EXCEPT);

  /**
   * Category consisting of all expression operators.
   *
   *
A node is an expression if it is NOT one of the following:
   * {@link #AS},
   * {@link #DESCENDING},
   * {@link #SELECT},
   * {@link #JOIN},
   * {@link #OTHER_FUNCTION},
   * {@link #CAST},
   * {@link #TRIM},
   * {@link #LITERAL_CHAIN},
   * {@link #JDBC_FN},
   * {@link #PRECEDING},
   * {@link #FOLLOWING},
   * {@link #ORDER_BY},
   * {@link #COLLECTION_TABLE},
   * {@link #TABLESAMPLE}.
   */
  public static final Set<SqlKind> EXPRESSION =
      EnumSet.complementOf(
          EnumSet.of(
              AS, DESCENDING, SELECT, JOIN, OTHER_FUNCTION, CAST, TRIM,
              LITERAL_CHAIN, JDBC_FN, PRECEDING, FOLLOWING, ORDER_BY,
              NULLS_FIRST, NULLS_LAST, COLLECTION_TABLE, TABLESAMPLE,
              WITH, WITH_ITEM));

  /**
   * Category consisting of all DML operators.
   *
   *
Consists of:
   * {@link #INSERT},
   * {@link #UPDATE},
   * {@link #DELETE},
   * {@link #MERGE},
   * {@link #PROCEDURE_CALL}.
   *
   *
NOTE jvs 1-June-2006: For now we treat procedure calls as DML;
   * this makes it easy for JDBC clients to call execute or
   * executeUpdate and not have to process dummy cursor results.  If
   * in the future we support procedures which return results sets,
   * we'll need to refine this.
   */
  public static final EnumSet<SqlKind> DML =
      EnumSet.of(INSERT, DELETE, UPDATE, MERGE, PROCEDURE_CALL);

  /**
   * Category consisting of query node types.
   *
   *
Consists of:
   * {@link #SELECT},
   * {@link #EXCEPT},
   * {@link #INTERSECT},
   * {@link #UNION},
   * {@link #VALUES},
   * {@link #ORDER_BY},
   * {@link #EXPLICIT_TABLE}.
   */
  public static final EnumSet<SqlKind> QUERY =
      EnumSet.of(SELECT, UNION, INTERSECT, EXCEPT, VALUES, WITH, ORDER_BY,
          EXPLICIT_TABLE);

  /**
   * Category of all SQL statement types.
   *
   *
Consists of all types in {@link #QUERY} and {@link #DML}.
   */
  public static final Set<SqlKind> TOP_LEVEL = plus(QUERY, DML);

  /**
   * Category consisting of regular and special functions.
   *
   *
Consists of regular functions {@link #OTHER_FUNCTION} and special
   * functions {@link #ROW}, {@link #TRIM}, {@link #CAST}, {@link #JDBC_FN}.
   */
  public static final Set<SqlKind> FUNCTION =
      EnumSet.of(OTHER_FUNCTION, ROW, TRIM, CAST, JDBC_FN);

  /**
   * Category of comparison operators.
   *
   *
Consists of:
   * {@link #IN},
   * {@link #EQUALS},
   * {@link #NOT_EQUALS},
   * {@link #LESS_THAN},
   * {@link #GREATER_THAN},
   * {@link #LESS_THAN_OR_EQUAL},
   * {@link #GREATER_THAN_OR_EQUAL}.
   */
  public static final Set<SqlKind> COMPARISON =
      EnumSet.of(
          IN, EQUALS, NOT_EQUALS,
          LESS_THAN, GREATER_THAN,
          GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL);

  /**
   * Returns whether this {@code SqlKind} belongs to a given category.
   *
   *
A category is a collection of kinds, not necessarily disjoint. For
   * example, QUERY is { SELECT, UNION, INTERSECT, EXCEPT, VALUES, ORDER_BY,
   * EXPLICIT_TABLE }.
   *
   * @param category Category
   * @return Whether this kind belongs to the given category
   */
  public final boolean belongsTo(Collection<SqlKind> category) {
    return category.contains(this);
  }

  private static <E extends Enum<E>> EnumSet<E> plus(EnumSet<E> set0,
      EnumSet<E> set1) {
    EnumSet<E> set = set0.clone();
    set.addAll(set1);
    return set;
  }
}

// End SqlKind.java


text:
<!DOCTYPE html >

          <title>Mongo Scala Driver</title>
          <meta name="description" content="Mongo Scala Driver" />
          <meta name="keywords" content="Mongo Scala Driver" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

EPSG_4326

NamedCoordinateReferenceSystem

EPSG_4326_STRICT_WINDING

NamedCoordinateReferenceSystem

elemMatch

Filters Projections

empty

Document Document

encode

ImmutableDocumentCodec MutableDocumentCodec

eq

Filters

equal

Filters

exclude

Projections

excludeId

Projections

exists

Filters


text:
while nc -q 1 ${CASS_HOST} ${CASS_PORT} < /dev/null; do sleep 10; echo "Awaiting cassandra"; done

cd /app
exec /sbin/setuser app java -javaagent:/app/lib/jamm.jar -cp ".:/app/etc" -jar /app/lib/usergrid-launcher.jar -nogui --port 8080


text:
from __future__ import print_function

import numpy as np
import argparse
import os
import sys
import signal
import time
import socket
from contextlib import closing
from six import string_types
import math
import paddle
import paddle.fluid as fluid
import paddle.fluid.profiler as profiler
import paddle.fluid.unique_name as nameGen
from paddle.fluid import core
import unittest
from multiprocessing import Process
import paddle.fluid.layers as layers
from functools import reduce
from test_collective_base import TestCollectiveRunnerBase, runtime_main

class TestCollectiveBroadcast(TestCollectiveRunnerBase):
    def __init__(self):
        self.global_ring_id = 0

    def get_model(self, main_prog, startup_program):
        ring_id = 0
        rootid = 1
        with fluid.program_guard(main_prog, startup_program):
            tindata = layers.data(
                name="tindata", shape=[10, 1000], dtype='float32')
            toutdata = main_prog.current_block().create_var(
                name="outofbroadcast",
                dtype='float32',
                type=core.VarDesc.VarType.LOD_TENSOR,
                persistable=False,
                stop_gradient=False)
            main_prog.global_block().append_op(
                type="c_broadcast",
                inputs={'X': tindata},
                attrs={'ring_id': ring_id,
                       'root': rootid},
                outputs={'Out': toutdata})
            main_prog.global_block().append_op(
                type="c_sync_comm_stream",
                inputs={'X': toutdata},
                outputs={'Out': toutdata},
                attrs={'ring_id': ring_id})
            return toutdata

if __name__ == "__main__":
    runtime_main(TestCollectiveBroadcast, "broadcast", 0)


text:
/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_CVARIANTBINARYSERIALIZER_H
#include "gucefCORE_CVariantBinarySerializer.h"
#define GUCEF_CORE_CVARIANTBINARYSERIALIZER_H
#endif /* GUCEF_CORE_CVARIANTBINARYSERIALIZER_H ? */

#ifndef GUCEF_CORE_CDATANODE_H
#include "CDataNode.h"
#define GUCEF_CORE_CDATANODE_H
#endif /* GUCEF_CORE_CDATANODE_H ? */

#ifndef GUCEF_CORE_LOGGING_H
#include "gucefCORE_Logging.h"
#define GUCEF_CORE_LOGGING_H
#endif /* GUCEF_CORE_LOGGING_H ? */

#ifndef GUCEF_PUBSUB_CPUBSUBCLIENTFEATURES_H
#include "gucefPUBSUB_CPubSubClientFeatures.h"
#define GUCEF_PUBSUB_CPUBSUBCLIENTFEATURES_H
#endif /* GUCEF_PUBSUB_CPUBSUBCLIENTFEATURES_H ? */

#include "gucefPUBSUB_CPubSubMsgBinarySerializer.h"

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

namespace GUCEF {
namespace PUBSUB {

/*-------------------------------------------------------------------------//
//                                                                         //
//      IMPLEMENTATION                                                     //
//                                                                         //
//-------------------------------------------------------------------------*/

CPubSubMsgBinarySerializerOptions::CPubSubMsgBinarySerializerOptions( void )
    : msgIdIncluded( true )
    , msgIndexIncluded( true )
    , msgDateTimeIncluded( true )
    , msgDateTimeAsMsSinceUnixEpochInUtc( true )
    , msgPrimaryPayloadIncluded( true )
    , msgKeyValuePairsIncluded( true )
    , msgMetaDataKeyValuePairsIncluded( true )
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------*/

CPubSubMsgBinarySerializerOptions::~CPubSubMsgBinarySerializerOptions()
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializerOptions::SaveConfig( CORE::CDataNode& config ) const
{GUCEF_TRACE;

    config.SetAttribute( "msgDateTimeIncluded", msgDateTimeIncluded );
    config.SetAttribute( "msgDateTimeAsMsSinceUnixEpochInUtc", msgDateTimeAsMsSinceUnixEpochInUtc );
    config.SetAttribute( "msgIdIncluded", msgIdIncluded );
    config.SetAttribute( "msgIndexIncluded", msgIndexIncluded );
    config.SetAttribute( "msgPrimaryPayloadIncluded", msgPrimaryPayloadIncluded );
    config.SetAttribute( "msgKeyValuePairsIncluded", msgKeyValuePairsIncluded );
    config.SetAttribute( "msgMetaDataKeyValuePairsIncluded", msgMetaDataKeyValuePairsIncluded );

    return true;
}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializerOptions::LoadConfig( const CORE::CDataNode& config )
{GUCEF_TRACE;

    msgDateTimeIncluded = config.GetAttributeValueOrChildValueByName( "msgDateTimeIncluded" ).AsBool( msgDateTimeIncluded, true );
    msgDateTimeAsMsSinceUnixEpochInUtc = config.GetAttributeValueOrChildValueByName( "msgDateTimeAsMsSinceUnixEpochInUtc" ).AsBool( msgDateTimeAsMsSinceUnixEpochInUtc, true );
    msgIdIncluded = config.GetAttributeValueOrChildValueByName( "msgIdIncluded" ).AsBool( msgIdIncluded, true );
    msgIndexIncluded = config.GetAttributeValueOrChildValueByName( "msgIndexIncluded" ).AsBool( msgIndexIncluded, true );
    msgPrimaryPayloadIncluded = config.GetAttributeValueOrChildValueByName( "msgPrimaryPayloadIncluded" ).AsBool( msgPrimaryPayloadIncluded, true );
    msgKeyValuePairsIncluded = config.GetAttributeValueOrChildValueByName( "msgKeyValuePairsIncluded" ).AsBool( msgKeyValuePairsIncluded, true );
    msgMetaDataKeyValuePairsIncluded = config.GetAttributeValueOrChildValueByName( "msgMetaDataKeyValuePairsIncluded" ).AsBool( msgMetaDataKeyValuePairsIncluded, true );
    return true;
}

/*-------------------------------------------------------------------------*/

const CString&
CPubSubMsgBinarySerializerOptions::GetClassTypeName( void ) const
{GUCEF_TRACE;

    static const CString classTypeName = "GUCEF::PUBSUB::CPubSubMsgBinarySerializerOptions";
    return classTypeName;
}

/*-------------------------------------------------------------------------*/

UInt32
CPubSubMsgBinarySerializerOptions::ToOptionsBitMask( void ) const
{GUCEF_TRACE;

    UInt32 bitMask = 0;
    msgDateTimeIncluded ? GUCEF_SETBITXON( bitMask, 1 ) : GUCEF_SETBITXOFF( bitMask, 1 );
    msgDateTimeAsMsSinceUnixEpochInUtc ? GUCEF_SETBITXON( bitMask, 2 ) : GUCEF_SETBITXOFF( bitMask, 2 );
    msgIdIncluded ? GUCEF_SETBITXON( bitMask, 3 ) : GUCEF_SETBITXOFF( bitMask, 3 );
    msgIndexIncluded ? GUCEF_SETBITXON( bitMask, 4 ) : GUCEF_SETBITXOFF( bitMask, 4 );
    msgPrimaryPayloadIncluded ? GUCEF_SETBITXON( bitMask, 5 ) : GUCEF_SETBITXOFF( bitMask, 5 );
    msgKeyValuePairsIncluded ? GUCEF_SETBITXON( bitMask, 6 ) : GUCEF_SETBITXOFF( bitMask, 6 );
    msgMetaDataKeyValuePairsIncluded ? GUCEF_SETBITXON( bitMask, 7 ) : GUCEF_SETBITXOFF( bitMask, 7 );
    return bitMask;
}

/*-------------------------------------------------------------------------*/

void
CPubSubMsgBinarySerializerOptions::FromOptionsBitMask( UInt32 bitMask )
{GUCEF_TRACE;

    msgDateTimeIncluded = ( 0 != GUCEF_GETBITX( bitMask, 1 ) );
    msgDateTimeAsMsSinceUnixEpochInUtc = ( 0 != GUCEF_GETBITX( bitMask, 2 ) );
    msgIdIncluded = ( 0 != GUCEF_GETBITX( bitMask, 3 ) );
    msgIndexIncluded = ( 0 != GUCEF_GETBITX( bitMask, 4 ) );
    msgPrimaryPayloadIncluded = ( 0 != GUCEF_GETBITX( bitMask, 5 ) );
    msgKeyValuePairsIncluded = ( 0 != GUCEF_GETBITX( bitMask, 6 ) );
    msgMetaDataKeyValuePairsIncluded = ( 0 != GUCEF_GETBITX( bitMask, 7 ) );
}

/*-------------------------------------------------------------------------*/

void
CPubSubMsgBinarySerializerOptions::FromPubSubClientFeatures( const CPubSubClientFeatures& features )
{GUCEF_TRACE;

    msgDateTimeIncluded = features.supportsMsgDateTimeBasedBookmark;
    msgDateTimeAsMsSinceUnixEpochInUtc = true;
    msgIdIncluded = features.supportsPerMsgIds;
    msgIndexIncluded = features.supportsMsgIndex;
    msgPrimaryPayloadIncluded = features.supportsPrimaryPayloadPerMsg;
    msgKeyValuePairsIncluded = features.supportsKeyValueSetPerMsg;
    msgMetaDataKeyValuePairsIncluded = features.supportsMetaDataKeyValueSetPerMsg;
}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializer::SerializeKvPairs( const CIPubSubMsg::TKeyValuePairs& kvPairs ,
                                              UInt32 currentTargetOffset                 ,
                                              CORE::CDynamicBuffer& target               ,
                                              UInt32& bytesWritten                       )
{GUCEF_TRACE;

    UInt32 nrOfKvPairs = (UInt32) kvPairs.size();
    UInt32 lastBytesWritten = target.CopyFrom( currentTargetOffset, sizeof(nrOfKvPairs), &nrOfKvPairs );
    currentTargetOffset += lastBytesWritten;
    bytesWritten += lastBytesWritten;

    CIPubSubMsg::TKeyValuePairs::const_iterator i = kvPairs.begin();
    while ( i != kvPairs.end() )
    {
        const CORE::CVariant& key = (*i).first;
        const CORE::CVariant& value = (*i).second;

        UInt32 varBinSize = 0;
        if ( !CORE::CVariantBinarySerializer::Serialize( key, currentTargetOffset, target, varBinSize ) )
            return false;
        currentTargetOffset += varBinSize;
        bytesWritten += varBinSize;

        varBinSize = 0;
        if ( !CORE::CVariantBinarySerializer::Serialize( value, currentTargetOffset, target, varBinSize ) )
            return false;
        currentTargetOffset += varBinSize;
        bytesWritten += varBinSize;

        ++i;
    }
    return true;
}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializer::Serialize( const CPubSubMsgBinarySerializerOptions& options ,
                                       const CIPubSubMsg& msg                           ,
                                       UInt32 currentTargetOffset                       ,
                                       CORE::CDynamicBuffer& target                     ,
                                       UInt32& bytesWritten                             )
{GUCEF_TRACE;

    try
    {
        if ( options.msgDateTimeIncluded )
        {
            if ( options.msgDateTimeAsMsSinceUnixEpochInUtc )
            {
                // Write the DateTime of the msg as milliseconds since Unix Epoch in UTC
                // In most applications Unix Epoch is not UTC and leap seconds are not taken into account
                // However since the source if of higher fidelity we can retain accuracy as long as the same method is
                // used to deserialize as well. There is a problem with any DateTime which predates Unix epoch
                // If you have to deal with those use string formatting instead
                UInt64 msSinceUnixEpochInUtc = msg.GetMsgDateTime().ToUnixEpochBasedTicksInMillisecs();
                UInt32 lastBytesWritten = target.CopyFrom( currentTargetOffset, sizeof(msSinceUnixEpochInUtc), &msSinceUnixEpochInUtc );
                currentTargetOffset += lastBytesWritten;
                bytesWritten += lastBytesWritten;
            }
            else
            {
                // Write the DateTime of the msg which as a ISO 8601 spec string
                // Writing it in string form actually takes up less space vs writing all the binary components at full fidelity
                // Using Unix epoch uses less space but we are limited in the time range since historical dates would be a problem
                Int32 dtStrSize = msg.GetMsgDateTime().ToIso8601DateTimeString( target, currentTargetOffset, false, true );
                if ( 0 >= dtStrSize )
                    return false;
                currentTargetOffset += (UInt32) dtStrSize;
                bytesWritten += (UInt32) dtStrSize;
            }
        }

        if ( options.msgIdIncluded )
        {
            // Write the ID using the variable length variant serializer
            UInt32 varBinSize = 0;
            if ( !CORE::CVariantBinarySerializer::Serialize( msg.GetMsgId(), currentTargetOffset, target, varBinSize ) )
                return false;
            currentTargetOffset += varBinSize;
            bytesWritten += varBinSize;
        }

        if ( options.msgIndexIncluded )
        {
            // Write the index using the variable length variant serializer
            UInt32 varBinSize = 0;
            if ( !CORE::CVariantBinarySerializer::Serialize( msg.GetMsgIndex(), currentTargetOffset, target, varBinSize ) )
                return false;
            currentTargetOffset += varBinSize;
            bytesWritten += varBinSize;
        }

        if ( options.msgPrimaryPayloadIncluded )
        {
            // Now write the primary payload if any exists
            const CORE::CVariant& primaryPayload = msg.GetPrimaryPayload();
            UInt32 varBinSize = 0;
            if ( !CORE::CVariantBinarySerializer::Serialize( primaryPayload, currentTargetOffset, target, varBinSize ) )
                return false;
            currentTargetOffset += varBinSize;
            bytesWritten += varBinSize;
        }

        if ( options.msgKeyValuePairsIncluded )
        {
            UInt32 kvPairsSize = 0;
            const CIPubSubMsg::TKeyValuePairs& kvPairs = msg.GetKeyValuePairs();
            if ( !SerializeKvPairs( kvPairs, currentTargetOffset, target, kvPairsSize ) )
                return false;
            currentTargetOffset += kvPairsSize;
            bytesWritten += kvPairsSize;
        }

        if ( options.msgMetaDataKeyValuePairsIncluded )
        {
            UInt32 kvPairsSize = 0;
            const CIPubSubMsg::TKeyValuePairs& kvPairs = msg.GetMetaDataKeyValuePairs();
            if ( !SerializeKvPairs( kvPairs, currentTargetOffset, target, kvPairsSize ) )
                return false;
            currentTargetOffset += kvPairsSize;
            bytesWritten += kvPairsSize;
        }
        return true;
    }
    catch ( const std::exception& e )
    {
        GUCEF_EXCEPTION_LOG( CORE::LOGLEVEL_NORMAL, CString( "PubSubMsgBinarySerializer:Serialize: caught exception: " ) + e.what()  );
        return false;
    }
}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializer::DeserializeKvPairs( bool linkWherePossible               ,
                                                CIPubSubMsg::TKeyValuePairs& kvPairs ,
                                                UInt32 currentSourceOffset           ,
                                                const CORE::CDynamicBuffer& source   ,
                                                UInt32& bytesRead                    )
{GUCEF_TRACE;

    // Now read the key-value pairs if any exists

    UInt32 nrOfKvPairs = source.AsConstType< UInt32 >( currentSourceOffset );
    currentSourceOffset += sizeof(nrOfKvPairs);
    bytesRead += sizeof(nrOfKvPairs);

    if ( nrOfKvPairs > 0 )
    {
        // Next is a basic sanity check
        // this is not full proof since the bytes needed for all kv pairs depends on the types of the variants used
        // however we do know that even if its a NIL variant or similar the smallest size is 1 byte hence we need at minimum nrOfKvPairs*2
        UInt32 bytesRemaining = source.GetDataSize() - currentSourceOffset;
        if ( nrOfKvPairs*2 > bytesRemaining )
        {
            GUCEF_WARNING_LOG( CORE::LOGLEVEL_NORMAL, "PubSubMsgBinarySerializer:DeserializeKvPairs: nrOfKvPairs (" + CORE::ToString( nrOfKvPairs ) + ") cannot fit into " +
                CORE::ToString( bytesRemaining ) + " bytes available, data is corrupt" );
            return false;
        }

        kvPairs.clear();
        kvPairs.resize( nrOfKvPairs );

        CIPubSubMsg::TKeyValuePairs::iterator i = kvPairs.begin();
        while ( i != kvPairs.end() )
        {
            CORE::CVariant& key = (*i).first;
            CORE::CVariant& value = (*i).second;

            UInt32 varByteSize = 0;
            if ( !CORE::CVariantBinarySerializer::Deserialize( key, currentSourceOffset, source, linkWherePossible, varByteSize ) )
                return false;
            currentSourceOffset += varByteSize;
            bytesRead += varByteSize;

            varByteSize = 0;
            if ( !CORE::CVariantBinarySerializer::Deserialize( value, currentSourceOffset, source, linkWherePossible, varByteSize ) )
                return false;
            currentSourceOffset += varByteSize;
            bytesRead += varByteSize;

            ++i;
        }
    }

    return true;
}

/*-------------------------------------------------------------------------*/

bool
CPubSubMsgBinarySerializer::Deserialize( const CPubSubMsgBinarySerializerOptions& options ,
                                         bool linkWherePossible                           ,
                                         CIPubSubMsg& msg                                 ,
                                         UInt32 currentSourceOffset                       ,
                                         const CORE::CDynamicBuffer& source               ,
                                         UInt32& bytesRead                                )
{GUCEF_TRACE;

    try
    {
        if ( options.msgDateTimeIncluded )
        {
            if ( options.msgDateTimeAsMsSinceUnixEpochInUtc )
            {
                // Read the DateTime of the msg which is milliseconds since Unix epoch in UTC IF
                // this class's Serialize() was used. Commonly used Unix epoch variables do NOT have a
                // timezone associated nor does the Unix epoch offset in a lot of implementations take
                // leap seconds into account. Hence choose carefully to ensure consistency in interpretation
                UInt64 msSinceUnixEpochInUtc = source.AsConstType< UInt64 >( currentSourceOffset );
                currentSourceOffset += sizeof(msSinceUnixEpochInUtc);
                bytesRead += sizeof(msSinceUnixEpochInUtc);

                msg.GetMsgDateTime().FromUnixEpochBasedTicksInMillisecs( msSinceUnixEpochInUtc );
            }
            else
            {
                // Read the DateTime of the msg which is a ISO 8601 format string
                Int32 dtStrSize = msg.GetMsgDateTime().FromIso8601DateTimeString( source, currentSourceOffset );
                if ( 0 >= dtStrSize )
                    return false;
                currentSourceOffset += (UInt32) dtStrSize;
                bytesRead += (UInt32) dtStrSize;
            }
        }

        if ( options.msgIdIncluded )
        {
            // Write the ID using the variable length variant serializer
            UInt32 varByteSize = 0;
            if ( !CORE::CVariantBinarySerializer::Deserialize( msg.GetMsgId(), currentSourceOffset, source, linkWherePossible, varByteSize ) )
                return false;
            currentSourceOffset += varByteSize;
            bytesRead += varByteSize;
        }

        if ( options.msgIndexIncluded )
        {
            // Write the msg index using the variable length variant serializer
            UInt32 varByteSize = 0;
            if ( !CORE::CVariantBinarySerializer::Deserialize( msg.GetMsgIndex(), currentSourceOffset, source, linkWherePossible, varByteSize ) )
                return false;
            currentSourceOffset += varByteSize;
            bytesRead += varByteSize;
        }

        if ( options.msgPrimaryPayloadIncluded )
        {
            // Now read the primary payload if any exists
            UInt32 varByteSize = 0;
            if ( !CORE::CVariantBinarySerializer::Deserialize( msg.GetPrimaryPayload(), currentSourceOffset, source, linkWherePossible, varByteSize ) )
                return false;
            currentSourceOffset += varByteSize;
            bytesRead += varByteSize;
        }

        if ( options.msgKeyValuePairsIncluded )
        {
            UInt32 kvPairsByteSize = 0;
            CIPubSubMsg::TKeyValuePairs& kvPairs = msg.GetKeyValuePairs();
            if ( !DeserializeKvPairs( linkWherePossible, kvPairs, currentSourceOffset, source, kvPairsByteSize ) )
                return false;
            currentSourceOffset += kvPairsByteSize;
            bytesRead += kvPairsByteSize;
        }

        if ( options.msgMetaDataKeyValuePairsIncluded )
        {
            UInt32 kvPairsByteSize = 0;
            CIPubSubMsg::TKeyValuePairs& kvPairs = msg.GetMetaDataKeyValuePairs();
            if ( !DeserializeKvPairs( linkWherePossible, kvPairs, currentSourceOffset, source, kvPairsByteSize ) )
                return false;
            currentSourceOffset += kvPairsByteSize;
            bytesRead += kvPairsByteSize;
        }

        return true;
    }
    catch ( const std::exception& e )
    {
        GUCEF_EXCEPTION_LOG( CORE::LOGLEVEL_NORMAL, CString( "PubSubMsgBinarySerializer:Deserialize: caught exception: " ) + e.what()  );
        return false;
    }
}

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

}; /* namespace PUBSUB */
}; /* namespace GUCEF */

/*-------------------------------------------------------------------------*/


text:
'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _IconBase = require('./../components/IconBase/IconBase');

var _IconBase2 = _interopRequireDefault(_IconBase);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var IosInformationOutline = function (_React$Component) {
	_inherits(IosInformationOutline, _React$Component);

	function IosInformationOutline() {
		_classCallCheck(this, IosInformationOutline);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(IosInformationOutline).apply(this, arguments));
	}

	_createClass(IosInformationOutline, [{
		key: 'render',
		value: function render() {
			if (this.props.bare) {
				return _react2.default.createElement(
					'g',
					null,
					_react2.default.createElement(
						'g',
						null,
						_react2.default.createElement(
							'g',
							null,
							_react2.default.createElement('circle', { cx: '251.5', cy: '172', r: '20' }),
							_react2.default.createElement('polygon', { points: '272,344 272,216 224,216 224,224 240,224 240,344 224,344 224,352 288,352 288,344 \t\t' })
						),
						_react2.default.createElement(
							'g',
							null,
							_react2.default.createElement('path', { d: 'M256,48C141.1,48,48,141.1,48,256c0,114.9,93.1,208,208,208c114.9,0,208-93.1,208-208C464,141.1,370.9,48,256,48z M256,446.7c-105.1,0-190.7-85.5-190.7-190.7c0-105.1,85.5-190.7,190.7-190.7c105.1,0,190.7,85.5,190.7,190.7 C446.7,361.1,361.1,446.7,256,446.7z' })
						)
					)
				);
			}return _react2.default.createElement(
				_IconBase2.default,
				null,
				_react2.default.createElement(
					'g',
					null,
					_react2.default.createElement(
						'g',
						null,
						_react2.default.createElement('circle', { cx: '251.5', cy: '172', r: '20' }),
						_react2.default.createElement('polygon', { points: '272,344 272,216 224,216 224,224 240,224 240,344 224,344 224,352 288,352 288,344 \t\t' })
					),
					_react2.default.createElement(
						'g',
						null,
						_react2.default.createElement('path', { d: 'M256,48C141.1,48,48,141.1,48,256c0,114.9,93.1,208,208,208c114.9,0,208-93.1,208-208C464,141.1,370.9,48,256,48z M256,446.7c-105.1,0-190.7-85.5-190.7-190.7c0-105.1,85.5-190.7,190.7-190.7c105.1,0,190.7,85.5,190.7,190.7 C446.7,361.1,361.1,446.7,256,446.7z' })
					)
				)
			);
		}
	}]);

	return IosInformationOutline;
}(_react2.default.Component);

exports.default = IosInformationOutline;
;IosInformationOutline.defaultProps = { bare: false };


text:
import Repository from '../Repository';
import { snapshot } from '../../../shared/test';

describe('components/container/Repository', () => {
  snapshot({
    component: Repository,
    name: 'Repository',
  });
});


text:
<!doctype html>

    <title>Code coverage report for All files</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="prettify.css" />
    <link rel="stylesheet" href="base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      /

        82.42%
        Statements
        150/182

        74.77%
        Branches
        80/107

        100%
        Functions
        12/12

        82.42%
        Lines
        150/182

   File

   Statements

   Branches

   Functions

   Lines

	src/

	82.42%
	150/182
	74.77%
	80/107
	100%
	12/12
	82.42%
	150/182

  Code coverage
  generated by istanbul at Fri Sep 02 2016 22:30:43 GMT+0100 (GMT Daylight Time)


text:
using System;

namespace Azure.ResourceManager.NotificationHubs.Models
{
    /// <summary> Description of a NotificationHub WnsCredential. </summary>
    public partial class NotificationHubWnsCredential
    {
        /// <summary> Initializes a new instance of NotificationHubWnsCredential. </summary>
        public NotificationHubWnsCredential()
        {
        }

        /// <summary> Initializes a new instance of NotificationHubWnsCredential. </summary>
        /// <param name="packageSid"> The package ID for this credential. </param>
        /// <param name="secretKey"> The secret key. </param>
        /// <param name="windowsLiveEndpoint"> The Windows Live endpoint. </param>
        internal NotificationHubWnsCredential(string packageSid, string secretKey, Uri windowsLiveEndpoint)
        {
            PackageSid = packageSid;
            SecretKey = secretKey;
            WindowsLiveEndpoint = windowsLiveEndpoint;
        }

        /// <summary> The package ID for this credential. </summary>
        public string PackageSid { get; set; }
        /// <summary> The secret key. </summary>
        public string SecretKey { get; set; }
        /// <summary> The Windows Live endpoint. </summary>
        public Uri WindowsLiveEndpoint { get; set; }
    }
}


text:
package extrabiomes.core;

import java.util.HashSet;
import java.util.Iterator;

import net.minecraft.world.biome.BiomeGenBase;

import com.google.common.collect.Sets;

import cpw.mods.fml.common.IWorldGenerator;
import extrabiomes.lib.Const;
import extrabiomes.lib.IEBXSMod;

public enum BiomeRegistry {
	INSTANCE;

	// every ebxs mod registered with us
	private HashSet<IEBXSMod> mods;

	// every biome id requested by a config file we are responsible for
	private final boolean[]   configBiomes = new boolean[BiomeGenBase.getBiomeGenArray().length];

	private BiomeRegistry() {
		mods = Sets.newHashSet();
	}

	public static boolean register(IEBXSMod mod, String apiVersion) {
		final String modName = mod.getClass().getSimpleName();
		Core.LOGGER.info("Got registration request from %s.", modName);
		if( !apiVersion.equals(Const.API_VERSION) ) {
			Core.LOGGER.error("-- %s is running mismatched EBXS api version %s (%s expected)",
					modName, apiVersion, Const.API_VERSION);
		}
		return INSTANCE.mods.add(mod);
	}

	public static Iterator<IEBXSMod> iterator() {
		return INSTANCE.mods.iterator();
	}

	public static void addWorldGenerator(IWorldGenerator generator) {
		// TODO Auto-generated method stub

	}

	/// Request a new biome id
	public static int getBiomeID(int defaultID) {
		return INSTANCE._getBiomeID(defaultID);
	}
	private int _getBiomeID(int defaultID) {
		// set to 0 or -1 to "disable"
		if( defaultID < 1 )
			return defaultID;

		// check if the id requested is available
		if( BiomeGenBase.getBiomeGenArray()[defaultID] == null && !configBiomes[defaultID]) {
			configBiomes[defaultID] = true;
			return defaultID;
		}

		// check for warning case where we've seen this ID before
		if( configBiomes[defaultID] ) {
			Core.LOGGER.warn("CONFLICT @ Biome ID %d.", defaultID);
		}
		// find an empty biome ID and log it
		for( int k = 0; k < configBiomes.length -1; ++k ) {
			if( BiomeGenBase.getBiomeGenArray()[k] == null && !configBiomes[k] ) {
				Core.LOGGER.debug("Found unclaimed Biome ID %d", k);
				configBiomes[k] = true;
				return k;
			}
		}

		throw new RuntimeException("No more Biome ID's available.");
	}

	public static void dump() {
		Core.LOGGER.info(":: beginning biome dump ::");
		for( BiomeGenBase biome : BiomeGenBase.getBiomeGenArray() ) {
			if( biome == null ) continue;
			if( INSTANCE.configBiomes[biome.biomeID] )
				Core.LOGGER.info("<%3d>  %s", biome.biomeID, biome.biomeName);
			else
				Core.LOGGER.info(" %3d - %s", biome.biomeID, biome.biomeName);
		}
		Core.LOGGER.info(":: end of biome dump ::");
	}
}


text:
'use strict';

/**
 * Module dependencies
 */

var utils = require('lazy-cache')(require);

/**
 * Lazily required module dependencies
 */

var fn = require;
require = utils;
require('archy');
require('base-tree', 'tree');
require('ansi-colors', 'colors');
require('union-value', 'union');
require('question-cache', 'Questions');
require = fn;

/**
 * Expose `utils` module
 */

module.exports = utils;


text:
						{{img.name}}

				Select


text:
memoization-utils
=================
Utilities for memoizing functions

## License
This code is licensed under the MIT license for Pedro Tacla Yamada. For more
information please refer to the [LICENSE](/LICENSE) file.

## Donations
Would you like to buy me a beer? Send bitcoin to 3JjxJydvoJjTrhLL86LGMc8cNB16pTAF3y


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

namespace Reflow.Tasks
{
    public class TaskLink
    {
        private Dictionary<string, string> _taskPipe = new Dictionary<string, string>();
        public ITask LastTask  { get; set; }
        public ITask NextTask { get; set; }
        public Dictionary<string, string> TaskPipe { get { return _taskPipe; }}

        public void Bind()
        {
            LastTask.OnAfterExecution += this.OnExecute;
        }

        private void OnExecute(TaskExecutionContext context, TaskResult result)
        {
            if (result.Output != null)
            {
                Type type = NextTask.GetType();
                foreach(  string key in TaskPipe.Keys)
                {
                    PropertyInfo pi = type.GetProperty(key);
                    pi.SetValue(NextTask, result.Output[TaskPipe[key]], (object[])null);
                }
            }
        }
    }
}


text:
!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Steven Kim</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/landing-page.css" rel="stylesheet">

    <link href="css/mycss.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                stevenjkim.me

                        About

                        Work

                        Contact

                        Resume

 Collaborative Graphical Editor

 Developed in Java, the Collaborative Graphical Editor to allow multiple
        users to design and edit simple designs at the same time.

 There are five components to this project:

            An editor sends requests to, according to the user's commands,
            and receives requests from the editor communicator. Its state
            is updated according to the command the editor communicator passes on.

            An editor communicator sends requests to and receives requests
            from the sketch server communicator.

            Handle message is a middleman that intercepts requests to the
            editor communicator and the sketch server communicator. Because all
            forms of communication is done through strings, it analyzes which
            commands need to be executed according to the string that is passed.

            A sketch server communicator sends requests to the server and
            receives requests from the editor communicator.

            The sketch server  updates the overall state and passes it onto clients.

 Four options were implemented: 'draw', 'move', 'recolor', and 'delete'.
        The user can draw an ellipse, rectangle, a polyline(free drawing line), or
        a straight line. The user can also select any color of his/her choice.

Copyright © Steven Joo Hyun Kim 2017. All Rights Reserved


text:
layout: post
title:  "Project - Building an IoT Light using Texas Instruments Parts"
author: ipv1
description: "An IoT Enabled Light design using TPS92512 and CC3200"
image: assets/images/iotlight/splash.png
categories:
  - Project
tags:
  - CC3200
  - HTML
  - JavaScript
---

An IoT Enabled Light design using TPS92512 and CC3200

Original Post is at: https://e2e.ti.com/blogs_/b/powerhouse/archive/2016/06/17/designing-an-iot-modular-light

## Introduction

In the first installment of this two-part series, I talked about an illuminating idea I had for a project I could use in my newborn baby's room: an Internet of Things (IoT) modular light. I've done the prep, so now let's create the prototype.

## Creating a prototype

As shown in the block diagram in Figure 1 from the previous post, a TI SimpleLink™ Wi-Fi® CC3200 wireless microcontroller (MCU) LaunchPad™ development kit connected to the TPS92512 drives a light-emitting diode (LED) array. I used a 12V switch-mode power supply as the power source and wrote the firmware for the CC3200 using Energia. You could also write the firmware using Code Composer Studio™ integrated development environment (IDE) software, which is my favorite tool, but in this case, the example code and Arduino-like interface accelerated the prototyping stage immensely.

I set up the CC3200 wireless MCU LaunchPad kit with the latest firmware and programmed the kit to talk to a particular topic at the Message Queue Telemetry Transport (MQTT) broker. MQTT is a protocol with very small overhead and allows for a server/client topology to create communication connections over the Internet. Facebook Messenger uses MQTT, and it is one of the more popular protocol projects being tuned to power the future IoT.

For my project, I also designed a small printed circuit board (PCB) that I framed as a Booster Pack™ plug-in module; the result is shown in Figure 1. You can stack a number of these PCBs to achieve the required number of LED drive channels.

![alt text](/assets/images/iotlight/b1.png){: .align-center}

Figure 1: A screenshot of the schematic for the TPS92512 BoosterPack

I was able to fit the design into a 50mm-by-50mm form factor, which would reduce manufacturing costs if mass-produced. Figure 2 shows a screenshot of the final layout which has four mounting holes as well as the BoosterPack module pin conformity.

![alt text](/assets/images/iotlight/b2.png){: .align-center}

Figure 2: Screenshot of the final layout for the TPS92512 BoosterPack

I used the schematic and layout from the evaluation module as a guide.
Würth Elektronik provided the coils as well as the electromechanical parts, which was a big help since they made the footprints for all of the parts available as well. Getting the board design ready was a breeze. Printing the layout and checking the footprints as shown in Figure 3, confirmed that everything was indeed in order.

![alt text](/assets/images/iotlight/b3.png){: .align-center}

Figure 3: Footprint verification via 1:1 paper print of the layout

## The Web client design

With my basic understanding of HTML, Code Composer Studio IDE and JavaScript®, I was able to create a simple user interface (UI) for my project. The idea was to create buttons in a web interface and then use JavaScript to send the commands via MQTT to the broker and finally to the IoT light. I used the Paho library in JavaScript and performed a bit of cosmetic surgery via Code Composer Studio to create a webpage that looks nice; Figure 4 is a screenshot.

![alt text](/assets/images/iotlight/b4.png){: .align-center}

Figure 4: The live webpage for remote control

I kind of went overboard with the home-automation front end, but you get the idea. I wanted a look-and-feel I would be willing to pay money for. In the end, four buttons was all I needed and they worked out pretty well. The page uses Twitter Bootstrap, which means the same webpage will look different on different screen sizes.

## The love and romance

I had worked out the technical details of the project, but it was more or less a science project. The real evolution came when my wife suggested that I turn the prototype into a real product for our own use. We were expecting a baby at the time and she requested a room light whose brightness we could control remotely. The same light would be usable as a room light, a night-light and a midnight-diaper-change light. Instead of 3-D printing an enclosure or something, I decided to recycle an old LCD monitor, some glass and a birthday card from before we were married. The romance was still alive and it was time to light things up. The manual layout of the components inside the enclosure is shown in Figure 5.

![alt text](/assets/images/iotlight/b5.png){: .align-center}

Figure 5: Various modules laid out in the recycled PC monitor

## Putting humpty dumpty together was fun and the finished product is shown in Figure 6.

![alt text](/assets/images/iotlight/b6.png){: .align-center}

Figure 6: The final product

The final product is not particularly a product so much as a piece of technology fused with a personalized artifact. Our baby currently enjoys staring at the final outcome above his crib and we are thankful for it.

<iframe width="560" height="315" src="https://www.youtube.com/embed/0IOaaPuzCQU" frameborder="0" allowfullscreen></iframe>

## Future work

I am currently working on creating a grow light for indoor hydroponic farming based on the same concept, which thus represents an additional application. Security was never important for this demo but is crucial for IoT products, so I am working to implement a more secure solution. I am experimenting with Raspberry Pi as a local broker, as well as considering porting the entire web UI to the SimpleLink Wi-Fi CC3200 device itself. Both solutions are viable but cannot be an IoT solution, since they will no longer require an Internet connection nor be accessible over the Internet.

## Conclusion

This project is a proof of concept but with a personal touch. I have had a lot of requests from friends to make one for them. So far I have declined, but maybe in the future I can provide a Phillips Hues alternative.
The important thing about this project is it proves it is quite easy to come up with an IoT prototype quickly and easily with the amount of resources available. Thanks to Texas Instruments, Würth Elektronik and element14 for their support. The future is indeed bright.

## Additional resources

- [Read my blog on element14 for a more detailed description of the CC3200 setup, upgrades and programming, along with details about the board design.](https://www.element14.com/community/community/tags#/? tags=ip_modular_light)
- [Access the code for the firmware at my GitHub repository.](https://github.com/inderpreet/babylight)
- [View a demo of the Web UI.](https://inderpreet.github.io/homeautomationui/babylight/)


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsCloud::Image::VolumeBundle::Volume::DatabaseDetails;
use Moose;
use CHI;

has 'myd_path' => (isa => 'Str' , is => 'rw', required => 1);
has 'name' => (isa => 'Str', is => 'rw', required => 1 ) ;
has 'size' => (isa => 'Str', is => 'rw', required => 1);
has 'type' => (isa => 'Str', is => 'rw', required => 1);
has 'copy_path' => (isa => 'Str', is => 'rw', );
has 'is_copied' => (isa => 'Str', is => 'rw', required => 1, default => 0);

1;

__END__


text:
import React from 'react';
import {
  TextInput,
  SafeAreaView,
  View,
  Text,
  StyleSheet,
  ScrollView,
  StyleProp,
  ViewStyle,
  LayoutChangeEvent,
} from 'react-native';
import { Keyboard } from 'react-native-ui-lib';
import flags from '../flags';
import testIDs from '../testIDs';

const KeyboardAwareInsetsView = Keyboard.KeyboardAwareInsetsView;
const { showTextInputToTestKeyboardInteraction } = flags;

type RootProps = {
  componentId?: string;
  style?: StyleProp<ViewStyle>;
  footer?: string;
  testID?: string;
  children?: React.ReactNode;
  onLayout?: (event: LayoutChangeEvent) => void;
};

const Root = ({ children, componentId, footer, style, testID, onLayout }: RootProps) => (
  <SafeAreaView style={styles.root} testID={testID} onLayout={onLayout}>
    <ScrollView contentContainerStyle={[styles.scrollView, style]}>
      {children}
      <Footer componentId={componentId} footer={footer} />
    </ScrollView>
    {showTextInputToTestKeyboardInteraction && <KeyboardAwareInsetsView />}
  </SafeAreaView>
);

type FooterProps = Pick<RootProps, 'componentId' | 'footer'>;

const Footer: React.FC<FooterProps> = ({ componentId, footer }) => {
  if (!componentId) {
    return null;
  }

  return (
    <View style={styles.footer}>
      {/* Rendering TextInput for a test. */}
      {showTextInputToTestKeyboardInteraction && (
        <TextInput placeholder="Input" style={styles.testInput} />
      )}

      {/* Rendering Footer. */}
      {footer && <Text style={styles.footerText}>{footer}</Text>}

      {/* Rendering component id. */}
      <Text
        testID={testIDs.FOOTER_TEXT}
        style={styles.footerText}
      >{`this.props.componentId = ${componentId}`}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  root: {
    flex: 1,
  },
  scrollView: {
    flexGrow: 1,
    alignItems: 'center',
    padding: 16,
  },
  testInput: {
    borderWidth: 1,
    borderRadius: 10,
    height: 40,
    width: 100,
  },
  footer: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  footerText: {
    fontSize: 10,
    color: '#888',
    marginTop: 10,
    backgroundColor: 'yellow',
  },
});

export default Root;


text:
If your application needs to count the number of shared, this gem can help you.

## Install

Add to your Gemfile and run the `bundle` command to install it.

```ruby
gem "sharer"
```
## Source

Sharer's Git repo is available on GitHub, which can be browsed at:

```ruby
http://github.com/14113/sharer
```

and cloned with:

```ruby
git clone git://github.com/14113/sharer.git
```

## Usage

Call Sharer in an Model and pass the url of the website.

```ruby
site = Sharer::Site.new("google.com")
number_of_likes = site.facebook_likes
number_of_shares = site.facebook_shares
number_of_tweets_buttons = site.twitter_button
number_of_linkedin_shares = site.linked_in_share

# or all together by threads
hash = site.find_all
```

This will find count of shareing in facebook, twitter abd linkedin.

This gem is created by Adam Martinik and is under the MIT License.


text:
using System;
using System.Text;
using Apache.Http.Entity.Mime;
using Apache.Http.Entity.Mime.Content;
using Sharpen;

namespace Apache.Http.Entity.Mime
{
    /// <summary>
    /// FormBodyPart class represents a content body that can be used as a part of multipart encoded
    /// entities.
    /// </summary>
    /// <remarks>
    /// FormBodyPart class represents a content body that can be used as a part of multipart encoded
    /// entities. This class automatically populates the header with standard fields based on
    /// the content description of the enclosed body.
    /// </remarks>
    /// <since>4.0</since>
    public class FormBodyPart
    {
        private readonly string name;

        private readonly Header header;

        private readonly ContentBody body;

        public FormBodyPart(string name, ContentBody body) : base()
        {
            if (name == null)
            {
                throw new ArgumentException("Name may not be null");
            }
            if (body == null)
            {
                throw new ArgumentException("Body may not be null");
            }
            this.name = name;
            this.body = body;
            this.header = new Header();
            GenerateContentDisp(body);
            GenerateContentType(body);
            GenerateTransferEncoding(body);
        }

        public virtual string GetName()
        {
            return this.name;
        }

        public virtual ContentBody GetBody()
        {
            return this.body;
        }

        public virtual Header GetHeader()
        {
            return this.header;
        }

        public virtual void AddField(string name, string value)
        {
            if (name == null)
            {
                throw new ArgumentException("Field name may not be null");
            }
            this.header.AddField(new MinimalField(name, value));
        }

        protected internal virtual void GenerateContentDisp(ContentBody body)
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append("attachment");
            if (body.GetFilename() != null)
            {
                buffer.Append("; filename=\"");
                buffer.Append(body.GetFilename());
                buffer.Append("\"");
            }
            AddField(MIME.ContentDisposition, buffer.ToString());
        }

        protected internal virtual void GenerateContentType(ContentBody body)
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append(body.GetMimeType());
            // MimeType cannot be null
            if (body.GetCharset() != null)
            {
                // charset may legitimately be null
                buffer.Append("; charset=");
                buffer.Append(body.GetCharset());
            }
            AddField(MIME.ContentType, buffer.ToString());
        }

        protected internal virtual void GenerateTransferEncoding(ContentBody body)
        {
            AddField(MIME.ContentTransferEnc, body.GetTransferEncoding());
        }
        // TE cannot be null
    }
}


text:
<?php

namespace Da\OAuthServerBundle\Controller;

use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use Da\AuthCommonBundle\Exception\InvalidApiTokenException;

class ClientController extends FOSRestController implements ClassResourceInterface
{
    /**
     * [GET] /clients/{apiToken}
     * Retrieve a client from its API token.
     *
     * @param string $apiToken The API token.
     */
    public function getAction($apiToken)
    {
        try {
            $data = $this->container->get('da_oauth_server.client_manager.doctrine')
                ->retrieveClientByApiToken($apiToken)
            ;
        } catch (InvalidApiTokenException $e) {
            $view = $this->view($e->getMessage(), 404);
        }

        if (empty($data)) {
            $view = $this->view('Client not found.', 404);
        } else {
            $view = $this->view($data, 200);
        }

        return $this->handleView($view);
    }
}


text:
<!DOCTYPE html>

  <title>Inspire</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
  <link rel="stylesheet" href="css/style.css">


text:
package org.ospokemon.manager.sqlite;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ospokemon.Ability;
import org.ospokemon.Builder;
import org.ospokemon.JPokemonException;
import org.ospokemon.Manager;
import org.ospokemon.Property;

import com.njkremer.Sqlite.DataConnectionException;
import com.njkremer.Sqlite.SqlStatement;

/**
 * Provides SqliteORM bindings for {@link Ability abilities}. Optionally
 * provides {@link Ability#properties} using the {@link Property#builders}
 *
 * @author zach
 *
 * @since 0.1
 */
public class SqliteAbilityManager implements Manager<Ability> {
	@Override
	public Ability create() {
		return new Ability();
	}

	@Override
	public boolean isRegistered(String id) {
		return get(id) != null;
	}

	@Override
	public List<Ability> getAll() throws JPokemonException {
		List<Ability> abilities = new ArrayList<Ability>();

		try {
			for (Table.Ability abilityRow : SqlStatement.select(Table.Ability.class).getList()) {
				Ability ability = create();
				ability.setId(abilityRow.getId());
				ability.setName(abilityRow.getName());
				ability.setDescription(abilityRow.getDescription());

				buildAbilityProperties(ability);
				abilities.add(ability);
			}
		} catch (DataConnectionException e) {
			throw new JPokemonException(e);
		}

		return abilities;
	}

	@Override
	public Ability get(String id) throws JPokemonException {
		Ability ability = null;

		try {
			Table.Ability abilityRow = SqlStatement.select(Table.Ability.class).where("id").eq(id).getFirst();

			if (abilityRow != null) {
				ability = create();
				ability.setId(abilityRow.getId());
				ability.setName(abilityRow.getName());
				ability.setDescription(abilityRow.getDescription());
				buildAbilityProperties(ability);
			}
		} catch (DataConnectionException e) {
			throw new JPokemonException(e);
		}

		return ability;
	}

	@Override
	public void register(Ability ability) throws JPokemonException {
		if (ability == null) {
			throw new JPokemonException("Cannot register null ability");
		}
		if (ability.getId() == null) {
			throw new JPokemonException("Cannot register ability without an id: " + ability);
		}
		if (isRegistered(ability.getId())) {
			throw new JPokemonException("An ability is already registered with id: " + ability.getId());
		}

		try {
			Table.Ability abilityRow = new Table.Ability(ability);
			SqlStatement.insert(abilityRow).execute();
			insertAbilityProperties(ability);
		} catch (DataConnectionException e) {
			throw new JPokemonException(e);
		}
	}

	@Override
	public void update(Ability ability) throws JPokemonException {
		if (ability == null) {
			throw new JPokemonException("Cannot register null ability");
		}
		if (ability.getId() == null) {
			throw new JPokemonException("Cannot register ability without an id: " + ability);
		}
		if (!isRegistered(ability.getId())) {
			throw new JPokemonException("An ability is not registered with id: " + ability.getId());
		}

		try {
			Table.Ability abilityRow = new Table.Ability(ability);
			SqlStatement.update(abilityRow).where("id").eq(ability.getId()).execute();
			updateAbilityProperties(ability);
		} catch (DataConnectionException e) {
			throw new JPokemonException(e);
		}
	}

	@Override
	public void unregister(String id) throws JPokemonException {
		if (id == null) {
			throw new JPokemonException("Cannot unregister ability without an id");
		}

		try {
			SqlStatement.delete(Table.Ability.class).where("id").eq(id).execute();
			deleteAbilityProperties(id);
		} catch (DataConnectionException e) {
			throw new JPokemonException(e);
		}
	}

	private static void buildAbilityProperties(Ability ability) throws DataConnectionException {
		List<Table.AbilityProperty> propertyRows = SqlStatement.select(Table.AbilityProperty.class).where("abilityId").eq(ability.getId()).getList();

		for (Table.AbilityProperty propertyRow : propertyRows) {
			Builder<Object> builder = Property.builders.get(propertyRow.getPropertyId());
			Object property;

			if (builder != null) {
				property = builder.construct(propertyRow.getOptions());
			}
			else {
				property = propertyRow.getOptions();
			}

			ability.setProperty(propertyRow.getPropertyId(), property);
		}
	}

	private static void insertAbilityProperties(Ability ability) throws DataConnectionException {
		String abilityId = ability.getId();

		for (Map.Entry<String, Object> propertyEntry : ability.getProperties().entrySet()) {
			String propertyId = propertyEntry.getKey();
			Object property = propertyEntry.getValue();
			String options = null;

			Builder<Object> builder = Property.builders.get(propertyId);
			if (builder != null) {
				options = builder.destruct(property);
			}
			else {
				options = property.toString();
			}

			Table.AbilityProperty propertyRow = new Table.AbilityProperty(abilityId, propertyId, options);
			SqlStatement.insert(propertyRow).execute();
		}
	}

	private static void updateAbilityProperties(Ability ability) throws DataConnectionException {
		deleteAbilityProperties(ability.getId());
		insertAbilityProperties(ability);
	}

	private static void deleteAbilityProperties(String id) throws DataConnectionException {
		SqlStatement.delete(Table.AbilityProperty.class).where("abilityId").eq(id).execute();
	}
}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_lwjgl_input_Mouse */

#ifndef _Included_org_lwjgl_input_Mouse
#define _Included_org_lwjgl_input_Mouse
#ifdef __cplusplus
extern "C" {
#endif
#undef org_lwjgl_input_Mouse_EVENT_SIZE
#define org_lwjgl_input_Mouse_EVENT_SIZE 22L
/* Inaccessible static: created */
/* Inaccessible static: buttons */
/* Inaccessible static: x */
/* Inaccessible static: y */
/* Inaccessible static: coord_buffer */
/* Inaccessible static: dx */
/* Inaccessible static: dy */
/* Inaccessible static: dwheel */
/* Inaccessible static: buttonCount */
/* Inaccessible static: hasWheel */
/* Inaccessible static: currentCursor */
/* Inaccessible static: buttonName */
/* Inaccessible static: buttonMap */
/* Inaccessible static: initialized */
/* Inaccessible static: readBuffer */
/* Inaccessible static: eventButton */
/* Inaccessible static: eventState */
/* Inaccessible static: event_dx */
/* Inaccessible static: event_dy */
/* Inaccessible static: event_dwheel */
/* Inaccessible static: event_x */
/* Inaccessible static: event_y */
/* Inaccessible static: event_nanos */
/* Inaccessible static: grab_x */
/* Inaccessible static: grab_y */
#undef org_lwjgl_input_Mouse_BUFFER_SIZE
#define org_lwjgl_input_Mouse_BUFFER_SIZE 50L
/* Inaccessible static: isGrabbed */
/* Inaccessible static: implementation */
/* Inaccessible static: emulateCursorAnimation */
/* Inaccessible static: allowNegativeMouseCoords */
#ifdef __cplusplus
}
#endif
#endif


text:
package com.wandrell.pattern.repository.pagination;

import java.util.Collection;

import com.wandrell.pattern.repository.FilteredRepository;

/**
 * Extension of {@link com.wandrell.pattern.repository.FilteredRepository
 * FilteredRepository} allowing paginating it's contents to get a subset of
 * them.
 *

 * The pagination is added to all the methods which return any set of entities,
 * meaning that it is possible paginate a subset created with the methods from
 * {@code FilteredRepository}.
 *
 * @author Bernardo Martínez Garrido
 *
 * @param <V>
 *            the type stored on the repository
 * @param <F>
 *            the type being used to filter the entities
 */
public interface PaginatedRepository<V, F> extends FilteredRepository<V, F> {

    /**
     * Returns all the entities contained in the repository paginated.
     *
     * @param pagination
     *            pagination data
     * @return all the entities contained in the repository paginated
     */
    public Collection<V> getAll(final PaginationData pagination);

    /**
     * Queries the entities in the repository and returns a paginated subset of
     * them.
     *

     * The collection is created filtering the stored data with the specified
     * filter.
     *

     * How this filter exactly work will depend on the implementation, it may be
     * an structure containing information to build an SQL query, or may just be
     * a predicate which the entities should validate.
     *
     * @param filter
     *            the filter which discriminates the entities to be returned
     * @param pagination
     *            pagination data
     * @return the filtered and paginated subset of entities
     */
    public Collection<V> getCollection(final F filter,
            final PaginationData pagination);

}