text:
SimpleForm.setup do |config|
  config.error_notification_class = 'alert alert-danger'
  config.button_class = 'btn btn-default'
  config.boolean_label_class = nil

  config.wrappers :vertical_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :pattern
    b.optional :min_max
    b.optional :readonly
    b.use :label, class: 'control-label'

    b.use :input, class: 'form-control'
    b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
    b.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
  end

  config.wrappers :vertical_file_input, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :readonly
    b.use :label, class: 'control-label'

    b.use :input
    b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
    b.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
  end

  config.wrappers :vertical_boolean, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.optional :readonly

    b.wrapper tag: 'div', class: 'checkbox' do |ba|
      ba.use :label_input
    end

    b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
    b.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
  end

  config.wrappers :vertical_radio_and_checkboxes, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.optional :readonly
    b.use :label, class: 'control-label'
    b.use :input
    b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
    b.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
  end

  config.wrappers :horizontal_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :pattern
    b.optional :min_max
    b.optional :readonly
    b.use :label, class: 'col-sm-3 control-label'

    b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
      ba.use :input, class: 'form-control'
      ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
    end
  end

  config.wrappers :horizontal_file_input, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :readonly
    b.use :label, class: 'col-sm-3 control-label'

    b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
      ba.use :input
      ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
    end
  end

  config.wrappers :horizontal_boolean, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.optional :readonly

    b.wrapper tag: 'div', class: 'col-sm-offset-3 col-sm-9' do |wr|
      wr.wrapper tag: 'div', class: 'checkbox' do |ba|
        ba.use :label_input, class: 'col-sm-9'
      end

      wr.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      wr.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
    end
  end

  config.wrappers :horizontal_radio_and_checkboxes, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.optional :readonly

    b.use :label, class: 'col-sm-3 control-label'

    b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
      ba.use :input
      ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
    end
  end

  config.wrappers :inline_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :pattern
    b.optional :min_max
    b.optional :readonly
    b.use :label, class: 'sr-only'

    b.use :input, class: 'form-control'
    b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
    b.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
  end

  # Wrappers for forms and inputs using the Bootstrap toolkit.
  # Check the Bootstrap docs (http://getbootstrap.com)
  # to learn about the different styles for forms and inputs,
  # buttons and other elements.
  # config.default_wrapper = :vertical_form
  config.default_wrapper = :horizontal_form
  config.wrapper_mappings = {
    check_boxes: :vertical_radio_and_checkboxes,
    radio_buttons: :vertical_radio_and_checkboxes,
    file: :vertical_file_input,
    boolean: :vertical_boolean,
  }
end

# wrapper: :horizontal_form,
#   wrapper_mappings: {
#     check_boxes: :horizontal_radio_and_checkboxes,
#     radio_buttons: :horizontal_radio_and_checkboxes,
#     file: :horizontal_file_input,
#     boolean: :horizontal_boolean
#   }

# #It should be used like this:
# # html: {class: 'form-horizontal multiple_tags', role: 'form'}, defaults: { label_html: { class: 'col-lg-2' }, input_html: { class: 'form-control'} } do |form|

# # Use this setup block to configure all options available in SimpleForm.
# SimpleForm.setup do |config|
#   config.wrappers :bootstrap, tag: 'div', class: 'form-group', error_class: 'error' do |b|
#     b.use :html5
#     b.use :placeholder
#     b.use :label
#     b.wrapper tag: 'div', class: 'col-lg-6 col-xs-4 col-sm-6' do |ba|
#       ba.use :input
#       ba.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
#       ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
#     end
#   end

#   #

#   #   Email
#   #

#   #     <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
#   #

#   #

#   config.wrappers :prepend, tag: 'div', class: "form-group", error_class: 'error' do |b|
#     b.use :html5
#     b.use :placeholder
#     b.use :label
#     b.wrapper tag: 'div', class: 'col-lg-6 col-xs-4 col-sm-6' do |input|
#       input.wrapper tag: 'div', class: 'input-prepend' do |prepend|
#         prepend.use :input
#       end
#       input.use :hint,  wrap_with: { tag: 'span', class: 'help-block' }
#       input.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
#     end
#   end

#   config.wrappers :append, tag: 'div', class: "form-group", error_class: 'error' do |b|
#     b.use :html5
#     b.use :placeholder
#     b.use :label
#     b.wrapper tag: 'div', class: 'col-lg-6 col-xs-4 col-sm-6' do |input|
#       input.wrapper tag: 'div', class: 'input-append' do |append|
#         append.use :input
#       end
#       input.use :hint,  wrap_with: { tag: 'span', class: 'help-block' }
#       input.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
#     end
#   end

#   # Wrappers for forms and inputs using the Twitter Bootstrap toolkit.
#   # Check the Bootstrap docs (http://twitter.github.com/bootstrap)
#   # to learn about the different styles for forms and inputs,
#   # buttons and other elements.
#   config.default_wrapper = :bootstrap
# end


text:
@jsinterop.annotations.JsPackage(namespace = "hal.meta")
package org.jboss.hal.meta;

redpajama_set_name: RedPajamaGithub


text:
Kivy Designer
=============

**WARNING:: This software was part of GSOC 2013, and is searching for a maintainer.**

Kivy Designer is Kivy's tool for designing Graphical User Interfaces
(GUIs) from Kivy Widgets. You can compose and customize widgets, and
test them. It is completely written in Python using Kivy.

Prerequisites
-------------

