text:
require "ld/form/checkbox"

module LD
  class Form
    class MultipleChoice < LD::Form::Checkbox
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
  Author: ""
  Description: ""
  FileName: "Snappy.tmTheme"
  ID: "Snappy"
  Title: "Snappy"
  layout: theme
---


text:
/*
 * Support and FAQ: visit Atmel Support
 */
#include "gfx_mono_ug_2832hsweg04.h"

/* If we are using a serial interface without readback, use framebuffer */

#ifdef CONFIG_SSD1306_FRAMEBUFFER
static uint8_t framebuffer[GFX_MONO_LCD_FRAMEBUFFER_SIZE];
#endif

/**
 * \brief Initialize SSD1306 controller and LCD display.
 * It will also write the graphic controller RAM to all zeroes.
 *
 * \note This function will clear the contents of the display.
 */
void gfx_mono_ssd1306_init(void)
{
	uint8_t page;
	uint8_t column;

#ifdef CONFIG_SSD1306_FRAMEBUFFER
	gfx_mono_set_framebuffer(framebuffer);
#endif

	/* Initialize the low-level display controller. */
	ssd1306_init();

	/* Set display to output data from line 0 */
	ssd1306_set_display_start_line_address(0);

	/* Clear the contents of the display.
	 * If using a framebuffer (SPI interface) it will both clear the
	 * controller memory and the framebuffer.
	 */
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		for (column = 0; column < GFX_MONO_LCD_WIDTH; column++) {
			gfx_mono_ssd1306_put_byte(page, column, 0x00, true);
		}
	}
}

#ifdef CONFIG_SSD1306_FRAMEBUFFER
/**
 * \brief Put framebuffer to LCD controller
 *
 * This function will output the complete framebuffer from RAM to the
 * LCD controller.
 *
 * \note This is done automatically if using the graphic primitives. Only
 * needed if you are manipulating the framebuffer directly in your code.
 */
void gfx_mono_ssd1306_put_framebuffer(void)
{
	uint8_t page;

	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		ssd1306_set_page_address(page);
		ssd1306_set_column_address(0);
		gfx_mono_ssd1306_put_page(framebuffer
				+ (page * GFX_MONO_LCD_WIDTH), page, 0,
				GFX_MONO_LCD_WIDTH);
	}
}
#endif

/**
 * \brief Draw pixel to screen
 *
 * \param[in] x         X coordinate of the pixel
 * \param[in] y         Y coordinate of the pixel
 * \param[in] color     Pixel operation
 *
 * The following will set the pixel at x=10,y=10:
 * \code
	gfx_mono_ssd1306_draw_pixel(10, 10, GFX_PIXEL_SET);
\endcode
 * The following example will clear the pixel at x=10,y=10:
 * \code
	gfx_mono_ssd1306_draw_pixel(10, 10, GFX_PIXEL_CLR);
\endcode
 * And the following will toggle the pixel at x=10,y=10:
 * \code
	gfx_mono_ssd1306_draw_pixel(10, 10, GFX_PIXEL_XOR);
\endcode
 */
void gfx_mono_ssd1306_draw_pixel(gfx_coord_t x, gfx_coord_t y,
		gfx_coord_t color)
{
	uint8_t page;
	uint8_t pixel_mask;
	uint8_t pixel_value;

	/* Discard pixels drawn outside the screen */
	if ((x > GFX_MONO_LCD_WIDTH - 1) || (y > GFX_MONO_LCD_HEIGHT - 1)) {
		return;
	}

	page = y / GFX_MONO_LCD_PIXELS_PER_BYTE;
	pixel_mask = (1 << (y - (page * 8)));

	/*
	 * Read the page containing the pixel in interest, then perform the
	 * requested action on this pixel before writing the page back to the
	 * display.
	 */
	pixel_value = gfx_mono_get_byte(page, x);

	switch (color) {
	case GFX_PIXEL_SET:
		pixel_value |= pixel_mask;
		break;

	case GFX_PIXEL_CLR:
		pixel_value &= ~pixel_mask;
		break;

	case GFX_PIXEL_XOR:
		pixel_value ^= pixel_mask;
		break;

	default:
		break;
	}

	gfx_mono_put_byte(page, x, pixel_value);
}

/**
 * \brief Get the pixel value at x,y
 *
 * \param[in] x      X coordinate of pixel
 * \param[in] y      Y coordinate of pixel
 * \return Non zero value if pixel is set.
 *
 * The following example will read the pixel value from x=10,y=10:
 * \code
	pixelval = gfx_mono_ssd1306_get_pixel(10,10);
\endcode
 */
uint8_t gfx_mono_ssd1306_get_pixel(gfx_coord_t x, gfx_coord_t y)
{
	uint8_t page;
	uint8_t pixel_mask;

	if ((x > GFX_MONO_LCD_WIDTH - 1) || (y > GFX_MONO_LCD_HEIGHT - 1)) {
		return 0;
	}

	page = y / GFX_MONO_LCD_PIXELS_PER_BYTE;
	pixel_mask = (1 << (y - (page * 8)));

	return gfx_mono_get_byte(page, x) & pixel_mask;
}

/**
 * \brief Put a page from RAM to display controller.
 *
 * If the controller is accessed by the SPI interface, we can not read
 * back data from the LCD controller RAM. Because of this all data that is
 * written to the LCD controller in this mode is also written to a framebuffer
 * in MCU RAM.
 *
 * \param[in] data Pointer to data to be written
 * \param[in] page Page address
 * \param[in] column Offset into page (x coordinate)
 * \param[in] width Number of bytes to be written.
 *
 * The following example will write 32 bytes from data_buf to the page 0,
 * column 10. This will place data_buf in the rectangle x1=10,y1=0,x2=42,y2=8
 * (10 pixels from the upper left corner of the screen):
 * \code
	gfx_mono_ssd1306_put_page(data_buf, 0, 10, 32);
\endcode
 */
void gfx_mono_ssd1306_put_page(gfx_mono_color_t *data, gfx_coord_t page,
		gfx_coord_t column, gfx_coord_t width)
{
#ifdef CONFIG_SSD1306_FRAMEBUFFER
	gfx_mono_framebuffer_put_page(data, page, column, width);
#endif
	ssd1306_set_page_address(page);
	ssd1306_set_column_address(column);

	do {
		ssd1306_write_data(*data++);
	} while (--width);
}

/**
 * \brief Read a page from the LCD controller
 *
 * If the LCD controller is accessed by the SPI interface we cannot read
 * data directly from the controller. In that case we will read the data from
 * the local framebuffer instead.
 *
 * \param[in] data   Pointer where to store the read data
 * \param[in] page   Page address
 * \param[in] column Offset into page (x coordinate)
 * \param[in] width  Number of bytes to be read
 *
 * The following example will read back the first 128 bytes (first page) from
 * the display memory:
 * \code
	gfx_mono_ssd1306_get_page(read_buffer, 0, 0, 128);
\endcode
 */
void gfx_mono_ssd1306_get_page(gfx_mono_color_t *data, gfx_coord_t page,
		gfx_coord_t column, gfx_coord_t width)
{
#ifdef CONFIG_SSD1306_FRAMEBUFFER
	gfx_mono_framebuffer_get_page(data, page, column, width);
#else
	ssd1306_set_page_address(page);
	ssd1306_set_column_address(column);

	do {
		*data++ = ssd1306_read_data();
	} while (--width);
#endif
}

/**
 * \brief Put a byte to the display controller RAM
 *
 * If the LCD controller is accessed by the SPI interface we will also put the
 * data to the local framebuffer.
 *
 * \param[in] page Page address
 * \param[in] column Page offset (x coordinate)
 * \param[in] data Data to be written
 * \param[in] force Forces the write
 *
 * This example will put the value 0xFF to the first byte in the display memory
 * setting a 8 pixel high column of pixels in the upper left corner of the
 * display.
 * \code
	gfx_mono_ssd1306_put_byte(0, 0, 0xFF, false);
\endcode
  */
 void gfx_mono_ssd1306_put_byte(gfx_coord_t page, gfx_coord_t column,
		uint8_t data, bool force)
{
#ifdef CONFIG_SSD1306_FRAMEBUFFER
	if (!force && data == gfx_mono_framebuffer_get_byte(page, column)) {
		return;
	}
	gfx_mono_framebuffer_put_byte(page, column, data);
#endif

	ssd1306_set_page_address(page);
	ssd1306_set_column_address(column);

	ssd1306_write_data(data);
}

/**
 * \brief Get a byte from the display controller RAM
 *
 * If the LCD controller is accessed by the SPI interface we cannot read the
 * data. In this case return the data from the local framebuffer instead.
 *
 * \param[in] page Page address
 * \param[in] column Page offset (x coordinate)
 * \return data from LCD controller or framebuffer.
 *
 * The following code will read the first byte from the display memory or the
 * local framebuffer if direct read is not possible. The data represents the
 * pixels from x = 0 and y = 0 to y = 7.
 * \code
	data = gfx_mono_ssd1306_get_byte(0, 0);
\endcode
 */
uint8_t gfx_mono_ssd1306_get_byte(gfx_coord_t page, gfx_coord_t column)
{
#ifdef CONFIG_SSD1306_FRAMEBUFFER
	return gfx_mono_framebuffer_get_byte(page, column);

#else
	ssd1306_set_page_address(page);
	ssd1306_set_column_address(column);

	return ssd1306_read_data();

#endif
}

/**
 * \brief Read/Modify/Write a byte on the display controller
 *
 * This function will read the byte from the display controller (or the
 * framebuffer if we cannot read directly from the controller) and
 * do a mask operation on the byte according to the pixel operation selected
 * by the color argument and the pixel mask provided.
 *
 * \param[in] page Page address
 * \param[in] column Page offset (x coordinate)
 * \param[in] pixel_mask Mask for pixel operation
 * \param[in] color Pixel operation
 *
 * A small example that will XOR the first byte of display memory with 0xAA
 * \code
	gfx_mono_ssd1306_mask_byte(0,0,0xAA,GFX_PIXEL_XOR);
\endcode
 */
void gfx_mono_ssd1306_mask_byte(gfx_coord_t page, gfx_coord_t column,
		gfx_mono_color_t pixel_mask, gfx_mono_color_t color)
{
	gfx_mono_color_t temp = gfx_mono_get_byte(page, column);

	switch (color) {
	case GFX_PIXEL_SET:
		temp |= pixel_mask;
		break;

	case GFX_PIXEL_CLR:
		temp &= ~pixel_mask;
		break;

	case GFX_PIXEL_XOR:
		temp ^= pixel_mask;
		break;

	default:
		break;
	}

	gfx_mono_put_byte(page, column, temp);
}


