text:
NSString *const kAlphaVideoFragmentShaderString = SHADER_STRING
(
        varying highp vec2 textureCoordinateRGB;
        varying highp vec2 textureCoordinateAlpha;

        uniform sampler2D inputImageTexture;

        void main() {
            highp vec4 rgbColor = texture2D(inputImageTexture, textureCoordinateRGB);
            highp vec4 alphaColor = texture2D(inputImageTexture, textureCoordinateAlpha);
            gl_FragColor = vec4(rgbColor.r, rgbColor.g, rgbColor.b, alphaColor.r);
        }
);

// OpenGL vertex shader to define the points to read the color and alpha values
NSString *const kAlphaVideoVertexShaderString = SHADER_STRING
(
        attribute vec4 position;
        attribute vec4 textureCoordinate;

        varying vec2 textureCoordinateRGB;
        varying vec2 textureCoordinateAlpha;

        void main() {
            gl_Position = position;
            textureCoordinateRGB = vec2(textureCoordinate.x, textureCoordinate.y);
            textureCoordinateAlpha = vec2(textureCoordinate.x + 0.5, textureCoordinate.y);
        }
);

// matches the attributes defined in the vertex shader
typedef NS_ENUM(NSInteger, ShaderAttribute) {
    ShaderAttributePosition,
    ShaderAttributeTextureCoordinate,
    NumShaderAttributes
};

@interface TSHAlphaVideoView ()
{
    // use old-school ivars so we can pass their addresses along to OpenGL calls
    CVOpenGLESTextureCacheRef videoTextureCache;
    GLuint displayProgram;
}
@end

@implementation TSHAlphaVideoView

- (void)dealloc
{
    if (displayProgram) {
        [self setCurrentGLContext];
        glDeleteProgram(displayProgram);
        displayProgram = 0;
    }

    CVOpenGLESTextureCacheFlush(videoTextureCache, 0);

    if (videoTextureCache) {
        CFRelease(videoTextureCache);
        videoTextureCache = 0;
    }
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame
                 andEAGLContext:[TSHGLHelpers getOpenGLESContext]];

    if (self != nil) {
        [self initializeVideoCache];
        [self initializeDisplayProgram];
    }

    return self;
}

// the openGL "program" compiles the vertex and fragment shaders so we can use
// them on the rendered pixels.
- (void)initializeDisplayProgram
{
    // Load OpenGL vertex and fragment shaders
    const GLchar *vertSrc = (GLchar *)[kAlphaVideoVertexShaderString UTF8String];
    const GLchar *fragSrc = (GLchar *)[kAlphaVideoFragmentShaderString UTF8String];

    // attributes found in the shaders
    GLint attribLocation[NumShaderAttributes] = {
            ShaderAttributePosition, ShaderAttributeTextureCoordinate,
    };
    GLchar *attribName[NumShaderAttributes] = {
            "position", "textureCoordinate",
    };

    [self setCurrentGLContext];

    // create the program, specifying which attributes and uniform variables are used in
    // the shaders.
    openGlCreateProgram(vertSrc, fragSrc,
                        NumShaderAttributes, (const GLchar **)&attribName[0], attribLocation,
                        0, 0, 0, // no uniform variables for now
                        &displayProgram);
}

- (void)initializeVideoCache
{
    [self setCurrentGLContext];

    //  Create a new CVOpenGLESTexture cache
    CVReturn err = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault,
                                                NULL,
                                                self.context,
                                                NULL,
                                                &videoTextureCache);
    if (err != kCVReturnSuccess) {
#if defined(DEBUG)
        NSLog(@"Error at CVOpenGLESTextureCacheCreate %d", err);
#endif
    }
}

- (void)renderWithSquareVertices:(const GLfloat *)squareVertices
                 textureVertices:(const GLfloat *)textureVertices
{
    [self setCurrentGLContext];

    // Use shader program.
    glUseProgram(displayProgram);

    // blend using the alpha of the frame
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Update attribute values.
    glVertexAttribPointer(ShaderAttributePosition, 2, GL_FLOAT, 0, 0, squareVertices);
    glEnableVertexAttribArray(ShaderAttributePosition);
    glVertexAttribPointer(ShaderAttributeTextureCoordinate, 2, GL_FLOAT, 0, 0, textureVertices);
    glEnableVertexAttribArray(ShaderAttributeTextureCoordinate);

    // Update uniform values if there are any (none for now).

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    // Present the buffer to be rendered on the screen.
    glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
    [self.context presentRenderbuffer:GL_RENDERBUFFER];

    glDisable(GL_BLEND);
}

- (CGRect)textureSamplingRectForCroppingTextureWithAspectRatio:(CGSize)textureAspectRatio
                                                 toAspectRatio:(CGSize)croppingAspectRatio
{
    CGRect normalizedSamplingRect = CGRectZero;
    CGSize cropScaleAmount = CGSizeMake(croppingAspectRatio.width / textureAspectRatio.width,
                                        croppingAspectRatio.height / textureAspectRatio.height);
    CGFloat maxScale = fmax(cropScaleAmount.width, cropScaleAmount.height);
    CGSize scaledTextureSize = CGSizeMake(textureAspectRatio.width * maxScale,
                                          textureAspectRatio.height * maxScale);

    if (cropScaleAmount.height > cropScaleAmount.width) {
        normalizedSamplingRect.size.width = croppingAspectRatio.width / scaledTextureSize.width;
        normalizedSamplingRect.size.height = 1.0;
    }
    else {
        normalizedSamplingRect.size.height = croppingAspectRatio.height / scaledTextureSize.height;
        normalizedSamplingRect.size.width = 1.0;
    }
    // Center crop (not needed yet).
    // normalizedSamplingRect.origin.x = (1.0 - normalizedSamplingRect.size.width)/2.0;
    // normalizedSamplingRect.origin.y = (1.0 - normalizedSamplingRect.size.height)/2.0;

    return normalizedSamplingRect;
}

- (void)displayPixelBuffer:(CVImageBufferRef)pixelBuffer
{
    [self setCurrentGLContext];

    // remove the last frame from the buffer each time you render the frame
    // so you don't see any ghosting between frames.
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    if (defaultFramebuffer == 0) {
        [self setFramebuffer];
    }

    if (videoTextureCache == NULL) {
        [self initializeVideoCache];
    }

    // the pixelBuffer contains all the pixel data for the frame we want
    // to display for the video, so make sure it is valid, and then
    // render the frame to the screen using OpenGL
    if (pixelBuffer != NULL) {

        // Create a CVOpenGLESTexture from the CVImageBuffer
        int frameWidth = (int)CVPixelBufferGetWidth(pixelBuffer);
        int frameHeight = (int)CVPixelBufferGetHeight(pixelBuffer);
        CVOpenGLESTextureRef texture = NULL;
        CVReturn err = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
                                                                    videoTextureCache,
                                                                    pixelBuffer,
                                                                    NULL,
                                                                    GL_TEXTURE_2D,
                                                                    GL_RGBA,
                                                                    frameWidth,
                                                                    frameHeight,
                                                                    GL_BGRA,
                                                                    GL_UNSIGNED_BYTE,
                                                                    0,
                                                                    &texture);

        if (!texture || err) {
#if defined(DEBUG)
            NSLog(@"CVOpenGLESTextureCacheCreateTextureFromImage failed (error: %d)", err);
#endif
            return;
        }

        glBindTexture(CVOpenGLESTextureGetTarget(texture), CVOpenGLESTextureGetName(texture));

        // Set texture parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer);

        // Set the view port to the entire view
        glViewport(0, 0, framebufferWidth, framebufferHeight);

        // set up the texture verticies for the frame texture
        static const GLfloat squareVertices[] = {
                -1.0f, -1.0f,
                1.0f, -1.0f,
                -1.0f, 1.0f,
                1.0f, 1.0f,
        };

        // The texture vertices are set up such that we flip the texture vertically.
        // This is so that our top left origin buffers match OpenGL's bottom left texture coordinate system.
        CGRect textureSamplingRect = [self textureSamplingRectForCroppingTextureWithAspectRatio:CGSizeMake(frameWidth, frameHeight)
                                                                                toAspectRatio:self.bounds.size];
        GLfloat textureVertices[] = {
                CGRectGetMinX(textureSamplingRect), CGRectGetMaxY(textureSamplingRect),
                CGRectGetMaxX(textureSamplingRect), CGRectGetMaxY(textureSamplingRect),
                CGRectGetMinX(textureSamplingRect), CGRectGetMinY(textureSamplingRect),
                CGRectGetMaxX(textureSamplingRect), CGRectGetMinY(textureSamplingRect),
        };

        // Draw the texture on the screen with OpenGL ES 2
        [self renderWithSquareVertices:squareVertices
                       textureVertices:textureVertices];

        glBindTexture(CVOpenGLESTextureGetTarget(texture), 0);

        // release the memory of the texture
        CFRelease(texture);
    }

    // make sure the video texture cache is flushed after each frame.
    CVOpenGLESTextureCacheFlush(videoTextureCache, 0);
}

- (void)prepareForBackground
{
    // call glFinish if the app is going into background mode to make sure no OpenGL
    // commands are run while in the background.
    [self setCurrentGLContext];
    glFinish();
}

- (void)setCurrentGLContext
{
    if (![[EAGLContext currentContext] isEqual:self.context]) {
        [EAGLContext setCurrentContext:self.context];
    }
}

@end


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Products_model extends CI_Model
{

    public $table = 'products';
    public $id = 'serial';
    public $order = 'DESC';

    function __construct()
    {
        parent::__construct();
    }

    // get all
    function get_all()
    {
        $this->db->order_by($this->id, $this->order);
        return $this->db->get($this->table)->result();
    }

    // get data by id
    function get_by_id($id)
    {
        $this->db->where($this->id, $id);
        return $this->db->get($this->table)->row();
    }

    // get total rows
    function total_rows() {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

    // get data with limit
    function index_limit($limit, $start = 0) {
        $this->db->order_by($this->id, $this->order);
        $this->db->limit($limit, $start);
        return $this->db->get($this->table)->result();
    }

    // get search total rows
    function search_total_rows($keyword = NULL) {
        $this->db->like('serial', $keyword);
	$this->db->or_like('name', $keyword);
	$this->db->or_like('description', $keyword);
	$this->db->or_like('price', $keyword);
	$this->db->or_like('picture', $keyword);
	$this->db->from($this->table);
        return $this->db->count_all_results();
    }

    // get search data with limit
    function search_index_limit($limit, $start = 0, $keyword = NULL) {
        $this->db->order_by($this->id, $this->order);
        $this->db->like('serial', $keyword);
	$this->db->or_like('name', $keyword);
	$this->db->or_like('description', $keyword);
	$this->db->or_like('price', $keyword);
	$this->db->or_like('picture', $keyword);
	$this->db->limit($limit, $start);
        return $this->db->get($this->table)->result();
    }

    // insert data
    function insert($data)
    {
        $this->db->insert($this->table, $data);
    }

    // update data
    function update($id, $data)
    {
        $this->db->where($this->id, $id);
        $this->db->update($this->table, $data);
    }

    // delete data
    function delete($id)
    {
        $this->db->where($this->id, $id);
        $this->db->delete($this->table);
    }

}

/* End of file Products_model.php */
/* Location: ./application/models/Products_model.php */

redpajama_set_name: RedPajamaGithub


text:
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  v8_fuzzer::FuzzerSupport* support = v8_fuzzer::FuzzerSupport::Get();
  v8::Isolate* isolate = support->GetIsolate();

  v8::Isolate::Scope isolate_scope(isolate);
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(support->GetContext());
  v8::TryCatch try_catch(isolate);

  v8::internal::Isolate* i_isolate =
      reinterpret_cast<v8::internal::Isolate*>(isolate);
  v8::internal::Factory* factory = i_isolate->factory();

  if (size > INT_MAX) return 0;
  v8::internal::MaybeHandle<v8::internal::String> source =
      factory->NewStringFromOneByte(
          v8::internal::Vector<const uint8_t>(data, static_cast<int>(size)));
  if (source.is_null()) return 0;

  v8::internal::Handle<v8::internal::Script> script =
      factory->NewScript(source.ToHandleChecked());
  v8::internal::Zone zone(i_isolate->allocator());
  v8::internal::ParseInfo info(&zone, script);
  info.set_global();
  v8::internal::Parser parser(&info);
  parser.Parse(&info);
  isolate->RequestGarbageCollectionForTesting(
      v8::Isolate::kFullGarbageCollection);
  return 0;
}


