text:
'use strict'

var shimmer = require('../shimmer')
var logger = require('../logger').child({component: 'pg'})
var parseSql = require('../db/parse-sql')
var POSTGRES = require('../metrics/names').POSTGRES
var util = require('util')

// Adds a segment
// The `config` argument is either a statement string template or a pg statement
// config object with a `text` property holding the statement string template.
function initializeSegment(tracer, segment, client, config) {
  var statement
  if (config && (typeof config === 'string' || config instanceof String)) {
    statement = config
  } else if (config && config.text) {
    statement = config.text
  } else {
    // Won't be matched by parser, but should be handled properly
    statement = 'Other'
  }

  var ps = parseSql(POSTGRES.PREFIX, statement)
  var model = ps.model
  var operation = ps.operation

  segment.name = POSTGRES.STATEMENT + (model || 'other') + '/' + operation
  segment.captureDBInstanceAttributes(client.host, client.port, client.database)

  logger.trace(
    'capturing postgresql query. model: %s, operation: %s',
    model,
    operation
  )

  tracer.getTransaction().addRecorder(ps.recordMetrics.bind(ps, segment))
}

module.exports = function initialize(agent, pgsql) {
  if (!pgsql) return

  var tracer = agent.tracer

  // allows for native wrapping to not happen if not necessary
  // when env var is true

  if (process.env.NODE_PG_FORCE_NATIVE) {
    return instrumentPGNative('pg', pgsql)
  }

  // The pg module defines "native" getter which sets up the native client lazily
  // (only when called).  We replace the getter, so that we can instrument the native
  // client.  The original getter replaces itself with the instance of the native
  // client, so only instrument if the getter exists (otherwise assume already
  // instrumented).
  var origGetter = pgsql.__lookupGetter__('native')
  if (origGetter) {
    delete pgsql.native
    pgsql.__defineGetter__('native', function getNative() {
      var temp = origGetter()
      instrumentPGNative('pg.native', temp)
      return temp
    })
  }

  // wrapping for native
  function instrumentPGNative(eng, pg) {
    shimmer.wrapMethod(pg, 'pg', 'Client', wrapClient)
    shimmer.wrapMethod(pg.pools, 'pg.pools', 'Client', wrapClient)
    shimmer.wrapMethod(pg, 'pg', 'Pool', wrapPool)

    function newApply(Cls) {
      return new (Cls.bind.apply(Cls, arguments))()
    }

    function wrapPool(Pool) {
      if (shimmer.isWrapped(Pool)) {
        return Pool
      }

      util.inherits(WrappedPool, Pool)
      WrappedPool.__NR_original = Pool
      return WrappedPool

      /* eslint-disable no-unused-vars */
      function WrappedPool(options, Client) {
        /* eslint-enable no-unused-vars */
        if (!(this instanceof WrappedPool)) {
          return newApply(WrappedPool, arguments)
        }

        Pool.apply(this, arguments)
        this.Client = wrapClient(this.Client)
      }
    }

    function wrapClient(Client) {
      if (shimmer.isWrapped(Client)) {
        return Client
      }

      util.inherits(WrappedClient, Client)
      Object.keys(Client).forEach(function forEachClientKey(k) {
        WrappedClient[k] = Client[k]
      })
      WrappedClient.__NR_original = Client
      return WrappedClient

      // -------------------------------------------------------------------- //

      /* eslint-disable no-unused-vars */
      function WrappedClient(options) {
        /* eslint-enable no-unused-vars */
        // NOTE:  This is an instance of PG's `Client` class, _not_ its
        //        `Connection` class. This is an important distinction as the
        //        latter does not have the host/port/database meta data.

        // Apply the constructor. JavaScript really needs a better way to do this.
        // This logic is the same as `newApply`, however for some reason `newApply`
        // does not work on Node v0.8 or v0.10. For `WrappedPool` this doesn't
        // matter since the versions of PG it is in don't support those ancient
        // versions of Node either, but here we must do it ourselves.
        var args = tracer.slice(arguments)
        args.unshift(Client) // `unshift` === `push_front`
        var client = new (Client.bind.apply(Client, args))()

        // Wrap the methods we care about.
        shimmer.wrapMethod(client, 'Client', 'connect', wrapConnect)
        shimmer.wrapMethod(client, 'Client', 'query', wrapNativeQuery)
        return client
      }

      function wrapConnect(connect) {
        return function wrappedConnect(callback) {
          if (typeof callback === 'function') {
            callback = tracer.bindFunction(callback)
          }
          return connect.call(this, callback)
        }
      }

      function wrapNativeQuery(original) {
        return tracer.wrapFunction(
          POSTGRES.STATEMENT + 'Unknown',
          null,
          original,
          nativeQueryWrapper,
          nativeResponseWrapper
        )
      }

      function nativeQueryWrapper(segment, args, bindCallback) {
        initializeSegment(tracer, segment, this, args[0])

        var pos = args.length - 1
        var last = args[pos]

        // Proxy callback in case they start new segments
        args[pos] = bindCallback(last)

        return args
      }

      function nativeResponseWrapper(segment, result, bindCallback) {
        // Wrap end and error events too, in case they start new segments
        // within them. Use end and error events to end segments.
        result.on('error', end)
        result.on('end', end)

        function end() {
          segment.touch()
          logger.trace(
            'postgres command trace segment ended by event for transaction %s.',
            segment.transaction.id
          )
        }

        // TODO: Maybe .on and .addListener shouldn't be different
        // Proxy events too, in case they start new segments within handlers
        shimmer.wrapMethod(result, 'query.on', 'on', function queryOnWrapper(on) {
          return function queryOnWrapped() {
            if (arguments[1]) {
              if (arguments[0] !== 'row') {
                arguments[1] = bindCallback(arguments[1])
              } else {
                arguments[1] = tracer.bindFunction(arguments[1], segment, true)
              }
            }
            return on.apply(this, arguments)
          }
        })

        shimmer.wrapMethod(
          result,
          'query.addListener',
          'addListener',
          queryAddListenerWrapper
        )

        function queryAddListenerWrapper(addL) {
          return function queryAddListenerWrapped() {
            if (arguments[1]) {
              if (arguments[0] !== 'row') {
                arguments[1] = bindCallback(arguments[1])
              } else {
                arguments[1] = tracer.bindFunction(arguments[1], segment, true)
              }
            }
            addL.apply(this, arguments)
          }
        }

        return result
      }
    }
  }

  // wrapping for JS
  shimmer.wrapMethod(
    pgsql && pgsql.Client && pgsql.Client.prototype,
    'pg.Client.prototype',
    'query',
    wrapQuery
  )

  function wrapQuery(original) {
    return tracer.wrapFunction(
      POSTGRES.STATEMENT + 'Unknown',
      null,
      original,
      queryWrapper,
      responseWrapper
    )
  }

  function queryWrapper(segment, args, bindCallback) {
    var position = args.length - 1
    var last = args[position]

    initializeSegment(tracer, segment, this, args[0])

    // Proxy callbacks in case they start new segments
    if (typeof last === 'function') {
      args[position] = bindCallback(last, true, true)
    } else if (Array.isArray(last) && typeof last[last.length - 1] === 'function') {
      var callback = last[last.length - 1]
      last[last.length - 1] = bindCallback(callback)
    }

    return args
  }

  function responseWrapper(segment, query, bindCallback) {
    // Use end and error events to end segments
    query.on('error', end)
    query.on('end', end)

    function end() {
      segment.end()
      logger.trace(
        'postgres command trace segment ended by event for transaction %s.',
        segment.transaction.id
      )
    }

    // Proxy events too, in case they start new segments within handlers
    shimmer.wrapMethod(query, 'query.on', 'on', function queryOnWrapper(on) {
      return function queryOnWrapped() {
        if (arguments[1]) {
          if (arguments[0] !== 'row') {
            arguments[1] = bindCallback(arguments[1])
          } else {
            arguments[1] = tracer.bindFunction(arguments[1], segment, true)
          }
        }
        return on.apply(this, arguments)
      }
    })

    shimmer.wrapMethod(query, 'query.addListener', 'addListener', addListenerWrapper)

    function addListenerWrapper(addL) {
      return function wrappedAddListener() {
        if (arguments[1]) {
          if (arguments[0] !== 'row') {
            arguments[1] = bindCallback(arguments[1])
          } else {
            arguments[1] = tracer.bindFunction(arguments[1], segment, true)
          }
        }
        addL.apply(this, arguments)
      }
    }

    return query
  }
}