text:
![Phaser+ES6+Webpack](https://raw.githubusercontent.com/lean/phaser-es6-webpack/master/assets/images/phaser-es6-webpack.jpg)

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

## Features
- ESLINT with JavaScript Standard Style configuration
- Next generation of Javascript
- Webpack ready
- Multiple browser testing
- WebFont Loader

# Setup
To use this bootstrap you'll need to install a few things before you have a working copy of the project.

## 1. Clone this repo:

Navigate into your workspace directory.

Run:

```git clone https://github.com/lean/phaser-es6-webpack.git```

## 2. Install node.js and npm:

https://nodejs.org/en/

## 3. Install dependencies (optionally you could install [yarn](https://yarnpkg.com/)):

Navigate to the cloned repo's directory.

Run:

```npm install```

or if you choose yarn, just run ```yarn```

## 4. Run the development server:

Run:

```npm run dev```

This will run a server so you can run the game in a browser.

Open your browser and enter localhost:3000 into the address bar.

Also this will start a watch process, so you can change the source and the process will recompile and refresh the browser

## Build for deployment:

Run:

```npm run deploy```

This will optimize and minimize the compiled bundle.

## Credits
Big thanks to this great repos:

https://github.com/belohlavek/phaser-es6-boilerplate

https://github.com/cstuncsik/phaser-es6-demo


text:
var Boot, _ref,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Phaser.State.prototype.constructor = Phaser.State;

module.exports = Boot = (function(_super) {
  __extends(Boot, _super);

  function Boot() {
    _ref = Boot.__super__.constructor.apply(this, arguments);
    return _ref;
  }

  Boot.prototype.preload = function() {
    return this.load.image('preloadBar', 'assets/loader.png');
  };

  Boot.prototype.create = function() {
    this.input.maxPointers = 1;
    this.stage.disableVisibilityChange = true;
    if (this.game.device.desktop) {
      this.stage.scale.pageAlignHorizontally = true;
    } else {

    }
    return this.game.state.start('Preloader', true, false);
  };

  return Boot;

})(Phaser.State);


text:
package main

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"

	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/alecthomas/kingpin"
)

var (
	timeout = kingpin.Flag("timeout", "Set connection timeout.").Short('t').Default("5s").Duration()
	headers = HTTPHeader(kingpin.Flag("headers", "Add HTTP headers to the request.").Short('H').PlaceHolder("HEADER=VALUE"))

	get         = kingpin.Command("get", "GET a resource.").Default()
	getFlag     = get.Flag("test", "Test flag").Bool()
	getURL      = get.Command("url", "Retrieve a URL.").Default()
	getURLURL   = getURL.Arg("url", "URL to GET.").Required().URL()
	getFile     = get.Command("file", "Retrieve a file.")
	getFileFile = getFile.Arg("file", "File to retrieve.").Required().ExistingFile()

	post           = kingpin.Command("post", "POST a resource.")
	postData       = post.Flag("data", "Key-value data to POST").Short('d').PlaceHolder("KEY:VALUE").StringMap()
	postBinaryFile = post.Flag("data-binary", "File with binary data to POST.").File()
	postURL        = post.Arg("url", "URL to POST to.").Required().URL()
)

type HTTPHeaderValue http.Header

func (h HTTPHeaderValue) Set(value string) error {
	parts := strings.SplitN(value, "=", 2)
	if len(parts) != 2 {
		return fmt.Errorf("expected HEADER=VALUE got '%s'", value)
	}
	(http.Header)(h).Add(parts[0], parts[1])
	return nil
}

func (h HTTPHeaderValue) String() string {
	return ""
}

func HTTPHeader(s kingpin.Settings) (target *http.Header) {
	target = &http.Header{}
	s.SetValue((*HTTPHeaderValue)(target))
	return
}

func applyRequest(req *http.Request) error {
	req.Header = *headers
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return fmt.Errorf("HTTP request failed: %s", resp.Status)
	}
	_, err = io.Copy(os.Stdout, resp.Body)
	return err
}

func apply(method string, url string) error {
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		return err
	}
	return applyRequest(req)
}

func applyPOST() error {
	req, err := http.NewRequest("POST", (*postURL).String(), nil)
	if err != nil {
		return err
	}
	if len(*postData) > 0 {
		for key, value := range *postData {
			req.Form.Set(key, value)
		}
	} else if postBinaryFile != nil {
		if headers.Get("Content-Type") != "" {
			headers.Set("Content-Type", "application/octet-stream")
		}
		req.Body = *postBinaryFile
	} else {
		return errors.New("--data or --data-binary must be provided to POST")
	}
	return applyRequest(req)
}

func main() {
	kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version("1.0").Author("Alec Thomas")
	kingpin.CommandLine.Help = "An example implementation of curl."
	switch kingpin.Parse() {
	case "get url":
		kingpin.FatalIfError(apply("GET", (*getURLURL).String()), "GET failed")

	case "post":
		kingpin.FatalIfError(applyPOST(), "POST failed")
	}
}


text:
 interface AxiosTransformer {
  (data: any, headers?: any): any;
}

 interface AxiosAdapter {
  (config: AxiosRequestConfig): AxiosPromise<any>;
}

 interface AxiosBasicCredentials {
  username: string;
  password: string;
}

 interface AxiosProxyConfig {
  host: string;
  port: number;
  auth?: {
    username: string;
    password:string;
  };
  protocol?: string;
}

 type Method =
  | 'get' | 'GET'
  | 'delete' | 'DELETE'
  | 'head' | 'HEAD'
  | 'options' | 'OPTIONS'
  | 'post' | 'POST'
  | 'put' | 'PUT'
  | 'patch' | 'PATCH'
  | 'link' | 'LINK'
  | 'unlink' | 'UNLINK'

 type AxiosResponseType =
  | 'arraybuffer'
  | 'blob'
  | 'document'
  | 'json'
  | 'text'
  | 'stream'

 interface AxiosRequestConfig {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: AxiosResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: (status: number) => boolean;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
}

 interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

 interface AxiosError<T = any> extends Error {
  config: AxiosRequestConfig;
  code?: string;
  request?: any;
  response?: AxiosResponse<T>;
  isAxiosError: boolean;
  toJSON: () => object;
}

 interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}

 interface CancelStatic {
  new (message?: string): Cancel;
}

 interface Cancel {
  message: string;
}

 interface Canceler {
  (message?: string): void;
}

 interface CancelTokenStatic {
  new (executor: (cancel: Canceler) => void): CancelToken;
  source(): CancelTokenSource;
}

 interface CancelToken {
  promise: Promise<Cancel>;
  reason?: Cancel;
  throwIfRequested(): void;
}

 interface CancelTokenSource {
  token: CancelToken;
  cancel: Canceler;
}

 interface AxiosInterceptorManager<V> {
  use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
  eject(id: number): void;
}

 interface AxiosInstance {
  (config: AxiosRequestConfig): AxiosPromise;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
  defaults: AxiosRequestConfig;
  interceptors: {
    request: AxiosInterceptorManager<AxiosRequestConfig>;
    response: AxiosInterceptorManager<AxiosResponse>;
  };
  getUri(config?: AxiosRequestConfig): string;
  request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
  get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}

 interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  isCancel(value: any): boolean;
  all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}

declare const Axios: AxiosStatic;


text:
package edu.psu.citeseerx.exec.com;

/**
 * Interface for listening to events in a connection pool.  Classes that
 * implement this interface should *not* register or de-register themselves
 * with the connection pool as part of the interface methods or a thread
 * deadlock can occur.
 *
 * @author Isaac Councill
 *
 */
public interface ConnectionPoolMonitor {
    public void notifyFinalized(ConnectionPool cp);
    public void notifyShutdown(ConnectionPool cp);
}


text:
  Treix est
       un village
       géographiquement positionné dans le département de Haute-Marne en Champagne-Ardenne. Elle totalisait 248 habitants en 2008.

À proximité de Treix sont positionnées géographiquement les villes de
Bologne située à 6 km, 1 849 habitants,
Riaucourt située à 4 km, 478 habitants,
Condes à 3 km, 271 habitants,
Briaucourt située à 6 km, 197 habitants,
Darmannes située à 3 km, 243 habitants,
Brethenay située à 3 km, 386 habitants,
 entre autres. De plus, Treix est située à seulement cinq km de Chaumont.

La ville compte quelques  équipements, elle propose entre autres un terrain de tennis et un terrain de sport.

Si vous envisagez de demenager à Treix, vous pourrez facilement trouver une maison à acheter.

Le parc d'habitations, à Treix, était réparti en 2011 en deux appartements et 106 maisons soit
 un marché plutôt équilibré.