text:
var SectionsApp;
(function (SectionsApp) {
    function MessageDirective() {
        return {
            templateUrl: '/SectionApp/sections/NewMess/message.tpl',
            replace: false,
        };
    }
    SectionsApp.MessageDirective = MessageDirective;
})(SectionsApp || (SectionsApp = {}));
//# sourceMappingURL=MessageDirective.js.map


text:
MaterialLoadingProgressBar   provide a styled ProgressBar which looks  like SwipeRefreshLayout's loading indicator(support-v4  v21+)

![ProgressBar](https://github.com/lsjwzh/MaterialLoadingProgressBar/blob/master/screen.gif)
## Usage

### how to import?
add this into gradle

    compile('com.lsjwzh:materialloadingprogressbar:0.5.3-RELEASE')

### xml:

```
<com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar
        android:id="@+id/progressBar"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
```
### options:

```
<com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar
        android:id="@+id/progressBar"

        app:mlpb_show_arrow="true"
        app:mlpb_arrow_height="5dp"
        app:mlpb_arrow_width="10dp"
        app:mlpb_enable_circle_background="true"

        app:mlpb_progress_stoke_width="5dp"
        app:mlpb_progress_text_visibility="visible"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
```

### java api:
#### show arrow
'CircleProgressBar' will not show arrow by default.
You can enable arrow drawing like this:
```
    circleProgressBar.setShowArrow(true);
```

#### Disable circle background
There is a white circle background on drawing 'CircleProgressBar' by default.
If you need hide the circle background,you can add a xml item

```
    app:mlpb_enable_circle_background="false"
```

or set it by java code
```
   circleProgressBar.setCircleBackgroundEnabled(false);
```

### release notes:
    0.5.3: 	add default ring color;fix bug:NPE happens when ring color has never been setted.

    0.5.2: 	support setColorSchemeColors.

	0.5.1:  fix bug: arrow be putting into incorrect position.

	0.5.0: 	support enable/disable circle back ground.

	0.4.0:  fix bug:#1 :progressbar can not hide.
        	fix bug:#2 :progressbar show full ring when running  too long.

	0.3.0:  add showArrow option.

License
-------

    Copyright 2014 lsjwzh

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
var Cube = require("./vendor/cubejs/cube");
require("./vendor/cubejs/solve");

self.addEventListener("message", function (e) {
  if (e.data.name !== "solve") return;
  var state = e.data.state;

  // Slice our state into faces, so it's easy to manipulate
  var faces = {};
  "ULFRBD".split("").forEach(function (face, idx) {
    faces[face] = state.substring(idx*9, (idx+1)*9);
  });

  // Map our state to an unrotated one
  var mapping = {};
  Object.keys(faces).forEach(function (face) {
    mapping[faces[face][4]] = face;
  });
  Object.keys(faces).forEach(function (face) {
    faces[face] = faces[face].split("").map(function (c) {
      return (c in mapping) ? mapping[c] : c;
    }).join("");
  });

  // Solve!
  var cst = "URFDLB".split("").map(function (face) {
    return faces[face];
  }).join("");
  var alg = Cube.fromString(cst).solve();

  self.postMessage({ name: "solved", state: state, alg: alg });
});

Cube.initSolver();
self.postMessage({ name: "ready" });


text:
(function($) {
  $.eb = $.eb || {};

  // $.eb.ie = function (min,max) {
  //   // return true;
  //   if ($.browser.msie) {
  //     var v = Math.floor($.browser.version);
  //     if (v >= min && v <= max) {
  //       return true;
  //     }
  //   }
  //   return false;
  // }
  $.eb.ie6 = function () {
    return navigator.userAgent.toLowerCase().indexOf('msie 6.0') > -1;
    // alert(navigator.userAgent.toLowerCase().indexOf('msie 6.0'));
  }

  $.eb.color = function () {
    var pad = function(num, totalChars) {
        var pad = '0';
        num = num + '';
        while (num.length < totalChars) {
            num = pad + num;
        }
        return num;
    };

    // Ratio is between 0 and 1
    this.changeColor = function(color, ratio, darker) {
        // Trim trailing/leading whitespace
        color = color.replace(/^\s*|\s*$/, '');

        // Expand three-digit hex
        color = color.replace(
            /^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i,
            '#$1$1$2$2$3$3'
        );

        // Calculate ratio
        var difference = Math.round(ratio * 256) * (darker ? -1 : 1),
            // Determine if input is RGB(A)
            rgb = color.match(new RegExp('^rgba?\\(\\s*' +
                '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                '\\s*,\\s*' +
                '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                '\\s*,\\s*' +
                '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                '(?:\\s*,\\s*' +
                '(0|1|0?\\.\\d+))?' +
                '\\s*\\)$'
            , 'i')),
            alpha = !!rgb && rgb[4] != null ? rgb[4] : null,

            // Convert hex to decimal
            decimal = !!rgb? [rgb[1], rgb[2], rgb[3]] : color.replace(
                /^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i,
                function() {
                    return parseInt(arguments[1], 16) + ',' +
                        parseInt(arguments[2], 16) + ',' +
                        parseInt(arguments[3], 16);
                }
            ).split(/,/),
            returnValue;

        // Return RGB(A)
        return !!rgb ?
            'rgb' + (alpha !== null ? 'a' : '') + '(' +
                Math[darker ? 'max' : 'min'](
                    parseInt(decimal[0], 10) + difference, darker ? 0 : 255
                ) + ', ' +
                Math[darker ? 'max' : 'min'](
                    parseInt(decimal[1], 10) + difference, darker ? 0 : 255
                ) + ', ' +
                Math[darker ? 'max' : 'min'](
                    parseInt(decimal[2], 10) + difference, darker ? 0 : 255
                ) +
                (alpha !== null ? ', ' + alpha : '') +
                ')' :
            // Return hex
            [
                '#',
                pad(Math[darker ? 'max' : 'min'](
                    parseInt(decimal[0], 10) + difference, darker ? 0 : 255
                ).toString(16), 2),
                pad(Math[darker ? 'max' : 'min'](
                    parseInt(decimal[1], 10) + difference, darker ? 0 : 255
                ).toString(16), 2),
                pad(Math[darker ? 'max' : 'min'](
                    parseInt(decimal[2], 10) + difference, darker ? 0 : 255
                ).toString(16), 2)
            ].join('');
    };
    this.lighten = function(color, ratio) {
        return changeColor(color, ratio, false);
    };
    this.darken = function(color, ratio) {
        return changeColor(color, ratio, true);
    };
    return this;
  }();

  function bootstrapIE6(el) {
    var dropdownWidthFix = function (el) {
      el.each(function () {
        var w = 0;
        $(this).children('li').each(function() {
          var aw = $(this).outerWidth();
          if (aw > w) w = aw;
        });

        $(this).width(w);
      });
    }

    if ($.eb.ie6()) {
      el = el || $('html');

      //-------------
      // GRID
      //-------------

      //-------------
      // dropdown
      //-------------
      // fix for IE6 not support li:hover
      var i, lis = ['dropdown-submenu'];
      for (i = 0; i < lis.length; i++) {
        var child = 'li.' + lis[i];
        var hover = lis[i] + '-hover';
        $('ul', el).on('mouseenter', child, function () {
          $(this).addClass(hover);
        }).on('mouseleave', child, function () {
          $(this).removeClass(hover);
        });
      }

      /// fix :after selector -- dropdown-submenu > a:after
      $('.dropdown-submenu > a', el).after('');

      /// fix multi class selector -- .dropdown-submenu.pull-left
      $('.dropdown-submenu.pull-left', el).removeClass('pull-left').addClass('dropdown-submenu-pull-left');
      // $('.navbar .nav.pull-right').removeClass('pull-right').addClass('nav-pull-right');

      /// fix ul li 100% width bug, set ul width to max width of it's sub li
      dropdownWidthFix($('.dropdown-menu:visible', el));

      //-------------
      // buttons
      //-------------
      var btnColorCls = ['btn-primary','btn-warning','btn-danger','btn-success','btn-info','btn-inverse'];
      var btnSizeCls = ['btn-mini','btn-small','btn-large'];
      $('.btn-group', el).parent().find('.btn-group:eq(0)').addClass('btn-group-first');
      $('.btn', el).parent().find('.btn:eq(0)').addClass('btn-first');

      // fix button:hover
      $('body', el).on('mouseenter', '.btn', function () {
        var btn = $(this);
        var hover = 'btn-hover';
        btn.data('ie6hover',hover);
        $.each(btnColorCls, function (k,v) {
          if (btn.hasClass(v)) {
            hover = v + '-hover';
            btn.data('ie6hover',hover);
            return false;
          }
        });
        btn.addClass(hover);
      }).on('mouseleave', '.btn', function () {
        var btn = $(this);
        var hover = btn.data('ie6hover');
        btn.removeData('ie6hover');
        if (hover) btn.removeClass(hover);
      });

      // fix .btn.dropdown-toggle, .btn-primary.dropdown-toggle ...
      // fix .btn.dropdown-toggle, .btn-small.dropdown-toggle ...
      $('.btn.dropdown-toggle', el).each(function () {
        var btn = $(this);
        var ddt = 'btn-dropdown-toggle';
        btn.addClass(ddt);

        ddt = null;
        $.each(btnColorCls, function (k,v) {
          if (btn.hasClass(v)) {
            ddt = v + '-dropdown-toggle';
            return false;
          }
        });
        if (ddt) btn.addClass(ddt);

        ddt = null;
        $.each(btnSizeCls, function (k,v) {
          if (btn.hasClass(v)) {
            ddt = v + '-dropdown-toggle';
            return false;
          }
        });
        if (ddt) btn.addClass(ddt);
      });

      // fix split button dropdown toggle background color
      $('.btn + .btn.dropdown-toggle', el).each(function () {
        var btn = $(this);
        var c = btn.css('background-color');
        // alert($.eb.color.darken(c, .2));
        btn.css('background-color', $.eb.color.darken(c, .1));
      });

      // fix .btn-group.open
      var dropdownPropertyChange = function(e) {
        var self = $(this);
        var cls = e.data.cls;

        /// fix ul li 100% width bug, set ul width to max width of it's sub li
        var el = $('.dropdown-menu:visible', this);
        if (el.length) dropdownWidthFix(el);

        if (self.hasClass('open') && !self.hasClass(cls+'-open')) {
          self.addClass(cls+'-open');
        }
        else if (!self.hasClass('open') && self.hasClass(cls+'-open')) {
          self.removeClass(cls+'-open');
        }

        self.one('propertychange', {cls:cls}, dropdownPropertyChange);
      };
      $.each(['btn-group', 'dropdown'], function (k,cls) {
        $('.'+cls, el).one('propertychange', {cls:cls}, dropdownPropertyChange);
      });

      // fix .btn.disabled selector
      $('.btn.disabled', el).addClass('btn-disabled');

      var btnPropertyChange = function (e) {
        var self = $(this);
        var cls = e.data.cls;

        if (self.hasClass('disabled') && !self.hasClass(cls+'-disabled')) {
          self.addClass(cls+'-disabled');
        }
        else if (!self.hasClass('disabled') && self.hasClass(cls+'-disabled')) {
          self.removeClass(cls+'-disabled');
        }

        self.one('propertychange', {cls:cls}, btnPropertyChange);
      }
      $.each(['btn'], function (k,cls) {
        $('.'+cls, el).one('propertychange', {cls:cls}, btnPropertyChange);
      });

      //-------------
      // table
      //-------------

      // fix table-hover effect
      $('table.table-hover', el).on('mouseenter', 'tr', function () {
        $(this).addClass('tr-hover');
      }).on('mouseleave', 'tr', function () {
        $(this).removeClass('tr-hover');
      });

      //-------------
      // form
      //-------------

      // fix input[type=xxx] selector
      $('input[type="file"], input[type="image"], input[type="submit"], input[type="reset"], input[type="button"], input[type="radio"], input[type="checkbox"], input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"]', el).each(function () {
        var input = $(this);
        input.addClass('input-'+input.attr('type'));
      });

      // fix form-horizontal controls margin-left
      $('.form-horizontal .controls:first-child', el).addClass('controls-first-child');

      // fix .checkbox.inline
      $('.checkbox.inline', el).addClass('checkbox-inline');
      $('.radio.inline', el).addClass('radio-inline');

      // fix select[multiple], select[size]
      $('select[multiple]', el).addClass('select-multiple');
      $('select[size]', el).addClass('select-size');

      // fix tag[disabled]
      $('input[disabled], select[disabled], textarea[disabled]', el).each(function () {
        var self = $(this);
        self.addClass(self[0].tagName.toLowerCase()+'-disabled');
      });

//       $('input,select,textarea', el).on('propertychange', function() {
//         var self = $(this);
//         if (self.data('chgDisabled')) return;

//         var cls = self[0].tagName.toLowerCase();
// // alert(self.attr('disabled'));
//         if (self.attr('disabled') && !self.hasClass(cls+'-disabled')) {
//           // alert('abc');
//           self.addClass(cls+'-disabled');
//           self.data('chgDisabled', true);
//         }
//         else if (!self.attr('disabled') && self.hasClass(cls+'-disabled')) {
//           self.removeClass(cls+'-disabled');
//           self.data('chgDisabled', true);
//         }
//       });

//       $('input,select,textarea', el).on('propertychange', function() {
//         var self = $(this);
//         if (self.data('chgReadonly')) return;

//         var cls = self[0].tagName.toLowerCase();

//         if (self.attr('readonly') && !self.hasClass(cls+'-readonly')) {
//           self.addClass(cls+'-readonly');
//           self.data('chgReadonly', true);
//         }
//         else if (typeof self.attr('readonly') == 'undefined' && self.hasClass(cls+'-readonly')) {
//           self.removeClass(cls+'-readonly');
//           self.data('chgReadonly', true);
//         }
//       });

      // fix tag[readonly]
      $('input[readonly], select[readonly], textarea[readonly]', el).each(function () {
        var self = $(this);
        self.addClass(self[0].tagName.toLowerCase()+'-readonly');
      });

      // fix input[type=xxx][disabled]
      $('input[type="radio"][disabled], input[type="checkbox"][disabled]', el).each(function () {
        var self = $(this);
        self.addClass(self.attr('type').toLowerCase()+'-disabled');
      });

      // fix input[type=xxx][readonly]
      $('input[type="radio"][readonly], input[type="checkbox"][readonly]', el).each(function () {
        var self = $(this);
        self.addClass(self.attr('type').toLowerCase()+'-readonly');
      });

      // fix.control-group.warning ...
      var ctlGrpTypeCls = ['warning','success','error','info'];
      $.each(ctlGrpTypeCls, function (k,v) {
        $('.control-group.'+v, el).addClass('control-group-'+v);
      });

      var controlGroupPropertyChange = function(e) {
        if(e.originalEvent.propertyName.toLowerCase() == 'classname') {
          var self = $(this);
          $.each(ctlGrpTypeCls, function (k,v) {
            var ieCls = 'control-group-'+v;
            if (self.hasClass(v)) {
              if (!self.hasClass(ieCls)) {
                self.addClass(ieCls);
              }
            }
            else {
              if (self.hasClass(ieCls)) {
                self.removeClass(ieCls);
              }
            }
          });
        }
        $(this).one('propertychange', controlGroupPropertyChange);
      };
      $('.control-group', el).one('propertychange', controlGroupPropertyChange);

      //-------------
      // popover
      //-------------
      // $('.popover .arrow', el).after('');

      //-------------
      // pagination
      //-------------
      $('.pagination ul li:first-child', el).addClass('first-child');

      //-------------
      // icons
      //-------------
      $('[class^="icon-"],[class*=" icon-"]').each(function () {
        var self = $(this);
        if (!self.hasClass('icon-xxx')) {
          self.addClass('icon-xxx');
          self.css('background-position-y',
            (parseInt(self.css('background-position-y')) + 1)+'px');
        }
      });

      //-------------
      // carousel
      //-------------
      $('.carousel-control.left', el).removeClass('left').addClass('carousel-control-left');
      $('.carousel-control.right', el).removeClass('right').addClass('carousel-control-right');
      $('.carousel-caption').each(function() {
        var self = $(this);
        var padding = self.outerWidth() - self.width();
        self.width(self.parents('.carousel-inner .item').width() - padding);
      });

    }
  }
  $.bootstrapIE6 = bootstrapIE6;

  $(document).ready(function () {
    bootstrapIE6();
  });

})(jQuery);


text:
package uk.ac.ebi.phenotype.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import uk.ac.ebi.phenotype.service.PostQcService;

import java.io.IOException;
import java.net.URISyntaxException;

public class PipelineSolrImpl {

	@Autowired
	@Qualifier("postqcService")
	PostQcService gpService;

	public PipelineSolrImpl() {
	}

	public Parameter getParameterByStableId(
			String paramStableId, String queryString) throws IOException,
			URISyntaxException {

		return gpService.getParameterByStableId(paramStableId, queryString);
	}
}


text:
[View Javadoc](../../../../../../apidocs/org/apache/struts/chain/commands/AbstractSetOriginalURI.html.md)

    1
    21  package org.apache.struts.chain.commands;
    22
    23  import org.apache.struts.Globals;
    24  import org.apache.struts.chain.contexts.ActionContext;
    25
    26  /**
    27   *
Check to original uri is set, and if not, set it for this request.

    28   *
    29   * @version $Rev: 471754 $ $Date: 2005-06-04 07:58:46 -0700 (Sat, 04 Jun 2005)
    30   *          $
    31   */
    32  public abstract class AbstractSetOriginalURI extends ActionCommandBase {
    33      // ---------------------------------------------------------- Public Methods
    34
    35      /**
    36       *
Check to original uri is set, and if not, set it for this
    37       * request.

    38       *
    39       * @param actionCtx The Context for the current request
    40       * @return false so that processing continues
    41       * @throws Exception if thrown by the Action class
    42       */
    43      public boolean execute(ActionContext actionCtx)
    44          throws Exception {
    45          // Set the original uri if not already set
    46          if (!actionCtx.getRequestScope().containsKey(Globals.ORIGINAL_URI_KEY)) {
    47              setOriginalURI(actionCtx);
    48          }
    49
    50          return (false);
    51      }
    52
    53      // ------------------------------------------------------- Protected Methods
    54
    55      /**
    56       *
Set the original uri.

    57       *
    58       * @param context The Context for this request
    59       */
    60      protected abstract void setOriginalURI(ActionContext context);
    61  }

------------------------------------------------------------------------

This page was automatically generated by [Maven](http://maven.apache.org/)


text:
DefaultForce::DefaultForce(ofxWWTweetParticleManager& manager)
	:Force(manager)
	,last_time_activated(-1000)
	,should_hide_on(0)
	,hide_duration_millis(2800) // TODO add to settings
	,force_repulsion_spring_force(0.05f) // TODO add to settings
	,force_repulsion_rest_distance(2500)
	,force_repulsion_from_eachother(260)
	,apply_startup_force_duration_seconds(1.5)
{
	center.set(manager.simulationWidth * 0.5,manager.simulationHeight * 0.5);
}

bool DefaultForce::isReadyWithHiding() {
	return (ofGetElapsedTimeMillis() >= should_hide_on);
}

void DefaultForce::activateParticle(ofxWWTweetParticle& p) {
}

void DefaultForce::deactivateParticle(ofxWWTweetParticle& p) {
	p.static_force = (p.pos - center).normalize() * force_repulsion_spring_force;
	p.setState(ofxWWTweetParticle::STATE_HIDING);
}

// called once when showing.
void DefaultForce::activate() {
	last_time_activated = ofGetElapsedTimef();
	should_hide_on = ofGetElapsedTimeMillis() + hide_duration_millis; // TODO make setting
	vector<ofxWWTweetParticle>::iterator it = tweets.begin();
	while(it != tweets.end()) {
		ofxWWTweetParticle& p = (*it);
		p.setState(ofxWWTweetParticle::STATE_DEFAULT);
		++it;
	}
}

// called once, when hiding.
void DefaultForce::deactivate() {
	should_hide_on = ofGetElapsedTimeMillis() + hide_duration_millis; // TODO make setting
	vector<ofxWWTweetParticle>::iterator it = tweets.begin();
	while(it != tweets.end()) {
		ofxWWTweetParticle& p = (*it);
		p.static_force = (p.pos - center).normalize() * force_repulsion_spring_force;
		p.setState(ofxWWTweetParticle::STATE_HIDING);
		++it;
	}
}

// called when "active" mode
void DefaultForce::show() {
	size_t len = tweets.size();
	float fadeInUpSpeed = ofMap(ofGetElapsedTimef(), last_time_activated, last_time_activated+apply_startup_force_duration_seconds, 0, 1, true);
	for(int i = 0; i < len; i++){
		ofxWWTweetParticle& tweet = tweets[i];
		if(tweet.isSearchTweet){
			continue;
		}
		tweets[i].force.y += fadeInUpSpeed*(manager.tweetFlowSpeed + tweet.speedAdjust) * (1-tweet.clampedSelectionWeight);
	}
}

void DefaultForce::hide() {

	// repulse from selected search term.
	ofxWWSearchTerm selected_term;
	if(manager.getSearchTermManager().getSelectedSearchTerm(selected_term)) {
		center = selected_term.pos;
	}

	float now = ofGetElapsedTimeMillis();
	float diff = should_hide_on - now;
	float p = MAX(0, (diff / hide_duration_millis)); // TODO add to settings

	// repulse from
	vector<ofxWWTweetParticle>::iterator it = tweets.begin();
	ofVec2f dir;
	float dist = 0;
	float dist_sq = 0;
	float f	= 0;
	float duration_influance = sin(p*HALF_PI);
	float flow_force = manager.tweetFlowSpeed * 2;

	while(it != tweets.end()) {
		ofxWWTweetParticle& tweet = (*it);
		tweet.dot_opacity = p;
		dir = (center - tweet.pos);
		dist = dir.length();
		if(dist < force_repulsion_rest_distance) {
			f = (dist - force_repulsion_rest_distance) * force_repulsion_spring_force; // TODO add to settings
			dir.normalize();
			dir *= f;
			tweet.force += dir;
		}
		tweet.force.y += (flow_force + tweet.speedAdjust) * (1-tweet.clampedSelectionWeight);
		++it;
	}

	// repulse from eachother.
	it = tweets.begin();
	vector<ofxWWTweetParticle>::iterator other_it ;
	while(it != tweets.end()) {
		other_it = it+1;
		ofxWWTweetParticle& a = *it;
		while(other_it != tweets.end()) {
			ofxWWTweetParticle& b = *other_it;
			dir = (b.pos - a.pos);
			dist_sq = dir.lengthSquared();
			f = 1.0/dist_sq;
			if(f > 0.001 ) {
				dir *= f * force_repulsion_from_eachother; // 260;  // TODO add to settings
				a.force -= dir;
				b.force += dir;
			}
			++other_it;
		}
		++it;
	}
}


text:
from time import sleep
from datetime import datetime

import rethinkdb as r

import cryptoconditions as cc
from decorator import contextmanager

import bigchaindb
import bigchaindb.util
import bigchaindb.crypto

@contextmanager
def take_at_least_seconds(amount_in_seconds):
    t_issued = datetime.now()

    yield

    t_expired = datetime.now() - t_issued
    while t_expired.total_seconds() < amount_in_seconds:
        sleep(1)
        t_expired = datetime.now() - t_issued

def query_reql_response(response, query):
    result = list(response)

    if result and len(result):
        content = result[0]["transaction"]["data"]["payload"]["content"]
        if query and content is not None:
            if query in content:
                return result
        else:
            return result
    return None

def get_owned_assets(bigchain, vk, query=None, table='bigchain'):
    assets = []
    asset_ids = bigchain.get_owned_ids(vk)

    if table == 'backlog':
        reql_query = \
            r.table(table) \
                .filter(lambda tx: tx['transaction']['conditions']
                        .contains(lambda c: c['new_owners']
                                  .contains(vk)))
        response = query_reql_response(reql_query.run(bigchain.conn), query)
        if response:
            assets += response

    elif table == 'bigchain':
        for asset_id in asset_ids:
            txid = asset_id['txid'] if isinstance(asset_id, dict) else asset_id

            reql_query = r.table(table) \
                .concat_map(lambda doc: doc['block']['transactions']) \
                .filter(lambda transaction: transaction['id'] == txid)
            response = query_reql_response(reql_query.run(bigchain.conn), query)
            if response:
                assets += response

    return assets

def get_assets(bigchain, search):
    if search:
        cursor = \
            r.table('bigchain') \
                .concat_map(lambda doc: doc["block"]["transactions"]
                            .filter(lambda transaction: transaction["transaction"]["data"]["payload"]["content"]
                                    .match(search))) \
                .run(bigchain.conn)
    else:
        cursor = \
            r.table('bigchain') \
                .concat_map(lambda doc: doc["block"]["transactions"]).run(bigchain.conn)
    return list(cursor)

def create_asset(bigchain, to, payload):
    # a create transaction uses the operation `CREATE` and has no inputs
    tx = bigchain.create_transaction(bigchain.me, to, None, 'CREATE', payload=payload)

    # all transactions need to be signed by the user creating the transaction
    tx_signed = bigchain.sign_transaction(tx, bigchain.me_private)

    bigchain.validate_transaction(tx_signed)
    # write the transaction to the bigchain
    bigchain.write_transaction(tx_signed)
    return tx_signed

def create_asset_hashlock(bigchain, payload, secret):
    # Create a hash-locked asset without any new_owners
    hashlock_tx = bigchain.create_transaction(bigchain.me, None, None, 'CREATE', payload=payload)

    hashlock_tx_condition = cc.PreimageSha256Fulfillment(preimage=secret.encode())

    # The conditions list is empty, so we need to append a new condition
    hashlock_tx['transaction']['conditions'].append({
        'condition': {
            'details': hashlock_tx_condition.to_dict(),
            'uri': hashlock_tx_condition.condition.serialize_uri()
        },
        'cid': 0,
        'new_owners': None
    })

    # Conditions have been updated, so hash needs updating
    hashlock_tx['id'] = bigchaindb.util.get_hash_data(hashlock_tx)

    # The asset needs to be signed by the current_owner
    hashlock_tx_signed = bigchain.sign_transaction(hashlock_tx, bigchain.me_private)

    bigchain.validate_transaction(hashlock_tx_signed)
    # write the transaction to the bigchain
    bigchain.write_transaction(hashlock_tx_signed)
    return hashlock_tx_signed

def transfer_asset(bigchain, source, to, asset_id, sk):
    asset = bigchain.get_transaction(asset_id['txid'])
    asset_transfer = bigchain.create_transaction(source, to, asset_id, 'TRANSFER',
                                                 payload=asset['transaction']['data']['payload'])
    asset_transfer_signed = bigchain.sign_transaction(asset_transfer, sk)
    bigchain.validate_transaction(asset_transfer_signed)
    bigchain.write_transaction(asset_transfer_signed)
    return asset_transfer_signed

def escrow_asset(bigchain, source, to, asset_id, sk,
                 expires_at=None, ilp_header=None, execution_condition=None):
    asset = bigchain.get_transaction(asset_id['txid'])
    payload = asset['transaction']['data']['payload'].copy()
    if ilp_header:
        payload.update({'ilp_header': ilp_header})

    # Create escrow template with the execute and abort address
    asset_escrow = bigchain.create_transaction(source, [source, to], asset_id, 'TRANSFER',
                                               payload=payload)
    if not expires_at:
        # Set expiry time (100 secs from now)
        time_sleep = 100
        expires_at = float(bigchaindb.util.timestamp()) + time_sleep

    # Create escrow and timeout condition
    condition_escrow = cc.ThresholdSha256Fulfillment(threshold=1)  # OR Gate
    condition_timeout = cc.TimeoutFulfillment(expire_time=str(expires_at))  # only valid if now() <= time_expire
    condition_timeout_inverted = cc.InvertedThresholdSha256Fulfillment(threshold=1)
    condition_timeout_inverted.add_subfulfillment(condition_timeout)

    # Create execute branch
    execution_threshold = 3 if execution_condition else 2
    condition_execute = cc.ThresholdSha256Fulfillment(threshold=execution_threshold)  # AND gate
    condition_execute.add_subfulfillment(cc.Ed25519Fulfillment(public_key=to))  # execute address
    condition_execute.add_subfulfillment(condition_timeout)  # federation checks on expiry
    if execution_condition:
        condition_execute.add_subcondition_uri(execution_condition)
    condition_escrow.add_subfulfillment(condition_execute)

    # Create abort branch
    condition_abort = cc.ThresholdSha256Fulfillment(threshold=2)  # AND gate
    condition_abort.add_subfulfillment(cc.Ed25519Fulfillment(public_key=source))  # abort address
    condition_abort.add_subfulfillment(condition_timeout_inverted)
    condition_escrow.add_subfulfillment(condition_abort)

    # Update the condition in the newly created transaction
    asset_escrow['transaction']['conditions'][0]['condition'] = {
        'details': condition_escrow.to_dict(),
        'uri': condition_escrow.condition.serialize_uri()
    }

    # conditions have been updated, so hash needs updating
    asset_escrow['id'] = bigchaindb.util.get_hash_data(asset_escrow)

    # sign transaction
    asset_escrow_signed = bigchaindb.util.sign_tx(asset_escrow, sk, bigchain=bigchain)
    bigchain.write_transaction(asset_escrow_signed)
    return asset_escrow_signed

def fulfill_escrow_asset(bigchain, source, to, asset_id, sk, execution_fulfillment=None):
    asset = bigchain.get_transaction(asset_id['txid'])
    asset_owners = asset['transaction']['conditions'][asset_id['cid']]['new_owners']

    other_owner = [owner for owner in asset_owners if not owner == source][0]

    # Create a base template for fulfill transaction
    asset_escrow_fulfill = bigchain.create_transaction(asset_owners, to, asset_id, 'TRANSFER',
                                                       payload=asset['transaction']['data']['payload'])

    # Parse the threshold cryptocondition
    escrow_fulfillment = cc.Fulfillment.from_dict(
        asset['transaction']['conditions'][0]['condition']['details'])

    # Get the fulfillment message to sign
    tx_escrow_execute_fulfillment_message = \
        bigchaindb.util.get_fulfillment_message(asset_escrow_fulfill,
                                                asset_escrow_fulfill['transaction']['fulfillments'][0],
                                                serialized=True)

    # get the indices path for the source that wants to fulfill
    _, indices = get_subcondition_indices_from_vk(escrow_fulfillment, source)
    subfulfillment_source = escrow_fulfillment
    for index in indices:
        subfulfillment_source = subfulfillment_source.subconditions[index]['body']

    # sign the fulfillment
    subfulfillment_source.sign(tx_escrow_execute_fulfillment_message, bigchaindb.crypto.SigningKey(sk))

    # get the indices path for the other source that delivers the condition
    _, indices = get_subcondition_indices_from_vk(escrow_fulfillment, other_owner)
    subfulfillment_other = escrow_fulfillment.subconditions[indices[0]]['body']

    # update the condition
    del escrow_fulfillment.subconditions[indices[0]]
    escrow_fulfillment.add_subcondition(subfulfillment_other.condition)

    if execution_fulfillment:
        _, indices = get_subcondition_indices_from_type(escrow_fulfillment, cc.PreimageSha256Fulfillment.TYPE_ID)
        del escrow_fulfillment.subconditions[indices[0]]['body'].subconditions[indices[1]]
        escrow_fulfillment.subconditions[indices[0]]['body'].add_subfulfillment_uri(execution_fulfillment)

    asset_escrow_fulfill['transaction']['fulfillments'][0]['fulfillment'] = escrow_fulfillment.serialize_uri()

    bigchain.write_transaction(asset_escrow_fulfill)
    return asset_escrow_fulfill

def get_subcondition_indices_from_vk(condition, vk):
    if isinstance(vk, str):
        vk = vk.encode()

    conditions = []
    indices = []
    for i, c in enumerate(condition.subconditions):
        if isinstance(c['body'], cc.Ed25519Fulfillment) and c['body'].public_key.to_ascii(encoding='base58') == vk:
            indices.append(i)
            conditions.append(c['body'])
            break
        elif isinstance(c['body'], cc.ThresholdSha256Fulfillment):
            result, index = get_subcondition_indices_from_vk(c['body'], vk)
            if result:
                conditions += result
                indices += [i]
                indices += index
                break
    return conditions, indices

def get_subcondition_indices_from_type(condition, type_id):
    conditions = []
    indices = []
    for i, c in enumerate(condition.subconditions):
        if c['body'].type_id == type_id:
            indices.append(i)
            conditions.append(c['body'])
            break
        elif isinstance(c['body'], cc.ThresholdSha256Fulfillment):
            result, index = get_subcondition_indices_from_type(c['body'], type_id)
            if result:
                conditions += result
                indices += [i]
                indices += index
                break
    return conditions, indices


text:
<?php

?>
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>SwissPaymentSlip Example 01-01: OrangePaymentSlipData basic usage</title>

SwissPaymentSlip Example 01-01: OrangePaymentSlipData basic usage

<?php
// Make sure the classes get auto-loaded
require __DIR__.'/../vendor/autoload.php';

// Import necessary classes
use SwissPaymentSlip\SwissPaymentSlip\OrangePaymentSlipData;

// Create an orange payment slip data container (value object)
$paymentSlipData = new OrangePaymentSlipData();

// Fill the data container with your data
$paymentSlipData->setBankData('Seldwyla Bank', '8001 Zürich');
$paymentSlipData->setAccountNumber('01-145-6');
$paymentSlipData->setRecipientData('H. Muster AG', 'Versandhaus', 'Industriestrasse 88', '8000 Zürich');
$paymentSlipData->setPayerData('Rutschmann Pia', 'Marktgasse 28', '9400 Rorschach');
$paymentSlipData->setAmount(2830.50);
$paymentSlipData->setReferenceNumber('7520033455900012');
$paymentSlipData->setBankingCustomerId('215703');

// Output the data fields of the slip
echo "Bank name: " . $paymentSlipData->getBankName() . "
";
echo "Bank city: " . $paymentSlipData->getBankCity() . "
";
echo "
";
echo "Recipient line 1: " . $paymentSlipData->getRecipientLine1() . "
";
echo "Recipient line 2: " . $paymentSlipData->getRecipientLine2() . "
";
echo "Recipient line 3: " . $paymentSlipData->getRecipientLine3() . "
";
echo "Recipient line 4: " . $paymentSlipData->getRecipientLine4() . "
";
echo "
";
echo "Account number: " . $paymentSlipData->getAccountNumber() . "
";
echo "
";
echo "Amount: " . $paymentSlipData->getAmount() . "
";
echo "Amount in francs: " . $paymentSlipData->getAmountFrancs() . "
";
echo "Amount in cents: " . $paymentSlipData->getAmountCents() . "
";
echo "
";
echo "Payer line 1: " . $paymentSlipData->getPayerLine1() . "
";
echo "Payer line 2: " . $paymentSlipData->getPayerLine2() . "
";
echo "Payer line 3: " . $paymentSlipData->getPayerLine3() . "
";
echo "Payer line 4: " . $paymentSlipData->getPayerLine4() . "
";
echo "
";
echo "Banking customer ID: " . $paymentSlipData->getBankingCustomerId() . "
";
echo "
";
echo "Complete reference number (with banking customer ID): " . $paymentSlipData->getCompleteReferenceNumber() . "
";
echo "
";
echo "Code line (at the bottom): " . $paymentSlipData->getCodeLine() . "
";
echo "
";

// Dump object to screen
echo "This is how your data container looks now:
";
var_dump($paymentSlipData);
?>


text:
package org.apache.hyracks.storage.am.bloomfilter.impls;

/**
 * This class has been taken from cassandra source code with minor modifications.
 */

/**
 * The following calculations are taken from:
 * http://www.cs.wisc.edu/~cao/papers/summary-cache/node8.html
 * "Bloom Filters - the math"
 * This class's static methods are meant to facilitate the use of the Bloom
 * Filter class by helping to choose correct values of 'bits per element' and
 * 'number of hash functions, k'.
 */
public class BloomCalculations {

    private static final int minBuckets = 2;
    private static final int minK = 1;

    /**
     * In the following table, the row 'i' shows false positive rates if i buckets
     * per element are used. Column 'j' shows false positive rates if j hash
     * functions are used. The first row is 'i=0', the first column is 'j=0'.
     * Each cell (i,j) the false positive rate determined by using i buckets per
     * element and j hash functions.
     */
    static final double[][] probs = new double[][] {
            { 1.0 }, // dummy row representing 0 buckets per element
            { 1.0, 1.0 }, // dummy row representing 1 buckets per element
            { 1.0, 0.393, 0.400 },
            { 1.0, 0.283, 0.237, 0.253 },
            { 1.0, 0.221, 0.155, 0.147, 0.160 },
            { 1.0, 0.181, 0.109, 0.092, 0.092, 0.101 }, // 5
            { 1.0, 0.154, 0.0804, 0.0609, 0.0561, 0.0578, 0.0638 },
            { 1.0, 0.133, 0.0618, 0.0423, 0.0359, 0.0347, 0.0364 },
            { 1.0, 0.118, 0.0489, 0.0306, 0.024, 0.0217, 0.0216, 0.0229 },
            { 1.0, 0.105, 0.0397, 0.0228, 0.0166, 0.0141, 0.0133, 0.0135, 0.0145 },
            { 1.0, 0.0952, 0.0329, 0.0174, 0.0118, 0.00943, 0.00844, 0.00819, 0.00846 }, // 10
            { 1.0, 0.0869, 0.0276, 0.0136, 0.00864, 0.0065, 0.00552, 0.00513, 0.00509 },
            { 1.0, 0.08, 0.0236, 0.0108, 0.00646, 0.00459, 0.00371, 0.00329, 0.00314 },
            { 1.0, 0.074, 0.0203, 0.00875, 0.00492, 0.00332, 0.00255, 0.00217, 0.00199, 0.00194 },
            { 1.0, 0.0689, 0.0177, 0.00718, 0.00381, 0.00244, 0.00179, 0.00146, 0.00129, 0.00121, 0.0012 },
            { 1.0, 0.0645, 0.0156, 0.00596, 0.003, 0.00183, 0.00128, 0.001, 0.000852, 0.000775, 0.000744 }, // 15
            { 1.0, 0.0606, 0.0138, 0.005, 0.00239, 0.00139, 0.000935, 0.000702, 0.000574, 0.000505, 0.00047, 0.000459 },
            { 1.0, 0.0571, 0.0123, 0.00423, 0.00193, 0.00107, 0.000692, 0.000499, 0.000394, 0.000335, 0.000302,
                    0.000287, 0.000284 },
            { 1.0, 0.054, 0.0111, 0.00362, 0.00158, 0.000839, 0.000519, 0.00036, 0.000275, 0.000226, 0.000198,
                    0.000183, 0.000176 },
            { 1.0, 0.0513, 0.00998, 0.00312, 0.0013, 0.000663, 0.000394, 0.000264, 0.000194, 0.000155, 0.000132,
                    0.000118, 0.000111, 0.000109 },
            { 1.0, 0.0488, 0.00906, 0.0027, 0.00108, 0.00053, 0.000303, 0.000196, 0.00014, 0.000108, 8.89e-05,
                    7.77e-05, 7.12e-05, 6.79e-05, 6.71e-05 } // 20
    }; // the first column is a dummy column representing K=0.

    /**
     * The optimal number of hashes for a given number of bits per element.
     * These values are automatically calculated from the data above.
     */
    private static final int[] optKPerBuckets = new int[probs.length];

    static {
        for (int i = 0; i < probs.length; i++) {
            double min = Double.MAX_VALUE;
            double[] prob = probs[i];
            for (int j = 0; j < prob.length; j++) {
                if (prob[j] < min) {
                    min = prob[j];
                    optKPerBuckets[i] = Math.max(minK, j);
                }
            }
        }
    }

    /**
     * Given the number of buckets that can be used per element, return a
     * specification that minimizes the false positive rate.
     *
     * @param bucketsPerElement
     *            The number of buckets per element for the filter.
     * @return A spec that minimizes the false positive rate.
     */
    public static BloomFilterSpecification computeBloomSpec(int bucketsPerElement) {
        assert bucketsPerElement >= 1;
        assert bucketsPerElement <= probs.length - 1;
        return new BloomFilterSpecification(optKPerBuckets[bucketsPerElement], bucketsPerElement);
    }

    /**
     * Given a maximum tolerable false positive probability, compute a Bloom
     * specification which will give less than the specified false positive rate,
     * but minimize the number of buckets per element and the number of hash
     * functions used. Because bandwidth (and therefore total bitvector size)
     * is considered more expensive than computing power, preference is given
     * to minimizing buckets per element rather than number of hash functions.
     *
     * @param maxBucketsPerElement
     *            The maximum number of buckets available for the filter.
     * @param maxFalsePosProb
     *            The maximum tolerable false positive rate.
     * @return A Bloom Specification which would result in a false positive rate
     *         less than specified by the function call
     * @throws UnsupportedOperationException
     *             if a filter satisfying the parameters cannot be met
     */
    public static BloomFilterSpecification computeBloomSpec(int maxBucketsPerElement, double maxFalsePosProb) {
        assert maxBucketsPerElement >= 1;
        assert maxBucketsPerElement <= probs.length - 1;
        int maxK = probs[maxBucketsPerElement].length - 1;

        // Handle the trivial cases
        if (maxFalsePosProb >= probs[minBuckets][minK]) {
            return new BloomFilterSpecification(2, optKPerBuckets[2]);
        }
        if (maxFalsePosProb < probs[maxBucketsPerElement][maxK]) {
            throw new UnsupportedOperationException(String.format("Unable to satisfy %s with %s buckets per element",
                    maxFalsePosProb, maxBucketsPerElement));
        }

        // First find the minimal required number of buckets:
        int bucketsPerElement = 2;
        int K = optKPerBuckets[2];
        while (probs[bucketsPerElement][K] > maxFalsePosProb) {
            bucketsPerElement++;
            K = optKPerBuckets[bucketsPerElement];
        }
        // Now that the number of buckets is sufficient, see if we can relax K
        // without losing too much precision.
        while (probs[bucketsPerElement][K - 1] <= maxFalsePosProb) {
            K--;
        }

        return new BloomFilterSpecification(K, bucketsPerElement);
    }

    /**
     * Calculates the maximum number of buckets per element that this implementation
     * can support. Crucially, it will lower the bucket count if necessary to meet
     * BitSet's size restrictions.
     */
    public static int maxBucketsPerElement(long numElements) {
        numElements = Math.max(1, numElements);
        double v = Long.MAX_VALUE / (double) numElements;
        if (v < 1.0) {
            throw new UnsupportedOperationException("Cannot compute probabilities for " + numElements + " elements.");
        }
        return Math.min(BloomCalculations.probs.length - 1, (int) v);
    }
}


text:
#pragma once

#include "stream_builder.h"

class StreamBuilderCustom final : public StreamBuilder {
public:
    StreamBuilderCustom()
        : StreamBuilder()
    {
    }
    ~StreamBuilderCustom() {}

    std::vector<Stream *> build_streams(ConfFile &conf);
};


text:
<?php

use yii\db\Migration;
use yii\db\Schema;

class m150406_193007_create_status_table extends Migration
{
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%status}}', [
            'id' => Schema::TYPE_PK,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'color' => Schema::TYPE_STRING . ' NOT NULL',
            'background' => Schema::TYPE_STRING . ' NOT NULL',
        ], $tableOptions);
    }

    public function safeDown()
    {
        $this->dropTable('{{%status}}');
    }
}