text:
By default, `Table` assumes the sortable rows can be sorted in ascending or descending order.
Clicking a column header the first time will trigger the `sort` callback with a suggested ordering of _ascending_.
Clicking it a second time will call `sort` with a suggested ordering of _descending_.
Clicking a third time will suggest _ascending_.

This is often desirable but it has a subtle side effect:
Once you have sorted a `Table` there is no way to return to an unsorted, "natural" order.

Fortunately `Table` makes it easy for you to implement this functionality within your application code like so:

```jsx
export default class NaturalSortTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      list: props.list, // Naturally sorted list
    };
  }

  componentWillUpdate(nextProps, nextState) {
    const {sortBy: prevSortBy, sortDirection: prevSortDirection} = this.state;

    if (
      nextState.sortBy !== prevSortBy ||
      nextState.sortDirection !== prevSortDirection
    ) {
      const {sortBy, sortDirection} = nextState;

      let {list} = this.props;

      if (sortBy) {
        list = list.sortBy(item => item[sortBy]);
        if (sortDirection === SortDirection.DESC) {
          list = list.reverse();
        }
      }
    }
  }

  render() {
    const {list, sortBy, sortDirection} = this.state;

    return (
      <Table
        {...this.props}
        sort={this._sort}
        sortBy={sortBy}
        sortDirection={sortDirection}>
        {/* <Column>s go here */}
      </Table>
    );
  }

  _sort({sortBy, sortDirection}) {
    const {sortBy: prevSortBy, sortDirection: prevSortDirection} = this.state;

    // If list was sorted DESC by this column.
    // Rather than switch to ASC, return to "natural" order.
    if (prevSortDirection === SortDirection.DESC) {
      sortBy = null;
      sortDirection = null;
    }

    this.setState({sortBy, sortDirection});
  }
}
```

