text:
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};
$ = jQuery;
/*************** COMMANDS *************/
var commands = {};

commands.Raise = function Raise(replayer, player, data) {
  this.replayer = replayer;
  this.player = player;
  this.amount = data.amount;

  this.apply = function() {
    stack = parseFloat(this.player.getStack()) - parseFloat(this.amount) + parseFloat(this.player.getBet());
    this.player.setStack(stack);
    realAmount = parseFloat(this.amount) - parseFloat(this.player.getBet());
    this.player.setBet(this.amount);
    this.player.pushBet(this.amount);
    this.player.setAction('raises');

	  this.replayer.pot.add(realAmount);
    this.replayer.pot.pushRaise(this.player.getBet());
  };

  this.undo = function() {
    lastBet = this.player.getLastBet();
    oldAmount = parseFloat(this.player.getBet()) - parseFloat(this.amount) + lastBet;
    this.player.setBet(oldAmount);
	  stack = parseFloat(this.player.getStack()) + parseFloat(this.amount) - lastBet;
	  this.player.setStack(stack);
    this.player.setAction('');

    this.replayer.pot.remove(this.amount - lastBet);
    this.replayer.pot.popRaise();
  };
};

commands.Call = function Call(replayer, player, data) {
  this.replayer = replayer;
  this.player = player;
  this.amount = data.amount;

  this.apply = function() {
	  stack = parseFloat(this.player.getStack()) - parseFloat(this.amount);
    this.player.setStack(stack);
    amount = parseFloat(this.amount) + parseFloat(this.player.getBet());
    this.player.setBet(amount);
    this.player.pushBet(amount);
    this.player.setAction('calls');

    this.replayer.pot.add(this.amount);
  };

  this.undo = function() {
    this.player.popBet();
    oldAmount = parseFloat(this.player.getBet()) - parseFloat(this.amount);
    this.player.setBet(oldAmount);
	  stack = parseFloat(this.player.getStack()) + parseFloat(this.amount);
	  this.player.setStack(stack);
    this.player.setAction('');

    this.replayer.pot.remove(this.amount);
  };
};

commands.Fold = function Fold(replayer, player, data) {
  this.replayer = replayer;
  this.player = player;

  this.apply = function(){
    this.player.setAction('folds');
    this.player.muck();
  };

  this.undo = function(){
    this.player.setAction('');
    this.player.unMuck();
  };
};

commands.Check = function Check(replayer, player, data) {
  this.replayer = replayer;
  this.player = player;

  this.apply = function(){
    this.player.setAction('checks');
    this.player.pushBet(0);
  };

  this.undo = function(){
    this.player.setAction('');
  };
};

commands.Street = function Street(replayer, player, data) {
  this.replayer = replayer;
  this.frame = player;
  this.cards = data.cards;

  this.apply = function(){
	  for (k in action.cards) {
      card = action.cards[k];
      this.frame.append('');
    }
    this.frame.addClass('show');
    this.replayer.savePlayersStates(this.frame);
    replayer.pot.flush();
    this.replayer.pot.pushRaise(0);
  };

  this.undo = function(){
    this.frame.html('');
	  this.frame.removeClass('show');
    this.replayer.reloadPlayersStates(this.frame);
    this.replayer.pot.popRaise();
  };
};

commands.Show = function Show(replayer, player, data) {
  this.replayer = replayer;
  this.players = data.players;
  this.winner = data.winner;

  this.apply = function(){
    for (k in this.players) {
      cards = this.players[k];
      player = this.replayer.createPlayer(cards.player, this.replayer.currency);
      player.showCards(cards.hc);
    }
    this.replayer.pot.pushRaise(0);
  }

  this.undo = function(){
    for (k in this.players) {
      cards = this.players[k];
      player = this.replayer.createPlayer(cards.player, this.replayer.currency);
      player.hideCards(cards.hc);
    }
    this.replayer.pot.popRaise();
  }
};

commands.Winning = function Winning(replayer, player, data) {
  this.replayer = replayer;
  this.players = data.players;
  this.frame = $(replayer.table);

  this.apply = function(){
    this.replayer.savePlayersStates(this.frame);

    for (k in this.players) {
      winning = this.players[k];
      player = this.replayer.createPlayer(winning.player, this.replayer.currency);
      newStack = parseFloat(player.getStack()) + parseFloat(winning.amount);
      player.setStack(newStack);
      player.setBet(winning.amount);
      this.replayer.pot.remove(winning.amount);
    }
    this.replayer.pot.flush();
    this.replayer.pot.total = 0;
  };

  this.undo = function(){
    this.replayer.reloadPlayersStates(this.frame);
  };
};

/*************** PLAYER *************/
function Player(frame, currency) {
  this.frame = frame;
  this.currency = currency;
}

Player.prototype.pushBet = function(amount) {
  dataBets = this.frame.find('.bet').attr('data-bets');

  if ('undefined' == typeof dataBets) {
    bets = [amount];
  } else {
    bets = JSON.parse(dataBets);
    bets.push(amount);
  }

  this.frame.find('.bet').attr('data-bets', JSON.stringify(bets));
}

Player.prototype.popBet = function() {
  dataBets = this.frame.find('.bet').attr('data-bets');

  if ('undefined' == typeof dataBets) {
    bets = [];
  } else {
    bets = JSON.parse(dataBets);
    bets.pop();
  }

  this.frame.find('.bet').attr('data-bets', JSON.stringify(bets));
}

Player.prototype.getLastBet = function() {
  this.popBet();
  dataBets = this.frame.find('.bet').attr('data-bets');

  if ('undefined' == typeof dataBets)
    return 0;

  bets = JSON.parse(dataBets);
  if (bets.length === 0)
    return 0;

  return parseFloat(bets[bets.length-1]);
}

Player.prototype.getBet = function() {
  amount = this.frame.find('.bet').attr('data-amount');
  if ('undefined' == typeof amount)
    return 0;

  return this.frame.find('.bet').attr('data-amount');
}

Player.prototype.setBet = function(amount) {
  if ('string' === typeof amount)
    amount = parseFloat(amount);

  this.frame.find('.bet').attr('data-amount', amount.toFixed(2));

  if (amount > 0) {
    this.frame.find('.bet').html(amount.toFixed(2)+this.currency);
  } else {
    this.frame.find('.bet').html('');
  }
};

Player.prototype.getStack = function() {
  amount = this.frame.find('.stack').attr('data-amount');
  if ('undefined' == typeof amount)
    return 0;

  return this.frame.find('.stack').attr('data-amount');
}

Player.prototype.setStack = function(amount) {
  if ('string' === typeof amount)
    amount = parseFloat(amount);

  stack = this.frame.find('.stack');
  stack.attr('data-amount', amount.toFixed(2));

  if (amount > 0) {
    stack.removeClass('all-in');
    stack.html(amount.toFixed(2)+this.currency);
  } else {
    stack.addClass('all-in');
    stack.html('ALL IN');
  }
};

Player.prototype.setAction = function(action) {
  this.frame.find('.action').html(action);
}

Player.prototype.muck = function() {
  this.frame.find('.cards').addClass('mucked');
}

Player.prototype.unMuck = function() {
  this.frame.find('.cards').removeClass('mucked');
}

Player.prototype.showCards = function(cards) {
  for (k in cards) {
    card = this.frame.find('.cards > .card:eq('+k+')')
    card.removeClass('card-cover').addClass('card-'+cards[k]);
  }
}

Player.prototype.hideCards = function(cards) {
  for (k in cards) {
    card = this.frame.find('.cards > .card:eq('+k+')')
    card.removeClass('card-'+cards[k]).addClass('card-cover');
  }
}

/*************** REPLAYER *************/
function HHReplayer(options) {
  this.table = options.table;
  this.currency = '';
  this.playBtn = options.playBtn;
  this.data = undefined;
  this.pot = {
    pot:options.pot,
    current:0.0,
    total:0.0,
    raises:[],

    add:function(v){
      if ('string' === typeof v)
        v = parseFloat(v);

      this.total += v
      this.total = Math.round(this.total * 100)/100;
    },
    remove:function(v){
      if ('string' === typeof v)
        v = parseFloat(v);

      this.total -= v
      this.total = Math.round(this.total * 100)/100;
    },
    flush:function(){
      this.current = this.total;
    },
    draw:function(){
      $(this.pot).find('.current > span').html(this.current.toFixed(2));
      $(this.pot).find('.total > span').html(this.total.toFixed(2));
    },
    reset:function(){
      this.current = 0.0;
      this.total = 0.0;
    },

    pushRaise:function(v){
      this.raises.push(this.toFloat(v));
    },
    popRaise:function(){
      this.raises.pop();
    },
    getOdds:function(player){
      if (this.raises.length == 0 || this.raises[this.raises.length-1] <= 0)
        return 'N/A';

	  playerMoneyInPot = player.getBet();

      toCall = this.raises[this.raises.length-1] - playerMoneyInPot;

	  if (toCall > player.getStack()) {
        toCall = parseFloat(player.getStack());
      }

      odds = this.total / toCall;
      percentage = 1/(odds+1)*100;
      return odds.toFixed(2) + ':1 ('+percentage.toFixed(1)+'%)';
    },

    toFloat:function(v){
      if ('string' === typeof v)
        return parseFloat(v);

      return v;
    }
  };
};

HHReplayer.prototype.createPlayer = function(frameClass) {
  if ('flop' === frameClass || 'turn' === frameClass || 'river' === frameClass)
    return $(this.table).find('.'+frameClass);

  return new Player($(this.table).find('.'+frameClass), this.currency);
};

HHReplayer.prototype.createCommand = function(data) {
  player = this.createPlayer(data.player);
  return new commands[data.type.capitalize()](this, player, data);
};

HHReplayer.prototype.savePlayersStates = function(frame) {
  states = {
    players: [],
    pot: {}
  };
  // save the state of the players
  $(this.table).find('.player').each(function(){
    playerState = {
      frame: $(this).find('.name').html(),
      bet: $(this).find('.bet').html(),
      betData: $(this).find('.bet').attr('data-amount'),
      stack: $(this).find('.stack').attr('data-amount')
    };
    states.players.push(playerState);
  });

  // save the state of the pot
  states.pot.current = this.pot.current;
  states.pot.total = this.pot.total;

  frame.attr('data-state', JSON.stringify(states));
  $(this.table).find('.player > .bet').attr('data-amount', 0).html('');
};

HHReplayer.prototype.reloadPlayersStates = function(frame) {
  states = JSON.parse(frame.attr('data-state'));
  for (k in states.players) {
    state = states.players[k];
    playerFrame = $(this.table).find('.'+state.frame);
    playerFrame.find('.bet').html(state.bet).attr('data-amount', state.betData);
    player = new Player(playerFrame, this.currency);
    player.setStack(state.stack);
  }

  // reload pot
  this.pot.current = states.pot.current;
  this.pot.total = states.pot.total;
};

HHReplayer.prototype.draw = function() {
  this.drawOdds();
  this.pot.draw();
};

HHReplayer.prototype.drawOdds = function() {
  step = parseInt($(this.table).attr('data-step'));
  step++;

  if (step >= this.data.actions.length)
    return $('#pot-odds').html('N/A');

  action = this.data.actions[step];
  player = this.createPlayer(action.player);
  //console.log(player);
  if (!(player instanceof Player) || action.type == 'show')
    return $('#pot-odds').html('N/A');

  $('#pot-odds').html(this.pot.getOdds(player));
};

HHReplayer.prototype.initQuickAccessBtns = function() {
  streetBtns = $('#action-bar .streets');
  streetBtns.find('a:not(:first)').addClass('disabled');

  for (step in this.data.actions) {
    action = this.data.actions[step];
    if ('street' === action.type) {
      switch (action.player) {
        case 'flop':
          streetBtns.find('.btn-flop')
            .removeClass('disabled')
            .attr('data-goto-step', step);
          break;
        case 'turn':
          streetBtns.find('.btn-turn')
            .removeClass('disabled')
            .attr('data-goto-step', step);
          break;
        case 'river':
          streetBtns.find('.btn-river')
            .removeClass('disabled')
            .attr('data-goto-step', step);
          break;
      }
    }
  }

  var _this = this;
  streetBtns.on('click', 'a:not(.disabled, .inactive)', function(e){
	e.preventDefault();
    $(this).parents('.streets').find('a').addClass('inactive');
    _this.gotoStep($(this).attr('data-goto-step'));
    $(this).parents('.streets').find('a').removeClass('inactive');
  });
}