text:
import * as React from "react";
import { Row, Col, BlurableInput } from "../../ui";
import { VariableNode } from "../locals_list/locals_list_support";
import { defensiveClone } from "../../util/util";
import { Xyz, Vector3 } from "farmbot";
import { determineEditable } from "../../resources/sequence_meta";
import { t } from "../../i18next_wrapper";

export interface AxisEditProps {
  axis: Xyz;
  onChange: (sd: VariableNode) => void;
  editableVariable: VariableNode;
}

/** Update a variable coordinate. */
export const manuallyEditAxis = (props: AxisEditProps) =>
  (e: React.SyntheticEvent<HTMLInputElement>) => {
    const { axis, onChange, editableVariable } = props;
    const num = parseFloat(e.currentTarget.value);
    if (editableVariable.kind !== "parameter_declaration" &&
      editableVariable.args.data_value.kind === "coordinate") {
      editableVariable.args.data_value.args[axis] = num;
      !isNaN(num) && onChange(editableVariable);
    }
  };

/** For LocationForm coordinate input boxes.  */
interface CoordinateInputBoxesProps {
  vector: Vector3 | undefined;
  variableNode: VariableNode;
  width: number | undefined;
  onChange: (sd: VariableNode | undefined) => void;
}

/** LocationForm coordinate input boxes.  */
export const CoordinateInputBoxes = (props: CoordinateInputBoxesProps) => {
  const { variableNode, vector, onChange } = props;
  /** Show coordinate input boxes if editable (not using external data). */
  const visible = determineEditable(variableNode);
  const editableVariable = defensiveClone(variableNode);
  return (vector && visible)
    ? <Row>
      {["x", "y", "z"].map((axis: Xyz) =>
        <Col xs={props.width || 4} key={axis}>
          <label>
            {t("{{axis}} (mm)", { axis })}
          </label>
          <BlurableInput type="number"
            onCommit={manuallyEditAxis({ axis, onChange, editableVariable })}
            name={`location-${axis}`}
            value={"" + vector[axis]} />
        </Col>)}
    </Row>
    : <div />;
};