text:
_[www.codever.land/bookmarks/t/base-de-datos](https://www.codever.land/bookmarks/t/base-de-datos)_
---
#### [Introducción a las Bases de Datos](http://ocw.uoc.edu/computer-science-technology-and-multimedia/bases-de-datos/bases-de-datos/P06_M2109_02147.pdf)
_http://ocw.uoc.edu/computer-science-technology-and-multimedia/bases-de-datos/bases-de-datos/P06_M210..._

(PDF)
* **tags**: [free-programming-books](../tagged/free-programming-books.md), [base-de-datos](../tagged/base-de-datos.md), [free-programming-books-es](../tagged/free-programming-books-es.md)
---
#### [El modelo relacional y el álgebra relacional](http://www.colegiodrriodelaloza.edu.mx/informatica/Analisis%20Diseno%20e%20Implementacion%20de%20Algoritmos/17470106-BASES-de-DATOS-3-El-Modelo-Relacional-y-Algebra-Relacional.pdf)
_http://www.colegiodrriodelaloza.edu.mx/informatica/Analisis%20Diseno%20e%20Implementacion%20de%20Alg..._

(PDF)
* **tags**: [free-programming-books](../tagged/free-programming-books.md), [base-de-datos](../tagged/base-de-datos.md), [free-programming-books-es](../tagged/free-programming-books-es.md)
---
#### [Base de Datos Avanzadas](http://repositori.uji.es/xmlui/bitstream/handle/10234/48034/s73.pdf)
_http://repositori.uji.es/xmlui/bitstream/handle/10234/48034/s73.pdf_

Aramburu & Sanz Blasco (PDF)
* **tags**: [free-programming-books](../tagged/free-programming-books.md), [base-de-datos](../tagged/base-de-datos.md), [free-programming-books-es](../tagged/free-programming-books-es.md)
---
#### [Base de Datos](http://www.uoc.edu/masters/oficiales/img/913.pdf)
_http://www.uoc.edu/masters/oficiales/img/913.pdf_

Mercedes Marqués (PDF)
* **tags**: [free-programming-books](../tagged/free-programming-books.md), [base-de-datos](../tagged/base-de-datos.md), [free-programming-books-es](../tagged/free-programming-books-es.md)
---
#### [Apuntes de Base de Datos 1, Universidad de Alicante](http://rua.ua.es/dspace/bitstream/10045/2990/1/ApuntesBD1.pdf)
_http://rua.ua.es/dspace/bitstream/10045/2990/1/ApuntesBD1.pdf_

(PDF)
* **tags**: [free-programming-books](../tagged/free-programming-books.md), [base-de-datos](../tagged/base-de-datos.md), [free-programming-books-es](../tagged/free-programming-books-es.md)
---


text:
import logging
from baseline.embeddings import register_embeddings, create_embeddings
from eight_mile.tf.embeddings import *
from eight_mile.tf.serialize import load_tlm_npz
from eight_mile.utils import read_json
from baseline.vectorizers import load_bert_vocab
from baseline.utils import MEAD_HUB_MODULES
import tensorflow as tf

logger = logging.getLogger('baseline')

class TensorFlowEmbeddingsMixin(tf.keras.layers.Layer):
    """This provides a base for TensorFlow embeddings sub-graphs that includes the placeholders

    """
    def __init__(self, trainable=True, name=None, dtype=tf.float32, **kwargs):
        """Constructor
        """
        super().__init__(trainable=trainable, name=name, dtype=dtype, **kwargs)
        self._record_state(**kwargs)

    def call(self, *x):
        self.x = x[0]

        return super().encode(*x)

    @classmethod
    def create(cls, model, name, **kwargs):
        """Instantiate this sub-graph from the generalized representation from `baseline.w2v`

        :param name: The name of the embeddings
        :param model: The `baseline.w2v` model
        :param kwargs:
        :return:
        """
        kwargs.pop('dsz', None)
        return cls(name=name, vsz=model.vsz, dsz=model.dsz, weights=model.weights, **kwargs)

    def _record_state(self, **kwargs):
        _ = kwargs.pop('weights', None)
        self._state = copy.deepcopy(kwargs)

    def save_md(self, target):
        """Save the metadata associated with this embedding as a JSON file

        :param target: The name of the output file
        :return:
        """
        write_json(self.get_config(), target)

    def get_config(self):
        config = {}
        config['dsz'] = int(self.get_dsz())
        config['vsz'] = int(self.get_vsz())
        config['module'] = self.__class__.__module__
        config['class'] = self.__class__.__name__
        config['mead_hub_modules'] = MEAD_HUB_MODULES
        config.update(self._state)
        return config

@register_embeddings(name='default')
class LookupTableEmbeddingsModel(TensorFlowEmbeddingsMixin, LookupTableEmbeddings):
    pass

@register_embeddings(name='char-conv')
class CharConvEmbeddingsModel(TensorFlowEmbeddingsMixin, CharConvEmbeddings):
    pass

@register_embeddings(name='char-transformer')
class CharTransformerModel(TensorFlowEmbeddingsMixin, CharTransformerEmbeddings):
    pass

@register_embeddings(name='char-lstm')
class CharLSTMEmbeddingsModel(TensorFlowEmbeddingsMixin, CharLSTMEmbeddings):
    pass

@register_embeddings(name='positional')
class PositionalLookupTableEmbeddingsModel(TensorFlowEmbeddingsMixin, PositionalLookupTableEmbeddings):
    pass

@register_embeddings(name='learned-positional')
class LearnedPositionalLookupTableEmbeddingsModel(TensorFlowEmbeddingsMixin, LearnedPositionalLookupTableEmbeddings):
    pass

@register_embeddings(name='learned-positional-w-bias')
class LearnedPositionalLookupTableEmbeddingsWithBiasModel(TensorFlowEmbeddingsMixin, LearnedPositionalLookupTableEmbeddingsWithBias):
    pass

@register_embeddings(name='positional-char-conv')
class PositionalCharConvEmbeddingsModel(TensorFlowEmbeddingsMixin, PositionalCharConvEmbeddings):
    pass

@register_embeddings(name='learned-positional-char-conv')
class PositionalCharConvEmbeddingsModel(TensorFlowEmbeddingsMixin, LearnedPositionalCharConvEmbeddings):
    pass

@register_embeddings(name='positional-char-lstm')
class PositionalCharLSTMEmbeddingsModel(TensorFlowEmbeddingsMixin, PositionalCharLSTMEmbeddings):
    pass

@register_embeddings(name='learned-positional-char-lstm')
class LearnedPositionalCharLSTMEmbeddingsModel(TensorFlowEmbeddingsMixin, LearnedPositionalCharLSTMEmbeddings):
    pass

class TransformerLMEmbeddings(TensorFlowEmbeddings):
    def __init__(self, name=None, **kwargs):
        super().__init__(name=name)
        # You dont actually have to pass this if you are using the `load_bert_vocab` call from your
        # tokenizer.  In this case, a singleton variable will contain the vocab and it will be returned
        # by `load_bert_vocab`
        # If you trained your model with MEAD/Baseline, you will have a `*.json` file which would want to
        # reference here
        vocab_file = kwargs.get('vocab_file')
        if vocab_file:
            if vocab_file.endswith('.json'):
                self.vocab = read_json(vocab_file)
            else:
                self.vocab = load_bert_vocab(kwargs.get('vocab_file'))
        else:
            self.vocab = kwargs.get('vocab', kwargs.get('known_vocab'))

        # When we reload, allows skipping restoration of these embeddings
        # If the embedding wasnt trained with token types, this allows us to add them later
        self.skippable = set(listify(kwargs.get('skip_restore_embeddings', [])))

        self.cls_index = self.vocab.get('[CLS]', self.vocab.get('<s>'))
        self.vsz = max(self.vocab.values()) + 1
        self.d_model = int(kwargs.get('dsz', kwargs.get('d_model', 768)))
        self.init_embed(**kwargs)
        self.proj_to_dsz = tf.keras.layers.Dense(self.dsz, self.d_model) if self.dsz != self.d_model else _identity
        self.init_transformer(**kwargs)
        self.return_mask = kwargs.get('return_mask', False)

    @property
    def dsz(self):
        return self.embeddings.output_dim

    def embed(self, input, token_type):
        return self.embeddings({'x': input, 'tt': token_type})

    def init_embed(self, **kwargs):
        # If you are using BERT, you probably want to use either
        # `learned-positional` with a token type feature
        # or `learned-positional-w-bias` if you dont care about the token type
        embed_type = kwargs.get('word_embed_type', 'learned-positional')
        mxlen = kwargs.get('mxlen', 512)
        x_embedding = create_embeddings(vsz=self.vsz, dsz=self.d_model, embed_type=embed_type, name='x', mxlen=mxlen)

        embeddings = {'x': x_embedding}
        # This is for BERT support when we are using 2 features
        token_type_vsz = kwargs.get('token_type_vsz')
        if token_type_vsz:
            tt_unif = float(kwargs.get('token_type_embed_unif', 0.001))
            tt_embedding = LookupTableEmbeddings(vsz=token_type_vsz, dsz=self.d_model, name='tt', padding_idx=None,
                                                 unif=tt_unif)
            embeddings['tt'] = tt_embedding
        # For bert, make sure this is `sum-layer-norm`
        reduction = kwargs.get('embeddings_reduction', kwargs.get('reduction', 'sum'))
        embeddings_dropout = kwargs.get('embeddings_dropout', 0.1)
        self.embeddings = EmbeddingsStack(embeddings, dropout_rate=embeddings_dropout, reduction=reduction)

    def init_transformer(self, **kwargs):
        num_layers = int(kwargs.get('layers', 12))
        num_heads = int(kwargs.get('num_heads', 12))
        pdrop = kwargs.get('dropout', 0.1)
        d_ff = int(kwargs.get('d_ff', 3072))
        d_k = kwargs.get('d_k')
        rpr_k = kwargs.get('rpr_k')
        layer_norms_after = kwargs.get('layer_norms_after', False)
        layer_norm_eps = kwargs.get('layer_norm_eps', 1e-12)
        activation = kwargs.get('activation', 'gelu')
        windowed_ra = kwargs.get('windowed_ra', False)
        rpr_value_on = kwargs.get('rpr_value_on', True)
        ra_type = kwargs.get('ra_type')
        transformer_type = kwargs.get("transformer_type", None)
        self.transformer = TransformerEncoderStack(num_heads, d_model=self.d_model, pdrop=pdrop, scale=True,
                                                   layers=num_layers, d_ff=d_ff, rpr_k=rpr_k, d_k=d_k,
                                                   activation=activation, layer_norms_after=layer_norms_after,
                                                   layer_norm_eps=layer_norm_eps, windowed_ra=windowed_ra,
                                                   rpr_value_on=rpr_value_on, ra_type=ra_type, transformer_type=transformer_type)
        self.mlm = kwargs.get('mlm', True)
        self.finetune = kwargs.get('finetune', True)

    def encode(self, x, token_type=None):
        # the following line masks out the attention to padding tokens
        input_mask = tf.expand_dims(tf.expand_dims(tf.cast(tf.not_equal(x, 0), tf.float32), 1), 1)
        # A causal LM should have a subsequent mask; and a masked LM should have no mask
        if not self.mlm:
            input_mask = tf.multiply(input_mask, subsequent_mask(x.shape[1]))
        embedding = self.embed(x, token_type)
        embedding = self.proj_to_dsz(embedding)
        transformer_out = self.transformer((embedding, input_mask))
        z = self.get_output(x, transformer_out, input_mask)
        return z

    def get_output(self, inputs, z, input_mask):
        if not self.finetune:
            z = tf.stop_gradient(z)
        if hasattr(self, 'return_mask') and self.return_mask:
            return (z, input_mask,)
        return z

    def get_vocab(self):
        return self.vocab

    def get_vsz(self):
        return self.vsz

    def get_dsz(self):
        return self.d_model

    @classmethod
    def load(cls, embeddings, **kwargs):
        c = cls("tlm-words-embed", **kwargs)

        # pass random data through to initialize the graph
        B = 1
        T = 8
        data_sample = tf.ones([B, T], dtype=tf.int32)
        token_type_vsz = kwargs.get('token_type_vsz')
        if token_type_vsz:
            _ = c(data_sample, data_sample)
        else:
            _ = c(data_sample)

        keys_to_restore = set(list(c.embeddings.keys()))
        filtered_keys = keys_to_restore.difference(c.skippable)
        if not keys_to_restore:
            raise Exception("No keys to restore!")
        if len(filtered_keys) < len(keys_to_restore):
            logger.warning("Restoring only key [%s]", ' '.join(filtered_keys))
        load_tlm_npz(c, embeddings, filtered_keys)
        return c

class TransformerLMPooledEmbeddings(TransformerLMEmbeddings):

    def __init__(self, name, **kwargs):
        super().__init__(name=name, **kwargs)

        pooling = kwargs.get('pooling', 'cls')
        if pooling == 'max':
            self.pooling_op = _max_pool
        elif pooling == 'mean':
            self.pooling_op = _mean_pool
        else:
            self.pooling_op = self._cls_pool

    def _cls_pool(self, inputs, tensor):
        pooled = tensor[tf.equal(inputs, self.cls_index)]
        return pooled

    def get_output(self, inputs, z, mask):
        return self.pooling_op(inputs, z)

class TransformerLMPooled2DEmbeddings(TransformerLMPooledEmbeddings):

    def encode(self, xch):
        """Encode 3D data

        When the TLM rehydrates, it uses a (B, T) shape, which would cause an exception on 3D data, so
        we do a try block to allow it to hydrate first

        :param xch:
        :return:
        """
        try:
            _0, _1, W = get_shape_as_list(xch)
            xch = tf.reshape(xch, [-1, W])
            pooled = super().encode(xch)
            pooled = tf.reshape(pooled, [_0, _1, self.get_dsz()])
        except:
            pooled = super().encode(xch)

        return pooled

@register_embeddings(name='tlm-words-embed')
class TransformerLMEmbeddingsModel(TensorFlowEmbeddingsMixin, TransformerLMEmbeddings):
    pass

@register_embeddings(name='tlm-words-embed-pooled')
class TransformerLMPooledEmbeddingsModel(TensorFlowEmbeddingsMixin, TransformerLMPooledEmbeddings):
    pass

@register_embeddings(name='tlm-words-embed-pooled2d')
class TransformerLMPooled2DEmbeddingsModel(TensorFlowEmbeddingsMixin, TransformerLMPooled2DEmbeddings):
    pass

def _identity(x):
    return x

def _mean_pool(inputs, embeddings):
    mask = tf.not_equal(inputs, 0)
    seq_lengths = tf.reduce_sum(tf.cast(mask, tf.int8), axis=1, keepdims=True)
    embeddings = tf.where(tf.expand_dims(mask, -1), embeddings, 0.)
    return tf.reduce_sum(embeddings, 1, False) / tf.cast(seq_lengths, embeddings.dtype)

def _max_pool(inputs, embeddings):
    mask = tf.not_equal(inputs, 0)
    embeddings = tf.where(tf.expand_dims(mask, -1), embeddings, -1.0e8)
    return tf.reduce_max(embeddings, 1, False)


text:
using System;
using System.Collections;
using System.IO;

// uncomment the define below to include unit tests
//#define nunit
#if nunit
using NUnit.Framework;

// Unit tests for the DotZLib class library
// ----------------------------------------
//
// Use this with NUnit 2 from http://www.nunit.org
//

namespace DotZLibTests
{
    using DotZLib;

    // helper methods
    internal class Utils
    {
        public static bool byteArrEqual( byte[] lhs, byte[] rhs )
        {
            if (lhs.Length != rhs.Length)
                return false;
            for (int i = lhs.Length-1; i >= 0; --i)
                if (lhs[i] != rhs[i])
                    return false;
            return true;
        }

    }

    [TestFixture]
    public class CircBufferTests
    {
        #region Circular buffer tests
        [Test]
        public void SinglePutGet()
        {
            CircularBuffer buf = new CircularBuffer(10);
            Assert.AreEqual( 0, buf.Size );
            Assert.AreEqual( -1, buf.Get() );

            Assert.IsTrue(buf.Put( 1 ));
            Assert.AreEqual( 1, buf.Size );
            Assert.AreEqual( 1, buf.Get() );
            Assert.AreEqual( 0, buf.Size );
            Assert.AreEqual( -1, buf.Get() );
        }

        [Test]
        public void BlockPutGet()
        {
            CircularBuffer buf = new CircularBuffer(10);
            byte[] arr = {1,2,3,4,5,6,7,8,9,10};
            Assert.AreEqual( 10, buf.Put(arr,0,10) );
            Assert.AreEqual( 10, buf.Size );
            Assert.IsFalse( buf.Put(11) );
            Assert.AreEqual( 1, buf.Get() );
            Assert.IsTrue( buf.Put(11) );

            byte[] arr2 = (byte[])arr.Clone();
            Assert.AreEqual( 9, buf.Get(arr2,1,9) );
            Assert.IsTrue( Utils.byteArrEqual(arr,arr2) );
        }

        #endregion
    }

    [TestFixture]
    public class ChecksumTests
    {
        #region CRC32 Tests
        [Test]
        public void CRC32_Null()
        {
            CRC32Checksum crc32 = new CRC32Checksum();
            Assert.AreEqual( 0, crc32.Value );

            crc32 = new CRC32Checksum(1);
            Assert.AreEqual( 1, crc32.Value );

            crc32 = new CRC32Checksum(556);
            Assert.AreEqual( 556, crc32.Value );
        }

        [Test]
        public void CRC32_Data()
        {
            CRC32Checksum crc32 = new CRC32Checksum();
            byte[] data = { 1,2,3,4,5,6,7 };
            crc32.Update(data);
            Assert.AreEqual( 0x70e46888, crc32.Value  );

            crc32 = new CRC32Checksum();
            crc32.Update("penguin");
            Assert.AreEqual( 0x0e5c1a120, crc32.Value );

            crc32 = new CRC32Checksum(1);
            crc32.Update("penguin");
            Assert.AreEqual(0x43b6aa94, crc32.Value);

        }
        #endregion

        #region Adler tests

        [Test]
        public void Adler_Null()
        {
            AdlerChecksum adler = new AdlerChecksum();
            Assert.AreEqual(0, adler.Value);

            adler = new AdlerChecksum(1);
            Assert.AreEqual( 1, adler.Value );

            adler = new AdlerChecksum(556);
            Assert.AreEqual( 556, adler.Value );
        }

        [Test]
        public void Adler_Data()
        {
            AdlerChecksum adler = new AdlerChecksum(1);
            byte[] data = { 1,2,3,4,5,6,7 };
            adler.Update(data);
            Assert.AreEqual( 0x5b001d, adler.Value  );

            adler = new AdlerChecksum();
            adler.Update("penguin");
            Assert.AreEqual(0x0bcf02f6, adler.Value );

            adler = new AdlerChecksum(1);
            adler.Update("penguin");
            Assert.AreEqual(0x0bd602f7, adler.Value);

        }
        #endregion
    }

    [TestFixture]
    public class InfoTests
    {
        #region Info tests
        [Test]
        public void Info_Version()
        {
            Info info = new Info();
            Assert.AreEqual("1.2.8", Info.Version);
            Assert.AreEqual(32, info.SizeOfUInt);
            Assert.AreEqual(32, info.SizeOfULong);
            Assert.AreEqual(32, info.SizeOfPointer);
            Assert.AreEqual(32, info.SizeOfOffset);
        }
        #endregion
    }

    [TestFixture]
    public class DeflateInflateTests
    {
        #region Deflate tests
        [Test]
        public void Deflate_Init()
        {
            using (Deflater def = new Deflater(CompressLevel.Default))
            {
            }
        }

        private ArrayList compressedData = new ArrayList();
        private uint adler1;

        private ArrayList uncompressedData = new ArrayList();
        private uint adler2;

        public void CDataAvail(byte[] data, int startIndex, int count)
        {
            for (int i = 0; i < count; ++i)
                compressedData.Add(data[i+startIndex]);
        }

        [Test]
        public void Deflate_Compress()
        {
            compressedData.Clear();

            byte[] testData = new byte[35000];
            for (int i = 0; i < testData.Length; ++i)
                testData[i] = 5;

            using (Deflater def = new Deflater((CompressLevel)5))
            {
                def.DataAvailable += new DataAvailableHandler(CDataAvail);
                def.Add(testData);
                def.Finish();
                adler1 = def.Checksum;
            }
        }
        #endregion

        #region Inflate tests
        [Test]
        public void Inflate_Init()
        {
            using (Inflater inf = new Inflater())
            {
            }
        }

        private void DDataAvail(byte[] data, int startIndex, int count)
        {
            for (int i = 0; i < count; ++i)
                uncompressedData.Add(data[i+startIndex]);
        }

        [Test]
        public void Inflate_Expand()
        {
            uncompressedData.Clear();

            using (Inflater inf = new Inflater())
            {
                inf.DataAvailable += new DataAvailableHandler(DDataAvail);
                inf.Add((byte[])compressedData.ToArray(typeof(byte)));
                inf.Finish();
                adler2 = inf.Checksum;
            }
            Assert.AreEqual( adler1, adler2 );
        }
        #endregion
    }

    [TestFixture]
    public class GZipStreamTests
    {
        #region GZipStream test
        [Test]
        public void GZipStream_WriteRead()
        {
            using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best))
            {
                BinaryWriter writer = new BinaryWriter(gzOut);
                writer.Write("hi there");
                writer.Write(Math.PI);
                writer.Write(42);
            }

            using (GZipStream gzIn = new GZipStream("gzstream.gz"))
            {
                BinaryReader reader = new BinaryReader(gzIn);
                string s = reader.ReadString();
                Assert.AreEqual("hi there",s);
                double d = reader.ReadDouble();
                Assert.AreEqual(Math.PI, d);
                int i = reader.ReadInt32();
                Assert.AreEqual(42,i);
            }

        }
        #endregion
	}
}