HHReplayer.prototype.init = function(data) {
    this.data = data;
	this.currency = data.currency;
    $(this.table).addClass('max'+data.format);
    //reset table
    $(this.table).attr('data-step', '-1');
    $(this.table).find('.player').remove();
    $(this.table).find('.flop').html('');
    $(this.table).find('.turn').html('');
    $(this.table).find('.river').html('');
    this.pot.reset();

    for (i in data.stacks) {
      stack = data.stacks[i];
      player = $('.template').clone();
      player.find('.name').html(stack.name);
      player.find('.stack').html(stack.stack+this.currency).attr('data-amount', stack.stack);
      player.removeClass('template').addClass(stack.name);
      if (stack.pos != stack.name)
        player.addClass(stack.pos);

      // show cards
      if (stack.pos == data.hero) {
        for (k in stack.hc) {
          player.find('.cards > .card:eq('+k+')').addClass('card-'+stack.hc[k]);
        }
      } else {
        player.find('.cards > .card').addClass('card-cover');
      }
      player.appendTo(this.table);

      if (stack.pos === 'sb' || stack.pos === 'bb') {
        action = {type:'raise', player:stack.name, amount:data.blinds[stack.pos]};
        command = this.createCommand(action);
        command.apply();
      }
    }
    // remove raises from blinds
    $(this.table).find('.player > .action').html('');

    for (playerName in data.antes) {
      ante = data.antes[playerName];
      player = this.createPlayer(playerName);
      player.setStack(player.getStack() - ante);
      this.pot.add(ante);
    }

    for (i in data.bigBlinds) {
      playerName = data.bigBlinds[i];
      action = {type:'raise', player:playerName, amount:data.blinds['bb']};
      command = this.createCommand(action);
      command.apply();
    }

	this.initQuickAccessBtns();

    this.draw();
};

HHReplayer.prototype.next = function() {
  step = parseInt($(this.table).attr('data-step'));
  step++;
  if (step >= this.data.actions.length) return false;

  $(this.table).attr('data-step', step);
  $(this.table).find('.player > .action').html('');

  action = this.data.actions[step];
  command = this.createCommand(action);
  command.apply();

  this.draw();
  return true;
};

HHReplayer.prototype.prev = function() {
  step = parseInt($(this.table).attr('data-step'));
  if (step < 0) return false;

  action = this.data.actions[step];
  command = this.createCommand(action);
  command.undo();

  if (step > 0) {
    action = this.data.actions[step-1];
    if ('street' !== action.type) {
      command = this.createCommand(action);
      command.undo();
      command.apply();
    }
  }

  step--;
  $(this.table).attr('data-step', step);

  this.draw();
  return true;
};

HHReplayer.prototype.play = function() {
  if ('true' === $(this.playBtn).attr('data-active')) {
    result = this.next();

    if (!result) {
      $(this.playBtn).click();
      return;
    }

    var _this = this;
    setTimeout(function() { _this.play(); }, 1200);
  }
};

HHReplayer.prototype.gotoStep = function(targetStep) {
  step = parseInt($(this.table).attr('data-step'));
  if (step == targetStep) return;

  if (step < targetStep) {
    for (i=step; i<targetStep; i++) {
      this.next();
    }
  } else {
    for (i=step; i>targetStep; i--) {
      this.prev();
    }
  }
};


text:
title: With node-sass
layout: documentation
doc-tab: customize
doc-subtab: node-sass
breadcrumb:
- home
- documentation
- customize
- customize-node-sass
---

{% capture dependencies %}
npm install node-sass --save-dev
npm install bulma --save-dev
{% endcapture %}

{% capture package %}
{
  "name": "mybulma",
  "version": "1.0.0",
  "main": "sass/mystyles.scss",
  "license": "MIT",
  "devDependencies": {
    "bulma": "^0.7.2",
    "node-sass": "^4.9.2"
  }
}
{% endcapture %}

{% capture step_2 %}

      You only need 2 packages to customize Bulma: node-sass and bulma itself.

  {% highlight bash %}{{ dependencies }}{% endhighlight %}

      Your package.json should look like this at this point.

  {% highlight bash %}{{ package }}{% endhighlight %}
{% endcapture %}

{% capture scripts %}
"scripts": {
  "css-build": "node-sass --omit-source-map-url sass/mystyles.scss css/mystyles.css",
  "css-watch": "npm run css-build -- --watch",
  "start": "npm run css-watch"
}
{% endcapture %}

{% capture npm_build %}
npm run css-build
{% endcapture %}

{% capture npm_build_success %}
Rendering Complete, saving .css file...
Wrote CSS to /path/to/mybulma/css/mystyles.css
{% endcapture %}

{% capture npm_watch %}
npm start
{% endcapture %}

{% capture step_5 %}

      To build a CSS file from a Sass file, we can use node scripts. In package.json, add the following:

  {% highlight html %}{{ scripts }}{% endhighlight %}

        css-build takes sass/mystyles.scss as an input, and outputs css/mystyles.css, while omitting the source map

        css-watch builds the CSS and watches for changes

        start is simply a shortcut for css-watch

      To test it out, go in your terminal and run the following command:

  {% highlight bash %}{{ npm_build }}{% endhighlight %}

      If set up correctly, you will see the following message:

  {% highlight bash %}{{ npm_build_success }}{% endhighlight %}

      Reload the page and it should be styled like this:

  {%
    include components/figure.html
    path="customize/custom-bulma-02-default"
    extension="png"
    alt="Bulma default styles"
    width="600"
    height="300"
    caption="Bulma's default styles"
  %}

      To watch for changes, just launch the following command:

  {% highlight bash %}{{ npm_watch }}{% endhighlight %}
{% endcapture %}

{% include steps/create-package.html
  number="1"
  entry="sass/mystyles.scss"
%}

{% include components/step.html
  title="2. Install the dev dependencies"
  content=step_2
%}

{% include steps/create-sass-file.html
  number="3"
  path="../node_modules/bulma/bulma.sass"
%}

{% include steps/create-html-page.html
  number="4"
%}

{% include components/step.html
  title="5. Add node scripts to build your CSS"
  content=step_5
%}

{% include steps/add-custom-styles.html
  number="6"
%}

redpajama_set_name: RedPajamaGithub


text:
import ShareYourSystem as SYS
#</Import Modules>

#<DefineClass>
class GlobalDynamicClass(object):

	#<DefineHookMethods>
	def initAfter(self):

		#<DefineSpecificDict>
		self.PitchInt=0
		self.ConnectivityMatrix=SYS.MatrixClass();
		self.MembraneTimeConstantFloat=0.
		self.PulsationFloat=0.
		self.SynapticDelayFloat=0.
		self.PerturbativeCoefficientFloat=0.
		#</DefineSpecificDict>

	#</DefineHookMethods>

	#<DefineBindingHookMethods>
	#</DefineBindingHookMethods>

	#<DefineMethods>
	#</DefineMethods>
#</DefineClass>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: Dtf::Command::DeleteVs

    — Documentation by YARD 0.8.2.1

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (D) »
    Dtf » Command
     »
    DeleteVs

(no frames)

      Class List

      Method List

      File List

Class: Dtf::Command::DeleteVs

Inherits:

      Object

Object

Dtf::Command::DeleteVs

        show all

Defined in:

lib/dtf.rb

Overview

This sub-command removes a Verification Suite from the Testing Framework
system

Required Parameters are:

--user-name [String], --id [Integer]

The '--user-name' parameter is the user_name of the User that owns the
Verification Suite you wish to delete The '--id' parameter is the ID # of
the Verification Suite you wish to delete, as provided by @vs.id

      Instance Method Summary
      (collapse)

      - (Object) execute

      - (DeleteVs) initialize(cmd_name, options)

    constructor

A new instance of DeleteVs.

Constructor Details

    - (<tt>DeleteVs</tt>) initialize(cmd_name, options)

A new instance of DeleteVs

179
180
181
182

# File 'lib/dtf.rb', line 179

def initialize(cmd_name, options)
  @cmd_name = cmd_name
  @cmd_opts = options
end

Instance Method Details

    - (<tt>Object</tt>) execute

184
185
186
187
188
189
190
191
192
193

# File 'lib/dtf.rb', line 184

def execute
  if [:user_name_given, :id_given].all? { |sym| @cmd_opts.key?(sym) } then
    puts "Deleting #{@cmd_opts[:user_name]}\'s VS with ID \'#{@cmd_opts[:id]}\'"
    user = User.find_by_user_name(@cmd_opts[:user_name])
    vs   = user.verification_suites.find(@cmd_opts[:id])
    VerificationSuite.delete(vs)
  else
    Dtf::ErrorSystem.raise_error(@cmd_name)
  end
end

  Generated on Wed Oct 10 14:11:34 2012 by
  yard
  0.8.2.1 (ruby-1.9.3).


text:
using namespace vespamalloc;

//typedef StackEntry<StackFrameReturnEntry> StackElem;
typedef CallGraph<int, 0x1000, Index> CallGraphIntT;
typedef CallGraph<StackElem, 0x1000, Index> CallGraphStackEntryT;

namespace vespalibtest {

template <typename T>
class DumpGraph
{
public:
    DumpGraph(const char * s="") : _string(s) { }
    void handle(const T & node)
    {
        asciistream os;
        os << ' ' << node;
        _string += os.c_str();
        if (node.callers() == nullptr) {
            printf("%s\n", _string.c_str());
        }
    }
    const std::string & str() const { return _string; }
private:
    std::string _string;
};

}
void testint() {
    CallGraphIntT callGraph;
    vespalibtest::DumpGraph<CallGraphIntT::Node> dump("int: ");
    int s1[3] = { 1, 2, 3 };
    int s2[3] = { 1, 2, 4 };
    int s3[1] = { 1 };
    int s4[3] = { 1, 3, 4 };
    callGraph.addStack(s1, 3);
    callGraph.addStack(s2, 3);
    callGraph.addStack(s3, 1);
    callGraph.addStack(s4, 3);
    callGraph.traverseDepth(dump);
    printf("%s\n", dump.str().c_str());
}

void teststackentry() {
    CallGraphStackEntryT callGraph;
    vespalibtest::DumpGraph<CallGraphStackEntryT::Node> dump("callstack: ");
    StackElem s1[3] = { StackElem((void *)1), StackElem((void *)2), StackElem((void *)3) };
    StackElem s2[3] = { StackElem((void *)1), StackElem((void *)2), StackElem((void *)4) };
    StackElem s3[1] = { StackElem((void *)1) };
    StackElem s4[3] = { StackElem((void *)1), StackElem((void *)3), StackElem((void *)4) };
    callGraph.addStack(s1, 3);
    callGraph.addStack(s2, 3);
    callGraph.addStack(s3, 1);
    callGraph.addStack(s4, 3);
    callGraph.traverseDepth(dump);
    printf("%s\n", dump.str().c_str());
}

void testaggregator() {
    CallGraphStackEntryT callGraph;
    StackElem s1[3] = { StackElem((void *)1), StackElem((void *)2), StackElem((void *)3) };
    StackElem s2[3] = { StackElem((void *)1), StackElem((void *)2), StackElem((void *)4) };
    StackElem s3[1] = { StackElem((void *)1) };
    StackElem s4[3] = { StackElem((void *)1), StackElem((void *)3), StackElem((void *)4) };
    callGraph.addStack(s1, 3);
    callGraph.addStack(s2, 3);
    callGraph.addStack(s3, 1);
    callGraph.addStack(s4, 3);
    Aggregator agg;
    DumpGraph<CallGraphT::Node> dump(&agg, "{ ", " }");
    callGraph.traverseDepth(dump);
    asciistream ost;
    ost << agg;
    printf("%s\n", ost.c_str());
}
int main (int argc, char *argv[])
{
    (void) argc;
    (void) argv;
    testint();
    teststackentry();
    testaggregator();
    return 0;
}


text:
#region Using Directives

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

#endregion

#region General Assembly Information

