text:
declare var Velocity;

export interface Handler<T extends Event> {
  (evt:T, elem:Element): void
}
export interface RenderHandler {
  (node:HTMLElement, elem:Element): void
}

export interface Element {
  t?:string
  c?:string
  id?:string
  parent?:string
  children?:Element[]
  ix?:number
  key?:string
  dirty?:boolean
  semantic?:string
  tween?: any
  enter?: any
  leave?: any
  debug?:any

  // Content
  contentEditable?:boolean
  checked?:boolean
  draggable?:boolean
  href?:string
  src?:string
  data?:any
  download?:string
  allowfullscreen?:boolean
  placeholder?:string
  selected?:boolean
  tabindex?:number
  text?:string
  strictText?: boolean
  type?:string
  value?:string
  dangerouslySetInnerHTML?:string
  target?:string

  style?: string,

  // Styles (Structure)
  flex?:number|string
  left?:number|string
  top?:number|string
  width?:number|string
  height?:number|string
  textAlign?:string
  transform?:string
  verticalAlign?:string
  zIndex?:number

  // Styles (Aesthetic)
  backgroundColor?:string
  backgroundImage?:string
  border?:string
  borderColor?:string
  borderWidth?:number|string
  borderRadius?:number|string
  color?:string
  colspan?:number
  fontFamily?:string
  fontSize?:string

  opacity?:number

  // Svg
  svg?:boolean
  x?:number|string
  y?:number|string
  dx?:number|string
  dy?:number|string
  cx?:number|string
  cy?:number|string
  r?:number|string
  d?:number|string
  fill?:string
  stroke?:string
  strokeWidth?:string
  startOffset?:number|string
  textAnchor?:string
  viewBox?:string
  xlinkhref?:string

  // Events
  dblclick?:Handler<MouseEvent>
  click?:Handler<MouseEvent>
  contextmenu?:Handler<MouseEvent>
  mousedown?:Handler<MouseEvent>
  mousemove?:Handler<MouseEvent>
  mouseup?:Handler<MouseEvent>
  mouseover?:Handler<MouseEvent>
  mouseout?:Handler<MouseEvent>
  mouseleave?:Handler<MouseEvent>
  mousewheel?:Handler<MouseEvent>
  dragover?:Handler<MouseEvent>
  dragstart?:Handler<MouseEvent>
  dragend?:Handler<MouseEvent>
  drag?:Handler<MouseEvent>
  drop?:Handler<MouseEvent>
  scroll?:Handler<MouseEvent>
  focus?:Handler<FocusEvent>
  blur?:Handler<FocusEvent>
  input?:Handler<Event>
  change?:Handler<Event>
  keyup?:Handler<KeyboardEvent>
  keydown?:Handler<KeyboardEvent>

  postRender?:RenderHandler

  [attr:string]: any
}

function now() {
  if(window.performance) {
    return window.performance.now();
  }
  return (new Date()).getTime();
}

function shallowEquals(a, b) {
  if(a === b) return true;
  if(!a || !b) return false;
  for(var k in a) {
    if(a[k] !== b[k]) return false;
  }
  for(var k in b) {
    if(b[k] !== a[k]) return false;
  }
  return true;
}

function postAnimationRemove(elements) {
  for(let elem of elements) {
    if(elem.parentNode) elem.parentNode.removeChild(elem);
  }
}

export class Renderer {
  // @TODO: A more performant implementation would have a way of rendering subtrees and just have a lambda Renderer to compile into
  static _compileRenderer:{[id:string]: Renderer} = {};
  static compile(elem:Element) {
    if(!elem.id) throw new Error("Cannot compile element with id " + elem.id);
    let renderer = Renderer._compileRenderer[elem.id];
    if(!renderer) renderer = Renderer._compileRenderer[elem.id] = new Renderer();
    renderer.render([elem]);
    return renderer.elementCache[elem.id];
  }

  content: HTMLElement;
  elementCache: {[id:string]: HTMLElement};
  prevTree:{[id:string]: Element};
  tree:{[id:string]: Element};
  postRenders: Element[];
  lastDiff: {adds: string[], updates: {}};
  queued: boolean;
  handleEvent: (any);
  constructor() {
    this.content = document.createElement("div");
    this.content.className = "__root";
    this.elementCache = { "__root": this.content };
    this.prevTree = {};
    this.tree = {};
    this.postRenders = [];
    this.lastDiff = {adds: [], updates: {}};
    var self = this;
    this.handleEvent = function handleEvent(e: Event) {
      var id = (e.currentTarget || e.target)["_id"];
      var elem = self.tree[id];
      if (!elem) return;
      var handler = elem[e.type];
      if (handler) { handler(e, elem); }
    };
  }
  reset() {
    this.prevTree = this.tree;
    this.tree = {};
    this.postRenders = [];
  }

