text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>mne.scale_labels — MNE 0.11.0 documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/gallery.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootswatch-3.3.4/flatly/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="MNE 0.11.0 documentation" href="../index.html" />
    <link rel="up" title="API Reference" href="../python_reference.html" />
    <link rel="next" title="mne.scale_source_space" href="mne.scale_source_space.html" />
    <link rel="prev" title="mne.scale_bem" href="mne.scale_bem.html" />

<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.11.0

Tutorials

Gallery

Manual

API

FAQ

Cite

  Site

Getting Started

What’s new

Cite MNE

Related publications

Tutorials

Examples Gallery

Manual

API Reference

Frequently Asked Questions

Advanced installation and setup

MNE with CPP

  Page

mne.scale_labels

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.scale_labels

    « mne.scale_bem

    mne.scale_sou... »

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.scale_labels¶

mne.scale_labels(subject_to, pattern=None, overwrite=False, subject_from=None, scale=None, subjects_dir=None)¶

Scale labels to match a brain that was previously created by scaling

<col class="field-name" />
<col class="field-body" />

Parameters:
subject_to : str

Name of the scaled MRI subject (the destination brain).

pattern : str | None

Pattern for finding the labels relative to the label directory in the
MRI subject directory (e.g., “lh.BA3a.label” will scale
“fsaverage/label/lh.BA3a.label”; “aparc/*.label” will find all labels
in the “fsaverage/label/aparc” directory). With None, scale all labels.

overwrite : bool

Overwrite any label file that already exists for subject_to (otherwise
existsing labels are skipped).

subject_from : None | str

Name of the original MRI subject (the brain that was scaled to create
subject_to). If None, the value is read from subject_to’s cfg file.

scale : None | float | array_like, shape = (3,)

Scaling parameter. If None, the value is read from subject_to’s cfg
file.

subjects_dir : None | str

Override the SUBJECTS_DIR environment variable.

      Back to top

        © Copyright 2012-2015, MNE Developers.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tmf.dsmapi.common.impl;

import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

@Provider
@Produces("application/json")
public class JacksonConfigurator implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public JacksonConfigurator() {
        mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> arg0) {
        return mapper;
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

var path = require('path')
var utils = require('../lib/utils')
var insecurity = require('../lib/insecurity')
var challenges = require('../data/datacache').challenges

exports = module.exports = function servePublicFiles () {
  return function (req, res, next) {
    var file = req.params.file
    var mdDebug = req.query.md_debug

    if (!file.includes('/')) {
      verify(file, res, next, mdDebug)
    } else {
      res.status(403)
      next(new Error('File names cannot contain forward slashes!'))
    }
  }

  function verify (file, res, next, mdDebug) {
    if (file && (utils.endsWith(file, '.md') || (utils.endsWith(file, '.pdf') || (file === 'incident-support.kdbx')))) {
      file = insecurity.cutOffPoisonNullByte(file)
      if (utils.notSolved(challenges.easterEggLevelOneChallenge) && file.toLowerCase() === 'eastere.gg') {
        utils.solve(challenges.easterEggLevelOneChallenge)
      } else if (utils.notSolved(challenges.directoryListingChallenge) && file.toLowerCase() === 'acquisitions.md') {
        utils.solve(challenges.directoryListingChallenge)
      } else if (utils.notSolved(challenges.forgottenDevBackupChallenge) && file.toLowerCase() === 'package.json.bak') {
        utils.solve(challenges.forgottenDevBackupChallenge)
      } else if (utils.notSolved(challenges.forgottenBackupChallenge) && file.toLowerCase() === 'coupons_2013.md.bak') {
        utils.solve(challenges.forgottenBackupChallenge)
      }
      res.sendFile(path.resolve(__dirname, '../ftp/', file))
    } else if (file && mdDebug && utils.contains(file, '.md') && (utils.endsWith(mdDebug, '.md') || utils.endsWith(mdDebug, '.pdf'))) {
      if (utils.notSolved(challenges.forgottenBackupChallenge) && file.toLowerCase() === 'coupons_2013.md.bak') {
        utils.solve(challenges.forgottenBackupChallenge)
      }
      res.sendFile(path.resolve(__dirname, '../ftp/', file))
    } else {
      res.status(403)
      next(new Error('Only .md and .pdf files are allowed!'))
    }
  }
}


text:
define(function(require, exports, module) {
  "use strict";

  var cc = require("../cc");
  var utils = require("./utils");
  var cubicinterp = utils.cubicinterp;
  var slice = [].slice;

  var sc_loop = function(unit, index, hi, loop) {
    if (index >= hi) {
      if (!loop) {
        unit.done = true;
        return hi;
      }
      index -= hi;
      if (index < hi) {
        return index;
      }
    } else if (index < 0) {
      if (!loop) {
        unit.done = true;
        return 0;
      }
      index += hi;
      if (index >= 0) {
        return index;
      }
    } else {
      return index;
    }
    return index - hi * Math.floor(index/hi);
  };

  var get_indices = function(phase, hi, loop) {
    var index1 = phase|0;
    var index0 = index1 - 1;
    var index2 = index1 + 1;
    var index3 = index2 + 1;
    if (index1 === 0) {
      if (loop) {
        index0 = hi;
      } else {
        index0 = index1;
      }
    } else if (index3 > hi) {
      if (index2 > hi) {
        if (loop) {
          index2 = 0;
          index3 = 1;
        } else {
          index2 = index3 = hi;
        }
      } else {
        if (loop) {
          index3 = 0;
        } else {
          index3 = hi;
        }
      }
    }
    return [ index0, index1, index2, index3 ];
  };

  var get_buffer = function(unit) {
    var buffer = unit.world.buffers[unit.inputs[0][0]|0];
    if (buffer) {
      var samples = buffer.samples;
      if (samples.length) {
        unit._frames     = buffer.frames;
        unit._channels   = buffer.channels;
        unit._sampleRate = buffer.sampleRate;
        unit._samples    = samples;
        return true;
      }
    }
    return false;
  };

  var asArray = function(obj) {
    if (Array.isArray(obj)) {
      return obj;
    }
    return [obj];
  };

  cc.ugen.specs.PlayBuf = {
    Klass: cc.MultiOutUGen,
    $ar: {
      defaults: "numChannels=0,bufnum=0,rate=1,trigger=1,startPos=0,loop=0,doneAction=0",
      ctor: function(numChannels, bufnum, rate, trigger, startPos, loop, doneAction) {
        if (typeof numChannels !== "number") {
          throw new TypeError("PlayBuf: numChannels should be an integer.");
        }
        return this.multiNew(C.AUDIO, numChannels, bufnum, rate, trigger, startPos, loop, doneAction);
      }
    },
    $kr: {
      defaults: "numChannels=0,bufnum,rate=1,trigger=1,startPos=0,loop=0,doneAction=0",
      ctor: function(numChannels, bufnum, rate, trigger, startPos, loop, doneAction) {
        if (typeof numChannels !== "number") {
          throw new TypeError("PlayBuf: numChannels should be an integer.");
        }
        return this.multiNew(C.CONTROL, numChannels, bufnum, rate, trigger, startPos, loop, doneAction);
      }
    },
    init: function(numChannels) {
      this.inputs = slice.call(arguments, 1);
      return this.initOutputs(numChannels, this.rate);
    }
  };

  cc.unit.specs.PlayBuf = (function() {
    var ctor = function() {
      switch (this.numOutputs) {
      case 1: this.process = next_1ch; break;
      case 2: this.process = next_2ch; break;
      default: this.process = next;
      }
      this._samples  = null;
      this._channels = 0;
      this._frames   = 0;
      this._phase = this.inputs[3][0];
      this._trig  = 0;
    };

    var next_1ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var out   = this.outputs[0];
      var phase = this._phase;
      var rate  = this.inputs[1][0];
      var trig  = this.inputs[2][0];
      var loop  = this.inputs[4][0];
      var samples  = this._samples;
      var frames   = this._frames;
      var indices, frac, a, b, c, d;
      var hi = frames - 1;

      if (trig > 0 && this._trig <= 0) {
        this.done = false;
        phase = this.inputs[3][0];
      }
      this._trig = trig;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phase, hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);

        a = samples[indices[0]];
        b = samples[indices[1]];
        c = samples[indices[2]];
        d = samples[indices[3]];
        out[i] = cubicinterp(frac, a, b, c, d);

        phase += rate;
      }
      if (this.done) {
        this.doneAction(this.inputs[5][0]|0);
      }
      this._phase = phase;
    };

    var next_2ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var out1  = this.outputs[0];
      var out2  = this.outputs[1];
      var phase = this._phase;
      var rate  = this.inputs[1][0];
      var trig  = this.inputs[2][0];
      var loop  = this.inputs[4][0];
      var samples  = this._samples;
      var frames   = this._frames;
      var indices, frac, a, b, c, d;
      var hi = frames - 1;

      if (trig > 0 && this._trig <= 0) {
        this.done = false;
        phase = this.inputs[3][0];
      }
      this._trig = trig;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phase, hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);

        a = samples[indices[0] * 2];
        b = samples[indices[1] * 2];
        c = samples[indices[2] * 2];
        d = samples[indices[3] * 2];
        out1[i] = cubicinterp(frac, a, b, c, d);

        a = samples[indices[0] * 2 + 1];
        b = samples[indices[1] * 2 + 1];
        c = samples[indices[2] * 2 + 1];
        d = samples[indices[3] * 2 + 1];
        out2[i] = cubicinterp(frac, a, b, c, d);

        phase += rate;
      }
      if (this.done) {
        this.doneAction(this.inputs[5][0]|0);
      }
      this._phase = phase;
    };

    var next = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var outputs = this.outputs;
      var phase = this._phase;
      var rate  = this.inputs[1][0];
      var trig  = this.inputs[2][0];
      var loop  = this.inputs[4][0];
      var samples  = this._samples;
      var channels = this._channels;
      var frames   = this._frames;
      var indices, frac, a, b, c, d;

      var hi = frames - 1;
      if (trig > 0 && this._trig <= 0) {
        this.done = false;
        phase = this.inputs[3][0];
      }
      this._trig = trig;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phase, hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);
        for (var j = 0, jmax = outputs.length; j < jmax; ++j) {
          a = samples[indices[0] * channels + j];
          b = samples[indices[1] * channels + j];
          c = samples[indices[2] * channels + j];
          d = samples[indices[3] * channels + j];
          outputs[j][i] = cubicinterp(frac, a, b, c, d);
        }
        phase += rate;
      }
      if (this.done) {
        this.doneAction(this.inputs[5][0]|0);
      }
      this._phase = phase;
    };

    return ctor;
  })();

  cc.ugen.specs.BufRd = {
    Klass: cc.MultiOutUGen,
    $ar: {
      defaults: "numChannels=0,bufnum=0,phase=0,loop=1,interpolation=2",
      ctor: function(numChannels, bufnum, phase, loop, interpolation) {
        if (typeof numChannels !== "number") {
          throw new TypeError("PlayBuf: numChannels should be an integer.");
        }
        return this.multiNew(C.AUDIO, numChannels, bufnum, phase, loop, interpolation);
      }
    },
    $kr: {
      defaults: "numChannels=0,bufnum=0,phase=0,loop=1,interpolation=2",
      ctor: function(numChannels, bufnum, phase, loop, interpolation) {
        if (typeof numChannels !== "number") {
          throw new TypeError("PlayBuf: numChannels should be an integer.");
        }
        return this.multiNew(C.CONTROL, numChannels, bufnum, phase, loop, interpolation);
      }
    },
    init: function(numChannels) {
      this.inputs = slice.call(arguments, 1);
      return this.initOutputs(numChannels, this.rate);
    }
  };

  var perform_N = function(samples, indices, mul, add) {
    return samples[indices[1] * mul + add];
  };
  var perform_L = function(samples, indices, mul, add, frac) {
    var b = samples[indices[1] * mul + add];
    var c = samples[indices[2] * mul + add];
    return b + frac * (c - b);
  };
  var perform_C = function(samples, indices, mul, add, frac) {
    var a = samples[indices[0] * mul + add];
    var b = samples[indices[1] * mul + add];
    var c = samples[indices[2] * mul + add];
    var d = samples[indices[3] * mul + add];
    return cubicinterp(frac, a, b, c, d);
  };
  cc.unit.specs.BufRd = (function() {
    var ctor = function() {
      switch (this.numOutputs) {
      case 1:
        this.process = next_1ch;
        break;
      case 2:
        this.process = next_2ch;
        break;
      default:
        this.process = next;
      }
      switch (this.inputs[3][0]|0) {
      case 1 : this._perform = perform_N; break;
      case 4 : this._perform = perform_C; break;
      default: this._perform = perform_L; break;
      }
      this._samples  = null;
      this._channels = 0;
      this._frames   = 0;
    };
    var next_1ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var out = this.outputs[0];
      var phaseIn = this.inputs[1];
      var loop = this.inputs[2][0];
      var samples = this._samples;
      var frames  = this._frames;
      var perform = this._perform;
      var phase, indices, frac;
      var hi = frames - 1;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);
        out[i] = perform(samples, indices, 1, 0, frac);
      }
    };
    var next_2ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var out1 = this.outputs[0];
      var out2 = this.outputs[1];
      var phaseIn = this.inputs[1];
      var loop = this.inputs[2][0];
      var samples = this._samples;
      var frames  = this._frames;
      var perform = this._perform;
      var phase, indices, frac;
      var hi = frames - 1;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);
        out1[i] = perform(samples, indices, 2, 0, frac);
        out2[i] = perform(samples, indices, 2, 1, frac);
      }
    };
    var next = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var outputs = this.outputs;
      var phaseIn = this.inputs[1];
      var loop = this.inputs[2][0];
      var samples = this._samples;
      var frames  = this._frames;
      var perform = this._perform;
      var phase, indices, frac;
      var hi = frames - 1;
      for (var i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], hi, loop);
        indices = get_indices(phase, hi, loop);
        frac = phase - (phase|0);
        for (var j = 0, jmax = outputs.length; j < jmax; ++j) {
          outputs[j][i] = perform(samples, indices, jmax, j, frac);
        }
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufWr = {
    $ar: {
      defaults: "inputArray=[],bufnum=0,phase=0,loop=1",
      ctor: function(inputArray, bufnum, phase, loop) {
        return this.multiNewList([C.AUDIO, bufnum, phase, loop].concat(asArray(inputArray)));
      }
    },
    $kr: {
      defaults: "inputArray=[],bufnum=0,phase=0,loop=1",
      ctor: function(inputArray, bufnum, phase, loop) {
        return this.multiNewList([C.CONTROL, bufnum, phase, loop].concat(asArray(inputArray)));
      }
    },
    checkNInputs: function() {
      if (this.rate === C.AUDIO && this.inputs[1].rate !== C.AUDIO) {
        throw new Error("phase input is not audio rate");
      }
    }
  };

  cc.unit.specs.BufWr = (function() {
    var ctor = function() {
      switch (this.numInputs - 3) {
      case 1:
        this.process = next_1ch;
        break;
      case 2:
        this.process = next_2ch;
        break;
      default:
        this.process = next;
        break;
      }
    };
    var next_1ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var phaseIn = this.inputs[1];
      var in0In   = this.inputs[3];
      var loop    = this.inputs[2][0];
      var loopMax = this._frames - (loop ? 0 : 1);
      var samples = this._samples;
      var phase;
      var i;
      for (i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], loopMax, loop);
        samples[phase|0] = in0In[i];
      }
    };
    var next_2ch = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var phaseIn = this.inputs[1];
      var in0In   = this.inputs[3];
      var in1In   = this.inputs[4];
      var loop    = this.inputs[2][0];
      var loopMax = this._frames - (loop ? 0 : 1);
      var samples = this._samples;
      var phase, index;
      var i;
      for (i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], loopMax, loop);
        index = phase << 1;
        samples[index  ] = in0In[i];
        samples[index+1] = in1In[i];
      }
    };
    var next = function(inNumSamples) {
      if (!get_buffer(this)) {
        return;
      }
      var phaseIn = this.inputs[1];
      var inputs  = this.inputs;
      var loop    = this.inputs[2][0];
      var loopMax = this._frames - (loop ? 0 : 1);
      var samples = this._samples;
      var channels = this._channels;
      var phase, index;
      var i, j;
      for (i = 0; i < inNumSamples; ++i) {
        phase = sc_loop(this, phaseIn[i], loopMax, loop);
        index = (phase|0) * channels;
        for (j = 0; j < channels; ++j) {
          samples[index+j] = inputs[j+3][i];
        }
      }
    };
    return ctor;
  })();

  cc.ugen.specs.RecordBuf = {
    $ar: {
      defaults: "inputArray=[],bufnum=0,offset=0,recLevel=1,preLevel=0,run=1,loop=1,trigger=1,doneAction=0",
      ctor: function(inputArray, bufnum, offset, recLevel, preLevel, run, loop, trigger, doneAction) {
        return this.multiNewList([
          C.AUDIO, bufnum, offset, recLevel, preLevel, run, loop, trigger, doneAction
        ].concat(asArray(inputArray)));
      }
    },
    $kr: {
      defaults: "inputArray=[],bufnum=0,offset=0,recLevel=1,preLevel=0,run=1,loop=1,trigger=1,doneAction=0",
      ctor: function(inputArray, bufnum, offset, recLevel, preLevel, run, loop, trigger, doneAction) {
        return this.multiNewList([
          C.CONTROL, bufnum, offset, recLevel, preLevel, run, loop, trigger, doneAction
        ].concat(asArray(inputArray)));
      }
    }
  };

  cc.unit.specs.RecordBuf = (function() {
    var ctor = function() {
      switch (this.numInputs - 8) {
      case 1:
        this.process = next_1ch;
        break;
      case 2:
        this.process = next_2ch;
        break;
      default:
        this.process = next;
        break;
      }
      this._writepos = this.inputs[1][0];
      this._recLevel = this.inputs[2][0];
      this._preLevel = this.inputs[3][0];
      this._prevtrig = 0;
      this._preindex = 0;
    };
    var recbuf_next = function(func) {
      return function(inNumSamples) {
        if (!get_buffer(this)) {
          return;
        }
        var channels = this._channels;
        var frames   = this._frames;
        var samples  = this._samples;
        var inputs   = this.inputs;
        var recLevel = this.inputs[2][0];
        var preLevel = this.inputs[3][0];
        var run      = this.inputs[4][0];
        var loop     = this.inputs[5][0]|0;
        var trig     = this.inputs[6][0];
        var writepos = this._writepos;
        var recLevel_slope = (recLevel - this._recLevel) * this.rate.slopeFactor;
        var preLevel_slope = (preLevel - this._preLevel) * this.rate.slopeFactor;
        var prevpos, posincr;
        var i;
        recLevel = this._recLevel;
        preLevel = this._preLevel;
        prevpos  = this._prevpos;
        posincr  = run > 0 ? +1 : -1;
        if (trig > 0 && this._prevtrig) {
          this.done = false;
          writepos  = (this.inputs[1][0] * channels)|0;
        }
        if (writepos < 0) {
          writepos = frames - 1;
        } else if (writepos >= frames) {
          writepos = 0;
        }
        for (i = 0; i < inNumSamples; ++i) {
          func(inputs, i, samples, writepos, prevpos, recLevel, preLevel, channels);
          prevpos   = writepos;
          writepos += posincr;
          if (writepos >= frames) {
            if (loop) {
              writepos = 0;
            } else {
              writepos = frames - 1;
              this.done = true;
            }
          } else if (0 < writepos) {
            if (loop) {
              writepos = frames - 1;
            } else {
              writepos  = 0;
              this.done = true;
            }
          }
          recLevel += recLevel_slope;
          preLevel += preLevel_slope;
        }
        if (this.done) {
          this.doneAction(this.inputs[7][0]|0);
        }
        this._prevtrig = trig;
        this._writepos = writepos;
        this._prevpos  = prevpos;
        this._recLevel = recLevel;
        this._preLevel = preLevel;
      };
    };

    var next_1ch = recbuf_next(function(inputs, index, samples, writepos, prevpos, recLevel, preLevel) {
      samples[writepos] = inputs[8][index] * recLevel + samples[prevpos] * preLevel;
    });

    var next_2ch = recbuf_next(function(inputs, index, samples, writepos, prevpos, recLevel, preLevel) {
      samples[writepos*2  ] = inputs[8][index] * recLevel + samples[prevpos*2  ] * preLevel;
      samples[writepos*2+1] = inputs[9][index] * recLevel + samples[prevpos*2+1] * preLevel;
    });

    var next = recbuf_next(function(inputs, index, samples, writepos, prevpos, recLevel, preLevel, channels) {
      var j;
      for (j = 0; j < channels; ++j) {
        samples[writepos*channels+j] = inputs[8+j][index] + recLevel * samples[prevpos*channels+j] * preLevel;
      }
    });
    return ctor;
  })();

  cc.ugen.specs.BufSampleRate = {
    $kr: {
      defaults: "bufnum=0",
      ctor: function(bufnum) {
        return this.multiNew(C.CONTROL, bufnum);
      }
    },
    $ir: {
      defaults: "bufnum=0",
      ctor: function(bufnum) {
        return this.multiNew(C.SCALAR, bufnum);
      }
    }
  };

  cc.unit.specs.BufSampleRate = (function() {
    var ctor = function() {
      this.process = next;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._sampleRate;
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufRateScale = cc.ugen.specs.BufSampleRate;

  cc.unit.specs.BufRateScale = (function() {
    var ctor = function() {
      this.process = next;
      this._sampleDur = cc.server.rates[C.AUDIO].sampleDur;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._sampleRate * this._sampleDur;
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufFrames = cc.ugen.specs.BufSampleRate;

  cc.unit.specs.BufFrames = (function() {
    var ctor = function() {
      this.process = next;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._frames;
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufSamples   = cc.ugen.specs.BufSampleRate;

  cc.unit.specs.BufSamples = (function() {
    var ctor = function() {
      this.process = next;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._samples.length;
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufDur = cc.ugen.specs.BufSampleRate;

  cc.unit.specs.BufDur = (function() {
    var ctor = function() {
      this.process = next;
      this._sampleDur = cc.server.rates[C.AUDIO].sampleDur;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._frames * this._sampleDur;
      }
    };
    return ctor;
  })();

  cc.ugen.specs.BufChannels = cc.ugen.specs.BufSampleRate;

  cc.unit.specs.BufChannels = (function() {
    var ctor = function() {
      this.process = next;
    };
    var next = function() {
      if (get_buffer(this)) {
        this.outputs[0][0] = this._channels;
      }
    };
    return ctor;
  })();

  module.exports = {};

});


text:
#ifndef __ERL_MESSAGE_H__
#define __ERL_MESSAGE_H__

struct proc_bin;
struct external_thing_;

/*
 * This struct represents data that must be updated by structure copy,
 * but is stored outside of any heap.
 */

struct erl_off_heap_header {
    Eterm thing_word;
    Uint size;
#if HALFWORD_HEAP
    void* dummy_ptr_padding__;
#endif
    struct erl_off_heap_header* next;
};

#define OH_OVERHEAD(oh, size) do { \
    (oh)->overhead += size;        \
} while(0)