text:
/**
 *

 *
ForecastRestYahooSax

 *
com.android2ee.formation.restservice.sax.forecastyahoo

 *
28 mai 2014

 *

 *
======================================================

 *

 *
Projet : Mathias Seguy Project

 *
Produit par MSE.

 *

 * /**
 *

 * Android Tutorial, An Android2EE's project.

 * Produced by Dr. Mathias SEGUY.

 * Delivered by http://android2ee.com/

 * Belongs to Mathias Seguy

 * ***************************************************************************************************************

 * This code is free for any usage but can't be distribute.

 * The distribution is reserved to the site http://android2ee.com.

 * The intelectual property belongs to Mathias Seguy.

 * http://mathias-seguy.developpez.com/

 *

 * *****************************************************************************************************************

 * Ce code est libre de toute utilisation mais n'est pas distribuable.

 * Sa distribution est reservée au site http://android2ee.com.

 * Sa propriété intellectuelle appartient à Mathias Seguy.

 * http://mathias-seguy.developpez.com/

 * *****************************************************************************************************************

 */

package com.android2ee.recyclerview.viewpager;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;

import com.android2ee.recyclerview.fragments.CardViewRecyclerViewFrag;
import com.android2ee.recyclerview.fragments.GridRecyclerViewFrag;
import com.android2ee.recyclerview.fragments.LinearRecyclerViewFrag;
import com.android2ee.recyclerview.fragments.StaggeredRecyclerViewFrag;