  domify() {
    var fakePrev:Element = {}; //create an empty object once instead of every instance of the loop
    var elements = this.tree;
    var prevElements = this.prevTree;
    var diff = this.lastDiff;
    var adds = diff.adds;
    var updates = diff.updates;
    var elemKeys = Object.keys(updates);
    var elementCache = this.elementCache;
    var tempTween:any = {};

    //Create all the new elements to ensure that they're there when they need to be
    //parented
    for(var i = 0, len = adds.length; i < len; i++) {
      var id = adds[i];
      var cur = elements[id];
      var div: any;
      if (cur.svg) {
        div = document.createElementNS("http://www.w3.org/2000/svg", cur.t || "rect");
      } else {
        div = document.createElement(cur.t || "div");
      }
      div._id = id;
      elementCache[id] = div;
      if(cur.enter) {
        if(cur.enter.delay) {
          cur.enter.display = "auto";
          div.style.display = "none";
        }

        Velocity(div, cur.enter, cur.enter);

      }
    }

    for(var i = 0, len = elemKeys.length; i < len; i++) {
      var id = elemKeys[i];
      var cur = elements[id];
      var prev = prevElements[id] || fakePrev;
      var type = updates[id];
      var div;
      if(type === "replaced") {
        var me = elementCache[id];
        if (me.parentNode) me.parentNode.removeChild(me);
        if (cur.svg) {
          div = document.createElementNS("http://www.w3.org/2000/svg", cur.t || "rect");
        } else {
          div = document.createElement(cur.t || "div");
        }
        prev = fakePrev;
        div._id = id;
        elementCache[id] = div;
      } else if (type === "removed") {
        //NOTE: Batching the removes such that you only remove the parent
        //didn't actually make this faster surprisingly. Given that this
        //strategy is much simpler and there's no noticable perf difference
        //we'll just do the dumb thing and remove all the children one by one.
        var me = elementCache[id]
        if(prev.leave) {
          prev.leave.complete = postAnimationRemove;
          if(prev.leave.absolute) {
            me.style.position = "absolute";
          }
          Velocity(me, prev.leave, prev.leave);
        }
        else if(me.parentNode) me.parentNode.removeChild(me);
        elementCache[id] = null;
        continue;
      } else {
        div = elementCache[id];
      }

      var style = div.style;
      if(cur.c !== prev.c) div.className = cur.c;
      if(cur.draggable !== prev.draggable) div.draggable = cur.draggable === undefined ? null : "true";
      if(cur.contentEditable !== prev.contentEditable) div.contentEditable = cur.contentEditable !== undefined ? JSON.stringify(cur.contentEditable) : "inherit";
      if(cur.colspan !== prev.colspan) div.colSpan = cur.colspan;
      if(cur.placeholder !== prev.placeholder) div.setAttribute("placeholder", cur.placeholder);
      if(cur.selected !== prev.selected) div.selected = cur.selected;
      if((cur.value !== prev.value || cur.strictText) && div.value !== cur.value) div.value = cur.value;
      if(cur.t === "input" && cur.type !== prev.type) div.type = cur.type;
      if(cur.t === "input" && cur.checked !== prev.checked) div.checked = cur.checked;
      if((cur.text !== prev.text || cur.strictText) && div.textContent !== cur.text) div.textContent = cur.text === undefined ? "" : cur.text;
      if(cur.tabindex !== prev.tabindex) div.setAttribute("tabindex", cur.tabindex);
      if(cur.href !== prev.href) div.setAttribute("href", cur.href);
      if(cur.src !== prev.src) div.setAttribute("src", cur.src);
      if(cur.target !== prev.target) div.setAttribute("target", cur.target);
      if(cur.data !== prev.data) div.setAttribute("data", cur.data);
      if(cur.download !== prev.download) div.setAttribute("download", cur.download);
      if(cur.allowfullscreen !== prev.allowfullscreen) div.setAttribute("allowfullscreen", cur.allowfullscreen);

      // animateable properties
      var tween = cur.tween || tempTween;
      if(cur.flex !== prev.flex) {
        if(tween.flex) tempTween.flex = cur.flex;
        else style.flex = cur.flex === undefined ? "" : cur.flex;
      }
      if(cur.left !== prev.left) {
          if(tween.left) tempTween.left = cur.left;
          else style.left = cur.left === undefined ? "" : cur.left;
      }
      if(cur.top !== prev.top) {
        if(tween.top) tempTween.top = cur.top;
        else style.top = cur.top === undefined ? "" : cur.top;
      }
      if(cur.height !== prev.height) {
        if(tween.height) tempTween.height = cur.height;
        else style.height = cur.height === undefined ? "auto" : cur.height;
      }
      if(cur.width !== prev.width) {
        if(tween.width) tempTween.width = cur.width;
        else style.width = cur.width === undefined ? "auto" : cur.width;
      }
      if(cur.zIndex !== prev.zIndex) {
        if(tween.zIndex) tempTween.zIndex = cur.zIndex;
        else style.zIndex = cur.zIndex;
      }
      if(cur.backgroundColor !== prev.backgroundColor) {
        if(tween.backgroundColor) tempTween.backgroundColor = cur.backgroundColor;
        else style.backgroundColor = cur.backgroundColor || "transparent";
      }
      if(cur.borderColor !== prev.borderColor) {
        if(tween.borderColor) tempTween.borderColor = cur.borderColor;
        else style.borderColor = cur.borderColor || "none";
      }
      if(cur.borderWidth !== prev.borderWidth) {
        if(tween.borderWidth) tempTween.borderWidth = cur.borderWidth;
        else style.borderWidth = cur.borderWidth || 0;
      }
      if(cur.borderRadius !== prev.borderRadius) {
        if(tween.borderRadius) tempTween.borderRadius = cur.borderRadius;
        else style.borderRadius = (cur.borderRadius || 0) + "px";
      }
      if(cur.opacity !== prev.opacity) {
        if(tween.opacity) tempTween.opacity = cur.opacity;
        else style.opacity = cur.opacity === undefined ? 1 : cur.opacity;
      }
      if(cur.fontSize !== prev.fontSize) {
        if(tween.fontSize) tempTween.fontSize = cur.fontSize;
        else style.fontSize = cur.fontSize;
      }
      if(cur.color !== prev.color) {
        if(tween.color) tempTween.color = cur.color;
        else style.color = cur.color || "inherit";
      }

      let animKeys = Object.keys(tempTween);
      if(animKeys.length) {
        Velocity(div, tempTween, tween);
        tempTween = {};
      }

      // non-animation style properties
      if(cur.backgroundImage !== prev.backgroundImage) style.backgroundImage = `url('${cur.backgroundImage}')`;
      if(cur.border !== prev.border) style.border = cur.border || "none";
      if(cur.textAlign !== prev.textAlign) {
        style.alignItems = cur.textAlign;
        if(cur.textAlign === "center") {
          style.textAlign = "center";
        } else if(cur.textAlign === "flex-end") {
          style.textAlign = "right";
        } else {
          style.textAlign = "left";
        }
      }
      if(cur.verticalAlign !== prev.verticalAlign) style.justifyContent = cur.verticalAlign;
      if(cur.fontFamily !== prev.fontFamily) style.fontFamily = cur.fontFamily || "inherit";
      if(cur.transform !== prev.transform) style.transform = cur.transform || "none";
      if(cur.style !== prev.style) div.setAttribute("style", cur.style);

      if(cur.dangerouslySetInnerHTML !== prev.dangerouslySetInnerHTML) div.innerHTML = cur.dangerouslySetInnerHTML;

      // debug/programmatic properties
      if(cur.semantic !== prev.semantic) div.setAttribute("data-semantic", cur.semantic);
      if(cur.debug !== prev.debug) div.setAttribute("data-debug", cur.debug);

      // SVG properties
      if(cur.svg) {
        if(cur.fill !== prev.fill) div.setAttributeNS(null, "fill", cur.fill);
        if(cur.stroke !== prev.stroke) div.setAttributeNS(null, "stroke", cur.stroke);
        if(cur.strokeWidth !== prev.strokeWidth) div.setAttributeNS(null, "stroke-width", cur.strokeWidth);
        if(cur.d !== prev.d) div.setAttributeNS(null, "d", cur.d);
        if(cur.c !== prev.c) div.setAttributeNS(null, "class", cur.c);
        if(cur.x !== prev.x)  div.setAttributeNS(null, "x", cur.x);
        if(cur.y !== prev.y) div.setAttributeNS(null, "y", cur.y);
        if(cur.dx !== prev.dx)  div.setAttributeNS(null, "dx", cur.dx);
        if(cur.dy !== prev.dy) div.setAttributeNS(null, "dy", cur.dy);
        if(cur.cx !== prev.cx)  div.setAttributeNS(null, "cx", cur.cx);
        if(cur.cy !== prev.cy) div.setAttributeNS(null, "cy", cur.cy);
        if(cur.r !== prev.r) div.setAttributeNS(null, "r", cur.r);
        if(cur.height !== prev.height) div.setAttributeNS(null, "height", cur.height);
        if(cur.width !== prev.width)  div.setAttributeNS(null, "width", cur.width);
        if(cur.xlinkhref !== prev.xlinkhref)  div.setAttributeNS('http://www.w3.org/1999/xlink', "href", cur.xlinkhref);
        if(cur.startOffset !== prev.startOffset) div.setAttributeNS(null, "startOffset", cur.startOffset);
        if(cur.id !== prev.id) div.setAttributeNS(null, "id", cur.id);
        if(cur.viewBox !== prev.viewBox) div.setAttributeNS(null, "viewBox", cur.viewBox);
        if(cur.transform !== prev.transform) div.setAttributeNS(null, "transform", cur.transform);
        if(cur.draggable !== prev.draggable) div.setAttributeNS(null, "draggable", cur.draggable);
        if(cur.textAnchor !== prev.textAnchor) div.setAttributeNS(null, "text-anchor", cur.textAnchor);
      }

      //events
      if(cur.dblclick !== prev.dblclick) div.ondblclick = cur.dblclick !== undefined ? this.handleEvent : undefined;
      if(cur.click !== prev.click) div.onclick = cur.click !== undefined ? this.handleEvent : undefined;
      if(cur.contextmenu !== prev.contextmenu) div.oncontextmenu = cur.contextmenu !== undefined ? this.handleEvent : undefined;
      if(cur.mousedown !== prev.mousedown) div.onmousedown = cur.mousedown !== undefined ? this.handleEvent : undefined;
      if(cur.mousemove !== prev.mousemove) div.onmousemove = cur.mousemove !== undefined ? this.handleEvent : undefined;
      if(cur.mouseup !== prev.mouseup) div.onmouseup = cur.mouseup !== undefined ? this.handleEvent : undefined;
      if(cur.mouseover !== prev.mouseover) div.onmouseover = cur.mouseover !== undefined ? this.handleEvent : undefined;
      if(cur.mouseout !== prev.mouseout) div.onmouseout = cur.mouseout !== undefined ? this.handleEvent : undefined;
      if(cur.mouseleave !== prev.mouseleave) div.onmouseleave = cur.mouseleave !== undefined ? this.handleEvent : undefined;
      if(cur.mousewheel !== prev.mousewheel) div.onmouseheel = cur.mousewheel !== undefined ? this.handleEvent : undefined;
      if(cur.dragover !== prev.dragover) div.ondragover = cur.dragover !== undefined ? this.handleEvent : undefined;
      if(cur.dragstart !== prev.dragstart) div.ondragstart = cur.dragstart !== undefined ? this.handleEvent : undefined;
      if(cur.dragend !== prev.dragend) div.ondragend = cur.dragend !== undefined ? this.handleEvent : undefined;
      if(cur.drag !== prev.drag) div.ondrag = cur.drag !== undefined ? this.handleEvent : undefined;
      if(cur.drop !== prev.drop) div.ondrop = cur.drop !== undefined ? this.handleEvent : undefined;
      if(cur.scroll !== prev.scroll) div.onscroll = cur.scroll !== undefined ? this.handleEvent : undefined;
      if(cur.focus !== prev.focus) div.onfocus = cur.focus !== undefined ? this.handleEvent : undefined;
      if(cur.blur !== prev.blur) div.onblur = cur.blur !== undefined ? this.handleEvent : undefined;
      if(cur.input !== prev.input) div.oninput = cur.input !== undefined ? this.handleEvent : undefined;
      if(cur.change !== prev.change) div.onchange = cur.change !== undefined ? this.handleEvent : undefined;
      if(cur.keyup !== prev.keyup) div.onkeyup = cur.keyup !== undefined ? this.handleEvent : undefined;
      if(cur.keydown !== prev.keydown) div.onkeydown = cur.keydown !== undefined ? this.handleEvent : undefined;

      if(type === "added" || type === "replaced" || type === "moved") {
        var parentEl = elementCache[cur.parent];
        if(parentEl) {
          if(cur.ix >= parentEl.children.length) {
            parentEl.appendChild(div);
          } else {
            parentEl.insertBefore(div, parentEl.children[cur.ix]);
          }
        }
      }
    }
  }