#endif


text:
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pg_eyes" to load this file. \quit

-- View: eyes.active_queryes

DROP VIEW eyes.active_queryes;

CREATE OR REPLACE VIEW eyes.active_queryes AS
SELECT sa.pid, sa.usename, sa.datname, sa.client_addr, application_name,
    now() - sa.xact_start AS xact_time,
    CASE
        WHEN sa.state = 'active' THEN now() - sa.query_start
        ELSE '00:00:00'
    END AS query_time,
    now() - sa.state_change AS state_time,
    sa.waiting, sa.state, sa.query
FROM eyes.get_pg_stat_activity() sa
WHERE sa.state != 'idle'
ORDER BY sa.xact_start;

ALTER VIEW eyes.active_queryes
    OWNER TO postgres;

COMMENT ON VIEW eyes.active_queryes
    IS 'Список всех активных запросов в базе данных';

-- View: eyes.db_objects

CREATE OR REPLACE VIEW eyes.db_objects AS
SELECT pn.nspname AS object_schema,
    pc.relname::TEXT AS object_name,
    CASE pc.relkind
        WHEN 'r' THEN 'TABLE'
        WHEN 'v' THEN 'VIEW'
        WHEN 'm' THEN 'MATERIALIZED VIEW'
        WHEN 'i' THEN 'INDEX'
        WHEN 'S' THEN 'SEQUENCE'
        WHEN 't' THEN 'TOAST'
        WHEN 'f' THEN 'FOREING TABLE'
        WHEN 'c' THEN 'COMPOSITE'
    END AS object_type,
    pg_catalog.pg_get_userbyid(pc.relowner) AS object_owner
FROM pg_catalog.pg_class pc
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace
WHERE  pn.nspname !~ '^pg_'
    AND pn.nspname != 'information_schema'
UNION
SELECT pn.nspname AS object_schema,
    pp.proname || '('
        || pg_catalog.pg_get_function_arguments(pp.oid)
        || ')'::TEXT AS object_name,
    'FUNCTION' AS object_type,
    pg_catalog.pg_get_userbyid(pp.proowner) AS object_owner
FROM pg_catalog.pg_proc pp
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pp.pronamespace
WHERE  pn.nspname !~ '^pg_'
    AND pn.nspname != 'information_schema';

ALTER VIEW eyes.db_objects
    OWNER TO postgres;

COMMENT ON VIEW eyes.db_objects
    IS 'Список всех объектов в базе данных';

-- View: eyes.db_functions

CREATE OR REPLACE VIEW eyes.db_functions AS
SELECT pn.nspname AS function_schema,
    pp.proname AS function_name,
    pg_catalog.pg_get_userbyid(pp.proowner) AS function_owner,
    pg_catalog.pg_get_function_result(pp.oid) as result_data_type,
    pg_catalog.pg_get_function_arguments(pp.oid) as argument_data_type,
    pp.prosrc AS source_code,
    pl.lanname AS function_language,
    CASE
        WHEN pp.provolatile = 'i' THEN 'IMMUTABLE'
        WHEN pp.provolatile = 's' THEN 'STABLE'
        WHEN pp.provolatile = 'v' THEN 'VOLATILE'
    END as function_volatility,
    CASE
        WHEN pp.prosecdef THEN 'SECURITY DEFINER'
        ELSE 'SECURITY INVOKER'
    END AS function_security
FROM pg_catalog.pg_proc pp
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pp.pronamespace
LEFT JOIN pg_catalog.pg_language pl ON pl.oid = pp.prolang
WHERE  pn.nspname !~ '^pg_'
    AND pn.nspname != 'information_schema';

ALTER VIEW eyes.db_functions
    OWNER TO postgres;

COMMENT ON VIEW eyes.db_functions
    IS 'Список всех функций в базе данных';

-- Function: eyes.backend_terminate(INTEGER)

CREATE OR REPLACE FUNCTION eyes.backend_terminate(p_pid INTEGER)
    RETURNS TEXT AS
$body$
DECLARE

/*
Описание:
    Выполнение функции pg_terminate_backend(p_pid)
*/

    v_terminate_status BOOLEAN;
    v_execute_status TEXT;

BEGIN

    EXECUTE 'SELECT pg_terminate_backend($1)'
    INTO v_terminate_status
    USING p_pid;

    IF v_terminate_status THEN
        v_execute_status := 'complete';
    ELSE
        v_execute_status := 'failure';
    END IF;

    IF NOT pg_is_in_recovery() THEN
        EXECUTE 'SELECT eyes.execute_log($1, $2, $3, $4, $5)'
        USING statement_timestamp(),
            statement_timestamp(),
            v_execute_status,
            'eyes.backend_terminate(' || p_pid || ')',
            null;
    END IF;

    RETURN v_execute_status;