typedef struct erl_off_heap {
    struct erl_off_heap_header* first;
    Uint64 overhead;     /* Administrative overhead (used to force GC). */
} ErlOffHeap;

#include "external.h"
#include "erl_process.h"

/*
 * This struct represents a heap fragment, which is used when there
 * isn't sufficient room in the process heap and we can't do a GC.
 */

typedef struct erl_heap_fragment ErlHeapFragment;
struct erl_heap_fragment {
    ErlHeapFragment* next;	/* Next heap fragment */
    ErlOffHeap off_heap;	/* Offset heap data. */
    unsigned alloc_size;	/* Size in (half)words of mem */
    unsigned used_size;         /* With terms to be moved to heap by GC */
    Eterm mem[1];		/* Data */
};

typedef struct erl_mesg {
    struct erl_mesg* next;	/* Next message */
    union {
	ErtsDistExternal *dist_ext;
	ErlHeapFragment *heap_frag;
	void *attached;
    } data;
    Eterm m[2];			/* m[0] = message, m[1] = seq trace token */
} ErlMessage;

#define ERL_MESSAGE_TERM(mp) ((mp)->m[0])
#define ERL_MESSAGE_TOKEN(mp) ((mp)->m[1])

/* Size of default message buffer (erl_message.c) */
#define ERL_MESSAGE_BUF_SZ 500