  diff() {
    var a = this.prevTree;
    var b = this.tree;
    var as = Object.keys(a);
    var bs = Object.keys(b);
    var updated = {};
    var adds = [];
    for(var i = 0, len = as.length; i < len; i++) {
      var id = as[i];
      var curA = a[id];
      var curB = b[id];
      if(curB === undefined) {
        updated[id] = "removed";
        continue;
      }
      if(curA.t !== curB.t) {
        updated[id] = "replaced";
        continue;
      }
      if(curA.ix !== curB.ix || curA.parent !== curB.parent) {
        updated[id] = "moved";
        continue;
      }

      if(!curB.dirty
          && curA.c === curB.c
          && curA.key === curB.key
          && curA.dangerouslySetInnerHTML === curB.dangerouslySetInnerHTML
          && curA.tabindex === curB.tabindex
          && curA.href === curB.href
          && curA.src === curB.src
          && curA.data === curB.data
          && curA.download === curB.download
          && curA.allowfullscreen === curB.allowfullscreen
          && curA.placeholder === curB.placeholder
          && curA.selected === curB.selected
          && curA.draggable === curB.draggable
          && curA.contentEditable === curB.contentEditable
          && curA.value === curB.value
          && curA.target === curB.target
          && curA.type === curB.type
          && curA.checked === curB.checked
          && curA.text === curB.text
          && curA.top === curB.top
          && curA.flex === curB.flex
          && curA.left === curB.left
          && curA.width === curB.width
          && curA.height === curB.height
          && curA.zIndex === curB.zIndex
          && curA.backgroundColor === curB.backgroundColor
          && curA.backgroundImage === curB.backgroundImage
          && curA.color === curB.color
          && curA.colspan === curB.colspan
          && curA.border === curB.border
          && curA.borderColor === curB.borderColor
          && curA.borderWidth === curB.borderWidth
          && curA.borderRadius === curB.borderRadius
          && curA.opacity === curB.opacity
          && curA.fontFamily === curB.fontFamily
          && curA.fontSize === curB.fontSize
          && curA.textAlign === curB.textAlign
          && curA.transform === curB.transform
          && curA.verticalAlign === curB.verticalAlign
          && curA.semantic === curB.semantic
          && curA.debug === curB.debug
          && curA.style === curB.style
          && (curB.svg === undefined || (
              curA.x === curB.x
              && curA.y === curB.y
              && curA.dx === curB.dx
              && curA.dy === curB.dy
              && curA.cx === curB.cx
              && curA.cy === curB.cy
              && curA.r === curB.r
              && curA.d === curB.d
              && curA.fill === curB.fill
              && curA.stroke === curB.stroke
              && curA.strokeWidth === curB.strokeWidth
              && curA.startOffset === curB.startOffset
              && curA.textAnchor === curB.textAnchor
              && curA.viewBox === curB.viewBox
              && curA.xlinkhref === curB.xlinkhref))
              ) {
        continue;
      }
      updated[id] = "updated";
    }
    for(var i = 0, len = bs.length; i < len; i++) {
      var id = bs[i];
      var curA = a[id];
      if(curA === undefined) {
        adds.push(id);
        updated[id] = "added";
        continue;
      }
    }
    this.lastDiff = {adds: adds, updates: updated};
    return this.lastDiff;
  }