import java.util.ArrayList;

/**
 * Created by Mathias Seguy - Android2EE on 19/05/2015.
 * This class is an Adapter, it's goal is to give at the right time the right view
 * So nothing complex here
 * This class only deal with Fragments !!!
 */
public class MyPagerAdapter extends FragmentPagerAdapter {

    /**
     * The list of ordered fragments
     */
    private final ArrayList<Fragment> fragments;

    //On fournit à l'adapter la liste des fragments à afficher

    /***
     * The constructor
     * @param ctx The Context
     */
    public MyPagerAdapter(AppCompatActivity ctx) {
        super(ctx.getSupportFragmentManager());
        fragments = new ArrayList<Fragment>();
        //A stuff I never did before, instanciate my fragment
        fragments.add(new LinearRecyclerViewFrag());
        fragments.add(new GridRecyclerViewFrag());
        fragments.add(new StaggeredRecyclerViewFrag());
        //TODO uncomment that line and the opengl bug disappears
        fragments.add(new CardViewRecyclerViewFrag());

    }
    @Override
    public int getCount() {
        return fragments.size();
    }
    /**
     * This method may be called by the ViewPager to obtain a title string
     * to describe the specified page. This method may return null
     * indicating no title for this page. The default implementation returns
     * null.
     *
     * @param position The position of the title requested
     * @return A title for the requested page
     */
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0: return "Linear";
            case 1: return "Grid";
            case 2: return "Stag";
            case 3: return "CardView";
        }
        return "This is the Page "+position;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

}