typedef struct {
    ErlMessage* first;
    ErlMessage** last;  /* point to the last next pointer */
    ErlMessage** save;
    int len;            /* queue length */

    /*
     * The following two fields are used by the recv_mark/1 and
     * recv_set/1 instructions.
     */
    BeamInstr* mark;		/* address to rec_loop/2 instruction */
    ErlMessage** saved_last;	/* saved last pointer */
} ErlMessageQueue;

#ifdef ERTS_SMP

typedef struct {
    ErlMessage* first;
    ErlMessage** last;  /* point to the last next pointer */
    int len;            /* queue length */
} ErlMessageInQueue;

#endif

/* Get "current" message */
#define PEEK_MESSAGE(p)  (*(p)->msg.save)

/* Add message last in private message queue */
#define LINK_MESSAGE_PRIVQ(p, mp) do { \
    *(p)->msg.last = (mp); \
    (p)->msg.last = &(mp)->next; \
    (p)->msg.len++; \
} while(0)

#ifdef ERTS_SMP

/* Move in message queue to end of private message queue */
#define ERTS_SMP_MSGQ_MV_INQ2PRIVQ(P)			\
do {							\
    if ((P)->msg_inq.first) {				\
	*(P)->msg.last = (P)->msg_inq.first;		\
	(P)->msg.last = (P)->msg_inq.last;		\
	(P)->msg.len += (P)->msg_inq.len;		\
	(P)->msg_inq.first = NULL;			\
	(P)->msg_inq.last = &(P)->msg_inq.first;	\
	(P)->msg_inq.len = 0;				\
    }							\
} while (0)

/* Add message last in message queue */
#define LINK_MESSAGE(p, mp) do { \
    *(p)->msg_inq.last = (mp); \
    (p)->msg_inq.last = &(mp)->next; \
    (p)->msg_inq.len++; \
} while(0)

#else

#define ERTS_SMP_MSGQ_MV_INQ2PRIVQ(P)

/* Add message last in message queue */
#define LINK_MESSAGE(p, mp) LINK_MESSAGE_PRIVQ((p), (mp))

#endif

/* Unlink current message */
#define UNLINK_MESSAGE(p,msgp) do { \
     ErlMessage* __mp = (msgp)->next; \
     *(p)->msg.save = __mp; \
     (p)->msg.len--; \
     if (__mp == NULL) \
         (p)->msg.last = (p)->msg.save; \
     (p)->msg.mark = 0; \
} while(0)

/* Reset message save point (after receive match) */
#define JOIN_MESSAGE(p) \
     (p)->msg.save = &(p)->msg.first

/* Save current message */
#define SAVE_MESSAGE(p) \
     (p)->msg.save = &(*(p)->msg.save)->next

/*
 * ErtsMoveMsgAttachmentIntoProc() moves data attached to a message
 * onto the heap of a process. The attached data is the content of
 * the the message either on the internal format or on the external
 * format, and also possibly a seq trace token on the internal format.
 * If the message content is on the external format, the decode might
 * fail. If the decoding fails, ERL_MESSAGE_TERM(M) will contain
 * THE_NON_VALUE. That is, ERL_MESSAGE_TERM(M) *has* to be checked
 * afterwards and taken care of appropriately.
 *
 * ErtsMoveMsgAttachmentIntoProc() will shallow copy to heap if
 * possible; otherwise, move to heap via garbage collection.
 *
 * ErtsMoveMsgAttachmentIntoProc() is used when receiveing messages
 * in process_main() and in hipe_check_get_msg().
 */

#define ErtsMoveMsgAttachmentIntoProc(M, P, ST, HT, FC, SWPO, SWPI)	\
do {									\
    if ((M)->data.attached) {						\
	Uint need__ = erts_msg_attached_data_size((M));			\
 	if ((ST) - (HT) >= need__) {					\
	    Uint *htop__ = (HT);					\
	    erts_move_msg_attached_data_to_heap(&htop__, &MSO((P)), (M));\
	    ASSERT(htop__ - (HT) <= need__);				\
	    (HT) = htop__;						\
	}								\
	else {								\
	    { SWPO ; }							\
	    (FC) -= erts_garbage_collect((P), 0, NULL, 0);		\
	    { SWPI ; }							\
	}								\
	ASSERT(!(M)->data.attached);					\
    }									\
} while (0)

#define ERTS_SND_FLG_NO_SEQ_TRACE		(((unsigned) 1) << 0)

#define ERTS_HEAP_FRAG_SIZE(DATA_WORDS) \
   (sizeof(ErlHeapFragment) - sizeof(Eterm) + (DATA_WORDS)*sizeof(Eterm))

#define ERTS_INIT_HEAP_FRAG(HEAP_FRAG_P, DATA_WORDS)	\
do {							\
    (HEAP_FRAG_P)->next = NULL;				\
    (HEAP_FRAG_P)->alloc_size = (DATA_WORDS);		\
    (HEAP_FRAG_P)->used_size = (DATA_WORDS);            \
    (HEAP_FRAG_P)->off_heap.first = NULL; 	        \
    (HEAP_FRAG_P)->off_heap.overhead = 0;		\
} while (0)

void init_message(void);
void free_message(ErlMessage *);
ErlHeapFragment* new_message_buffer(Uint);
ErlHeapFragment* erts_resize_message_buffer(ErlHeapFragment *, Uint,
					    Eterm *, Uint);
void free_message_buffer(ErlHeapFragment *);
void erts_queue_dist_message(Process*, ErtsProcLocks*, ErtsDistExternal *, Eterm);
void erts_queue_message(Process*, ErtsProcLocks*, ErlHeapFragment*, Eterm, Eterm);
void erts_deliver_exit_message(Eterm, Process*, ErtsProcLocks *, Eterm, Eterm);
void erts_send_message(Process*, Process*, ErtsProcLocks*, Eterm, unsigned);
void erts_link_mbuf_to_proc(Process *proc, ErlHeapFragment *bp);

void erts_move_msg_mbuf_to_heap(Eterm**, ErlOffHeap*, ErlMessage *);

Uint erts_msg_attached_data_size_aux(ErlMessage *msg);
void erts_move_msg_attached_data_to_heap(Eterm **, ErlOffHeap *, ErlMessage *);

Eterm erts_msg_distext2heap(Process *, ErtsProcLocks *, ErlHeapFragment **,
			    Eterm *, ErtsDistExternal *);

ERTS_GLB_INLINE Uint erts_msg_used_frag_sz(const ErlMessage *msg);
ERTS_GLB_INLINE Uint erts_msg_attached_data_size(ErlMessage *msg);

#if ERTS_GLB_INLINE_INCL_FUNC_DEF
ERTS_GLB_INLINE Uint erts_msg_used_frag_sz(const ErlMessage *msg)
{
    const ErlHeapFragment *bp;
    Uint sz = 0;
    for (bp = msg->data.heap_frag; bp!=NULL; bp=bp->next) {
	sz += bp->used_size;
    }
    return sz;
}

ERTS_GLB_INLINE Uint erts_msg_attached_data_size(ErlMessage *msg)
{
    ASSERT(msg->data.attached);
    if (is_value(ERL_MESSAGE_TERM(msg)))
	return erts_msg_used_frag_sz(msg);
    else if (msg->data.dist_ext->heap_size < 0)
	return erts_msg_attached_data_size_aux(msg);
    else {
	Uint sz = msg->data.dist_ext->heap_size;
	if (is_not_nil(ERL_MESSAGE_TOKEN(msg))) {
	    ErlHeapFragment *heap_frag;
	    heap_frag = erts_dist_ext_trailer(msg->data.dist_ext);
	    sz += heap_frag->used_size;
	}
	return sz;
    }
}
#endif

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Pintura</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Landing page for OBRAMAX, the world's third largest retailer of construction materials and home decor.">
    <link rel="canonical" href="http://localhost:4000/line_3/2017/01/01/project-9/">

    <link rel="stylesheet" href="/style.css">

    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                OBRAMAX

                        Pilares

                        Clientes

                        Categorias

                        Quem Somos

                        Adeo

                        História

                        Contato