  prepare(root:Element) {
    var elemLen = 1;
    var tree = this.tree;
    var elements = [root];
    var elem:Element;
    for(var elemIx = 0; elemIx < elemLen; elemIx++) {
      elem = elements[elemIx];
      if(elem.parent === undefined) elem.parent = "__root";
      if(elem.id === undefined) elem.id = "__root__" + elemIx;
      tree[elem.id] = elem;
      if(elem.postRender !== undefined) {
        this.postRenders.push(elem);
      }
      var children = elem.children;
      if(children !== undefined) {
        for(var childIx = 0, len = children.length; childIx < len; childIx++) {
          var child = children[childIx];
          if(child === undefined) continue;
          if(child.id === undefined) { child.id = elem.id + "__" + childIx; }
          if(child.ix === undefined) { child.ix = childIx; }
          if(child.parent === undefined) { child.parent = elem.id; }
          elements.push(child);
          elemLen++;
        }
      }
    }
    return tree;
  }

  postDomify() {
    var postRenders = this.postRenders;
    var diff = this.lastDiff.updates;
    var elementCache = this.elementCache;
    for(var i = 0, len = postRenders.length; i < len; i++) {
      var elem = postRenders[i];
      var id = elem.id;
      if(diff[id] === "updated" || diff[id] === "added" || diff[id] === "replaced" || elem.dirty || diff[id] === "moved") {
        elem.postRender(elementCache[elem.id], elem);
      }
    }
  }

  render(elems:Element[]) {
      this.reset();
    // We sort elements by depth to allow them to be self referential.
    elems.sort((a, b) => (a.parent ? a.parent.split("__").length : 0) - (b.parent ? b.parent.split("__").length : 0));
    let start = now();
    for(let elem of elems) {
      let post = this.prepare(elem);

    }
    let prepare = now();
    let d = this.diff();
    let diff = now();
    this.domify();
    let domify = now();
    this.postDomify();
    let postDomify = now();
    let time = now() - start;
    if(time > 5) {
      console.log("slow render (> 5ms): ", time, {
        prepare: prepare - start,
        diff: diff - prepare,
        domify: domify - diff,
        postDomify: postDomify - domify
      });
    }
  }
}


text:
:- module(bc_api_config, []).

/** <module> HTTP handlers for config entry management */

:- use_module(library(arouter)).
:- use_module(library(dict_schema)).

:- use_module(bc_view).
:- use_module(bc_api_io).
:- use_module(bc_api_auth).
:- use_module(bc_api_actor).
:- use_module(bc_data_config).

% Gets config values.

:- route_get(api/configs,
    bc_auth, config_list).

config_list:-
    bc_actor(Actor),
    bc_config_list(Actor, List),
    bc_reply_success(List).

% Updates the config value.

:- route_put(api/config,
    bc_auth, config_update).

config_update:-
    bc_actor(Actor),
    bc_read_by_schema(bc_config, Config),
    Name = Config.name,
    Value = Config.value,
    bc_config_set_api(Actor, Name, Value),
    bc_view_purge_cache,
    bc_reply_success(Name).

% Updates the list of config values.

:- route_put(api/configs,
    bc_auth, config_update_list).

config_update_list:-
    bc_actor(Actor),
    bc_read_by_schema(bc_config_list, List),
    bc_config_set_list_api(Actor, List),
    bc_view_purge_cache,
    bc_reply_success(true).

% Generic config entry.

:- register_schema(bc_config, _{
    type: dict,
    tag: config,
    keys: _{
        name: atom,
        value: [ atom, number ]
    }
}).

:- register_schema(bc_config_list, _{
    type: list,
    items: bc_config
}).

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division, print_function, absolute_import

import os

import numpy as np
from numpy.testing import assert_allclose
from scipy._lib._numpy_compat import suppress_warnings
import pytest
from scipy import stats

from .test_continuous_basic import distcont

# this is not a proper statistical test for convergence, but only
# verifies that the estimate and true values don't differ by too much

fit_sizes = [1000, 5000]  # sample sizes to try

thresh_percent = 0.25  # percent of true parameters for fail cut-off
thresh_min = 0.75  # minimum difference estimate - true to fail test

failing_fits = [
        'burr',
        'chi2',
        'gausshyper',
        'genexpon',
        'gengamma',
        'kappa4',
        'ksone',
        'mielke',
        'ncf',
        'ncx2',
        'pearson3',
        'powerlognorm',
        'truncexpon',
        'tukeylambda',
        'vonmises',
        'wrapcauchy',
        'levy_stable',
        'trapz'
]

# Don't run the fit test on these:
skip_fit = [
    'erlang',  # Subclass of gamma, generates a warning.
]

def cases_test_cont_fit():
    # this tests the closeness of the estimated parameters to the true
    # parameters with fit method of continuous distributions
    # Note: is slow, some distributions don't converge with sample size <= 10000
    for distname, arg in distcont:
        if distname not in skip_fit:
            yield distname, arg