[assembly: AssemblyTitle("XAML Reporting")]
[assembly: AssemblyDescription("The XAML Reporting engine is a tool, which offers reporting tools based on XAML and has the functionality to export to XPS, XLS(X), CSV and PDF.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XAML Reporting")]
[assembly: AssemblyCopyright("Copyright © David Neumann & Lukas Rögner 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("e4b8a5c6-f483-490c-af3d-3345083ab7dc")]
[assembly: NeutralResourcesLanguage("en", UltimateResourceFallbackLocation.MainAssembly)]

#endregion

#region Assembly Version

[assembly: AssemblyVersion("0.3.0.*")]
[assembly: AssemblyFileVersion("0.3.0.0")]

#endregion


text:
using namespace BinaryNinja;
using namespace Json;
using namespace std;

struct DatabaseProgressCallbackContext
{
	std::function<void(size_t, size_t)> func;
};

static void DatabaseProgressCallback(void* ctxt, size_t progress, size_t total)
{
	DatabaseProgressCallbackContext* cb = (DatabaseProgressCallbackContext*)ctxt;
	cb->func(progress, total);
}

char* NavigationHandler::GetCurrentViewCallback(void* ctxt)
{
	NavigationHandler* handler = (NavigationHandler*)ctxt;
	string result = handler->GetCurrentView();
	return BNAllocString(result.c_str());
}

uint64_t NavigationHandler::GetCurrentOffsetCallback(void* ctxt)
{
	NavigationHandler* handler = (NavigationHandler*)ctxt;
	return handler->GetCurrentOffset();
}

bool NavigationHandler::NavigateCallback(void* ctxt, const char* view, uint64_t offset)
{
	NavigationHandler* handler = (NavigationHandler*)ctxt;
	return handler->Navigate(view, offset);
}

NavigationHandler::NavigationHandler()
{
	m_callbacks.context = this;
	m_callbacks.getCurrentView = GetCurrentViewCallback;
	m_callbacks.getCurrentOffset = GetCurrentOffsetCallback;
	m_callbacks.navigate = NavigateCallback;
}

FileMetadata::FileMetadata()
{
	m_object = BNCreateFileMetadata();
}

FileMetadata::FileMetadata(const string& filename)
{
	m_object = BNCreateFileMetadata();
	BNSetFilename(m_object, filename.c_str());
}

FileMetadata::FileMetadata(BNFileMetadata* file)
{
	m_object = file;
}

void FileMetadata::Close()
{
	BNCloseFile(m_object);
}

void FileMetadata::SetNavigationHandler(NavigationHandler* handler)
{
	if (handler)
		BNSetFileMetadataNavigationHandler(m_object, handler->GetCallbacks());
	else
		BNSetFileMetadataNavigationHandler(m_object, nullptr);
}

string FileMetadata::GetOriginalFilename() const
{
	char* str = BNGetOriginalFilename(m_object);
	string result = str;
	BNFreeString(str);
	return result;
}

void FileMetadata::SetOriginalFilename(const string& name)
{
	BNSetOriginalFilename(m_object, name.c_str());
}

string FileMetadata::GetFilename() const
{
	char* str = BNGetFilename(m_object);
	string result = str;
	BNFreeString(str);
	return result;
}

void FileMetadata::SetFilename(const string& name)
{
	BNSetFilename(m_object, name.c_str());
}

bool FileMetadata::IsModified() const
{
	return BNIsFileModified(m_object);
}

bool FileMetadata::IsAnalysisChanged() const
{
	return BNIsAnalysisChanged(m_object);
}

void FileMetadata::MarkFileModified()
{
	BNMarkFileModified(m_object);
}

void FileMetadata::MarkFileSaved()
{
	BNMarkFileSaved(m_object);
}

bool FileMetadata::IsBackedByDatabase(const string& binaryViewType) const
{
	return BNIsBackedByDatabase(m_object, binaryViewType.c_str());
}

bool FileMetadata::CreateDatabase(const string& name, BinaryView* data, Ref<SaveSettings> settings)
{
	return BNCreateDatabase(data->GetObject(), name.c_str(), settings ? settings->GetObject() : nullptr);
}

bool FileMetadata::CreateDatabase(const string& name, BinaryView* data,
	const function<void(size_t progress, size_t total)>& progressCallback, Ref<SaveSettings> settings)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progressCallback;
	return BNCreateDatabaseWithProgress(data->GetObject(), name.c_str(), &cb, DatabaseProgressCallback, settings ? settings->GetObject() : nullptr);
}

Ref<BinaryView> FileMetadata::OpenExistingDatabase(const string& path)
{
	BNBinaryView* data = BNOpenExistingDatabase(m_object, path.c_str());
	if (!data)
		return nullptr;
	return new BinaryView(data);
}

Ref<BinaryView> FileMetadata::OpenExistingDatabase(const string& path,
	const function<void(size_t progress, size_t total)>& progressCallback)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progressCallback;
	BNBinaryView* data = BNOpenExistingDatabaseWithProgress(m_object, path.c_str(), &cb, DatabaseProgressCallback);
	if (!data)
		return nullptr;
	return new BinaryView(data);
}

Ref<BinaryView> FileMetadata::OpenDatabaseForConfiguration(const string& path)
{
	BNBinaryView* data = BNOpenDatabaseForConfiguration(m_object, path.c_str());
	if (!data)
		return nullptr;
	return new BinaryView(data);
}

bool FileMetadata::SaveAutoSnapshot(BinaryView* data, Ref<SaveSettings> settings)
{
	return BNSaveAutoSnapshot(data->GetObject(), settings ? settings->GetObject() : nullptr);
}

bool FileMetadata::SaveAutoSnapshot(BinaryView* data,
	const function<void(size_t progress, size_t total)>& progressCallback, Ref<SaveSettings> settings)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progressCallback;
	return BNSaveAutoSnapshotWithProgress(data->GetObject(), &cb, DatabaseProgressCallback, settings ? settings->GetObject() : nullptr);
}

void FileMetadata::GetSnapshotData(Ref<KeyValueStore> data, Ref<KeyValueStore> cache,
	const std::function<void(size_t, size_t)>& progress)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progress;
	BNGetSnapshotData(GetObject(), data->GetObject(), cache->GetObject(), &cb, DatabaseProgressCallback);
}

void FileMetadata::ApplySnapshotData(BinaryView* file, Ref<KeyValueStore> data, Ref<KeyValueStore> cache,
	const std::function<void(size_t, size_t)>& progress, bool openForConfiguration, bool restoreRawView)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progress;
	BNApplySnapshotData(GetObject(), file->GetObject(), data->GetObject(), cache->GetObject(), &cb, DatabaseProgressCallback, openForConfiguration, restoreRawView);
}

Ref<Database> FileMetadata::GetDatabase()
{
	BNDatabase* db = BNGetFileMetadataDatabase(m_object);
	if (db == nullptr)
		return nullptr;
	return new Database(db);
}

bool FileMetadata::Rebase(BinaryView* data, uint64_t address)
{
	return BNRebase(data->GetObject(), address);
}

bool FileMetadata::Rebase(BinaryView* data, uint64_t address, const function<void(size_t progress, size_t total)>& progressCallback)
{
	DatabaseProgressCallbackContext cb;
	cb.func = progressCallback;
	return BNRebaseWithProgress(data->GetObject(), address, &cb, DatabaseProgressCallback);
}

MergeResult FileMetadata::MergeUserAnalysis(const std::string& name, const std::function<void(size_t, size_t)>& progress, std::vector<string> excludedHashes)
{
	size_t numHashes = excludedHashes.size();
	char** tempList = new char*[numHashes];
	for (size_t i = 0; i < numHashes; i++)
	{
		tempList[i] = BNAllocString(excludedHashes[i].c_str());
	}

	DatabaseProgressCallbackContext cb;
	cb.func = progress;

	BNMergeResult bnResult = BNMergeUserAnalysis(m_object, name.c_str(), &cb, DatabaseProgressCallback, tempList, numHashes);
	//BNFreeStringList(hashList, numHashes);
	MergeResult result(bnResult);
	return result;
}

void FileMetadata::BeginUndoActions()
{
	BNBeginUndoActions(m_object);
}

void FileMetadata::CommitUndoActions()
{
	BNCommitUndoActions(m_object);
}

bool FileMetadata::Undo()
{
	return BNUndo(m_object);
}

bool FileMetadata::Redo()
{
	return BNRedo(m_object);
}

vector<Ref<User>> FileMetadata::GetUsers()
{
	size_t count;
	BNUser** users = BNGetUsers(m_object, &count);

	vector<Ref<User>> result;
	result.reserve(count);
	for (size_t i = 0; i < count; i++)
		result.push_back(new User(BNNewUserReference(users[i])));

	BNFreeUserList(users, count);
	return result;
}

vector<UndoEntry> FileMetadata::GetUndoEntries()
{
	size_t numEntries;
	BNUndoEntry* entries = BNGetUndoEntries(m_object, &numEntries);

	vector<UndoEntry> result;
	result.reserve(numEntries);
	for (size_t i = 0; i < numEntries; i++)
	{
		UndoEntry temp;
		temp.timestamp = entries[i].timestamp;
		temp.hash = entries[i].hash;
		temp.user = new User(BNNewUserReference(entries[i].user));
		size_t actionCount = entries[i].actionCount;
		for (size_t actionIndex = 0; actionIndex < actionCount; actionIndex++)
		{
			temp.actions.emplace_back(entries[i].actions[actionIndex]);
		}
		result.push_back(temp);
	}

	//BNFreeUndoEntries(entries, count);
	return result;
}

void FileMetadata::ClearUndoEntries()
{
	BNClearUndoEntries(m_object);
}

bool FileMetadata::OpenProject()
{
	return BNOpenProject(m_object);
}

void FileMetadata::CloseProject()
{
	BNCloseProject(m_object);
}

bool FileMetadata::IsProjectOpen()
{
	return BNIsProjectOpen(m_object);
}

string FileMetadata::GetCurrentView()
{
	char* view = BNGetCurrentView(m_object);
	string result = view;
	BNFreeString(view);
	return result;
}

uint64_t FileMetadata::GetCurrentOffset()
{
	return BNGetCurrentOffset(m_object);
}

bool FileMetadata::Navigate(const string& view, uint64_t offset)
{
	return BNNavigate(m_object, view.c_str(), offset);
}

Ref<BinaryView> FileMetadata::GetViewOfType(const string& name)
{
	BNBinaryView* view = BNGetFileViewOfType(m_object, name.c_str());
	if (!view)
		return nullptr;
	return new BinaryView(view);
}

std::vector<std::string> FileMetadata::GetExistingViews() const
{
	size_t count;
	char** views = BNGetExistingViews(m_object, &count);
	vector<string> result;
	result.reserve(count);

	for (size_t i = 0; i < count; i++)
		result.push_back(string(views[i]));

	BNFreeStringList(views, count);
	return result;
}

bool FileMetadata::IsSnapshotDataAppliedWithoutError() const
{
	return BNIsSnapshotDataAppliedWithoutError(m_object);
}

SaveSettings::SaveSettings()
{
	m_object = BNCreateSaveSettings();
}

SaveSettings::SaveSettings(BNSaveSettings* settings)
{
	m_object = settings;
}

bool SaveSettings::IsOptionSet(BNSaveOption option) const
{
	return BNIsSaveSettingsOptionSet(m_object, option);
}

void SaveSettings::SetOption(BNSaveOption option, bool state)
{
	BNSetSaveSettingsOption(m_object, option, state);
}


text:
using Domain.Exceptions;
using Infrastructure.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Infrastructure.Domain
{
    public class FakeEventStore : IEventStore
    {
        private readonly IEventPublisher _publisher;

        public FakeEventStore(IEventPublisher publisher)
        {
            _publisher = publisher;
        }

        private readonly Dictionary<Guid, List<Event>> _current = new Dictionary<Guid, List<Event>>();

        public void SaveEvents<T>(Guid aggregateId, IEnumerable<Event> events, int expectedVersion)
            where T : AggregateRoot
        {
            List<Event> aggregateEvents;

            // try to get event descriptors list for given aggregate id
            // otherwise -> create empty dictionary
            if (!_current.TryGetValue(aggregateId, out aggregateEvents))
            {
                aggregateEvents = new List<Event>();
                _current.Add(aggregateId, aggregateEvents);
            }
            // check whether latest event version matches current aggregate version
            // otherwise -> throw exception
            else if (aggregateEvents[aggregateEvents.Count - 1].Version != expectedVersion && expectedVersion != -1)
            {
                throw new ConcurrencyException();
            }

            foreach (var @event in events)
            {
                // push event to the event list for current aggregate
                aggregateEvents.Add(@event);

                // publish current event to the bus for further processing by subscribers
                _publisher.Publish(@event);
            }
        }

        // collect all processed events for given aggregate and return them as a list
        // used to build up an aggregate from its history (Domain.LoadsFromHistory)
        public List<Event> GetEventsForAggregate<T>(Guid aggregateId) where T : AggregateRoot
        {
            List<Event> aggregateEvents;

            if (!_current.TryGetValue(aggregateId, out aggregateEvents))
            {
                throw new AggregateNotFoundException();
            }

            return aggregateEvents.ToList();
        }

        public List<T> GetEventsForType<T>(int startIndex, int maxCount) where T : Event =>
            _current.Values.OfType<T>()
                .Skip(startIndex).Take(maxCount)
                .ToList();
    }
}