OBRAMAX

Atacado de Construção

                Saiba Mais

Pilares

Sortimento

Gama técnica ampla, selecionada

Produtos de qualidade de marcas profissionais

Preços transparentes e competitivos

Atendimento

Compra simples e rápida em todos os canais

Relação profissional e amigável

Disponibilidade

Disponibilidade imediata em grandes volumes

Entrega rápida

Confiabilidade na loja e na obra

PARA NÓS, OBRA É COMPROMISSO!

Nossos Clientes

Engenheiros, mestres de obras, arquitetos, autônomos que com uma pequena estrutura, planificam as obras e as compras de produtos para seus clientes.

Pequenas e médias construtoras que planificam e realizam obras e reformas de maneira estruturada. São profissionais que respondem a um caderno de encargo contratual.

Comércio de pequeno e médio porte de materiais de construção que servem clientes e profissionais.

Profissionais como o gesseiro, marceneiro e serralheiro, que realizam as compras para um projeto desenhado com o cliente que paga pelo projeto completo instalado com mão de obra e produtos.

Profissionais de uma especialidade que fazem pequenos reparos e reformas. Eles vendem a mão de obra, listam e indicam os materiais para seus clientes, podendo ou não acompanhar a compra. Alguns profissionais que trabalham desta forma são o pedreiro, encanador, eletricista, pintor.

Compradores pessoa física que definem e abordam suas obras com tecnicidade e uma visão principalmente racional, preocupados com a funcionalidade do produto, ganho de tempo e orçamento.

Categorias

                        A Obramax oferece uma gama técnica ampla, selecionada e disponível em grandes volumes com produtos de qualidade e marcas profissionais, preços transparentes e competitivos.

Materiais Básicos

Materiais Elétricos

Materiais Hidráulicos

Esquadrias

Cerâmica

Louças e Metais

Ferramentas

Ferragens

Marcenaria

Pintura

Quem Somos

Primeiro atacarejo de materiais de construção do Brasil

Visão

Revolucionamos a experiência de compra ao torná-la incrivelmente fácil, profissional, confiável e amigável.

Para atingir e sempre renovar essa ambição, ajudamos incansavelmente nossas equipes e nossos clientes a se superarem.

Faremos a diferença na vida dos brasileiros.

Missão

Ser o parceiro confiável dos profissionais e consumidores finais pragmáticos garantindo uma economia de tempo, energia e dinheiro na realização de seus projetos de construção, reforma, instalação e manutenção residencial e comercial de pequeno e médio porte.

Valores

Proximidade

Partilha

Gosto por empreender

Compromisso com o resultado

Transparência

Paixão

Fazemos parte do Grupo Adeo, fundado em 1923 pelo casal Adolphe Leroy e Rose Merlin, com a marca Leroy Merlin. A primeira loja era uma revenda de resíduos deixados pelos soldados americanos no fim da Primeira Guerra Mundial. Em 1979, a empresa foi comprada pela Associação Familiar Mulliez, que se torna o acionista majoritário.

LOJAS DEPÓSITO / PRO

                            BRICOMAN

                            DomPro

                            quotatis

                            Kbane

                            E.P.I. Center

MULTIESPECIALISTAS

                            Leroy-Merlin

                            KoziKaza

LOJAS DE DECORAÇÃO

                            Zodio

                            DecoClico

                            delaMaison

                            LIGHTONLINE

                            Tikamoon

                            Alice Delice

LOJAS DE PROXIMIDADE

                            AKI

                            WELDOM

                            Bricocenter

Adeo é a união das forças, das ideias, dos recursos, dos compromissos. Todas as empresas se reuniram em torno de valores humanos, conhecimentos e partilha de experiências, com a missão de "criar, acompanhar e tornar acessível o sonho de Habitat para todos os habitantes do mundo".

Sobre Nós

1923

No norte da França, Adolphe Leroy e Rose Merlin iniciam a venda de materiais deixados pelos aliados no pós Primeira Guerra Mundial.

1989

O Grupo cresce para fora do território francês e abre sua primeira loja Leroy Merlin na Espanha.

1998

Abertura primeira loja Leroy Merlin Brasil.

1999

Lançamento da Bricoman na França, com foco para o profissional de construção civil.

2017

Lançamento da Obramax no Brasil.

Seja parte

da nossa

história!

Contato

Gostaríamos de ouvir de você.

                    <form name="sentMessage" id="" action="//obramax.us15.list-manage.com/subscribe/post?u=3489cdb813640ec2093bb2398&id=07af593636" method="post" novalidate>

                                    <input name="NAME" type="text" class="form-control" placeholder="Seu Nome *" id="name" required data-validation-required-message="Por favor, insira seu nome.">

                                    <input name="EMAIL" type="email" class="form-control" placeholder="Seu Email *" id="email" required data-validation-required-message="Por favor, insira seu email.">

                                    <input name="PHONE" type="tel" class="form-control" placeholder="Seu Número de Telefone *" id="phone" required data-validation-required-message="Por favor, digite seu número de telefone.">

                                    <textarea name="COMPANY" class="form-control" placeholder="Sua Mensagem" id="message"></textarea>

                                <button type="submit" class="btn btn-xl">Enviar Mensagem</button>

                    </form>

                    Copyright © OBRAMAX 2017

Termos de Revenda


text:
import Options.Applicative
import Options

main :: IO ()
main = do
  opts <- execParser Options.parser
  perform (optCommand opts)


text:
package com.tierline.scala.activemodel

import java.sql.{Connection, ResultSet}

import grizzled.slf4j.Logging

object NativeQuery {
  implicit def stringMapToSeqStringMap(vMap: Map[String, String]): Map[String, Seq[String]] = vMap.map { case (k, v) => k -> Seq(v) }

  implicit def stringToSeqString(v: String): Seq[String] = Seq(v)
}

case class NativeQuery(schema: ActiveModelSchema) extends Logging {

  def using[Closeable <: {def close() : Unit}, B](closeable: Closeable)(func: Closeable => B): B = {
    try {
      func(closeable)
    } finally {
      closeable.close
    }
  }

  def connection: Connection = schema.newSession.connection

  import scala.collection.mutable.ListBuffer

  def toList[T](exists: => Boolean)(func: => T): List[T] = {
    val buff = new ListBuffer[T]
    while (exists) buff += func
    buff.toList
  }

  private def query[T](sql: String)(resultToObj: ResultSet => T): T = {
    using(connection) { con =>
      using(con.createStatement) { statement =>
        debug("execute query:" + sql)
        using(statement.executeQuery(sql)) { results =>
          resultToObj(results)
        }
      }
    }
  }

  def escape(vSeq: Seq[String]): Seq[String] = vSeq.map { v => v.replaceAll("'", "\"").replaceAll(";", "") }

  def addQuote(v: Seq[String]) = s"'${v.mkString("','")}'"

  private def replacement(sql: String, params: Map[String, Seq[String]]): String = {
    if (params.isEmpty) {
      sql
    } else {
      var sqlHolder = sql
      params.foreach { param =>
        sqlHolder = sqlHolder.replaceAll("%" + param._1, addQuote(escape(param._2)))
      }
      sqlHolder
    }
  }

  def queryEach[T](sql: String, params: Map[String, Seq[String]] = Map())(resultToObj: ResultSet => T): Seq[T] = {
    val sqlQuery = replacement(sql, params)
    query(sqlQuery) { results =>
      toList(results.next) {
        resultToObj(results)
      }
    }
  }

  def querySingle[T](sql: String, params: Map[String, Seq[String]] = Map())(resultToObj: ResultSet => T): Option[T] = {
    val sqlQuery = replacement(sql, params)
    query(sqlQuery) { results =>
      if (results.next) {
        Some(resultToObj(results))
      } else {
        None
      }

    }
  }

  def update(sql: String): Int = {
    using(connection) { con =>
      using(con.createStatement) { statement =>
        debug("execute update:" + sql)
        statement.executeUpdate(sql)
      }
    }
  }

  def execute[T](sql: String)(resultToObj: ResultSet => T): Seq[T] = {
    query(sql) { results =>
      toList(results.next) {
        resultToObj(results)
      }
    }
  }

}


text:
  // ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"

  // ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif

// DEBUGGING:  Uncomment the following line to print shock data
//#define DEBUG_LOG

using namespace chrono;
using namespace hmmwv;

// =============================================================================

// Initial vehicle position
ChVector<> initLoc(0, 0, 1.0);

// Initial vehicle orientation
ChQuaternion<> initRot(1, 0, 0, 0);
//ChQuaternion<> initRot(0.866025, 0, 0, 0.5);
//ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068);
//ChQuaternion<> initRot(0.25882, 0, 0, 0.965926);
//ChQuaternion<> initRot(0, 0, 0, 1);

// Type of powertrain model (SHAFTS, SIMPLE)
PowertrainModelType powertrain_model = SHAFTS;

// Type of tire model (RIGID, PACEJKA, or LUGRE)
TireModelType tire_model = RIGID;

// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0;   // size in X direction
double terrainWidth  = 100.0;   // size in Y direction

// Simulation step size
double step_size = 0.001;

// Time interval between two render frames
double render_step_size = 1.0 / 50;   // FPS = 50

// Time interval between two output frames
double output_step_size = 1.0 / 1;    // once a second

#ifdef USE_IRRLICHT
  // Point on chassis tracked by the camera
  ChVector<> trackPoint(0.0, 0.0, 1.75);
#else
  double tend = 20.0;

  const std::string out_dir = "../HMMWV";
  const std::string pov_dir = out_dir + "/POVRAY";
#endif

// =============================================================================