text:
package net.magik6k.jwwf.util;

import net.magik6k.jwwf.core.Group;
import net.magik6k.jwwf.handlers.SelectionHandler;

public final class RadioGroup extends Group {
	private SelectionHandler handler;

	/**
	 * Creates new RadioGroup with default selection hndler
	 *
	 * @param handler Handler to be fired when user selects some option
	 */
	public RadioGroup(SelectionHandler handler) {
		this.handler = handler;
	}

	public RadioGroup() {
	}

	/**
	 * Sets new selection handler
	 *
	 * @param handler Handler to be fired when user selects some option
	 * @return This instance for chaining
	 */
	public RadioGroup setHandler(SelectionHandler handler) {
		this.handler = handler;
		return this;
	}

	/**
	 * Internal use only
	 *
	 * @param userdata userdata
	 */
	public void select(Object userdata) {
		if (handler != null)
			handler.select(userdata);
	}

}


text:
class EXPCL_PANDA_PGUI PGScrollFrame : public PGVirtualFrame, public PGSliderBarNotify {
PUBLISHED:
  PGScrollFrame(const string &name = "");
  virtual ~PGScrollFrame();

protected:
  PGScrollFrame(const PGScrollFrame &copy);

public:
  virtual PandaNode *make_copy() const;
  virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data);
  virtual void xform(const LMatrix4 &mat);

PUBLISHED:
  void setup(PN_stdfloat width, PN_stdfloat height,
             PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top,
             PN_stdfloat slider_width, PN_stdfloat bevel);

  INLINE void set_virtual_frame(PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top);
  INLINE void set_virtual_frame(const LVecBase4 &virtual_frame);
  INLINE const LVecBase4 &get_virtual_frame() const;
  INLINE bool has_virtual_frame() const;
  INLINE void clear_virtual_frame();

  INLINE void set_manage_pieces(bool manage_pieces);
  INLINE bool get_manage_pieces() const;

  INLINE void set_auto_hide(bool auto_hide);
  INLINE bool get_auto_hide() const;

  INLINE void set_horizontal_slider(PGSliderBar *horizontal_slider);
  INLINE void clear_horizontal_slider();
  INLINE PGSliderBar *get_horizontal_slider() const;

  INLINE void set_vertical_slider(PGSliderBar *vertical_slider);
  INLINE void clear_vertical_slider();
  INLINE PGSliderBar *get_vertical_slider() const;

  void remanage();
  INLINE void recompute();

protected:
  virtual void frame_changed();

  virtual void item_transform_changed(PGItem *item);
  virtual void item_frame_changed(PGItem *item);
  virtual void item_draw_mask_changed(PGItem *item);
  virtual void slider_bar_adjust(PGSliderBar *slider_bar);

private:
  void recompute_clip();

  void recompute_canvas();
  PN_stdfloat interpolate_canvas(PN_stdfloat clip_min, PN_stdfloat clip_max,
                           PN_stdfloat canvas_min, PN_stdfloat canvas_max,
                           PGSliderBar *slider_bar);

private:
  bool _needs_remanage;
  bool _needs_recompute_clip;
  bool _needs_recompute_canvas;

  LVecBase4 _orig_clip_frame;

  bool _has_virtual_frame;
  LVecBase4 _virtual_frame;

  bool _manage_pieces;
  bool _auto_hide;

  PT(PGSliderBar) _horizontal_slider;
  PT(PGSliderBar) _vertical_slider;

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    PGVirtualFrame::init_type();
    register_type(_type_handle, "PGScrollFrame",
                  PGVirtualFrame::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#include "pgScrollFrame.I"

#endif


text:
CREATE OR REPLACE FUNCTION set_period_duration_trigger_function() RETURNS TRIGGER
    LANGUAGE plpgsql
    AS $$
BEGIN

    IF NEW.per_start IS NOT NULL AND NEW.per_stop IS NOT NULL AND NEW.per_duration IS NULL THEN
        NEW.per_duration := NEW.per_stop - NEW.per_start;
    ELSIF NEW.per_duration IS NOT NULL AND (NEW.per_start IS NOT NULL OR NEW.per_stop IS NOT NULL) THEN
        RAISE EXCEPTION 'specify either per_start and per_stop or per_duration not both!';
    ELSIF NEW.per_duration IS NULL AND (NEW.per_start IS NULL OR NEW.per_stop IS NULL) THEN
        RAISE EXCEPTION 'you have to specify both per_start and per_stop or per_duration';
    END IF;

    RETURN NEW;
END;
$$;

ALTER TABLE periods
    ALTER COLUMN per_start DROP NOT NULL,
    ALTER COLUMN per_stop DROP NOT NULL,
    ALTER COLUMN per_duration DROP NOT NULL,
    ALTER COLUMN per_duration SET DEFAULT NULL;


text:
package org.eclipse.net4j.signal;

import org.eclipse.net4j.util.io.ExtendedDataInputStream;
import org.eclipse.net4j.util.io.ExtendedDataOutputStream;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import org.eclipse.internal.net4j.bundle.OM;

/**
 * @author Eike Stepper
 */
class SetTimeoutIndication extends IndicationWithResponse
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_SIGNAL, SetTimeoutIndication.class);

  public SetTimeoutIndication(SignalProtocol<?> protocol)
  {
    super(protocol, SignalProtocol.SIGNAL_SET_TIMEOUT);
  }

  @Override
  protected void indicating(ExtendedDataInputStream in) throws Exception
  {
    long timeout = in.readLong();
    if (TRACER.isEnabled())
    {
      TRACER.format("Set timeout: {0}", timeout); //$NON-NLS-1$
    }

    getProtocol().handleSetTimeOut(timeout);
  }

  @Override
  protected void responding(ExtendedDataOutputStream out) throws Exception
  {
    out.writeBoolean(true);
  }
}


text:
package de.vanmar.android.yarrn;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;

import com.androidquery.util.AQUtility;

import org.scribe.builder.ServiceBuilder;
import org.scribe.oauth.OAuthService;

import de.vanmar.android.yarrn.ravelry.GetAccessTokenActivity;
import de.vanmar.android.yarrn.ravelry.GetAccessTokenActivity_;
import de.vanmar.android.yarrn.ravelry.IRavelryActivity;
import de.vanmar.android.yarrn.ravelry.RavelryApi;
import de.vanmar.android.yarrn.util.NetworkHelper;
import de.vanmar.android.yarrn.util.NetworkHelper_;
import de.vanmar.android.yarrn.util.RequestCode;