@pytest.mark.slow
@pytest.mark.parametrize('distname,arg', cases_test_cont_fit())
def test_cont_fit(distname, arg):
    if distname in failing_fits:
        # Skip failing fits unless overridden
        xfail = True
        try:
            xfail = not int(os.environ['SCIPY_XFAIL'])
        except:
            pass
        if xfail:
            msg = "Fitting %s doesn't work reliably yet" % distname
            msg += " [Set environment variable SCIPY_XFAIL=1 to run this test nevertheless.]"
            pytest.xfail(msg)

    distfn = getattr(stats, distname)

    truearg = np.hstack([arg, [0.0, 1.0]])
    diffthreshold = np.max(np.vstack([truearg*thresh_percent,
                                      np.ones(distfn.numargs+2)*thresh_min]),
                           0)

    for fit_size in fit_sizes:
        # Note that if a fit succeeds, the other fit_sizes are skipped
        np.random.seed(1234)

        with np.errstate(all='ignore'), suppress_warnings() as sup:
            sup.filter(category=DeprecationWarning, message=".*frechet_")
            rvs = distfn.rvs(size=fit_size, *arg)
            est = distfn.fit(rvs)  # start with default values

        diff = est - truearg

        # threshold for location
        diffthreshold[-2] = np.max([np.abs(rvs.mean())*thresh_percent,thresh_min])

        if np.any(np.isnan(est)):
            raise AssertionError('nan returned in fit')
        else:
            if np.all(np.abs(diff) <= diffthreshold):
                break
    else:
        txt = 'parameter: %s\n' % str(truearg)
        txt += 'estimated: %s\n' % str(est)
        txt += 'diff     : %s\n' % str(diff)
        raise AssertionError('fit not very good in %s\n' % distfn.name + txt)

def _check_loc_scale_mle_fit(name, data, desired, atol=None):
    d = getattr(stats, name)
    actual = d.fit(data)[-2:]
    assert_allclose(actual, desired, atol=atol,
                    err_msg='poor mle fit of (loc, scale) in %s' % name)

def test_non_default_loc_scale_mle_fit():
    data = np.array([1.01, 1.78, 1.78, 1.78, 1.88, 1.88, 1.88, 2.00])
    _check_loc_scale_mle_fit('uniform', data, [1.01, 0.99], 1e-3)
    _check_loc_scale_mle_fit('expon', data, [1.01, 0.73875], 1e-3)

def test_expon_fit():
    """gh-6167"""
    data = [0, 0, 0, 0, 2, 2, 2, 2]
    phat = stats.expon.fit(data, floc=0)
    assert_allclose(phat, [0, 1.0], atol=1e-3)