int main(int argc, char* argv[])
{
  SetChronoDataPath(CHRONO_DATA_DIR);

  // --------------------------
  // Create the various modules
  // --------------------------

  // Create the HMMWV vehicle
  HMMWV_Vehicle vehicle(false,
                        RWD,
                        PRIMITIVES,
                        MESH);

  vehicle.Initialize(ChCoordsys<>(initLoc, initRot));

  // Create the ground
  RigidTerrain terrain(vehicle.GetSystem(), terrainHeight, terrainLength, terrainWidth, 0.8);
  //terrain.AddMovingObstacles(10);
  terrain.AddFixedObstacles();

  // Create and initialize the powertrain system
  ChSharedPtr<ChPowertrain> powertrain;

  switch (powertrain_model) {
  case SHAFTS:
  {
    ChSharedPtr<HMMWV_Powertrain> ptrain(new HMMWV_Powertrain);

    ptrain->Initialize(vehicle.GetChassis(), vehicle.GetDriveshaft());
    powertrain = ptrain;

    break;
  }
  case SIMPLE:
  {
    ChSharedPtr<HMMWV_SimplePowertrain> ptrain(new HMMWV_SimplePowertrain);

    ptrain->Initialize();
    powertrain = ptrain;

    break;
  }
  }

  // Create and initialize the tires
  ChSharedPtr<ChTire> tire_front_right;
  ChSharedPtr<ChTire> tire_front_left;
  ChSharedPtr<ChTire> tire_rear_right;
  ChSharedPtr<ChTire> tire_rear_left;

  switch (tire_model) {
  case RIGID:
  {
    ChSharedPtr<HMMWV_RigidTire> tire_FL(new HMMWV_RigidTire("FL", terrain, 0.7f));
    ChSharedPtr<HMMWV_RigidTire> tire_FR(new HMMWV_RigidTire("FR", terrain, 0.7f));
    ChSharedPtr<HMMWV_RigidTire> tire_RL(new HMMWV_RigidTire("RL", terrain, 0.7f));
    ChSharedPtr<HMMWV_RigidTire> tire_RR(new HMMWV_RigidTire("RR", terrain, 0.7f));

    tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT));
    tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
    tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT));
    tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT));

    tire_front_left = tire_FL;
    tire_front_right = tire_FR;
    tire_rear_left = tire_RL;
    tire_rear_right = tire_RR;

    break;
  }
  case LUGRE:
  {
    ChSharedPtr<HMMWV_LugreTire> tire_FL(new HMMWV_LugreTire("FL", terrain));
    ChSharedPtr<HMMWV_LugreTire> tire_FR(new HMMWV_LugreTire("FR", terrain));
    ChSharedPtr<HMMWV_LugreTire> tire_RL(new HMMWV_LugreTire("RL", terrain));
    ChSharedPtr<HMMWV_LugreTire> tire_RR(new HMMWV_LugreTire("RR", terrain));

    tire_FL->Initialize();
    tire_FR->Initialize();
    tire_RL->Initialize();
    tire_RR->Initialize();

    tire_front_left = tire_FL;
    tire_front_right = tire_FR;
    tire_rear_left = tire_RL;
    tire_rear_right = tire_RR;

    break;
  }
  case PACEJKA:
  {
    std::string param_file = vehicle::GetDataFile("hmmwv/tire/HMMWV_pacejka.tir");

    ChSharedPtr<ChPacejkaTire> tire_FL(new ChPacejkaTire("FL", param_file, terrain));
    ChSharedPtr<ChPacejkaTire> tire_FR(new ChPacejkaTire("FR", param_file, terrain));
    ChSharedPtr<ChPacejkaTire> tire_RL(new ChPacejkaTire("RL", param_file, terrain));
    ChSharedPtr<ChPacejkaTire> tire_RR(new ChPacejkaTire("RR", param_file, terrain));

    tire_FL->Initialize(LEFT,false);
    tire_FR->Initialize(RIGHT,false);
    tire_RL->Initialize(LEFT,true);
    tire_RR->Initialize(RIGHT,true);

    tire_front_left = tire_FL;
    tire_front_right = tire_FR;
    tire_rear_left = tire_RL;
    tire_rear_right = tire_RR;

    break;
  }
  }

#ifdef USE_IRRLICHT
  irr::ChIrrApp application(vehicle.GetSystem(),
                            L"HMMWV demo",
                            irr::core::dimension2d<irr::u32>(1000, 800),
                            false,
                            true);

  // make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
  std::string mtexturedir = GetChronoDataFile("skybox/");
  std::string str_lf = mtexturedir + "sky_lf.jpg";
  std::string str_up = mtexturedir + "sky_up.jpg";
  std::string str_dn = mtexturedir + "sky_dn.jpg";
  irr::video::ITexture* map_skybox_side =
      application.GetVideoDriver()->getTexture(str_lf.c_str());
  irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
      application.GetVideoDriver()->getTexture(str_up.c_str()),
      application.GetVideoDriver()->getTexture(str_dn.c_str()),
      map_skybox_side,
      map_skybox_side,
      map_skybox_side,
      map_skybox_side);
  mbox->setRotation( irr::core::vector3df(90,0,0));

  bool do_shadows = false; // shadow map is experimental
  irr::scene::ILightSceneNode* mlight = 0;

  if (do_shadows) {
    mlight = application.AddLightWithShadow(
      irr::core::vector3df(10.f, 30.f, 60.f),
      irr::core::vector3df(0.f, 0.f, 0.f),
      150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
  } else {
    application.AddTypicalLights(
      irr::core::vector3df(30.f, -30.f, 100.f),
      irr::core::vector3df(30.f, 50.f, 100.f),
      250, 130);
  }

  application.SetTimestep(step_size);

  ChIrrGuiDriver driver(application, vehicle, *powertrain.get_ptr(), trackPoint, 6.0, 0.5, true);
  driver.LogInit("driver_inputs.out");

  // Set the time response for steering and throttle keyboard inputs.
  // NOTE: this is not exact, since we do not render quite at the specified FPS.
  double steering_time = 1.0;  // time to go from 0 to +1 (or from 0 to -1)
  double throttle_time = 1.0;  // time to go from 0 to +1
  double braking_time = 0.3;   // time to go from 0 to +1
  driver.SetSteeringDelta(render_step_size / steering_time);
  driver.SetThrottleDelta(render_step_size / throttle_time);
  driver.SetBrakingDelta(render_step_size / braking_time);

  // Set up the assets for rendering
  application.AssetBindAll();
  application.AssetUpdateAll();
  if (do_shadows)
  {
    application.AddShadowAll();
  }
#else
  HMMWV_FuncDriver driver;
#endif

  // ---------------
  // Simulation loop
  // ---------------

#ifdef DEBUG_LOG
  GetLog() << "\n\n============ System Configuration ============\n";
  vehicle.LogHardpointLocations();
#endif

  // Inter-module communication data
  ChTireForces  tire_forces(4);
  ChWheelState  wheel_states[4];
  double        driveshaft_speed;
  double        powertrain_torque;
  double        throttle_input;
  double        steering_input;
  double        braking_input;

  // Number of simulation steps between two 3D view render frames
  int render_steps = (int)std::ceil(render_step_size / step_size);

  // Number of simulation steps between two output frames
  int output_steps = (int)std::ceil(output_step_size / step_size);

  // Initialize simulation frame counter and simulation time
  int step_number = 0;
  double time = 0;

#ifdef USE_IRRLICHT

  ChRealtimeStepTimer realtime_timer;

  while (application.GetDevice()->run())
  {
    // update the position of the shadow mapping so that it follows the car
    if (do_shadows)
    {
      ChVector<> lightaim = vehicle.GetChassisPos();
      ChVector<> lightpos = vehicle.GetChassisPos() + ChVector<>(10, 30, 60);
      irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);
      irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);
      application.GetEffects()->getShadowLight(0).setPosition(mlightpos);
      application.GetEffects()->getShadowLight(0).setTarget(mlightaim);
      mlight->setPosition(mlightpos);
    }

    // Render scene
    if (step_number % render_steps == 0) {
      application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
      driver.DrawAll();
      application.GetVideoDriver()->endScene();
    }

#ifdef DEBUG_LOG
    if (step_number % output_steps == 0) {
      GetLog() << "\n\n============ System Information ============\n";
      GetLog() << "Time = " << time << "\n\n";
      vehicle.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
    }
#endif

    // Collect output data from modules (for inter-module communication)
    throttle_input = driver.GetThrottle();
    steering_input = driver.GetSteering();
    braking_input = driver.GetBraking();

    powertrain_torque = powertrain->GetOutputTorque();

    tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
    tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
    tire_forces[REAR_LEFT.id()] = tire_rear_left->GetTireForce();
    tire_forces[REAR_RIGHT.id()] = tire_rear_right->GetTireForce();

    driveshaft_speed = vehicle.GetDriveshaftSpeed();

    wheel_states[FRONT_LEFT.id()] = vehicle.GetWheelState(FRONT_LEFT);
    wheel_states[FRONT_RIGHT.id()] = vehicle.GetWheelState(FRONT_RIGHT);
    wheel_states[REAR_LEFT.id()] = vehicle.GetWheelState(REAR_LEFT);
    wheel_states[REAR_RIGHT.id()] = vehicle.GetWheelState(REAR_RIGHT);

    // Update modules (process inputs from other modules)
    time = vehicle.GetSystem()->GetChTime();

    driver.Update(time);
    if (step_number % output_steps == 0)
      driver.Log(time);

    terrain.Update(time);

    tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
    tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
    tire_rear_left->Update(time, wheel_states[REAR_LEFT.id()]);
    tire_rear_right->Update(time, wheel_states[REAR_RIGHT.id()]);

    powertrain->Update(time, throttle_input, driveshaft_speed);

    vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);

    // Advance simulation for one timestep for all modules
    double step = realtime_timer.SuggestSimulationStep(step_size);

    driver.Advance(step);

    terrain.Advance(step);

    tire_front_left->Advance(step);
    tire_front_right->Advance(step);
    tire_rear_right->Advance(step);
    tire_rear_left->Advance(step);

    powertrain->Advance(step);

    vehicle.Advance(step);

    // Increment frame number
    step_number++;
  }

  application.GetDevice()->drop();