public abstract class AbstractRavelryActivity extends AppCompatActivity
        implements IRavelryActivity {

    public de.vanmar.android.yarrn.YarrnPrefs_ prefs;
    public NetworkHelper networkHelper;
    protected OAuthService service;

    @Override
    protected void onActivityResult(final int requestCode,
                                    final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RequestCode.REQUEST_CODE_GET_TOKEN
                && resultCode == RESULT_OK) {
            prefs.username().put(
                    data.getStringExtra(GetAccessTokenActivity.EXTRA_USERNAME));
            prefs.accessToken()
                    .put(data
                            .getStringExtra(GetAccessTokenActivity.EXTRA_ACCESSTOKEN));
            prefs.accessSecret()
                    .put(data
                            .getStringExtra(GetAccessTokenActivity.EXTRA_ACCESSSECRET));
            prefs.requestToken()
                    .put(data
                            .getStringExtra(GetAccessTokenActivity.EXTRA_REQUESTTOKEN));
        }
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final String apiKey = getString(R.string.api_key);
        final String apiSecret = getString(R.string.api_secret);
        final String callback = getString(R.string.api_callback);
        service = new ServiceBuilder()
                .provider(new RavelryApi(getString(R.string.ravelry_url)))
                .apiKey(apiKey).apiSecret(apiSecret).callback(callback).build();

        prefs = new YarrnPrefs_(this);
        networkHelper = NetworkHelper_.getInstance_(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isTaskRoot()) {
            AQUtility.cleanCacheAsync(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void requestToken() {
        startActivityForResult(new Intent(AbstractRavelryActivity.this,
                        GetAccessTokenActivity_.class),
                RequestCode.REQUEST_CODE_GET_TOKEN);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using DAL;

namespace BLL
{
    public class ctrHistoriaClinica
    {
        PersonaDAO pDAO = new PersonaDAO();
        ClinicalDataDAO cdDAO = new ClinicalDataDAO();
        public HistoriaClinica getHistoriaClinca(string cod)
        {
            HistoriaClinica hc = new HistoriaClinica();
            hc.persona = pDAO.select(cod);
            hc.datosClinicos = cdDAO.getDatosClinicos(cod);
            return hc;
        }
    }
}


text:
package net.anotheria.moskito.webui.accumulators.action;

import net.anotheria.moskito.webui.accumulators.bean.AccumulatedValuesBean;
import net.anotheria.moskito.webui.shared.api.MoskitoAPIInitializer;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TestAccumulatorNormalization {

	@BeforeClass public static void initialize(){
		MoskitoAPIInitializer.initialize();
	}

	//this test ensures that values that
	@Test public void testWithSimilarValues(){
		String[] names = new String[]{"smalline","mediumline", "bigline"};
		List<AccumulatedValuesBean> sourceData = 		createData(
				names,
				new String[]{"1","2","3","4"},
				new String[]{"10","20","30", "40"},
				new String[]{"100","200","300", "400"}
				);
		ShowAccumulatorsAction.normalize(sourceData, Arrays.asList(names), 100);
		for (AccumulatedValuesBean toCheck : sourceData){
			checkForFloatSimilarity(toCheck.getValue("smalline"), toCheck.getValue("mediumline"), toCheck.getValue("bigline"));
		}

	}

	private void checkForFloatSimilarity(String f1, String f2, String ... ff){
		float pattern = Float.parseFloat(f1);
		assertTrue("expected similarity in "+pattern+", "+f2, Math.abs(pattern-Float.parseFloat(f2))<0.1);
		if (ff!=null){
			for (String s : ff){
				assertTrue("expected similarity in "+pattern+", "+Float.parseFloat(s), Math.abs(pattern-Float.parseFloat(s))<0.1);
			}
		}
	}

	@Test public void testReverseOrder(){
		String[] names = new String[]{"line","reverseline"};
		List<AccumulatedValuesBean> sourceData = 		createData(
				names,
				new String[]{"1","2","3","4","5"},
				new String[]{"5","4","3","2","1"}
				);
		ShowAccumulatorsAction.normalize(sourceData, Arrays.asList(names), 100);
		for (int i=0; i<sourceData.size(); i++){
			checkForFloatSimilarity(sourceData.get(i).getValue("line"), sourceData.get(sourceData.size()-i-1).getValue("reverseline"));
		}
	}

	private static List<AccumulatedValuesBean> createData(String[] names, String [] ... valuesArray ){
		int vLength = valuesArray[0].length;
		for (String[] vv : valuesArray){
			if (vv.length!=vLength)
				throw new AssertionError("Arrays must have same length");
		}

		if (valuesArray.length!=names.length)
			throw new AssertionError("Expect similar count of names and values "+names.length+" vs "+valuesArray.length);

		List<AccumulatedValuesBean> valuesBeans = new ArrayList<AccumulatedValuesBean>();
		for (int i=0; i<vLength; i++){
			long timestamp = 0 + 1000L*60*i;
			AccumulatedValuesBean vBean = new AccumulatedValuesBean(timestamp);
			for (int n=0; n<names.length; n++){
				vBean.setValue(names[n], valuesArray[n][i]);
			}
			valuesBeans.add(vBean);
		}
		//DebugUtilities.printList(valuesBeans);
		return valuesBeans;

	}

	@Test public void testSingleValue(){
		//this test is based on real-life examples
		String[] names = new String[]{"threads"};
		List<AccumulatedValuesBean> sourceData = 		createData(
				names,
				new String[]{"25","25","25","26"}
				);
		ShowAccumulatorsAction.normalize(sourceData, Arrays.asList(names), 100);
		//DebugUtilities.printList(sourceData);
		assertEquals(Float.parseFloat(sourceData.get(0).getValue("threads")), 0.0, 0.0001);
		assertEquals(Float.parseFloat(sourceData.get(sourceData.size()-1).getValue("threads")), 100.0, 0.0001);
	}

}


text:
require 'google/protobuf'

require 'google/api/field_behavior_pb'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/monitoring/dashboard/v1/table_display_options.proto", :syntax => :proto3) do
    add_message "google.monitoring.dashboard.v1.TableDisplayOptions" do
      repeated :shown_columns, :string, 1
    end
  end
end

module Google
  module Cloud
    module Monitoring
      module Dashboard
        module V1
          TableDisplayOptions = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.monitoring.dashboard.v1.TableDisplayOptions").msgclass
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Node id="10" name="Supporters" thumb="section-supporters">
	<NodeMap>
		<Nodes>

			<Node id="101" name="CVSDude" thumb="site-cvsdude">
				<NodeMap>
					<Site
						name="CVSDude: The Version Control Experts"
						site_url="http://cvsdude.com"
						pic="PureMVC-Site-CVSDude.png"><![CDATA[
CVSDude is the leading provider of Subversion Hosting, making web-based collaborative development safe and affordable. Long-time supporters of Open Source projects, CVSDude has provided technical support and reliable hosting for the Trac-integrated Subversion repositories for our 90+ PureMVC ports, demos and utilities.
Without CVSDude, the PureMVC project would not be possible. Thanks, 'Dudes.
]]>
					</Site>
				</NodeMap>
			</Node>

			<Node id="102" name="Futurescale" thumb="site-futurescale">
				<NodeMap>
					<Site
						name="Futurescale, Inc"
						site_url="http://futurescale.com"
						pic="PureMVC-Site-Futurescale.png"><![CDATA[
Futurescale offers architectural guidance and development expertise to aid in the implementation of Rich Internet Applications, specifically on the ActionScript-based Flex, Flash, AIR platforms.
Futurescale supports the project financially by providing architecture, development, hosting, and administrative maintenance for the 90+ PureMVC ports, demos and utilities currently making up the project.
]]>
					</Site>
				</NodeMap>
			</Node>

			<Node id="103" name="WebAppers" thumb="site-webappers">
				<NodeMap>
					<Site
						name="Ray Cheung's WebAppers Blog"
						site_url="http://www.webappers.com/2008/02/12/webappers-released-free-web-application-icons-set/"
						pic="PureMVC-Site-WebAppers.png"><![CDATA[

WebAppers is a blog dedicated to share top quality open source resources for web developer and web designer daily. The creator of WebAppers is Ray Cheung, a web developer and designer who has a passion on web design and web application development.

Several of the icons used in the Darkstar PureMVC Manifold Roamer application are provided free by Webappers under the Creative Commons 3.0 License.

]]>
					</Site>
				</NodeMap>
			</Node>

			<Node id="104" name="Dry Icons" thumb="site-dryicons">
				<NodeMap>
					<Site
						name="Dry Icons"
						site_url="http://dryicons.com/free-icons/"
						pic="PureMVC-Site-DryIcons.png"><![CDATA[

Rabotilnica (Workshop) doo, is a small creative studio working in the creative design and web development industry. This is an independent company founded and run by 4 good friends. The team is comprised of two programmers and two designers, all engaging, skilled, committed and highly competent persons with more than 6 years of experience in their fields of interest.

DryIcons is Rabotilnica's first born (project). Not like any other icon developing website, DryIcons creates unique icons and icon sets and gives them away freely, that way giving priority to independent coders/developers, small design firms and organizations - against larger, well-funded corporations.

]]>
					</Site>
				</NodeMap>
			</Node>

		</Nodes>
	</NodeMap>
</Node>


text:
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
		var fb_param = {};
	fb_param.pixel_id = '6005510697475';
	fb_param.value = '0.00';
	(function(){
	  var fpw = document.createElement('script');
	  fpw.async = true;
	  fpw.src = (location.protocol=='http:'?'http':'https')+'://connect.facebook.net/en_US/fp.js';
	  var ref = document.getElementsByTagName('script')[0];
	  ref.parentNode.insertBefore(fpw, ref);
	})();
    </script>
</head>
<body>

</body>
</html>


text:
define([], function() {
    return {

        "roleDefinitionForSiteLabel": "Role def users get on site",
        "ownersGroupLabel": "group that owns the groups"
    }
});


text:
require 'test_helper'

class DeliveryImportTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package org.sxxp.xpath1.exp

import org.scalatest.FlatSpec
import org.sxxp.xpath1.parser.XPathParser
import scala.xml.Node
import org.sxxp.xpath1.parser.types.XNodeSeq

class EvaluatorTest extends FlatSpec {

  val xml =
    <root>

        <aa>someContent</aa>
        <aa>
          <aa/>
        </aa>

        <aa/>

        <aa/>
        <bb>
          <aa/>
        </bb>

    </root>

  val parser: XPathParser = new XPathParser()

  def evaluate(node: Node, path: String) =
    Evaluator.evaluate(node, parser.parseExpression(path)) match {
      case xNodeSeq: XNodeSeq => xNodeSeq.toNodeSeq
      case _ => fail("XNodeSeq expected when evaluating PathExpression")
    }

  "evaluate()" should "support simple node test step" in {
    // given
    val path = "a"
    val expected = xml \ "a"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select 'a/aa' path" in {
    // given
    val path = "a/aa"
    val expected = xml \ "a" \ "aa"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select '//aa' path" in {
    // given
    val path = "//aa"
    val expected = xml \\ "aa"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select '/root' path" in {
    // given
    val path = "/root"
    val expected = xml \\ "root"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select '/root//aa' path" in {
    // given
    val path = "/root//aa"
    val expected = xml \\ "aa"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select '//aa[1]' path" in {
    // given
    val path = "//aa[1]"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result.size === 5)
  }

  it should "select '(//aa)[1]' path" in {
    // given
    val path = "(//aa)[1]"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result.length === 1)
  }

  it should "select '/*' path" in {
    // given
    val path = "/*"
    val expected = xml \\ "root"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected, s"${result.getClass}, ${expected.getClass}")
  }

  it should "select 'b/../a" in {
    // given
    val path = "b/../a"
    val expected = xml \ "a"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

  it should "select 'a|b'" in {
    // given
    val path = "a|b"
    val expected = xml \ "_"
    // when
    val result = evaluate(xml, path)
    // then
    assert(result === expected)
  }

}


text:
package org.auraframework.integration.test.root.parser.handler.design;

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.design.DesignDef;
import org.auraframework.def.design.DesignSectionDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;

import java.util.Iterator;
import java.util.Set;

public class DesignSectionDefHandlerTest extends AuraImplTestCase {
    private static final String SECTION = "<design:section/>";
    private static final String SECTION_NAME = "<design:section name=\"%s\"/>";

    public DesignSectionDefHandlerTest(String name) {
        super(name);
    }

    public void testNoSection() throws Exception {
        Set<DesignSectionDef> layout = setupDesignSectionDef("");
        assertTrue("Layout did not contain no sections", layout.size() == 0);
    }

    public void testSection() throws Exception {
        Set<DesignSectionDef> sections = setupDesignSectionDef(SECTION);
        assertTrue("Layouts did not contain one section", sections.size() == 1);
    }

    public void testMultipleSectionOrder() throws Exception {
        StringBuilder sectionsStr = new StringBuilder();
        sectionsStr.append(String.format(SECTION_NAME, "5"));
        sectionsStr.append(String.format(SECTION_NAME, "b"));
        sectionsStr.append(String.format(SECTION_NAME, "a"));
        sectionsStr.append(String.format(SECTION_NAME, "0"));
        sectionsStr.append(String.format(SECTION_NAME, "someName"));
        Iterator<DesignSectionDef> sections = setupDesignSectionDef(sectionsStr.toString()).iterator();
        assertEquals("Section name was incorrect, order may not be maintained", "5", sections.next().getName());
        assertEquals("Section name was incorrect, order may not be maintained", "b", sections.next().getName());
        assertEquals("Section name was incorrect, order may not be maintained", "a", sections.next().getName());
        assertEquals("Section name was incorrect, order may not be maintained", "0", sections.next().getName());
        assertEquals("Section name was incorrect, order may not be maintained", "someName", sections.next().getName());
    }

    public void testMultipleSectionSameName() throws Exception {
        //Both name="" and not specifying a name should result in the same name
        String sections = String.format(SECTION_NAME, "") + SECTION;
        try {
            setupDesignSectionDef(sections);
            fail("Layouts can not contain duplicate sections");
        } catch (Exception e) {
            assertExceptionMessageStartsWith(e, InvalidDefinitionException.class,"Section with name");
        }
    }

    private Set<DesignSectionDef> setupDesignSectionDef(String markup) throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = getAuraTestingUtil().createStringSourceDescriptor(null,
                ComponentDef.class, null);
        addSourceAutoCleanup(cmpDesc, String.format(baseComponentTag, "", ""));

        DefDescriptor<DesignDef> designDesc = definitionService.getDefDescriptor(cmpDesc.getQualifiedName(),
                DesignDef.class);
        addSourceAutoCleanup(designDesc, String.format("<design:component><design:layout>%s</design:layout></design:component>", markup));

        return designDesc.getDef().getDefaultDesignLayoutDef().getSections();
    }
}


text:
require 'pathname'

unless Pathname.instance_methods.any?{|m| m.to_s=='sub_ext'}
  class Pathname
    # This method is available in Ruby >= 1.9.1
    def sub_ext(new_ext)
      # this is how I would do it:
      #   new_ext = ".#{new_ext}" unless new_ext[0,1]=='.'
      #   Pathname.new to_s[/.*(?=\..+$)/]+new_ext
      # but we'll try to be compatible with the standars library method
      Pathname(self.to_s.chomp(extname) + new_ext)
    end
  end
end


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DatatypeContexts #-}

module Control.CP.FD.Interface (
  FDSolver,
  FDInstance,
  (@+),(@-),(@*),(@/),(@%),(!),(@!!),(@..),(@++),size,xfold,xsum,xhead,xtail,list,slice,xmap,cte,
  (Control.CP.FD.Interface.@||),
  (Control.CP.FD.Interface.@&&),
  Control.CP.FD.Interface.inv,
  (Control.CP.FD.Interface.@=),
  (Control.CP.FD.Interface.@/=),
  (Control.CP.FD.Interface.@<),
  (Control.CP.FD.Interface.@>),
  (Control.CP.FD.Interface.@<=),
  (Control.CP.FD.Interface.@>=),
  (Control.CP.FD.Interface.@:),
  (Control.CP.FD.Interface.@?),
  (Control.CP.FD.Interface.@??),
  Control.CP.FD.Interface.channel,
  val,
--  Control.CP.FD.Interface.newInt, Control.CP.FD.Interface.newBool, Control.CP.FD.Interface.newCol,
  Control.CP.FD.Interface.sorted,
  Control.CP.FD.Interface.sSorted,
  Control.CP.FD.Interface.forall,
  Control.CP.FD.Interface.forany,
  Control.CP.FD.Interface.loopall,
  Control.CP.FD.Interface.allDiff,
  Control.CP.FD.Interface.allDiffD,
  Control.CP.FD.Interface.loopany,
  allin,
  asExpr, asCol, Control.CP.FD.Interface.asBool,
  colList, labelCol,
  ModelInt, ModelCol, ModelBool,
  exists, true, false,
--  Modelable,
) where

import Control.CP.FD.FD (FDSolver, FDInstance, FDIntTerm, getColItems)
import qualified Control.CP.FD.Model as Model
import Control.CP.FD.Model (Model, ModelBool, ModelCol, ModelInt, ToModelBool, asBool, asExpr, asCol, cte, newModelTerm, ModelIntArg, ModelBoolArg, ModelColArg)
import qualified Data.Expr.Sugar as Sugar
import Data.Expr.Util
import Data.Expr.Data
import Data.Expr.Sugar ((@+),(@-),(@*),(@/),(@%),(!),(@!!),(@..),(@++),size,xfold,xhead,xtail,slice,xmap,xsum,list)
import Control.CP.Solver
import Control.CP.SearchTree
import Control.CP.EnumTerm
import Control.Monad (ap, liftM)

newtype DummySolver a = DummySolver ()

instance Monad DummySolver where
  return = pure
  _ >>= _ = DummySolver ()

instance Applicative DummySolver where
  pure _ = DummySolver ()
  (<*>) = ap

instance Functor DummySolver where
  fmap = liftM

data EQHelp b where
  EQHelp :: Model.ModelTermType b => ((b -> Model) -> Model) -> EQHelp b

instance Model.ModelTermType t => Term DummySolver t where
  type Help DummySolver t = EQHelp t
  help _ _ = EQHelp newModelTerm
  newvar = DummySolver ()

instance Solver DummySolver where
  type Constraint DummySolver = Either Model ()
  type Label DummySolver = ()
  add _ = DummySolver ()
  run _ = error "Attempt to run dummy solver"
  mark = DummySolver ()
  goto _ = DummySolver ()

newtype Model.ModelTermType t => DummyTerm t = DummyTerm t

-- class (Solver s, Term s ModelBool, Term s ModelInt, Term s ModelCol) => Modelable s where

-- instance Modelable DummySolver where

-- instance FDSolver s => Modelable (FDInstance s) where

treeToModel :: Tree DummySolver () -> Model
treeToModel (Return _) = BoolConst True
treeToModel (Try a b) = (Sugar.@||) (treeToModel a) (treeToModel b)
treeToModel (Add (Left c) m) = (Sugar.@&&) c (treeToModel m)
treeToModel Fail = BoolConst False
treeToModel (Label _) = error "Cannot turn labelled trees into expressions"
treeToModel (NewVar (f :: t -> Tree DummySolver ())) = case (help ((error "treeToModel undefined 1") :: DummySolver ()) ((error "treeToModel undefined 2") :: t)) of EQHelp ff -> ff (\x -> treeToModel $ f (x :: t))

addM :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Model -> m ()
addM m = addC $ Left m

infixr 2 @||
(@||) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> Tree DummySolver () -> m ()
(@||) a b = addM $ treeToModel $ a \/ b

infixr 3 @&&
(@&&) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> Tree DummySolver () -> m ()
(@&&) a b = addM $ treeToModel $ a /\ b

channel :: Tree DummySolver () -> ModelInt
channel a = Sugar.channel $ treeToModel a

inv :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> m ()
inv a = addM $ Sugar.inv $ treeToModel a

infix 4 @=, @/=, @<, @>, @<=, @>=

class ModelExprClass a where
  (@=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => a -> a -> m ()
  (@/=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => a -> a -> m ()

instance ModelExprClass ModelInt where
  a @= b  = addM $ (Sugar.@=)  a b
  a @/= b = addM $ (Sugar.@/=) a b

instance ModelExprClass ModelCol where
  a @= b  = addM $ (Sugar.@=)  a b
  a @/= b = addM $ (Sugar.@/=) a b

instance ModelExprClass ModelBool where
  a @= b  = addM $ (Sugar.@=)  a b
  a @/= b = addM $ (Sugar.@/=) a b

instance ModelExprClass (Tree DummySolver ()) where
  a @= b  = addM $ (Sugar.@=)  (treeToModel a) (treeToModel b)
  a @/= b = addM $ (Sugar.@/=) (treeToModel a) (treeToModel b)

(@<) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@<) a b = addM $ (Sugar.@<) a b

(@>) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@>) a b = addM $ (Sugar.@>) a b

(@>=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@>=) a b = addM $ (Sugar.@>=) a b

(@<=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@<=) a b = addM $ (Sugar.@<=) a b

val :: Tree DummySolver () -> ModelInt
val = Sugar.toExpr . treeToModel

{- newBool :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelBool -> Tree DummySolver a) -> m a
newBool = exists

newInt :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt -> m a) -> m a
newInt = exists