text:
[![Build Status](https://travis-ci.org/guidance-guarantee-programme/record_of_guidance.svg)](https://travis-ci.org/guidance-guarantee-programme/record_of_guidance)

Record of guidance from [Pension Wise].

## Prerequisites

* [Bundler]
* [Git]
* [Node.js][Node]
* [NPM]
* [PostgreSQL]
* [Redis]
* [Ruby 2.2.1][Ruby]

## Installation

Clone the repository:

```sh
$ git clone https://github.com/guidance-guarantee-programme/record_of_guidance.git
```

Setup the application:

```sh
$ ./bin/setup
```

## Usage

To start the application:

```sh
$ ./bin/foreman s
```

## Heroku

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

## Contributing

Please see the [contributing guidelines](/CONTRIBUTING.md).

[bundler]: http://bundler.io
[git]: http://git-scm.com
[heroku]: https://www.heroku.com
[node]: http://nodejs.org
[npm]: https://www.npmjs.org
[pension wise]: https://www.gov.uk/pensionwise
[postgresql]: http://www.postgresql.org
[redis]: http://redis.io
[ruby]: http://www.ruby-lang.org/en


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>8. Errors and Exceptions — Python 2.7.12 documentation</title>

    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.12 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 2.7.12 documentation" href="../contents.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="9. Classes" href="classes.html" />
    <link rel="prev" title="7. Input and Output" href="inputoutput.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          2.7.12
          Documentation »

The Python Tutorial »

8. Errors and Exceptions¶

Until now error messages haven’t been more than mentioned, but if you have tried
out the examples you have probably seen some.  There are (at least) two
distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors¶

Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:

>>> while True print 'Hello world'
  File "<stdin>", line 1, in ?
    while True print 'Hello world'
                   ^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at
the earliest point in the line where the error was detected.  The error is
caused by (or at least detected at) the token preceding the arrow: in the
example, the error is detected at the keyword print, since a colon
(':') is missing before it.  File name and line number are printed so you
know where to look in case the input came from a script.

8.2. Exceptions¶

Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called exceptions and are not unconditionally fatal: you will soon learn
how to handle them in Python programs.  Most exceptions are not handled by
programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are ZeroDivisionError, NameError and TypeError.
The string printed as the exception type is the name of the built-in exception
that occurred.  This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what
caused it.

The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions¶

It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using Control-C or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the KeyboardInterrupt exception.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...

The try statement works as follows.

First, the try clause (the statement(s) between the try and
except keywords) is executed.

If no exception occurs, the except clause is skipped and execution of the
try statement is finished.

If an exception occurs during execution of the try clause, the rest of the
clause is skipped.  Then if its type matches the exception named after the
except keyword, the except clause is executed, and then execution
continues after the try statement.

If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler is
found, it is an unhandled exception and execution stops with a message as
shown above.

A try statement may have more than one except clause, to specify
handlers for different exceptions.  At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same try statement.  An except clause may
name multiple exceptions as a parenthesized tuple, for example:

... except (RuntimeError, TypeError, NameError):
...     pass

Note that the parentheses around this tuple are required, because
except ValueError, e: was the syntax used for what is normally
written as except ValueError as e: in modern Python (described
below). The old syntax is still supported for backwards compatibility.
This means except RuntimeError, TypeError is not equivalent to
except (RuntimeError, TypeError): but to except RuntimeError as
TypeError: which is not what you want.

The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way!  It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

The try ... except statement has an optional else
clause, which, when present, must follow all except clauses.  It is useful for
code that must be executed if the try clause does not raise an exception.  For
example:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

The use of the else clause is better than adding additional code to
the try clause because it avoids accidentally catching an exception
that wasn’t raised by the code being protected by the try ...
except statement.

When an exception occurs, it may have an associated value, also known as the
exception’s argument. The presence and type of the argument depend on the
exception type.

The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
instance.args.  For convenience, the exception instance defines
__str__() so the arguments can be printed directly without having to
reference .args.

One may also instantiate an exception first before raising it and add any
attributes to it as desired.

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print type(inst)     # the exception instance
...     print inst.args      # arguments stored in .args
...     print inst           # __str__ allows args to be printed directly
...     x, y = inst.args
...     print 'x =', x
...     print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

If an exception has an argument, it is printed as the last part (‘detail’) of
the message for unhandled exceptions.

Exception handlers don’t just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:

>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as detail:
...     print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero

8.4. Raising Exceptions¶

The raise statement allows the programmer to force a specified
exception to occur. For example:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere

The sole argument to raise indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from Exception).

If you need to determine whether an exception was raised but don’t intend to
handle it, a simpler form of the raise statement allows you to
re-raise the exception:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

8.5. User-defined Exceptions¶

Programs may name their own exceptions by creating a new exception class (see
Classes for more about Python classes).  Exceptions should typically
be derived from the Exception class, either directly or indirectly.  For
example:

>>> class MyError(Exception):
...     def __init__(self, value):
...         self.value = value
...     def __str__(self):
...         return repr(self.value)
...
>>> try:
...     raise MyError(2*2)
... except MyError as e:
...     print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

In this example, the default __init__() of Exception has been
overridden.  The new behavior simply creates the value attribute.  This
replaces the default behavior of creating the args attribute.

Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception.  When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expr -- input expression in which the error occurred
        msg  -- explanation of the error
    """

    def __init__(self, expr, msg):
        self.expr = expr
        self.msg = msg

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        prev -- state at beginning of transition
        next -- attempted new state
        msg  -- explanation of why the specific transition is not allowed
    """

    def __init__(self, prev, next, msg):
        self.prev = prev
        self.next = next
        self.msg = msg

Most exceptions are defined with names that end in “Error,” similar to the
naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may
occur in functions they define.  More information on classes is presented in
chapter Classes.

8.6. Defining Clean-up Actions¶

The try statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances.  For
example:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print 'Goodbye, world!'
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in ?

A finally clause is always executed before leaving the try
statement, whether an exception has occurred or not. When an exception has
occurred in the try clause and has not been handled by an
except clause (or it has occurred in a except or
else clause), it is re-raised after the finally clause has
been executed.  The finally clause is also executed “on the way out”
when any other clause of the try statement is left via a
break, continue or return statement.  A more
complicated example (having except and finally clauses in
the same try statement works as of Python 2.5):

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event.  The
TypeError raised by dividing two strings is not handled by the
except clause and therefore re-raised after the finally
clause has been executed.

In real world applications, the finally clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.

8.7. Predefined Clean-up Actions¶

Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen.

for line in open("myfile.txt"):
    print line,

The problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. This is not an issue in
simple scripts, but can be a problem for larger applications. The
with statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly.

with open("myfile.txt") as f:
    for line in f:
        print line,

After the statement is executed, the file f is always closed, even if a
problem was encountered while processing the lines. Other objects which provide
predefined clean-up actions will indicate this in their documentation.

Table Of Contents

8. Errors and Exceptions

8.1. Syntax Errors

8.2. Exceptions

8.3. Handling Exceptions

8.4. Raising Exceptions

8.5. User-defined Exceptions

8.6. Defining Clean-up Actions

8.7. Predefined Clean-up Actions

Previous topic

7. Input and Output

Next topic

9. Classes

This Page

Report a Bug

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python »

          2.7.12
          Documentation »

The Python Tutorial »

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jun 25, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
package config

import (
	"os"
	"path/filepath"
)

func defaultDirectory(dirRoot string) string {
	base := filepath.Base(os.Args[0])
	ext := filepath.Ext(base)

	name := base[0 : len(base)-len(ext)]

	return filepath.Join("/", dirRoot, name)
}

func defaultConfDir() string {
	return defaultDirectory("/etc")
}

func defaultLibDir() string {
	return defaultDirectory("/var/lib")
}


text:
#ifndef __XM_UTILS_H__
#define __XM_UTILS_H__

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "XMTypes.h"

/**
 * XMUtils provides useful service functionality which
 * does not belong at another place
 **/
@interface XMUtils : NSObject {

@private
  SCDynamicStoreRef dynamicStore;
  NSArray *networkInterfaces;

  BOOL doesUpdateSTUNInformation;
  BOOL doesUpdateCheckipInformation;

  XMNATType natType;
  NSString *stunPublicAddress;
  NSString *checkipPublicAddress;

  NSURLConnection *checkipURLConnection;
  NSMutableData *checkipURLData;
  NSTimer *checkipTimer;
}

/**
 * Returns the shared singleton instance of XMUtils
 **/
+ (XMUtils *)sharedInstance;

/**
 * Returns the local network interfaces for this computer
 **/
- (NSArray *)networkInterfaces;

/**
 * Returns whether the given IP address is a local address.
 **/
- (BOOL)isLocalAddress:(NSString *)address;

/**
 * Returns the type of NAT detected.
 * The value returned may depend on the STUN settings of the currently
 * active preferences set in XMCallManager.
 * If a STUN-Server is used, returns the NAT-Type returned by the
 * STUN-Server. If no STUN-Server is used, checks whether the public
 * address is contained is found in the localAddresses array. If so,
 * returns XMNATType_NoNAT. Else, returns XMNATType_UnknownNAT
 **/
- (XMNATType)natType;

/**
 * Returns the public address as determined either by STUN
 * or by the checkip - address lookup
 **/
- (NSString *)publicAddress;

/**
 * Updates the network information
 **/
- (void)updateNetworkInformation;

@end

@interface XMNetworkInterface : NSObject {

@private
  NSString *ipAddress;
  NSString *name;
}

- (id)initWithIPAddress:(NSString *)ipAddress name:(NSString *)name;
- (NSString *)ipAddress;
- (NSString *)name;

@end

/**
 * checks whether phoneNumber is a phone number and consists of only
 * digits, white space and '(' ')' '+' or '-'
 **/
BOOL XMIsPhoneNumber(NSString *phoneNumber);

/**
 * checks whether phoneNumber is a phone number, similar
 * to XMIsPhoneNumber, but must only contain digits
 **/
BOOL XMIsPlainPhoneNumber(NSString *phoneNumber);

/**
 * checks whether address is an ip address in the form
 * xxx.xxx.xxx.xxx (IPv4)
 **/
BOOL XMIsIPAddress(NSString *address);

/**
 * Returns an NSSize containing the width and height
 * of the specified video size
 **/
NSSize XMVideoSizeToDimensions(XMVideoSize videoSize);

/**
 * Returns the video size corresponding to the size argument.
 * Returns XMVideoSize_NoVideo in case size does not correspond
 * to a "valid" video size
 **/
XMVideoSize XMDimensionsToVideoSize(NSSize dimensions);

/**
 * calculates the other dimension from the given dimension.
 * Since different video sizes may have different aspect ratios,
 * the videoSize argument defines which aspect ration is used.
 **/
float XMGetVideoHeightForWidth(float width, XMVideoSize videoSize);
float XMGetVideoWidthForHeight(float height, XMVideoSize videoSize);

/**
 * Logs the message given by string to the debug log
 **/
void XMLogMessage(NSString *message);

/**
 * Constructs an address-of-record string based on host and username.
 **/
NSString *XMGetAddressOfRecord(NSString *domain, NSString *username);

#endif // __XM_UTILS_H__


text:
{% strip %}
    <title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="../dist/img/favicon.ico">

    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../dist/img/apple-touch-icon-precomposed-152.png">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../dist/img/apple-touch-icon-precomposed-144.png">

    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="../dist/img/apple-touch-icon-precomposed-76.png">

    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../dist/img/apple-touch-icon-precomposed-72.png">

    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="../dist/img/apple-touch-icon-precomposed-180.png">

    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../dist/img/apple-touch-icon-precomposed-114.png">

    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="../dist/img/apple-touch-icon-precomposed-57.png">
    <link rel="stylesheet" href="{{site.url-css-main}}" >
    <link rel="stylesheet" href="{{site.url-css-additions}}" >
    {% if page.css-extra %}<link href="{% if page.url-css-extra %}{{ page.url-css-extra }}{% else %}{{ site.url-css-extra }}{% endif %}" rel="stylesheet" media="screen, print">{% endif %}

    {% if page.url-js-extra %}{% for urlextrajs in page.url-js-extra %}

    {% endfor %}{% endif %}

  {% if page.full-page %}

    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">

    </button>

    {% if page.alt-layout %}The alternate layouts are not officially supported by Patternfly.  {% endif %}These examples are included for development testing purposes.  For official documentation, see https://www.patternfly.org and http://getbootstrap.com.

{% endif  %}{% endstrip %}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: jgutix
 * Date: 07-16-13
 * Time: 03:01 PM
 */
class Dictionary_entries_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function set_create()
    {
        $data = array(
            'term' => $this->input->post('term'),
            'chapter_id' => $this->input->post('chapter_id'),
            'language' => $this->input->post('language_id')

        );
        $this->db->insert('dictionary_entries', $data);
        return $this->db->insert_id();

    }

    public function term_list($dictionary)
    {
        $this->db->select('de.id, de.term, de.meaning, de.language, de.updated, l.code_dir, l.iso_code, i.full_image_path');
        $this->db->from('dictionary_entries de');
        $this->db->join('languages l','de.language = l.id');
        $this->db->join('images i','i.id = de.image_id', 'LEFT');
        $this->db->where(array('chapter_id' => $dictionary));
        $this->db->order_by("term", "asc");
        $query = $this->db->get();

        return $query->result_array();
    }

    public function get_term($id)
    {
        $this->db->select('de.id, term, meaning, language, full_image_path');
        $this->db->from('dictionary_entries de');
        $this->db->join('images i', 'i.id = de.image_id', 'LEFT');
        $this->db->where(array('de.id' => $id));
        $query = $this->db->get();

        // $query = $this->db->get();
        $data = $query->row_array();
        if(!empty($data['flags'])){
            $data['flags'] = explode(';',$data['flags']);
        }

        return $data;
    }

    public function update_item()
    {
        $this->db->where('id', $this->input->post('id'));
        $this->db->update(
            'dictionary_entries',
            $data = array(
                'term'    => $this->input->post('term'),
                'meaning' => $this->input->post('meaning'),
                'language'=> $this->input->post('language')

            )

        );
    }

    public function updateImageReference($termId, $imageId)
    {
        $this->db->where('id', $termId);
        $this->db->update(
            'dictionary_entries',
            $data = array(
                'image_id'    => $imageId
            )
        );
    }

    public function deleteImageReference($termId)
    {
        $this->db->where('id', $termId);
        $this->db->update(
            'dictionary_entries',
            $data = array(
                'image_id'    => null
            )
        );
    }

    public function term_delete($id){
        $this->db->where('id',$id);
        $this->db->delete('dictionary_entries');
    }

    public function update_chapterItem($id, $data){

        $this->db->where('id', $id);
        $this->db->update(
            'dictionary_entries',
            $data );
    }

}