#else

  int render_frame = 0;

  if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
    std::cout << "Error creating directory " << out_dir << std::endl;
    return 1;
  }
  if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
    std::cout << "Error creating directory " << pov_dir << std::endl;
    return 1;
  }

  vehicle.ExportMeshPovray(out_dir);

  char filename[100];

  while (time < tend)
  {
    if (step_number % render_steps == 0) {
      // Output render data
      sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
      utils::WriteShapesPovray(vehicle.GetSystem(), filename);
      std::cout << "Output frame:   " << render_frame << std::endl;
      std::cout << "Sim frame:      " << step_number << std::endl;
      std::cout << "Time:           " << time << std::endl;
      std::cout << "             throttle: " << driver.GetThrottle() << " steering: " << driver.GetSteering() << std::endl;
      std::cout << std::endl;
      render_frame++;
    }

#ifdef DEBUG_LOG
    if (step_number % output_steps == 0) {
      GetLog() << "\n\n============ System Information ============\n";
      GetLog() << "Time = " << time << "\n\n";
      vehicle.DebugLog(DBG_SHOCKS);
    }
#endif

    // Collect output data from modules (for inter-module communication)
    throttle_input = driver.GetThrottle();
    steering_input = driver.GetSteering();
    braking_input = driver.GetBraking();

    powertrain_torque = powertrain->GetOutputTorque();

    tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
    tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
    tire_forces[REAR_LEFT.id()] = tire_rear_left->GetTireForce();
    tire_forces[REAR_RIGHT.id()] = tire_rear_right->GetTireForce();

    driveshaft_speed = vehicle.GetDriveshaftSpeed();

    wheel_states[FRONT_LEFT.id()] = vehicle.GetWheelState(FRONT_LEFT);
    wheel_states[FRONT_RIGHT.id()] = vehicle.GetWheelState(FRONT_RIGHT);
    wheel_states[REAR_LEFT.id()] = vehicle.GetWheelState(REAR_LEFT);
    wheel_states[REAR_RIGHT.id()] = vehicle.GetWheelState(REAR_RIGHT);

    // Update modules (process inputs from other modules)
    time = vehicle.GetSystem()->GetChTime();

    driver.Update(time);

    terrain.Update(time);

    tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
    tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
    tire_rear_left->Update(time, wheel_states[REAR_LEFT.id()]);
    tire_rear_right->Update(time, wheel_states[REAR_RIGHT.id()]);

    powertrain->Update(time, throttle_input, driveshaft_speed);

    vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);

    // Advance simulation for one timestep for all modules
    driver.Advance(step_size);

    terrain.Advance(step_size);

    tire_front_right->Advance(step_size);
    tire_front_left->Advance(step_size);
    tire_rear_right->Advance(step_size);
    tire_rear_left->Advance(step_size);

    powertrain->Advance(step_size);

    vehicle.Advance(step_size);

    // Increment frame number
    step_number++;
  }

#endif

  return 0;
}


text:
/* $NetBSD: gpiosim.c,v 1.16 2014/02/25 18:30:09 pooka Exp $ */
/*      $OpenBSD: gpiosim.c,v 1.1 2008/11/23 18:46:49 mbalmer Exp $	*/

/*
 * Copyright (c) 2007 - 2011, 2013 Marc Balmer <marc@msys.ch>
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* 64 bit wide GPIO simulator  */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/gpio.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/sysctl.h>
#include <sys/ioccom.h>
#include <dev/gpio/gpiovar.h>

#define	GPIOSIM_NPINS	64

struct gpiosim_softc {
	device_t		sc_dev;
	device_t		sc_gdev;	/* gpio that attaches here */
	uint64_t		sc_state;
	struct gpio_chipset_tag	sc_gpio_gc;
	gpio_pin_t		sc_gpio_pins[GPIOSIM_NPINS];

	struct sysctllog	*sc_log;
};

static int	gpiosim_match(device_t, cfdata_t, void *);
void		gpiosimattach(int);
static void	gpiosim_attach(device_t, device_t, void *);
static int	gpiosim_detach(device_t, int);
static int	gpiosim_sysctl(SYSCTLFN_PROTO);

static int	gpiosim_pin_read(void *, int);
static void	gpiosim_pin_write(void *, int, int);
static void	gpiosim_pin_ctl(void *, int, int);

CFATTACH_DECL_NEW(gpiosim, sizeof(struct gpiosim_softc), gpiosim_match,
    gpiosim_attach, gpiosim_detach, NULL);

extern struct cfdriver gpiosim_cd;

static int
gpiosim_match(device_t parent, cfdata_t match, void *aux)
{
	return 1;
}

void
gpiosimattach(int num)
{
	cfdata_t cf;
	int n, err;

	err = config_cfattach_attach(gpiosim_cd.cd_name, &gpiosim_ca);
	if (err)
		printf("%s: unable to register cfattach\n", gpiosim_cd.cd_name);

	for (n = 0; n < num; n++) {
		cf = malloc(sizeof(*cf), M_DEVBUF, M_WAITOK);
		cf->cf_name = "gpiosim";
		cf->cf_atname = "gpiosim";
		cf->cf_unit = n;
		cf->cf_fstate = FSTATE_NOTFOUND;
		config_attach_pseudo(cf);
	}
}

static void
gpiosim_attach(device_t parent, device_t self, void *aux)
{
	struct gpiosim_softc *sc = device_private(self);
	struct gpiobus_attach_args gba;
	const struct sysctlnode *node;
	int i;

	sc->sc_dev = self;

	printf("%s", device_xname(sc->sc_dev));

	/* initialize pin array */
	for (i = 0; i < GPIOSIM_NPINS; i++) {
		sc->sc_gpio_pins[i].pin_num = i;
		sc->sc_gpio_pins[i].pin_caps = GPIO_PIN_INPUT |
		    GPIO_PIN_OUTPUT | GPIO_PIN_OPENDRAIN |
		    GPIO_PIN_PULLUP | GPIO_PIN_PULLDOWN |
		    GPIO_PIN_INVIN | GPIO_PIN_INVOUT;

		/* read initial state */
		sc->sc_gpio_pins[i].pin_flags = GPIO_PIN_INPUT;
	}
	sc->sc_state = 0;

	/* create controller tag */
	sc->sc_gpio_gc.gp_cookie = sc;
	sc->sc_gpio_gc.gp_pin_read = gpiosim_pin_read;
	sc->sc_gpio_gc.gp_pin_write = gpiosim_pin_write;
	sc->sc_gpio_gc.gp_pin_ctl = gpiosim_pin_ctl;

	/* gba.gba_name = "gpio"; */
	gba.gba_gc = &sc->sc_gpio_gc;
	gba.gba_pins = sc->sc_gpio_pins;
	gba.gba_npins = GPIOSIM_NPINS;

	pmf_device_register(self, NULL, NULL);

        sysctl_createv(&sc->sc_log, 0, NULL, &node,
            0,
            CTLTYPE_NODE, device_xname(sc->sc_dev),
            SYSCTL_DESCR("GPIO simulator"),
            NULL, 0, NULL, 0,
            CTL_HW, CTL_CREATE, CTL_EOL);

        if (node == NULL) {
		printf(": can't create sysctl node\n");
                return;
	}

        sysctl_createv(&sc->sc_log, 0, &node, NULL,
            CTLFLAG_READWRITE,
            CTLTYPE_QUAD, "value",
            SYSCTL_DESCR("Current GPIO simulator value"),
            gpiosim_sysctl, 0, (void *)sc, 0,
	    CTL_CREATE, CTL_EOL);

	printf(": simulating %d pins\n", GPIOSIM_NPINS);
	sc->sc_gdev = config_found_ia(self, "gpiobus", &gba, gpiobus_print);
}

static int
gpiosim_detach(device_t self, int flags)
{
	struct gpiosim_softc *sc = device_private(self);

	/* Detach the gpio driver that attached here */
	if (sc->sc_gdev != NULL)
		config_detach(sc->sc_gdev, 0);

	pmf_device_deregister(self);
	if (sc->sc_log != NULL) {
		sysctl_teardown(&sc->sc_log);
		sc->sc_log = NULL;
	}
	return 0;
}

static int
gpiosim_sysctl(SYSCTLFN_ARGS)
{
	struct sysctlnode node;
	struct gpiosim_softc *sc;
	uint64_t val, error;

	node = *rnode;
	sc = node.sysctl_data;

	node.sysctl_data = &val;

	val = sc->sc_state;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	sc->sc_state = val;
	return 0;
}

static int
gpiosim_pin_read(void *arg, int pin)
{
	struct gpiosim_softc *sc = arg;

	if (sc->sc_state & (1LL << pin))
		return GPIO_PIN_HIGH;
	else
		return GPIO_PIN_LOW;
}

static void
gpiosim_pin_write(void *arg, int pin, int value)
{
	struct gpiosim_softc *sc = arg;

	if (value == 0)
		sc->sc_state &= ~(1LL << pin);
	else
		sc->sc_state |= (1LL << pin);
}

static void
gpiosim_pin_ctl(void *arg, int pin, int flags)
{
	struct gpiosim_softc *sc = arg;

	sc->sc_gpio_pins[pin].pin_flags = flags;
}

MODULE(MODULE_CLASS_DRIVER, gpiosim, "gpio");

#ifdef _MODULE
static const struct cfiattrdata gpiobus_iattrdata = {
	"gpiobus", 0, { { NULL, NULL, 0 },}
};
static const struct cfiattrdata *const gpiosim_attrs[] = {
	&gpiobus_iattrdata, NULL
};
CFDRIVER_DECL(gpiosim, DV_DULL, gpiosim_attrs);
extern struct cfattach gpiosim_ca;
static int gpiosimloc[] = {
	-1,
	-1,
	-1
};
static struct cfdata gpiosim_cfdata[] = {
	{
		.cf_name = "gpiosim",
		.cf_atname = "gpiosim",
		.cf_unit = 0,
		.cf_fstate = FSTATE_STAR,
		.cf_loc = gpiosimloc,
		.cf_flags = 0,
		.cf_pspec = NULL,
	},
	{ NULL, NULL, 0, FSTATE_NOTFOUND, NULL, 0, NULL }
};
#endif

static int
gpiosim_modcmd(modcmd_t cmd, void *opaque)
{
#ifdef _MODULE
	int error = 0;
#endif
	switch (cmd) {
	case MODULE_CMD_INIT:
#ifdef _MODULE
		error = config_cfdriver_attach(&gpiosim_cd);
		if (error)
			return error;

		error = config_cfattach_attach(gpiosim_cd.cd_name,
		    &gpiosim_ca);
		if (error) {
			config_cfdriver_detach(&gpiosim_cd);
			aprint_error("%s: unable to register cfattach\n",
			    gpiosim_cd.cd_name);
			return error;
		}
		error = config_cfdata_attach(gpiosim_cfdata, 1);
		if (error) {
			config_cfattach_detach(gpiosim_cd.cd_name,
			    &gpiosim_ca);
			config_cfdriver_detach(&gpiosim_cd);
			aprint_error("%s: unable to register cfdata\n",
			    gpiosim_cd.cd_name);
			return error;
		}
		config_attach_pseudo(gpiosim_cfdata);
#endif
		return 0;
	case MODULE_CMD_FINI:
#ifdef _MODULE
		error = config_cfdata_detach(gpiosim_cfdata);
		if (error)
			return error;

		config_cfattach_detach(gpiosim_cd.cd_name, &gpiosim_ca);
		config_cfdriver_detach(&gpiosim_cd);
#endif
		return 0;
	case MODULE_CMD_AUTOUNLOAD:
		/* no auto-unload */
		return EBUSY;
	default:
		return ENOTTY;
	}
}


text:
package org.jboss.pnc.model;

import org.hibernate.annotations.ForeignKey;

import javax.persistence.*;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Date;

/**
 * Represents a product milestone. A single product version, for example "1.0", can be associated with several product
 * milestones such as "1.0.0.build1", "1.0.0.build2", etc. A milestone represents the set of work (build records) that was
 * performed during a development cycle from the previous milestone until the end of the current milestone.
 */