- [Kivy 1.8+](http://kivy.org/#download)
- The following Python modules (available via pip)
    - [watchdog](http://pythonhosted.org/watchdog/)
    - [Pygments](http://pygments.org/)
    - [docutils](http://docutils.sourceforge.net/)
- The FileBrowser widget from the [Kivy garden](http://kivy.org/docs/api-kivy.garden.html)

Installation
------------

To install the prerequisites, enter a console (on windows use kivy.bat in the kivy folder):

    pip install watchdog
    pip install pygments
    pip install docutils

To install the FileBrowser, enter a console (on windows use kivy.bat in the kivy folder):

    pip install kivy-garden
    garden install filebrowser

With the prerequisites installed, you can use the designer:

    git clone http://github.com/kivy/kivy-designer/
    cd kivy-designer
    python main.py

without git download, extract and execute main.py:
https://github.com/kivy/kivy-designer/archive/master.zip

On OS X you might need to use `kivy` command instead of `Python` if you are using our portable package.

If you're successful, you'll see something like this:

![ScreenShot](https://raw.github.com/kivy/kivy-designer/master/kivy_designer.png)


text:
import React, { cloneElement } from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import ValidComponentChildren from './utils/ValidComponentChildren';

const Carousel = React.createClass({
  mixins: [BootstrapMixin],

  propTypes: {
    slide: React.PropTypes.bool,
    indicators: React.PropTypes.bool,
    controls: React.PropTypes.bool,
    pauseOnHover: React.PropTypes.bool,
    wrap: React.PropTypes.bool,
    onSelect: React.PropTypes.func,
    onSlideEnd: React.PropTypes.func,
    activeIndex: React.PropTypes.number,
    defaultActiveIndex: React.PropTypes.number,
    direction: React.PropTypes.oneOf(['prev', 'next'])
  },

  getDefaultProps() {
    return {
      slide: true,
      interval: 5000,
      pauseOnHover: true,
      wrap: true,
      indicators: true,
      controls: true
    };
  },

  getInitialState() {
    return {
      activeIndex: this.props.defaultActiveIndex == null ?
        0 : this.props.defaultActiveIndex,
      previousActiveIndex: null,
      direction: null
    };
  },

  getDirection(prevIndex, index) {
    if (prevIndex === index) {
      return null;
    }

    return prevIndex > index ?
      'prev' : 'next';
  },

  componentWillReceiveProps(nextProps) {
    let activeIndex = this.getActiveIndex();

    if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) {
      clearTimeout(this.timeout);
      this.setState({
        previousActiveIndex: activeIndex,
        direction: nextProps.direction != null ?
          nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex)
      });
    }
  },

  componentDidMount() {
    this.waitForNext();
  },

  componentWillUnmount() {
    clearTimeout(this.timeout);
  },

  next(e) {
    if (e) {
      e.preventDefault();
    }

    let index = this.getActiveIndex() + 1;
    let count = ValidComponentChildren.numberOf(this.props.children);

    if (index > count - 1) {
      if (!this.props.wrap) {
        return;
      }
      index = 0;
    }

    this.handleSelect(index, 'next');
  },

  prev(e) {
    if (e) {
      e.preventDefault();
    }

    let index = this.getActiveIndex() - 1;

    if (index < 0) {
      if (!this.props.wrap) {
        return;
      }
      index = ValidComponentChildren.numberOf(this.props.children) - 1;
    }

    this.handleSelect(index, 'prev');
  },

  pause() {
    this.isPaused = true;
    clearTimeout(this.timeout);
  },

  play() {
    this.isPaused = false;
    this.waitForNext();
  },

  waitForNext() {
    if (!this.isPaused && this.props.slide && this.props.interval &&
        this.props.activeIndex == null) {
      this.timeout = setTimeout(this.next, this.props.interval);
    }
  },

  handleMouseOver() {
    if (this.props.pauseOnHover) {
      this.pause();
    }
  },

  handleMouseOut() {
    if (this.isPaused) {
      this.play();
    }
  },

  render() {
    let classes = {
      carousel: true,
      slide: this.props.slide
    };

    return (

        {this.props.indicators ? this.renderIndicators() : null}

          {ValidComponentChildren.map(this.props.children, this.renderItem)}

        {this.props.controls ? this.renderControls() : null}

    );
  },

  renderPrev() {
    return (

    );
  },

  renderNext() {
    return (

    );
  },

  renderControls() {
    if (!this.props.wrap) {
      let activeIndex = this.getActiveIndex();
      let count = ValidComponentChildren.numberOf(this.props.children);

      return [
        (activeIndex !== 0) ? this.renderPrev() : null,
        (activeIndex !== count - 1) ? this.renderNext() : null
      ];
    }

    return [
      this.renderPrev(),
      this.renderNext()
    ];
  },

  renderIndicator(child, index) {
    let className = (index === this.getActiveIndex()) ?
      'active' : null;

    return (

    );
  },

  renderIndicators() {
    let indicators = [];
    ValidComponentChildren
      .forEach(this.props.children, function(child, index) {
        indicators.push(
          this.renderIndicator(child, index),

          // Force whitespace between indicator elements, bootstrap
          // requires this for correct spacing of elements.
          ' '
        );
      }, this);

    return (

        {indicators}

    );
  },

  getActiveIndex() {
    return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex;
  },

  handleItemAnimateOutEnd() {
    this.setState({
      previousActiveIndex: null,
      direction: null
    }, function() {
      this.waitForNext();

      if (this.props.onSlideEnd) {
        this.props.onSlideEnd();
      }
    });
  },

  renderItem(child, index) {
    let activeIndex = this.getActiveIndex();
    let isActive = (index === activeIndex);
    let isPreviousActive = this.state.previousActiveIndex != null &&
            this.state.previousActiveIndex === index && this.props.slide;

    return cloneElement(
        child,
        {
          active: isActive,
          ref: child.ref,
          key: child.key ? child.key : index,
          index: index,
          animateOut: isPreviousActive,
          animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide,
          direction: this.state.direction,
          onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd: null
        }
      );
  },

  handleSelect(index, direction) {
    clearTimeout(this.timeout);

    let previousActiveIndex = this.getActiveIndex();
    direction = direction || this.getDirection(previousActiveIndex, index);

    if (this.props.onSelect) {
      this.props.onSelect(index, direction);
    }

    if (this.props.activeIndex == null && index !== previousActiveIndex) {
      if (this.state.previousActiveIndex != null) {
        // If currently animating don't activate the new index.
        // TODO: look into queuing this canceled call and
        // animating after the current animation has ended.
        return;
      }

      this.setState({
        activeIndex: index,
        previousActiveIndex: previousActiveIndex,
        direction: direction
      });
    }
  }
});

export default Carousel;


text:
package usps

import (
	"os"
	"testing"
)

func TestTrackPackage(t *testing.T) {
	var usps USPS
	usps.Username = os.Getenv("USPSUsername")

	output := usps.TrackPackage("9341989949036022338924")
	if output.TrackInfo.TrackSummary != "The Postal Service could not locate the tracking information for your request. Please verify your tracking number and try again later." {
		t.Error("Tracker is incorrect")
	}
}


text:
layout: post
title: Using closest() to return the correct DOM element
description: Sometimes you need JavaScript to target specific selectors in the DOM. The closest() method can help you do just that.
image: img/posts/sunset-home-office-min.jpg
tags: [HTML, JavaScript]
comments: true
---

I was recently working with a vertical navigation component and ran into a hiccup where the JavaScript code wouldn't fire depending on _where_ I clicked on the menu item link. I did some digging and thought I'd share a little about what I discovered and how I was able to resolve the problem.

To start, I have a list item that when selected will expand or collapse a submenu:

```html
<li>
  <a href="#submenu" class="toggle">Billing</a>
  <div id="submenu">
    <ul>
      <li><a href="/statment/">My Statement</a></li>
      <li><a href="/history/">Pay History</a></li>
    </ul>
  </div>
</li>
```

This event listener will manage toggling the submenu's expanded/collapsed state:

```javascript
document.addEventListener('click', function (event) {

  // Make sure clicked element is our toggle
  if (!event.target.classList.contains('toggle')) {
    return;
  }
  event.preventDefault();

  // Get the content
  let content = document.querySelector(event.target.hash);
  if (!content) {
    return;
  }

  // Toggle the content
  toggle(content);

}, false);
```

The `toggle()` method executes a function to check if the submenu has the `.is-visible` CSS class. If the element has that class, the submenu will be hidden; otherwise, the submenu is displayed:

```javascript
const toggle = function (elem, timing) {

  // If the element is visible, hide it
  if (elem.classList.contains('is-visible')) {
    hide(elem);
    return;
  }

  // Otherwise, show it
  show(elem);
};
```

I expected that clicking anywhere within the menu item would fire the JavaScript and perform the toggle. But if I clicked on either the icon or the label child elements, the JavaScript wouldn't execute. The reason is that `event.target` returns the exact DOM element. Clicking on the icon or the label returned only the image or span elements.

## The closest() method

This was something I had to look up. I needed the target and return the parent element, not the child elements. I found the solution using the [`closest()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest){:rel="external"} method. This method travels up the DOM tree from the current element and returns the closest ancestor that matches the given parameter:

```javascript
const closestElement = Element.closest(selector);
```

This was my "ah-ha!" moment. I could chain `closest()` to `event.target` to find and return the parent element (menu item link), regardless if I ended up clicking on the child elements (icon or label):

```javascript
if (!event.target.closest('a').classList.contains('toggle')) {
  return;
}

const content = document.querySelector(event.target.closest('a').hash);
```

Now clicking anywhere in the menu item link fires the JavaScript to toggle the submenu.

    See the Pen
    WPMPaV by Matt Smith (@AllThingsSmitty)
    on CodePen.

Hopefully this tip will help you if you need to target specific elements in the DOM. The `closest()` method is supported in [most major browsers](https://caniuse.com/#search=closest){:rel="external"} but requires a [polyfill with IE11](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill){:rel="external"}.

If you're looking for more in-depth reading on this, I'd recommend [Zell Liew's post](https://zellwk.com/blog/dom-traversals/){:rel="external"} on traversing the DOM. He covers this method and a few other tricks that are worth checking out.


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/action_save" android:showAsAction="ifRoom" android:title="@string/action_save"></item>

</menu>


text:
using Ponics.Organisms.Tolerances;

namespace Ponics.Analysis.Levels.Salinity
{
    public class SalinityLevelAnalysis: LevelAnalysis<SalinityTolerance>
    {
    }
}


text:
import {
    Component,
    ReactElement,
    ChangeEvent,
    DragEvent,
    FocusEvent
} from "react";
import { Dispatch } from "redux";
import { ComponentConstructor, DataShape, FieldValue } from "../index";

/**
 * These are the props to give to `Field`.
 * Any others will be passed through to your component.
 */
interface BaseFieldProps {
    /**
     * A string path, in dot-and-bracket notation, corresponding to a value
     * in the form values. It may be as simple as 'firstName' or as complicated
     * as contact.billing.address[2].phones[1].areaCode.
     *
     * Required but made optional so interface can be used on decorated components.
     */
    name?: string;

    /**
     * A Component, stateless function, or string corresponding to a default
     * JSX element.
     *
     * Required but made optional so interface can be used on decorated components.
     */
    component?: ComponentConstructor<any> | "input" | "select" | "textarea",

    /**
     * Formats the value from the Redux store to be displayed in the field input.
     * Common use cases are to format Numbers into currencies or Dates into a
     * localized date format.
     */
    format?: Formatter | null;

    /**
     * A function to convert whatever value the user has entered into the value that you
     * want stored in the Redux store for the field.
     *
     * For instance, if you want the value to be in all uppercase, you would pass
     *   value => value.toUpperCase()
     */
    normalize?: Normalizer;

    /**
     * Don't use.
     */
    props?: any;

    /**
     * Parses the value given from the field input component to the type that you want
     * stored in the Redux store. Common use cases are to parse currencies into Numbers into
     * currencies or localized date formats into Dates.
     */
    parse?: Parser;

    /**
     * Allows you to to provide a field-level validation rule. The function will be given the
     * current value of the field and all the other form values. If the field is valid, it
     * should return `undefined`, if the field is invalid, it should return an error
     * (usually, but not necessarily, a `String`).
     */
    validate?: Validator | Validator[];

    /**
     * Allows you to to provide a field-level warning rule. The function will be given the
     * current value of the field and all the other form values. If the field needs a warning,
     * it should return the warning (usually, but not necessarily, a `String`). If the field
     * does not need a warning, it should return `undefined`.
     */
    warn?: Validator | Validator[];

    /**
     * If true, the rendered component will be available with the
     * getRenderedComponent() method. Defaults to false. Cannot be used if your
     * component is a stateless function component.
     */
    withRef?: boolean;
}

/**
 * @param value             The value entered by the user.
 * @param previousValue     The previous value for the field.
 * @param allValues         All the values in the entire form with the new value.
 *                          This will be an Immutable Map if you are using Immutable JS.
 * @param previousAllValues All the values in the entire form before the current change.
 *                          This will be an Immutable Map if you are using Immutable JS.
 */
export type Normalizer = (value: FieldValue, previousValue?: FieldValue, allValues?: any, previousAllValues?: any) => FieldValue;

export type Formatter = (value: FieldValue, name: string) => FieldValue;

export type Parser = (value: FieldValue, name: string) => FieldValue;

export type Validator = (value: FieldValue, allValues?: any, props?: any) => any;

/**
 * Declare Field as this interface to specify the generic.
 */
export interface GenericField<FieldCustomProps, S> extends Component<BaseFieldProps & FieldCustomProps> {
    /**
     * true if the current value is different from the initialized value,
     * false otherwise.
     */
    dirty: boolean;

    /**
     * The name prop that you passed in.
     */
    name: string;

    /**
     * true if the current value is the same as the initialized value,
     * false otherwise.
     */
    pristine: boolean;

    /**
     * The current value of the field.
     */
    value: FieldValue;

    /**
     * Returns the instance of the rendered component. For this to work, you must
     * provide a withRef prop, and your component must not be a stateless function
     * component.
     */
    getRenderedComponent(): Component<WrappedFieldProps<S> & FieldCustomProps>;
}

/**
 * The Field Instance API.
 */
export class Field extends Component<any> implements GenericField<any, any> {
    /**
     * true if the current value is different from the initialized value,
     * false otherwise.
     */
    dirty: boolean;

    /**
     * The name prop that you passed in.
     */
    name: string;

    /**
     * true if the current value is the same as the initialized value,
     * false otherwise.
     */
    pristine: boolean;

    /**
     * The current value of the field.
     */
    value: FieldValue;

    /**
     * Returns the instance of the rendered component. For this to work, you must
     * provide a withRef prop, and your component must not be a stateless function
     * component.
     */
    getRenderedComponent(): Component<any>;
}

/**
 * These are props that `Field` will pass to your wrapped component (not including custom props).
 */
interface WrappedFieldProps<S> {
    /**
     * An object containing all the props that you will normally want to pass to
     * your input component.
     */
    input?: WrappedFieldInputProps;

    /**
     * An object containing all the metadata props.
     */
    meta: WrappedFieldMetaProps<S>;
}

/**
 * These props are meant to be destructured into your <input/> component.
 */
interface EventOrValueHandler<Event> {
    (event: Event): void;
    (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void;
}

interface WrappedFieldInputProps {
    /**
     * An alias for value only when value is a boolean. Provided for
     * convenience of destructuring the whole field object into the props of a
     * form element.
     */
    checked?: boolean;

    /**
     * The name prop passed in.
     */
    name: string;

    /**
     * A function to call when the form field loses focus.
     */
    onBlur: EventOrValueHandler<FocusEvent<any>>;

    /**
     * A function to call when the form field is changed.
     */
    onChange: EventOrValueHandler<ChangeEvent<any>>;

    /**
     * A function to call when the form field receives a 'dragStart' event.
     * Saves the field value in the event for giving the field it is dropped
     * into.
     */
    onDragStart: EventOrValueHandler<DragEvent<any>>;

    /**
     * A function to call when the form field receives a drop event.
     */
    onDrop: EventOrValueHandler<DragEvent<any>>;

    /**
     * A function to call when the form field receives focus.
     */
    onFocus: EventOrValueHandler<FocusEvent<any>>;

    /**
     * The value of this form field. It will be a boolean for checkboxes, and
     * a string for all other input types. If there is no value in the Redux
     * state for this field, it will default to ''. This is to
     * ensure that the input is controlled.
     */
    value: FieldValue;
}

/**
 * These props are metadata about the state of this field that redux-form is tracking for you.
 */
interface WrappedFieldMetaProps<S> {

    /**
     * true if this field currently has focus. It will only work if you are
     * passing onFocus to your input element.
     */
    active?: boolean;

    /**
     * true if this field has been set with the AUTOFILL action and has not since been changed
     * with a CHANGE action. This is useful to render the field in a way that the user can tell
     * that the value was autofilled for them.
     */
    autofilled: boolean;

    /**
     * true if the form is currently running asynchronous validation because this
     * field was blurred.
     */
    asyncValidating: boolean;

    /**
     * true if the field value has changed from its initialized value.
     * Opposite of pristine.
     */
    dirty: boolean;

    /**
     * The Redux dispatch function.
     */
    dispatch: Dispatch<S>;

    /**
     * The error for this field if its value is not passing validation. Both
     * synchronous, asynchronous, and submit validation errors will be reported here.
     */
    error?: any;

    /**
     * The name of the form. Could be useful if you want to manually dispatch actions.
     */
    form?: string;

    /**
     * true if the field value fails validation (has a validation error).
     * Opposite of valid.
     */
    invalid: boolean;

    /**
     * true if the field value is the same as its initialized value. Opposite
     * of dirty.
     */
    pristine: boolean;

    /**
     * true if the field is currently being submitted
     */
    submitting?: boolean;

    /**
     * true if the form had onSubmit called and failed to submit for any reason.
     * A subsequent successful submit will set it back to false.
     */
    submitFailed?: boolean;

    /**
     * true if the field has been touched. By default this will be set when
     * the field is blurred.
     */
    touched: boolean;

    /**
     * true if the field value passes validation (has no validation errors).
     * Opposite of invalid.
     */
    valid: boolean;

    /**
     * true if this field has ever had focus. It will only work if you are
     * passing onFocus to your input element.
     */
    visited?: boolean;

    /**
     * The warning for this field if its value is not passing warning validation.
     */
    warning?: any;
}


text:
package com.cisco.axl.api._8;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for LVoiceMailPilot complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="LVoiceMailPilot">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence minOccurs="0">
 *         <element name="dirn" type="{http://www.cisco.com/AXL/API/8.0}String255" minOccurs="0"/>
 *         <element name="description" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
 *         <element name="cssName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
 *         <element name="isDefault" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LVoiceMailPilot", propOrder = {
    "dirn",
    "description",
    "cssName",
    "isDefault"
})
public class LVoiceMailPilot {

    protected String dirn;
    protected String description;
    protected XFkType cssName;
    protected String isDefault;
    @XmlAttribute
    protected String uuid;

    /**
     * Gets the value of the dirn property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDirn() {
        return dirn;
    }

    /**
     * Sets the value of the dirn property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDirn(String value) {
        this.dirn = value;
    }

    /**
     * Gets the value of the description property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescription(String value) {
        this.description = value;
    }

    /**
     * Gets the value of the cssName property.
     *
     * @return
     *     possible object is
     *     {@link XFkType }
     *
     */
    public XFkType getCssName() {
        return cssName;
    }

    /**
     * Sets the value of the cssName property.
     *
     * @param value
     *     allowed object is
     *     {@link XFkType }
     *
     */
    public void setCssName(XFkType value) {
        this.cssName = value;
    }

    /**
     * Gets the value of the isDefault property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIsDefault() {
        return isDefault;
    }

    /**
     * Sets the value of the isDefault property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIsDefault(String value) {
        this.isDefault = value;
    }

    /**
     * Gets the value of the uuid property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUuid() {
        return uuid;
    }

    /**
     * Sets the value of the uuid property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUuid(String value) {
        this.uuid = value;
    }

}


text:
export const methodCheck = function ({ rpcAdapter: { checkMethod }, method }) {
  checkMethod({ method })
}


text:
var RSVP = require('rsvp'),
    request = require('request'),
    _ = require('lodash');

function dbpHelper() {
    var ntBooks = ['Matt', 'Mark', 'Luke', 'John', 'Acts', 'Rom', '1Cor', '2Cor', 'Gal', 'Eph', 'Phil', 'Col', '1Thess', '2Thess', '1Tim', '2Tim', 'Titus', 'Phlm', 'Heb', 'Jas', '1Pet', '2Pet', '1John', '2John', '3John', 'Jude', 'Rev'];
    var self = this;
	var dbpApiKey = '';

    var exports = {

		// This decides which volume to use based on the book requested.
        GetVolume: function(book, language, version) {
            var versionCode = language + version;
			versionCode += ntBooks.indexOf(book) > -1 ? 'N2ET' : 'O2ET';
            console.log("Version Code: " + versionCode);
            return versionCode;
        },

		// Concatenates all verses into a user friendly string.
        CombineVerses: function(verses) {
            var combinedVerses = '';
            for (var i = 0; i < verses.length; i++) {
                combinedVerses += verses[i].verse_text;
            }

            return combinedVerses;
        },

		// Gets the verse reference string based on the book, chapter and veres.
        GetVerseReferenceString: function(book, chapter, verseBegin, verseEnd) {
            return book + ' ' + chapter + ':' + verseBegin + '-' + verseEnd;
        },

		// An asynchronous method that gets gets the actual scripture verse in a specified language.
        GetScripture: function(verse, language, version) {
			var dam_id = this.GetVolume(verse.book_id, language, version);
			var dbtUrl = 'http://dbt.io/text/verse?v=2&key=' +
				this.dbpApiKey +
				'&book_id=' + verse.book_id + '&chapter_id=' + verse.chapter_id +
				'&verse_start=' + verse.verse_start + '&verse_end=' + verse.verse_end +
				'&dam_id=' + dam_id;

			var result = new RSVP.Promise(function(resolve, reject) {
				request.get({
					url: dbtUrl,
					json: true
				}, function(e, r, verses) {
					if (e) {
						reject(e);
					} else {
						resolve({
							verses: verses,
							dbtUrl: dbtUrl
						});
					}
				});
			});

            return result;
        }
    };

    _.bindAll(exports);
    return exports;
}

module.exports = dbpHelper;


text:
package com.twitter.finagle.mysql.unit

import com.twitter.finagle.mysql.PoisonConnection.PoisonedConnectionException
import com.twitter.finagle.Service
import com.twitter.finagle.Status
import com.twitter.finagle.service.RetryPolicy
import com.twitter.finagle.service.RequeueFilter
import com.twitter.finagle.mysql.CloseRequest
import com.twitter.finagle.mysql.PoisonConnectionRequest
import com.twitter.finagle.mysql.Request
import com.twitter.finagle.mysql.Result
import com.twitter.util.Future
import com.twitter.util.Promise
import com.twitter.util.Throw
import com.twitter.util.Time
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.funsuite.AnyFunSuite

class PoisonableServiceFactoryTest extends AnyFunSuite with MockitoSugar {

  import com.twitter.finagle.mysql.PoisonConnection.PoisonableService

  private def mockService = {
    val svc = mock[Service[Request, Result]]
    when(svc.close(any[Time])).thenReturn(Future.Done)
    when(svc.status).thenReturn(Status.Open)
    svc
  }

  test("PoisonableService can be poisoned") {
    val underlying = mockService
    val svc = new PoisonableService(underlying)
    assert(svc.status == Status.Open)

    val p = Promise[Result]()
    // Send a request
    when(underlying.apply(any[Request])).thenReturn(p)
    assert(svc(CloseRequest(2)) eq p)

    svc(PoisonConnectionRequest).poll match {
      case Some(Throw(_: PoisonedConnectionException)) => // ok
      case other => fail(s"Unexpected result: $other")
    }

    assert(svc.status == Status.Closed)
    svc(CloseRequest(2)).poll match {
      case Some(Throw(_: PoisonedConnectionException)) => // ok
      case other => fail(s"Unexpected result: $other")
    }
  }

  test("PoisonConnectionException is not retryable or requeueable") {
    val poisonExc = new PoisonedConnectionException

    val retryableExc = RetryPolicy.RetryableWriteException.unapply(poisonExc)
    assert(retryableExc.isEmpty)

    val requeueableExc = RequeueFilter.Requeueable.unapply(poisonExc)
    assert(requeueableExc.isEmpty)
  }
}


text:
package io.reactivex.internal.operators.flowable;

import static org.mockito.Mockito.*;

import java.util.List;

import org.junit.Test;
import org.reactivestreams.Subscriber;

import io.reactivex.*;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.internal.subscriptions.BooleanSubscription;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.subscribers.TestSubscriber;
;

public class FlowableTakeUntilPredicateTest {
    @Test
    public void takeEmpty() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Flowable.empty().takeUntil(new Predicate<Object>() {
            @Override
            public boolean test(Object v) {
                return true;
            }
        }).subscribe(subscriber);

        verify(subscriber, never()).onNext(any());
        verify(subscriber, never()).onError(any(Throwable.class));
        verify(subscriber).onComplete();
    }

    @Test
    public void takeAll() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Flowable.just(1, 2).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return false;
            }
        }).subscribe(subscriber);

        verify(subscriber).onNext(1);
        verify(subscriber).onNext(2);
        verify(subscriber, never()).onError(any(Throwable.class));
        verify(subscriber).onComplete();
    }

    @Test
    public void takeFirst() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Flowable.just(1, 2).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return true;
            }
        }).subscribe(subscriber);

        verify(subscriber).onNext(1);
        verify(subscriber, never()).onNext(2);
        verify(subscriber, never()).onError(any(Throwable.class));
        verify(subscriber).onComplete();
    }

    @Test
    public void takeSome() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Flowable.just(1, 2, 3).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer t1) {
                return t1 == 2;
            }
        })
        .subscribe(subscriber);

        verify(subscriber).onNext(1);
        verify(subscriber).onNext(2);
        verify(subscriber, never()).onNext(3);
        verify(subscriber, never()).onError(any(Throwable.class));
        verify(subscriber).onComplete();
    }

    @Test
    public void functionThrows() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Predicate<Integer> predicate = new Predicate<Integer>() {
            @Override
            public boolean test(Integer t1) {
                    throw new TestException("Forced failure");
            }
        };
        Flowable.just(1, 2, 3).takeUntil(predicate).subscribe(subscriber);

        verify(subscriber).onNext(1);
        verify(subscriber, never()).onNext(2);
        verify(subscriber, never()).onNext(3);
        verify(subscriber).onError(any(TestException.class));
        verify(subscriber, never()).onComplete();
    }

    @Test
    public void sourceThrows() {
        Subscriber<Object> subscriber = TestHelper.mockSubscriber();

        Flowable.just(1)
        .concatWith(Flowable.<Integer>error(new TestException()))
        .concatWith(Flowable.just(2))
        .takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return false;
            }
        }).subscribe(subscriber);

        verify(subscriber).onNext(1);
        verify(subscriber, never()).onNext(2);
        verify(subscriber).onError(any(TestException.class));
        verify(subscriber, never()).onComplete();
    }

    @Test
    public void backpressure() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>(5L);

        Flowable.range(1, 1000).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return false;
            }
        }).subscribe(ts);

        ts.assertNoErrors();
        ts.assertValues(1, 2, 3, 4, 5);
        ts.assertNotComplete();
    }

    @Test
    public void testErrorIncludesLastValueAsCause() {
        TestSubscriber<String> ts = new TestSubscriber<String>();
        final TestException e = new TestException("Forced failure");
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String t) {
                    throw e;
            }
        };
        Flowable.just("abc").takeUntil(predicate).subscribe(ts);

        ts.assertTerminated();
        ts.assertNotComplete();
        ts.assertError(TestException.class);
        // FIXME last cause value is not saved
//        assertTrue(ts.errors().get(0).getCause().getMessage().contains("abc"));
    }

    @Test
    public void dispose() {
        TestHelper.checkDisposed(PublishProcessor.create().takeUntil(Functions.alwaysFalse()));
    }

    @Test
    public void doubleOnSubscribe() {
        TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() {
            @Override
            public Flowable<Object> apply(Flowable<Object> f) throws Exception {
                return f.takeUntil(Functions.alwaysFalse());
            }
        });
    }

    @Test
    public void badSource() {
        List<Throwable> errors = TestHelper.trackPluginErrors();
        try {
            new Flowable<Integer>() {
                @Override
                protected void subscribeActual(Subscriber<? super Integer> subscriber) {
                    subscriber.onSubscribe(new BooleanSubscription());
                    subscriber.onComplete();
                    subscriber.onNext(1);
                    subscriber.onError(new TestException());
                    subscriber.onComplete();
                }
            }
            .takeUntil(Functions.alwaysFalse())
            .test()
            .assertResult();

            TestHelper.assertUndeliverable(errors, 0, TestException.class);
        } finally {
            RxJavaPlugins.reset();
        }
    }
}


text:
using namespace std;

class Inputstorage{
    protected:
        string cmd;
        vector<string> args;

    public:
    Inputstorage(string command, vector<string> arguments)
    :  cmd(command), args(arguments) {
        // for (unsigned int i = 0; i < args.size(); i++) {
        //     cout << args.at(i) << endl;
        // }
    }
    // gets the command as a char* to a c string so it's easier to put into execvp
        char *ret_cmd(){
        char * cmdpoint = new char[cmd.length() + 1];
        strcpy(cmdpoint, cmd.c_str());
        return cmdpoint;
    }
    // returns a pointer to the vector of arguements so easy to access in the execvp function
    vector<string>* get_args(){
      return &args;
    }

    string get_cmd() {
        return cmd;
    }

    string get_test() {
        string test;
        if (args.size() >= 1) {
            test = args.at(0);
        }
        return test;
    }

    string get_path() {
        string path = "";
        for (unsigned int i = 1; i < args.size(); i++) {
            //cout << args.at(i) << endl;
            path = path + args.at(i);
        }
        return path;
     }

};
#endif


text:
package club.jmint.crossing.bservice.provider;

import club.jmint.crossing.specs.CrossException;

/**
 * @author shc
 *
 */
public abstract class Provider implements IProvider {
	private String name;
	private boolean enabled;
	private String clazz;

	protected Provider(boolean enabled, String clazz){
		this.name = "Provider";
		this.enabled = enabled;
		this.clazz = clazz;
	}

	protected Provider(String name, boolean enabled, String clazz){
		this.name = name;
		this.enabled = enabled;
		this.clazz = clazz;
	}

	/* (non-Javadoc)
	 * @see club.jmint.crossing.bservice.provider.IProvider#init()
	 */
	public void init() throws CrossException {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see club.jmint.crossing.bservice.provider.IProvider#execute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean)
	 */
	public String execute(String server, String clazz, String inf, String jsonParams, boolean encrypt)
			throws CrossException {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see club.jmint.crossing.bservice.provider.IProvider#getName()
	 */
	public String getName(){
		// TODO Auto-generated method stub
		return name;
	}

	/* (non-Javadoc)
	 * @see club.jmint.crossing.bservice.provider.IProvider#getClazz()
	 */
	public String getClazz() {
		// TODO Auto-generated method stub
		return clazz;
	}

	/* (non-Javadoc)
	 * @see club.jmint.crossing.bservice.provider.IProvider#isEnabled()
	 */
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return enabled;
	}

}


text:
package ringo

import (
	"runtime"
	"testing"
)

// A simple queue: Publisher <==> Consumer
func TestSimpleQueueSmallType1(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewSimplePublishNode(32)
	slave := NewSimpleConsumeNode()
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < 64; i++ {
			slave.Reserve()
			slave.Commit()
		}
		close(done)
	}()

	for i := int64(0); i < 64; i++ {
		master.Reserve()
		master.Commit()
	}
	<-done
}

// A simple queue: Publisher <==> Consumer with larger buffer.
func TestSimpleQueueLargeType1(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewSimplePublishNode(PT32Meg)
	slave := NewSimpleConsumeNode()
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < PT64Meg; i++ {
			slave.Reserve()
			slave.Commit()
		}
		close(done)
	}()

	for i := int64(0); i < PT64Meg; i++ {
		master.Reserve()
		master.Commit()
	}
	<-done
}

// A Multi Publisher queue: n-Publishers <==> 1 Consumer
func TestMultiQueueSmallType1(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewMultiPublishNode(32)
	slave := NewSimpleConsumeNode()
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < 64; i++ {
			slave.Reserve()
			slave.Commit()

		}
		close(done)
	}()
	for i := int64(0); i < 64; i++ {
		master.Reserve()
		master.Commit()
	}
	<-done
}

// A simple queue: Publisher <==> Consumer
func TestSimpleQueueSmallType2(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewSimpleNode(true, 32)
	slave := NewSimpleNode(false, 32)
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < 64; i++ {
			ndx := slave.Reserve()
			slave.Commit(ndx)
		}
		close(done)
	}()

	for i := int64(0); i < 64; i++ {
		ndx := master.Reserve()
		master.Commit(ndx)
	}
	<-done
}

// A simple queue: Publisher <==> Consumer With larger buffer.
func TestSimpleQueueLargeType2(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewSimpleNode(true, PT32Meg)
	slave := NewSimpleNode(false, PT32Meg)
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < PT64Meg; i++ {
			ndx := slave.Reserve()
			slave.Commit(ndx)
		}
		close(done)
	}()

	for i := int64(0); i < PT64Meg; i++ {
		ndx := master.Reserve()
		master.Commit(ndx)
	}
	<-done
}

// A Multi Publisher queue: n-Publishers <==> 1 Consumer
func TestMultiQueueSmallType2(t *testing.T) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)

	master := NewMultiNode(true, 32)
	slave := NewSimpleNode(false, 32)
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < 64; i++ {
			ndx := slave.Reserve()
			slave.Commit(ndx)

		}
		close(done)
	}()
	for i := int64(0); i < 64; i++ {
		ndx := master.Reserve()
		master.Commit(ndx)
	}
	<-done
}

// BENCHMARKING TESTS
// go test -run=XXX -bench .

func BenchmarkSimpleQueueType1(b *testing.B) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)
	interations := int64(b.N)

	master := NewSimplePublishNode(PT64Meg)
	slave := NewSimpleConsumeNode()
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < interations; i++ {
			slave.Reserve()
			slave.Commit()
		}
		close(done)
	}()

	b.ReportAllocs()
	b.ResetTimer()
	for i := int64(0); i < interations; i++ {
		master.Reserve()
		master.Commit()
	}
	b.StopTimer()
	<-done

}

func BenchmarkMultiQueueType1(b *testing.B) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)
	interations := int64(b.N)

	master := NewMultiPublishNode(PT64Meg)
	slave := NewSimpleConsumeNode()
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < interations; i++ {
			slave.Reserve()
			slave.Commit()
		}
		close(done)
	}()

	b.ReportAllocs()
	b.ResetTimer()
	for i := int64(0); i < interations; i++ {
		master.Reserve()
		master.Commit()
	}

	b.StopTimer()
	<-done
}

func BenchmarkSimpleQueueType2(b *testing.B) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)
	interations := int64(b.N)

	master := NewSimpleNode(true, PT64Meg)
	slave := NewSimpleNode(false, PT64Meg)
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < interations; i++ {
			ndx := slave.Reserve()
			slave.Commit(ndx)
		}
		close(done)
	}()

	b.ReportAllocs()
	b.ResetTimer()
	for i := int64(0); i < interations; i++ {
		ndx := master.Reserve()
		master.Commit(ndx)
	}
	b.StopTimer()
	<-done
}

func BenchmarkMultiQueueType2(b *testing.B) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)
	interations := int64(b.N)

	master := NewMultiNode(true, PT64Meg)
	slave := NewSimpleNode(false, PT64Meg)
	master.SetDependency(slave.Committed())
	slave.SetDependency(master.Committed())

	done := make(chan bool)

	go func() {
		for i := int64(0); i < interations; i++ {
			ndx := slave.Reserve()
			slave.Commit(ndx)
		}
		close(done)
	}()

	b.ReportAllocs()
	b.ResetTimer()
	for i := int64(0); i < interations; i++ {
		ndx := master.Reserve()
		master.Commit(ndx)
	}
	b.StopTimer()
	<-done
}

// Baseline queue test using Golang Channel
func BenchmarkChannelCompare(b *testing.B) {
	prevProcs := runtime.GOMAXPROCS(-1)
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer runtime.GOMAXPROCS(prevProcs)
	interations := int64(b.N)

	queue := make(chan bool, interations)
	done := make(chan bool)

	go func(q chan bool, d chan bool) {
		i := int64(0)
		for i < interations {
			select {
			case <-q:
				i++
			default:
			}
			runtime.Gosched()
		}
		d <- true
	}(queue, done)

	b.ReportAllocs()
	b.ResetTimer()
	for i := int64(0); i < interations; i++ {
		queue <- true
	}

	b.StopTimer()
	<-done
}


text:
/*
 * 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.
 */
package io.trino.plugin.phoenix5;

import com.google.common.collect.ImmutableMap;
import io.trino.Session;
import io.trino.plugin.jdbc.BaseJdbcConnectorTest;
import io.trino.plugin.jdbc.UnsupportedTypeHandling;
import io.trino.testing.QueryRunner;
import io.trino.testing.TestingConnectorBehavior;
import io.trino.testing.sql.SqlExecutor;
import io.trino.testing.sql.TestTable;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import static io.trino.plugin.jdbc.TypeHandlingJdbcSessionProperties.UNSUPPORTED_TYPE_HANDLING;
import static io.trino.plugin.jdbc.UnsupportedTypeHandling.CONVERT_TO_VARCHAR;
import static io.trino.plugin.phoenix5.PhoenixQueryRunner.createPhoenixQueryRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.testng.Assert.assertTrue;

public class TestPhoenixConnectorTest
        extends BaseJdbcConnectorTest
{
    private TestingPhoenixServer testingPhoenixServer;

    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        testingPhoenixServer = TestingPhoenixServer.getInstance();
        return createPhoenixQueryRunner(testingPhoenixServer, ImmutableMap.of());
    }

    @AfterClass(alwaysRun = true)
    public void destroy()
    {
        TestingPhoenixServer.shutDown();
    }

    @Override
    protected boolean hasBehavior(TestingConnectorBehavior connectorBehavior)
    {
        switch (connectorBehavior) {
            case SUPPORTS_LIMIT_PUSHDOWN:
            case SUPPORTS_TOPN_PUSHDOWN:
            case SUPPORTS_AGGREGATION_PUSHDOWN:
                return false;

            case SUPPORTS_COMMENT_ON_TABLE:
            case SUPPORTS_COMMENT_ON_COLUMN:
                return false;

            case SUPPORTS_RENAME_TABLE:
                return false;

            default:
                return super.hasBehavior(connectorBehavior);
        }
    }

    @Override
    protected TestTable createTableWithDefaultColumns()
    {
        throw new SkipException("Phoenix connector does not support column default values");
    }

    @Override
    protected TestTable createTableWithUnsupportedColumn()
    {
        // Apparently all Phoenix types are supported in the Phoenix connector.
        throw new SkipException("Cannot find an unsupported data type");
    }

    @Override
    public void testRenameColumn()
    {
        assertThatThrownBy(super::testRenameColumn)
                // TODO (https://github.com/trinodb/trino/issues/7205) support column rename in Phoenix
                .hasMessageContaining("Syntax error. Encountered \"RENAME\"");
        throw new SkipException("Rename column is not yet supported by Phoenix connector");
    }

    @Override
    public void testInsert()
    {
        String query = "SELECT orderdate, orderkey, totalprice FROM orders";

        assertUpdate("CREATE TABLE test_insert WITH (ROWKEYS='orderkey') AS " + query + " WITH NO DATA", 0);
        assertQuery("SELECT count(*) FROM test_insert", "SELECT 0");

        assertUpdate("INSERT INTO test_insert " + query, "SELECT count(*) FROM orders");

        assertQuery("SELECT * FROM test_insert", query);

        assertUpdate("INSERT INTO test_insert (orderkey) VALUES (-1)", 1);
        assertUpdate("INSERT INTO test_insert (orderkey) VALUES (-1)", 1); // Phoenix Upsert
        assertUpdate("INSERT INTO test_insert (orderkey) VALUES (-2)", 1);
        assertUpdate("INSERT INTO test_insert (orderkey, orderdate) VALUES (-3, DATE '2001-01-01')", 1);
        assertUpdate("INSERT INTO test_insert (orderkey, orderdate) VALUES (-4, DATE '2001-01-02')", 1);
        assertUpdate("INSERT INTO test_insert (orderdate, orderkey) VALUES (DATE '2001-01-03', -5)", 1);
        assertUpdate("INSERT INTO test_insert (orderkey, totalprice) VALUES (-6, 1234)", 1);

        assertQuery("SELECT * FROM test_insert", query
                + " UNION ALL SELECT null, -1, null"
                + " UNION ALL SELECT null, -2, null"
                + " UNION ALL SELECT DATE '2001-01-01', -3, null"
                + " UNION ALL SELECT DATE '2001-01-02', -4, null"
                + " UNION ALL SELECT DATE '2001-01-03', -5, null"
                + " UNION ALL SELECT null, -6, 1234");

        // UNION query produces columns in the opposite order
        // of how they are declared in the table schema
        assertUpdate(
                "INSERT INTO test_insert (orderkey, orderdate, totalprice) " +
                        "SELECT orderkey, orderdate, totalprice FROM orders " +
                        "UNION ALL " +
                        "SELECT orderkey, orderdate, totalprice FROM orders",
                "SELECT 2 * count(*) FROM orders");

        assertUpdate("DROP TABLE test_insert");
    }

    @Override
    public void testInsertArray()
    {
        assertThatThrownBy(super::testInsertArray)
                // TODO (https://github.com/trinodb/trino/issues/6421) array with double null stored as array with 0
                .hasMessageContaining("Actual rows (up to 100 of 1 extra rows shown, 2 rows in total):\n" +
                        "    [0.0, null]\n" +
                        "Expected rows (up to 100 of 1 missing rows shown, 2 rows in total):\n" +
                        "    [null, null]");
    }

    @Override
    public void testCreateSchema()
    {
        throw new SkipException("test disabled until issue fixed"); // TODO https://github.com/trinodb/trino/issues/2348
    }

    @Override
    protected boolean isColumnNameRejected(Exception exception, String columnName, boolean delimited)
    {
        // TODO This should produce a reasonable exception message like "Invalid column name". Then, we should verify the actual exception message
        return columnName.equals("a\"quote");
    }

    @Override
    public void testDataMappingSmokeTest(DataMappingTestSetup dataMappingTestSetup)
    {
        // TODO enable the test
        throw new SkipException("test fails on Phoenix");
    }

    @Override
    public void testShowCreateTable()
    {
        assertThat(computeActual("SHOW CREATE TABLE orders").getOnlyValue())
                .isEqualTo("CREATE TABLE phoenix.tpch.orders (\n" +
                        "   orderkey bigint,\n" +
                        "   custkey bigint,\n" +
                        "   orderstatus varchar(1),\n" +
                        "   totalprice double,\n" +
                        "   orderdate date,\n" +
                        "   orderpriority varchar(15),\n" +
                        "   clerk varchar(15),\n" +
                        "   shippriority integer,\n" +
                        "   comment varchar(79)\n" +
                        ")\n" +
                        "WITH (\n" +
                        "   data_block_encoding = 'FAST_DIFF',\n" +
                        "   rowkeys = 'ROWKEY',\n" +
                        "   salt_buckets = 10\n" +
                        ")");
    }

    @Test
    public void testSchemaOperations()
    {
        assertUpdate("CREATE SCHEMA new_schema");
        assertUpdate("CREATE TABLE new_schema.test (x bigint)");

        assertThatThrownBy(() -> getQueryRunner().execute("DROP SCHEMA new_schema"))
                .isInstanceOf(RuntimeException.class)
                .hasMessage("ERROR 723 (43M06): Cannot mutate schema as schema has existing tables schemaName=NEW_SCHEMA");

        assertUpdate("DROP TABLE new_schema.test");
        assertUpdate("DROP SCHEMA new_schema");
    }

    @Test
    public void testMultipleSomeColumnsRangesPredicate()
    {
        assertQuery("SELECT orderkey, shippriority, clerk, totalprice, custkey FROM orders WHERE orderkey BETWEEN 10 AND 50 OR orderkey BETWEEN 100 AND 150");
    }

    @Test
    public void testUnsupportedType()
            throws Exception
    {
        executeInPhoenix("CREATE TABLE tpch.test_timestamp (pk bigint primary key, val1 timestamp)");
        executeInPhoenix("UPSERT INTO tpch.test_timestamp (pk, val1) VALUES (1, null)");
        executeInPhoenix("UPSERT INTO tpch.test_timestamp (pk, val1) VALUES (2, '2002-05-30T09:30:10.5')");
        assertUpdate("INSERT INTO test_timestamp VALUES (3)", 1);
        assertQuery("SELECT * FROM test_timestamp", "VALUES 1, 2, 3");
        assertQuery(
                withUnsupportedType(CONVERT_TO_VARCHAR),
                "SELECT * FROM test_timestamp",
                "VALUES " +
                        "(1, null), " +
                        "(2, '2002-05-30 09:30:10.500'), " +
                        "(3, null)");
        assertQueryFails(
                withUnsupportedType(CONVERT_TO_VARCHAR),
                "INSERT INTO test_timestamp VALUES (4, '2002-05-30 09:30:10.500')",
                "Underlying type that is mapped to VARCHAR is not supported for INSERT: TIMESTAMP");
        assertUpdate("DROP TABLE tpch.test_timestamp");
    }

    private Session withUnsupportedType(UnsupportedTypeHandling unsupportedTypeHandling)
    {
        return Session.builder(getSession())
                .setCatalogSessionProperty("phoenix", UNSUPPORTED_TYPE_HANDLING, unsupportedTypeHandling.name())
                .build();
    }

    @Test
    public void testCreateTableWithProperties()
    {
        assertUpdate("CREATE TABLE test_create_table_with_properties (created_date date, a bigint, b double, c varchar(10), d varchar(10)) WITH(rowkeys = 'created_date row_timestamp, a,b,c', salt_buckets=10)");
        assertTrue(getQueryRunner().tableExists(getSession(), "test_create_table_with_properties"));
        assertTableColumnNames("test_create_table_with_properties", "created_date", "a", "b", "c", "d");
        assertThat(computeActual("SHOW CREATE TABLE test_create_table_with_properties").getOnlyValue())
                .isEqualTo("CREATE TABLE phoenix.tpch.test_create_table_with_properties (\n" +
                        "   created_date date,\n" +
                        "   a bigint NOT NULL,\n" +
                        "   b double NOT NULL,\n" +
                        "   c varchar(10) NOT NULL,\n" +
                        "   d varchar(10)\n" +
                        ")\n" +
                        "WITH (\n" +
                        "   data_block_encoding = 'FAST_DIFF',\n" +
                        "   rowkeys = 'A,B,C',\n" +
                        "   salt_buckets = 10\n" +
                        ")");

        assertUpdate("DROP TABLE test_create_table_with_properties");
    }

    @Test
    public void testCreateTableWithPresplits()
    {
        assertUpdate("CREATE TABLE test_create_table_with_presplits (rid varchar(10), val1 varchar(10)) with(rowkeys = 'rid', SPLIT_ON='\"1\",\"2\",\"3\"')");
        assertTrue(getQueryRunner().tableExists(getSession(), "test_create_table_with_presplits"));
        assertTableColumnNames("test_create_table_with_presplits", "rid", "val1");
        assertUpdate("DROP TABLE test_create_table_with_presplits");
    }

    @Test
    public void testSecondaryIndex()
            throws Exception
    {
        assertUpdate("CREATE TABLE test_primary_table (pk bigint, val1 double, val2 double, val3 double) with(rowkeys = 'pk')");
        executeInPhoenix("CREATE LOCAL INDEX test_local_index ON tpch.test_primary_table (val1)");
        executeInPhoenix("CREATE INDEX test_global_index ON tpch.test_primary_table (val2)");
        assertUpdate("INSERT INTO test_primary_table VALUES (1, 1.1, 1.2, 1.3)", 1);
        assertQuery("SELECT val1,val3 FROM test_primary_table where val1 < 1.2", "SELECT 1.1,1.3");
        assertQuery("SELECT val2,val3 FROM test_primary_table where val2 < 1.3", "SELECT 1.2,1.3");
        assertUpdate("DROP TABLE test_primary_table");
    }

    @Test
    public void testCaseInsensitiveNameMatching()
            throws Exception
    {
        executeInPhoenix("CREATE TABLE tpch.\"TestCaseInsensitive\" (\"pK\" bigint primary key, \"Val1\" double)");
        assertUpdate("INSERT INTO testcaseinsensitive VALUES (1, 1.1)", 1);
        assertQuery("SELECT Val1 FROM testcaseinsensitive where Val1 < 1.2", "SELECT 1.1");
    }

    @Test
    public void testMissingColumnsOnInsert()
            throws Exception
    {
        executeInPhoenix("CREATE TABLE tpch.test_col_insert(pk VARCHAR NOT NULL PRIMARY KEY, col1 VARCHAR, col2 VARCHAR)");
        assertUpdate("INSERT INTO test_col_insert(pk, col1) VALUES('1', 'val1')", 1);
        assertUpdate("INSERT INTO test_col_insert(pk, col2) VALUES('1', 'val2')", 1);
        assertQuery("SELECT * FROM test_col_insert", "SELECT 1, 'val1', 'val2'");
    }

    @Override
    protected TestTable createTableWithDoubleAndRealColumns(String name, List<String> rows)
    {
        return new TestTable(onRemoteDatabase(), name, "(t_double double primary key, u_double double, v_real float, w_real float)", rows);
    }

    @Override
    protected SqlExecutor onRemoteDatabase()
    {
        return sql -> {
            try {
                executeInPhoenix(sql);
            }
            catch (SQLException e) {
                throw new RuntimeException(e);
            }
        };
    }

    private void executeInPhoenix(String sql)
            throws SQLException
    {
        try (Connection connection = DriverManager.getConnection(testingPhoenixServer.getJdbcUrl());
                Statement statement = connection.createStatement()) {
            statement.execute(sql);
            connection.commit();
        }
    }
}


text:
var contentoptimizer_contentanalysis_data = function(aid) {
  data = new Array();
  data['keyword'] = document.getElementById('edit-seo-keyword').value;
  return data;
}


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

<title>com.survivingwithandroid.weather.lib.provider</title>
<meta name="date" content="2014-09-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.survivingwithandroid.weather.lib.provider

Interface Summary

Interface
Description

IProviderType

This interface provides the description of the weather provider.

IWeatherCodeProvider

Interface for converting the internal weather provider code into a unified weather code system

IWeatherProvider

Public interface that all the weather provider must implement.

Class Summary

Class
Description

WeatherProviderFactory
Deprecated

You shouldn't use this class anymore to instantiate a weather provider from 1.4.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
function varargout = patchGraph(nodes, edges, faces) %#ok<INUSL>
%PATCHGRAPH Transform 3D graph (mesh) into a patch handle
%
%   [PX, PY, PZ] = PATCHGRAPH(NODES, EDGES, FACES)
%   Transform the graph defined as a set of nodes, edges and faces in a
%   patch which can be drawn usind matlab function 'patch'.
%   The result is a set of 3 array of size [NV*NF], with NV being the
%   number of vertices per face, and NF being the total number of faces.
%   each array contains one coordinate of vertices of each patch.
%
%
%   ---------
%
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 28/06/2004.
%

if iscell(faces)
    p = zeros(length(faces), 1);
    for i = 1:length(faces)
        p(i) = patch( ...
            'Faces', faces{i}, ...
            'Vertices', nodes, ...
            'FaceColor', 'r', ...
            'EdgeColor', 'none') ;
    end
else
    p = patch( ...
        'Faces', faces, ...
        'Vertices', nodes, ...
        'FaceColor', 'r', ...
        'EdgeColor', 'none') ;
end

if nargout>0
    varargout{1}=p;
end


text:
package ua.com.fielden.platform.persistence.composite;

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

import org.hibernate.Session;
import org.junit.Test;

import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.persistence.types.EntityWithMoney;
import ua.com.fielden.platform.test_config.AbstractDaoTestCase;
import ua.com.fielden.platform.types.Money;

/**
 * Implements test cases for using entity with composite key, which includes testing of basic functionality such as method equals, as well as DB interaction.
 *
 * @author TG Team
 *
 */
public class DynamicCompositeKeyPersistenceTestCase extends AbstractDaoTestCase {

    private static final String keyPartOne = "key-1-1";

    @Test
    public void testThatCommonMethodsAreCorrectlyImplemented() {
        final String keyPartOne = "key-part-one";
        final EntityWithMoney keyPartTwo = new EntityWithMoney("key", "desc", new Money("200.00"));
        final EntityWithDynamicCompositeKey entity = new EntityWithDynamicCompositeKey(keyPartOne, keyPartTwo);

        final DynamicEntityKey key = entity.getKey();
        assertEquals("Incorrectly calculated hash code.", key.hashCode() * 23, entity.hashCode());

        final EntityWithDynamicCompositeKey entity2 = new EntityWithDynamicCompositeKey(keyPartOne, keyPartTwo);
        assertEquals("Should be equal.", entity, entity2);

        final EntityWithDynamicCompositeKey entity3 = new EntityWithDynamicCompositeKey("key-part-two", keyPartTwo); // "key-part-one" < "key-part-two"
        assertTrue("Incorrect comparison result", entity.compareTo(entity3) < 0);
    }

    @Test
    public void key_members_are_corectly_populated_upon_retrieval_of_entities_with_a_composite_key() {
        final EntityWithMoney ewm = co(EntityWithMoney.class).findByKey("key1");
        assertNotNull(ewm);
        final EntityWithDynamicCompositeKey result = co(EntityWithDynamicCompositeKey.class).findByKey(keyPartOne, ewm);
        assertNotNull(result);

        assertEquals(keyPartOne, result.getKeyPartOne());
        assertEquals(ewm, result.getKeyPartTwo());
    }

    @Override
    protected void populateDomain() {
        super.populateDomain();

        final EntityWithMoney ewm = save(new_(EntityWithMoney.class, "key1", "desc").setMoney(Money.of("20.00")));
        save(new_composite(EntityWithDynamicCompositeKey.class, keyPartOne, ewm));
    }
}


text:
import {Component, ChangeDetectionStrategy, ChangeDetectorRef, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'ngl-pill',
  templateUrl: './pill.jade',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.slds-pill]': 'true',
  },
})
export class NglPill {
  removable: boolean;
  unlinked: boolean = true;

  @Output() nglPillRemove = new EventEmitter();

  constructor(public detector: ChangeDetectorRef) {}

  remove() {
    this.nglPillRemove.emit(null);
  }
}


text:
class Browser;
class ExtensionHost;
class FileBrowserHandler;
class GURL;
class Profile;

namespace file_handler_util {

// Gets read-write file access permission flags.
int GetReadWritePermissions();
// Gets read-only file access permission flags.
int GetReadOnlyPermissions();

// Generates file task id for the file actin specified by the extension.
std::string MakeTaskID(const std::string& extension_id,
                       const std::string& action_id);

// Extracts action and extension id bound to the file task.
bool CrackTaskID(const std::string& task_id,
                 std::string* target_extension_id,
                 std::string* action_id);

// Struct that keeps track of when a handler was `last used.
// It is used to determine default file action for a file.
struct LastUsedHandler {
  LastUsedHandler(int t, const FileBrowserHandler* h, URLPatternSet p)
      : timestamp(t),
        handler(h),
        patterns(p) {
  }

  int timestamp;
  const FileBrowserHandler* handler;
  URLPatternSet patterns;
};

typedef std::vector<LastUsedHandler> LastUsedHandlerList;

// Generates list of tasks common for all files in |file_list|.
// The resulting list is sorted by last usage time.
bool FindCommonTasks(Profile* profile,
                     const std::vector<GURL>& files_list,
                     LastUsedHandlerList* named_action_list);

// Find the default task for a file whose url is |url|. (The default task is the
// task that is assigned to file browser task button by default).
bool GetDefaultTask(Profile* profile,
                    const GURL& url,
                    const FileBrowserHandler** handler);

// Helper class for executing file browser file action.
class FileTaskExecutor : public base::RefCountedThreadSafe<FileTaskExecutor> {
 public:

  FileTaskExecutor(Profile* profile,
                   const GURL source_url,
                   const std::string& extension_id,
                   const std::string& action_id);

  virtual ~FileTaskExecutor();

  // Initiates execution of file handler task for each element of |file_urls|.
  // Return |false| if the execution cannot be initiated.
  // Otherwise returns |true| and then eventually calls |Done|.
  bool Execute(const std::vector<GURL>& file_urls);

 protected:
   virtual Browser* browser() = 0;
   virtual void Done(bool success) = 0;

   Profile* profile() { return profile_; }

 private:
  struct FileDefinition {
    FileDefinition();
    ~FileDefinition();

    GURL target_file_url;
    FilePath virtual_path;
    FilePath absolute_path;
    bool is_directory;
  };

  typedef std::vector<FileDefinition> FileDefinitionList;
  class ExecuteTasksFileSystemCallbackDispatcher;
  void RequestFileEntryOnFileThread(
      const GURL& handler_base_url,
      const scoped_refptr<const Extension>& handler,
      int handler_pid,
      const std::vector<GURL>& file_urls);

  void ExecuteFailedOnUIThread();
  void ExecuteFileActionsOnUIThread(const std::string& file_system_name,
                                    const GURL& file_system_root,
                                    const FileDefinitionList& file_list,
                                    int handler_id);
  void SetupPermissionsAndDispatchEvent(const std::string& file_system_name,
                                        const GURL& file_system_root,
                                        const FileDefinitionList& file_list,
                                        int handler_pid_in,
                                        ExtensionHost* host);

  // Populates |handler_host_permissions| with file path-permissions pairs that
  // will be given to the handler extension host process.
  void InitHandlerHostFileAccessPermissions(
      const FileDefinitionList& file_list,
      const Extension* handler_extension,
      const std::string& action_id);
  // Registers file permissions from |handler_host_permissions_| with
  // ChildProcessSecurityPolicy for process with id |handler_pid|.
  void SetupHandlerHostFileAccessPermissions(int handler_pid);

  Profile* profile_;
  const GURL source_url_;
  const std::string extension_id_;
  const std::string action_id_;

  // (File path, permission for file path) pairs for the handler.
  std::vector<std::pair<FilePath, int> > handler_host_permissions_;
};

}  // namespace file_handler_util

#endif  // CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_HANDLER_UTIL_H_


text:
    <title>react & draft.js test</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/facebook/draft-js/examples/draft-0-10-0/rich/RichEditor.css">


text:
layout: post
title: PyClass Meeting - Setup, Decorators and web2py
date: 2011-12-30 19:56:39 UTC
updated: 2011-12-30 19:56:39 UTC
comments: false
categories: development python code
---

The free Python class (PyClass) at Noisebridge has rebooted and is being taught by Elizabeth Leddy (@eleddy) and Daniel Nowak (@kellankade), who are awesome.  For once I have time in the evening to show up!!!  I'm really stoked about this as I have been wanting to learn python for awhile but just never got around to it.  I plan on making this the first in a series of (weekly-ish) posts where I record the items we discussed.   Getting to it,  this week we covered basic setup, simple hello world, operators, decorators and the web2py framework.

I wont go into setting up Python on OS X because it is pretty straight foward.  One thing to note though is that, although python is already installed, it was suggested that we install a custom version from python.org.  Apparently, as with most of the preinstalled Apple items, much of the functionality was ripped out or tweaked.


text:
<?xml version="1.0" encoding="utf-8"?>
<doc>
  <assembly>
    <name>Gallio.PowerShellCommands</name>
  </assembly>
  <members>
    <member name="T:Gallio.PowerShellCommands.RunGallioCommand">
      A PowerShell Cmdlet for running Gallio.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ApplicationBaseDirectory">

        <para> The relative or absolute path of the application base directory. </para>
        <para> If relative, the path is based on the current working directory, so a value of "" causes the current working directory to be used. </para>
        <para> The default is "". </para>

    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.Assemblies">
      The list of relative or absolute paths of test assembly files to execute. This is required.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.DoNotRun">
      Sets whether to load the tests but not run them. This option may be used to produce a report that contains test metadata for consumption by other tools.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.Filter">
      Sets the filter expression to apply, which consists of one or more filter rules that may be combined using 'and', 'or', and 'not' and grouped with parentheses. A filter rule consists of a filter key followed by one or more comma-delimited matching values in the form 'key: value, "quoted value", /regular expression/'.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.HintDirectories">
      The list of directories used for loading assemblies and other dependent resources.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.IgnoreAnnotations">
      Sets whether to ignore annotations when determining the result code. If false (default), then error annotations, usually indicative of broken tests, will cause a failure result to be generated.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.NoEchoResults">
      Sets whether to echo results to the screen as tests finish. If this option is specified only the final summary statistics are displayed. Otherwise test results are echoed to the console in varying detail depending on the current verbosity level.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.PluginDirectories">
      Additional Gallio plugin directories to search recursively.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ReportDirectory">
      Sets the name of the directory where the reports will be put.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ReportNameFormat">
      Sets the format string to use to generate the reports filenames.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ReportTypes">
      A list of the types of reports to generate, separated by semicolons.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.RunnerExtensions">

        <para> Specifies the type, assembly, and parameters of custom test runner extensions to use during the test run in the form: '[Namespace.]Type,Assembly[;Parameters]'. </para>
        <para> eg. 'FancyLogger,MyCustomExtensions.dll;SomeParameters' </para>

    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.RunnerType">
      Sets the type of test runner to use.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ShadowCopy">

        <para> Enables shadow copying when set to true. </para>
        <para> Shadow copying allows the original assemblies to be modified while the tests are running. However, shadow copying may occasionally cause some tests to fail if they depend on their original location. </para>
        <para> The default is false. </para>

    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.ShowReports">
      Sets whether to open the generated reports once execution has finished.
    </member>
    <member name="P:Gallio.PowerShellCommands.RunGallioCommand.WorkingDirectory">

        <para> The relative or absolute path of the working directory. </para>
        <para> If relative, the path is based on the current working directory, so a value of "" causes the current working directory to be used. </para>
        <para> The default is "". </para>

    </member>
  </members>
</doc>


text:
nyaBsSelect is the main directive of this module. You can consider it as a select directive. It manipulates the the dropdown-toggle content and all user interaction.

###Usage

as element:
```html
<nya-bs-select
  ng-mode=""
  [multiple=""]
  [live-search=""]
  [required=""]
  [ng-required=""]
  [disabled=""]
  [size=""]
  [select-text-format=""]
  [title=""]>
...
</nya-bs-select>
```

as attribute:
```html
<ANY
  nya-bs-select
  ng-mode=""
  [multiple=""]
  [live-search=""]
  [required=""]
  [ng-required=""]
  [disabled=""]
  [size=""]
  [select-text-format=""]
  [title=""]>
...
</ANY>
```

as class:
```html
<ANY
  class="nya-bs-select"
  ng-mode=""
  [multiple=""]
  [live-search=""]
  [required=""]
  [ng-required=""]
  [disabled=""]
  [size=""]
  [select-text-format=""]
  [title=""]>
...
</ANY>
```

###Arguments

    Param
    Type
    Details

    ngModel
    string
    Assignable angular expression to data-bind to

    multiple(optional)
    string
    Act as a multiple select control if multiple attribute is set.

    live-search(optional)
    string
    Provide a input box to search through all option content only if `live-search="true"`

    required
    string
    The control is considered valid if ngModel value is defined or not an empty array(for multiple)

    ng-required
    string
    Adds required attribute and required validation constraints to the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of required when you want to data-bind to the required attribute

    disabled
    expression
    if the expression is truthy, then the whole control will be disabled.

    size
    number
    Sets max number which the dropdown-menu can show. if the number of options exceed the limit. an scrollbar will be shown.

    select-text-format
    string

      Sets the content format of dropdown-toggle.

          if sets to `value`, the dropdown-toggle button will show content user has selected, this is default value.

          if sets to `count`, the dropdown-toggle button will show the number of options user has selected.

          if sets to `count>x`, the dropdown-toggle button will show the number of user selected options when the number of options greater than x. otherwise, show the content.

    title
    string
    provide a replacement for default text when nothing is selected.


text:
package org.apache.beam.sdk.extensions.sql;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.beam.sdk.schemas.Schema.FieldType.INT64;
import static org.apache.beam.sdk.schemas.Schema.FieldType.STRING;
import static org.hamcrest.Matchers.containsInAnyOrder;

import java.io.Serializable;
import java.util.List;
import org.apache.beam.sdk.extensions.sql.impl.BeamSqlEnv;
import org.apache.beam.sdk.extensions.sql.impl.rel.BeamSqlRelUtils;
import org.apache.beam.sdk.extensions.sql.meta.provider.bigquery.BigQueryTableProvider;
import org.apache.beam.sdk.extensions.sql.meta.provider.pubsub.PubsubJsonTableProvider;
import org.apache.beam.sdk.io.gcp.bigquery.TestBigQuery;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
import org.apache.beam.sdk.io.gcp.pubsub.TestPubsub;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Integration tests form writing to BigQuery with Beam SQL. */
@RunWith(JUnit4.class)
public class PubsubToBigqueryIT implements Serializable {
  private static final Schema SOURCE_SCHEMA =
      Schema.builder().addNullableField("id", INT64).addNullableField("name", STRING).build();

  @Rule public transient TestPipeline pipeline = TestPipeline.create();
  @Rule public transient TestPubsub pubsub = TestPubsub.create();
  @Rule public transient TestBigQuery bigQuery = TestBigQuery.create(SOURCE_SCHEMA);

  @Test
  public void testSimpleInsert() throws Exception {
    BeamSqlEnv sqlEnv =
        BeamSqlEnv.inMemory(new PubsubJsonTableProvider(), new BigQueryTableProvider());

    String createTableString =
        "CREATE EXTERNAL TABLE pubsub_topic (\n"
            + "event_timestamp TIMESTAMP, \n"
            + "attributes MAP<VARCHAR, VARCHAR>, \n"
            + "payload ROW< \n"
            + "             id INTEGER, \n"
            + "             name VARCHAR \n"
            + "           > \n"
            + ") \n"
            + "TYPE 'pubsub' \n"
            + "LOCATION '"
            + pubsub.topicPath()
            + "' \n"
            + "TBLPROPERTIES '{ \"timestampAttributeKey\" : \"ts\" }'";
    sqlEnv.executeDdl(createTableString);

    String createTableStatement =
        "CREATE EXTERNAL TABLE bq_table( \n"
            + "   id BIGINT, \n"
            + "   name VARCHAR \n "
            + ") \n"
            + "TYPE 'bigquery' \n"
            + "LOCATION '"
            + bigQuery.tableSpec()
            + "'";
    sqlEnv.executeDdl(createTableStatement);

    String insertStatement =
        "INSERT INTO bq_table \n"
            + "SELECT \n"
            + "  pubsub_topic.payload.id, \n"
            + "  pubsub_topic.payload.name \n"
            + "FROM pubsub_topic";

    BeamSqlRelUtils.toPCollection(pipeline, sqlEnv.parseQuery(insertStatement));

    pipeline.run();

    List<PubsubMessage> messages =
        ImmutableList.of(
            message(ts(1), 3, "foo"), message(ts(2), 5, "bar"), message(ts(3), 7, "baz"));
    pubsub.publish(messages);

    bigQuery
        .assertThatAllRows(SOURCE_SCHEMA)
        .eventually(
            containsInAnyOrder(
                row(SOURCE_SCHEMA, 3L, "foo"),
                row(SOURCE_SCHEMA, 5L, "bar"),
                row(SOURCE_SCHEMA, 7L, "baz")))
        .pollFor(Duration.standardMinutes(5));
  }

  private Row row(Schema schema, Object... values) {
    return Row.withSchema(schema).addValues(values).build();
  }

  private PubsubMessage message(Instant timestamp, int id, String name) {
    return message(timestamp, jsonString(id, name));
  }

  private PubsubMessage message(Instant timestamp, String jsonPayload) {
    return new PubsubMessage(
        jsonPayload.getBytes(UTF_8), ImmutableMap.of("ts", String.valueOf(timestamp.getMillis())));
  }

  private String jsonString(int id, String name) {
    return "{ \"id\" : " + id + ", \"name\" : \"" + name + "\" }";
  }

  private Instant ts(long millis) {
    return new Instant(millis);
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace MovePeopleDataToXML
{
    public class Startup
    {
        private static void Main()
        {
            var people = ReadPeopleData("../../Files/people.txt");
            WritePeopleDataToXMLFile("../../Files/people.xml", people);

            Console.WriteLine("Done");
        }

        private static void WritePeopleDataToXMLFile(string fileUrl, IEnumerable<IPerson> people)
        {
            var peopleElement = new XElement("people");
            foreach (var person in people)
            {
                var personElement = new XElement("person",
                        new XElement("firstName", person.FirstName),
                        new XElement("lastName", person.LastName),
                        new XElement("phoneNumber", person.PhoneNumber)
                    );
                peopleElement.Add(personElement);
            }

            peopleElement.Save(fileUrl);
        }

        private static IEnumerable<IPerson> ReadPeopleData(string fileUrl)
        {
            var people = new List<IPerson>();
            using (StreamReader reader = new StreamReader(fileUrl))
            {
                var line = reader.ReadLine();
                while (line != null)
                {
                    var person = ParsePersonData(line);
                    people.Add(person);

                    line = reader.ReadLine();
                }
            }

            return people;
        }

        private static IPerson ParsePersonData(string data)
        {
            var tokens = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length != 3)
            {
                throw new ArgumentException("Person must have first name, last name, phone number!");
            }

            string firstName = tokens[0];
            string lastName = tokens[1];
            string phoneNumber = tokens[2];
            var person = new Person(firstName, lastName, phoneNumber);

            return person;
        }
    }
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

#pragma once
#if __has_include(<thrift/compiler/test/fixtures/adapter/src/gen-cpp2/Service.h>)
#include <thrift/compiler/test/fixtures/adapter/src/gen-cpp2/Service.h>
#else
#include <thrift/compiler/test/fixtures/adapter/src/gen-cpp2/module_handlers.h>
#endif
#if __has_include(<thrift/compiler/test/fixtures/adapter/src/gen-cpp2/AdapterService.h>)
#include <thrift/compiler/test/fixtures/adapter/src/gen-cpp2/AdapterService.h>
#else
#include <thrift/compiler/test/fixtures/adapter/src/gen-cpp2/module_handlers.h>
#endif
#include <folly/python/futures.h>
#include <Python.h>

#include <memory>

namespace facebook {
namespace thrift {
namespace test {

class ServiceWrapper : virtual public ServiceSvIf {
  protected:
    PyObject *if_object;
    folly::Executor *executor;
  public:
    explicit ServiceWrapper(PyObject *if_object, folly::Executor *exc);
    void async_tm_func(std::unique_ptr<apache::thrift::HandlerCallback<int32_t>> callback
        , std::unique_ptr<std::string> arg1
        , std::unique_ptr<std::string> arg2
        , std::unique_ptr<::facebook::thrift::test::Foo> arg3
    ) override;
folly::SemiFuture<folly::Unit> semifuture_onStartServing() override;
folly::SemiFuture<folly::Unit> semifuture_onStopRequested() override;
};

std::shared_ptr<apache::thrift::ServerInterface> ServiceInterface(PyObject *if_object, folly::Executor *exc);

class AdapterServiceWrapper : virtual public AdapterServiceSvIf {
  protected:
    PyObject *if_object;
    folly::Executor *executor;
  public:
    explicit AdapterServiceWrapper(PyObject *if_object, folly::Executor *exc);
    void async_tm_count(std::unique_ptr<apache::thrift::HandlerCallback<std::unique_ptr<::facebook::thrift::test::CountingStruct>>> callback) override;
    void async_tm_adaptedTypes(std::unique_ptr<apache::thrift::HandlerCallback<std::unique_ptr<::facebook::thrift::test::HeapAllocated>>> callback
        , std::unique_ptr<::facebook::thrift::test::HeapAllocated> arg
    ) override;
folly::SemiFuture<folly::Unit> semifuture_onStartServing() override;
folly::SemiFuture<folly::Unit> semifuture_onStopRequested() override;
};

std::shared_ptr<apache::thrift::ServerInterface> AdapterServiceInterface(PyObject *if_object, folly::Executor *exc);
} // namespace facebook
} // namespace thrift
} // namespace test


text:
package org.innovateuk.ifs.filter;

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.NestedServletException;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ErrorHandlerFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception ex) {
            if(ex instanceof NestedServletException && ((NestedServletException) ex).getRootCause() instanceof org.thymeleaf.exceptions.TemplateProcessingException) {
                    request.setAttribute("message", "There was a problem processing this request.  Please contact site administrator");
                    RequestDispatcher rd = request.getRequestDispatcher("/rendering-error");
                    rd.forward(request, response);
            }
        }
    }
}


text:
require_recipe 'ruby_shadow'

# node contains attributes from run_list, automatic attributes (ohai generated)
# node is a ruby mash, so can be accessed as hash or using syntactical sugar like node.users
node[:users].each do |name, conf|
  home_dir = "/home/#{name}"

  user name do
    password conf[:password]
    action [:create]
  end

  directory home_dir do
    owner name
    group name
    mode 0700
  end

  directory "#{home_dir}/.ssh" do
    owner name
    group name
    mode 0700
  end

  template "#{home_dir}/.ssh/authorized_keys" do
    owner name
    mode 0600
    variables :keys => conf[:ssh_keys]
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="DROP TABLE statement" />
<meta content="DROP TABLE statement, Tables, dropping" name="DC.subject" />
<meta content="DROP TABLE statement, Tables, dropping" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj80721.html" />
<meta scheme="URI" name="DC.Relation" content="rrefdropfunctionstatement.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj59893.html" />
<meta scheme="URI" name="DC.Relation" content="rrefdropprocedurestatement.html" />
<meta scheme="URI" name="DC.Relation" content="rrefdroprole.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj31648.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqljdropsequence.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqljdropsynonym.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj42082.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqljdroptype.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj61102.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj34148" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>DROP TABLE statement</title>

DROP TABLE statement

DROP TABLE removes the specified table.

Syntax

DROP TABLE table-Name

Statement dependency system

Triggers,
constraints (primary, unique, check and references from the table being dropped)
and indexes on the table are silently dropped. The existence of an open cursor
that references table being dropped cause the DROP TABLE statement to generate
an error, and the table is not dropped.

Dropping a table invalidates
statements that depend on the table. (Invalidating a statement causes it to
be recompiled upon the next execution. See Interaction with the dependency system.)

Parent topic: DROP statements

Related reference

DROP FUNCTION statement

DROP INDEX statement

DROP PROCEDURE statement

DROP ROLE statement

DROP SCHEMA statement

DROP SEQUENCE statement

DROP SYNONYM statement

DROP TRIGGER statement

DROP TYPE statement

DROP VIEW statement