text:
#ifndef _SMT_TACTIC_H_
#define _SMT_TACTIC_H_

#include"params.h"

class tactic;

tactic * mk_smt_tactic(params_ref const & p = params_ref());
// syntax sugar for using_params(mk_smt_tactic(), p) where p = (:auto_config, auto_config)
tactic * mk_smt_tactic_using(bool auto_config = true, params_ref const & p = params_ref());

/*
  ADD_TACTIC("smt", "apply a SAT based SMT solver.", "mk_smt_tactic(p)")
*/

#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.artifactregistry.v1beta1.model;

/**
 * The response to upload an artifact.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Artifact Registry API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class UploadAptArtifactMediaResponse extends com.google.api.client.json.GenericJson {

  /**
   * Operation to be returned to the user.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Operation operation;

  /**
   * Operation to be returned to the user.
   * @return value or {@code null} for none
   */
  public Operation getOperation() {
    return operation;
  }

  /**
   * Operation to be returned to the user.
   * @param operation operation or {@code null} for none
   */
  public UploadAptArtifactMediaResponse setOperation(Operation operation) {
    this.operation = operation;
    return this;
  }

  @Override
  public UploadAptArtifactMediaResponse set(String fieldName, Object value) {
    return (UploadAptArtifactMediaResponse) super.set(fieldName, value);
  }

  @Override
  public UploadAptArtifactMediaResponse clone() {
    return (UploadAptArtifactMediaResponse) super.clone();
  }

}


text:
<@pp.dropOutputFile />
<@pp.changeOutputFile name="/org/apache/arrow/vector/complex/impl/AbstractFieldReader.java" />

<#include "/@includes/license.ftl" />

package org.apache.arrow.vector.complex.impl;

<#include "/@includes/vv_imports.ftl" />

/**
 * Source code generated using FreeMarker template ${.template_name}
 */
@SuppressWarnings("unused")
abstract class AbstractFieldReader extends AbstractBaseReader implements FieldReader{

  AbstractFieldReader(){
    super();
  }

  /**
   * Returns true if the current value of the reader is not null
   * @return whether the current value is set
   */
  public boolean isSet() {
    return true;
  }

  @Override
  public Field getField() {
    fail("getField");
    return null;
  }

