text:
package net.smoofyuniverse.common.util.io;

import net.smoofyuniverse.common.util.ArrayUtil;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public abstract class AbstractCopyFileVisitor implements FileVisitor<Path> {
	protected final CopyOption[] options;
	protected final boolean replace;

	protected AbstractCopyFileVisitor(CopyOption... options) {
		this.options = options;
		this.replace = ArrayUtil.contains(options, StandardCopyOption.REPLACE_EXISTING);
	}

	@Override
	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
		Path dest = getDestination(dir);
		if (Files.exists(dest)) {
			if (Files.isDirectory(dest))
				return FileVisitResult.CONTINUE;

			if (this.replace)
				Files.delete(dest);
			else
				throw new FileAlreadyExistsException(dest.toString());
		}
		Files.createDirectory(dest);
		return FileVisitResult.CONTINUE;
	}

	protected abstract Path getDestination(Path path);

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		Files.copy(file, getDestination(file), this.options);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException {
		throw e;
	}

	@Override
	public FileVisitResult postVisitDirectory(Path dir, IOException e) {
		return FileVisitResult.CONTINUE;
	}
}


text:
'use strict';
describe('frequency-counter', function() {
  var FC = require('..');
  var assert = require('assert');

  var fc;

  beforeEach(function() {
    fc = new FC();
  });

  it('most vs uniquelyMost', function() {
    fc.add('1');
    fc.add('2');
    fc.add('1');
    assert(fc.most('1'), '1 is most');
    assert(fc.uniquelyMost('1'), '1 is uniquely most');
    assert(!fc.most('2'), '2 is not the most');
    fc.add('2');
    fc.add('3');
    assert(fc.most('1'), '1 should still be most');
    assert(!fc.uniquelyMost('1'), '1 is no longer uniquely most');
    assert(fc.most('2'), '2 is also the most');
    assert(!fc.uniquelyMost('2'), '1 is no longer uniquely most');
    assert(!fc.most('3'), '3 is not the most');
  });

  it('handles constructor calls without new', function() {
    fc = FC();
    fc.add('1');
    assert(fc.most('1'));
  });

  it('keeps count', function() {
    fc.add('1');
    assert.strictEqual(fc.count('1'), 1);
    fc.add('1');
    assert.strictEqual(fc.count('1'), 2);
    fc.add('1');
    assert.strictEqual(fc.count('1'), 3);
    fc.add('2');
    assert.strictEqual(fc.count('2'), 1);
    assert.strictEqual(fc.count('1'), 3);
    fc.add('1');
    assert.strictEqual(fc.count('1'), 4);
  });

  it('works with numbers', function() {
    fc.add(1);
    assert.strictEqual(fc.count(1), 1);
    assert.strictEqual(fc.most(1), true);
    assert.strictEqual(fc.uniquelyMost(1), true);
    fc.add(1);
    assert.strictEqual(fc.count(1), 2);
    fc.add(1);
    assert.strictEqual(fc.count(1), 3);
    fc.add(2);
    assert.strictEqual(fc.count(2), 1);
    assert.strictEqual(fc.count(1), 3);
    fc.add(1);
    assert.strictEqual(fc.count(1), 4);
  });

  it('universal', function() {
    assert.strictEqual(fc.universal, true);
    fc.add(1);
    assert.strictEqual(fc.universal, true);
    fc.add(1);
    assert.strictEqual(fc.universal, true);
    fc.add(1);
    assert.strictEqual(fc.universal, true);
    fc.add(2);
    assert.strictEqual(fc.universal, false);
  });

  it('universal', function() {
    assert.strictEqual(fc.universal, true);
    fc.add(1);
    assert.strictEqual(fc.universal, true);
    fc.add(2);
    assert.strictEqual(fc.universal, false);
  });
});

redpajama_set_name: RedPajamaGithub