END;
$body$
    LANGUAGE plpgsql VOLATILE SECURITY DEFINER
    COST 100;

ALTER FUNCTION eyes.backend_terminate(INTEGER) OWNER TO postgres;

REVOKE ALL ON FUNCTION eyes.backend_terminate(INTEGER) FROM public;

-- Function: eyes.backend_cancel(INTEGER)

CREATE OR REPLACE FUNCTION eyes.backend_cancel(p_pid INTEGER)
    RETURNS TEXT AS
$body$
DECLARE

/*
Описание:
    Выполнение функции pg_cancel_backend(p_pid)
*/

    v_terminate_status BOOLEAN;
    v_execute_status TEXT;

BEGIN

    EXECUTE 'SELECT pg_cancel_backend($1)'
    INTO v_terminate_status
    USING p_pid;

    IF v_terminate_status THEN
        v_execute_status := 'complete';
    ELSE
        v_execute_status := 'failure';
    END IF;

    IF NOT pg_is_in_recovery() THEN
        EXECUTE 'SELECT eyes.execute_log($1, $2, $3, $4, $5)'
        USING statement_timestamp(),
            statement_timestamp(),
            v_execute_status,
            'eyes.backend_cancel(' || p_pid || ')',
            null;
    END IF;

    RETURN v_execute_status;

END;
$body$
    LANGUAGE plpgsql VOLATILE SECURITY DEFINER
    COST 100;

ALTER FUNCTION eyes.backend_cancel(INTEGER) OWNER TO postgres;

REVOKE ALL ON FUNCTION eyes.backend_cancel(INTEGER) FROM public;

-- Function: eyes.get_activity();

CREATE OR REPLACE FUNCTION eyes.get_activity()
    RETURNS TABLE(stat_name character varying,
        stat_value bigint
    ) AS
$body$
DECLARE

/*
Описание:
    Получение метрик для систем мониторинга
*/

    -- pg_stat_activity
    v_total bigint;
    v_active bigint;
    v_active_1s bigint;
    v_active_time bigint;
    v_idle bigint;
    v_idle_in_tr bigint;
    v_idle_in_tr_1s bigint;
    v_idle_in_tr_time bigint;
    v_xact_time bigint;
    v_waiting bigint;
    v_waiting_1s bigint;
    v_waiting_time bigint;
    v_autovacuum bigint;
    v_autovacuum_time bigint;

    -- pg_stat_database
    v_backends_pct bigint;
    v_xact_total bigint;
    v_xact_commit bigint;
    v_xact_rollback bigint;
    v_blks_read bigint;
    v_blks_hit bigint;
    v_tup_returned bigint;
    v_tup_fetched bigint;
    v_tup_inserted bigint;
    v_tup_updated bigint;
    v_tup_deleted bigint;
    v_conflicts bigint;
    v_temp_files bigint;
    v_temp_bytes bigint;
    v_deadlocks bigint;

    -- pg_stat_database
    v_checkpoints_timed bigint;
    v_checkpoints_req bigint;
    v_checkpoint_write_time bigint;
    v_checkpoint_sync_time bigint;
    v_buffers_checkpoint bigint;
    v_buffers_clean bigint;
    v_maxwritten_clean bigint;
    v_buffers_backend bigint;
    v_buffers_backend_fsync bigint;
    v_buffers_alloc bigint;

    -- replication state
    v_last_xact_replay_timestamp timestamp with time zone;
    v_clock_timestamp timestamp with time zone;
    v_is_in_recovery bigint;
    v_ms_lag bigint;
    v_last_update_status bigint;

    r record;

BEGIN

    -- Get pg_stat_activity

    SELECT count(1) AS total,
        count(*) FILTER (WHERE state = 'active') AS active,
        count(*) FILTER (WHERE state = 'active'
            AND now() - query_start > interval '1s') AS active_1s,
        coalesce(max(round(extract(epoch FROM age(statement_timestamp(),
            query_start))*1000)) FILTER (WHERE state = 'active'),
            0) AS active_time,
        count(*) FILTER (WHERE state = 'idle') AS idle,
        count(*) FILTER (WHERE state LIKE 'idle in%') AS idle_in_tr,
        count(*) FILTER (WHERE state LIKE 'idle in%'
            AND statement_timestamp() - state_change > interval '1s')
            AS idle_in_tr_1s,
        coalesce(max(round(extract(epoch FROM age(statement_timestamp(),
            state_change))*1000)) FILTER (WHERE state LIKE 'idle in%'),
            0) AS idle_in_tr_time,
        coalesce(max(round(extract(epoch FROM age(statement_timestamp(),
            xact_start))*1000)) FILTER (WHERE state != 'idle'),
            0) AS xact_time,
        count(*) FILTER (WHERE waiting) AS waiting,
        count(*) FILTER (WHERE waiting
            AND statement_timestamp() - query_start > interval '1s')
            AS waiting_1s,
        coalesce(max(round(extract(epoch FROM age(statement_timestamp(),
            query_start))*1000)) FILTER (WHERE waiting),
            0) AS waiting_time,
        count(*) FILTER (WHERE state = 'active' AND query LIKE 'autovacuum:%')
            AS autovacuum,
        coalesce(max(round(extract(epoch FROM age(statement_timestamp(),
            query_start))*1000)) FILTER (WHERE state = 'active'
            AND query LIKE 'autovacuum:%'), 0) AS autovacuum_time
        INTO v_total,
            v_active, v_active_1s, v_active_time,
            v_idle, v_idle_in_tr, v_idle_in_tr_1s, v_idle_in_tr_time,
            v_xact_time, v_waiting, v_waiting_1s, v_waiting_time,
            v_autovacuum, v_autovacuum_time
    FROM pg_stat_activity;

    stat_name := 'pg_stat_activity.total';
    stat_value := v_total;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.active';
    stat_value := v_active;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.active_1s';
    stat_value := v_active_1s;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.active_time';
    stat_value := v_active_time;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.idle';
    stat_value := v_idle;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.idle_in_tr';
    stat_value := v_idle_in_tr;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.idle_in_tr_1s';
    stat_value := v_idle_in_tr_1s;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.idle_in_tr_time';
    stat_value := v_idle_in_tr_time;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.xact_time';
    stat_value := v_xact_time;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.waiting';
    stat_value := v_waiting;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.waiting_1s';
    stat_value := v_waiting_1s;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.waiting_time';
    stat_value := v_waiting_time;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.autovacuum';
    stat_value := v_autovacuum;
    RETURN NEXT;
    stat_name := 'pg_stat_activity.autovacuum_time';
    stat_value := v_autovacuum_time;
    RETURN NEXT;

    -- Get pg_stat_database

    SELECT round(
            100*(sum(numbackends)/current_setting('max_connections')::numeric),
            0) AS backends_pct,
        sum(xact_commit + xact_rollback) AS xact_total,
        sum(xact_commit) AS xact_commit,
        sum(xact_rollback) AS xact_rollback,
        sum(blks_read) AS blks_read,
        sum(blks_hit) AS blks_hit,
        sum(tup_returned) AS tup_returned,
        sum(tup_fetched) AS tup_fetched,
        sum(tup_inserted) AS tup_inserted,
        sum(tup_updated) AS tup_updated,
        sum(tup_deleted) AS tup_deleted,
        sum(conflicts) AS conflicts,
        sum(temp_files) AS temp_files,
        sum(temp_bytes) AS temp_bytes,
        sum(deadlocks) AS deadlocks
        INTO v_backends_pct, v_xact_total, v_xact_commit, v_xact_rollback,
            v_blks_read, v_blks_hit, v_tup_returned, v_tup_fetched,
            v_tup_inserted, v_tup_updated, v_tup_deleted, v_conflicts,
            v_temp_files, v_temp_bytes, v_deadlocks
    FROM pg_stat_database;

    stat_name := 'pg_stat_database.backends_pct';
    stat_value := v_backends_pct;
    RETURN NEXT;
    stat_name := 'pg_stat_database.xact_total';
    stat_value := v_xact_total;
    RETURN NEXT;
    stat_name := 'pg_stat_database.xact_commit';
    stat_value := v_xact_commit;
    RETURN NEXT;
    stat_name := 'pg_stat_database.xact_rollback';
    stat_value := v_xact_rollback;
    RETURN NEXT;
    stat_name := 'pg_stat_database.blks_read';
    stat_value := v_blks_read;
    RETURN NEXT;
    stat_name := 'pg_stat_database.blks_hit';
    stat_value := v_blks_hit;
    RETURN NEXT;
    stat_name := 'pg_stat_database.tup_returned';
    stat_value := v_tup_returned;
    RETURN NEXT;
    stat_name := 'pg_stat_database.tup_fetched';
    stat_value := v_tup_fetched;
    RETURN NEXT;
    stat_name := 'pg_stat_database.tup_inserted';
    stat_value := v_tup_inserted;
    RETURN NEXT;
    stat_name := 'pg_stat_database.tup_updated';
    stat_value := v_tup_updated;
    RETURN NEXT;
    stat_name := 'pg_stat_database.tup_deleted';
    stat_value := v_tup_deleted;
    RETURN NEXT;
    stat_name := 'pg_stat_database.conflicts';
    stat_value := v_conflicts;
    RETURN NEXT;
    stat_name := 'pg_stat_database.temp_files';
    stat_value := v_temp_files;
    RETURN NEXT;
    stat_name := 'pg_stat_database.temp_bytes';
    stat_value := v_temp_bytes;
    RETURN NEXT;
    stat_name := 'pg_stat_database.deadlocks';
    stat_value := v_deadlocks;
    RETURN NEXT;

    -- Get pg_stat_bgwriter

    SELECT checkpoints_timed AS checkpoints_timed,
        checkpoints_req AS checkpoints_req,
        checkpoint_write_time AS checkpoint_write_time,
        checkpoint_sync_time AS checkpoint_sync_time,
        buffers_checkpoint AS buffers_checkpoint,
        buffers_clean AS buffers_clean,
        maxwritten_clean AS maxwritten_clean,
        buffers_backend AS buffers_backend,
        buffers_backend_fsync AS buffers_backend_fsync,
        buffers_alloc AS buffers_alloc
        INTO v_checkpoints_timed, v_checkpoints_req, v_checkpoint_write_time,
            v_checkpoint_sync_time, v_buffers_checkpoint, v_buffers_clean,
            v_maxwritten_clean, v_buffers_backend, v_buffers_backend_fsync,
            v_buffers_alloc
    FROM pg_stat_bgwriter;

    stat_name := 'pg_stat_bgwriter.checkpoints_timed';
    stat_value := v_checkpoints_timed;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.checkpoints_req';
    stat_value := v_checkpoints_req;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.checkpoint_write_time';
    stat_value := v_checkpoint_write_time;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.checkpoint_sync_time';
    stat_value := v_checkpoint_sync_time;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.buffers_checkpoint';
    stat_value := v_buffers_checkpoint;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.buffers_clean';
    stat_value := v_buffers_clean;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.maxwritten_clean';
    stat_value := v_maxwritten_clean;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.buffers_backend';
    stat_value := v_buffers_backend;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.buffers_backend_fsync';
    stat_value := v_buffers_backend_fsync;
    RETURN NEXT;
    stat_name := 'pg_stat_bgwriter.buffers_alloc';
    stat_value := v_buffers_alloc;
    RETURN NEXT;

    -- Get replication state

    IF NOT pg_is_in_recovery() THEN
        -- If primary database
        v_is_in_recovery := 0;
        v_ms_lag := 0;
        -- Fake update to test replication
        v_last_update_status := eyes.update_time();
        -- Check the streaming replication lag
        FOR r IN SELECT application_name AS application_name,
            trunc(pg_xlog_location_diff(sent_location, replay_location)
                ) AS b_lag
            FROM pg_stat_replication
            WHERE state = 'streaming'
        LOOP
            stat_name := 'replication.streaming_'||r.application_name||'_b_lag';
            stat_value := r.b_lag;
            return next;
        END LOOP;
    ELSE
        -- If standby database
        v_is_in_recovery := 1;
        v_last_xact_replay_timestamp := pg_last_xact_replay_timestamp();
        v_clock_timestamp := clock_timestamp();
        v_ms_lag := trunc(extract(epoch FROM age(v_clock_timestamp,
            coalesce(v_last_xact_replay_timestamp, v_clock_timestamp)))*1000);
    END IF;

    stat_name := 'replication.is_in_recovery';
    stat_value := v_is_in_recovery;
    RETURN NEXT;
    stat_name := 'replication.ms_lag';
    stat_value := v_ms_lag;
    RETURN NEXT;

    -- Время ответа функции
    stat_name := 'response_time';
    stat_value := trunc(extract(epoch FROM age(clock_timestamp(),
            current_timestamp))*1000);
    RETURN NEXT;

    RETURN;