text:
package fr.openwide.core.wicket.more.markup.html.action;

import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;

import fr.openwide.core.wicket.more.condition.Condition;

public abstract class AbstractOneParameterAjaxAction<T> implements IOneParameterAjaxAction<T> {

	private static final long serialVersionUID = 3044339655373492663L;

	@Override
	public void updateAjaxAttributes(AjaxRequestAttributes attributes, T model) {
		// nothing to do
	}

	@Override
	public void detach() {
		// nothing to do
	}

	@Override
	public Condition getActionAvailableCondition(T parameter) {
		return Condition.alwaysTrue();
	}

}


text:
package com.paypal.svcs.types.ap;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.paypal.core.NVPUtil;
import com.paypal.svcs.types.ap.InvoiceData;
import com.paypal.svcs.types.ap.ReceiverIdentifier;

/**
 * Options that apply to the receiver of a payment, allows
 * setting additional details for payment using invoice.
 */
public class ReceiverOptions{

	/**
	 *
	 */
	private String description;

	/**
	 *
	 */
	private String customId;

	/**
	 *
	 */
	private InvoiceData invoiceData;

	/**
	 *
	 *@Required
	 */
	private ReceiverIdentifier receiver;

	/**
	 *
	 */
	private String referrerCode;

	/**
	 * Constructor with arguments
	 */
	public ReceiverOptions (ReceiverIdentifier receiver){
		this.receiver = receiver;
	}

	/**
	 * Default Constructor
	 */
	public ReceiverOptions (){
	}

	/**
	 * Getter for description
	 */
	 public String getDescription() {
	 	return description;
	 }

	/**
	 * Setter for description
	 */
	 public void setDescription(String description) {
	 	this.description = description;
	 }

	/**
	 * Getter for customId
	 */
	 public String getCustomId() {
	 	return customId;
	 }

	/**
	 * Setter for customId
	 */
	 public void setCustomId(String customId) {
	 	this.customId = customId;
	 }

	/**
	 * Getter for invoiceData
	 */
	 public InvoiceData getInvoiceData() {
	 	return invoiceData;
	 }

	/**
	 * Setter for invoiceData
	 */
	 public void setInvoiceData(InvoiceData invoiceData) {
	 	this.invoiceData = invoiceData;
	 }

	/**
	 * Getter for receiver
	 */
	 public ReceiverIdentifier getReceiver() {
	 	return receiver;
	 }

	/**
	 * Setter for receiver
	 */
	 public void setReceiver(ReceiverIdentifier receiver) {
	 	this.receiver = receiver;
	 }

	/**
	 * Getter for referrerCode
	 */
	 public String getReferrerCode() {
	 	return referrerCode;
	 }

	/**
	 * Setter for referrerCode
	 */
	 public void setReferrerCode(String referrerCode) {
	 	this.referrerCode = referrerCode;
	 }

	public String toNVPString() throws UnsupportedEncodingException {
		return toNVPString("");
	}

	public String toNVPString(String prefix) throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder();
		if (this.description != null) {
			sb.append(prefix).append("description=").append(NVPUtil.encodeUrl(this.description));
			sb.append("&");
		}
		if (this.customId != null) {
			sb.append(prefix).append("customId=").append(NVPUtil.encodeUrl(this.customId));
			sb.append("&");
		}
		if (this.invoiceData != null) {
			String newPrefix = prefix + "invoiceData.";
			sb.append(this.invoiceData.toNVPString(newPrefix));
		}
		if (this.receiver != null) {
			String newPrefix = prefix + "receiver.";
			sb.append(this.receiver.toNVPString(newPrefix));
		}
		if (this.referrerCode != null) {
			sb.append(prefix).append("referrerCode=").append(NVPUtil.encodeUrl(this.referrerCode));
			sb.append("&");
		}
		return sb.toString();
	}

	public static com.paypal.svcs.types.ap.ReceiverOptions createInstance(Map<String, String> map, String prefix, int index) {
		com.paypal.svcs.types.ap.ReceiverOptions receiverOptions = null;
		int i = 0;
		if (index != -1) {
				if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) {
					prefix = prefix + "(" + index + ").";
				}
		} else {
			if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) {
				prefix = prefix + ".";
			}
		}

		if (map.containsKey(prefix + "description")) {
				receiverOptions = (receiverOptions == null) ? new com.paypal.svcs.types.ap.ReceiverOptions() : receiverOptions;
				receiverOptions.setDescription(map.get(prefix + "description"));
		}
		if (map.containsKey(prefix + "customId")) {
				receiverOptions = (receiverOptions == null) ? new com.paypal.svcs.types.ap.ReceiverOptions() : receiverOptions;
				receiverOptions.setCustomId(map.get(prefix + "customId"));
		}
		InvoiceData invoiceData =  InvoiceData.createInstance(map, prefix + "invoiceData", -1);
		if (invoiceData != null) {
			receiverOptions = (receiverOptions == null) ? new com.paypal.svcs.types.ap.ReceiverOptions() : receiverOptions;
			receiverOptions.setInvoiceData(invoiceData);
		}
		ReceiverIdentifier receiver =  ReceiverIdentifier.createInstance(map, prefix + "receiver", -1);
		if (receiver != null) {
			receiverOptions = (receiverOptions == null) ? new com.paypal.svcs.types.ap.ReceiverOptions() : receiverOptions;
			receiverOptions.setReceiver(receiver);
		}
		if (map.containsKey(prefix + "referrerCode")) {
				receiverOptions = (receiverOptions == null) ? new com.paypal.svcs.types.ap.ReceiverOptions() : receiverOptions;
				receiverOptions.setReferrerCode(map.get(prefix + "referrerCode"));
		}
		return receiverOptions;
	}

}


text:
@implementation SDL2_ttf

@end


text:
#include "packer.h"
#include "cr_opcodes.h"
#include "cr_mem.h"
#include "cr_glstate.h"

void PACK_APIENTRY crPackPolygonStipple( const GLubyte *mask )
{
    CR_GET_PACKER_CONTEXT(pc);
    unsigned char *data_ptr;
    int nodata = crStateIsBufferBound(GL_PIXEL_UNPACK_BUFFER_ARB);
    int packet_length = sizeof(int);

    if (nodata)
        packet_length += sizeof(GLint);
    else
        packet_length += 32*32/8;

    CR_GET_BUFFERED_POINTER(pc, packet_length );
    WRITE_DATA_AI(int, nodata);
    if (nodata)
    {
        WRITE_DATA_AI(GLint, (GLint)(uintptr_t)mask);
    }
    else
    {
       crMemcpy( data_ptr, mask, 32*32/8 );
    }
    WRITE_OPCODE( pc, CR_POLYGONSTIPPLE_OPCODE );
    CR_UNLOCK_PACKER_CONTEXT(pc);
}


text:
<?php
namespace Armd\DCXBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class SearchType extends AbstractType
{

    public function buildForm( FormBuilderInterface $builder, array $options ) {
        $builder->add( 'Search','search')
        ;
    }

    function getName() {
        return 'SearchType';
    }
}


text:
var liveServer = require("live-server");

var params = {
    port: 4200, // Set the server port. Defaults to 8080.
    host: "localhost", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
    root: "./dist", // Set root directory that's being server. Defaults to cwd.
    open: true, // When false, it won't load your browser by default.
    ignore: 'scss,my/templates', // comma-separated string for paths to ignore
    file: "index.html", // When set, serve this file for every 404 (useful for single-page applications)
    wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
    mount: [['/components', './node_modules']], // Mount a directory to a route.
    logLevel: 2 // 0 = errors only, 1 = some, 2 = lots
};
liveServer.start(params);


text:
title: How to use a Custom Expectation
---
import Prerequisites from '../creating_custom_expectations/components/prerequisites.jsx'
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import TechnicalTag from '@site/docs/term_tags/_tag.mdx';

Custom <TechnicalTag tag="expectation" text="Expectations"/> are extensions to the core functionality of Great Expectations. Many Custom Expectations may be fit for a very specific purpose,
or be at lower levels of stability and feature maturity than the core library.

As such, they are not available for use from the core library, and require registration and import to become available.

This guide will walk you through the process of utilizing Custom Expectations, whether they were built by you or came from the Great Expectations Experimental Library.

<Prerequisites>