  <#list ["Object", "BigDecimal", "Short", "Integer", "Long", "Boolean",
          "LocalDateTime", "Duration", "Period", "Double", "Float",
          "Character", "Text", "String", "Byte", "byte[]"] as friendlyType>
  <#assign safeType=friendlyType />
  <#if safeType=="byte[]"><#assign safeType="ByteArray" /></#if>
  public ${friendlyType} read${safeType}(int arrayIndex) {
    fail("read${safeType}(int arrayIndex)");
    return null;
  }

  public ${friendlyType} read${safeType}() {
    fail("read${safeType}()");
    return null;
  }

  </#list>
  public void copyAsValue(StructWriter writer) {
    fail("CopyAsValue StructWriter");
  }

  public void copyAsField(String name, StructWriter writer) {
    fail("CopyAsField StructWriter");
  }

  public void copyAsField(String name, ListWriter writer) {
    fail("CopyAsFieldList");
  }

  <#list vv.types as type><#list type.minor as minor><#assign name = minor.class?cap_first />
  <#assign boxedType = (minor.boxedType!type.boxedType) />
  public void read(${name}Holder holder) {
    fail("${name}");
  }

  public void read(Nullable${name}Holder holder) {
    fail("${name}");
  }

  public void read(int arrayIndex, ${name}Holder holder) {
    fail("Repeated${name}");
  }

  public void read(int arrayIndex, Nullable${name}Holder holder) {
    fail("Repeated${name}");
  }

  public void copyAsValue(${name}Writer writer) {
    fail("CopyAsValue${name}");
  }

  public void copyAsField(String name, ${name}Writer writer) {
    fail("CopyAsField${name}");
  }

  </#list></#list>
  public FieldReader reader(String name) {
    fail("reader(String name)");
    return null;
  }

  public FieldReader reader() {
    fail("reader()");
    return null;
  }

  public int size() {
    fail("size()");
    return -1;
  }

  private void fail(String name) {
    throw new IllegalArgumentException(String.format("You tried to read a [%s] type when you are using a field reader of type [%s].", name, this.getClass().getSimpleName()));
  }
}


text:
package net.sf.katta.util;

/**
 * The public interface for the front end of a dummy server. It just sleeps
 * for a while then returns nothing.
 */
public interface ISleepClient {

  /**
   * Sleep for the given number of milliseconds on all nodes.
   * @param msec How long each node should sleep for.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleep(long msec) throws KattaException;

  /**
   * Sleep for the given number of milliseconds on all nodes.
   * @param msec How long each node should sleep for.
   * @param delta The maximum size of the delta (msec) to add or remove
   *     from the specified time. The node will choose an evenly distributed
   *     random sleep time from msec-delta to msec+delta.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleep(long msec, int delta) throws KattaException;

  /**
   * Sleep for the given number of milliseconds.
   * @param msec How long each node should sleep for.
   * @param shards Which shards to send the request to. Use this to control
   *     which nodes will sleep. Within a node, the shard list is ignored.
   *     The call will return after all nodes have finished sleeping.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleepShards(long msec, String[] shards) throws KattaException;

  /**
   * Sleep for the given number of milliseconds, +- a random delta.
   * @param msec How long each node should sleep for.
   * @param delta The maximum size of the delta (msec) to add or remove
   *     from the specified time. The node will choose an evenly distributed
   *     random sleep time from msec-delta to msec+delta.
   * @param shards Which shards to send the request to. Use this to control
   *     which nodes will sleep. Within a node, the shard list is ignored.
   *     The call will return after all nodes have finished sleeping.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleepShards(long msec, int delta, String[] shards) throws KattaException;

  /**
   * Sleep for the given number of milliseconds.
   * @param msec How long each node should sleep for.
   * @param indices Which indices to send the request to. Use this to control
   *     which nodes will sleep.
   *     The call will return after all nodes have finished sleeping.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleepIndices(long msec, String[] indices) throws KattaException;

  /**
   * Sleep for the given number of milliseconds, +- a random delta.
   * @param msec How long each node should sleep for.
   * @param delta The maximum size of the delta (msec) to add or remove
   *     from the specified time. The node will choose an evenly distributed
   *     random sleep time from msec-delta to msec+delta.
   * @param indices Which indices to send the request to. Use this to control
   *     which nodes will sleep.
   *     The call will return after all nodes have finished sleeping.
   * @return the total number of shards referenced (note: sleeping is done per-node).
   * @throws KattaException If an IO exception occurs.
   */
  public int sleepIndices(long msec, int delta, String[] indices) throws KattaException;

  /**
   * Closes down the client. Does nothing.
   */
  public void close();

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18052
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace FileHelpers.WizardApp.Templates {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Templates {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Templates() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FileHelpers.WizardApp.Templates.Templates", typeof(Templates).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Generics___Read_And_Check_Errors {
            get {
                object obj = ResourceManager.GetObject("CS___Generics___Read_And_Check_Errors", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Generics___Read_Record_by_Record {
            get {
                object obj = ResourceManager.GetObject("CS___Generics___Read_Record_by_Record", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Generics___Read_Whole_File {
            get {
                object obj = ResourceManager.GetObject("CS___Generics___Read_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Generics___Write_Whole_File {
            get {
                object obj = ResourceManager.GetObject("CS___Generics___Write_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Read_And_Check_Errors {
            get {
                object obj = ResourceManager.GetObject("CS___Read_And_Check_Errors", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Read_Record_by_Record {
            get {
                object obj = ResourceManager.GetObject("CS___Read_Record_by_Record", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Read_Whole_File {
            get {
                object obj = ResourceManager.GetObject("CS___Read_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] CS___Write_Whole_File {
            get {
                object obj = ResourceManager.GetObject("CS___Write_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Generics___Read_and_Check_Errors {
            get {
                object obj = ResourceManager.GetObject("VB___Generics___Read_and_Check_Errors", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Generics___Read_Record_by_Record {
            get {
                object obj = ResourceManager.GetObject("VB___Generics___Read_Record_by_Record", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Generics___Read_Whole_File {
            get {
                object obj = ResourceManager.GetObject("VB___Generics___Read_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Generics___Write_Whole_File {
            get {
                object obj = ResourceManager.GetObject("VB___Generics___Write_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Read_and_Check_Errors {
            get {
                object obj = ResourceManager.GetObject("VB___Read_and_Check_Errors", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Read_Record_by_Record {
            get {
                object obj = ResourceManager.GetObject("VB___Read_Record_by_Record", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Read_Whole_File {
            get {
                object obj = ResourceManager.GetObject("VB___Read_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] VB___Write_Whole_File {
            get {
                object obj = ResourceManager.GetObject("VB___Write_Whole_File", resourceCulture);
                return ((byte[])(obj));
            }
        }
    }
}