newCol :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelCol -> m a) -> m a
newCol = exists
-}

asBool :: (FDSolver s, MonadTree m, TreeSolver m ~ FDInstance s, ToModelBool t) => t -> m ()
asBool = addM . Control.CP.FD.Model.asBool

sorted :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
sorted = addM . Sugar.sorted

sSorted :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
sSorted = addM . Sugar.sSorted

allDiff :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
allDiff = addM . Sugar.allDiff

allDiffD :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
allDiffD = addM . Sugar.allDiffD

mm (nv@(Term tv)) m x =
     let tf t = if (t==tv) then x else Term t
         tb t = if (Term t==x) then nv else Term t
         in boolTransformEx (tf,ColTerm,BoolTerm,tb,ColTerm,BoolTerm) m

forall :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> (ModelInt -> Tree DummySolver ()) -> m ()
-- forall col f = exists $ \nv -> addM $ Sugar.forall col $ mm nv $ treeToModel $ f nv
forall col f = addM $ Sugar.forall col (treeToModel . f)

forany :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> (ModelInt -> Tree DummySolver ()) -> m ()
-- forany col f = exists $ \nv -> addM $ Sugar.forany col $ mm nv $ treeToModel $ f nv
forany col f = addM $ Sugar.forany col (treeToModel . f)

loopall :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt,ModelInt) -> (ModelInt -> Tree DummySolver ()) -> m ()
-- loopall r f = exists $ \nv -> addM $ Sugar.loopall r $ mm nv $ treeToModel $ f nv
loopall r f = addM $ Sugar.loopall r (treeToModel . f)

loopany :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt,ModelInt) -> (ModelInt -> Tree DummySolver ()) -> m ()
-- loopany r f = exists $ \nv -> addM $ Sugar.loopany r $ mm nv $ treeToModel $ f nv
loopany r f = addM $ Sugar.loopany r (treeToModel . f)

colList :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> Int -> m [ModelInt]
colList col len = do
  addM $ (Sugar.@=) (size col) (asExpr len)
  return $ map (\i -> col!cte i) [0..len-1]

labelCol :: (FDSolver s, MonadTree m, TreeSolver m ~ FDInstance s, EnumTerm s (FDIntTerm s)) => ModelCol -> m [TermBaseType s (FDIntTerm s)]
labelCol col = label $ do
  lst <- getColItems col maxBound
  return $ do
    lsti <- colList col $ length lst
    enumerate lsti
    assignments lsti

infix 5 @:

(@:) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s, Sugar.ExprRange ModelIntArg ModelColArg ModelBoolArg r, Term s ModelInt, Term s ModelBool, Term s ModelCol) => ModelInt -> r -> m ()
a @: b = addM $ (Sugar.@:) a b

infix 4 @?
infix 4 @??

a @? (t,f) = (Sugar.@?) (treeToModel a) (t,f)
a @?? (t,f) = addM $ (Sugar.@??) (treeToModel a) (treeToModel t, treeToModel f)

allin :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s, Sugar.ExprRange ModelIntArg ModelColArg ModelBoolArg r, Term s ModelInt, Term s ModelBool, Term s ModelCol) => ModelCol -> r -> m ()
allin c b = Control.CP.FD.Interface.forall c $ \x -> addM $ (Sugar.@:) x b


text:
/*
 * @(#)DocHandler.java
 *
 * @project    : serviceapp
 * @package    : net.jsomnium.jlib.mod.doc.filter
 * @creation   : 12/lug/07
 * @license	   : META-INF/LICENSE.TXT
 */
package org.morozko.java.mod.doc.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.morozko.java.core.cfg.ConfigException;
import org.w3c.dom.Element;

/**
 * <p>
 *	<jdl:section>
 * 		<jdl:text lang='it'>
 * 		</jdl:text>
 * 		<jdl:text lang='en'>
 * 		</jdl:text>
 *	</jdl:section>
 * </p>
 *
 * @author mfranci
 *
 */
public interface DocHandler {

	public final static String MODE_DIRECT = "direct";
	public final static String MODE_JSP = "jsp";

	public final static String ATT_NAME_DOC = "org.morozko.java.mod.doc.DocBase.ATT_NAME";

	public void handleDoc( HttpServletRequest request, HttpServletResponse response, ServletContext context ) throws Exception;

	public void handleDocPost( HttpServletRequest request, HttpServletResponse response, ServletContext context ) throws Exception;

	public void init( Element config ) throws ConfigException;

	public String getEncoding();

	public String getForward();

	public boolean isUseJsp();

	public void setUseJsp(boolean useJsp);

	public String getJsp();

	public void setJsp(String jsp);

	public String getMode();

	public void setMode(String mode);
}