- Created a <TechnicalTag tag="custom_expectation" text="Custom Expectation"/> ***or*** identified a Custom Expectation for use from the [Great Expectations Experimental Library](https://github.com/great-expectations/great_expectations/tree/develop/contrib/experimental/great_expectations_experimental/expectations)

</Prerequisites>

## Steps

<Tabs
  groupId="expectation-type"
  defaultValue='custom-expectations'
  values={[
  {label: 'Custom Expectations You\'ve Built', value:'custom-expectations'},
  {label: 'Custom Expectations Contributed To Great Expectations', value:'contrib-expectations'},
  ]}>

<TabItem value="custom-expectations">

### 1. File placement & import

If you're using a Custom Expectation you've built,
you'll need to place it in the `great_expectations/plugins/expectations` folder of your Great Expectations deployment.

When you instantiate your <TechnicalTag tag="data_context" text="Data Context"/>, it will automatically make all plugins in the directory available for use,
allowing you to import your Custom Expectation from that directory whenever and wherever it will be used.
This import will be needed when an <TechnicalTag tag="expectation_suite" text="Expectation Suite"/> is created, *and* when a <TechnicalTag tag="checkpoint" text="Checkpoint"/> is defined and run.

### 2. Use in a Suite

To use your Custom Expectation, we need to import it.

To do this, we first need to instantiate our Data Context.

For example, a pattern for importing a Custom Expectation `ExpectColumnValuesToBeAlphabetical` could look like:

```python
context = ge.get_context()
from expectations.expect_column_values_to_be_alphabetical import ExpectColumnValuesToBeAlphabetical
```

Now that your Custom Expectation has been imported, it is available with the same patterns as the core Expectations:

```python
validator.expect_column_values_to_be_alphabetical(column="test")
```

### 3. Use in a Checkpoint

Once you have your Custom Expectation in a Suite, you will also need to make it available to your Checkpoint.

To do this, we'll need to put together our own Checkpoint script. From your command line, you can execute:

```commandline
great_expectations checkpoint new <my_checkpoint_name>
```

This will open a Jupyter Notebook allowing you to create a Checkpoint.
If you would like to run your Checkpoint from this notebook, you will need to import your Custom Expectation again as above.

To continue to use this Checkpoint containing a Custom Expectation outside this notebook, we will need to set up a script for your Checkpoint.

To do this, execute the following from your command line:

```commandline
great_expectations checkpoint script <my_checkpoint_name>
```

This will create a script in your GE directory at `great_expectations/uncommitted/run_my_checkpoint_name.py`.
That script can be edited that script to include the Custom Expectation import(s) you need:

```python
import sys

from great_expectations.checkpoint.types.checkpoint_result import CheckpointResult
from great_expectations.data_context import DataContext

data_context: DataContext = DataContext(
    context_root_dir="/your/path/to/great_expectations"
)

from expectations.expect_column_values_to_be_alphabetical import ExpectColumnValuesToBeAlphabetical

result: CheckpointResult = data_context.run_checkpoint(
    checkpoint_name="my_checkpoint_name",
    batch_request=None,
    run_name=None,
)

if not result["success"]:
    print("Validation failed!")
    sys.exit(1)

print("Validation succeeded!")
sys.exit(0)
```

The Checkpoint can then be run with:

```python
python great_expectations/uncommitted/run_my_checkpoint_name.py
```

</TabItem>

<TabItem value="contrib-expectations">

### 1. Installation & import

If you're using a Custom Expectation that is coming from the `Great Expectations Experimental` library,
it will need to either be imported from there directly. To do this, we'll first need to `pip install great_expectations_experimental`.

Once that is done, you will be able to import directly from that package:

```python
from great_expectations_experimental.expectations.expect_column_values_to_be_alphabetical import ExpectColumnValuesToBeAlphabetical
```

This import will be needed when an <TechnicalTag tag="expectation_suite" text="Expectation Suite"/> is created, *and* when a <TechnicalTag tag="checkpoint" text="Checkpoint"/> is defined and run.

### 2. Use in a Suite

To use your Custom Expectation, we need to import it as above.

Once that is done, your Custom Expectation will be available with the same patterns as the core Expectations:

```python
validator.expect_column_values_to_be_alphabetical(column="test")
```

### 3. Use in a Checkpoint

Once you have your Custom Expectation in a Suite, you will also need to make it available to your Checkpoint.

To do this, we'll need to put together our own Checkpoint script. From your command line, you can execute:

```commandline
great_expectations checkpoint new <my_checkpoint_name>
```

This will open a Jupyter Notebook allowing you to create a Checkpoint.
If you would like to run your Checkpoint from this notebook, you will need to import your Custom Expectation again as above.

To continue to use this Checkpoint containing a Custom Expectation outside this notebook, we will need to set up a script for your Checkpoint.

To do this, execute the following from your command line:

```commandline
great_expectations checkpoint script <my_checkpoint_name>
```

This will create a script in your GE directory at `great_expectations/uncommitted/run_my_checkpoint_name.py`.
That script can be edited that script to include the Custom Expectation import(s) you need:

```python
import sys

from great_expectations.checkpoint.types.checkpoint_result import CheckpointResult
from great_expectations.data_context import DataContext
from great_expectations_experimental.expectations.expect_column_values_to_be_alphabetical import ExpectColumnValuesToBeAlphabetical

data_context: DataContext = DataContext(
    context_root_dir="/your/path/to/great_expectations"
)

result: CheckpointResult = data_context.run_checkpoint(
    checkpoint_name="my_checkpoint_name",
    batch_request=None,
    run_name=None,
)

if not result["success"]:
    print("Validation failed!")
    sys.exit(1)

print("Validation succeeded!")
sys.exit(0)
```

The Checkpoint can then be run with:

```python
python great_expectations/uncommitted/run_my_checkpoint_name.py
```

</TabItem>

</Tabs>

Congratulations!
🎉 You've just run a Checkpoint with a Custom Expectation! 🎉


text:
var Q = require('q');
var path = require('path');
var fs = require('fs');
var shell = require('shelljs');
var Version = require('./Version');
var events = require('cordova-common').events;
var spawn = require('cordova-common').superspawn.spawn;

function MSBuildTools (version, path) {
    this.version = version;
    this.path = path;
}

MSBuildTools.prototype.buildProject = function (projFile, buildType, buildarch, buildFlags) {
    events.emit('log', 'Building project: ' + projFile);
    events.emit('log', '\tConfiguration : ' + buildType);
    events.emit('log', '\tPlatform      : ' + buildarch);
    events.emit('log', '\tBuildflags    : ' + buildFlags);
    events.emit('log', '\tMSBuildTools  : ' + this.path);

    // Additional requirement checks
    var checkWinSDK = function (target_platform) {
        return require('./check_reqs').isWinSDKPresent(target_platform);
    };
    var checkPhoneSDK = function () {
        return require('./check_reqs').isPhoneSDKPresent();
    };

    // default build args
    var args = ['/clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal', '/nologo',
        '/p:Configuration=' + buildType,
        '/p:Platform=' + buildarch];

    // add buildFlags if present
    if (buildFlags) {
        args = args.concat(buildFlags);
    }

    var that = this;
    var promise;

    // Check if SDK required to build the respective platform is present. If not present, return with corresponding error, else call msbuild.
    if (projFile.indexOf('CordovaApp.Phone.jsproj') > -1) {
        promise = checkPhoneSDK();
    } else if (projFile.indexOf('CordovaApp.Windows.jsproj') > -1) {
        promise = checkWinSDK('8.1');
    } else {
        promise = checkWinSDK('10.0');
    }

    return promise.then(function () {
        console.log('buildProject spawn:', path.join(that.path, 'msbuild'), [projFile].concat(args), { stdio: 'inherit' });
        return spawn(path.join(that.path, 'msbuild'), [projFile].concat(args), { stdio: 'inherit' });
    });
};

// check_reqs.js -> checkMSBuild()
module.exports.findAllAvailableVersions = function () {
    // console.log('findAllAvailableVersions');

    var msBuildPath = '';

    // Use MSBUILDDIR environment variable if defined to find MSBuild.
    // MSBUILDDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin
    // MSBUILDDIR = C:\Program Files (x86)\MSBuild\14.0\bin\
    if (process.env.MSBUILDDIR) {
        console.log('ENV var MSBUILDDIR is set', process.env.MSBUILDDIR);
        msBuildPath = process.env.MSBUILDDIR;
        return module.exports.getMSBuildToolsAt(msBuildPath)
            .then(function (msBuildTools) {
                return [msBuildTools];
            })
            // If MSBUILDDIR is not specified or doesn't contain a valid MSBuild
            // - fall back to default discovery mechanism.
            .catch(findAllAvailableVersionsFallBack);
    }

    // CB-11548 use VSINSTALLDIR environment if defined to find MSBuild.
    if (process.env.VSINSTALLDIR) {
        console.log('ENV var VSINSTALLDIR is set', process.env.VSINSTALLDIR);
        msBuildPath = path.join(process.env.VSINSTALLDIR, 'MSBuild/15.0/Bin');
        return module.exports.getMSBuildToolsAt(msBuildPath)
            .then(function (msBuildTools) {
                return [msBuildTools];
            })
            // If VSINSTALLDIR is not specified or doesn't contain the MSBuild path we are
            // looking for - fall back to default discovery mechanism.
            .catch(findAllAvailableVersionsFallBack);
    }

    return findAllAvailableVersionsFallBack();
};

function findAllAvailableVersionsFallBack () {
    // console.log('findAllAvailableVersionsFALLBACK');

    var versions = ['15.5', '15.0', '14.0', '12.0', '4.0'];
    events.emit('verbose', 'Searching for available MSBuild versions...');

    return Q.all(versions.map(checkMSBuildVersion)).then(function (unprocessedResults) {
        return unprocessedResults.filter(function (item) {
            return !!item;
        });
    });
}

// returns full path to msbuild tools required to build the project and tools version
// check_reqs.js -> run()
module.exports.findAvailableVersion = function () {
    var versions = ['15.5', '15.0', '14.0', '12.0', '4.0'];

    return Q.all(versions.map(checkMSBuildVersion)).then(function (versions) {
        // console.log('findAvailableVersion', versions);
        // select first msbuild version available, and resolve promise with it
        var msbuildTools = versions[0] || versions[1] || versions[2] || versions[3] || versions[4];

        return msbuildTools ? Q.resolve(msbuildTools) : Q.reject('MSBuild tools not found');
    });
};

/**
 * Gets MSBuildTools instance for user-specified location
 *
 * @param {String}  location  FS location where to search for MSBuild
 * @returns  Promise<MSBuildTools>  The MSBuildTools instance at specified location
 */
module.exports.getMSBuildToolsAt = function (location) {
    // console.log('getMSBuildToolsAt', location);
    var msbuildExe = path.resolve(location, 'msbuild');

    // TODO: can we account on these params availability and printed version format?
    return spawn(msbuildExe, ['-version', '-nologo'])
        .then(function (output) {
            // MSBuild prints its' version as 14.0.25123.0, so we pick only first 2 segments
            var version = output.match(/^(\d+\.\d+)/)[1];
            // console.log('return `new MSBuildTools`', version, location);
            return new MSBuildTools(version, location);
        });
};

function checkMSBuildVersion (version) {
    // console.log('checkMSBuildVersion', version);

    // first, check if we have a VS 2017+ with such a version
    var willows = module.exports.getWillowInstallations();
    // console.log('willows', willows);
    var correspondingWillows = willows.filter(function (inst) {
        // console.log('willows.filter', inst.version, version, inst.version === version);
        return inst.version === version;
    });
    // console.log('correspondingWillows', correspondingWillows);
    var correspondingWillow = correspondingWillows[0]; // TODO Do not only handle one!
    if (correspondingWillow) {
        // super hacky: VS2017/Willow is 15.x but MSBuild is always 15.0 in path - so set that here
        version = '15.0';
        var toolsPath = path.join(correspondingWillow.path, 'MSBuild', version, 'Bin');
        // console.log('matching VS:', version, toolsPath);
        // console.log('from list of VS installations: ', correspondingWillows);
        if (shell.test('-e', toolsPath)) {
            var msbuild = module.exports.getMSBuildToolsAt(toolsPath);
            // console.log('selected VS exists:', toolsPath);
            // TODO check for JavaScript folder
            return msbuild;
        }
    }

    // older vs versions that were registered in registry
    return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + version, '/v', 'MSBuildToolsPath'])
        .then(function (output) {
            // console.log('spawn', output);
            // fetch msbuild path from 'reg' output
            var toolsPath = /MSBuildToolsPath\s+REG_SZ\s+(.*)/i.exec(output);
            if (toolsPath) {
                toolsPath = toolsPath[1];
                // CB-9565: Windows 10 invokes .NET Native compiler, which only runs on x86 arch,
                // so if we're running an x64 Node, make sure to use x86 tools.
                if ((version === '15.0' || version === '14.0') && toolsPath.indexOf('amd64') > -1) {
                    toolsPath = path.resolve(toolsPath, '..');
                }
                events.emit('verbose', 'Found MSBuild v' + version + ' at ' + toolsPath);
                return new MSBuildTools(version, toolsPath);
            }
        }).catch(function (err) { /* eslint handle-callback-err : 0 */
            // console.log('no registry result for version ' + version);
            // if 'reg' exits with error, assume that registry key not found
        });
}

// build.js -> run()
module.exports.getLatestMatchingMSBuild = function (selectedBuildTargets) {
    events.emit('verbose', 'getLatestMatchingMSBuild');
    // console.log('getLatestMatchingMSBuild', selectedBuildTargets);
    // TODO
    // 1. findAllAvailableVersions
    // 2. filter down to versions that can build all selectedBuildTargets
    // 3. filter for latest one of those
    return this.getLatestMSBuild()
        .then(function (msbuild) {
            // filter targets to make sure they are supported on this development machine
            var myBuildTargets = filterSupportedTargets(selectedBuildTargets, msbuild);
            return [msbuild, myBuildTargets];
        });
};

// gets the latest MSBuild version from a list of versions
module.exports.getLatestMSBuild = function () {
    events.emit('verbose', 'getLatestMSBuild');

    return this.findAllAvailableVersions()
        .then(function (allMsBuildVersions) {

            var availableVersions = allMsBuildVersions
                .filter(function (buildTools) {
                    // Sanitize input - filter out tools w/ invalid versions
                    return Version.tryParse(buildTools.version);
                }).sort(function (a, b) {
                    // Sort tools list - use parsed Version objects for that
                    // to respect both major and minor versions segments
                    var parsedA = Version.fromString(a.version);
                    var parsedB = Version.fromString(b.version);

                    if (parsedA.gt(parsedB)) return -1;
                    if (parsedA.eq(parsedB)) return 0;
                    return 1;
                });

            // console.log('availableVersions', availableVersions);

            if (availableVersions.length > 0) {
                // After sorting the first item will be the highest version available
                var msbuild = availableVersions[0];
                events.emit('verbose', 'Using MSBuild v' + msbuild.version + ' from ' + msbuild.path);
                return msbuild;
            }
        });
};

var projFiles = {
    phone: 'CordovaApp.Phone.jsproj',
    win: 'CordovaApp.Windows.jsproj',
    win10: 'CordovaApp.Windows10.jsproj'
};

// TODO: Fix this so that it outlines supported versions based on version criteria:
// - v14: Windows 8.1, Windows 10
// - v12: Windows 8.1
function msBuild12TargetsFilter (target) {
    return target === projFiles.win || target === projFiles.phone;
}

function msBuild14TargetsFilter (target) {
    return target === projFiles.win || target === projFiles.phone || target === projFiles.win10;
}

function msBuild15TargetsFilter (target) {
    return target === projFiles.win || target === projFiles.phone || target === projFiles.win10;
}

function msBuild155TargetsFilter (target) {
    return target === projFiles.win10;
}