END;
$body$
    LANGUAGE plpgsql VOLATILE SECURITY DEFINER
    COST 100;

ALTER FUNCTION eyes.get_activity()
    OWNER TO postgres;

COMMENT ON FUNCTION eyes.get_activity()
    IS 'Получение метрик для систем мониторинга';

-- END


text:
import React = require('react')
import * as katex from 'katex'

interface KataxRendererProps {
  content
}

interface KataxRendererState {

}

export class KataxRenderer extends React.Component<KataxRendererProps, KataxRendererState> {
  private container: HTMLDivElement

  constructor(props) {
    super(props)
  }

  ref = el => this.container = el

  componetDidMount() {
    this.update(this.props.content)
  }

  componentWillReceiveProps(nextProps: KataxRendererProps) {
    if (this.props.content !== nextProps.content) {
      this.update(nextProps.content)
    }
  }

  update = (content) => {
    katex.render(content, this.container)
  }

  render() {
    return <div className="KataxRenderer black center" ref={ this.ref }>

    </div>
  }
}


text:
package org.neo4art.domain;

import org.neo4j.graphdb.Label;

/**
 * @author Lorenzo Speranzoni
 * @since 5 Apr 2015
 */
public enum Neo4ArtLabel implements Label
{
  Artist, Artwork, ArtMovement, Tecnique,

  Museum, ReligiousBuilding, Monument, HistoricSite, HistoricPlace,

  Country, Settlement,

  Book, Document,

  Colour, Emotion
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.sreevidya.opal.screen.home.HomeActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/appbar_padding_top"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <android.support.design.widget.TabLayout
                    android:id="@+id/tab_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabGravity="fill"
                    app:tabMode="fixed" />

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>


text:
using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Data;
using Subtext.Framework.Security;
using Subtext.Framework.Services;
using Subtext.Framework.Tracking;
using Subtext.Infrastructure;
using Subtext.Web.Controls;
using Subtext.Web.Properties;

namespace Subtext.Web.UI.Controls
{
    ///
    ///	Control used to view a single blog post.
    ///
    public partial class ViewPost : BaseControl
    {
        const string LinkToComments = "{1}{2}";
        const string LinkToEnclosure = "{2}{3}";

        ///
        /// Loads the entry specified by the URL.  If the user is an
        /// admin and the skin supports it, will also display an edit
        /// link that navigates to the admin section and allows the
        /// admin to edit the post.
        ///
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            //Get the entry
            Entry entry = Cacher.GetEntryFromRequest(true, SubtextContext);

            //if found
            if(entry != null)
            {
                BindCurrentEntryControls(entry, this);

                DisplayEditLink(entry);

                Bootstrapper.RequestContext = SubtextContext.RequestContext;
                var statistics = Bootstrapper.ServiceLocator.GetService<IStatisticsService>();
                statistics.RecordWebView(new EntryView {EntryId = entry.Id, BlogId = Blog.Id});

                //Set the page title
                Globals.SetTitle(entry.Title, Context);

                //Sent entry properties
                TitleUrl.Text = entry.Title;
                ControlHelper.SetTitleIfNone(TitleUrl, "Title of this entry.");
                TitleUrl.NavigateUrl = Url.EntryUrl(entry);
                Body.Text = entry.Body;
                if(PostDescription != null)
                {
                    PostDescription.Text = string.Format(CultureInfo.InvariantCulture, "{0} {1}",
                                                         entry.DateSyndicated.ToLongDateString(),
                                                         entry.DateSyndicated.ToShortTimeString());
                }
                Trace.Write("loading categories");
                if(Categories != null)
                {
                    Categories.LinkCategories = Links.GetLinkCategoriesByPostId(entry.Id);
                    Categories.DataBind();
                }

                if(date != null)
                {
                    string entryUrl = Url.EntryUrl(entry);
                    if(date.Attributes["Format"] != null)
                    {
                        date.Text = string.Format(CultureInfo.InvariantCulture, "{1}",
                                                  entryUrl, entry.DateSyndicated.ToString(date.Attributes["Format"]),
                                                  Resources.EntryList_PermanentLink);
                        date.Attributes.Remove("Format");
                    }
                    else
                    {
                        date.Text = string.Format(CultureInfo.InvariantCulture, "{1}",
                                                  entryUrl, entry.DateSyndicated.ToString("f"),
                                                  Resources.EntryList_PermanentLink);
                    }
                }

                if(commentCount != null)
                {
                    if(Blog.CommentsEnabled && entry.AllowComments)
                    {
                        string entryUrl = Url.EntryUrl(entry);
                        if(entry.FeedBackCount == 0)
                        {
                            commentCount.Text = string.Format(LinkToComments, entryUrl, Resources.EntryList_AddComment,
                                                              string.Empty);
                        }
                        else if(entry.FeedBackCount == 1)
                        {
                            commentCount.Text = string.Format(LinkToComments, entryUrl, Resources.EntryList_OneComment,
                                                              string.Empty);
                        }
                        else if(entry.FeedBackCount > 1)
                        {
                            commentCount.Text = string.Format(LinkToComments, entryUrl, entry.FeedBackCount,
                                                              Resources.EntryList_CommentsPlural);
                        }
                    }
                }

                BindEnclosure(entry);

                //Set Pingback/Trackback
                if(PingBack == null)
                {
                    PingBack = Page.FindControl("pinbackLinkTag") as Literal;
                }

                if(PingBack != null)
                {
                    PingBack.Text = TrackHelpers.GetPingPackTag(Url);
                }

                if(TrackBack != null)
                {
                    TrackBack.Text = TrackHelpers.TrackBackTag(entry, Blog, Url);
                }
                DataBind();
            }
            else
            {
                //No post? Deleted? Help :)
                Controls.Clear();
                Controls.Add(new LiteralControl(Resources.ViewPost_EntryNotFound));
            }
        }

        private void BindEnclosure(Entry entry)
        {
            if(Enclosure != null)
            {
                if(entry.Enclosure != null && entry.Enclosure.ShowWithPost)
                {
                    bool displaySize;
                    Boolean.TryParse(Enclosure.Attributes["DisplaySize"], out displaySize);

                    string sizeStr = "";
                    if(displaySize)
                    {
                        sizeStr = string.Format(" ({0})", entry.Enclosure.FormattedSize);
                    }
                    Enclosure.Text = string.Format(LinkToEnclosure, entry.Enclosure.Url, entry.Enclosure.Title,
                                                   entry.Enclosure.Title, sizeStr);
                }
            }
        }

        // If the user is an admin AND the the skin
        // contains an edit Hyperlink control, this
        // will display the edit control.
        private void DisplayEditLink(IIdentifiable entry)
        {
            if(editLink != null)
            {
                if(SecurityHelper.IsAdmin)
                {
                    editLink.Visible = true;
                    editLink.NavigateUrl = AdminUrl.PostsEdit(entry.Id);
                    ControlHelper.SetTitleIfNone(editLink, Resources.ViewPost_EditThisEntry);

                    if(String.IsNullOrEmpty(editLink.Text) && String.IsNullOrEmpty(editLink.ImageUrl))
                    {
                        //We'll slap on our little pencil icon.
                        editLink.ImageUrl = Url.EditIconUrl();
                    }
                }
                else
                {
                    editLink.Visible = false;
                }
            }
        }
    }
}


text:
using System.Linq;
using System.Text;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Razor.TagHelpers;
using WebApp.Models;

namespace WebApp.TagHelpers
{
    [HtmlTargetElement("city-list", Attributes = "city-id")]
    public class CitySelectListTagHelper : TagHelper
    {
        public int CityId { get; set; }
        public bool Disabled { get; set; }

        private ApplicationDbContext DbContext;

        public CitySelectListTagHelper([FromServices] ApplicationDbContext dbContext)
        {
            DbContext = dbContext;
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {

            output.TagName = "select";

            if (Disabled)
            {
                output.Attributes["disabled"] = "disabled";
            }

            var items = new StringBuilder();
            var cityList = DbContext.Cities.OrderBy(x => x.Name).ToList();

            items.Append("<option value=\"\">Все города</option>");
            foreach (var city in cityList)
            {
                if (city.Id == CityId)
                {
                    items.Append($"<option value=\"{city.Id}\" selected=\"true\">{city.Name}</option>");
                }
                else
                {
                    items.Append($"<option value=\"{city.Id}\">{city.Name}</option>");
                }
            }

            output.Content.SetHtmlContent(items.ToString());
            output.Attributes.Add("class", "ui fluid dropdown");
        }
    }
}


text:
package cn.internship.service;

import java.util.List;

import cn.internship.entity.Course;

/**
 * 课程业务层接口
 * @author dreamlate
 */
public interface CourseService {
	public List<Course> getAll();

	public List<Course> getBySno(Integer studentId);

	public List<Course> getByTno(Integer teacherId);

	public Integer getCourseScore(Integer studentId,Integer courseId);

	public Integer setCourseScore(Integer studentId,Integer courseId,Integer score);

	public Course get(Integer courseId);

	public void saveCourse(Course course);

	public void deleteCourse(Integer id);