redpajama_set_name: RedPajamaGithub


text:
lib_dir = File.join(File.dirname(__FILE__), '..', 'lib')
$LOAD_PATH.unshift File.expand_path(lib_dir)
require 'watirmark-bvt'
require 'rspec/autorun'


text:
(HUGE thanks to [Monte Lunacek](https://twitter.com/MonteLunacek) for
teaching me his hack with the custom D3 module!)

Let's start with reviewing a few of the ideas for using JavaScript in IPython. We'll then work with some data in python and then build a few d3 visualizations. We'll conclude by crafting a custom module that can receive data and render the d3 viz!

### JS with IPython?
The nice thing about ipython is that we can write in almost any lanaguage. For example, we can use javascript below and pull in the D3 library.

### Python data | D3 Viz
A basic method is to serialze your results and then render html that pulls in the data. In this example, we save a json file and then load the html doc in an IFrame. We're now using D3 in ipython!

The example below is adapted from:
* Hagberg, A & Schult, D. & Swart, P. Networkx (2011). Github repository, https://github.com/networkx/networkx/tree/master/examples/javascript/force

### Passing data from IPython to JS
Let's create some random numbers and render them in js (see the [stackoverflow explanation](http://stackoverflow.com/questions/26207668/how-to-use-python-defined-variables-in-javascript-code-within-ipython-notebook) and discussion).

### Passing data from JS to IPython
We can also interact with js to define python variables (see [this example](https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/)).

### Custom D3 module.
Now we're having fun. The simplicity of this process wins. We can pass data to javascript via a module called visualize that contains an attribute `plot_circle`, which uses jinja to render our js template. The advantage of using jinja to read our html is apparent: we can pass variables directly from python!

**Now we just need to learn how to write useful javacript!**
(Enter Jason)


text:
package VMOMI::ClusterFailoverLevelAdmissionControlPolicy;
use parent 'VMOMI::ClusterDasAdmissionControlPolicy';

use strict;
use warnings;

our @class_ancestors = (
    'ClusterDasAdmissionControlPolicy',
    'DynamicData',
);

our @class_members = (
    ['failoverLevel', undef, 0, ],
    ['slotPolicy', 'ClusterSlotPolicy', 0, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<title>CSS Test: ruby layout items should block text decoration propagation just like atomic inlines do</title>

Bug 71266: CSS2:text-decoration: <rt> element should not inherit text-decoration property

<ruby>X<rt>This line should NOT be underlined nor strike-through</rt></ruby>

<ruby>X<rt>This line should be underlined and strike-through</rt></ruby>


text:
/*
 * Data Grid Search API
 * This is and extensible, pluggable search API for iRODS focused on pluggable Elastic Search indexes.
 *
 * OpenAPI spec version: 1.0.0-oas3
 * Contact: mike.conway@nih.gov
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package org.irods.jargon.extensions.searchplugin.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.google.gson.annotations.SerializedName;

import io.swagger.v3.oas.annotations.media.Schema;

/**
 * SearchAttributes
 */

@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2019-08-06T15:09:01.384Z[GMT]")
public class SearchAttributes {
	@SerializedName("id")
	private String id = null;

	@SerializedName("name")
	private String name = null;

	@SerializedName("info")
	private String info = null;

	@SerializedName("attributes")
	private List<IndexSearchAttributes> attributes = null;

	public SearchAttributes id(String id) {
		this.id = id;
		return this;
	}

	/**
	 * Unique identifier for this index type
	 *
	 * @return id
	 **/
	@Schema(description = "Unique identifier for this index type")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public SearchAttributes name(String name) {
		this.name = name;
		return this;
	}

	/**
	 * Display name for this index type
	 *
	 * @return name
	 **/
	@Schema(description = "Display name for this index type")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public SearchAttributes info(String info) {
		this.info = info;
		return this;
	}

	/**
	 * Documentation about this particular index type
	 *
	 * @return info
	 **/
	@Schema(description = "Documentation about this particular index type")
	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public SearchAttributes attributes(List<IndexSearchAttributes> attributes) {
		this.attributes = attributes;
		return this;
	}

	public SearchAttributes addAttributesItem(IndexSearchAttributes attributesItem) {
		if (this.attributes == null) {
			this.attributes = new ArrayList<IndexSearchAttributes>();
		}
		this.attributes.add(attributesItem);
		return this;
	}

	/**
	 * array of possible search attributes that can be used to support textual
	 * advanced search flags as well as query builder interfaces
	 * attribute-by-attribute
	 *
	 * @return attributes
	 **/
	@Schema(description = "array of possible search attributes that can be used to support textual advanced search flags as well as query builder interfaces attribute-by-attribute")
	public List<IndexSearchAttributes> getAttributes() {
		return attributes;
	}

	public void setAttributes(List<IndexSearchAttributes> attributes) {
		this.attributes = attributes;
	}

	@Override
	public boolean equals(java.lang.Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		SearchAttributes searchAttributes = (SearchAttributes) o;
		return Objects.equals(this.id, searchAttributes.id) && Objects.equals(this.name, searchAttributes.name)
				&& Objects.equals(this.info, searchAttributes.info)
				&& Objects.equals(this.attributes, searchAttributes.attributes);
	}

	@Override
	public int hashCode() {
		return Objects.hash(id, name, info, attributes);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("class SearchAttributes {\n");

		sb.append("    id: ").append(toIndentedString(id)).append("\n");
		sb.append("    name: ").append(toIndentedString(name)).append("\n");
		sb.append("    info: ").append(toIndentedString(info)).append("\n");
		sb.append("    attributes: ").append(toIndentedString(attributes)).append("\n");
		sb.append("}");
		return sb.toString();
	}

	/**
	 * Convert the given object to string with each line indented by 4 spaces
	 * (except the first line).
	 */
	private String toIndentedString(java.lang.Object o) {
		if (o == null) {
			return "null";
		}
		return o.toString().replace("\n", "\n    ");
	}

}