function filterSupportedTargets (targets, msbuild) {
    // console.log('MSBuildTools->filterSupportedTargets', targets, msbuild);
    if (!targets || targets.length === 0) {
        events.emit('warn', 'No build targets specified');
        return [];
    }

    var targetFilters = {
        '12.0': msBuild12TargetsFilter,
        '14.0': msBuild14TargetsFilter,
        '15.x': msBuild15TargetsFilter,
        '15.5': msBuild155TargetsFilter,
        get: function (version) {
            // Apart from exact match also try to get filter for version range
            // so we can find for example targets for version '15.1'
            return this[version] || this[version.replace(/\.\d+$/, '.x')];
        }
    };

    var filter = targetFilters.get(msbuild.version);
    if (!filter) {
        events.emit('warn', 'MSBuild v' + msbuild.version + ' is not supported, aborting.');
        return [];
    }

    var supportedTargets = targets.filter(filter);
    // unsupported targets have been detected
    if (supportedTargets.length !== targets.length) {
        events.emit('warn', 'Not all desired build targets are compatible with the current build environment. ' +
            'Please install Visual Studio 2015 for Windows 8.1 and Windows 10, ' +
            'or Visual Studio 2013 Update 2 for Windows 8.1.');
    }
    return supportedTargets;
}

/**
 * Lists all VS 2017+ instances dirs in ProgramData
 *
 * @return {String[]} List of paths to all VS2017+ instances
 */
function getWillowProgDataPaths () {
    if (!process.env.systemdrive) {
        // running on linux/osx?
        return [];
    }
    var instancesRoot = path.join(process.env.systemdrive, 'ProgramData/Microsoft/VisualStudio/Packages/_Instances');
    if (!shell.test('-d', instancesRoot)) {
        // can't seem to find VS instances dir, return empty result
        return [];
    }

    return fs.readdirSync(instancesRoot).map(function (file) {
        var instanceDir = path.join(instancesRoot, file);
        if (shell.test('-d', instanceDir)) {
            return instanceDir;
        }
    }).filter(function (progDataPath) {
        // make sure state.json exists
        return shell.test('-e', path.join(progDataPath, 'state.json'));
    });
}

/**
 * Lists all installed VS 2017+ versions
 *
 * @return {Object[]} List of all VS 2017+ versions
 */
module.exports.getWillowInstallations = function () {
    var progDataPaths = getWillowProgDataPaths();
    var installations = [];
    progDataPaths.forEach(function (progDataPath) {
        try {
            var stateJsonPath = path.join(progDataPath, 'state.json');
            var fileContents = fs.readFileSync(stateJsonPath, 'utf-8');
            var state = JSON.parse(fileContents);
            // get only major and minor version
            var version = state.product.version.match(/^(\d+\.\d+)/)[1];
            installations.push({ version: version, path: state.installationPath });
        } catch (err) {
            // something's wrong, skip this one
        }
    });
    return installations;
};

// returns an array of available UAP Versions
// prepare.js
module.exports.getAvailableUAPVersions = function () {
    var programFilesFolder = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
    // No Program Files folder found, so we won't be able to find UAP SDK
    if (!programFilesFolder) return [];

    var uapFolderPath = path.join(programFilesFolder, 'Windows Kits', '10', 'Platforms', 'UAP');
    if (!shell.test('-e', uapFolderPath)) {
        return []; // No UAP SDK exists on this machine
    }

    var result = [];
    shell.ls(uapFolderPath).filter(function (uapDir) {
        return shell.test('-d', path.join(uapFolderPath, uapDir));
    }).map(function (folder) {
        return Version.tryParse(folder);
    }).forEach(function (version, index) {
        if (version) {
            result.push(version);
        }
    });

    return result;
};


text:
/* this compiler is intended to work in a gemini.qof compiled
   image.

   If we use this enough, it could be promoted to being a full-fledged
   gemini compiler.
*/

gemini2regulus(OutputFile):-
	determine_regulus_feature_value_spaces,
	determine_regulus_features,
	determine_regulus_categories,
	determine_regulus_top_level_category,
	determine_regulus_rules,
	write_regulus_file(OutputFile).

determine_regulus_feature_value_spaces:-
	clear_dynamic_predicates([regulus_feature_value_space/2]),
	feature_type_def(ValueSpaceID, Values, EnableBooleanOps),
	\+ logical_form_valueset(ValueSpaceID), % exclude LF valued features
	\+ ValueSpaceID = lexform_types, % exclude lexform_types
	(EnableBooleanOps = no ->
	     ValueSpaces = [Values]
	;    ValueSpaces = Values),
	assert(regulus_feature_value_space(ValueSpaceID, ValueSpaces)),
	fail.
determine_regulus_feature_value_spaces.

determine_regulus_features :-
	clear_dynamic_predicates([regulus_feature/2]),
        % only even consider syntactic features
	feature_def(_Category, FeatureName, syn, _, ValueSpaceID, _, _,_),
	% should be a known ValueSpaceID,
	regulus_feature_value_space(ValueSpaceID, _),
	assert_once(regulus_feature(FeatureName, ValueSpaceID)),
	fail.
determine_regulus_features.

determine_regulus_categories :-
	clear_dynamic_predicates([regulus_category/2]),
	category(CategoryName, _Lexical),
	findall(Feature,
		(feature_def(CategoryName, Feature, syn, _, _, _, _, _),
		 regulus_feature(Feature, _)),
		FeatsList),
	assert(regulus_category(CategoryName, FeatsList)),
	fail.
determine_regulus_categories.

determine_regulus_top_level_category:-
	clear_dynamic_predicates([regulus_top_level_category/1]),
	assert(regulus_top_level_category(sigma)).

determine_regulus_rules:-
	clear_dynamic_predicates([regulus_rule/2]),
	determine_regulus_syntax_rules,
	determine_regulus_lexicon.

determine_regulus_lexicon:-
	cat(Word, GeminiCategory),
	gemini_category2regulus_category(GeminiCategory, RegulusCategory),
	assert(regulus_rule(RegulusCategory, Word)),
	fail.
% multi-words are stored in multi_word_cat in reverse order,
% so they are easier to match against the chart.
determine_regulus_lexicon:-
	multi_word_cat(LastWord, RestWords, GeminiCategory),
	gemini_category2regulus_category(GeminiCategory, RegulusCategory),
	words_to_comma_tuples(RestWords, LastWord, RHS),
	assert(regulus_rule(RegulusCategory, RHS)),
	fail.
determine_regulus_lexicon.

% top level rules using application_sigma_rule/5 are
% required to to non-branching.  This code should be generalized
% to allow other top_down rules (none in PSA, but...)
determine_regulus_syntax_rules:-
	top_down_rule(GeminiCategory, [GeminiRHS], RuleName),
	application_sigma_rule(_Handle, _Feats, RuleName, yes, _) ,
	decode_cat((GeminiCategory,GeminiRHS),(RegulusCategory, RegulusRHS)),
	assert(regulus_rule(RegulusCategory, RegulusRHS)),
	fail.
determine_regulus_syntax_rules:-
	rule(GeminiCategory, GeminiRHS, _RuleName),
	my_decode_cat([GeminiCategory|GeminiRHS], [RegulusCategory|RegulusRHS]),
	list_to_comma_tuples(RegulusRHS, RHS),
	assert(regulus_rule(RegulusCategory, RHS)),
	fail.

determine_regulus_syntax_rules.

gemini_rhs2regulus_rhs([GeminiCategory], RegulusCategory):-
	!,
        gemini_category2regulus_category(GeminiCategory, RegulusCategory).
gemini_rhs2regulus_rhs([GeminiCategory|RestGeminiRHS],
		       (RegulusCategory,RestRegulusRHS)):-
        gemini_category2regulus_category(GeminiCategory, RegulusCategory),
	gemini_rhs2regulus_rhs(RestGeminiRHS, RestRegulusRHS).

% words_to_comma_tuples does a reverse on the way down
% multi-words are stored in reverse order
words_to_comma_tuples([], Partial, Partial):-
	!.
words_to_comma_tuples([Term], Partial, (Term,Partial)):-
	!.
words_to_comma_tuples([Term|RestWords], Partial, Result):-
	words_to_comma_tuples(RestWords, (Term,Partial), Result).

% like words_to_comma_tuples, but does not do the reverse
list_to_comma_tuples([Term], Term):-
	!.
list_to_comma_tuples([Term|Rest], (Term,Result)):-
	list_to_comma_tuples(Rest, Result).

gemini_category2regulus_category(Category, Category):-
	atomic(Category),
	!.
gemini_category2regulus_category(GeminiCategory,
				 CategoryName:PrunedFeatureValues):-
	% decode_cat/2 translates from Gemini internal form
	% to MajorCat:FeatureValues form.
	decode_cat(GeminiCategory, CategoryName:FeatureValues),
	prune_nonregulus_features(FeatureValues, PrunedFeatureValues).

prune_nonregulus_features([], []).
prune_nonregulus_features([(FeatName=Val)|RestFeats], [(FeatName=Val)|ResultFeats]):-
	regulus_feature(FeatName, _),
	!,
	prune_nonregulus_features(RestFeats, ResultFeats).
prune_nonregulus_features([(_FeatName=_Val)|RestFeats], ResultFeats):-
	prune_nonregulus_features(RestFeats, ResultFeats).

/*
 my_decode_cat/2 is a varient of decode_cat/2 that preserves
 variables across pretty printing of (for instance) boolean valued
 features.  That is, the source grammar may have something like

 syn(utterance_s, basic,
        [utterance:[stype=SType],
         s:[stype=SType, stype=(dcl\/imp\/ynq\/whq), operator_wrapped=y,
	    gapsin=null, gapsout=null]]).

Where the stype is explicitly shared between the utterance and the s.
Internal processing forces those to have shared variables, but
decode_cat/2 will lose those sharings.

*/
my_decode_cat(Source, Result):-
	note_shared_terms(Source, Shares),
	substitute_shares_with_vars(Source, Shares, NextSource),
	convert_shares(Shares, NextSource, Target, TargetShares),
	add_shares_back_in(Target, TargetShares, Result).

% this predicate is a mess.  It seems to work, but I need
% to work through this from first principles again.
convert_shares(Shares, Source, Target, ResultShares):-
	copy_term((Shares,Source),(CopyShares,CopySource)),
	unify_shares_in(CopyShares),
	decode_cat((Shares,Source), (TempShares,NextSource)),
	decode_cat((CopyShares,CopySource), (NextShares,NextSource)),
	pair_shares_back_up(TempShares, Shares, Shares1),
	decode_cat((Shares1,Source), (ResultShares,Target)).

pair_shares_back_up([], [], []).
pair_shares_back_up([pair(_, R)|Rest],[pair(_, Var)|RestSource],[pair(R,Var)|RestResults]):-
	pair_shares_back_up(Rest,RestSource, RestResults).

unify(X,X).

unify_shares_in([]).
unify_shares_in([pair(Val, Val)|RestShares]):-
	unify_shares_in(RestShares).

add_shares_back_in([], [], []).
add_shares_back_in([Cat|RestCats], Shares, [ResultCat|RestResultCats]):-
	add_shares_back_in_cat(Cat, Shares, ResultCat, RestShares),
	add_shares_back_in(RestCats, RestShares, RestResultCats).

add_shares_back_in_cat(Cat, Shares, Cat, Shares):-
	atomic(Cat),
	!.
add_shares_back_in_cat(Cat, Shares, Cat, Shares):-
	var(Cat), % shouldn't happen
	!.
add_shares_back_in_cat((MajorCat:Feats), Shares, (MajorCat:NewFeats), RestShares):-
	add_shares_back_in_feats(Feats, Shares, NewFeats, RestShares).

add_shares_back_in_feats([], Shares, [], Shares).
add_shares_back_in_feats([(FeatName=FeatValue)|RestFeats], Shares, [(FeatName=RealValue),(FeatName=FeatValue)|RestResultFeats], ResultShares):-
	matches_with_term(Shares, FeatValue, RealValue, RestShares),
	!,
	add_shares_back_in_feats(RestFeats, RestShares,RestResultFeats, ResultShares).
add_shares_back_in_feats([(FeatName=FeatValue)|RestFeats], Shares, [(FeatName=NewFeatValue)|RestResultFeats], ResultShares):-
	add_shares_back_in_value(FeatValue, Shares, NewFeatValue, RestShares),
	!,
	add_shares_back_in_feats(RestFeats, RestShares,RestResultFeats, ResultShares).

add_shares_back_in_value(FeatValue, Shares, FeatValue, Shares):-
	atomic(FeatValue),
	!.