	public void updateCourse(Course course);
}


text:
package httpfunction

import (
	"errors"
	"log"
)

//如果自定义了handler, 在此处添加case
func GetDatatablesHandler(tableName string)(ret DataTableHandler, err error)  {
	switch tableName {
	case "pets":
		ret = new(Petshandler)
	default:
		err = errors.New("tablename is not found")
		log.Println("failed to match tablename in func GetDatatablesHandler, err: ", err.Error())
	}
	return
}


text:
'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var mainBowerFiles = require('main-bower-files');
var electronServer = require('electron-connect').server;
var packager = require('electron-packager');
var pkg = require('./package.json');
var del = require('del');

var appDir = 'app/' + '';
var distDir = 'dist';
var serveDir = '.serve';
var releaseDir = 'release';

gulp.task('html', function () {
  gulp.src(appDir + '/*.html')
    .pipe(gulp.dest(serveDir))
    .pipe($.useref())
    .pipe(gulp.dest(distDir));
  return gulp.src(appDir + '/views/*.html')
    .pipe(gulp.dest(serveDir + '/views'))
    .pipe(gulp.dest(distDir + '/views'));
});

gulp.task('js', function () {
  gulp.src('main.js')
    .pipe(gulp.dest(serveDir))
    .pipe(gulp.dest(distDir));
  gulp.src([appDir + '/lib/*.js'])
    .pipe($.plumber())
    .pipe(gulp.dest(serveDir + '/lib'))
    .pipe(gulp.dest(distDir + '/lib'));
  gulp.src([appDir + '/scripts/*.js', appDir + '/scripts/**/*.js'])
    .pipe($.plumber())
    .pipe(gulp.dest(serveDir + '/scripts'));
  return gulp.src([appDir + '/scripts/*.js', appDir + '/scripts/**/*.js'])
    .pipe($.plumber())
    .pipe($.concat('main.js'))
    .pipe($.uglify({ mangle: false }))
    .pipe(gulp.dest(distDir + '/scripts'));
});

gulp.task('app', function () {
  return gulp.src(['package.json'])
    .pipe(gulp.dest(serveDir))
    .pipe(gulp.dest(distDir));
});

gulp.task('css', function () {
  gulp.src(appDir + '/styles/*.scss')
    .pipe($.plumber())
    .pipe($.sass())
    .pipe(gulp.dest(serveDir + '/styles'));
  return gulp.src(appDir + '/styles/*.scss')
    .pipe($.plumber())
    .pipe($.sass())
    .pipe($.concat('main.css'))
    .pipe(gulp.dest(distDir + '/styles'));
});

gulp.task('vendor', function () {
  gulp.src('bower_components/jquery/dist/jquery.min.js')
    .pipe(gulp.dest(distDir));
  gulp.src('bower_components/bootstrap/dist/fonts/*')
    .pipe(gulp.dest(distDir + '/fonts'));
  return gulp.src(mainBowerFiles({
      overrides: {
        bootstrap: {
          main: [
            './dist/js/bootstrap.js',
            './dist/css/*.min.*',
          ]
        }
      }
    }))
    .pipe(gulp.dest(serveDir + '/vendor'))
    .pipe($.plumber())
    .pipe($.if(function(file){
        return file.path.substr(-4) === '.css';
      }
      ,$.concat('vendor.css')
      ,$.concat('vendor.js')
    ))
    .pipe(gulp.dest(distDir + '/vendor'));
});

gulp.task('build', ['html', 'js', 'css', 'app', 'vendor', 'lint'], function () {
  return console.log('build finished!');
});

gulp.task('serve', ['build', 'watch'], function () {
  var electron = electronServer.create({ path: serveDir });
  electron.start();

  gulp.watch(['main.js'], electron.restart);
  gulp.watch([serveDir + '/scripts/*.js'], electron.restart);
  gulp.watch([serveDir + '/**/*.html', serveDir + '/styles/*.css'], electron.reload);
});

gulp.task('watch', function() {
  gulp.watch(['main.js', appDir + '/scripts/*.js', appDir + '/scripts/**/*.js'], ['js', 'js-hint']);
  gulp.watch([appDir + '/styles/*.scss'], ['css', 'scss-lint']);
  gulp.watch([appDir + '/*.html', appDir + '/views/*.html'], ['html']);
  gulp.watch('gulpfile.js', ['build']);
});

gulp.task('clean', function (done) {
  del([serveDir, distDir, releaseDir], function () {
    done();
  });
});

gulp.task('package', ['win32', 'darwin'].map(function (platform) {
  var taskName = 'package:' + platform;
  gulp.task(taskName, ['build'], function (done) {
    packager({
      dir: distDir,
      name: pkg.name,
      arch: 'x64',
      platform: platform,
      out: releaseDir,
      overwrite: true,
      version: '0.34.1'
    }, function (err) {
      done();
    });
  });
  return taskName;
}));

gulp.task('js-hint', function() {
  return gulp.src(appDir + '/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('default'));
});

gulp.task('scss-lint', function() {
  return gulp.src(appDir + '/**/*.scss')
    .pipe($.scssLint({
      'config': './scss-lint.yml',
    }));
});

gulp.task('lint', ['js-hint', 'scss-lint'], function() {
});

gulp.task('default', ['build', 'watch'], function () {
});


text:
#include "wm_HC_Bluetooth.h"

#include <EEPROM.h>
#include "Funcs.h"

bool HC_Bluetooth::WasNameChangeRequested(){
  /* Make sure to add delay before this function to avoid accidentally sending AT command when unplugging (in case if board resets during unplug and reboots quickly)  */
  int num = 0;
  EEPROM.get(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_NAME_CHANGE, num);

  dbgf(F("HC_Bluetooth::WasNameChangeRequested - num = %d"), num);

  return num == EEPROM_CHANGE_REQUESTED_ID;
}

void HC_Bluetooth::ResetNameChangeRequestFlag(){
  EEPROM.put(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_NAME_CHANGE, 0);
}

bool HC_Bluetooth::WasPasswordChangeRequested(){
  /* Make sure to add delay before this function to avoid accidentally sending AT command when unplugging (in case if board resets during unplug and reboots quickly)  */
  int num;
  EEPROM.get(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_PIN_CHANGE, num);

  dbgf(F("HC_Bluetooth::WasPasswordChangeRequested - num = %d"), num);
  return num == EEPROM_CHANGE_REQUESTED_ID;
}

void HC_Bluetooth::ResetPasswordChangeRequestFlag(){
  EEPROM.put(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_PIN_CHANGE, (int)0);
}

void HC_Bluetooth::ChangeName(){
  char bluetoothName[BLUETOOTH_NAME_SIZE] = {0};
  //Serial.println(bluetoothName);
  EEPROM.get(EEPROM_ADDRESS_BLUETOOTH_NAME, bluetoothName);
  char at_cmd[BLUETOOTH_NAME_SIZE + 15] = {0};
  sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
  delay(700);

  ser->print(at_cmd);

  dbgf(F("HC_Bluetooth::ChangeName - at_cmd = %s"), at_cmd);

  delay(1000);
  if(ser->available()){
    dbgf(F("HC_Bluetooth::ChangeName - at_cmd response = %s"), ser->readString().c_str());
  }

  while(ser->available()){char c = ser->read();}
}

void HC_Bluetooth::ChangePassword(){
  char pin[5] = {0};
  EEPROM.get(EEPROM_ADDRESS_BLUETOOTH_PIN, pin);
  char at_cmd[16] = {0};
  sprintf(at_cmd, "AT+PIN%s\0", pin);
  delay(700);
  ser->print(at_cmd);

  dbgf(F("HC_Bluetooth::ChangePassword - at_cmd = %s"), at_cmd);

  delay(1000);

  if(ser->available()){
    dbgf(F("HC_Bluetooth::ChangePassword - at_cmd response = %s"), ser->readString().c_str());
  }

  while(ser->available()){char c = ser->read();}
}

/* OLD FUNCTION */

/*
void ChangeBluetoothCheck(){
  int numCheck = 0;

  EEPROM.get(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_NAME_CHANGE, numCheck);
  if(numCheck == 777)
  {
    delay(700);                                 // delay is there to avoid accidentally sending AT command when unplugging (in case if board resets during unplug and reboots quickly)
    EEPROM.put(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_NAME_CHANGE, 0);
    char bluetoothName[BLUETOOTH_NAME_SIZE] = {0};
    //Serial.println(bluetoothName);
    EEPROM.get(EEPROM_ADDRESS_BLUETOOTH_NAME, bluetoothName);
    char at_cmd[BLUETOOTH_NAME_SIZE + 15] = {0};
    sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
    delay(700);

    wm->ser->print(at_cmd);

    delay(1000);
    #ifdef LOG_SERIAL
      if(wm->ser->available()){Serial.println("Changed bluetooth name (" + String(at_cmd) + "), response: " + wm->ser->readString());}
      while(wm->ser->available()){char c = wm->ser->read();}                // just to be sure there's no bytes left
    #else
      while(wm->ser->available()){char c = wm->ser->read();}
    #endif
  }

  numCheck = 0;

  EEPROM.get(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_PIN_CHANGE, numCheck);
  if(numCheck == 777)
  {
    delay(700);                                 // delay is there to avoid accidentally sending AT command when unplugging (in case if board resets during unplug and reboots quickly)
    EEPROM.put(EEPROM_ADDRESS_REQUESTED_BLUETOOTH_PIN_CHANGE, (int)0);
    char pin[5] = {0};
    EEPROM.get(EEPROM_ADDRESS_BLUETOOTH_PIN, pin);
    char at_pin_cmd[16] = {0};
    sprintf(at_pin_cmd, "AT+PIN%s\0", pin);
    delay(700);
    wm->ser->print(at_pin_cmd);

    delay(1000);

    #ifdef LOG_SERIAL
      if(wm->ser->available()){Serial.println("Changed bluetooth pin (" + String(at_pin_cmd) + "), response: " + wm->ser->readString());}
      while(wm->ser->available()){char c = wm->ser->read();}                // just to be sure there's no bytes left
    #else
      while(wm->ser->available()){char c = wm->ser->read();}
    #endif
  }
}
*/


text:
#!/usr/bin/env php
<?php

/**
 * Template for migration
 */
$template = "<?php

use App\Models\Configs;
use Illuminate\Database\Migrations\Migration;

class BumpVersion%s extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Configs::where('key', 'version')->update(['value' => '%s']);
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Configs::where('key', 'version')->update(['value' => '%s']);
	}
}
";

/**
 * We get the current version number
 *
 * @return array
 */
function get_version()
{
    $str_CurrentVersion = @file_get_contents('version.md');
    if (!$str_CurrentVersion) {
        throw new Exception("unable to find current version number in version.md\n");
    }
    $arr_CurrentVersion = array_map('intval', explode('.', $str_CurrentVersion));
    if (count($arr_CurrentVersion) != 3) {
        throw new Exception("invalid version number");
    }

    return $arr_CurrentVersion;
}

/**
 * Given the current version and the update array return the new version number
 *
 * @param array $curr_version : current version number
 * @param string $kind : 'minor' or 'major'
 *
 * @return array
 */
function new_version(array $curr_version, string $kind)
{
    $new_version = $curr_version;
    switch ($kind) {
        case 'major':
            if ($curr_version[1] == 99) {
                throw new Exception("Maybe it is time for a big change?");
            }
            $new_version[1] += 1;
            $new_version[2] = 0;
            break;
        case 'minor':
        default:
            if ($curr_version[2] == 99) {
                throw new Exception("Maybe it is time for a major release?");
            }
            $new_version[2] += 1;
            break;
    }

    return $new_version;
}

/**
 * encode $version into a string of 6 digits
 *
 * @return string
 */
function str_version(array $version)
{
    return sprintf("%02d%02d%02d", $version[0], $version[1], $version[2]);
}

/**
 * Check if migration with same name already exists
 */
function does_migration_exists(string $version)
{
    $name_candidate = 'bump_version' . $version;
    $migrations = array_slice(scandir('database/migrations'), 2);
    foreach ($migrations as $migration) {
        // given 2020_04_22_155712_bump_version040002.php we retrieve bump_version040002
        $name = explode("_", $migration, 5);
        $name = substr($name[4], 0, -4);
        if ($name == $name_candidate) {
            throw new Exception('Migration ' . $name_candidate . ' already exsists!');
        }
    }
}

$kind = $argv[1] ?? 'minor';