@Entity
@Table(uniqueConstraints = {
        @UniqueConstraint(columnNames = {"version", "productVersion_id"})
})
public class ProductMilestone implements GenericEntity<Integer> {

    private static final long serialVersionUID = 6314079319551264379L;

    public static final String SEQUENCE_NAME = "product_milestone_id_seq";

    @Id
    @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME)
    private Integer id;

    /**
     * Contains the milestone version string.  This consists of a major, minor, and micro
     * numeric version followed by an alphanumeric qualifier.  For example "1.0.0.ER1".
     */
    @Pattern(message="The version should consist of three numeric parts and one alphanumeric qualifier each separated by a dot" , regexp="^[0-9]+\\.[0-9]+\\.[0-9]+\\.[\\w]+$")
    @NotNull
    private String version;

    /**
     * The release (or handoff) date of this milestone
     */
    private Date endDate;

    /**
     * The scheduled starting date of this milestone
     */
    private Date startingDate;

    /**
     * The scheduled ending date of this milestone
     */
    private Date plannedEndDate;

    /**
     * URL which can be used to download the product distribution
     */
    private String downloadUrl;

    @NotNull
    @ManyToOne(cascade = { CascadeType.REFRESH })
    @ForeignKey(name = "fk_productmilestone_productversion")
    private ProductVersion productVersion;

    @OneToOne(mappedBy = "productMilestone")
    private ProductRelease productRelease;

    /**
     * Set of build records which represents the builds which were executed/performed during
     * this milestone build cycle.  This includes failed builds and builds which produced
     * artifacts which were later replaced by subsequent builds.
     * The intent of this field is to track total effort of a milestone, so for example,
     * failed builds consumed machine and human resources even though they were not delivered
     * with the product distribution.
     */
    @OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH })
    private BuildRecordSet performedBuildRecordSet;

    /**
     * Set of build records which represents the builds which generated artifacts included
     * in this product distribution.  Should not include builds which were run during
     * the milestone cycle but then later replaced by subsequent builds.
     * The intent of this field is to provide a way to lookup a build that produced a
     * specific artifact included in a particular product distribution.
     */
    @OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH })
    private BuildRecordSet distributedBuildRecordSet;

    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public ProductVersion getProductVersion() {
        return productVersion;
    }

    public void setProductVersion(ProductVersion productVersion) {
        this.productVersion = productVersion;
    }

    /**
     * The scheduled starting date of this milestone
     *
     * @return a Date
     */
    public Date getStartingDate() {
        return startingDate;
    }

    public void setStartingDate(Date startingDate) {
        this.startingDate = startingDate;
    }

    /**
     * The scheduled ending date of this milestone
     *
     * @return a Date
     */
    public Date getPlannedEndDate() {
        return plannedEndDate;
    }

    public void setPlannedEndDate(Date plannedEndDate) {
        this.plannedEndDate = plannedEndDate;
    }

    /**
     * The release (or handoff) date of this milestone
     *
     * @return a Date
     */
    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    /**
     * URL which can be used to download the product distribution
     *
     * @return The url where this milestone distribution can be downloaded
     */
    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }

    public BuildRecordSet getPerformedBuildRecordSet() {
        return performedBuildRecordSet;
    }

    public void setPerformedBuildRecordSet(BuildRecordSet performedBuildRecordSet) {
        this.performedBuildRecordSet = performedBuildRecordSet;
    }

    public BuildRecordSet getDistributedBuildRecordSet() {
        return distributedBuildRecordSet;
    }

    public void setDistributedBuildRecordSet(BuildRecordSet distributedBuildRecordSet) {
        this.distributedBuildRecordSet = distributedBuildRecordSet;
    }

    /**
     * If this milestone was promoted to a release, this field will be set. Will be null if the milestone was not relesed.
     *
     * @return the product release or null
     */
    public ProductRelease getProductRelease() {
        return productRelease;
    }

    public void setProductRelease(ProductRelease productRelease) {
        this.productRelease = productRelease;
    }

    @Override
    public String toString() {
        return "ProductMilestone [id=" + id + ", version=" + version + "]";
    }

    public static class Builder {

        private Integer id;

        private String version;

        private ProductVersion productVersion;

        private Date endDate;

        private Date startingDate;

        private Date plannedEndDate;

        private String downloadUrl;

        private BuildRecordSet performedBuildRecordSet;

        private BuildRecordSet distributedBuildRecordSet;

        private ProductRelease productRelease;

        private Builder() {
        }

        public static Builder newBuilder() {
            return new Builder();
        }

        public ProductMilestone build() {
            ProductMilestone productMilestone = new ProductMilestone();
            productMilestone.setId(id);
            productMilestone.setVersion(version);
            productMilestone.setEndDate(endDate);
            productMilestone.setStartingDate(startingDate);
            productMilestone.setPlannedEndDate(plannedEndDate);
            productMilestone.setDownloadUrl(downloadUrl);

            if (productVersion != null) {
                productVersion.addProductMilestone(productMilestone);
                productMilestone.setProductVersion(productVersion);
            }

            if (performedBuildRecordSet == null) {
                performedBuildRecordSet = BuildRecordSet.Builder.newBuilder()
                        .description("Performed in " + getProductName() + " " + productMilestone.getVersion())
                        .build();
            }
            performedBuildRecordSet.setPerformedInProductMilestone(productMilestone);
            productMilestone.setPerformedBuildRecordSet(performedBuildRecordSet);

            if (distributedBuildRecordSet == null) {
                distributedBuildRecordSet = BuildRecordSet.Builder.newBuilder()
                        .description("Distributed in " + getProductName() + " " + productMilestone.getVersion())
                        .build();
            }
            distributedBuildRecordSet.setDistributedInProductMilestone(productMilestone);
            productMilestone.setDistributedBuildRecordSet(distributedBuildRecordSet);

            if (productRelease != null) {
                productRelease.setProductMilestone(productMilestone);
                productMilestone.setProductRelease(productRelease);
            }

            return productMilestone;
        }

        public Builder id(Integer id) {
            this.id = id;
            return this;
        }

        public Builder version(String version) {
            this.version = version;
            return this;
        }

        public Builder endDate(Date endDate) {
            this.endDate = endDate;
            return this;
        }

        public Builder startingDate(Date startingDate) {
            this.startingDate = startingDate;
            return this;
        }

        public Builder plannedEndDate(Date plannedEndDate) {
            this.plannedEndDate = plannedEndDate;
            return this;
        }

        public Builder downloadUrl(String downloadUrl) {
            this.downloadUrl = downloadUrl;
            return this;
        }

        public Builder productVersion(ProductVersion productVersion) {
            this.productVersion = productVersion;
            return this;
        }

        public Builder performedBuildRecordSet(BuildRecordSet performedBuildRecordSet) {
            this.performedBuildRecordSet = performedBuildRecordSet;
            return this;
        }

        public Builder distributedBuildRecordSet(BuildRecordSet distributedBuildRecordSet) {
            this.distributedBuildRecordSet = distributedBuildRecordSet;
            return this;
        }

        public Builder productRelease(ProductRelease productRelease) {
            this.productRelease = productRelease;
            return this;
        }

        /**
         * Safe way to try to get the associated product name without worrying about null pointers
         *
         * @return The associated product name, or an empty string
         */
        public String getProductName() {
            if (productVersion != null && productVersion.getProduct() != null) {
                return productVersion.getProduct().getName();
            }
            return "";
        }
    }
}


text:
using IxMilia.Dxf;
using IxMilia.Dxf.Blocks;
using IxMilia.Dxf.Entities;
using Xunit;

namespace Examples
{
    public class TestExamples
    {
        [Fact]
        public void InsertBlockR12()
        {
            var file = new DxfFile();
            file.Header.Version = DxfAcadVersion.R12; // this example has only been tested on R12 drawings

            // create a block with a line from (0,0) to (1,1)
            var block = new DxfBlock();
            block.Name = "my-block";
            block.Entities.Add(new DxfLine(new DxfPoint(0.0, 0.0, 0.0), new DxfPoint(1.0, 1.0, 0.0)));
            file.Blocks.Add(block);

            // insert a copy of the block at location (3,3); the result is a line from (3,3) to (4,4)
            var insert = new DxfInsert();
            insert.Name = "my-block"; // this is the name of the block that we're going to insert
            insert.Location = new DxfPoint(3.0, 3.0, 0.0);
            file.Entities.Add(insert);

            file.SaveExample();
        }
    }
}


text:
layout: tagpage
tag: tech
---


text:
<?php

/**
 * @file
 * Contains Drupal\user\Access\RegisterAccessCheck.
 */

namespace Drupal\user\Access;

use Drupal\Core\Access\StaticAccessCheckInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Access check for user registration routes.
 */
class RegisterAccessCheck implements StaticAccessCheckInterface {

  /**
   * {@inheritdoc}
   */
  public function appliesTo() {
    return array('_access_user_register');
  }