add_shares_back_in_value(FeatValue, Shares, FeatValue, Shares):-
	var(FeatValue),
	!.
add_shares_back_in_value((MajorCat:Feats), Shares, (MajorCat:NewFeats), RestShares):-
	!,
	add_shares_back_in_feats(Feats, Shares, NewFeats, RestShares).
add_shares_back_in_value(FeatValue, Shares, FeatValue, Shares).

substitute_shares_with_vars(Source, _Shares, Source):-
	atomic(Source),
	!.
substitute_shares_with_vars(Source, _Shares, Source):-
	var(Source),
	!.
substitute_shares_with_vars(Source, Shares, Var):-
	matches_with_var(Shares, Source, Var),
	!.
substitute_shares_with_vars(Source, Shares, Result):-
	functor(Source, Functor, Arity),
	functor(Result, Functor, Arity),
	substitute_shares_with_var_helper(Arity, Source, Shares, Result).

substitute_shares_with_var_helper(0, _Source, _Shares, _Result).
substitute_shares_with_var_helper(Arity, Source, Shares, Result):-
	arg(Arity, Source, SourceArg),
	arg(Arity, Result, ResultArg),
	NextArity is Arity - 1,
	substitute_shares_with_vars(SourceArg, Shares, ResultArg),
	substitute_shares_with_var_helper(NextArity, Source, Shares, Result).

note_shared_terms(Source, Shares):-
	find_all_terms(Source, [], Terms),
	remove_non_shared(Terms, Shares).

find_all_terms(Var, Terms, Terms):-
	var(Var),
	!. % not interested in isolated vars, only non-ground compound terms
find_all_terms(Atomic, Terms, Terms):-
	atomic(Atomic),
	!.
find_all_terms(CompoundTerm, Terms, Terms):-
	ground(CompoundTerm),
	!.
find_all_terms(CompoundTerm, Terms, Terms):-
	already_seen_term(Terms, CompoundTerm),
	!.
find_all_terms(CompoundTerm, Terms, RestTerms):-
	functor(CompoundTerm, _, Arity),
	find_all_terms_helper(Arity, CompoundTerm, [term(CompoundTerm,_)|Terms], RestTerms).

find_all_terms_helper(0, _CompoundTerm, Terms, Terms).
find_all_terms_helper(Arity, CompoundTerm, Terms, RestTerms):-
	Arity > 0,
	arg(Arity, CompoundTerm, Arg),
	find_all_terms(Arg, Terms, TempTerms),
	NextArity is Arity - 1,
	find_all_terms_helper(NextArity, CompoundTerm, TempTerms, RestTerms).

matches_with_term([pair(Term, Var)|RestShares], TargetVar, Term, RestShares):-
	Var == TargetVar,
	!.
matches_with_var([This|Rest], TargetVar, Term, [This|RestShares]):-
	matches_with_var(Rest, TargetVar, Term, RestShares).

matches_with_var([pair(Term, Var)|_], TargetTerm, Var):-
	Term == TargetTerm,
	!.
matches_with_var([_|Rest], TargetTerm, Var):-
	matches_with_var(Rest, TargetTerm, Var).

already_seen_term([term(Term, true)|_], TargetTerm):-
	Term == TargetTerm,
	!.
already_seen_term([_|Rest], TargetTerm):-
	already_seen_term(Rest, TargetTerm).

remove_non_shared([], []).
remove_non_shared([term(Term, Var)|RestTerms], [pair(Term, _NewVar)|Result]):-
	Var == true,
	!,
	remove_non_shared(RestTerms, Result).
remove_non_shared([_|RestTerms], Result):-
	remove_non_shared(RestTerms, Result).

write_regulus_file(OutputFile):-
	open(OutputFile, write, Stream),
	write_regulus_stream(Stream),
	close(Stream).

write_regulus_stream(Stream):-
	regulus_feature_value_space(ValueSpaceID, Values),
	format(Stream, '~q.~n', [feature_value_space(ValueSpaceID, Values)]),
	fail.
write_regulus_stream(Stream):-
	nl(Stream),
	regulus_feature(FeatureName, ValueSpaceID),
	format(Stream, '~q.~n', [feature(FeatureName, ValueSpaceID)]),
	fail.
write_regulus_stream(Stream):-
	nl(Stream),
	regulus_category(Category, FeatureList),
	format(Stream, '~q.~n', [category(Category, FeatureList)]),
	fail.
write_regulus_stream(Stream):-
	nl(Stream),
	regulus_top_level_category(Category),
	format(Stream, '~q.~n', [top_level_category(Category)]),
	fail.
write_regulus_stream(Stream):-
	nl(Stream),
	regulus_rule(Category, RHS),
	numbervars((Category --> RHS), 0, _),
	format(Stream, '~q.~n', [(Category --> RHS)]),
	fail.
write_regulus_stream(_Stream).


text:
  Vernoux-en-Vivarais est
      une commune localisée dans le département de l'Ardêche en Rhône-Alpes. On dénombrait 1 877 habitants en 2008.

Le parc d'habitations, à Vernoux-en-Vivarais, était réparti en 2011 en 237 appartements et 880 maisons soit
 un marché relativement équilibré.

La commune est équipée concernant l'éducation des jeunes de deux collèges.
Pour les plus petits d'entre nous, la localité est pourvue de une maternelle et deux écoles primaires.
Vernoux-en-Vivarais est équipée des  installations facilitant une bonne prise en charge des jeunes.
Si vous avez un projet de faire une acquisition à Vernoux-en-Vivarais, il est intéressant d' évaluer la valeur des équipements éducatifs

À Vernoux-en-Vivarais, le prix moyen à la vente d'un appartement s'évalue à 970 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 186 € du m². À la location le prix moyen se situe à 0 € du m² par mois.

La commune offre de multiples  aménagements, elle propose entre autres un bassin de natation, un terrain de tennis, un terrain de sport et trois boucles de randonnée.

À coté de Vernoux-en-Vivarais sont positionnées géographiquement les communes de
Saint-Apollinaire-de-Rias à 4 km, 151 habitants,
Saint-Jean-Chambre à 6 km, 251 habitants,
Saint-Barthélemy-Grozon à 7 km, 521 habitants,
Boffres à 5 km, 604 habitants,
Saint-Maurice-en-Chalencon située à 6 km, 174 habitants,
Saint-Julien-le-Roux à 4 km, 87 habitants,
 entre autres. De plus, Vernoux-en-Vivarais est située à seulement 19 km de Valence.


text:
namespace OpenLiveWriter.Controls
{
	/// <summary>
	/// Defines the abstract interface for an object that can display tool tips.
	/// </summary>
	public interface IToolTipDisplay
	{
		/// <summary>
		/// Sets the tooltip.
		/// </summary>
		/// <param name="toolTipText">The tooltip text, or null if no tooltip text should be displayed.</param>
		void SetToolTip(string toolTipText);
	}
}


text:
<?php

namespace MamuzBlog\Feature;

use MamuzBlog\Entity\Tag;

interface TagQueryInterface extends Pageable
{
    /**
     * @return Tag[]|\Countable|\IteratorAggregate
     */
    public function findUsedTags();
}


text:
package com.groupon.jenkins.buildtype.install_packages.buildconfiguration;

import com.groupon.jenkins.buildtype.util.shell.ShellCommands;
import org.junit.Test;

import static org.junit.Assert.*;

public class NotificationsSectionTest {

    @Test
    public void shouldnt_run_any_shell_commands() {
        assertEquals(ShellCommands.NOOP, new NotificationsSection(null).toScript(null));
    }
}


text:
package net.techcable.techutils.scheduler;

/**
 * A task in a {@link net.techcable.techutils.scheduler.TechScheduler}
 *
 * @author Techcable
 */
public interface TechTask {

    /**
     * Add the specified completion listener to this task
     *

     * A completion listener will run when the task is completed
     * It is up to the implementation to decide which thread the completion listener will run in
     *

     *
     * @param r the completion listener
     */
    public void addCompletionListener(Runnable r);

    /**
     * Returns true if the Task is a sync task.
     *
     * @return true if the task is run by main thread
     */
    public boolean isSync();

    /**
     * Attempt to cancel this task
     *

     * Won't Interrupt if running
     *

     * Returns false if failed
     * A return value of true doesn't always indicate success
     *
     * @return false if successful
     */
    public boolean cancel();
}


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="vertical"
	>
	<ListView
		android:id="@android:id/list"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_weight="1"
		>
	</ListView>
	<LinearLayout
		android:id="@android:id/empty"
		android:orientation="vertical"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_weight="1"
		android:gravity="center"
		>
		<TextView
			android:id="@+id/empty_msg"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			/>
	</LinearLayout>

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		style="@android:style/ButtonBar"
		>
		<TextView
			android:id="@+id/filename"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:layout_marginLeft="@dimen/large_gutter"
			/>
		<Button
			android:id="@+id/btn_choose"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Pick"
			android:onClick="onClickChoose"
			android:clickable="false"
			/>
	</LinearLayout>

</LinearLayout>


text:
class Lang {
    constructor(langEl) {
        /**
         * @param langEl:TYPE String or 为空 or HTMLElement
         *  TYPE String:document.querySelector的那个选择器字符串,Eg:'[data-ftc-component="ftc-header-lang"]'
         *  TYPE HTMLElement:属性data-ftc-component的值为ftc-header-lang的元素
        */
        if (!langEl) {
            langEl = document.querySelector('[data-ftc-component="ftc-header-lang"]');
        } else if (!(langEl instanceof HTMLElement)) {
            langEl = document.querySelector(langEl);
        }
        this.langEl = langEl;

        const langList = langEl.querySelector('.ftc-header__lang-list');
        if(!langList) {
            return;
        }
        this.langList = langList;

        const langFistItem = langList.querySelector('.ftc-header__lang-item');
        if(!langFistItem) {
            return;
        }
        this.langFistItem = langFistItem;

        this.toggle = this.toggle.bind(this);
        this.langFistItem.addEventListener('click',this.toggle,false)

    }

    toggle(e) {
        this.langList.classList.toggle('ftc-header__lang-listdefault');
    }

    static init(rootEl) {
        /**
		 * @param rootEl: TYPE HTMLElement or String or 为空
		 * 	TYPE HTMLElement,要初始化所有属性data-ftc-component为ftc-header-lang的元素的区域的顶级元素,Eg:header组件,即其上级的[data-ftc-component]="ftc-header"的元素
		 *  TYPE String: 以上HTMLElement使用document.querySelector传入的选择器字符串
		 */
		if (!rootEl) {
			rootEl = document.querySelector('[data-ftc-component="ftc-header"]');
		} else if (typeof rootEl === 'string') {
			rootEl = document.querySelector(rootEl);
        }

        if (rootEl.querySelector('[data-ftc-component="ftc-header-lang"]')) {
            const langEl = rootEl.querySelector('[data-ftc-component="ftc-header-lang"]');
            return new Lang(langEl);
        }
    }
}

export default Lang;


text:
'use strict';

var queue = require('queue-async');
var debug = require('debug')('windshaft:analysis');

var camshaft = require('camshaft');
const queryUtils = require('../../../../lib/utils/query-utils');
var dot = require('dot');
dot.templateSettings.strip = false;

function AnalysisMapConfigAdapter (analysisBackend) {
    this.analysisBackend = analysisBackend;
}

module.exports = AnalysisMapConfigAdapter;

