text:
package org.diorite.impl.world.chunk;

import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import org.diorite.impl.Tickable;
import org.diorite.impl.world.WorldImpl;
import org.diorite.impl.world.generator.ChunkBuilderImpl;
import org.diorite.impl.world.io.ChunkIoService;
import org.diorite.event.EventType;
import org.diorite.event.chunk.ChunkGenerateEvent;
import org.diorite.event.chunk.ChunkLoadEvent;
import org.diorite.event.chunk.ChunkPopulateEvent;
import org.diorite.utils.math.pack.IntsToLong;
import org.diorite.world.chunk.Chunk;
import org.diorite.world.chunk.ChunkManager;
import org.diorite.world.chunk.ChunkPos;
import org.diorite.world.generator.WorldGenerator;
import org.diorite.world.generator.maplayer.MapLayer;

public class ChunkManagerImpl implements ChunkManager, Tickable
{

    /**
     * The world this ChunkManager is managing.
     */
    private final WorldImpl world;

    /**
     * The chunk I/O service used to read chunks from the disk and write them to
     * the disk.
     */
    private final ChunkIoService service;

    /**
     * The chunk generator used to generate new chunks.
     */
    private final WorldGenerator generator;

    /**
     * The biome maps used to fill chunks biome grid and terrain generation.
     */
    private final MapLayer[] biomeGrid;

    /**
     * A map of chunks currently loaded in memory.
     */
    private final ConcurrentMap<Long, ChunkImpl> chunks = new ConcurrentHashMap<>(1000, .25f, 8);

    /**
     * A map of chunks which are being kept loaded by players or other factors.
     */
    private final ConcurrentMap<Long, Set<ChunkLock>> locks = new ConcurrentHashMap<>(1000, .25f, 8);

    public ChunkManagerImpl(final WorldImpl world, final ChunkIoService service, final WorldGenerator generator)
    {
        this.world = world;
        this.service = service;
        this.generator = generator;
        this.biomeGrid = MapLayer.initialize(world.getSeed(), world.getDimension(), world.getWorldType());
    }

    /**
     * Get the chunk generator.
     */
    public WorldGenerator getGenerator()
    {
        return this.generator;
    }

    public ChunkIoService getService()
    {
        return this.service;
    }

    public MapLayer[] getBiomeGrid()
    {
        return this.biomeGrid;
    }

    public WorldImpl getWorld()
    {
        return this.world;
    }

    @Override
    public ChunkImpl getChunk(final ChunkPos pos)
    {
        return this.getChunk(pos.getX(), pos.getZ());
    }

    /**
     * Gets a chunk object representing the specified coordinates, which might
     * not yet be loaded.
     *
     * @param x The X coordinate.
     * @param z The Z coordinate.
     *
     * @return The chunk.
     */
    @Override
    public ChunkImpl getChunk(final int x, final int z)
    {
        final Long key = IntsToLong.pack(x, z);
        if (this.chunks.containsKey(key))
        {
            return this.chunks.get(key);
        }
        else
        {
            // only create chunk if it's not in the map already
            final ChunkImpl chunk = new ChunkImpl(new ChunkPos(x, z, this.world));
            final ChunkImpl prev = this.chunks.putIfAbsent(key, chunk);
            // if it was created in the intervening time, the earlier one wins
            return (prev == null) ? chunk : prev;
        }
    }

    /**
     * Checks if the Chunk at the specified coordinates is loaded.
     *
     * @param x The X coordinate.
     * @param z The Z coordinate.
     *
     * @return true if the chunk is loaded, otherwise false.
     */
    @Override
    public boolean isChunkLoaded(final int x, final int z)
    {
        final Long key = IntsToLong.pack(x, z);
        final ChunkImpl chunk = this.chunks.get(key);
        return (chunk != null) && chunk.isLoaded();
    }

    /**
     * Check whether a chunk has locks on it preventing it from being unloaded.
     *
     * @param x The X coordinate.
     * @param z The Z coordinate.
     *
     * @return Whether the chunk is in use.
     */
    @Override
    public boolean isChunkInUse(final int x, final int z)
    {
        final Long key = IntsToLong.pack(x, z);
        final Set<ChunkLock> lockSet = this.locks.get(key);
        return (lockSet != null) && ! lockSet.isEmpty();
    }

    /**
     * Call the ChunkIoService to load a chunk, optionally generating the chunk.
     *
     * @param x        The X coordinate of the chunk to load.
     * @param z        The Y coordinate of the chunk to load.
     * @param generate Whether to generate the chunk if needed.
     *
     * @return True on success, false on failure.
     */
    @Override
    public boolean loadChunk(final int x, final int z, final boolean generate)
    {
        final ChunkLoadEvent loadEvt = new ChunkLoadEvent(new ChunkPos(x, z, this.world));
        EventType.callEvent(loadEvt);
        if (loadEvt.isCancelled())
        {
            return false;
        }
        final ChunkImpl chunk = (ChunkImpl) loadEvt.getLoadedChunk();

        if (chunk == null)
        {
            throw new NullPointerException("Loaded null chunk from: " + x + ", " + z);
        }
        // stop here if we can't generate
        if (! generate || ! loadEvt.isNeedBeGenerated())
        {
            return false;
        }

        // get generating
        final ChunkGenerateEvent genEvt = new ChunkGenerateEvent(chunk);
        EventType.callEvent(genEvt);
        return ! genEvt.isCancelled();
    }

    /**
     * Unload chunks with no locks on them.
     */
    @Override
    public void unloadOldChunks()
    {
        for (final Map.Entry<Long, ChunkImpl> entry : this.chunks.entrySet())
        {
            final Set<ChunkLock> lockSet = this.locks.get(entry.getKey());
            if ((lockSet == null) || lockSet.isEmpty())
            {
                if (! entry.getValue().unload(true, true))
                {
                    System.err.println("[ChunkIO] Failed to unload chunk " + this.world.getName() + ":" + entry.getKey());
                }
            }
            // cannot remove old chunks from cache - Block and BlockState keep references.
            // they must either be changed to look up the chunk again all the time, or this code left out.
            /*if (!entry.getValue().isLoaded()) {
                chunks.entrySet().remove(entry);
                locks.remove(entry.getKey());
            }*/
        }
    }

    /**
     * Populate a single chunk if needed.
     */
    @Override
    public void populateChunk(final int x, final int z, final boolean force)
    {
        final ChunkImpl chunk = this.getChunk(x, z);
        final ChunkPopulateEvent popEvt = new ChunkPopulateEvent(chunk, force);
        EventType.callEvent(popEvt);
    }

    /**
     * Force a chunk to be populated by loading the chunks in an area around it. Used when streaming chunks to players
     * so that they do not have to watch chunks being populated.
     *
     * @param x The X coordinate.
     * @param z The Z coordinate.
     */
    @Override
    public void forcePopulation(final int x, final int z)
    {
        try
        {
            final ChunkImpl chunk = this.getChunk(x, z);
            final ChunkPopulateEvent popEvt = new ChunkPopulateEvent(chunk, true);
            EventType.callEvent(popEvt);
        } catch (final Throwable e)
        {
            System.err.println("[ChunkIO] Error while populating chunk (" + x + "," + z + ")");
            e.printStackTrace();
        }
    }

    /**
     * Initialize a single chunk from the chunk generator.
     */
    @Override
    public void generateChunk(final Chunk chunk, final int x, final int z)
    {
        final ChunkPos pos = new ChunkPos(x, z, this.world);
        this.generator.generate(this.generator.generateBiomes(new ChunkBuilderImpl(this.biomeGrid), pos), pos).init(chunk);
    }