  /**
   * Implements AccessCheckInterface::access().
   */
  public function access(Route $route, Request $request) {
    return user_is_anonymous() && (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: rebie
 * Date: 17-1-28
 * Time: 上午12:21
 */

namespace PreviewFramework\Utils;

trait ObjectTrait
{

    public static function getClassName()
    {
        return get_called_class();
    }
}


text:
__author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"

import unittest
from nose.plugins.attrib import attr
from mock import patch, MagicMock
import os
import sys

from jnpr.junos import Device
from jnpr.junos.ofacts.routing_engines import facts_routing_engines as routing_engines

from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSession

@attr("unit")
class TestRoutingEngines(unittest.TestCase):
    @patch("ncclient.manager.connect")
    @patch("jnpr.junos.device.warnings")
    def setUp(self, mock_warnings, mock_connect):
        mock_connect.side_effect = self._mock_manager
        self.dev = Device(
            host="1.1.1.1",
            user="rick",
            password="password123",
            gather_facts=False,
            fact_style="old",
        )
        self.dev.open()
        self.facts = {}
        self.mode = ""
        self.vc = False
        self.vct = False
        self.vcf = False

    @patch("jnpr.junos.Device.execute")
    @unittest.skipIf(sys.platform == "win32", "will work for windows in coming days")
    def test_multi_re_vc(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.mode = "multi"
        self.vc = True
        routing_engines(self.dev, self.facts)
        self.assertTrue(self.facts["vc_capable"])
        self.assertTrue(self.facts["2RE"])
        self.assertEqual(self.facts["RE0-RE1"]["mastership_state"], "backup")

    # This test is for an issue where a MX may return nothing for the vc rpc
    @patch("jnpr.junos.Device.execute")
    def test_vc_info_true(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.mode = "multi"
        self.vc = True
        self.vct = True
        routing_engines(self.dev, self.facts)
        self.assertFalse(self.facts["vc_capable"])
        self.assertTrue(self.facts["2RE"])
        self.assertEqual(self.facts["RE1"]["mastership_state"], "backup")

    @patch("jnpr.junos.Device.execute")
    @unittest.skipIf(sys.platform == "win32", "will work for windows in coming days")
    def test_mixed_mode_vcf(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.mode = "multi"
        self.vc = True
        self.vcf = True
        routing_engines(self.dev, self.facts)
        self.assertTrue(self.facts["vc_fabric"])
        self.assertEqual(self.facts["vc_mode"], "Mixed")

    @patch("jnpr.junos.Device.execute")
    def test_multi_instance(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.mode = "multi"
        routing_engines(self.dev, self.facts)
        self.assertTrue(self.facts["2RE"])

    @patch("jnpr.junos.Device.execute")
    def test_master(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.mode = "master"
        routing_engines(self.dev, self.facts)
        self.assertEqual(self.facts["RE0"]["mastership_state"], "master")

    @patch("jnpr.junos.Device.execute")
    def test_routing_engine_exception_ret_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.dev.rpc.get_route_engine_information = MagicMock(side_effect=ValueError)
        self.assertEqual(routing_engines(self.dev, self.facts), None)

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(
            foo, self.dev._conn._device_handler.transform_reply()
        )._NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            device_params = kwargs["device_params"]
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        if args:
            if self.vc is True and args[0].tag == "get-virtual-chassis-information":
                if self.vct is True:
                    return True
                elif self.vcf is True:
                    return self._read_file("get-virtual-chassis-information_mmvcf.xml")
                else:
                    return self._read_file("get-virtual-chassis-information.xml")
            return self._read_file(args[0].tag + "_" + self.mode + ".xml")


text:
"""
Extendable server handler for memcached binary protocol.

Socket servers (eg. gevent) should create one instance of ClientHandler
for each connection.

ClientHandler class can also be extended to handle your own commands:
 - add your extra context (eg. storage instance) in your own class __init__
 - add / override wanted do_OPNAME() methods

Another option is to pass in explicit handler dictionary. You then
need to define _all_ handlers, including QUIT, NOOP and others.

It's also possible to modify the handler dictionary from outside.

Note: this is just a prototype interface, and might change quite a bit
once glued together with existing storage implementations.
"""

from gmcbs.const import *
from collections import defaultdict
from datetime import timedelta
import logging
import os
import struct
import time

def pack_response(request, status=RESPONSE_SUCCESS, key=b'', extra=b'', value=b'', cas=0, datatype=TYPE_RAW_BYTES):
    """
    Formats a binary response based on request.
    NOTE: this doesn't use / create named tuples. Usually creating those objects is just extra overhead.
    Maybe those could be added later, if required (const.py already has some extra named tuples).
    For example, if connection loop part wants to access any of the values (hooks or similar)
    """
    header = struct.pack(HEADER_RESPONSE_FORMAT, MAGIC_RES, request.header.opcode,
                         len(key), len(extra), datatype, status,
                         len(key) + len(extra) + len(value),
                         request.header.opaque, cas)
    return header + extra + key + value

class ClientHandler(object):
    """ Handler for a single already-open client connection """
    def __init__(self, sock, handlers=None, set_thread_name=True):
        """
        :param sock: client socket for recv()/send()
        :param handlers: explicit request handlers, use numeric opcode as key
        :param set_thread_name: set thread name based on client address
        """
        self.log = logging.getLogger(self.__class__.__name__)
        # TODO: config? extra args, kwargs? maybe encourage sub-classing
        self.sock = sock
        if set_thread_name:
            # intentionally imported here, to make (gevent) monkey patching easier
            import threading
            threading.current_thread().setName("%s:%s" % sock.getpeername())

        self.buffer_in = bytearray()
        self.buffer_out = bytearray()

        self.stats = defaultdict(int)
        self.stats['time_init'] = time.time()

        if handlers is None:
            handlers = {}
            for opcode, opname in COMMANDS.iteritems():
                funcname = 'do_%s' % opname.lower()
                handler = getattr(self, funcname, None)
                if handler:
                    self.log.debug("registered handler %s (%#.2x): %r", opname, opcode, handler)
                    handlers[opcode] = handler
        self.handlers = handlers

    def read_bytes(self, amount, chunk_size=4096):
        """
        Return explicit amount of bytes from socket.
        Uses input buffer internally, for reading multiple request
        at the same go.

        :param amount: amount of bytes to return
        :param chunk_size: socket read sise
        :return: raw bytes
        """
        # i tried to use also memoryview + recv_into here, but something went horribly wrong.
        while len(self.buffer_in) < amount:
            chunk = self.sock.recv(chunk_size)
            self.log.debug("bytes read: %d", len(chunk))
            if chunk == '':
                # client most likely gone, but recv() doesn't fail
                break
            else:
                self.buffer_in.extend(chunk)

        ret = self.buffer_in[:amount]
        self.buffer_in = self.buffer_in[amount:]
        self.stats['bytes_read'] += amount
        return ret

    def read_request(self):
        """
        Reads a single client request using self.read_bytes().
        :return: Message named tuple (header, extra, key, value)
        """
        packet = self.read_bytes(HEADER_REQUEST_LEN)
        if not packet:
            return
        header = RequestHeader._make(struct.unpack(HEADER_REQUEST_FORMAT, packet))
        self.log.debug("header: %r", header)
        if header.magic != MAGIC_REQ:
            raise ValueError("Invalid magic byte %#.2x" % header.magic)

        # extra, key, value might also be empty strings
        extra = self.read_bytes(header.extlen)
        self.log.debug("extra: %r", extra)

        key = self.read_bytes(header.keylen)
        self.log.debug("key: %r", key)

        remaining = header.bodylen - header.extlen - header.keylen
        value = self.read_bytes(remaining)
        self.log.debug("value: %r", value)

        self.stats[header.opcode] += 1
        self.stats['ops'] += 1

        return Message(header, extra, key, value)

    # XXX: this interface might still change. or these default ones might disappear.
    # right now these are enough for pylibmc doing get_multi() + disconnect
    def do_get(self, request):
        return pack_response(request, status=RESPONSE_KEY_ENOENT)

    def do_getq(self, request):
        return self.do_get(request)

    def do_getk(self, request):
        return pack_response(request, key=request.key, status=RESPONSE_KEY_ENOENT)

    def do_getkq(self, request):
        return self.do_getk(request)

    def do_noop(self, request):
        return pack_response(request)

    def do_quit(self, request):
        return pack_response(request)

    def do_quitq(self, request):
        return self.do_quit(request)

    def do_stat(self, request):
        """ STAT command, expects multiple reply packets + one empty packet  """
        if request.key:
            # would need to read more memcached code for the specific keys
            self.log.warning("TODO: STAT %r", request)
            return pack_response(request, key=request.key, status=RESPONSE_KEY_ENOENT)
        stats = {
            'time': '%d' % time.time(),
            'pid': str(os.getpid()),
        }
        ret = []
        for key, value in stats.iteritems():
            ret.append(pack_response(request, key=key, value=value))
        ret.append(pack_response(request))
        return ''.join(ret)

    def send_replies(self):
        """ Flush all buffered replies (usually at least one) """
        if self.buffer_out:
            self.sock.sendall(self.buffer_out)
            self.stats['bytes_sent'] += len(self.buffer_out)
            self.log.debug("bytes sent: %d", len(self.buffer_out))
            self.buffer_out = bytearray()

    def serve_client(self):
        """
        Client connection loop. Serve until exception or QUIT command.
        TODO: gevent Timeout object? maybe outside?
        """
        self.log_stats("CONNECT")
        while True:
            request = self.read_request()
            self.log.debug("request: %r", request)
            if not request:
                self.log.error("No data received. Client disconnected?")
                break
            opcode = request.header.opcode
            if opcode in self.handlers:
                response = self.handlers[opcode](request)
            else:
                self.log.warning("No handler for %s %#.2x %r", COMMANDS.get(opcode), opcode, request.header)
                response = pack_response(request, status=RESPONSE_UNKNOWN_COMMAND)

            if response:
                self.buffer_out.extend(response)

            if opcode not in QUIET:
                self.send_replies()

            if opcode in (CMD_QUIT, CMD_QUITQ):
                self.log_stats(COMMANDS[opcode])
                self.stats['time_quit'] = time.time()
                break
        return self.stats

    def log_stats(self, prefix="STATUS", level=logging.INFO):
        """ Logs client statistics """
        # TODO: call this periodically? then it would be nice to show ops/s for the last period (not full connection)
        now = time.time()
        t_diff = now - self.stats['time_init']
        out = [
            "connection_time: %s" % timedelta(seconds=int(t_diff)),
            "ops/s: %.1f" % (self.stats['ops']/t_diff),
        ]
        for key in self.stats:
            out.append("%s: %s" % (COMMANDS.get(key, key), self.stats[key]))
        self.log.log(level, prefix + ": " + ", ".join(sorted(out)))


text:
<?php

namespace Majora\Framework\Serializer\Model;

@trigger_error('The '.__NAMESPACE__.'\ScopableInterface class is deprecated and will be removed in 2.0. Use Majora\Framework\Normalizer\Model\NormalizableInterface instead.', E_USER_DEPRECATED);

use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Majora\Framework\Normalizer\Model\NormalizableInterface;

/**
 * Interface to implements on all serializable models.
 *
 * @deprecated
 */
interface SerializableInterface extends ScopableInterface, NormalizableInterface
{
    /**
     * has to return an array representation of model.
     *
     * @param string                    $scope            optionnal scope of data
     * @param PropertyAccessorInterface $propertyAccessor optionnal instance of property accessor (used for accessing data)
     *
     * @see Majora\Framework\Serializer\Model\ScopableInterface
     * @see Majora\Framework\Serializer\Model\SerializableTrait
     *
     * @example
     *    return array(
     *        'id'        => $this->getId(),
     *        'firstname' => $this->getFirstname(),
     *        'skills'    => $this->getSkills()->serialize()
     *    );
     *
     * @return array
     */
    public function serialize($scope = 'default', PropertyAccessorInterface $propertyAccessor = null);

    /**
     * hydrate model from an array.
     *
     * @param array                     $objectData       model fields as array
     * @param PropertyAccessorInterface $propertyAccessor optionnal instance of property accessor (used for accessing data)
     *
     * @see Majora\Framework\Serializer\Model\SerializableTrait
     *
     * @return self
     */
    public function deserialize(array $objectData, PropertyAccessorInterface $propertyAccessor = null);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mThink.Geographic
{
    public enum Type
    {
        Free,
        TreeTop,
        TreeBranches
    }
}


text:
    #define CATCH_CONFIG_DISABLE_EXCEPTIONS
#endif

#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"

int main(int argc, char* argv[])
{
    // global setup...
	sockpp::socket_initializer sockInit;

    int result = Catch::Session().run(argc, argv);

    // global clean-up...

    return result;
}