AnalysisMapConfigAdapter.prototype.getMapConfig = function (user, requestMapConfig, params, context, callback) {
    var self = this;

    if (!shouldAdaptLayers(requestMapConfig)) {
        return callback(null, requestMapConfig);
    }

    var analysisConfiguration = context.analysisConfiguration;

    var filters = {};
    if (params.filters) {
        try {
            filters = JSON.parse(params.filters);
        } catch (e) {
            // ignore
        }
    }

    var dataviewsFilters = filters.dataviews || {};
    debug(dataviewsFilters);
    var dataviews = requestMapConfig.dataviews || {};

    var errors = getDataviewsErrors(dataviews);
    if (errors.length > 0) {
        return callback(errors);
    }

    var dataviewsFiltersBySourceId = Object.keys(dataviewsFilters).reduce(function (bySourceId, dataviewName) {
        var dataview = dataviews[dataviewName];
        if (dataview) {
            var sourceId = dataview.source.id;
            if (!Object.prototype.hasOwnProperty.call(bySourceId, sourceId)) {
                bySourceId[sourceId] = {};
            }

            bySourceId[sourceId][dataviewName] = getFilter(dataview, dataviewsFilters[dataviewName]);
        }
        return bySourceId;
    }, {});

    debug(dataviewsFiltersBySourceId);

    debug('mapconfig input', JSON.stringify(requestMapConfig, null, 4));

    requestMapConfig = appendFiltersToNodes(requestMapConfig, dataviewsFiltersBySourceId);

    // Expected format for analyses filters
    // filters = {analyses: {
    //     a1: [{min, max}, {accept, reject}],
    //     b1: [{range, column, min, max}, {category, column, accept, reject}]
    // }}
    requestMapConfig = appendFiltersToNodes(requestMapConfig, filters.analyses);

    function createAnalysis (analysisDefinition, done) {
        self.analysisBackend.create(analysisConfiguration, analysisDefinition, function (err, analysis) {
            if (err) {
                var error = new Error(err.message);
                error.type = 'analysis';
                error.analysis = {
                    id: analysisDefinition.id,
                    node_id: err.node_id,
                    type: analysisDefinition.type
                };
                return done(error);
            }

            done(null, analysis);
        });
    }

    var analysesQueue = queue(1);
    requestMapConfig.analyses.forEach(function (analysis) {
        analysesQueue.defer(createAnalysis, analysis);
    });

    analysesQueue.awaitAll(function (err, analysesResults) {
        if (err) {
            return callback(err);
        }

        var sourceId2Node = analysesResults.reduce(function (sourceId2Query, analysis) {
            var rootNode = analysis.getRoot();
            if (rootNode.params && rootNode.params.id) {
                sourceId2Query[rootNode.params.id] = rootNode;
            }

            analysis.getNodes().forEach(function (node) {
                if (node.params && node.params.id) {
                    sourceId2Query[node.params.id] = node;
                }
            });

            return sourceId2Query;
        }, {});

        var analysesErrors = [];

        requestMapConfig.layers = requestMapConfig.layers.map(function (layer, layerIndex) {
            if (getLayerSourceId(layer)) {
                var layerSourceId = getLayerSourceId(layer);
                var layerNode = sourceId2Node[layerSourceId];
                if (layerNode) {
                    try {
                        var analysisSql;

                        // it might throw error: Range filter from camshaft, for instance.
                        analysisSql = layerQuery(layerNode);

                        var sqlQueryWrap = layer.options.sql_wrap;
                        if (sqlQueryWrap) {
                            layer.options.sql_raw = analysisSql;
                            analysisSql = sqlQueryWrap.replace(/<%=\s*sql\s*%>/g, analysisSql);
                        }
                        layer.options.sql = analysisSql;
                        layer.options.columns = getDataviewsColumns(getLayerDataviews(layer, dataviews));
                        layer.options.affected_tables = getAllAffectedTablesFromSourceNodes(layerNode);
                    } catch (error) {
                        analysesErrors.push(error);
                    }
                } else {
                    analysesErrors.push(
                        new Error('Missing analysis node.id="' + layerSourceId + '" for layer=' + layerIndex)
                    );
                }
            }
            return layer;
        });

        var missingDataviewsNodesErrors = getMissingDataviewsSourceIds(dataviews, sourceId2Node);
        if (analysesErrors.length > 0 || missingDataviewsNodesErrors.length > 0) {
            return callback(analysesErrors.concat(missingDataviewsNodesErrors));
        }

        // Augment dataviews with sql from analyses
        Object.keys(dataviews).forEach(function (dataviewName) {
            var dataview = requestMapConfig.dataviews[dataviewName];
            var dataviewSourceId = dataview.source.id;
            var dataviewNode = sourceId2Node[dataviewSourceId];
            dataview.node = {
                type: dataviewNode.type,
                filters: dataviewNode.getFilters()
            };
            dataview.sql = {
                own_filter_on: dataviewQuery(dataviewNode, dataviewName, true),
                own_filter_off: dataviewQuery(dataviewNode, dataviewName, false),
                no_filters: dataviewNode.getQuery(Object.keys(dataviewNode.getFilters())
                    .reduce(function (applyFilters, filterId) {
                        applyFilters[filterId] = false;
                        return applyFilters;
                    }, {})
                )
            };
        });
        if (Object.keys(dataviews).length > 0) {
            requestMapConfig.dataviews = dataviews;
        }

        debug('mapconfig output', JSON.stringify(requestMapConfig, null, 4));

        context.analysesResults = analysesResults;

        return callback(null, requestMapConfig);
    });
};

var SKIP_COLUMNS = {
    the_geom: true,
    the_geom_webmercator: true
};

function skipColumns (columnNames) {
    return columnNames
        .filter(function (columnName) { return !SKIP_COLUMNS[queryUtils.stripQuotes(columnName)]; });
}

var wrappedQueryTpl = dot.template([
    'SELECT {{=it._columns}}',
    'FROM ({{=it._query}}) _cdb_analysis_query'
].join('\n'));

function layerQuery (node) {
    if (node.type === 'source') {
        return node.getQuery();
    }
    var _columns = ['ST_Transform(the_geom, 3857) the_geom_webmercator'].concat(skipColumns(node.getColumns()));
    return wrappedQueryTpl({ _query: node.getQuery(), _columns: _columns.join(', ') });
}

function dataviewQuery (node, dataviewName, ownFilter) {
    var applyFilters = {};
    if (!ownFilter) {
        applyFilters[dataviewName] = false;
    }

    if (node.type === 'source') {
        return node.getQuery(applyFilters);
    }
    var _columns = ['ST_Transform(the_geom, 3857) the_geom_webmercator'].concat(skipColumns(node.getColumns()));
    return wrappedQueryTpl({ _query: node.getQuery(applyFilters), _columns: _columns.join(', ') });
}

function appendFiltersToNodes (requestMapConfig, dataviewsFiltersBySourceId) {
    var analyses = requestMapConfig.analyses || [];
    dataviewsFiltersBySourceId = dataviewsFiltersBySourceId || {};

    requestMapConfig.analyses = analyses.map(function (analysisDefinition) {
        var analysisGraph = new camshaft.reference.AnalysisGraph(analysisDefinition);
        var definition = analysisDefinition;
        Object.keys(dataviewsFiltersBySourceId).forEach(function (sourceId) {
            definition = analysisGraph.getDefinitionWith(sourceId, { filters: dataviewsFiltersBySourceId[sourceId] });
        });

        return definition;
    });

    return requestMapConfig;
}

function shouldAdaptLayers (requestMapConfig) {
    return (Array.isArray(requestMapConfig.layers) && requestMapConfig.layers.some(getLayerSourceId)) ||
        (Array.isArray(requestMapConfig.analyses) && requestMapConfig.analyses.length > 0) ||
        requestMapConfig.dataviews;
}

var DATAVIEW_TYPE_2_FILTER_TYPE = {
    aggregation: 'category',
    histogram: 'range'
};
function getFilter (dataview, params) {
    var type = dataview.type;

    return {
        type: DATAVIEW_TYPE_2_FILTER_TYPE[type],
        column: dataview.options.column,
        params: params
    };
}

function getLayerSourceId (layer) {
    return layer.options.source && layer.options.source.id;
}

function getDataviewSourceId (dataview) {
    return dataview.source && dataview.source.id;
}

function getLayerDataviews (layer, dataviews) {
    var layerDataviews = [];

    var layerSourceId = getLayerSourceId(layer);
    if (layerSourceId) {
        var dataviewsList = getDataviewsList(dataviews);
        dataviewsList.forEach(function (dataview) {
            if (getDataviewSourceId(dataview) === layerSourceId) {
                layerDataviews.push(dataview);
            }
        });
    }

    return layerDataviews;
}

function getDataviewsColumns (dataviews) {
    return Object.keys(dataviews.reduce(function (columnsDict, dataview) {
        getDataviewColumns(dataview).forEach(function (columnName) {
            if (columnName) {
                columnsDict[columnName] = true;
            }
        });
        return columnsDict;
    }, {}));
}

function getDataviewColumns (dataview) {
    var columns = [];
    var options = dataview.options;
    ['column', 'aggregationColumn'].forEach(function (opt) {
        if (Object.prototype.hasOwnProperty.call(options, opt) && !!options[opt]) {
            columns.push(options[opt]);
        }
    });
    return columns;
}

function getDataviewsList (dataviews) {
    return Object.keys(dataviews).map(function (dataviewKey) { return dataviews[dataviewKey]; });
}

function getDataviewsErrors (dataviews) {
    var dataviewType = typeof dataviews;
    if (dataviewType !== 'object') {
        return [new Error('"dataviews" must be a valid JSON object: "' + dataviewType + '" type found')];
    }

    if (Array.isArray(dataviews)) {
        return [new Error('"dataviews" must be a valid JSON object: "array" type found')];
    }

    var errors = [];

    Object.keys(dataviews).forEach(function (dataviewName) {
        var dataview = dataviews[dataviewName];
        if (!Object.prototype.hasOwnProperty.call(dataview, 'source') || !dataview.source.id) {
            errors.push(new Error('Dataview "' + dataviewName + '" is missing `source.id` attribute'));
        }

        if (!dataview.type) {
            errors.push(new Error('Dataview "' + dataviewName + '" is missing `type` attribute'));
        }
    });

    return errors;
}

function getMissingDataviewsSourceIds (dataviews, sourceId2Node) {
    var missingDataviewsSourceIds = [];
    Object.keys(dataviews).forEach(function (dataviewName) {
        var dataview = dataviews[dataviewName];
        var dataviewSourceId = getDataviewSourceId(dataview);
        if (!Object.prototype.hasOwnProperty.call(sourceId2Node, dataviewSourceId)) {
            missingDataviewsSourceIds.push(new AnalysisError('Node with `source.id="' + dataviewSourceId + '"`' +
                ' not found in analyses for dataview "' + dataviewName + '"'));
        }
    });

    return missingDataviewsSourceIds;
}

function AnalysisError (message) {
    Error.captureStackTrace(this, this.constructor);
    this.name = this.constructor.name;
    this.type = 'analysis';
    this.message = message;
}

function getAllAffectedTablesFromSourceNodes (node) {
    var affectedTables = node.getAllInputNodes(function (node) {
        return node.getType() === 'source';
    }).reduce(function (list, node) {
        return list.concat(node.getAffectedTables());
    }, []);
    return affectedTables;
}

require('util').inherits(AnalysisError, Error);


text:
import random
class graph:
    def __init__(self):
        self.vertices = {}
    def add_node(self,myid):
        if myid in self.vertices:
            print("Node already added")
        else:
            self.vertices[myid] = set()
    def add_edge(self,id1,id2,weight):
        self.vertices[id1].add((id2,weight))
        self.vertices[id2].add((id1,weight))
    def show_graph(self):
        for key in self.vertices:
            print(str(key)+" : " + str(self.vertices[key]))
    def dfs(self,root):
        stack = [root]
        visited = set()
        seq = []
        while stack:
            curr = stack.pop()
            if curr not in visited:
                seq.append(curr)
                visited.add(curr)
                stack.extend(self.vertices[curr][0] - visited)
        return seq
    def bfs(self,root):
        queue = [root]
        visited = set()
        seq = []
        while queue:
            curr = queue.pop(0)
            if curr not in visited:
                seq.append(curr)
                visited.add(curr)
                queue.extend(self.vertices[curr][0] - visited)
        return seq
    def check_bipartite(self):
        all_vertices = self.vertices.keys()
        root = random.choice(list(all_vertices))
        colors = {}
        for key in all_vertices:
            colors[key] = -1
        colors[root] = 0
        queue = [root]
        visited = set()
        while queue:
            curr = queue.pop(0)
            curr_color = colors[curr]
            new_color = (curr_color+1)%2
            adjs = self.vertices[curr]
            visited.add(curr)
            for adj,weight in adjs:
                if colors[adj]!=-1 and colors[adj]!=new_color:
                    return False
                else:
                    colors[adj] = new_color
                if adj not in visited:
                    queue.append(adj)
        return True
    # def shortest_path(start,end):
    #     queue = [start , [start]]
    #     visited = set()
    #     while queue:
    #         curr , curr_path = queue.pop(0)
    #         for next in self.vertices

g = graph()
g.add_node(1)
g.add_node(2)
g.add_node(3)
g.add_node(4)
g.add_edge(1,4,2)
g.add_edge(1,3,1)
g.add_edge(3,2,3)
# g.add_edge(4,3,1)
print(g.check_bipartite())