text:
import { AfterViewInit, Directive, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import { ControlContainer, FormControl } from '@angular/forms';
import { ApiHelper } from 'app/shared/api-helper';
import { BaseFormFieldComponent } from 'app/shared/base-form-field.component';
import { blank, empty } from 'app/shared/helper';
import { LayoutService } from 'app/core/layout.service';
import { BsDropdownDirective } from 'ngx-bootstrap/dropdown';
import { BehaviorSubject, Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs/operators';

/**
 * Base class for fields that present a text field and searches for keywords.
 * @param T The field data type
 * @param A The autocomplete results data type
 */
@Directive()
export abstract class BaseAutocompleteFieldComponent<T, A>
  extends BaseFormFieldComponent<T> implements OnInit, OnDestroy, AfterViewInit {
  inputFieldControl: FormControl;
  @ViewChild('inputField') inputField: ElementRef<HTMLInputElement>;
  @ViewChild('dropdown') dropdown: BsDropdownDirective;

  @Input() autoSearch = true;

  @Output() selected = new EventEmitter<A>();
  selection$ = new BehaviorSubject<A>(null);
  get selection(): A {
    return this.selection$.value;
  }
  set selection(value: A) {
    this.select(value);
  }
  options$ = new BehaviorSubject<A[]>(null);

  allowOptions = true;

  private bodyListener: any;

  layout: LayoutService;

  constructor(
    injector: Injector,
    protected controlContainer: ControlContainer) {
    super(injector, controlContainer);
    this.inputFieldControl = new FormControl(null);
    this.layout = injector.get(LayoutService);
  }

  ngOnInit() {
    super.ngOnInit();
    this.addSub(this.inputFieldControl.valueChanges.pipe(
      filter(text => blank(text)),
    ).subscribe(() => {
      this.close();
    }));
    if (this.autoSearch && this.allowOptions) {
      this.addSub(this.inputFieldControl.valueChanges.pipe(
        filter(text => !blank(text)),
        debounceTime(ApiHelper.DEBOUNCE_TIME),
        distinctUntilChanged(),
        switchMap(text => this.query(text)),
      ).subscribe(rows => {
        if (!this.allowOptions || blank(this.inputFieldControl.value)) {
          this.options$.next([]);
        } else {
          this.options$.next(rows);
          if (!empty(rows)) {
            this.open();
          }
        }
      }));
    }
    this.addSub(this.formControl.statusChanges.subscribe(status => {
      // We should delegate the error to the input field control, so it is correctly marked as error
      if (status === 'INVALID') {
        this.inputFieldControl.setErrors(this.formControl.errors);
      } else if (status === 'VALID') {
        this.inputFieldControl.setErrors(null);
      }
    }));
    this.bodyListener = () => this.close();
  }

  search(text?: string) {
    if (!this.allowOptions) {
      return;
    }
    if (blank(text)) {
      text = this.inputFieldControl.value;
    }
    if (blank(text)) {
      this.options$.next([]);
      this.close();
    } else {
      this.addSub(this.query(text).subscribe(rows => {
        if (this.allowOptions) {
          this.options$.next(rows);
          if (!empty(rows)) {
            this.open();
          }
        }
      }));
    }
  }

  ngAfterViewInit() {
    this.dropdown.onShown.subscribe(() => {
      document.body.addEventListener('click', this.bodyListener, false);
    });
    this.dropdown.onHidden.subscribe(() => {
      document.body.removeEventListener('click', this.bodyListener, false);
    });
  }

  onValueInitialized() {
    if (empty(this.value)) {
      this.select(null);
    } else {
      this.fetch(this.value).subscribe(res => {
        this.select(res, this.value, {
          emitEvent: false,
        });
      });
    }
  }

  /**
   * Must be implemented in order to fetch the autocomplete data from the given initial value
   * @param value The initial value
   */
  protected abstract fetch(value: T): Observable<A>;

  /**
   * Must be implemented in order to fetch the autocomplete results matching the given text
   * @param text The query text
   */
  protected abstract query(text: string): Observable<A[]>;

  /**
   * Must be implemented to return a display text for the given autocomplete result
   */
  abstract toDisplay(value: A): string;

  /**
   * Must be implemented to return the internal value for the given autocomplete result
   */
  abstract toValue(value: A): T;

  protected getFocusableControl() {
    return this.inputField;
  }

  onShown() {
    if (!this.inputField) {
      return;
    }
    const input = this.inputField.nativeElement as HTMLInputElement;
    const rect = input.getBoundingClientRect();
    const docHeight = (window.innerHeight || document.documentElement.clientHeight);
    this.dropdown.dropup = rect.bottom > docHeight - 100;
    this.layout.setFocusTrap(this.dropdownMenuId);

    // To manipulate the menu, we need to give time to ngx-bootstrap to append it to the body
    setTimeout(() => {
      const menu = document.getElementById(this.dropdownMenuId);

      // Workaround: ngx-bootstrap sets top, bottom, transform sometimes when we set dropup, which causes a position error
      menu.style.top = '';
      menu.style.bottom = '';
      menu.style.transform = '';

      // Make sure the menu is at least the same width as the input
      menu.style.minWidth = `${input.getBoundingClientRect().width}px`;
      menu.style.visibility = 'visible';
    });
  }

  onHidden() {
    this.layout.setFocusTrap(null);
  }

  onDisabledChange(isDisabled: boolean): void {
    const input = this.inputField.nativeElement as HTMLInputElement;
    input.disabled = isDisabled;
  }

  /**
   * Selects the given autocomplete value, emitting the event
   * @param selected The selected value
   * @param value The internal value to be set
   */
  select(selected: A, value?: T, options?: { emitEvent?: boolean }) {
    options = options || {};
    const newValue = value || (selected == null ? null : this.toValue(selected));
    if (this.value !== newValue) {
      this.value = newValue;
    }
    this.selection$.next(selected);
    if (options.emitEvent !== false) {
      this.selected.emit(selected);
    }
    this.close();
    if (selected == null) {
      this.inputFieldControl.setValue(null, options);
    } else if (this.inputFieldControl.value !== newValue) {
      this.inputFieldControl.setValue(newValue, options);
    }
  }

  protected getDisabledValue(): string {
    return this.selection ? this.toDisplay(this.selection) : String(this.value || '');
  }

  close() {
    if (this.dropdown) {
      this.dropdown.hide();
    }
    this.options$.next(null);
  }

  open() {
    this.dropdown.show();
  }

  ngClassFor(option: A, index: number): any {
    const result = {
      'mt-1': index > 0,
      selected: this.value === this.toValue(option),
    };
    result[`autocomplete-option-${index}`] = true;
    return result;
  }

  protected onEscapePressed() {
    this.select(null);
  }

  get dropdownMenuId() {
    return `dropdown-menu-${this.id}`;
  }
}


text:
Tapir is Oracle PL/SQL Table API generator - err ... will be ...

# Installation

* 1. get [SQLSN](https://github.com/principal-engineering/sqlsn) and optionally [Pete](https://github.com/principal-engineering/pete) for testing

````bash
$ ./install_oradb_modules.sh
````

* 2. install Tapir simply by

````bash
$ sqlplus username/password@connect_string @install
````

* 3. uninstall Tapir by

````bash
$ sqlplus username/password@connect_string @uninstall
````

# How to develop

* fork
* develop
* test using [Pete](https://github.com/principal-engineering/pete)
* post PR


text:
/*!
  \file aqfp_node_resyn.hpp
  \brief AQFP node resynthesis strategy

  \author Dewmini Sudara Marakkalage
*/

#pragma once

#include <type_traits>
#include <unordered_map>
#include <vector>

#include "../../traits.hpp"
#include "aqfp_assumptions.hpp"
#include "aqfp_db.hpp"

namespace mockturtle
{

/*! \brief Strategy for resynthesizing a node. */
enum class aqfp_node_resyn_strategy
{
  area, /*!< choose the database entry that gives the minimum area and break ties uing the delay */
  delay /*!< choose the database entry that gives the minimum delay and break ties uing the cost */
};

/*! \brief AQFP node re-synthesis parameters. */
struct aqfp_node_resyn_param
{
  aqfp_assumptions assume = { false, false, true, 4u };
  std::unordered_map<uint32_t, double> splitters = { { 1u, 2.0 }, { 4u, 2.0 } };
  aqfp_node_resyn_strategy strategy = aqfp_node_resyn_strategy::area;
};

/*! \brief A callback to re-synthesize a node in an AQFP network.
 *
 * A suitable AQFP sub-graph structure for a given node will be chosen from
 * a database of AQFP structures.
   \verbatim embed:rst

   Example

   .. code-block:: c++

     aqfp_assumptions assume = { false, false, true, 4u };
     aqfp_fanout_resyn fanout_resyn{ assume };

     std::unordered_map<uint32_t, double> gate_costs = { { 3u, 6.0 }, { 5u, 10.0 } };
     std::unordered_map<uint32_t, double> splitters = { { 1u, 2.0 }, { assume.splitter_capacity, 2.0 } };
     aqfp_node_resyn_param ps{ assume, splitters, aqfp_node_resyn_strategy::delay };

     aqfp_db<> db( gate_costs, splitters );
     db.load_db( ... ); // from an input-stream (e.g., std::ifstream or std::stringstream)

     aqfp_node_resyn node_resyn( db, ps );

     klut_network src_ntk = ...;
     aqfp_network dst_ntk;
     auto res = aqfp_resynthesis( dst_ntk, src_ntk, node_resyn, fanout_resyn );

   \endverbatim
 */
struct aqfp_node_resyn
{

  /*! \brief Default constructor.
   *
   * \param db AQFP database.
   * \param ps AQFP note re-synthesis parameters.
   */
  aqfp_node_resyn( aqfp_db<>& db, const aqfp_node_resyn_param& ps ) : params( ps ), db( db )
  {
    /*! must provid the cost of a simple buffer with one output */
    assert( ps.splitters.count( 1u ) > 0 );
    /*! must provid the cost of a splitter with the maximum capacity */
    assert( ps.splitters.count( ps.assume.splitter_capacity ) > 0 );
  }

  /*! Re-synthesize a given node as a sub-graph in an AQFP network.
   *
   * \param ntk_dest AQFP network that is being synthesized.
   * \param f Function computed by the source node that is being re-synthesized.
   * \param leaves_begin Iterator (begin) for the leaves of the source node.
   * \param leaves_end Iterator (end) for the leaves of the source node.
   * \param level_update_callback Callback with parameters (new node, level of the new node).
   * \param resyn_performed_callback Callback with the signal that correspond to the source node and its level.
   */
  template<typename NtkDest, typename TruthTable, typename LeavesIterator, typename LevelUpdateCallback, typename ResynPerformedCallback>
  void operator()( NtkDest& ntk_dest, const TruthTable& f, LeavesIterator leaves_begin, LeavesIterator leaves_end,
                   LevelUpdateCallback&& level_update_callback, ResynPerformedCallback&& resyn_performed_callback )
  {
    static_assert( std::is_invocable_v<LevelUpdateCallback, node<NtkDest>, uint32_t>,
                   "LevelUpdateCallback must be callable with arguments of types (node<NtkDest>, level)" );
    static_assert( std::is_invocable_v<ResynPerformedCallback, signal<NtkDest>, uint32_t>,
                   "ResynPerformedCallback must be callable with arguments of type (signal<NtkDest>, level)" );

    std::vector<signal<NtkDest>> leaves;
    std::vector<uint32_t> leaf_levels;
    std::vector<bool> leaf_no_splitters;
    for ( auto it = leaves_begin; it != leaves_end; it++ )
    {
      auto leaf = std::get<0>( *it );
      auto leaf_level = std::get<1>( *it );

      leaves.push_back( leaf );
      leaf_levels.push_back( leaf_level );
      leaf_no_splitters.push_back( ntk_dest.is_constant( ntk_dest.get_node( leaf ) ) || ( ntk_dest.is_ci( ntk_dest.get_node( leaf ) ) && !params.assume.branch_pis ) );
    }

    // should not have more than 4 fanin nodes
    assert( leaves.size() <= 4u );

    // if less than 4 fanins, add dummy inputs
    while ( leaves.size() < 4u )
    {
      leaves.push_back( ntk_dest.get_constant( false ) );
      leaf_levels.push_back( 0u );
      leaf_no_splitters.push_back( true );
    }

    auto tt = kitty::extend_to( f, 4u );

    auto new_n = ntk_dest.get_constant( false );
    auto n_lev = 0u;
    switch ( tt._bits[0] )
    {
    case 0x0000u:
      new_n = ntk_dest.get_constant( false );
      break;
    case 0xffffu:
      new_n = ntk_dest.get_constant( true );
      break;
    case 0x5555u:
      new_n = !leaves[0];
      n_lev = leaf_levels[0];
      break;
    case 0xaaaau:
      new_n = leaves[0];
      n_lev = leaf_levels[0];
      break;
    case 0x3333u:
      new_n = !leaves[1];
      n_lev = leaf_levels[1];
      break;
    case 0xccccu:
      new_n = leaves[1];
      n_lev = leaf_levels[1];
      break;
    case 0x0f0fu:
      new_n = !leaves[2];
      n_lev = leaf_levels[2];
      break;
    case 0xf0f0u:
      new_n = leaves[2];
      n_lev = leaf_levels[2];
      break;
    case 0x00ffu:
      new_n = !leaves[3];
      n_lev = leaf_levels[3];
      break;
    case 0xff00u:
      new_n = leaves[3];
      n_lev = leaf_levels[3];
      break;
    default:
      auto [mig, depths, output_inv] = db.get_best_replacement(
          tt._bits[0], leaf_levels, leaf_no_splitters,
          [&]( const std::pair<double, uint32_t>& f, const std::pair<double, uint32_t>& s ) {
            if ( params.strategy == aqfp_node_resyn_strategy::area )
            {
              return ( f.first < s.first || ( f.first == s.first && f.second < s.second ) );
            }
            else
            {
              assert( params.strategy == aqfp_node_resyn_strategy::delay );
              return ( f.second < s.second || ( f.second == s.second && f.first < s.first ) );
            }
          } );

      std::vector<signal<NtkDest>> sig_map( mig.size() );
      std::vector<uint32_t> lev_map( mig.size() );

      sig_map[0] = ntk_dest.get_constant( false );
      lev_map[0] = 0u;
      for ( auto i = 1u; i <= 4u; i++ )
      {
        sig_map[i] = leaves[i - 1];
        lev_map[i] = leaf_levels[i - 1];
      }
      for ( auto i = 5u; i < mig.size(); i++ )
      {
        std::vector<signal<NtkDest>> fanin;
        for ( auto fin : mig[i] )
        {
          const auto fin_inv = ( ( fin & 1u ) == 1u );
          const auto fin_id = ( fin >> 1 );
          fanin.push_back( fin_inv ? !sig_map[fin_id] : sig_map[fin_id] );
        }
        sig_map[i] = ntk_dest.create_maj( fanin );
        lev_map[i] = 0u;

        const auto node_i = ntk_dest.get_node( sig_map[i] );
        if ( !( ntk_dest.is_constant( node_i ) || ntk_dest.is_ci( node_i ) ) )
        {
          for ( auto fin : mig[i] )
          {
            const auto fin_id = ( fin >> 1u );
            const auto lev_dif = ( depths[fin_id] > depths[i] ) ? depths[fin_id] - depths[i] : 1u;
            lev_map[i] = std::max( lev_map[i], lev_map[fin_id] + lev_dif );
          }
        }

        level_update_callback( ntk_dest.get_node( sig_map[i] ), lev_map[i] );
      }
      n_lev = lev_map[mig.size() - 1];
      new_n = output_inv ? !sig_map[mig.size() - 1] : sig_map[mig.size() - 1];
    }

    resyn_performed_callback( new_n, n_lev );
  }

private:
  aqfp_node_resyn_param params;
  aqfp_db<>& db;
};

} // namespace mockturtle


text:
package com.valtech.source.dependometer.app.controller.compilationunit;

import com.valtech.source.dependometer.app.controller.project.TangleCollectedEvent;
import com.valtech.source.dependometer.app.core.elements.EntityTypeEnum;

public final class CompilationUnitTangleCollectedEvent extends TangleCollectedEvent
{

   @Override
   public EntityTypeEnum getEntityTypeEnum()
   {
      return EntityTypeEnum.COMPILATION_UNIT;
   }
}


text:
from chroma_core.lib.storage_plugin.api import attributes
from chroma_core.lib.storage_plugin.api.identifiers import GlobalId, ScopedId
from chroma_core.lib.storage_plugin.api.resources import ScannableResource
from chroma_core.lib.storage_plugin.api.plugin import Plugin
from chroma_core.lib.storage_plugin.api.resources import Controller, StoragePool, PhysicalDisk, LogicalDrive

class Resource1(ScannableResource):
    class Meta:
        identifier = GlobalId("address1", "address2")

    address_1 = attributes.Hostname()
    address_2 = attributes.Hostname()

class Resource2(Controller):
    class Meta:
        identifier = ScopedId("index")

    index = attributes.Enum(0, 1)

class Resource3(PhysicalDisk):
    serial_number = attributes.String()
    capacity = attributes.Bytes()

    class Meta:
        identifier = ScopedId("serial_number")

class Resource4(StoragePool):
    local_id = attributes.Integer()
    raid_type = attributes.Enum("raid0", "raid1", "raid5", "raid6")
    capacity = attributes.Bytes()

    class Meta:
        identifier = ScopedId("local_id")

    def get_label(self):
        return self.local_id

class Resource5(LogicalDrive):
    local_id = attributes.Integer()
    capacity = attributes.Bytes()
    name = attributes.String()

    class Meta:
        identifier = ScopedId("local_id")

    def get_label(self):
        return self.name

class ExamplePlugin(Plugin):
    def initial_scan(self, scannable_resource):
        pass

    def update_scan(self, scannable_resource):
        pass

    def teardown(self):
        # Free any resources
        pass


text:
#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/render-manager.hpp>
#include <algorithm>
#include <cmath>
#include <linux/input-event-codes.h>
#include "wayfire/signal-definitions.hpp"
#include <wayfire/plugins/common/geometry-animation.hpp>
#include "wayfire/plugins/grid.hpp"
#include "wayfire/plugins/crossfade.hpp"

#include <wayfire/plugins/wobbly/wobbly-signal.hpp>
#include <wayfire/view-transform.hpp>

const std::string grid_view_id = "grid-view";

class wf_grid_slot_data : public wf::custom_data_t
{
  public:
    int slot;
};

nonstd::observer_ptr<wf::grid::grid_animation_t> ensure_grid_view(wayfire_view view)
{
    if (!view->has_data<wf::grid::grid_animation_t>())
    {
        wf::option_wrapper_t<std::string> animation_type{"grid/type"};
        wf::option_wrapper_t<int> duration{"grid/duration"};

        wf::grid::grid_animation_t::type_t type = wf::grid::grid_animation_t::NONE;
        if (animation_type.value() == "crossfade")
        {
            type = wf::grid::grid_animation_t::CROSSFADE;
        } else if (animation_type.value() == "wobbly")
        {
            type = wf::grid::grid_animation_t::WOBBLY;
        }

        view->store_data(
            std::make_unique<wf::grid::grid_animation_t>(view, type, duration));
    }

    return view->get_data<wf::grid::grid_animation_t>();
}

/*
 * 7 8 9
 * 4 5 6
 * 1 2 3
 */
static uint32_t get_tiled_edges_for_slot(uint32_t slot)
{
    if (slot == 0)
    {
        return 0;
    }

    uint32_t edges = wf::TILED_EDGES_ALL;
    if (slot % 3 == 0)
    {
        edges &= ~WLR_EDGE_LEFT;
    }

    if (slot % 3 == 1)
    {
        edges &= ~WLR_EDGE_RIGHT;
    }

    if (slot <= 3)
    {
        edges &= ~WLR_EDGE_TOP;
    }

    if (slot >= 7)
    {
        edges &= ~WLR_EDGE_BOTTOM;
    }

    return edges;
}

static uint32_t get_slot_from_tiled_edges(uint32_t edges)
{
    for (int slot = 0; slot <= 9; slot++)
    {
        if (get_tiled_edges_for_slot(slot) == edges)
        {
            return slot;
        }
    }

    return 0;
}

class wayfire_grid : public wf::plugin_interface_t
{
    std::vector<std::string> slots =
    {"unused", "bl", "b", "br", "l", "c", "r", "tl", "t", "tr"};
    wf::activator_callback bindings[10];
    wf::option_wrapper_t<wf::activatorbinding_t> keys[10];
    wf::option_wrapper_t<wf::activatorbinding_t> restore_opt{"grid/restore"};

    wf::activator_callback restore = [=] (auto)
    {
        if (!output->can_activate_plugin(grab_interface))
        {
            return false;
        }

        auto view = output->get_active_view();
        if (!view || (view->role != wf::VIEW_ROLE_TOPLEVEL))
        {
            return false;
        }

        view->tile_request(0);

        return true;
    };

  public:
    void init() override
    {
        grab_interface->name = "grid";
        grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;

        for (int i = 1; i < 10; i++)
        {
            keys[i].load_option("grid/slot_" + slots[i]);
            bindings[i] = [=] (auto)
            {
                auto view = output->get_active_view();
                if (!view || (view->role != wf::VIEW_ROLE_TOPLEVEL))
                {
                    return false;
                }

                if (!output->can_activate_plugin(wf::CAPABILITY_MANAGE_DESKTOP))
                {
                    return false;
                }

                handle_slot(view, i);
                return true;
            };

            output->add_activator(keys[i], &bindings[i]);
        }

        output->add_activator(restore_opt, &restore);

        output->connect_signal("workarea-changed", &on_workarea_changed);
        output->connect_signal("grid-snap-view", &on_snap_signal);
        output->connect_signal("grid-query-geometry", &on_snap_query);
        output->connect_signal("view-tile-request", &on_maximize_signal);
        output->connect_signal("view-fullscreen-request", &on_fullscreen_signal);
    }

    bool can_adjust_view(wayfire_view view)
    {
        auto workspace_impl =
            output->workspace->get_workspace_implementation();

        return workspace_impl->view_movable(view) &&
               workspace_impl->view_resizable(view);
    }

    void handle_slot(wayfire_view view, int slot, wf::point_t delta = {0, 0})
    {
        if (!can_adjust_view(view))
        {
            return;
        }

        view->get_data_safe<wf_grid_slot_data>()->slot = slot;
        ensure_grid_view(view)->adjust_target_geometry(
            get_slot_dimensions(slot) + delta,
            get_tiled_edges_for_slot(slot));
    }

    /*
     * 7 8 9
     * 4 5 6
     * 1 2 3
     * */
    wf::geometry_t get_slot_dimensions(int n)
    {
        auto area = output->workspace->get_workarea();
        int w2    = area.width / 2;
        int h2    = area.height / 2;

        if (n % 3 == 1)
        {
            area.width = w2;
        }

        if (n % 3 == 0)
        {
            area.width = w2, area.x += w2;
        }

        if (n >= 7)
        {
            area.height = h2;
        } else if (n <= 3)
        {
            area.height = h2, area.y += h2;
        }

        return area;
    }

    wf::signal_connection_t on_workarea_changed = [=] (wf::signal_data_t *data)
    {
        auto ev = static_cast<wf::workarea_changed_signal*>(data);
        for (auto& view : output->workspace->get_views_in_layer(wf::LAYER_WORKSPACE))
        {
            if (!view->is_mapped())
            {
                continue;
            }

            auto data = view->get_data_safe<wf_grid_slot_data>();

            /* Detect if the view was maximized outside of the grid plugin */
            auto wm = view->get_wm_geometry();
            if (view->tiled_edges && (wm.width == ev->old_workarea.width) &&
                (wm.height == ev->old_workarea.height))
            {
                data->slot = wf::grid::SLOT_CENTER;
            }

            if (!data->slot)
            {
                continue;
            }

            /* Workarea changed, and we have a view which is tiled into some slot.
             * We need to make sure it remains in its slot. So we calculate the
             * viewport of the view, and tile it there */
            auto output_geometry = output->get_relative_geometry();

            int vx = std::floor(1.0 * wm.x / output_geometry.width);
            int vy = std::floor(1.0 * wm.y / output_geometry.height);

            handle_slot(view, data->slot,
                {vx *output_geometry.width, vy * output_geometry.height});
        }
    };

    wf::signal_connection_t on_snap_query = [=] (wf::signal_data_t *data)
    {
        auto query = dynamic_cast<wf::grid::grid_query_geometry_signal*>(data);
        assert(query);
        query->out_geometry = get_slot_dimensions(query->slot);
    };

    wf::signal_connection_t on_snap_signal = [=] (wf::signal_data_t *ddata)
    {
        auto data = dynamic_cast<wf::grid::grid_snap_view_signal*>(ddata);
        handle_slot(data->view, data->slot);
    };

    wf::geometry_t adjust_for_workspace(wf::geometry_t geometry,
        wf::point_t workspace)
    {
        auto delta_ws = workspace - output->workspace->get_current_workspace();
        auto scr_size = output->get_screen_size();
        geometry.x += delta_ws.x * scr_size.width;
        geometry.y += delta_ws.y * scr_size.height;
        return geometry;
    }

    wf::signal_connection_t on_maximize_signal = [=] (wf::signal_data_t *ddata)
    {
        auto data = static_cast<wf::view_tile_request_signal*>(ddata);

        if (data->carried_out || (data->desired_size.width <= 0) ||
            !can_adjust_view(data->view))
        {
            return;
        }

        data->carried_out = true;
        uint32_t slot = get_slot_from_tiled_edges(data->edges);
        if (slot > 0)
        {
            data->desired_size = get_slot_dimensions(slot);
        }

        data->view->get_data_safe<wf_grid_slot_data>()->slot = slot;
        ensure_grid_view(data->view)->adjust_target_geometry(
            adjust_for_workspace(data->desired_size, data->workspace),
            get_tiled_edges_for_slot(slot));
    };

    wf::signal_connection_t on_fullscreen_signal = [=] (wf::signal_data_t *ev)
    {
        auto data = static_cast<wf::view_fullscreen_signal*>(ev);
        static const std::string fs_data_name = "grid-saved-fs";

        if (data->carried_out || (data->desired_size.width <= 0) ||
            !can_adjust_view(data->view))
        {
            return;
        }

        data->carried_out = true;
        ensure_grid_view(data->view)->adjust_target_geometry(
            adjust_for_workspace(data->desired_size, data->workspace), -1);
    };

    void fini() override
    {
        for (int i = 1; i < 10; i++)
        {
            output->rem_binding(&bindings[i]);
        }

        output->rem_binding(&restore);
    }
};

DECLARE_WAYFIRE_PLUGIN(wayfire_grid);


text:
If we confess our sins, he is faithful and just and will forgive us our sins and purify us from all unrighteousness.

1 John 1:9
(NIV)


text:
angular.module("umbraco.filters")
    .filter('compareArrays', function() {
        return function inArray(array, compareArray, compareProperty) {

            var result = [];

            angular.forEach(array, function(arrayItem){

                var exists = false;

                angular.forEach(compareArray, function(compareItem){
                    if( arrayItem[compareProperty] === compareItem[compareProperty]) {
                        exists = true;
                    }
                });

                if(!exists) {
                    result.push(arrayItem);
                }

            });

            return result;

        };
});


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.02.04 at 01:34:24 PM CET
//

package com.evolveum.prism.xml.ns._public.types_3;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;

import com.evolveum.midpoint.prism.util.CloneUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.xml.security.exceptions.Base64DecodingException;
import org.apache.xml.security.utils.Base64;
import org.w3c.dom.Element;

import com.evolveum.midpoint.prism.crypto.ProtectedData;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.QNameUtil;

/**
 *
 * 				TODO
 * 				May be either encrypted or hashed or provided in the clear (e.g. for debugging).
 *
 * 				This type is marked as "mixed" because it may have alternative representation where
 * 				just the plaintext value is presented as the only value.
 *
 * 				This is considered to be primitive built-in type for prism objects.
 *
 *
 *
Java class for ProtectedDataType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ProtectedDataType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="encryptedData" type="{http://prism.evolveum.com/xml/ns/public/types-3}EncryptedDataType" minOccurs="0"/>
 *         <any namespace='##other'/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProtectedDataType", propOrder = {
    "content"
})
@XmlSeeAlso({
    ProtectedByteArrayType.class,
    ProtectedStringType.class
})
public abstract class ProtectedDataType<T> implements ProtectedData<T>, Serializable {

	public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "ProtectedDataType");
	public final static QName F_ENCRYPTED_DATA = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "encryptedData");
	public final static QName F_CLEAR_VALUE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "clearValue");

	public static final String NS_XML_ENC = "http://www.w3.org/2001/04/xmlenc#";
	public static final String NS_XML_DSIG = "http://www.w3.org/2000/09/xmldsig#";
	public static final QName F_XML_ENC_ENCRYPTED_DATA = new QName(NS_XML_ENC, "EncryptedData");
	public static final QName F_XML_ENC_ENCRYPTION_METHOD = new QName(NS_XML_ENC, "EncryptionMethod");
	public static final String ATTRIBUTE_XML_ENC_ALGORITHM = "Algorithm";
	public static final QName F_XML_ENC_ALGORITHM = new QName(NS_XML_ENC, ATTRIBUTE_XML_ENC_ALGORITHM);
	public static final QName F_XML_ENC_CIPHER_DATA = new QName(NS_XML_ENC, "CipherData");
	public static final QName F_XML_ENC_CIPHER_VALUE = new QName(NS_XML_ENC, "CipherValue");
	public static final QName F_XML_DSIG_KEY_INFO = new QName(NS_XML_DSIG, "KeyInfo");
	public static final QName F_XML_DSIG_KEY_NAME = new QName(NS_XML_DSIG, "KeyName");

	@XmlTransient
	private EncryptedDataType encryptedDataType;

	@XmlTransient
	private T clearValue;

    @XmlElementRef(name = "encryptedData", namespace = "http://prism.evolveum.com/xml/ns/public/types-3", type = JAXBElement.class)
    @XmlMixed
    @XmlAnyElement(lax = true)
    protected List<Object> content;

    /**
     *
     * 				TODO
     * 				May be either encrypted or hashed or provided in the clear (e.g. for debugging).
     *
     * 				This type is marked as "mixed" because it may have alternative representation where
     * 				just the plaintext value is presented as the only value.
     *
     * 				This is considered to be primitive built-in type for prism objects.
     * 			Gets the value of the content property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the content property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContent().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Object }
     * {@link String }
     * {@link JAXBElement }{@code <}{@link EncryptedDataType }{@code >}
     *
     *
     */
    public List<Object> getContent() {
        if (content == null) {
            content = new ContentList();
        }
        return this.content;
    }

    @Override
    public EncryptedDataType getEncryptedDataType() {
		return encryptedDataType;
	}

    @Override
	public void setEncryptedData(EncryptedDataType encryptedDataType) {
		this.encryptedDataType = encryptedDataType;
	}

    @Override
	public boolean isEncrypted() {
		return encryptedDataType != null;
	}

    public T getClearValue() {
    	return clearValue;
    }

    public void setClearValue(T clearValue) {
    	this.clearValue = clearValue;
    }

    @Override
	public void destroyCleartext() {
    	// Not perfect. But OK for now.
		clearValue = null;
	}

    private JAXBElement<EncryptedDataType> toJaxbElement(EncryptedDataType encryptedDataType) {
    	return new JAXBElement<EncryptedDataType>(F_ENCRYPTED_DATA, EncryptedDataType.class, encryptedDataType);
    }

    private void clearContent() {
    	encryptedDataType = null;
    }

    private boolean addContent(Object newObject) {
    	if (newObject instanceof String){
            String s = (String) newObject;
            if (StringUtils.isNotBlank(s)) {
                clearValue = (T) s;
            }
    		return true;
    	} else
    	if (newObject instanceof JAXBElement<?>) {
    		JAXBElement<?> jaxbElement = (JAXBElement<?>)newObject;
    		if (QNameUtil.match(F_ENCRYPTED_DATA, jaxbElement.getName())) {
    			encryptedDataType = (EncryptedDataType) jaxbElement.getValue();
    			return true;
    		} else {
    			throw new IllegalArgumentException("Attempt to add unknown JAXB element "+jaxbElement);
    		}
    	} else if (newObject instanceof Element) {
    		Element element = (Element)newObject;
    		QName elementName = DOMUtil.getQName(element);
    		if (QNameUtil.match(F_XML_ENC_ENCRYPTED_DATA, elementName)) {
    			encryptedDataType = convertXmlEncToEncryptedDate(element);
    			return true;
    		} else if (QNameUtil.match(F_CLEAR_VALUE, elementName)){
    			clearValue = (T) element.getTextContent();
    			return true;
    		} else {
    			throw new IllegalArgumentException("Attempt to add unknown DOM element "+elementName);
    		}
    	} else {
    		throw new IllegalArgumentException("Attempt to add unknown object "+newObject+" ("+newObject.getClass()+")");
    	}
    }

    private EncryptedDataType convertXmlEncToEncryptedDate(Element eEncryptedData) {
    	EncryptedDataType encryptedDataType = new EncryptedDataType();
    	Element eEncryptionMethod = DOMUtil.getChildElement(eEncryptedData, F_XML_ENC_ENCRYPTION_METHOD);
    	if (eEncryptionMethod != null) {
    		String algorithm = eEncryptionMethod.getAttribute(ATTRIBUTE_XML_ENC_ALGORITHM);
    		EncryptionMethodType encryptionMethodType = new EncryptionMethodType();
    		encryptionMethodType.setAlgorithm(algorithm);
			encryptedDataType.setEncryptionMethod(encryptionMethodType);
    	}
    	Element eKeyInfo = DOMUtil.getChildElement(eEncryptedData, F_XML_DSIG_KEY_INFO);
    	if (eKeyInfo != null) {
    		KeyInfoType keyInfoType = new KeyInfoType();
    		encryptedDataType.setKeyInfo(keyInfoType);
    		Element eKeyName = DOMUtil.getChildElement(eKeyInfo, F_XML_DSIG_KEY_NAME);
			if (eKeyName != null) {
				keyInfoType.setKeyName(eKeyName.getTextContent());
			}
    	}
    	Element eCipherData = DOMUtil.getChildElement(eEncryptedData, F_XML_ENC_CIPHER_DATA);
    	if (eCipherData != null) {
    		CipherDataType cipherDataType = new CipherDataType();
			encryptedDataType.setCipherData(cipherDataType);
			Element eCipherValue = DOMUtil.getChildElement(eCipherData, F_XML_ENC_CIPHER_VALUE);
			if (eCipherValue != null) {
				String cipherValue = eCipherValue.getTextContent();
				byte[] cipherValueBytes;
				try {
					cipherValueBytes = Base64.decode(cipherValue);
				} catch (Base64DecodingException e) {
					throw new IllegalArgumentException("Bad base64 encoding in CipherValue element: "+e.getMessage(),e);
				}
				cipherDataType.setCipherValue(cipherValueBytes);
			}
    	}
    	return encryptedDataType;
	}

    public boolean isEmpty() {
    	return encryptedDataType == null && clearValue == null;
    }

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((clearValue == null) ? 0 : clearValue.hashCode());
		result = prime * result + ((encryptedDataType == null) ? 0 : encryptedDataType.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ProtectedDataType other = (ProtectedDataType) obj;
		if (clearValue == null) {
			if (other.clearValue != null)
				return false;
		} else if (!clearValue.equals(other.clearValue))
			return false;
		if (encryptedDataType == null) {
			if (other.encryptedDataType != null)
				return false;
		} else if (!encryptedDataType.equals(other.encryptedDataType))
			return false;
		return true;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(getClass().getSimpleName());
		sb.append("(");
		if (encryptedDataType != null) {
			sb.append("encrypted=");
			sb.append(encryptedDataType);
		}
		if (clearValue != null) {
			sb.append("clearValue=");
			sb.append(clearValue);
		}
		sb.append(")");
		return sb.toString();
	}

    protected void cloneTo(ProtectedDataType<T> cloned) {
        cloned.clearValue = CloneUtil.clone(clearValue);
        cloned.encryptedDataType = CloneUtil.clone(encryptedDataType);

        // content is virtual, there is no point in copying it

//        for (Object o : getContent()) {
//            if (o instanceof JAXBElement<?>) {
//                JAXBElement<?> je = (JAXBElement) o;
//                Object v = je.getValue();
//                if (v == null) {
//                    // do nothing
//                } else if (v instanceof EncryptedDataType) {
//                    EncryptedDataType edt = (EncryptedDataType) v;
//                    cloned.addContent(new JAXBElement<EncryptedDataType>(je.getName(), (Class) je.getDeclaredType(), edt.clone()));
//                } else {
//                    throw new IllegalStateException("Unknown JAXB element "+je.getName()+" ("+je.getValue().getClass()+") in ProtectedDataType");
//                }
//            } else if (o instanceof Element) {
//                cloned.addContent(((Element) o).cloneNode(true));
//            } else if (o instanceof String) {
//                cloned.addContent(o);           // will this work?
//            } else {
//                throw new IllegalStateException("Unknown object of type "+o.getClass()+ " in ProtectedDataType");
//            }
//        }
    }

    class ContentList implements List<Object>, Serializable {

		@Override
		public int size() {
			if (encryptedDataType != null) {
				return 1;
			} else {
				return 0;
			}
		}

		@Override
		public boolean isEmpty() {
			return encryptedDataType == null;
		}

		@Override
		public boolean contains(Object o) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public Iterator<Object> iterator() {
			return new Iterator<Object>() {
				private int index = 0;
				@Override
				public boolean hasNext() {
					return index == 0;
				}

				@Override
				public Object next() {
					if (index == 0) {
						index++;
						return toJaxbElement(encryptedDataType);
					} else {
						return null;
					}
				}

				@Override
				public void remove() {
					throw new UnsupportedOperationException();
				}
			};
		}

		@Override
		public Object[] toArray() {
			if (encryptedDataType == null) {
				return new Object[0];
			} else {
				Object[] a = new Object[1];
				a[0] = toJaxbElement(encryptedDataType);
				return a;
			}
		}

		@Override
		public <T> T[] toArray(T[] a) {
			return (T[]) toArray();
		}

		@Override
		public boolean add(Object e) {
			return addContent(e);
		}

		@Override
		public boolean remove(Object o) {
			throw new UnsupportedOperationException();
		}

		@Override
		public boolean containsAll(Collection<?> c) {
			for (Object e: c) {
				if (!contains(e)) {
					return false;
				}
			}
			return true;
		}

		@Override
		public boolean addAll(Collection<? extends Object> c) {
			boolean changed = false;
			for (Object e: c) {
				if (add(e)) {
					changed = true;
				}
			}
			return changed;
		}

		@Override
		public boolean addAll(int index, Collection<? extends Object> c) {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

		@Override
		public boolean removeAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}

		@Override
		public boolean retainAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}

		@Override
		public void clear() {
			// We would normally throw an exception here. but JAXB is actually using it.
			clearContent();
		}

		@Override
		public Object get(int index) {
			if (index == 0) {
                // what if encryptedDataType is null and clearValue is set? [pm]
				return toJaxbElement(encryptedDataType);
			} else {
				return null;
			}
		}

		@Override
		public Object set(int index, Object element) {
			throw new UnsupportedOperationException();
		}

		@Override
		public void add(int index, Object element) {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object remove(int index) {
			throw new UnsupportedOperationException();
		}

		@Override
		public int indexOf(Object o) {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

		@Override
		public int lastIndexOf(Object o) {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

		@Override
		public ListIterator<Object> listIterator() {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

		@Override
		public ListIterator<Object> listIterator(int index) {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

		@Override
		public List<Object> subList(int fromIndex, int toIndex) {
			throw new UnsupportedOperationException("we are too lazy for this");
		}

    }
}


text:
class RemoveDefaultValuesForFieldsOnIncidents < ActiveRecord::Migration
  def up
    change_column_default :incidents, :number_of_frs_to_allocate, nil
    change_column_default :incidents, :number_of_transport_vehicles_to_allocate, nil
  end

  def down
    change_column_default :incidents, :number_of_frs_to_allocate, 3
    change_column_default :incidents, :number_of_transport_vehicles_to_allocate, 1
  end
end


text:
DELIMITER //
#cur_uuid:sim卡的uuid   cur_number:Sim卡号    cur_userUuid:当前sim卡的对应的集客用户名	     whichMonth:对当前卡的那个月进行统计(年月日时分秒,便于以后扩展)
DROP PROCEDURE IF EXISTS getSimConsumptionRecord //
CREATE PROCEDURE calculatePhoneCardBill(IN cur_uuid VARCHAR(32),IN cur_number VARCHAR(20),IN cur_userUuid VARCHAR(32),IN whichMonth DATETIME)
BEGIN
	#最终表中的数据项
	DECLARE con_contractIDList VARCHAR(128) DEFAULT '';
	DECLARE con_totalPrice DOUBLE(10,2) DEFAULT 0;
	DECLARE con_actualTotalInvoice  DOUBLE(10,2) DEFAULT 0;
	DECLARE con_totalFlow DOUBLE(10,1) DEFAULT 0;
	DECLARE con_actualTotalFlow DOUBLE(10,1) DEFAULT 0;
	DECLARE con_totalSms INT(5) DEFAULT 0;
	DECLARE con_actualTotalSms INT(5) DEFAULT 0;
	DECLARE con_beyondFlow DOUBLE(5,1) DEFAULT 0;
	DECLARE con_beyondFlowInvoice DOUBLE(5,2) DEFAULT 0;
	DECLARE con_beyondSms INT(5) DEFAULT 0;
	DECLARE con_beyondSmsInvoice DOUBLE(5,2) DEFAULT 0;

	#计划的指示性属性
	DECLARE cur_flowChargingStandards DOUBLE(2,1) DEFAULT 0;
	DECLARE cur_SmsChargingStandards DOUBLE(2,1) DEFAULT 0;
	DECLARE cur_planCycleId INT DEFAULT 4;
	DECLARE cur_planExpirationTime DATETIME;
	DECLARE cur_planActiveTime  DATETIME;

	#无周期类型计划总流量和总短信
	DECLARE non_TotalFlow,non_actualTotalFlow DOUBLE(10,1) DEFAULT 0;
	DECLARE non_TotalSms,non_actualTotalSms INT(5) DEFAULT 0;

	#合约表中相关的属性
	DECLARE cur_planID INT;
	DECLARE cur_expiryDate DATETIME;
	DECLARE cur_contractID VARCHAR(3);

	#临时变量
	DECLARE flag_end INT DEFAULT 1;

	DECLARE m_cursor CURSOR FOR SELECT contract_id,plan_id,expiration_time FROM neo_contract WHERE STRCMP(sim_card_uuid,cur_uuid) = 0;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag_end = 0;
	OPEN m_cursor;
	FETCH NEXT FROM m_cursor INTO cur_contractID,cur_planID,cur_expiryDate;
	#查询neo_contract和neo_plan,获取计划的流量短信信息和合约列表
	WHILE (flag_end <> 0) DO
		SELECT plan_cycle_id,FROM_UNIXTIME(SUBSTRING(active_time,1,10)),expiration_time INTO cur_planCycleId,cur_planActiveTime,cur_planExpirationTime FROM neo_plan WHERE plan_id = cur_planID;
		IF(cur_expiryDate IS NULL OR cur_expiryDate > NOW()) THEN
			#月周期类型的计划
			IF(cur_planCycleId = 2 AND cur_planExpirationTime > NOW()) THEN
				SELECT cur_contractID,cur_planID;
				SELECT plan_price+con_totalPrice,base_flow+con_totalFlow,base_sms+con_totalSms,beyond_flow+cur_flowChargingStandards,beyond_sms+cur_SmsChargingStandards
				INTO con_totalPrice,con_totalFlow,con_totalSms,cur_flowChargingStandards,cur_SmsChargingStandards
				FROM neo_plan WHERE plan_id = cur_planID;
				SET con_contractIDList = CONCAT_WS(',',cur_contractID,con_contractIDList);
			END IF;
			#无周期类型的计划
			IF(cur_planCycleId = 4 AND LENGTH(cur_planActiveTime)>9 AND EXTRACT(YEAR_MONTH from cur_planActiveTime) = EXTRACT(YEAR_MONTH from whichMonth)) THEN
				 SELECT cur_contractID,cur_planID,cur_planActiveTime,cur_planExpirationTime;
				 SELECT plan_price+con_totalPrice,base_flow,base_sms INTO con_totalPrice,non_TotalFlow,non_TotalSms FROM neo_plan WHERE plan_id = cur_planID;
				 SELECT SUM(daily_flow_total_count +0) INTO non_actualTotalFlow FROM sim_card_daily_summary WHERE phone_num = cur_number AND STR_TO_DATE(verify_date_dd, '%Y%m%d') BETWEEN cur_planActiveTime AND cur_planExpirationTime ;
				 SELECT SUM(sms_total +0) INTO non_actualTotalSms FROM sim_card_daily_summary WHERE phone_num = cur_number AND STR_TO_DATE(verify_date_dd, '%Y%m%d') BETWEEN cur_planActiveTime AND cur_planExpirationTime ;
				 #计算额定流量和额定短信数
				 IF(non_actualTotalFlow < non_TotalFlow) THEN
						SET con_totalFlow = con_totalFlow + non_actualTotalFlow ;
				 ELSE
						SET con_totalFlow = con_totalFlow + non_TotalFlow ;
				 END IF;
				 IF(non_actualTotalSms < non_TotalSms) THEN
						SET con_totalSms = con_totalSms + non_actualTotalSms ;
				 ELSE
						SET con_totalSms = con_totalSms + non_TotalSms ;
				 END IF;
				 SELECT non_TotalFlow,non_TotalSms,non_actualTotalFlow,non_actualTotalSms;
				 SET con_contractIDList = CONCAT_WS(',',cur_contractID,con_contractIDList);
			END IF;
		END IF;
		FETCH NEXT FROM m_cursor INTO cur_contractID,cur_planID,cur_expiryDate;
	END WHILE;
	CLOSE m_cursor;
	IF(LENGTH(TRIM(con_contractIDList)) >= 1) THEN
		#连接sim_card_monthy_summary,获取当月sim卡消费信息
		SELECT flow_total,sms_total INTO con_actualTotalFlow,con_actualTotalSms FROM sim_card_mouthly_summary WHERE phone_num = cur_number AND EXTRACT(YEAR_MONTH from STR_TO_DATE(verify_date_mm, '%Y%m')) = EXTRACT(YEAR_MONTH from whichMonth) ;
		#计算超额套餐资费信息
		IF(con_actualTotalFlow > con_totalFlow) THEN
				SET con_beyondFlow = con_actualTotalFlow - con_totalFlow;
				SET con_beyondFlowInvoice = con_beyondFlow * cur_flowChargingStandards;
		END IF;
		IF(con_actualTotalSms > con_totalSms) THEN
				SET con_beyondSms = con_actualTotalSms - con_totalSms;
				SET con_beyondSmsInvoice = con_beyondSms * cur_SmsChargingStandards;
		END IF;
		SET con_actualTotalInvoice = con_totalPrice + con_beyondFlowInvoice + con_beyondSmsInvoice;
		#将汇总结果插入到neo_sim_card_settlement_statement中
		INSERT INTO neo_sim_card_settlement_statement(user_uuid,statistic_month,sim_card_num,neo_contract_id_list,contract_total_invoice,actual_contract_use_invoice,contract_total_flow,actual_contract_user_flow,contract_total_sms,actual_contract_user_sms,beyond_contract_flow,beyond_contract_flow_invoice,beyond_contract_sms,beyond_contract_sms_invoice)
		VALUES(cur_userUuid,EXTRACT(YEAR_MONTH from whichMonth),cur_number,con_contractIDList,con_totalPrice,con_actualTotalInvoice,con_totalFlow,con_actualTotalFlow,con_totalSms,con_actualTotalSms,con_beyondFlow,con_beyondFlowInvoice,con_beyondSms,con_beyondSmsInvoice);
		SELECT cur_userUuid,cur_uuid,whichMonth,cur_number,con_contractIDList,con_totalPrice,con_totalFlow,con_actualTotalFlow,con_totalSms,con_actualTotalSms,cur_flowChargingStandards,cur_SmsChargingStandards;
	END IF;
END;//
DELIMITER ;

#CALL calculatePhoneCardBill('48ce2e75dd99449082a1eaef32264c50','13410421460','test011','2016-10-22 14:05:35');


text:
#if GOOGLE_CUDA

#define EIGEN_USE_GPU

#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/type_traits.h"
#include "tensorflow/core/kernels/eye_functor.h"
#include "tensorflow/core/util/cuda_kernel_helper.h"

namespace tensorflow {
namespace functor {

typedef Eigen::GpuDevice GPUDevice;

template <typename Scalar>
__global__ void EyeKernel(int num_threads, int batch_size, int m, int n,
                          Scalar* output_ptr) {
  const Scalar one = Scalar(1);
  const Scalar zero = Scalar(0);
  CUDA_1D_KERNEL_LOOP(index, num_threads) {
    // TODO(rmlarsen): Benchmark to see if it's just as fast to use mod (%),
    // since it's easier to read.
    const int global_row = index / n;
    const int col = index - global_row * n;
    const int batch = global_row / m;
    const int row = global_row - batch * m;
    output_ptr[index] = col == row ? one : zero;
  }
}

template <typename Scalar>
struct EyeFunctor<GPUDevice, Scalar> {
  void operator()(const GPUDevice& device,
                  typename TTypes<Scalar, 3>::Tensor matrix_batch) {
    const int batch_size = matrix_batch.dimension(0);
    const int m = matrix_batch.dimension(1);
    const int n = matrix_batch.dimension(2);
    CudaLaunchConfig config = GetCudaLaunchConfig(batch_size * m * n, device);
    EyeKernel<<<config.block_count, config.thread_per_block, 0,
                device.stream()>>>(config.virtual_thread_count, batch_size, m,
                                   n, matrix_batch.data());
  }
};

template struct EyeFunctor<GPUDevice, float>;
template struct EyeFunctor<GPUDevice, double>;
template struct EyeFunctor<GPUDevice, complex64>;
template struct EyeFunctor<GPUDevice, complex128>;

}  // namespace functor
}  // namespace tensorflow

#endif  // GOOGLE_CUDA


text:
# This file is used to boot your plugin when it is running in standalone mode
# from its own workspace - i.e. when the plugin is being developed.
#
# It will not be loaded when the plugin is imported by a 3rd party app - in that
# case only lib/origen_std_lib.rb is loaded.
#
# Therefore this file can be used to load anything extra that you need to boot
# the development environment for this app. For example, this is typically used
# to load some additional test classes to use your plugin APIs so that they can
# be tested and/or interacted with in the console.
require "origen_std_lib"

module OrigenStdLibDev
  # Example of how to explicitly require a file
  # require "origen_std_lib_dev/my_file"

  # Load all files in the lib/origen_std_lib_dev directory.
  # Note that there is no problem from requiring a file twice (Ruby will ignore
  # the second require), so if you have a file that must be required first, then
  # explicitly require it up above and then let this take care of the rest.
  Dir.glob("#{File.dirname(__FILE__)}/../lib/origen_std_lib_dev/**/*.rb").sort.each do |file|
    require file
  end
end


text:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ForbiddenComponent } from './forbidden.component';

describe('ForbiddenComponent', () => {
  let component: ForbiddenComponent;
  let fixture: ComponentFixture<ForbiddenComponent>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ForbiddenComponent],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(ForbiddenComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
Code Easy is a project of collection all the programming languages cheat sheets with elements, properties, reference, etc with their syntax, description and example.

DEMO : http://ganesank.github.io/codeeasy/

Ganesan


text:
package com.cloudera.sa.node360.service.deamon;

import com.cloudera.sa.node360.model.EventPojo;
import com.cloudera.sa.node360.service.HBaseService;
import com.cloudera.sa.node360.service.QueueService;

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

/**
 * Created by ted.malaska on 6/4/15.
 */
public class QueueToHBaseProcess {

  long sleepTime = 1;
  boolean running;
  HBaseService hbaseService;

  public QueueToHBaseProcess(HBaseService hbaseService) {
    this.hbaseService = hbaseService;
  }

  public QueueToHBaseProcess(HBaseService hbaseService, long sleepTime) {
    this.sleepTime = sleepTime;
    this.hbaseService = hbaseService;
  }

  public void start() {
    running = true;
    Thread t = new Thread(new PullingRunnable());
    t.start();
  }

  public void stop() {
    running = false;
  }

  private class PullingRunnable implements Runnable {

    @Override
    public void run() {
      int batchSize = 0;
      List<EventPojo> eventList = new ArrayList<EventPojo>();
      while (running) {
        EventPojo event;
        while (batchSize++ < 1000 && (event = QueueService.internalEventQueue.poll()) != null) {
          eventList.add(event);
        }
        try {
          hbaseService.publishEvents(eventList);
        } catch (Throwable t) {
          t.printStackTrace();
          throw new RuntimeException(t);
        }

        if (batchSize == 1) {
          try {
            Thread.sleep(2);
          } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          }
        }
        if (batchSize < 1000) {
          try {
            Thread.sleep(sleepTime);
          } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          }
        }
        batchSize = 0;
        eventList.clear();
      }
    }
  }
}


text:
namespace ppapi {
namespace thunk {

class PPB_PDF_API {
 public:
  virtual void SearchString(const unsigned short* input_string,
                            const unsigned short* input_term,
                            bool case_sensitive,
                            PP_PrivateFindResult** results,
                            uint32_t* count) = 0;
  virtual void DidStartLoading() = 0;
  virtual void DidStopLoading() = 0;
  virtual void SetContentRestriction(int restrictions) = 0;
  virtual void UserMetricsRecordAction(const PP_Var& action) = 0;
  virtual void HasUnsupportedFeature() = 0;
  virtual void ShowAlertDialog(const char* message) = 0;
  virtual bool ShowConfirmDialog(const char* message) = 0;
  virtual PP_Var ShowPromptDialog(const char* message,
                                  const char* default_answer) = 0;
  virtual void SaveAs() = 0;
  virtual PP_Bool IsFeatureEnabled(PP_PDFFeature feature) = 0;
  virtual void Print() = 0;
  virtual void SetSelectedText(const char* selected_text) = 0;
  virtual void SetLinkUnderCursor(const char* url) = 0;
  virtual void GetV8ExternalSnapshotData(const char** snapshot_data_out,
                                         int* snapshot_size_out) = 0;
  virtual void SetAccessibilityViewportInfo(
      const PP_PrivateAccessibilityViewportInfo* viewport_info) = 0;
  virtual void SetAccessibilityDocInfo(
      const PP_PrivateAccessibilityDocInfo* doc_info) = 0;
  virtual void SetAccessibilityPageInfo(
      const PP_PrivateAccessibilityPageInfo* page_info,
      const PP_PrivateAccessibilityTextRunInfo text_runs[],
      const PP_PrivateAccessibilityCharInfo chars[],
      const PP_PrivateAccessibilityPageObjects* page_objects) = 0;
  virtual void SetCrashData(const char* pdf_url, const char* top_level_url) = 0;
  virtual void SelectionChanged(const PP_FloatPoint& left,
                                int32_t left_height,
                                const PP_FloatPoint& right,
                                int32_t right_height) = 0;
  virtual void SetPluginCanSave(bool can_save) = 0;

  static const SingletonResourceID kSingletonResourceID = PDF_SINGLETON_ID;
};

}  // namespace thunk
}  // namespace ppapi

#endif  // PPAPI_THUNK_PPB_PDF_API_H_


text:
[![Build Status](https://travis-ci.org/wiruzx/PureFutures.svg?branch=master)](https://travis-ci.org/wiruzx/PureFutures) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

A simple Futures and Promises library.

##Installation

###Carthage

Add the following in your Cartfile:

```
github "wiruzx/PureFutures"
```

And run `carthage update`

Up to date instructions in [Carthage's README](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)

##Alternatives:

1. [BrightFutures](https://github.com/Thomvis/BrightFutures) ❤
2. [PromiseKit](https://github.com/mxcl/PromiseKit) 👍
3. [Bolts](https://github.com/BoltsFramework/Bolts-iOS) 😏
4. [SwiftTask](https://github.com/ReactKit/SwiftTask) 😐

##License

PureFutures is available under the MIT license. See the [LICENSE](LICENSE) file for more info.


text:
#ifndef JSON_ALLOCATOR_STANDARD_HPP
#define JSON_ALLOCATOR_STANDARD_HPP

#include "json/allocator.hpp"

namespace json {
namespace allocator {

class Standard final : public Allocator {
public:
    Standard() noexcept = default;

    virtual void* allocate(Size size) noexcept override;

    virtual void* reallocate(void* ptr, Size size) noexcept override;

    virtual void deallocate(void* ptr) noexcept override;

    virtual Size size(const void* ptr) const noexcept override;

    virtual ~Standard() noexcept override;
};

}
}

#endif /* JSON_ALLOCATOR_STANDARD_HPP */


text:
import warnings
from functools import reduce
from distutils.version import LooseVersion

import numpy as np
import pandas as pd
from shapely.ops import unary_union, polygonize
from shapely.geometry import MultiLineString

from geopandas import GeoDataFrame, GeoSeries

if str(pd.__version__) < LooseVersion('0.23'):
    CONCAT_KWARGS = {}
else:
    CONCAT_KWARGS = {'sort': False}

def _uniquify(columns):
    ucols = []
    for col in columns:
        inc = 1
        newcol = col
        while newcol in ucols:
            inc += 1
            newcol = "{0}_{1}".format(col, inc)
        ucols.append(newcol)
    return ucols

def _extract_rings(df):
    """Collects all inner and outer linear rings from a GeoDataFrame
    with (multi)Polygon geometeries

    Parameters
    ----------
    df: GeoDataFrame with MultiPolygon or Polygon geometry column

    Returns
    -------
    rings: list of LinearRings
    """
    poly_msg = "overlay only takes GeoDataFrames with (multi)polygon geometries"
    rings = []
    geometry_column = df.geometry.name

    for i, feat in df.iterrows():
        geom = feat[geometry_column]

        if geom.type not in ['Polygon', 'MultiPolygon']:
            raise TypeError(poly_msg)

        if hasattr(geom, 'geoms'):
            for poly in geom.geoms:  # if it's a multipolygon
                if not poly.is_valid:
                    # geom from layer is not valid attempting fix by buffer 0"
                    poly = poly.buffer(0)
                rings.append(poly.exterior)
                rings.extend(poly.interiors)
        else:
            if not geom.is_valid:
                # geom from layer is not valid attempting fix by buffer 0"
                geom = geom.buffer(0)
            rings.append(geom.exterior)
            rings.extend(geom.interiors)

    return rings

def _overlay_old(df1, df2, how, use_sindex=True, **kwargs):
    """Perform spatial overlay between two polygons.

    Currently only supports data GeoDataFrames with polygons.
    Implements several methods that are all effectively subsets of
    the union.

    Parameters
    ----------
    df1 : GeoDataFrame with MultiPolygon or Polygon geometry column
    df2 : GeoDataFrame with MultiPolygon or Polygon geometry column
    how : string
        Method of spatial overlay: 'intersection', 'union',
        'identity', 'symmetric_difference' or 'difference'.
    use_sindex : boolean, default True
        Use the spatial index to speed up operation if available.

    Returns
    -------
    df : GeoDataFrame
        GeoDataFrame with new set of polygons and attributes
        resulting from the overlay

    """
    allowed_hows = [
        'intersection',
        'union',
        'identity',
        'symmetric_difference',
        'difference',  # aka erase
    ]

    if how not in allowed_hows:
        raise ValueError("`how` was \"%s\" but is expected to be in %s" % \
            (how, allowed_hows))

    if isinstance(df1, GeoSeries) or isinstance(df2, GeoSeries):
        raise NotImplementedError("overlay currently only implemented for GeoDataFrames")

    # Collect the interior and exterior rings
    rings1 = _extract_rings(df1)
    rings2 = _extract_rings(df2)
    mls1 = MultiLineString(rings1)
    mls2 = MultiLineString(rings2)

    # Union and polygonize
    mm = unary_union([mls1, mls2])
    newpolys = polygonize(mm)

    # determine spatial relationship
    collection = []
    for fid, newpoly in enumerate(newpolys):
        cent = newpoly.representative_point()

        # Test intersection with original polys
        # FIXME there should be a higher-level abstraction to search by bounds
        # and fall back in the case of no index?
        if use_sindex and df1.sindex is not None:
            candidates1 = [x.object for x in
                           df1.sindex.intersection(newpoly.bounds, objects=True)]
        else:
            candidates1 = [i for i, x in df1.iterrows()]

        if use_sindex and df2.sindex is not None:
            candidates2 = [x.object for x in
                           df2.sindex.intersection(newpoly.bounds, objects=True)]
        else:
            candidates2 = [i for i, x in df2.iterrows()]

        df1_hit = False
        df2_hit = False
        prop1 = None
        prop2 = None
        for cand_id in candidates1:
            cand = df1.loc[cand_id]
            if cent.intersects(cand[df1.geometry.name]):
                df1_hit = True
                prop1 = cand
                break  # Take the first hit
        for cand_id in candidates2:
            cand = df2.loc[cand_id]
            if cent.intersects(cand[df2.geometry.name]):
                df2_hit = True
                prop2 = cand
                break  # Take the first hit

        # determine spatial relationship based on type of overlay
        hit = False
        if how == "intersection" and (df1_hit and df2_hit):
            hit = True
        elif how == "union" and (df1_hit or df2_hit):
            hit = True
        elif how == "identity" and df1_hit:
            hit = True
        elif how == "symmetric_difference" and not (df1_hit and df2_hit):
            hit = True
        elif how == "difference" and (df1_hit and not df2_hit):
            hit = True

        if not hit:
            continue

        # gather properties
        if prop1 is None:
            prop1 = pd.Series(dict.fromkeys(df1.columns, None))
        if prop2 is None:
            prop2 = pd.Series(dict.fromkeys(df2.columns, None))

        # Concat but don't retain the original geometries
        out_series = pd.concat([prop1.drop(df1._geometry_column_name),
                                prop2.drop(df2._geometry_column_name)])

        out_series.index = _uniquify(out_series.index)

        # Create a geoseries and add it to the collection
        out_series['geometry'] = newpoly
        collection.append(out_series)

    # Return geodataframe with new indices
    return GeoDataFrame(collection, index=range(len(collection)))

def _ensure_geometry_column(df):
    """
    Helper function to ensure the geometry column is called 'geometry'.
    If another column with that name exists, it will be dropped.
    """
    if not df._geometry_column_name == 'geometry':
        if 'geometry' in df.columns:
            df.drop('geometry', axis=1, inplace=True)
        df.rename(columns={df._geometry_column_name: 'geometry'},
                  copy=False, inplace=True)
        df.set_geometry('geometry', inplace=True)

def _overlay_intersection(df1, df2):
    """
    Overlay Intersection operation used in overlay function
    """
    # Spatial Index to create intersections
    spatial_index = df2.sindex
    bbox = df1.geometry.apply(lambda x: x.bounds)
    sidx = bbox.apply(lambda x: list(spatial_index.intersection(x)))
    # Create pairs of geometries in both dataframes to be intersected
    nei = []
    for i, j in enumerate(sidx):
        for k in j:
            nei.append([i, k])
    if nei != []:
        pairs = pd.DataFrame(nei, columns=['__idx1', '__idx2'])
        left = df1.geometry.take(pairs['__idx1'].values)
        left.reset_index(drop=True, inplace=True)
        right = df2.geometry.take(pairs['__idx2'].values)
        right.reset_index(drop=True, inplace=True)
        intersections = left.intersection(right).buffer(0)

        # only keep actual intersecting geometries
        pairs_intersect = pairs[~intersections.is_empty]
        geom_intersect = intersections[~intersections.is_empty]

        # merge data for intersecting geometries
        df1 = df1.reset_index(drop=True)
        df2 = df2.reset_index(drop=True)
        dfinter = pairs_intersect.merge(
            df1.drop(df1._geometry_column_name, axis=1),
            left_on='__idx1', right_index=True)
        dfinter = dfinter.merge(
            df2.drop(df2._geometry_column_name, axis=1),
            left_on='__idx2', right_index=True, suffixes=['_1', '_2'])

        return GeoDataFrame(dfinter, geometry=geom_intersect, crs=df1.crs)
    else:
        return GeoDataFrame(
            [],
            columns=list(set(df1.columns).union(df2.columns)),
            crs=df1.crs)

def _overlay_difference(df1, df2):
    """
    Overlay Difference operation used in overlay function
    """
    # Spatial Index to create intersections
    spatial_index = df2.sindex
    bbox = df1.geometry.apply(lambda x: x.bounds)
    sidx = bbox.apply(lambda x: list(spatial_index.intersection(x)))
    # Create differences
    new_g = []
    for geom, neighbours in zip(df1.geometry, sidx):
        new = reduce(lambda x, y: x.difference(y).buffer(0),
                     [geom] + list(df2.geometry.iloc[neighbours]))
        new_g.append(new)
    differences = GeoSeries(new_g, index=df1.index)
    geom_diff = differences[~differences.is_empty].copy()
    dfdiff = df1[~differences.is_empty].copy()
    dfdiff[dfdiff._geometry_column_name] = geom_diff
    return dfdiff

def _overlay_symmetric_diff(df1, df2):
    """
    Overlay Symmetric Difference operation used in overlay function
    """
    dfdiff1 = _overlay_difference(df1, df2)
    dfdiff2 = _overlay_difference(df2, df1)
    dfdiff1['__idx1'] = range(len(dfdiff1))
    dfdiff2['__idx2'] = range(len(dfdiff2))
    dfdiff1['__idx2'] = np.nan
    dfdiff2['__idx1'] = np.nan
    # ensure geometry name (otherwise merge goes wrong)
    _ensure_geometry_column(dfdiff1)
    _ensure_geometry_column(dfdiff2)
    # combine both 'difference' dataframes
    dfsym = dfdiff1.merge(dfdiff2, on=['__idx1', '__idx2'], how='outer',
                          suffixes=['_1', '_2'])
    geometry = dfsym.geometry_1.copy()
    geometry[dfsym.geometry_1.isnull()] = \
        dfsym.loc[dfsym.geometry_1.isnull(), 'geometry_2']
    dfsym.drop(['geometry_1', 'geometry_2'], axis=1, inplace=True)
    dfsym.reset_index(drop=True, inplace=True)
    dfsym = GeoDataFrame(dfsym, geometry=geometry, crs=df1.crs)
    return dfsym

def _overlay_union(df1, df2):
    """
    Overlay Union operation used in overlay function
    """
    dfinter = _overlay_intersection(df1, df2)
    dfsym = _overlay_symmetric_diff(df1, df2)
    dfunion = pd.concat([dfinter, dfsym], ignore_index=True, **CONCAT_KWARGS)
    # keep geometry column last
    columns = list(dfunion.columns)
    columns.remove('geometry')
    columns = columns + ['geometry']
    return dfunion.reindex(columns=columns)

def overlay(df1, df2, how='intersection', make_valid=True, use_sindex=None):
    """Perform spatial overlay between two polygons.

    Currently only supports data GeoDataFrames with polygons.
    Implements several methods that are all effectively subsets of
    the union.

    Parameters
    ----------
    df1 : GeoDataFrame with MultiPolygon or Polygon geometry column
    df2 : GeoDataFrame with MultiPolygon or Polygon geometry column
    how : string
        Method of spatial overlay: 'intersection', 'union',
        'identity', 'symmetric_difference' or 'difference'.

    Returns
    -------
    df : GeoDataFrame
        GeoDataFrame with new set of polygons and attributes
        resulting from the overlay

    """
    if use_sindex is not None:
        warnings.warn("'use_sindex' is deprecated. The overlay operation "
                      "always requires a spatial index (rtree).",
                      DeprecationWarning, stacklevel=2)

    # Allowed operations
    allowed_hows = [
        'intersection',
        'union',
        'identity',
        'symmetric_difference',
        'difference',  # aka erase
    ]
    # Error Messages
    if how not in allowed_hows:
        raise ValueError("`how` was '{0}' but is expected to be "
                         "in %s".format(how, allowed_hows))

    if isinstance(df1, GeoSeries) or isinstance(df2, GeoSeries):
        raise NotImplementedError("overlay currently only implemented for "
                                  "GeoDataFrames")

    accepted_types = ['Polygon', 'MultiPolygon']
    if (not df1.geom_type.isin(accepted_types).all()
            or not df2.geom_type.isin(accepted_types).all()):
        raise TypeError("overlay only takes GeoDataFrames with (multi)polygon "
                        " geometries.")

    # Computations
    df1 = df1.copy()
    df2 = df2.copy()
    df1[df1._geometry_column_name] = df1.geometry.buffer(0)
    df2[df2._geometry_column_name] = df2.geometry.buffer(0)

    if how == 'difference':
        return _overlay_difference(df1, df2)
    elif how == 'intersection':
        result = _overlay_intersection(df1, df2)
    elif how == 'symmetric_difference':
        result = _overlay_symmetric_diff(df1, df2)
    elif how == 'union':
        result = _overlay_union(df1, df2)
    elif how == 'identity':
        dfunion = _overlay_union(df1, df2)
        result = dfunion[dfunion['__idx1'].notnull()].copy()
        result.reset_index(drop=True, inplace=True)
    result.drop(['__idx1', '__idx2'], axis=1, inplace=True)
    return result