    /**
     * Forces generation of the given chunk.
     *
     * @param x The X coordinate.
     * @param z The Z coordinate.
     *
     * @return Whether the chunk was successfully regenerated.
     */
    @Override
    public boolean forceRegeneration(final int x, final int z)
    {
        final ChunkImpl chunk = this.getChunk(x, z);

        if ((chunk == null) || ! chunk.unload(false, false))
        {
            return false;
        }
        chunk.setPopulated(false);
        try
        {
            final ChunkGenerateEvent genEvt = new ChunkGenerateEvent(chunk);
            EventType.callEvent(genEvt);
            if (genEvt.isCancelled())
            {
                return false;
            }
            final ChunkPopulateEvent popEvt = new ChunkPopulateEvent(chunk, false); // should this be forced?
            EventType.callEvent(popEvt);
            if (popEvt.isCancelled())
            {
                return false;
            }
        } catch (final Throwable e)
        {
            System.err.println("[ChunkIO] Error while regenerating chunk (" + x + "," + z + ")");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Gets a list of loaded chunks.
     *
     * @return The currently loaded chunks.
     */
    @Override
    public List<ChunkImpl> getLoadedChunks()
    {
        return this.chunks.values().stream().filter(ChunkImpl::isLoaded).collect(Collectors.toList());
    }

    /**
     * Performs the save for the given chunk using the storage provider.
     *
     * @param chunk The chunk to save.
     */
    @Override
    public boolean save(final Chunk chunk)
    {
        if (chunk.isLoaded())
        {
            try
            {
                this.service.write((ChunkImpl) chunk);
                return true;
            } catch (final IOException e)
            {
                System.err.println("[ChunkIO] Error while saving " + chunk);
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    public int[] getBiomeGridAtLowerRes(final int x, final int z, final int sizeX, final int sizeZ)
    {
        return this.biomeGrid[1].generateValues(x, z, sizeX, sizeZ);
    }

    @Override
    public void doTick(final int tps)
    {
        this.chunks.values().stream().filter(ChunkImpl::isLoaded).forEach(c -> {
            c.getTileEntities().forEachValue(t -> {
                t.doTick(tps);
                return true;
            });
        });
    }

    /**
     * Look up the set of locks on a given chunk.
     *
     * @param key The chunk key.
     *
     * @return The set of locks for that chunk.
     */
    private Collection<ChunkLock> getLockSet(final Long key)
    {
        if (this.locks.containsKey(key))
        {
            return this.locks.get(key);
        }
        else
        {
            // only create chunk if it's not in the map already
            final Set<ChunkLock> set = new HashSet<>(5);
            final Set<ChunkLock> prev = this.locks.putIfAbsent(key, set);
            // if it was created in the intervening time, the earlier one wins
            return (prev == null) ? set : prev;
        }
    }

    /**
     * A group of locks on chunks to prevent them from being unloaded while in use.
     */
    public static class ChunkLock implements Iterable<Long>
    {
        private final ChunkManagerImpl cm;
        private final String           desc;
        private final Collection<Long> keys = new HashSet<>(5);

        public ChunkLock(final ChunkManagerImpl cm, final String desc)
        {
            this.cm = cm;
            this.desc = desc;
        }

        public void acquire(final Long key)
        {
            if (this.keys.contains(key))
            {
                return;
            }
            this.keys.add(key);
            this.cm.getLockSet(key).add(this);
        }

        public void release(final Long key)
        {
            if (! this.keys.contains(key))
            {
                return;
            }
            this.keys.remove(key);
            this.cm.getLockSet(key).remove(this);
        }

        public void clear()
        {
            for (final Long key : this.keys)
            {
                this.cm.getLockSet(key).remove(this);
            }
            this.keys.clear();
        }

        @Override
        public Iterator<Long> iterator()
        {
            return this.keys.iterator();
        }

        @Override
        public String toString()
        {
            return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("cm", this.cm).append("desc", this.desc).append("keys", this.keys).toString();
        }
    }

    @Override
    public String toString()
    {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("world", this.world).append("generator", this.generator).toString();
    }
}


text:
namespace System.IdentityModel.Configuration
{
    using System.Configuration;
    using System.IdentityModel.Tokens;

#pragma warning disable 1591
    [ConfigurationCollection( typeof( CustomTypeElement ), CollectionType = ConfigurationElementCollectionType.BasicMap )]
    public sealed partial class SecurityTokenHandlerElementCollection : ConfigurationElementCollection
    {
        public SecurityTokenHandlerElementCollection()
        {
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new CustomTypeElement();
        }

        protected override object GetElementKey( ConfigurationElement element )
        {
            return ( (CustomTypeElement)element ).Type;
        }

        protected override void Init()
        {
            //
            // Keep this list synchronized with SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection
            //
            BaseAdd( new CustomTypeElement( typeof( SamlSecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( Saml2SecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( WindowsUserNameSecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( X509SecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( KerberosSecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( RsaSecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( SessionSecurityTokenHandler ) ) );
            BaseAdd( new CustomTypeElement( typeof( EncryptedSecurityTokenHandler ) ) );

        }

        [ConfigurationProperty( ConfigurationStrings.Name, Options = ConfigurationPropertyOptions.IsKey )]
        [StringValidator(MinLength = 0)]
        public string Name
        {
            get { return (string)this[ConfigurationStrings.Name]; }
            set { this[ConfigurationStrings.Name] = value; }
        }

        [ConfigurationProperty( ConfigurationStrings.SecurityTokenHandlerConfiguration, IsRequired = false )]
        public SecurityTokenHandlerConfigurationElement SecurityTokenHandlerConfiguration
        {
            get { return (SecurityTokenHandlerConfigurationElement)this[ConfigurationStrings.SecurityTokenHandlerConfiguration]; }
            set { this[ConfigurationStrings.SecurityTokenHandlerConfiguration] = value; }
        }

        /// <summary>
        /// Returns a value indicating whether this element has been configured with non-default values.
        /// </summary>
        internal bool IsConfigured
        {
            get
            {
                return ( ( ElementInformation.Properties[ConfigurationStrings.Name].ValueOrigin != PropertyValueOrigin.Default ) ||
                         SecurityTokenHandlerConfiguration.IsConfigured ||
                         Count > 0 );
            }
        }
    }

#pragma warning restore 1591
}

redpajama_set_name: RedPajamaGithub


text:
Configuration in this directory creates IAM group with users who are allowed to assume IAM roles and extended with IAM policies.

This is a combination of `iam-group-with-assumable-roles-policy` and `iam-group-with-policies` exampled.

# Usage

To run this example you need to execute:

```bash
$ terraform init
$ terraform plan
$ terraform apply
```

Run `terraform destroy` when you don't need these resources.

## Requirements

| Name | Version |
|------|---------|
|  [terraform](#requirement\_terraform) | >= 1.0 |
|  [aws](#requirement\_aws) | >= 4.0 |

## Providers

No providers.

## Modules

| Name | Source | Version |
|------|--------|---------|
|  [iam\_group\_complete](#module\_iam\_group\_complete) | ../../modules/iam-group-with-assumable-roles-policy | n/a |
|  [iam\_group\_complete\_with\_custom\_policy](#module\_iam\_group\_complete\_with\_custom\_policy) | ../../modules/iam-group-with-policies | n/a |
|  [iam\_user1](#module\_iam\_user1) | ../../modules/iam-user | n/a |
|  [iam\_user2](#module\_iam\_user2) | ../../modules/iam-user | n/a |

## Resources

No resources.

## Inputs

No inputs.

## Outputs

| Name | Description |
|------|-------------|
|  [assumable\_roles](#output\_assumable\_roles) | List of ARNs of IAM roles which members of IAM group can assume |
|  [group\_users](#output\_group\_users) | List of IAM users in IAM group |
|  [policy\_arn](#output\_policy\_arn) | Assume role policy ARN for IAM group |


text:
package game.saver.interfaces;

import game.saver.Quarry;
import java.io.RandomAccessFile;

/**
 *
 * @author MrInformatic
 */
public interface Seriable {
    public void write(Quarry quarry);
    public void read(Quarry quarry);
}


text:
require_relative "../base_item"

module Greeve
  module Character
    # Notifications received when having been added to someone's contact list.
    #
    # @see https://eveonline-third-party-documentation.readthedocs.io/en/latest/xmlapi/character/char_contactnotifications.html
    class ContactNotifications < Greeve::BaseItem
      endpoint "char/ContactNotifications"

      rowset :contact_notifications, xpath: "eveapi/result/rowset[@name='contactNotifications']" do
        attribute :notification_id, xpath: "@notificationID", type: :integer
        attribute :sender_id,       xpath: "@senderID",       type: :integer
        attribute :sender_name,     xpath: "@senderName",     type: :string
        attribute :sent_date,       xpath: "@sentDate",       type: :datetime
        attribute :message_data,    xpath: "@messageData",    type: :hash
      end

      # @param character_id [Integer] EVE character ID
      def initialize(character_id, opts = {})
        opts[:query_params] = { "characterID" => character_id }
        super(opts)
      end
    end
  end
end


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

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

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

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

import React from 'react';
import ReactDOM from 'react-dom';
import ClickOutside from 'react-click-outside';
import PropTypes from 'prop-types';
import { default as Component } from '../Common/plugs/index.js'; //提供style, classname方法
import Input from '../Input';
import Suggestions from './Suggestions';
import '../Common/css/Autocomplete.css';

var AutoComplete = function (_Component) {
  _inherits(AutoComplete, _Component);

  function AutoComplete(props) {
    _classCallCheck(this, AutoComplete);

    var _this = _possibleConstructorReturn(this, (AutoComplete.__proto__ || Object.getPrototypeOf(AutoComplete)).call(this, props));

    _this.state = {
      inputValue: props.value,
      isFocus: false,
      suggestions: [],
      loading: false,
      highlightedIndex: -1
    };
    return _this;
  }

  _createClass(AutoComplete, [{
    key: 'getChildContext',
    value: function getChildContext() {
      return {
        component: this
      };
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(props) {
      this.setState({ inputValue: props.value });
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      var _this2 = this;

      var visible = this.suggestionVisible();
      var reference = this.inputNode ? ReactDOM.findDOMNode(this.inputNode) : null;
      if (reference instanceof HTMLElement) {
        setTimeout(function () {
          //if(visible && reference && reference.offsetWidth)
          if (reference && reference.offsetWidth) {
            console.log(_this2.suggestionsNode);
            _this2.suggestionsNode.onVisibleChange(visible, reference.offsetWidth);
          }
        });
      }
    }
  }, {
    key: 'getData',
    value: function getData(queryString) {
      var _this3 = this;

      this.setState({ loading: true });

      this.props.fetchSuggestions(queryString, function (suggestions) {
        _this3.setState({ loading: false });

        if (Array.isArray(suggestions)) {
          _this3.setState({ suggestions: suggestions });
        }
      });
    }
  }, {
    key: 'handleChange',
    value: function handleChange(value) {
      this.setState({ inputValue: value });

      if (!this.props.triggerOnFocus && !value) {
        this.setState({ suggestions: [] });return;
      }

      if (this.props.onChange) {
        this.props.onChange(value);
      }

      this.getData(value);
    }
  }, {
    key: 'handleFocus',
    value: function handleFocus(e) {
      this.setState({ isFocus: true });
      if (this.props.onFocus) this.props.onFocus(e);
      if (this.props.triggerOnFocus) {
        this.getData(this.state.inputValue);
      }
    }
  }, {
    key: 'handleKeyEnter',
    value: function handleKeyEnter(highlightedIndex) {
      if (this.suggestionVisible() && highlightedIndex >= 0 && highlightedIndex < this.state.suggestions.length) {
        this.select(this.state.suggestions[highlightedIndex]);
      }
    }
  }, {
    key: 'handleClickOutside',
    value: function handleClickOutside() {
      if (this.state.isFocus) {
        this.setState({ isFocus: false });
      }
    }
  }, {
    key: 'select',
    value: function select(item) {
      var _this4 = this;

      this.setState({ inputValue: item.value }, function () {
        _this4.setState({ suggestions: [] });
      });

      if (this.props.onSelect) {
        this.props.onSelect(item);
      }
    }
  }, {
    key: 'highlight',
    value: function highlight(index) {
      if (!this.suggestionVisible() || this.state.loading) return;
      if (index < 0) index = 0;
      if (index >= this.state.suggestions.length) {
        index = this.state.suggestions.length - 1;
      }
      var reference = ReactDOM.findDOMNode(this.suggestionsNode);
      if (reference instanceof HTMLElement) {
        var suggestion = document.querySelector('.ishow-autocomplete-suggestion__wrap');
        var suggestionList = document.querySelectorAll('.ishow-autocomplete-suggestion__list li');
        if (suggestion instanceof HTMLElement && suggestionList instanceof NodeList) {
          var highlightItem = suggestionList[index];
          var scrollTop = suggestion.scrollTop;
          var offsetTop = highlightItem.offsetTop;

          if (offsetTop + highlightItem.scrollHeight > scrollTop + suggestion.clientHeight) {
            suggestion.scrollTop += highlightItem.scrollHeight;
          }

          if (offsetTop < scrollTop) {
            suggestion.scrollTop -= highlightItem.scrollHeight;
          }

          this.setState({ highlightedIndex: index });
        }
      }
    }

    /* Computed Methods */

  }, {
    key: 'suggestionVisible',
    value: function suggestionVisible() {
      var suggestions = this.state.suggestions;
      var isValidData = Array.isArray(suggestions) && suggestions.length > 0;

      return (isValidData || this.state.loading) && this.state.isFocus;
    }
  }, {
    key: 'onKeyDown',
    value: function onKeyDown(e) {
      var highlightedIndex = this.state.highlightedIndex;

      switch (e.keyCode) {
        case 13:
          this.handleKeyEnter(highlightedIndex);
          break;
        case 38:
          this.highlight(highlightedIndex - 1);
          break;
        case 40:
          this.highlight(highlightedIndex + 1);
          break;
        default:
          break;
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this5 = this;

      var _props = this.props,
          disabled = _props.disabled,
          placeholder = _props.placeholder,
          name = _props.name,
          size = _props.size,
          icon = _props.icon,
          append = _props.append,
          prepend = _props.prepend,
          onIconClick = _props.onIconClick,
          popperClass = _props.popperClass;
      var _state = this.state,
          inputValue = _state.inputValue,
          suggestions = _state.suggestions;

      return React.createElement(
        'div',
        { style: this.style(), className: this.className('ishow-autocomplete') },
        React.createElement(Input, {
          ref: function ref(node) {
            return _this5.inputNode = node;
          },
          value: inputValue,
          disabled: disabled,
          placeholder: placeholder,
          name: name,
          size: size,
          icon: icon,
          prepend: prepend,
          append: append,
          onIconClick: onIconClick,
          onChange: this.handleChange.bind(this),
          onFocus: this.handleFocus.bind(this),
          onBlur: this.props.onBlur,
          onKeyDown: this.onKeyDown.bind(this)
        }),
        React.createElement(Suggestions, {
          ref: function ref(node) {
            return _this5.suggestionsNode = node;
          },
          className: this.classNames(popperClass),
          suggestions: suggestions
        })
      );
    }
  }]);

  return AutoComplete;
}(Component);

AutoComplete.childContextTypes = {
  component: PropTypes.any
};

AutoComplete.defaultProps = {
  triggerOnFocus: true
};

export default ClickOutside(AutoComplete);


text:
10/6/15
=======

##### DOM Crawler basic
*	Goutte uses [Symfony Dom Crawler](http://symfony.com/doc/current/components/dom_crawler.html)
*	[another basic intro](http://stackoverflow.com/a/19257829/1369136)
*	my understanding: crawler is a very capable DOM content object able to navigate and manipulate DOM content. `Goutte\Client` is able to do http actions to fetch data from url.

##### Status and TODO:
*	Now I am able to click links through home page, click each job post link and then fetch each job post content in `actionTrypostlink` function of `ScrapeController`. use command: `./yii scrape/trypostlink`
*	ToDo: create a organized model to do the job, create database to store post data.

10/7/15
=======

##### some Yii tips
*	`yii/base/Object` features:
	-	able to add/set properties with built in get/set function
	-	the contructor can add config array into the object, and call `init()` for you.
	-	if you override `__construct()`, call `parent::__construct($config);` at the end, and `$config` array should be the last parameter in constructor
*	`yii::config` and `yii::createObject`:
	- `yii::createObject` creates a new object using the given configuration. support configuration using  class name, a configuration array or an anonymous function.
	- `yii::config` just add config array into the object
*	`yii/base/Component` features: besides *property*, it adds *behavior* and *event*

10/10/15
========

##### some weried git status show all files changed from `old mode 100644` to `new mode 100755`
It seems file permission changed from 644 to 755, but git should not care about it. do `git config core.filemode false` [link](http://stackoverflow.com/questions/1257592/how-do-i-remove-files-saying-old-mode-100755-new-mode-100644-from-unstaged-cha) to disable that.

##### how to change PATH permenanently on ubuntu virtual box?
example: add `/home/vagrant/.composer/vendor/bin` into PATH:

	sudo vi ~/.profile
	#add this:
	export PATH=$PATH:/home/vagrant/.composer/vendor/bin
	#now save it and to make it effect immediately, run
	. ~/.profile
[reference](http://stackoverflow.com/questions/11709374/change-path-permanently-on-ubuntu)

#### Codeception tips:

##### 1. how to get started with Codeception in Yii project?
*	follow the `test/README.md` to install codeception globally, add composer's `vendor/bin` into PATH, now you can run `codecept` wherever.
*	go to rootdir/test folder, run `codecept build`, codeception will pick up the `codeception.yml` file and build test suits.
*	run `codecept run` to run all test suits. if only care about unit test, run `codecept run unit`
*	to generate a example test in unit folder, do `codecept generate:test unit example`, but if i want to generate a unit test case for a example class under "models", do `codecept generate:test unit models/Example`

##### 2. Question: how to do unit test for functions in `BaseModel` ???
*	Very confused. for example, `clickLinkInHomePage` function has so many dependencies on
`Goutte\Client` functions, should I mock them all?


text:
import weakref

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from electroncash.i18n import _
from electroncash.plugins import hook
from electroncash_gui.qt.main_window import ElectrumWindow, StatusBarButton
from electroncash_gui.qt.popup_widget import ShowPopupLabel, KillPopupLabel
from electroncash_gui.qt.util import ColorScheme

class ShuffleStatusBarButtonMgr:
    ''' Apologies for how contorted this is.  All this code used to live inside
    the ElectrumWindow instance in Electron Cash 4.0.x, before CashFusion.
    We moved it out into a separate "manager" class, for managing the
    StatusBarButton state. '''

    def __init__(self, plugin : object, window : ElectrumWindow):
        from .qt import Plugin  # <--- we lazy-load this each time becasue the Plugin class may go away and come back as a different class for each plugin load/unload cycle
        assert isinstance(plugin, Plugin)
        assert isinstance(window, ElectrumWindow)
        self.weak_window = weakref.ref(window)
        self.weak_plugin = weakref.ref(plugin)
        self._create_button()

    @property
    def window(self):
        return self.weak_window()

    @property
    def plugin(self):
        return self.weak_plugin()

    def require_good_window_first_arg(func, *args, **kwargs):
        ''' Verifies that self.window is good, and then passes it as the first
        arg to func.  If it is not good, returns with no-op. '''
        def inner(self, *args, **kwargs):
            w = self.window
            if w:
                return func(self, w, *args, **kwargs)
        return inner

    @require_good_window_first_arg
    def remove(self, window):
        attrs2del = [ 'cashshuffle_set_flag', 'cashshuffle_get_flag' ]
        for attr in attrs2del:
            if hasattr(window, attr):
                delattr(window, attr)
        sb = window.statusBar()
        sb.removeWidget(self.cashshuffle_status_button)
        self.cashshuffle_status_button.setParent(None)
        self.cashshuffle_status_button.deleteLater()
        self.cashshuffle_status_button = None
        self.cashshuffle_toggle_action = None
        self.cashshuffle_settings_action = None
        self.cashshuffle_viewpools_action = None
        self.cashshuffle_separator_action = None

    @require_good_window_first_arg
    def _create_button(self, window):
        sb = window.statusBar()
        self.cashshuffle_status_button = StatusBarButton(
            self.cashshuffle_icon(),
            '', # ToolTip will be set in update_cashshuffle code
            self.cashshuffle_icon_leftclick
        )
        self.cashshuffle_toggle_action = QAction("", self.cashshuffle_status_button) # action text will get set in update_cashshuffle_icon()
        self.cashshuffle_toggle_action.triggered.connect(self.toggle_cashshuffle)
        self.cashshuffle_settings_action = QAction("", self.cashshuffle_status_button)
        self.cashshuffle_settings_action.triggered.connect(self.show_cashshuffle_settings)
        self.cashshuffle_viewpools_action = QAction(_("View pools..."), self.cashshuffle_status_button)
        self.cashshuffle_viewpools_action.triggered.connect(self.show_cashshuffle_pools)
        self.cashshuffle_status_button.addAction(self.cashshuffle_viewpools_action)
        self.cashshuffle_status_button.addAction(self.cashshuffle_settings_action)
        self.cashshuffle_separator_action = sep = QAction(self.cashshuffle_status_button); sep.setSeparator(True)
        self.cashshuffle_status_button.addAction(sep)
        self.cashshuffle_status_button.addAction(self.cashshuffle_toggle_action)
        self.cashshuffle_status_button.setContextMenuPolicy(Qt.ActionsContextMenu)

        # monkey patch window because client.py code expects these method
        window.cashshuffle_set_flag = self.cashshuffle_set_flag
        window.cashshuffle_get_flag = self.cashshuffle_get_flag

        sb.insertPermanentWidget(4, self.cashshuffle_status_button)

    @require_good_window_first_arg
    def is_cashshuffle_enabled(self, window):
        plugin = self.plugin
        return bool(plugin and plugin.is_enabled() and plugin.window_has_cashshuffle(window))

    def cashshuffle_icon(self):
        if self.is_cashshuffle_enabled():
            if self._cash_shuffle_flag == 1:
                return QIcon(":icons/cashshuffle_on_error.svg")
            else:
                return QIcon(":icons/cashshuffle_on.svg")
        else:
            self._cash_shuffle_flag = 0
            return QIcon(":icons/cashshuffle_off.svg")

    @require_good_window_first_arg
    def update_cashshuffle_icon(self, window):
        self.cashshuffle_status_button.setIcon(self.cashshuffle_icon())
        loaded = bool(self.plugin)
        en = self.is_cashshuffle_enabled()
        if self._cash_shuffle_flag == 0:
            self.cashshuffle_status_button.setStatusTip(_("CashShuffle") + " - " + _("ENABLED") if en else _("CashShuffle") + " - " + _("Disabled"))
            rcfcm = _("Right-click for context menu")
            self.cashshuffle_status_button.setToolTip(
                (_("Toggle CashShuffle") + "\n" + rcfcm)
            )
            self.cashshuffle_toggle_action.setText(_("Enable CashShuffle") if not en else _("Disable CashShuffle"))
            self.cashshuffle_settings_action.setText(_("CashShuffle Settings..."))
            self.cashshuffle_viewpools_action.setEnabled(True)
        elif self._cash_shuffle_flag == 1: # Network server error
            self.cashshuffle_status_button.setStatusTip(_('CashShuffle Error: Could not connect to server'))
            self.cashshuffle_status_button.setToolTip(_('Right-click to select a different CashShuffle server'))
            self.cashshuffle_settings_action.setText(_("Resolve Server Problem..."))
            self.cashshuffle_viewpools_action.setEnabled(False)
        self.cashshuffle_settings_action.setVisible(en or loaded)
        self.cashshuffle_viewpools_action.setVisible(en)
        if en:
            # ensure 'Disable CashShuffle' appears at the end of the context menu
            self.cashshuffle_status_button.removeAction(self.cashshuffle_separator_action)
            self.cashshuffle_status_button.removeAction(self.cashshuffle_toggle_action)
            self.cashshuffle_status_button.addAction(self.cashshuffle_separator_action)
            self.cashshuffle_status_button.addAction(self.cashshuffle_toggle_action)
        else:
            # ensure 'Enable CashShuffle' appears at the beginning of the context menu
            self.cashshuffle_status_button.removeAction(self.cashshuffle_separator_action)
            self.cashshuffle_status_button.removeAction(self.cashshuffle_toggle_action)
            actions = self.cashshuffle_status_button.actions()
            self.cashshuffle_status_button.insertAction(actions[0] if actions else None, self.cashshuffle_separator_action)
            self.cashshuffle_status_button.insertAction(self.cashshuffle_separator_action, self.cashshuffle_toggle_action)

    @require_good_window_first_arg
    def show_cashshuffle_settings(self, window, *args):
        p = self.plugin
        if p:
            msg = None
            if self._cash_shuffle_flag == 1:
                # had error
                msg = _("There was a problem connecting to this server.\nPlease choose a different CashShuffle server.")
            p.settings_dialog(window, msg)

    @require_good_window_first_arg
    def show_cashshuffle_pools(self, window, *args):
        p = self.plugin
        if p:
            p.view_pools(window)

    @require_good_window_first_arg
    def cashshuffle_icon_leftclick(self, window, *args):
        self.toggle_cashshuffle()

    @require_good_window_first_arg
    def toggle_cashshuffle(self, window, *args):
        from .qt import Plugin
        if not Plugin.is_wallet_cashshuffle_compatible(window):
            window.show_warning(_("This wallet type cannot be used with CashShuffle."), parent=window)
            return
        plugins = window.gui_object.plugins
        p0 = self.plugin
        p = p0 or plugins.enable_internal_plugin("shuffle")
        if not p:
            raise RuntimeError("Could not find CashShuffle plugin")
        was_enabled = p.window_has_cashshuffle(window)
        if was_enabled and not p.warn_if_shuffle_disable_not_ok(window):
            # user at nag screen said "no", so abort
            self.update_cashshuffle_icon()
            return
        enable_flag = not was_enabled
        self._cash_shuffle_flag = 0
        KillPopupLabel("CashShuffleError")
        if not p0:
            # plugin was not loaded -- so flag window as wanting cashshuffle and do init
            p.window_set_wants_cashshuffle(window, enable_flag)
            p.init_qt(window.gui_object)
        else:
            # plugin was already started -- just add the window to the plugin
            p.window_set_cashshuffle(window, enable_flag)
        self.update_cashshuffle_icon()
        window.statusBar().showMessage(self.cashshuffle_status_button.statusTip(), 3000)
        if enable_flag and window.config.get("show_utxo_tab") is None:
            window.toggle_tab(window.utxo_tab) # toggle utxo tab to 'on' if user never specified it should be off.

    _cash_shuffle_flag = 0
    @require_good_window_first_arg
    def cashshuffle_set_flag(self, window, flag):
        flag = int(flag)
        changed = flag != self._cash_shuffle_flag
        if not changed:
            return
        if flag:
            def onClick():
                KillPopupLabel("CashShuffleError")
                self.show_cashshuffle_settings()
            ShowPopupLabel(name = "CashShuffleError",
                           text="{}
{}".format(_("Server Error"),_("Click here to resolve")),
                           target=self.cashshuffle_status_button,
                           timeout=20000, onClick=onClick, onRightClick=onClick,
                           dark_mode = ColorScheme.dark_scheme)
        else:
            KillPopupLabel("CashShuffleError")
        window.print_error("Cash Shuffle flag is now {}".format(flag))
        oldTip = self.cashshuffle_status_button.statusTip()
        self._cash_shuffle_flag = flag
        window.update_status()  # ultimately leads to a call to self.update_cashshuffle_icon()
        newTip = self.cashshuffle_status_button.statusTip()
        if newTip != oldTip:
            window.statusBar().showMessage(newTip, 7500)

    def cashshuffle_get_flag(self):
        return self._cash_shuffle_flag


text:
;(function ( $, window, document, undefined ) {

  var pluginName = 'stylesheetSwitcher',
  defaults = {
    cssFiles: 'style.css'
  };

  function Plugin( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options) ;
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype = {

    init: function() {
      console.log('stylesheetSwitcher');
    }

  };

  // A really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName,
          new Plugin( this, options ));
      }
    });
  };

})( jQuery, window, document );


text:
package psyco.reactiveX;

import com.google.common.collect.Lists;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by lipeng on 15/7/20.
 */
public class Hello {
    Observable<String> myObservable = Observable.create(
            new Observable.OnSubscribe<String>() {
                @Override
                public void call(Subscriber<? super String> sub) {
                    sub.onNext("Hello, world!");
                    sub.onCompleted();
                }
            }
    );

    Observable<String> myObservablex = Observable.create(subscriber -> {
        subscriber.onNext("Hello, world!");
        subscriber.onCompleted();
    });

    Subscriber<String> mySubscriber = new Subscriber<String>() {
        @Override
        public void onNext(String s) {
            System.out.println(s);
        }

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }
    };

    @Test
    public void tes() {
//        myObservable.subscribe(mySubscriber);
        Observable.just("Hello, worldXXX!").subscribe(s -> System.out.println(s));
        Observable.just("Hello, worldXXX!").map(e -> e + " fuckyou").map(e -> Lists.newArrayList(e)).subscribe(s -> System.out.println(s + "\t" + s.getClass().getName()));
    }

}


text:
        // 404
	open('@{HasErrors.willBeNotFound()}')
	assertTextPresent('Not found')
	assertTextPresent('Hop')

	// 500
	open('@{HasErrors.willThrowError()}')
	assertTextPresent('Execution exception')
	assertTextPresent('In /app/controllers/HasErrors.java (around line 15)')

	// 500
	open('@{HasErrors.willThrowErrorToo()}')
	assertTextPresent('Template compilation error')
	assertTextPresent(' is not opened.')

	// 404
	open('/nimp')
	assertTextPresent('Not found')
        assertTextPresent('GET /nimp')

        // 404
	open('/application/nimp')
	assertTextPresent('Not found')
        assertTextPresent('application.nimp action not found')

#{/selenium}


text:
JSON-Patch
===============

A leaner and meaner implementation of JSON-Patch. Small footprint. High performance.

With JSON-Patch, you can:
- **apply** patches
- **validate** a sequence of patches
- **observe** for changes (and generate patches when a change is detected)
- **compare** two objects (to obtain the difference)

## Why you should use JSON-Patch

JSON-Patch [(RFC6902)](http://tools.ietf.org/html/rfc6902) is a standard format that
allows you to update a JSON document by sending the changes rather than the whole document.
JSON Patch plays well with the HTTP PATCH verb (method) and REST style programming.

Mark Nottingham has a [nice blog]( http://www.mnot.net/blog/2012/09/05/patch) about it.

## Footprint
1.22 KB minified and gzipped (3 KB minified)

## Performance

##### [`add` benchmark](http://jsperf.com/json-patch-benchmark/2)

##### [`replace` benchmark](http://jsperf.com/json-patch-benchmark-replace/2)

Tested on 22.10.2015. Compared libraries:

- [Starcounter-Jack/JSON-Patch](https://github.com/Starcounter-Jack/JSON-Patch) 0.5.4
- [bruth/jsonpatch-js](https://github.com/bruth/jsonpatch-js) 0.5.0
- [dharmafly/jsonpatch.js](https://github.com/dharmafly/jsonpatch.js) master branch
- [jiff](https://www.npmjs.com/package/jiff) 0.7.2 browserified
- [json8-patch](https://www.npmjs.com/package/json8-patch) 0.3.2 browserified

We aim the tests to be fair. Our library puts performance as the #1 priority, while other libraries can have different priorities. If you'd like to update the benchmarks or add a library, please edit the jsperf benchmarks linked above and open an issue to include new results.

## Features
* Allows you to apply patches on object trees for incoming traffic.
* Allows you to freely manipulate object trees and then generate patches for outgoing traffic.
* ES7 Object.observe() is used when available.
* Tested in IE 8-11, Firefox, Chrome, Safari and Node.js

## Install

Install the current version (and save it as a dependency):

### npm

```sh
$ npm install fast-json-patch --save
```
### bower

```sh
$ bower install fast-json-patch --save
```

### [download as ZIP](https://github.com/Starcounter-Jack/JSON-Patch/archive/master.zip)

## Adding to your project

### In a web browser

Include `json-patch.js` if you want support for applying patches **or**
include `json-patch-duplex.js` if you also want to generate patches.

### In Node.js

Call require to get the instance:

```js
var jsonpatch = require('fast-json-patch')
```

:bulb: Node.js supports native `Object.observe` in preview release 0.11.x (and only when started with `--harmony_observation` flag). With stable versions of Node, a shimmed version of `Object.observe` is used.

## Usage

Applying patches:

```js
var myobj = { firstName:"Albert", contactDetails: { phoneNumbers: [ ] } };
var patches = [
   {op:"replace", path:"/firstName", value:"Joachim" },
   {op:"add", path:"/lastName", value:"Wester" },
   {op:"add", path:"/contactDetails/phoneNumbers/0", value:{ number:"555-123" }  }
   ];
jsonpatch.apply( myobj, patches );
// myobj == { firstName:"Joachim", lastName:"Wester", contactDetails:{ phoneNumbers[ {number:"555-123"} ] } };
```
Generating patches:

```js
var myobj = { firstName:"Joachim", lastName:"Wester", contactDetails: { phoneNumbers: [ { number:"555-123" }] } };
observer = jsonpatch.observe( myobj );
myobj.firstName = "Albert";
myobj.contactDetails.phoneNumbers[0].number = "123";
myobj.contactDetails.phoneNumbers.push({number:"456"});
var patches = jsonpatch.generate(observer);
// patches  == [
//   { op:"replace", path="/firstName", value:"Albert"},
//   { op:"replace", path="/contactDetails/phoneNumbers/0/number", value:"123"},
//   { op:"add", path="/contactDetails/phoneNumbers/1", value:{number:"456"}}];
```
Comparing two object trees:

```js
var objA = {user: {firstName: "Albert", lastName: "Einstein"}};
var objB = {user: {firstName: "Albert", lastName: "Collins"}};
var diff = jsonpatch.compare(objA, objB));
//diff == [{op: "replace", path: "/user/lastName", value: "Collins"}]
```

Validating a sequence of patches:

```js
var obj = {user: {firstName: "Albert"}};
var patches = [{op: "replace", path: "/user/firstName", value: "Albert"}, {op: "replace", path: "/user/lastName", value: "Einstein"}];
var errors = jsonpatch.validate(patches, obj);
if (errors.length == 0) {
 //there are no errors!
}
else {
  for (var i=0; i < errors.length; i++) {
    if (!errors[i]) {
      console.log("Valid patch at index", i, patches[i]);
    }
    else {
      console.error("Invalid patch at index", i, errors[i], patches[i]);
    }
  }
}
```

## Testing

### In a web browser

1. Testing **json-patch.js**
 - Load `test/SpecRunner.html` in your web browser
2. Testing **json-patch-duplex.js**
 - Load `test/SpecRunnerDuplex.html` in your web browser

Each of the test suite files contains *Jasmine* unit test suite and *Benchmark.js* performance test suite.

To run *Benchmark.js* performance tests, press "Run Tests" button.

### In Node.js

1. Go to directory where you have cloned the repo
2. Install Jasmine Node.js module by running command `npm install jasmine-node -g`
3. Testing **json-patch.js**
 - Run command `jasmine-node --matchall --config duplex no test/spec/coreSpec.js`
4. Testing **json-patch-duplex.js**
 - Run command `jasmine-node --matchall --config duplex yes test/spec/coreSpec.js test/spec/duplexSpec.js`

## API

#### jsonpatch.apply (`obj` Object, `patches` Array, `validate` Boolean) : boolean

Available in *json-patch.js* and *json-patch-duplex.js*

Applies `patches` array on `obj`.

If the `validate` parameter is set to `true`, the patch is extensively validated before applying.
An invalid patch results in throwing an error (see `jsonpatch.validate` for more information about the error object).

If patch was succesfully applied, returns `true`.

If there was a `test` patch in `patches` array, returns the result of the test.

If there was more than one patch in the array, the result of the last patch is returned.

#### jsonpatch.observe (`obj` Object, `callback` Function (optional)) : `observer` Object

Available in *json-patch-duplex.js*

Sets up an deep observer on `obj` that listens for changes in object tree. When changes are detected, the optional
callback is called with the generated patches array as the parameter.

Returns `observer`.

#### jsonpatch.generate (`obj` Object, `observer` Object) : `patches` Array

Available in *json-patch-duplex.js*

If there are pending changes in `obj`, returns them synchronously. If a `callback` was defined in `observe`
method, it will be triggered synchronously as well.

If there are no pending changes in `obj`, returns an empty array (length 0).

#### jsonpatch.unobserve (`obj` Object, `observer` Object) : void

Available in *json-patch-duplex.js*

Destroys the observer set up on `obj`.

Any remaining changes are delivered synchronously (as in `jsonpatch.generate`). Note: this is different that ES6/7 `Object.unobserve`, which delivers remaining changes asynchronously.

#### jsonpatch.compare (`obj1` Object, `obj2` Object) : `patches` Array

Available in *json-patch-duplex.js*

Compares object trees `obj1` and `obj2` and returns the difference relative to `obj1` as a patches array.

If there are no differences, returns an empty array (length 0).

#### jsonpatch.validate (`patches` Array, `tree` Object (optional)) : `error` JsonPatchError

Available in *json-patch.js* and *json-patch-duplex.js*

Validates a sequence of operations. If `tree` parameter is provided, the sequence is additionally validated against the object tree.

If there are no errors, returns undefined. If there is an errors, returns a JsonPatchError object with the following properties:

- `name` String - short error code
- `message` String - long human readable error message
- `index` Number - index of the operation in the sequence
- `operation` Object - reference to the operation
- `tree` Object - reference to the tree

Possible errors:

Error name                    | Error message
------------------------------|------------
SEQUENCE_NOT_AN_ARRAY         | Patch sequence must be an array
OPERATION_NOT_AN_OBJECT       | Operation is not an object
OPERATION_OP_INVALID          | Operation `op` property is not one of operations defined in RFC-6902
OPERATION_PATH_INVALID        | Operation `path` property is not a string
OPERATION_FROM_REQUIRED       | Operation `from` property is not present (applicable in `move` and `copy` operations)
OPERATION_VALUE_REQUIRED      | Operation `value` property is not present, or `undefined` (applicable in `add`, `replace` and `test` operations)
OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED  | Operation `value` property object has at least one `undefined` value (applicable in `add`, `replace` and `test` operations)
OPERATION_PATH_CANNOT_ADD     | Cannot perform an `add` operation at the desired path
OPERATION_PATH_UNRESOLVABLE   | Cannot perform the operation at a path that does not exist
OPERATION_FROM_UNRESOLVABLE   | Cannot perform the operation from a path that does not exist
OPERATION_PATH_ILLEGAL_ARRAY_INDEX | Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index
OPERATION_VALUE_OUT_OF_BOUNDS | The specified index MUST NOT be greater than the number of elements in the array

## `undefined`s (JSON to JS extension)

As `undefined` is not a valid value for any JSON node, it's also not valid value o JSON Patch operation object value property. Therefore, for valid JSON document, `jsonpatch` will not generate JSON Patches that sets anything to `undefined`.

However, to play nicer with natural JavaScipt objects `jsonpatch` can be applied to an object that contains `undefined`, in such case we will treat it as JS does. `.apply` will handle JSON Patches with `value: undefined` as any other falsy value. `.generate`, `.compare`, `.observe` methods will also produce JSON Patches with `undefined`s, but only for (non valid) JSON documents that contains it.

## :no_entry_sign: `undefined`s (JS to JSON projection)

~~As `undefined` is not a valid value for any JSON node, it's also not valid value o JSON Patch operation object value property. Therefore `jsonpatch` will not generate JSON Patches that sets anything to `undefined`.~~

~~However, to play nicer with natural JavaScipt objects `jsonpatch` can be applied to an object that contains `undefined`, in such case we will use it as native `JSON.stringify` - we will treat them as non-existing nodes, and map to `null` for array elements.~~

## Changelog

To see the list of recent changes, see [Releases](https://github.com/Starcounter-Jack/JSON-Patch/releases).


text:
package org.boon.tests;

import junit.framework.Assert;
import org.boon.core.reflection.BeanUtils;
import org.boon.criteria.ObjectFilter;
import org.boon.datarepo.Repo;
import org.boon.criteria.internal.Visitor;
import org.boon.tests.model.Employee;
import org.junit.Before;
import org.junit.Test;

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

import static junit.framework.Assert.*;
import static org.boon.criteria.ProjectedSelector.max;
import static org.boon.criteria.Selector.*;
import static org.boon.criteria.Update.set;
import static org.boon.criteria.Update.update;
import static org.boon.tests.model.Employee.employee;

import static org.boon.core.reflection.BeanUtils.idx;

public class RepoDefaultTest {

    Repo<String, Employee> repo;

    @Before
    public void setup() {
        repo = TestHelper.createFromBuilder();
    }

    @Test
    public void testGet() throws Exception {
        Employee employee = repo.get( TestHelper.getTestSSN );
        assertNotNull( "employee should not be null", employee );
        String firstName = employee.getFirstName();
        assertEquals( "firstName should be this", TestHelper.getTestFirstName, firstName );

    }

    @Test
    public void testAdd() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "21785999", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "21785999" ) );
        //assertNotSame(emp, repo.get("21785999"));
        repo.delete( emp );
        assertNull( "We were able to remove emp", repo.get( "21785999" ) );

    }

    @Test
    public void testRemove() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "21785999", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "21785999" ) );
        repo.delete( emp );
        assertNull( "We were able to remove emp", repo.get( "21785999" ) );

    }

    @Test
    public void testModify() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "21785999", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "21785999" ) );
        repo.modify( emp, "firstName", "Di" );

        String firstName = repo.get( "21785999" ).getFirstName();
        assertEquals( "firstName equals", "Di", firstName );

        assertEquals( "Test that the search index is rebuilt", "Di",
                repo.query( ObjectFilter.eq( "firstName", "Di" ) ).get( 0 ).getFirstName() );

    }

    @Test
    public void testUpdateByKey() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "21785999", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "21785999" ) );
        repo.update( emp.getSsn(), "firstName", "Di" );

        String firstName = repo.get( "21785999" ).getFirstName();
        assertEquals( "firstName equals", "Di", firstName );

        assertEquals( "Test that the search index is rebuilt", "Di",
                repo.query( ObjectFilter.eq( "firstName", "Di" ) ).get( 0 ).getFirstName() );

    }

    @Test
    public void testUpdateByKeyUsingValues() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "217859991", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "217859991" ) );
        repo.update( emp.getSsn(), set( "firstName", "Di" ) );

        String firstName = repo.get( "217859991" ).getFirstName();
        assertEquals( "firstName equals", "Di", firstName );

        assertEquals( "Test that the search index is rebuilt", "Di",
                repo.query( ObjectFilter.eq( "firstName", "Di" ) ).get( 0 ).getFirstName() );

    }

    @Test
    public void testUpdateByFilter() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "217859992", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "217859992" ) );

        repo.updateByFilter( "firstName", "Di",
                ObjectFilter.eq( "firstName", "Diana" ),
                ObjectFilter.eq( "lastName", "Hightower" ),
                ObjectFilter.eq( "id", "217859992" ) );

        String firstName = repo.get( "217859992" ).getFirstName();
        assertEquals( "firstName equals", "Di", firstName );

        assertEquals( "Test that the search index is rebuilt", "Di",
                repo.query( ObjectFilter.eq( "firstName", "Di" ) ).get( 0 ).getFirstName() );

    }

    @Test
    public void testUpdateByFilterUsingValues() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599917788", "08.15.82", 100_000 );
        repo.add( emp );
        assertNotNull( repo.get( "2178599917788" ) );

        repo.updateByFilter( update( set( "firstName", "Di" ) ),
                ObjectFilter.eq( "firstName", "Diana" ),
                ObjectFilter.eq( "lastName", "Hightower" ),
                ObjectFilter.eq( "id", "2178599917788" ) );

        String firstName = repo.get( "2178599917788" ).getFirstName();
        assertEquals( "firstName equals", "Di", firstName );

        assertEquals( "Test that the search index is rebuilt", "Di",
                repo.query( ObjectFilter.eq( "firstName", "Di" ) ).get( 0 ).getFirstName() );

    }

    @Test
    public void testEasyFilter2() throws Exception {
        Employee emp = employee( "Dianazzz", "Hightower", "8178599912", "08.15.82", 100_000 );
        repo.add( emp );
        emp = employee( "Dianazzz", "Hightower", "8178599912", "08.15.82", 100_000 );
        repo.add( emp );

        List<Employee> employees = repo.query( ObjectFilter.eq( "firstName", "Dianazzz" ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Dianazzz", employees.get( 0 ).getFirstName() );
    }

    @Test
    public void testEasyFilter() throws Exception {
        Employee emp = employee( "DianaSkywalker", "Hightower", "2178599912", "08.15.82", 100_000 );
        repo.add( emp );
        List<Employee> employees = repo.query( ObjectFilter.eq( "firstName", "DianaSkywalker" ) );
        assertNotNull( employees );

        assertEquals( 1, employees.size() );
        assertEquals( "DianaSkywalker", employees.get( 0 ).getFirstName() );
    }

    @Test
    public void testEasyFilterByMap() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "3178599912", "08.15.82", 100_000 );
        repo.add( emp );
        List<Map<String, Object>> employees = repo.queryAsMaps( ObjectFilter.eq( "firstName", "Diana" ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Diana", employees.get( 0 ).get( "firstName" ) );

    }

    @Test
    public void testEasySelect() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "21785999661234", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "217859901234", "08.15.82", 100_000 );

        repo.modify( emp );
        repo.modify( emp2 );

        List<Map<String, Object>> list = repo.sortedQuery( "firstName", selects( select( "firstName" ) ), ObjectFilter.eq( "lastName", "Hightower" ) );

        assertEquals( 2, list.size() );
        assertEquals( "Bob", list.get( 0 ).get( "firstName" ) );
        assertEquals( "Diana", list.get( 1 ).get( "firstName" ) );

    }

    @Test
    public void testMax() throws Exception {
        List<Map<String, Object>> list = repo.query( selects( max( "salary" ) ) );

        assertEquals( 666_000, list.get( 0 ).get( "max.salary" ) );

    }

    @Test
    public void testQueryOnUniqueIndex() throws Exception {
        List<Map<String, Object>> list = repo.query( selects( select( "firstName" ) ), ObjectFilter.gt( "empNum", 5l ) );
        assertNotNull( list );
        assertTrue( list.size() > 1 );

    }

    @Test
    public void testFieldPathSelect() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.modify( emp );
        repo.modify( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( select( "department", "name" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        assertEquals( "engineering", list.get( 0 ).get( "department.name" ) );
        assertEquals( "engineering", list.get( 1 ).get( "department.name" ) );

    }

    @Test
    public void testFieldPathSelectToCollection() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( select( "tags", "name" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        System.out.println( list.get( 0 ) );
        Assert.assertEquals( "tag1", BeanUtils.idx ( list.get ( 0 ).get ( "tags.name" ), 0 ) );

    }

    @Test
    public void testFieldPathSelectToCollection2() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( select( "tags", "metas", "name0" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        Assert.assertEquals( "mtag1", BeanUtils.idx ( list.get ( 0 ).get ( "tags.metas.name0" ), 0 ) );

    }

    @Test
    public void testFieldPathSelectToCollection3() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( select( "tags", "metas", "metas2", "name2" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        Assert.assertEquals( "2tag1", BeanUtils.idx ( list.get ( 0 ).get ( "tags.metas.metas2.name2" ), 0 ) );

    }

    @Test
    public void testIndexedLookup() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

    }

    @Test
    public void testPropertyPathSelect() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599966", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "21785990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( selectPropPath( "department", "name" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        assertEquals( "engineering", list.get( 0 ).get( "department.name" ) );
        assertEquals( "engineering", list.get( 1 ).get( "department.name" ) );

    }

    @Test
    public void testEasySelectWithSort() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "2178599990", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "2178599088", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.sortedQuery( "firstName", selects( select( "firstName" ) ), ObjectFilter.eq( "lastName", "Hightower" ) );

        assertEquals( "Bob", list.get( 0 ).get( "firstName" ) );
        assertEquals( "Diana", list.get( 1 ).get( "firstName" ) );

    }

    @Test
    public void testHarderFilter() throws Exception {
        Employee emp = employee( "Diana222", "Hightower", "217859997", "08.15.82", 100_000 );
        repo.add( emp );
        List<Employee> employees = repo.query(
                ObjectFilter.eq( "firstName", "Diana222" ), ObjectFilter.eq( "lastName", "Hightower" ), ObjectFilter.eq( "id", "217859997" ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Diana222", employees.get( 0 ).getFirstName() );
    }

    @Test
    public void testFilterLogicalOperators() throws Exception {
        List<Employee> employees = repo.query(
                ObjectFilter.startsWith( "firstName", "Bob" ), ObjectFilter.eq( "lastName", "Smith" ),
                ObjectFilter.lte( "salary", 200_000 ), ObjectFilter.gte( "salary", 190_000 ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Bob", employees.get( 0 ).getFirstName() );
        assertEquals( "222-222-2222", employees.get( 0 ).getSsn() );

    }

    @Test
    public void testFilterLogicalOperators2() throws Exception {
        List<Employee> employees = repo.query(
                ObjectFilter.startsWith( "firstName", "Bob" ),
                ObjectFilter.eq( "lastName", "Smith" ),
                ObjectFilter.lt( "salary", 200_000 ),
                ObjectFilter.gt( "salary", 190_000 ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Bob", employees.get( 0 ).getFirstName() );
        assertEquals( "222-222-2222", employees.get( 0 ).getSsn() );

    }

    @Test
    public void testFilterLT() throws Exception {
        List<Employee> employees = repo.query(
                ObjectFilter.gt( "salary", 200_000 ), ObjectFilter.eq( "lastName", "Smith" ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Bobbzie", employees.get( 0 ).getFirstName() );
        assertEquals( "422-222-2222", employees.get( 0 ).getSsn() );

    }

    @Test
    public void testFilterLogicalOperators3() throws Exception {
        List<Employee> employees = repo.query(
                ObjectFilter.startsWith( "firstName", "Bob" ), ObjectFilter.eq( "lastName", "Smith" ), ObjectFilter.between( "salary", 190_000, 200_000 ) );
        assertNotNull( employees );
        assertEquals( 1, employees.size() );
        assertEquals( "Bob", employees.get( 0 ).getFirstName() );
        assertEquals( "222-222-2222", employees.get( 0 ).getSsn() );

    }

    @Test
    public void testFieldPathSelectToCollection4() throws Exception {
        Employee emp = employee( "Diana", "Hightower", "asdf", "08.15.82", 100_000 );
        Employee emp2 = employee( "Bob", "Hightower", "217asdfasdfasdf85990", "08.15.82", 100_000 );

        repo.add( emp );
        repo.add( emp2 );

        List<Map<String, Object>> list = repo.query(
                selects( select( "tags", "metas", "metas2", "metas3", "name3" ) ),
                ObjectFilter.eq( "lastName", "Hightower" ) );

        //rint("listStream", listStream);

        Assert.assertEquals( "3tag1", BeanUtils.idx ( list.get ( 0 ).get ( "tags.metas.metas2.metas3.name3" ), 0 ) );

    }

    @Test
    public void testVisitor() throws Exception {

        repo.query( new Visitor<String, Employee>() {
            @Override
            public void visit( String s, Employee employee, Object currentProperty, List<String> propertyPath ) {
                System.out.printf( "VISITOR TEST key %s, \t employee=%s \t \n currentProperty=%s \t \npath=%s\n\n", s, employee, currentProperty, propertyPath );
            }
        } );

    }

    @Test
    public void testClear() {
        Employee emp = employee( "Clear", "Day", "asdf", "08.15.72", 70_000 );
        repo.add( emp );
        assertTrue( repo.size() > 1 );
        repo.clear();
        assertEquals( 0, repo.size() );
    }
}


text:
require 'spec_helper'

describe ErbContext do
  let(:dog) {
    instance_double(
      Dogapi::Client,
      get_all_screenboards:
        [ "200",
          { "screenboards"=> [
              {
                "resource"=>"/api/v1/screen/1234",
                "id"=>1234,
                "title"=>"sometitle"
              } ]
          } ],
      get_dashboards:
        ["200",
          { "dashes"=>
            [ {
                "title" => "somedashboard",
                "resource"=>"/api/v1/dash/123456",
                "id"=>"123456",
                "description"=>"The uptime of all the jobs"
              } ]
         } ]
    )
  }

  let(:context) {
    a = ErbContext.new
    a.dog = dog
    return a
  }

  describe '#lookup_note_asset' do
    it 'looks up screenboards from datadog' do
      expect(context.lookup_note_asset("sometitle", :screenboard)).to match("1234")
    end

    it 'fails gracefully when they do not exist' do
      expect(context.lookup_note_asset("nonexistent", :screenboard)).to match("")
    end

    it 'looks up dashboards from datadog' do
      expect(context.lookup_note_asset("somedashboard", :dashboard)).to match("123456")
    end

    it 'fails gracefully when they do not exist' do
      expect(context.lookup_note_asset("nonexistent", :dashboard)).to match("")
    end
  end

end


text:
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using VendingMachineApp.Business;
using VendingMachineApp.Business.Events;
using VendingMachineApp.DataAccess.Core;
using VendingMachineApp.DataAccess.Entities;

namespace VendingMachineApp.Commands
{
    public abstract class VendingMachineCommandHandler<TInCommand, TOutEvent> where TOutEvent : IEvent
    {
        private readonly Func<UnitOfWork<UserVendingMachineAggregationEntity>> _uowFactory;

        protected VendingMachineCommandHandler(Func<UnitOfWork<UserVendingMachineAggregationEntity>> uowFactory)
        {
            Contract.Requires(uowFactory != null);

            _uowFactory = uowFactory;
        }

        public TOutEvent Execute(TInCommand command)
        {
            using (var uow = _uowFactory())
            {
                var vMachineEntity = uow.Get(new NullIdentity());
                var machineCoins = vMachineEntity.VendingMachine.Coins
                    .Select(x => new Coin(x.FaceValue, x.Count))
                    .ToArray();
                var buyerCoins = vMachineEntity.User.Coins
                    .Select(x => new Coin(x.FaceValue, x.Count))
                    .ToArray();
                var machineGoods = vMachineEntity.VendingMachine.Goods
                    .Select(x => new Goods(new GoodsIdentity(x.Id), x.Price, x.Count))
                    .ToList();
                var machineWallet = new Wallet(machineCoins);
                var buyerWallet = new Wallet(buyerCoins);

                var aggregate = new VendingMachine(machineWallet, buyerWallet, machineGoods);
                var @event = Execute(aggregate, command);
                Contract.Assume(@event != null);
                uow.Commit(@event);

                return @event;
            }
        }

        protected abstract TOutEvent Execute(VendingMachine vendingMachine, TInCommand command);
    }
}


text:
from __future__ import absolute_import, division, print_function

import sys
import struct

from muninn.enum import Enum
from muninn.exceptions import *
from muninn.geometry import *
from muninn.visitor import Visitor

class GeometryType(Enum):
    _items = ("GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON")

class BLOBGeometryEncoder(Visitor):
    def __init__(self, little_endian=True):
        self.endianness = int(little_endian)
        self.prefix = (">", "<")[little_endian]
        self.entity = self._encode("B", 0x69)

    def visit(self, visitable, tagged=True):
        return super(BLOBGeometryEncoder, self).visit(visitable, tagged)

    def visit_Point(self, visitable, tagged):
        wkb = self._encode("dd", visitable.x, visitable.y)
        return self._encode_tag(GeometryType.POINT) + wkb if tagged else wkb

    def visit_LineString(self, visitable, tagged):
        wkb = self._encode("I", len(visitable))
        wkb += b"".join([self.visit(point, False) for point in visitable])
        return self._encode_tag(GeometryType.LINESTRING) + wkb if tagged else wkb

    def visit_LinearRing(self, visitable, tagged):
        if len(visitable) == 0:
            wkb = self._encode("I", 0)
        else:
            wkb = self._encode("I", len(visitable) + 1)
            wkb += b"".join([self.visit(point, False) for point in visitable])
            wkb += self.visit(visitable.point(0), False)
        return self._encode_tag(GeometryType.LINESTRING) + wkb if tagged else wkb

    def visit_Polygon(self, visitable, tagged):
        wkb = self._encode("I", len(visitable))
        wkb += b"".join([self.visit(ring, False) for ring in visitable])
        return self._encode_tag(GeometryType.POLYGON) + wkb if tagged else wkb

    def visit_MultiPoint(self, visitable, tagged):
        wkb = self._encode("I", len(visitable))
        wkb += b"".join([self.entity + self.visit(point, True) for point in visitable])
        return self._encode_tag(GeometryType.MULTIPOINT) + wkb if tagged else wkb

    def visit_MultiLineString(self, visitable, tagged):
        wkb = self._encode("I", len(visitable))
        wkb += b"".join([self.entity + self.visit(line_string, True) for line_string in visitable])
        return self._encode_tag(GeometryType.MULTILINESTRING) + wkb if tagged else wkb

    def visit_MultiPolygon(self, visitable, tagged):
        wkb = self._encode("I", len(visitable))
        wkb += b"".join([self.entity + self.visit(polygon, True) for polygon in visitable])
        return self._encode_tag(GeometryType.MULTIPOLYGON) + wkb if tagged else wkb

    def default(self, visitable, tagged):
        raise Error("unsupported type: %s" % type(visitable).__name__)

    def _encode_tag(self, wkb_type):
        return self._encode("I", wkb_type)

    def _encode(self, format, *args):
        try:
            return struct.pack(self.prefix + format, *args)
        except struct.error as _error:
            raise Error("encoding error: %s" % str(_error))

class BLOBGeometryStream(object):
    def __init__(self, wkb):
        self.wkb = wkb
        self.offset = 0
        self.prefix = "="

    def decode(self, format):
        return self._decode(self.prefix, format)

    def tail(self):
        return self.wkb[self.offset:]

    def set_endian(self, little_endian):
        self.prefix = (">", "<")[little_endian]

    def _decode(self, prefix, format):
        format = prefix + format

        try:
            start, end = self.offset, self.offset + struct.calcsize(format)
            values = struct.unpack(format, self.wkb[start:end])
        except struct.error as _error:
            raise Error("decoding error: %s" % str(_error))

        self.offset = end
        return values[0] if len(values) == 1 else values

def _decode_point(stream):
    return Point(*stream.decode("dd"))

def _decode_line_string(stream):
    count = stream.decode("I")
    return LineString([_decode_point(stream) for _ in range(count)])

def _decode_linear_ring(stream):
    count = stream.decode("I")
    if count == 0:
        return LinearRing()

    if count < 4:
        raise Error("linear ring should be empty or should contain >= 4 points")

    points = [_decode_point(stream) for _ in range(count)]
    if points[-1] != points[0]:
        raise Error("linear ring should be closed")

    return LinearRing(points[:-1])

def _decode_polygon(stream):
    count = stream.decode("I")
    return Polygon([_decode_linear_ring(stream) for _ in range(count)])

def _decode_geometry_sequence(stream, expected_wkb_type):
    count = stream.decode("I")
    sequence = []
    for _ in range(count):
        entity = stream.decode("B")
        if entity != 0x69:
            raise Error("invalid SQLite BLOB-Geometry")
        sequence.append(_decode_wkb(stream, expected_wkb_type))
    return sequence

def _decode_multi_point(stream):
    return MultiPoint(_decode_geometry_sequence(stream, GeometryType.POINT))

def _decode_multi_line_string(stream):
    return MultiLineString(_decode_geometry_sequence(stream, GeometryType.LINESTRING))

def _decode_multi_polygon(stream):
    return MultiPolygon(_decode_geometry_sequence(stream, GeometryType.POLYGON))

def _decode_wkb(stream, expected_wkb_type=None):
    wkb_type = stream.decode("I")

    if expected_wkb_type is not None and wkb_type != expected_wkb_type:
        raise Error("unexpected WKB type code: %s (expected: %s)" % (wkb_type, expected_wkb_type))

    if wkb_type == GeometryType.POINT:
        return _decode_point(stream)
    elif wkb_type == GeometryType.LINESTRING:
        return _decode_line_string(stream)
    elif wkb_type == GeometryType.POLYGON:
        return _decode_polygon(stream)
    elif wkb_type == GeometryType.MULTIPOINT:
        return _decode_multi_point(stream)
    elif wkb_type == GeometryType.MULTILINESTRING:
        return _decode_multi_line_string(stream)
    elif wkb_type == GeometryType.MULTIPOLYGON:
        return _decode_multi_polygon(stream)

    raise Error("unsupported WKB type code: %d" % wkb_type)

def encode_blob_geometry(geometry):
    little_endian = (sys.byteorder == 'little')
    srid = 4326
    encoder = BLOBGeometryEncoder(little_endian)
    # Start
    blob = encoder._encode("B", 0)
    # ENDIAN
    blob += encoder._encode("B", int(little_endian))
    # SRID
    blob += encoder._encode("I", srid)
    # MBR_MIN_X
    blob += encoder._encode("d", geometry.min_x)
    # MBR_MIN_Y
    blob += encoder._encode("d", geometry.min_y)
    # MBR_MAX_X
    blob += encoder._encode("d", geometry.max_x)
    # MBR_MAX_Y
    blob += encoder._encode("d", geometry.max_y)
    # MBR_END
    blob += encoder._encode("B", 0x7c)
    # 'WKB' of geometry
    blob += encoder.visit(geometry)
    # LAST
    blob += encoder._encode("B", 0xfe)
    return blob

def decode_blob_geometry(blob):
    stream = BLOBGeometryStream(blob)
    if stream.decode("B") != 0:
        raise Error("invalid SQLite BLOB-Geometry")
    stream.set_endian(stream.decode("B"))
    srid = stream.decode("I")
    if srid != 4326:
        raise Error("unsupported SRID code: %d" % srid)
    # MBR
    stream.decode("dddd")
    if stream.decode("B") != 0x7c:
        raise Error("invalid SQLite BLOB-Geometry")
    geometry = _decode_wkb(stream)
    if stream.decode("B") != 0xfe:
        raise Error("invalid SQLite BLOB-Geometry")
    return geometry


text:
layout: post
title: Perfect Babe Fucked Real Hard Where The Sun Don't Shine
titleinfo: pornvd
desc: Watch Perfect Babe Fucked Real Hard Where The Sun Don't Shine. Pornhub is the ultimate xxx porn and sex site.
---

Perfect Babe Fucked Real Hard Where The Sun Don't Shine

Watch Perfect Babe Fucked Real Hard Where The Sun Don't Shine. Pornhub is the ultimate xxx porn and sex site.


text:
define(['backbone', '../models/task'], function (Backbone, TaskModel) {
	'use strict';

	var TasksCollection = Backbone.Collection.extend({
		url: "http://localhost:8000/api/v1/tasks/",
		model: TaskModel
	});;

	return TasksCollection;
});


text:
play-tepkin-mongo-example
==================

A starter application with Play Framework 2.5 and Tepkin a Reactive MongoDB Driver for Scala built on top of Akka IO and Akka Streams

Using a driver built on top of Akka Streams allows for a very smooth integration with the new streaming API of Play framework 2.5

More information about the tepkin driver in its own github project
https://github.com/jeroenr/tepkin

# Requirements
- MongoDB
- SBT

# Configure
Review conf/application.conf and check mongo.url a new database 'tepkin' will be created with a collection 'projects'

#Run
```
sbt run
```

Open http://localhost:9000/assets/websocketsample.html to insert projects in a non blocking streaming fashion (with backpressure) using a websocket connection

Open http://localhost:9000/ to list the projects

Or run to create a project with your preferred name
```
curl -X "PUT" http://localhost:9000/projects/my-project
```

Have fun.


text:
<?php

namespace Ddeboer\Vatin\Vies;

use SoapFault;
use Ddeboer\Vatin\Exception\ViesException;

/**
 * A client for the VIES SOAP web service
 */
class Client
{
    /**
     * URL to WSDL
     *
     * @var string
     */
    private $wsdl = 'https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';

    /**
     * SOAP client
     *
     * @var \SoapClient
     */
    private $soapClient;

    /**
     * SOAP classmap
     *
     * @var array
     */
    private $classmap = [
        'checkVatResponse' => 'Ddeboer\Vatin\Vies\Response\CheckVatResponse'
    ];

    /**
     * Constructor
     *
     * @param string|null $wsdl URL to WSDL
     */
    public function __construct($wsdl = null)
    {
        if ($wsdl) {
            $this->wsdl = $wsdl;
        }
    }

    /**
     * Check VAT
     *
     * @param string $countryCode Country code
     * @param string $vatNumber   VAT number
     *
     * @return Response\CheckVatResponse
     * @throws ViesException
     */
    public function checkVat($countryCode, $vatNumber)
    {
        try {
            return $this->getSoapClient()->checkVat(
                [
                    'countryCode' => $countryCode,
                    'vatNumber' => $vatNumber
                ]
            );
        } catch (SoapFault $e) {
            throw new ViesException('Error communicating with VIES service', 0, $e);
        }
    }

    /**
     * Get SOAP client
     *
     * @return \SoapClient
     */
    private function getSoapClient()
    {
        if (null === $this->soapClient) {
            $this->soapClient = new \SoapClient(
                $this->wsdl,
                [
                    'classmap' => $this->classmap,
                    'user_agent' => 'Mozilla', // the request fails unless a (dummy) user agent is specified
                    'exceptions' => true,
                ]
            );
        }

        return $this->soapClient;
    }
}


text:
import { LitElement, html, css } from 'lit-element'
import { Config, Device } from '../globals'

export class Annotate extends LitElement {
    static get properties() {
        return {
            isOn: { type: Boolean },
        }
    }
    static get styles() {
        return css`
        :host {
            width: 100vh;
            height: 100vh;
        }
        #container {
            display: block;
            width: 100%;
            height: 100%;
            z-index: 50;
            position: absolute;
            left: 0;
            background: rgba(0,0,0,0.5);
            top: 0;
            cursor: text;
            display: none;
        }
        #selection {
            pointer-events: none;
            background-color: #86bcbc;
            opacity: 0.3;
            position: absolute;
            height: 400px;
            opacity: 0;
            top: 50%;
            transform: translateY(-50%);
        }
        #annotate {
            position: absolute;
            top: 10px;
            right: 10px;
            color: #818181;
            font-size: 12px;
            padding: 15px;
            z-index: 51;
        }
        #save {
            cursor: pointer;
            position: absolute;
            top: 20px;
            left: 20px;
            color: #818181;
            font-size: 12px;
            padding: 10px 15px;
            z-index: 51;
            display: none;
            background-color: transparent;
        }
        `
    }
    constructor() {
        super()
        this.isOn = false
    }

    off() {
        this.isOn = false
        this.shadowRoot.querySelector('#container').style.display = 'none'
        this.$$save.style.display = 'none'
        this.$$selection.style.opacity = 0
    }

    on() {
        this.isOn = true
        this.shadowRoot.querySelector('#container').style.display = 'block'
    }

    toggle() {
        this.isOn = !this.isOn
        if (this.isOn) {
            this.on()
        } else {
            this.off()
        }
    }

    firstUpdated() {
        this.$$selection = this.shadowRoot.querySelector('#selection')
        this.$$save = this.shadowRoot.querySelector('#save')

        this.resize()
        window.addEventListener('resize', () => {
            this.resize()
        })
    }

    mouseDown(event) {
        this.startingPoint = event.clientX
        this.$$selection.style.left = `${event.clientX}px`
        this.mousedown = true
        this.$$save.style.display = 'none'
    }

    mouseUp(event) {
        this.endingPoint = event.clientX
        this.mousedown = false
        this.$$save.style.display = 'block'
    }

    mouseMove(event) {
        if (this.mousedown) {
            this.$$selection.style.opacity = 0.5
            if (event.clientX - this.startingPoint >= 0) {
                this.$$selection.style.width = `${event.clientX - this.startingPoint}px`
            } else {
                this.$$selection.style.left = `${event.clientX}px`
                this.$$selection.style.width = `${this.startingPoint - event.clientX}px`
            }
        }
    }

    save() {
        let points = {}
        if (this.startingPoint <= this.endingPoint) {
            points = {
                startX: this.startingPoint,
                endX: this.endingPoint,
            }
        } else {
            points = {
                startX: this.endingPoint,
                endX: this.startingPoint,
            }
        }
        const event = new CustomEvent('annotate', { detail: points })
        this.dispatchEvent(event)

        const btn = this.shadowRoot.querySelector('#save')
        const text = btn.innerHTML
        btn.innerHTML = 'Copied!'
        setTimeout(()=>{
            this.off()
            btn.innerHTML = text
        }, 1000)
    }

    resize() {
        this.annotateHeight = !Device.tabletLandscape ? (Config.tileHeight / 4) : window.innerHeight / 1.25
    }

    render() {
        return html`

         ${(!this.isOn) ? html`<span>Annotate</span>` : html`<span>Done</span>`}

        <button id="save" @click="${this.save}">Copy to clipboard</button>
        `
    }
}
customElements.define('annotate-el', Annotate)


text:
Buttons

{{#code class="lang-markup"}}

    Button A
    <button class="flat-buttons">Button B</button>
    <input class="flat-buttons" type="submit" value="Button C">

    Button A
    <button class="btn float-button-light">Button B</button>
    <input class="btn float-buttons" type="submit" value="Button C">

{{/code}}

Icons

{{#code class="lang-markup"}}

{{/code}}

DIVs & Images

{{#code class="lang-markup"}}

Flat Box

Float Box

{{/code}}

Action/Event

{{#code class="lang-markup"}}

    <button id="snarl-demo">Click Me!</button>

{{/code}}


text:
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using ViewModels;

    public interface ICampaignService
    {
        Task<Campaign> GetCampaigns(int pageSize, int pageIndex);

        Task<CampaignItem> GetCampaignById(int id);
    }
}


text:
using System.IO;
using System.Runtime.InteropServices;

namespace LiteDB
{
    internal static class IOExceptionExtensions
    {
        private const int ERROR_SHARING_VIOLATION = 32;
        private const int ERROR_LOCK_VIOLATION = 33;

        /// <summary>
        /// Detect if exception is an Locked exception
        /// </summary>
        public static bool IsLocked(this IOException ex)
        {
            var errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1);

            return errorCode == ERROR_SHARING_VIOLATION ||
                errorCode == ERROR_LOCK_VIOLATION;
        }

        public static void WaitIfLocked(this IOException ex, int timer)
        {
            if (ex.IsLocked())
            {
                if (timer > 0)
                {
                    WaitFor(timer);
                }
            }
            else
            {
                throw ex;
            }
        }

        /// <summary>
        /// WaitFor function used in NETFULL + PCL
        /// </summary>
        public static void WaitFor(int ms)
        {
            // http://stackoverflow.com/questions/12641223/thread-sleep-replacement-in-net-for-windows-store
#if NET35
            System.Threading.Thread.Sleep(ms);
#else
            System.Threading.Tasks.Task.Delay(ms).Wait();
#endif
        }
    }
}


text:
package oracle.ateam.sample.mobile.persistence.metadata;

import oracle.adfmf.util.XmlAnyDefinition;

 /**
  * Interface that defines SOAP method header parameter or RESTful resource header parameter
  *
  * @deprecated Use the class with same name in oracle.ateam.sample.mobile.v2.persistence.* instead
  */
public interface MethodHeaderParameter
{
  public String getName();

  public String getValue();
}


text:
'use strict'

module.exports = function(sequelize, DataTypes) {
  var ingredient = sequelize.define('ingredient', {
    // idProduct: {
    //   allowNull: false,
    //   autoIncrement: true,
    //   primaryKey: true,
    //   type: DataTypes.INTEGER
    // },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    // quantity: {
    //   type: DataTypes.DOUBLE,
    //   defaultValue: 0
    // },
    price: {
      type: DataTypes.DOUBLE,
      defaultValue: 0
    },
    active: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    }
  });

  ingredient.associate = function(models) {
    // associations can be defined here
    ingredient.belongsTo(models.measure,  {as: 'measure', foreignKey: 'measureId'}) //, {as: 'Measure', foreignKey: 'id'})
    // ingredient.belongsTo(models.recipeIngredient)
  }

  return ingredient
}


text:
class AddUserDefaultExternalToApplicationSettings < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers
  disable_ddl_transaction!

  def up
    add_column_with_default(:application_settings, :user_default_external, :boolean,
                            default: false, allow_null: false)
  end

  def down
    remove_column(:application_settings, :user_default_external)
  end
end


text:
import {Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core';
import {ProfileService} from '../../services/profile.service';
import {User} from '../../services/users.service';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css'],
})
export class ProfileComponent implements OnInit, OnChanges {

  constructor(private profileService: ProfileService, private fb: FormBuilder) {
    this.createForm();
  }

  @Input()
  user: User;

  @Output()
  done = new EventEmitter<User>();

  profileForm: FormGroup;

  get firstName() {
    return this.profileForm.get('firstName');
  }

  get lastName() {
    return this.profileForm.get('lastName');
  }

  get password() {
    return this.profileForm.get('password');
  }

  get confirmPassword() {
    return this.profileForm ? this.profileForm.get('confirmPassword') : null;
  }

  ngOnInit() {
  }

  ngOnChanges() {
    this.profileForm.reset({
      firstName: this.user.firstName,
      lastName: this.user.lastName,
      password: '',
      confirmPassword: ''
    });
  }

  createForm() {
    const firstName = new FormControl('', Validators.required);
    const lastName = new FormControl('', Validators.required);
    const password = new FormControl('');
    const confirmPassword = new FormControl('', me => password.value === me.value ? null : {mismatch: true});

    password.valueChanges.subscribe(() => confirmPassword.updateValueAndValidity());

    this.profileForm = this.fb.group({
      firstName,
      lastName,
      password,
      confirmPassword
    });
  }

  onSave() {
    const formModel = this.profileForm.value;
    const toSave: User = {
      id: this.user.id,
      email: this.user.email,

      firstName: formModel.firstName,
      lastName: formModel.lastName
    };
    if (formModel.password) {
      toSave.password = formModel.password;
    }

    this.profileService.saveUser(toSave)
      .subscribe(user => {
        this.user = user;
        this.onDone();
      });
  }

  onCancel() {
    this.onDone();
  }

  onDone() {
    this.ngOnChanges();
    this.done.emit(this.user);
  }

}


text:
@extends('layouts.app')

@section('content')

    <div class="container">
        {{--{{ dd($courses) }}--}}
        <courses :courselist="{{ $courses}}"></courses>

    </div>
@endsection


text:
var express = require('express');
var app = express();

var port = process.env.PORT || 3000;

app.use(express.static('app'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/app/index.html');
});

var server = app.listen(port, function(err) {
    console.log('listening on http://%s:%s', 'localhost', port);
});


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 javax.lang.model.type;

public enum TypeKind {

  BOOLEAN(true),
  BYTE(true),
  SHORT(true),
  INT(true),
  LONG(true),
  CHAR(true),
  FLOAT(true),
  DOUBLE(true),
  VOID(false),
  NONE(false),
  NULL(false),
  ARRAY(false),
  DECLARED(false),
  ERROR(false),
  TYPEVAR(false),
  WILDCARD(false),
  PACKAGE(false),
  EXECUTABLE(false),
  OTHER(false),
  UNION(false),
  INTERSECTION(false);

  private final boolean isPrimitive;

  TypeKind(boolean isPrimitive) {
    this.isPrimitive = isPrimitive;
  }

  public boolean isPrimitive() {
    return isPrimitive;
  }
}


text:
package org.apache.vxquery.xmlquery.ast;

import java.util.List;

import org.apache.vxquery.util.SourceLocation;

public class ForClauseNode extends FLWORClauseNode {
    private List<ForVarDeclNode> variables;

    public ForClauseNode(SourceLocation loc) {
        super(loc);
    }

    @Override
    public ASTTag getTag() {
        return ASTTag.FOR_CLAUSE;
    }

    public List<ForVarDeclNode> getVariables() {
        return variables;
    }

    public void setVariables(List<ForVarDeclNode> variables) {
        this.variables = variables;
    }
}


text:
'use strict';

angular.module('paizaqaApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('categoriesShow', {
        url: '/categories/show/:id',
        templateUrl: 'app/categoriesShow/categoriesShow.html',
        controller: 'CategoriesShowComponent'
      });
  });