try {
    $cv = get_version();
    $nv = new_version($cv, $kind);

    $str_cv = str_version($cv);
    $str_nv = str_version($nv);

    does_migration_exists($str_nv);

    $fileName = sprintf('database/migrations/%s_bump_version%s.php', date('Y_m_d_His'), $str_nv);
    $fileContent = sprintf($template, $str_nv, $str_nv, $str_cv);

    file_put_contents($fileName, $fileContent);
    echo "Migration generated!\n";

    file_put_contents('version.md', implode('.', $nv));
    echo "version.md updated!\n";

    exit;
} catch (Exception $e) {
    exit("\e[0;31m" . $e->getMessage() . "\e[0m\n");
}


text:
<?php

	namespace MrAudioGuy\Syslog;

	/**
	 * Description of Prioroty
	 *
	 * Prioroties of Syslog as described in RFC 5424 Headers
	 *
	 * @author Talaeezadeh <your.brother.t@hotmail.com>
	 */
	class Prioroty
	{
		// <editor-fold defaultstate="collapsed" desc="Facilities">

		public static $fac_kernel_messages = 0;
		public static $fac_user_level_messages = 1;
		public static $fac_mail_system = 2;
		public static $fac_system_daemons = 3;
		public static $fac_security_or_authorization_messages = 4;
		public static $fac_messages_generated_internally_by_syslogd = 5;
		public static $fac_line_printer_subsystem = 6;
		public static $fac_network_news_subsystem = 7;
		public static $fac_UUCP_subsystem = 8;
		public static $fac_clock_daemon = 9;
		public static $fac_security_or_authorization_messages_1 = 10;
		public static $fac_FTP_daemon = 11;
		public static $fac_NTP_subsystem = 12;
		public static $fac_log_audit = 13;
		public static $fac_log_alert = 14;
		public static $fac_clock_daemon_1 = 15;
		public static $fac_local_use_0 = 16;
		public static $fac_local_use_1 = 17;
		public static $fac_local_use_2 = 18;
		public static $fac_local_use_3 = 19;
		public static $fac_local_use_4 = 20;
		public static $fac_local_use_5 = 21;
		public static $fac_local_use_6 = 22;
		public static $fac_local_use_7 = 23;

		public static $FAC_KERNEL_MESSAGES = 0;
		public static $FAC_USER_LEVEL_MESSAGES = 1;
		public static $FAC_MAIL_SYSTEM = 2;
		public static $FAC_SYSTEM_DAEMONS = 3;
		public static $FAC_SECURITY_OR_AUTHORIZATION_MESSAGES = 4;
		public static $FAC_MESSAGES_GENERATED_INTERNALLY_BY_SYSLOGD = 5;
		public static $FAC_LINE_PRINTER_SUBSYSTEM = 6;
		public static $FAC_NETWORK_NEWS_SUBSYSTEM = 7;
		public static $FAC_UUCP_SUBSYSTEM = 8;
		public static $FAC_CLOCK_DAEMON = 9;
		public static $FAC_SECURITY_OR_AUTHORIZATION_MESSAGES_1 = 10;
		public static $FAC_FTP_DAEMON = 11;
		public static $FAC_NTP_SUBSYSTEM = 12;
		public static $FAC_LOG_AUDIT = 13;
		public static $FAC_LOG_ALERT = 14;
		public static $FAC_CLOCK_DAEMON_1 = 15;
		public static $FAC_LOCAL_USE_0 = 16;
		public static $FAC_LOCAL_USE_1 = 17;
		public static $FAC_LOCAL_USE_2 = 18;
		public static $FAC_LOCAL_USE_3 = 19;
		public static $FAC_LOCAL_USE_4 = 20;
		public static $FAC_LOCAL_USE_5 = 21;
		public static $FAC_LOCAL_USE_6 = 22;
		public static $FAC_LOCAL_USE_7 = 23;

		// </editor-fold>

		// <editor-fold defaultstate="collapsed" desc="Severities">

		public static $emergency = 0;
		public static $alert = 1;
		public static $critical = 2;
		public static $error = 3;
		public static $warning = 4;
		public static $notice = 5;
		public static $informational = 6;
		public static $debug = 7;

		public static $EMERGENCY = 0;
		public static $ALERT = 1;
		public static $CRITICAL = 2;
		public static $ERROR = 3;
		public static $WARNING = 4;
		public static $NOTICE = 5;
		public static $INFORMATIONAL = 6;
		public static $DEBUG = 7;

		// </editor-fold>
	}


text:
import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { FormsModule }      from '@angular/forms';
import { HttpModule }       from '@angular/http';

import { WebsocketService } from './websocket.service';

import { BoardComponent }   from './board.component';
import { Cell }             from './cell.component';

@NgModule({
  imports:      [ BrowserModule,
				  FormsModule,
				  HttpModule
				],
  declarations: [ BoardComponent
				],
  providers:    [ WebsocketService ],
  bootstrap:    [ BoardComponent ]
})
export class AppModule { }


text:
package cuke4duke.internal.jvmclass;

import com.google.inject.AbstractModule;
import cuke4duke.internal.jvmclass.GuiceFactoryTest.SomeClass.SomeInnerClass;
import org.junit.Before;
import org.junit.Test;

public class GuiceFactoryTest {
    public static class SomeClass {
        public class SomeInnerClass {
        }

        public Object someInstance = new Object() {
        };
    }

    public class SomeModule extends AbstractModule {
        @Override
        protected void configure() {
        }
    }

    private GuiceFactory guiceFactory;

    @Before
    public void setUp() throws Throwable {
        guiceFactory = new GuiceFactory("cuke4duke.internal.jvmclass.SomeModule");
    }

    /**
     * Tests that GuiceFactory does not fail if a class cannot be instantiated.
     * One problem that occurs frequently is that inner classes get compiled
     * to their own .class files and are picked up by GuiceFactory.
     * As Guice cannot instantiate non-static inner classes and anonymous classes
     * it throws an exception and aborts the instantiation process.
     * By catching those exceptions Guice can continue and creates
     * everything correctly.
     */
    @Test
    public void shouldNotAbortIfClassCannotBeInstantiated() {
        guiceFactory.addClass(SomeClass.class);

        SomeClass instance = new SomeClass();
        Class<? extends SomeInnerClass> someInnerClass = instance.new SomeInnerClass().getClass();
        if (guiceFactory.canHandle(someInnerClass)) {
            guiceFactory.addClass(someInnerClass);
        }
        guiceFactory.createObjects();

	}

}


text:
package com.msopentech.odatajclient.engine.data.metadata.edm.v3;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.msopentech.odatajclient.engine.data.metadata.edm.AbstractEdm;

public class ValueTerm extends AbstractEdm {

    private static final long serialVersionUID = 6149019886137610604L;

    @JsonProperty(value = "Name", required = true)
    private String name;

    @JsonProperty(value = "Type", required = true)
    private String type;

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(final String type) {
        this.type = type;
    }
}


text:
'''
PROBLEM LINK:
https://www.hackerrank.com/challenges/strange-advertising/problem
'''

import math
import os
import random
import re
import sys

def f(prev):
    return (prev // 2) * 3, prev // 2

# Complete the viralAdvertising function below.
def viralAdvertising(n):
    culm_likes = 0
    shared = 5
    for i in range(n):
        shared, likes = f(shared)
        culm_likes += likes
    return culm_likes

if __name__ == '__main__':
    # fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    result = viralAdvertising(n)

    print(result)

    # fptr.write(str(result) + '\n')

    # fptr.close()


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>69 nips-2001-Escaping the Convex Hull with Extrapolated Vector Machines</title>

nips nips2001 nips2001-69 nips2001-69-reference knowledge-graph by maker-knowledge-mining

69 nips-2001-Escaping the Convex Hull with Extrapolated Vector Machines

Source: pdf

Author: Patrick Haffner

Abstract: Maximum margin classifiers such as Support Vector Machines (SVMs) critically depends upon the convex hulls of the training samples of each class, as they implicitly search for the minimum distance between the convex hulls. We propose Extrapolated Vector Machines (XVMs) which rely on extrapolations outside these convex hulls. XVMs improve SVM generalization very significantly on the MNIST [7] OCR data. They share similarities with the Fisher discriminant: maximize the inter-class margin while minimizing the intra-class disparity. 1

reference text

[1] R. Collobert and S. Bengio. Support vector machines for large-scale regression problems. Technical Report IDIAP-RR-00-17, IDIAP, 2000.

[2] C. Cortes and V. Vapnik. Support vector networks. Machine Learning, 20:1- 25 , 1995.

[3] D. Crisp and C.J.C. Burges. A geometric interpretation of v-SVM classifiers. In Advances in Neural Information Processing Systems 12, S. A. Solla, T. K. Leen, K.-R. Mller, eds, Cambridge, MA, 2000. MIT Press.

[4] D. DeCoste and B. Schoelkopf. Training invariant support vector machines. Machine Learning, special issue on Support Vector Machines and Methods, 200l.

[5] S.S. Keerthi, S.K. Shevade, C. Bhattacharyya, and K.R.K. Murthy. A fast iterative nearest point algorithm for support vector machine classifier design. IEEE transactions on neural networks, 11(1):124 - 136, jan 2000.

[6] A. Kowalczyk. Maximal margin perceptron. In Advances in Large Margin Classifiers, Smola, Bartlett, Schlkopf, and Schuurmans, editors, Cambridge, MA, 2000. MIT Press.

[7] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. Gradient-based learning applied to document recognition. proceedings of the IEEE, 86(11), 1998.

[8] J. Platt, N. Christianini, and J. Shawe-Taylor. Large margin dags for multiclass classification. In Advances in Neural Information Processing Systems 12, S. A. Solla, T. K. Leen, K.-R. Mller, eds, Cambridge, MA, 2000. MIT Press.

[9] V. N. Vapnik. Statistical Learning Theory. John Wiley & Sons, New-York, 1998.


text:
'use strict';

var through = require('through'),
  extend = require('extend');

/**
 * Create a transform stream that normalizes synonymous tags to the canonical tag type
 * listed on http://usejsdoc.org/.
 *
 * For example, given the input object:
 *
 *     { tags: [
 *       { title: "virtual" },
 *       { title: "return", ... }
 *     ]}
 *
 * The output object will be:
 *
 *     { tags: [
 *       { title: "abstract" },
 *       { title: "returns", ... }
 *     ]}
 *
 * The following synonyms are normalized:
 *
 *  * virtual -> abstract
 *  * extends -> augments
 *  * constructor -> class
 *  * const -> constant
 *  * defaultvalue -> default
 *  * desc -> description
 *  * host -> external
 *  * fileoverview, overview -> file
 *  * emits -> fires
 *  * func, method -> function
 *  * var -> member
 *  * arg, argument -> param
 *  * prop -> property
 *  * return -> returns
 *  * exception -> throws
 *  * linkcode, linkplain -> link
 *
 * @name normalize
 * @return {stream.Transform}
 */
module.exports = function () {
  return through(function (comment) {
    this.push(extend({}, comment, {
      tags: comment.tags.map(normalize)
    }));
  });
};

var synonyms = {
  'virtual': 'abstract',
  'extends': 'augments',
  'constructor': 'class',
  'const': 'constant',
  'defaultvalue': 'default',
  'desc': 'description',
  'host': 'external',
  'fileoverview': 'file',
  'overview': 'file',
  'emits': 'fires',
  'func': 'function',
  'method': 'function',
  'var': 'member',
  'arg': 'param',
  'argument': 'param',
  'prop': 'property',
  'return': 'returns',
  'exception': 'throws',
  'linkcode': 'link',
  'linkplain': 'link'
};

function normalize(tag) {
  var canonical = synonyms[tag.title];
  return canonical ? extend({}, tag, { title: canonical }) : tag;
}