text:
'use strict';

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const spawn = require('cross-spawn');

const { fixturesDir, spawnOpts } = require('./util');

const elmtestPath = path.join(__dirname, '..', 'bin', 'elm-test');

const packageInfo = require('../package.json');
const elmTestVersion = packageInfo.version;

// exit codes
const resultSuccess = 0;
const resultErrored = 1;
const resultFailureThreshold = 2;

function execElmTest(args, cwd = '.') {
  return spawn.sync(
    elmtestPath,
    args,
    Object.assign({ encoding: 'utf-8', cwd }, spawnOpts)
  );
}

function getDetailedMessage(message, runResult) {
  return (
    message +
    '\n\n' +
    'STDOUT\n' +
    runResult.stdout +
    '\n\n' +
    'STDERR\n' +
    runResult.stderr
  );
}

function assertTestSuccess(runResult) {
  const msg =
    'Expected success (exit code ' +
    resultSuccess +
    '), but got ' +
    runResult.status;
  assert.strictEqual(
    resultSuccess,
    runResult.status,
    getDetailedMessage(msg, runResult)
  );
}

function assertTestErrored(runResult) {
  const msg =
    'Expected error (exit code ' +
    resultErrored +
    '), but got ' +
    runResult.status;
  assert.strictEqual(
    resultErrored,
    runResult.status,
    getDetailedMessage(msg, runResult)
  );
}

function assertTestFailure(runResult) {
  const msg =
    'Expected failure (exit code >= ' +
    resultFailureThreshold +
    '), but got ' +
    runResult.status;
  assert.ok(
    runResult.status >= resultFailureThreshold,
    getDetailedMessage(msg, runResult)
  );
}

function assertDistributionShown(reporter, runResult) {
  const msg = getDetailedMessage(
    'Expected to show distribution table',
    runResult
  );
  switch (reporter) {
    case 'console':
      assert.ok(runResult.stdout.includes('Distribution report:'), msg);
      break;
    case 'junit':
      assert.ok(runResult.stdout.includes('Distribution report:'), msg);
      break;
    case 'json':
      assert.ok(runResult.stdout.includes('distributionCount'), msg);
      break;
    default:
      throw 'Unknown reporter!';
  }
}

function assertDistributionNotShown(reporter, runResult) {
  const msg = getDetailedMessage(
    'Expected to show distribution table',
    runResult
  );
  switch (reporter) {
    case 'console':
      assert.ok(!runResult.stdout.includes('Distribution report:'), msg);
      break;
    case 'junit':
      assert.ok(!runResult.stdout.includes('Distribution report:'), msg);
      break;
    case 'json':
      assert.ok(!runResult.stdout.includes('distributionCount'), msg);
      break;
    default:
      throw 'Unknown reporter!';
  }
}

function readdir(dir) {
  return fs
    .readdirSync(dir)
    .filter((item) => item.endsWith('.elm'))
    .sort();
}

describe('--help', () => {
  it('Should print the usage and exit indicating success', () => {
    const runResult = execElmTest(['--help']);
    assertTestSuccess(runResult);
    // ensure we have a non-empty output
    assert.ok(runResult.stdout.length > 0);
  }).timeout(5000);
});

describe('--version', () => {
  it('Should print the version and exit indicating success', () => {
    const runResult = execElmTest(['--version']);
    assertTestSuccess(runResult);
    assert.strictEqual(elmTestVersion, runResult.stdout.trim());
  }).timeout(5000);
});

/* Test examples */

describe('Testing elm-test on an example application', () => {
  const cwd = 'example-application';

  it('Should pass for successful tests', () => {
    const args = path.join('tests', '*Pass*.elm');
    const runResult = execElmTest([args], cwd);
    assertTestSuccess(runResult);
  }).timeout(60000);

  it('Should fail for failing tests', () => {
    const args = path.join('tests', '*Fail*.elm');
    const runResult = execElmTest([args], cwd);
    assertTestFailure(runResult);
  }).timeout(60000);

  it('Should successfully run `elm-test make`', () => {
    const runResult = execElmTest(['make'], cwd);
    assertTestSuccess(runResult);
  }).timeout(60000);
});

describe('Testing elm-test on an example package', () => {
  const cwd = 'example-package';

  it('Should pass for successful tests', () => {
    const args = path.join('tests', '*Pass*.elm');
    const runResult = execElmTest([args], cwd);
    assertTestSuccess(runResult);
  }).timeout(60000);

  it('Should fail for failing tests', () => {
    const args = path.join('tests', '*Fail*.elm');
    const runResult = execElmTest([args], cwd);
    assertTestFailure(runResult);
  }).timeout(60000);

  it('Should successfully run `elm-test make`', () => {
    const runResult = execElmTest(['make'], cwd);
    assertTestSuccess(runResult);
  }).timeout(60000);
});

describe('Testing elm-test on example-application-src', () => {
  const cwd = 'example-application-src';

  it('Should pass successfully', () => {
    const runResult = execElmTest(['src'], cwd);
    assertTestSuccess(runResult);
  }).timeout(60000);
});

describe('Testing elm-test on an application with no tests', () => {
  const cwd = 'example-application-no-tests';

  it('Should fail due to missing tests', () => {
    const runResult = execElmTest([], cwd);
    assertTestFailure(runResult);
  }).timeout(60000);
});

/* ci tests on single elm files */
describe('Testing elm-test on single Elm files', () => {
  const cwd = fixturesDir;

  // passing tests
  const passingTestFiles = [
    'Dependency.elm',
    'One.elm',
    'Ports.elm',
    'Several.elm',
    'TrickyMultilines.elm',
    'Unexposed.elm',
  ];

  for (const testToRun of passingTestFiles) {
    it(`Should succeed for the passing test: ${testToRun}`, () => {
      const itsPath = path.join('tests', 'Passing', testToRun);
      const runResult = execElmTest([itsPath], cwd);
      assertTestSuccess(runResult);
    }).timeout(10000);
  }

  it(`Should run every file in tests/Passing`, () => {
    const filesFound = readdir(path.join(cwd, 'tests', 'Passing'));
    assert.deepStrictEqual(filesFound, passingTestFiles);
  });

  // failing tests
  const failingTestFiles = [
    'Fuzz.elm',
    'One.elm',
    'OneRuntimeException.elm',
    'OneTodo.elm',
    'Several.elm',
    'SeveralTodos.elm',
    'SeveralWithComments.elm',
    'SplitSocketMessage.elm',
  ];

  for (const testToRun of failingTestFiles) {
    it(`Should fail for the failing test: ${testToRun}`, () => {
      const itsPath = path.join('tests', 'Failing', testToRun);
      const runResult = execElmTest([itsPath], cwd);
      assertTestFailure(runResult);
    }).timeout(10000);
  }

  it(`Should run every file in tests/Failing`, () => {
    const filesFound = readdir(path.join(cwd, 'tests', 'Failing'));
    assert.deepStrictEqual(filesFound, failingTestFiles);
  });

  // tests that raise runtime errors
  const erroredTestFiles = ['OnePort.elm'];

  for (const testToRun of erroredTestFiles) {
    it(`Should raise a runtime exception for test: ${testToRun}`, () => {
      const itsPath = path.join('tests', 'RuntimeException', testToRun);
      const runResult = execElmTest([itsPath], cwd);
      assertTestErrored(runResult);
    }).timeout(10000);
  }

  it(`Should run every file in tests/RuntimeException`, () => {
    const filesFound = readdir(path.join(cwd, 'tests', 'RuntimeException'));
    assert.deepStrictEqual(filesFound, erroredTestFiles);
  });

  // tests that fail at compile time
  const compilerErrorTestFiles = {
    'InvalidSyntax.elm': 'endless comment',
    'NoTests.elm': 'no exposed values of type test',
  };

  for (const [testToRun, output] of Object.entries(compilerErrorTestFiles)) {
    for (const reporter of ['console', 'junit', 'json']) {
      it(`Compile errors should go to stderr for test: ${testToRun}, reporter: ${reporter}`, () => {
        const itsPath = path.join('tests', 'CompileError', testToRun);
        const runResult = execElmTest([itsPath, '--report', reporter], cwd);
        assert(
          runResult.stderr.toLowerCase().includes(output),
          runResult.stderr
        );
        assert.deepStrictEqual(
          runResult.stdout.split('\n').slice(1).join('\n').trim(),
          ''
        );
      });
    }
  }

  it(`Should run every file in tests/CompileError`, () => {
    const filesFound = readdir(path.join(cwd, 'tests', 'CompileError'));
    assert.deepStrictEqual(
      filesFound,
      Object.keys(compilerErrorTestFiles).sort()
    );
  });
});

describe('Distribution report tests', () => {
  const cwd = fixturesDir;
  const distributionReportFiles = {
    console: {
      'ReportDistributionPassing.elm': { showDistribution: true },
      'ReportDistributionFailing.elm': { showDistribution: true },
      'ExpectDistributionPassing.elm': { showDistribution: false },
      'ExpectDistributionFailingDistribution.elm': { showDistribution: true },
      'ExpectDistributionFailingTest.elm': { showDistribution: true },
    },
    junit: {
      'ReportDistributionPassing.elm': { showDistribution: true },
      'ReportDistributionFailing.elm': { showDistribution: true },
      'ExpectDistributionPassing.elm': { showDistribution: false },
      'ExpectDistributionFailingDistribution.elm': { showDistribution: true },
      'ExpectDistributionFailingTest.elm': { showDistribution: true },
    },
    json: {
      'ReportDistributionPassing.elm': { showDistribution: true },
      'ReportDistributionFailing.elm': { showDistribution: true },
      'ExpectDistributionPassing.elm': { showDistribution: true },
      'ExpectDistributionFailingDistribution.elm': { showDistribution: true },
      'ExpectDistributionFailingTest.elm': { showDistribution: true },
    },
  };

  for (const [reporter, tests] of Object.entries(distributionReportFiles)) {
    for (const [test, { showDistribution }] of Object.entries(tests)) {
      const testFile = path.join(cwd, 'tests', 'Distribution', test);
      it(`Distribution report test for test: ${test}, reporter: ${reporter}`, () => {
        const runResult = execElmTest([testFile, '--report', reporter], cwd);
        if (showDistribution) {
          assertDistributionShown(reporter, runResult);
        } else {
          assertDistributionNotShown(reporter, runResult);
        }
      });
    }
  }
});


text:
/* jspsych-text.js
 * Josh de Leeuw
 *
 * This plugin displays text (including HTML formatted strings) during the experiment.
 * Use it to show instructions, provide performance feedback, etc...
 *
 * documentation: docs.jspsych.org
 *
 * Modified by Ian Eisenberg to allow timing response to be set
 */

jsPsych.plugins["poldrack-text"] = (function() {

  var plugin = {};

  plugin.trial = function(display_element, trial) {

    trial.timing_response = trial.timing_response || -1;
    trial.cont_key = trial.cont_key || [];
    trial.timing_post_trial = (typeof trial.timing_post_trial === 'undefined') ? 1000 : trial.timing_post_trial;
    // if any trial variables are functions
    // this evaluates the function and replaces
    // it with the output of the function
    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

    // set the HTML of the display target to replaced_text.
    display_element.html(trial.text);

    var after_response = function(info) {
      clearTimeout(t1);
      display_element.html(''); // clear the display

      if (typeof keyboardListener !== 'undefined') {
        jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener);
      }

      var block_duration = trial.timing_response
      if (info.rt != -1) {
          block_duration = info.rt
      }

      var trialdata = {
        "text": trial.text,
        "rt": info.rt,
        "key_press": info.key,
        "block_duration": block_duration,
        "timing_post_trial": trial.timing_post_trial
      }

      jsPsych.finishTrial(trialdata);

    };

    var mouse_listener = function(e) {
      clearTimeout(t1);
      var rt = (new Date()).getTime() - start_time;

      display_element.unbind('click', mouse_listener);

      after_response({
        key: 'mouse',
        rt: rt
      });

    };

    // check if key is 'mouse'
    if (trial.cont_key == 'mouse') {
      display_element.click(mouse_listener);
      var start_time = (new Date()).getTime();
    } else {
      var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({
        callback_function: after_response,
        valid_responses: trial.cont_key,
        rt_method: 'date',
        persist: false,
        allow_held_key: false
      });
    }

    // end trial if time limit is set
    if (trial.timing_response > 0) {
      var t1 = setTimeout(function() {
        after_response({
          key: -1,
          rt: -1
        });
      }, trial.timing_response);
    }

  };

  return plugin;
})();

redpajama_set_name: RedPajamaGithub


text:
<?php

require '../vendor/autoload.php';

$config = require 'config.php';

use Jump24\FitBit\FitBitProfile;

$profile = new FitBitProfile($config['consumer_key'], $config['consumer_secret']);

//$profile->setAccessCredentials($config['auth_token'], $config['auth_secret']);

//$profile->dumpCallData();

$info = $profile->getProfileInfo('234HQW');

var_dump($info);

die();


text:
module Admin
  class TablesController < ActionController::Base
    helper "table"

    attr_accessor :test_assigns
    attr_accessor :inline_template

    def index
      @events = test_assigns
      render :inline => inline_template, :locals => { :controller => self }
    end
  end
end


text:
default[:harden][:ssh_allow_root] = false
default[:harden][:ssh_password_authentication] = false
default[:harden][:ssh_ports] = [22]


text:
package com.jasontoradler.tictactoe;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

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

/**
 * Custom tic-tac-toe grid which has ImageViews for each cell and the ability
 * to listen to each view click.
 */
public class TicTacToeGrid extends RelativeLayout {

    private static final String TAG = "TicTacToeGrid";
    private static final int DEFAULT_NUM_COLS = 3;
    private static final int DEFAULT_NUM_ROWS = 3;
    private static final int DEFAULT_CELL_MARGIN = 32;
    private static final int DEFAULT_COLOR = 0xff000000;
    private static final float DEFAULT_STROKE_WIDTH = 9f;
    private static final long DEFAULT_GRID_LINE_ANIMATION_DURATION = 500;
    private static final long DEFAULT_GRID_LINE_ANIMATION_START_DELAY = 750;
    private static final long DEFAULT_CELL_IMAGE_ANIMATOR_DURATION = 500;

    private OnCellClickListener mOnCellClickListener = null;
    private Paint mPaint;
    private int mNumCols = DEFAULT_NUM_COLS;
    private int mNumRows = DEFAULT_NUM_ROWS;
    private int mCellMargin = DEFAULT_CELL_MARGIN;
    private List<ImageView> mCells;
    private int mColor = DEFAULT_COLOR;
    private int mWidth;
    private int mHeight;
    private float mVertical1;
    private float mVertical2;
    private float mHorizontal1;
    private float mHorizontal2;
    private float mStrokeWidth = DEFAULT_STROKE_WIDTH;
    private float mVertLineX1;
    private float mVertLineX2;
    private float mHorizLineY1;
    private float mHorizLineY2;
    private long mGridLineAnimationDuration = DEFAULT_GRID_LINE_ANIMATION_DURATION;
    private long mGridLineAnimationStartDelay = DEFAULT_GRID_LINE_ANIMATION_START_DELAY;
    private long mCellImageAnimatorDuration = DEFAULT_CELL_IMAGE_ANIMATOR_DURATION;
    private boolean mIsEnabled = true;
    private boolean mIsGridAnimationDone = false;
    private View.OnClickListener mCellClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Handle each click on a specific ImageView.
            int position = (int) v.getTag();
//            Log.v(TAG, "onClick: " + position);
            if (mOnCellClickListener != null && mIsEnabled) {
                mOnCellClickListener.onCellClicked(position);
            }
        }
    };

    public TicTacToeGrid(Context context) {
        super(context);
        init(null, 0);
    }

    public TicTacToeGrid(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public TicTacToeGrid(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    /**
     * Change the ImageView at position to use resourceId.
     *
     * @param position
     * @param resourceId
     */
    public void setCellImage(int position, int resourceId) {
        // Find the ImageView corresponding to the position and set it to the
        // new image resource.
        final ImageView cell = mCells.get(position);
        cell.setImageResource(resourceId);
        // Set initial values of alpha and scale and then animate those
        // properties to their final values.
        cell.setAlpha(0.0f);
        cell.setScaleX(0f);
        cell.setScaleY(0f);
        cell.animate()
                .setDuration(mCellImageAnimatorDuration)
                .setInterpolator(new OvershootInterpolator(3f))
                .alpha(1.0f)
                .scaleX(1f)
                .scaleY(1f)
                .start();
    }

    @Override
    public void setEnabled(boolean enabled) {
        mIsEnabled = enabled;
        super.setEnabled(enabled);
    }

    /**
     * Register a callback to be invoked whenever a cell is clicked.
     *
     * @param listener
     */
    public void setOnCellClickListener(OnCellClickListener listener) {
        mOnCellClickListener = listener;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        mWidth = right - left;
        mHeight = bottom - top;
        final int CELL_WIDTH = mWidth / 3 - (mCellMargin * 2);
        final int CELL_HEIGHT = mHeight / 3 - (mCellMargin * 2);
        for (int ii = 0; ii < getChildCount(); ++ii) {
            final View view = getChildAt(ii);
            final LayoutParams params = (LayoutParams) view.getLayoutParams();
            params.width = CELL_WIDTH;
            params.height = CELL_HEIGHT;
            view.setLayoutParams(params);
        }

        mVertLineX1 = mWidth / 3f;
        mVertLineX2 = 2f * mWidth / 3f;
        mHorizLineY1 = mHeight / 3f;
        mHorizLineY2 = 2f * mHeight / 3f;

        if (!mIsGridAnimationDone) {
            Log.d(TAG, "onLayout: animation not done");
            mHorizontal1 = 0;
            mHorizontal2 = mWidth;
            mVertical1 = 0;
            mVertical2 = mHeight;
            animateGridLines(true);
        }

        super.onLayout(changed, left, top, right, bottom);
    }

    private void init(AttributeSet attrs, int defStyle) {
        Log.v(TAG, "init");

        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.TicTacToeGrid, defStyle, 0);

        mColor = a.getColor(R.styleable.TicTacToeGrid_gridColor, DEFAULT_COLOR);

        a.recycle();

        // Allow our onDraw method to be called.
        setWillNotDraw(false);

        mCells = new ArrayList<>();

        mPaint = new Paint();
        mPaint.setColor(mColor);
        mPaint.setStrokeWidth(mStrokeWidth);

        for (int y = 0; y < mNumRows; ++y) {
            for (int x = 0; x < mNumCols; ++x) {
                ImageView iv = new ImageView(getContext());

                // Create a hopefully unique ID for this view so we can use the
                // RelativeLayout parameters to lay out the view in the correct
                // position.
                iv.setId(1000 + x + y * mNumCols);

                // Set the tag to a zero-based index of the ImageView to aid in
                // identifying which cell was clicked.
                iv.setTag(x + y * mNumCols);

                // Register a listener for clicks on each ImageView.
                iv.setOnClickListener(mCellClickListener);

                // Set the resource to the 'empty' image so that onLayout will
                // calculate the correct size for our grid.
                iv.setImageResource(R.drawable.empty);

                final RelativeLayout.LayoutParams params = new LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                );
                params.setMargins(mCellMargin, mCellMargin, mCellMargin, mCellMargin);
                if (x > 0 && y == 0) { // still on first row, past first cell
                    final int leftId = mCells.get(x - 1).getId();
                    params.addRule(RIGHT_OF, leftId);
                } else if (x == 0 && y > 0) { // first column, not first row
                    final int topId = mCells.get((y - 1) * mNumCols).getId();
                    params.addRule(BELOW, topId);
                } else if (x > 0 && y > 0) { // remaining non-edge cases
                    final int leftId = mCells.get(x - 1).getId();
                    params.addRule(RIGHT_OF, leftId);
                    final int topId = mCells.get((y - 1) * mNumCols).getId();
                    params.addRule(BELOW, topId);
                }
                addView(iv, params);
                mCells.add(iv);
            }
        }
    }

    private void animateGridLines(boolean useDelay) {
        Log.v(TAG, "animateGridLines");

        mIsGridAnimationDone = true;

        ValueAnimator animator = ValueAnimator.ofFloat(0f, 2.5f);
        animator.setInterpolator(null);
        animator.setDuration(mGridLineAnimationDuration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final float value = (float) animation.getAnimatedValue();
                if (value <= 1.0f) {
                    mHorizontal1 = value * mWidth;
                }
                if (value >= 0.5f && value <= 1.5f) {
                    mVertical1 = (value - 0.5f) * mHeight;
                }
                if (value >= 1.0f && value <= 2.0f) {
                    mHorizontal2 = (2.0f - value) * mWidth;
                }
                if (value >= 1.5f && value <= 2.5f) {
                    mVertical2 = (2.5f - value) * mHeight;
                }
                invalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                Log.v(TAG, "onAnimationEnd: grid lines");

                // Make sure our lines are complete at the end of the animation.
                mHorizontal1 = mWidth;
                mHorizontal2 = 0;
                mVertical1 = mHeight;
                mVertical2 = 0;
                invalidate();
            }
        });
        if (useDelay) {
            animator.setStartDelay(mGridLineAnimationStartDelay);
        }
        animator.start();
    }

    @Override
    protected void onDraw(final Canvas canvas) {
//        Log.d(TAG, "width/height: " + mWidth + "/" + mHeight);
//        Log.d(TAG, "horiz1=" + mHorizontal1 + ", horiz2=" + mHorizontal2);
//        Log.d(TAG, "vert1=" + mVertical1 + ", vert2=" + mVertical2);

        // Draw the grid lines: two vertical and two horizontal.
        if (mWidth > 0 && mHeight > 0) {
            canvas.drawLine(mVertLineX1, 0, mVertLineX1, mVertical1, mPaint);
            canvas.drawLine(mVertLineX2, mHeight, mVertLineX2, mVertical2, mPaint);
            canvas.drawLine(0, mHorizLineY1, mHorizontal1, mHorizLineY1, mPaint);
            canvas.drawLine(mWidth, mHorizLineY2, mHorizontal2, mHorizLineY2, mPaint);
        }
    }

    /**
     * Override this to allow Android Studio to preview custom component.
     *
     * @return true to allow view to be displayed in preview
     */
    @Override
    public boolean isInEditMode() {
        return true;
    }

    /**
     * Display who won by drawing a line through winning row/column/diagonal. Also, animate
     * cell images in that line.
     *
     * @param start starting position
     * @param end   ending position
     */
    public void displayWinner(int start, int end) {
        // TODO animate values of x & y positions for drawing line through winning row/column/diagonal
        // TODO need to also modify onDraw to draw the winning line when flag is set
    }

    public void reset() {
        for (final ImageView iv : mCells) {
            iv.setImageResource(R.drawable.empty);
        }
//        animateGridLines(false);
    }

    /**
     * Callback which is invoked upon a grid cell click.
     */
    public interface OnCellClickListener {
        /**
         * Called when the grid cell at a specific position is clicked.
         *
         * @param position which cell was clicked (e.g. 0-8)
         */
        void onCellClicked(int position);
    }
}


text:
.. _js-lib:

JavaScript Library
==================

.. toctree::
   :hidden:
   :glob:

   javascript-*

The Bitdeli JavaScript library provides an easy and flexible way to gather usage
data from any web application directly to Bitdeli. The library is similar to the
ones provided by other analytics providers such as Google Analytics, Mixpanel
and KISSmetrics.

The main features of the Bitdeli JavaScript library are:

- **Identifying page visitors** with a random UUID or a custom user ID
- **Storing custom user properties** over multiple events and sessions
- **Tracking user actions**, such as page views, clicks and form submissions
- **Automatically gathering page visit information**, such as browser user agent
  strings and referrers

See :doc:`API reference <javascript-api>` for detailed documentation.

Since the data from the tracking library is sent directly to Bitdeli, your
:ref:`cards <card-script>` will update more frequently than with our 3rd party
service integrations. Also, data from the JavaScript library has a higher
retention than data from other sources. See :ref:`data-sources` for more details
about update intervals and retention.

The source code for the library can be found on `GitHub
<https://github.com/bitdeli/bitdeli-tracking-js>`_. To suggest a feature or
report a bug, `contact us </contact>`_ or visit the `Issues page
<https://github.com/bitdeli/bitdeli-tracking-js/issues>`_ on GitHub.

.. _js-lib-setup:

Setup
-----

`Log in </login>`_ to your Bitdeli account and go to `your account settings
</settings/data>`_ to find your unique snippet and instructions for setting up
the JavaScript tracking library.

To start tracking events in your web application add the following snippet
inside the `<head>` tag of your site:

.. code-block:: html

    <script type="text/javascript">
      var _bdq = _bdq || [];
      _bdq.push(["setAccount", "YOUR_INPUT_ID", "YOUR_INPUT_TOKEN"]);
      _bdq.push(["trackPageview"]);

      (function() {
        var bd = document.createElement("script"); bd.type = "text/javascript"; bd.async = true;
        bd.src = ("https:" == document.location.protocol ? "https://" : "http://") + "d2flrkr957qc5j.cloudfront.net/bitdeli.min.js";
        var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bd, s);
      })();
    </script>

The snippet loads the JavaScript tracking library for Bitdeli asynchronously
without affecting the loading time of other elements on your site.

For more details on using the tracking library, see the :doc:`javascript-api`.

If you are using multiple analytics providers you can also use `analytics.js
<https://github.com/segmentio/analytics.js>`_ to embed and use the Bitdeli
library alongside other tracking libraries.


text:
    function htmlbodyHeightUpdate(){
		var height3 = $( window ).height()
		var height1 = $('.nav').height()+50
		height2 = $('.main').height()
		console.log(height1, height2, height3);
		if(height2 > height3){
			$('html').height(Math.max(height1,height3,height2));
			$('body').height(Math.max(height1,height3,height2));
		}
		else
		{
			$('html').height(Math.max(height1,height3,height2));
			$('body').height(Math.max(height1,height3,height2));
		}

	}
	$(document).ready(function () {
		htmlbodyHeightUpdate()
		$( window ).resize(function() {
			htmlbodyHeightUpdate()
		});
		$( window ).scroll(function() {
			height2 = $('.main').height()
  			htmlbodyHeightUpdate()
		});
	});


text:
. "$(dirname "$(readlink -f "$0")")"/engine-prolog.sh

usage () {
	cat << __EOF__
Usage: engine-config <action> [<args>]

AVAILABLE ACTIONS
       -l, --list
           List available configuration keys.

       -a, --all
           Get all available configuration values.

       -g KEY, --get=KEY
           Get the value of the given key for the given version. If a version is not given, the values of all existing versions are returned.

       -s KEY=VALUE, --set KEY=VALUE
           Set the value of the given key for the given version. The version is required for this action only when the version is not 'general'.

       -m KEY=VALUE, --merge KEY=VALUE
           Merge the value of the given key for the given version with the value in the database. The version is required for this action only when the version is not 'general'.

       -h, --help
           Show this help message and exit.

OPTIONS
       --cver=VERSION
           Relevant configuration version to use.

       -p PROP_FILE, --properties=PROP_FILE
           Use the given alternate properties file.

       -c CFG_FILE, --config=CFG_FILE
           Use the given alternate configuration file.

       --log-file=LOG_FILE
           Sets file to write logging into (if not set nothing is logged).

       --log-level=LOG_LEVEL
           Sets log level, one of DEBUG (default), INFO, WARN, ERROR (case insensitive).

       --log4j-config=XML_FILE
           Sets log4j.xml file which logging configuration is loaded from.

SETTING PASSWORDS
       Passwords can be set in interactive mode:

           engine-config -s PasswordEntry=interactive

       or via file with one of the following options:

           engine-config -s PasswordEntry --admin-pass-file=/tmp/mypass
           engine-config -s PasswordEntry=/tmp/mypass

       PasswordEntry varies between the different password options.

NOTE
       In order for your change(s) to take effect, restart the oVirt engine.
__EOF__
	return 0
}

# TODO:
# why do we need CONF_FILE here?
# we do not use any vairable
CONF_FILE="${ENGINE_ETC}/engine-config/engine-config.conf"

parseArgs() {
	while [ -n "$1" ]; do
		local x="$1"
		local v="${x#*=}"
		shift
		case "${x}" in
			-c)
				CONF_FILE="$1"
				shift
			;;
			-configFile=*)
				CONF_FILE="${v}"
			;;
			-h|-help|--help)
				usage
				exit 0
			;;
		esac
	done
}
# do this in function so we do not lose $@
parseArgs "$@"

[ -s "${CONF_FILE}" ] || die "Configuration file '${CONF_FILE}' is either empty or does not exist"
. "${CONF_FILE}"

#
# Add this option to the java command line to enable remote debugging in
# all IP addresses and port 8787:
#
# -Xrunjdwp:transport=dt_socket,address=0.0.0.0:8787,server=y,suspend=y
#
# Note that the "suspend=y" options is needed to suspend the execution
# of the JVM till you connect with the debugger, otherwise it is
# not possible to debug the execution of the main method.
#

exec "${JAVA_HOME}/bin/java" \
	-Djboss.modules.write-indexes=false \
	-jar "${JBOSS_HOME}/jboss-modules.jar" \
	-dependencies org.ovirt.engine.core.tools \
	-class org.ovirt.engine.core.config.EngineConfigExecutor \
	"$@"


text:
from setuptools import setup

_depends = '''
numpy
pydot
matplotlib
pyparsing==1.5.7
scipy
'''

setup( \
  name='symath', \
  version='git', \
  description='symbolic mathematics for python', \
  author='Brandon Niemczyk', \
  author_email='brandon.niemczyk@gmail.com', \
  url='http://github.com/bniemczyk/symbolic', \
  packages=['symath', 'symath.solvers', 'symath.graph', 'symath.algorithms', 'symath.datastructures'], \
  test_suite='tests', \
  license='BSD', \
  install_requires=_depends, \
  zip_safe=False, \
  classifiers = [ \
    'Development Status :: 3 - Alpha', \
    'Intended Audience :: Developers', \
    'Intended Audience :: Science/Research', \
    'License :: OSI Approved :: BSD License', \
    'Topic :: Scientific/Engineering :: Mathematics' \
    ]
  )


text:
<?php
/* @var $this PasswordsController */
/* @var $data Passwords */
?>

	<?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:
	<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('location')); ?>:
	<?php echo CHtml::encode($data->location); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('username')); ?>:
	<?php echo CHtml::encode($data->username); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('password')); ?>:
	<?php echo CHtml::encode($data->password); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('date_created')); ?>:
	<?php echo CHtml::encode($data->date_created); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('last_update')); ?>:
	<?php echo CHtml::encode($data->last_update); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('users_id')); ?>:
	<?php echo CHtml::encode($data->users_id); ?>


text:
#ifndef WTF_DynamicAnnotations_h
#define WTF_DynamicAnnotations_h

/* This file defines dynamic annotations for use with dynamic analysis
 * tool such as ThreadSanitizer, Valgrind, etc.
 *
 * Dynamic annotation is a source code annotation that affects
 * the generated code (that is, the annotation is not a comment).
 * Each such annotation is attached to a particular
 * instruction and/or to a particular object (address) in the program.
 *
 * By using dynamic annotations a developer can give more details to the dynamic
 * analysis tool to improve its precision.
 *
 * In C/C++ program the annotations are represented as C macros.
 * With the default build flags, these macros are empty, hence don't affect
 * performance of a compiled binary.
 * If dynamic annotations are enabled, they just call no-op functions.
 * The dynamic analysis tools can intercept these functions and replace them
 * with their own implementations.
 *
 * See http://code.google.com/p/data-race-test/wiki/DynamicAnnotations for more information.
 */

#include "wtf/WTFExport.h"

#if USE(DYNAMIC_ANNOTATIONS)
/* Tell data race detector that we're not interested in reports on the given address range. */
#define WTF_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) WTFAnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description)
#define WTF_ANNOTATE_BENIGN_RACE(pointer, description) WTFAnnotateBenignRaceSized(__FILE__, __LINE__, pointer, sizeof(*(pointer)), description)

/* Annotations for user-defined synchronization mechanisms.
 * These annotations can be used to define happens-before arcs in user-defined
 * synchronization mechanisms: the race detector will infer an arc from
 * the former to the latter when they share the same argument pointer.
 *
 * The most common case requiring annotations is atomic reference counting:
 * bool deref() {
 *     ANNOTATE_HAPPENS_BEFORE(&m_refCount);
 *     if (!atomicDecrement(&m_refCount)) {
 *         // m_refCount is now 0
 *         ANNOTATE_HAPPENS_AFTER(&m_refCount);
 *         // "return true; happens-after each atomicDecrement of m_refCount"
 *         return true;
 *     }
 *     return false;
 * }
 */
#define WTF_ANNOTATE_HAPPENS_BEFORE(address) WTFAnnotateHappensBefore(__FILE__, __LINE__, address)
#define WTF_ANNOTATE_HAPPENS_AFTER(address) WTFAnnotateHappensAfter(__FILE__, __LINE__, address)

#ifdef __cplusplus
extern "C" {
#endif
/* Don't use these directly, use the above macros instead. */
WTF_EXPORT void WTFAnnotateBenignRaceSized(const char* file, int line, const volatile void* memory, long size, const char* description);
WTF_EXPORT void WTFAnnotateHappensBefore(const char* file, int line, const volatile void* address);
WTF_EXPORT void WTFAnnotateHappensAfter(const char* file, int line, const volatile void* address);
#ifdef __cplusplus
} // extern "C"
#endif

#else // USE(DYNAMIC_ANNOTATIONS)
/* These macros are empty when dynamic annotations are not enabled so you can
 * use them without affecting the performance of release binaries. */
#define WTF_ANNOTATE_BENIGN_RACE_SIZED(address, size, description)
#define WTF_ANNOTATE_BENIGN_RACE(pointer, description)
#define WTF_ANNOTATE_HAPPENS_BEFORE(address)
#define WTF_ANNOTATE_HAPPENS_AFTER(address)
#endif // USE(DYNAMIC_ANNOTATIONS)

#endif // WTF_DynamicAnnotations_h


text:
//Write an expression that calculates rectangle's perimeter and area by given width and height.

using System;

class PerimeterArea
{
    static void Main()
    {
        Console.WriteLine("What's the width of your rectangle (in cm)? ");
        double side1 = double.Parse(Console.ReadLine());
        Console.WriteLine("How about the other?");
        double side2 = double.Parse(Console.ReadLine());
        double area = side1 * side2;
        double perimeter = 2 * (side1 + side2);
        Console.WriteLine("The perimeter is {0}cm, and the area is {1}cm^2.", perimeter, area);
    }
}


text:
@implementation RESideMenuCell

- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.imageView.image) {
        [self.imageView setContentMode:UIViewContentModeCenter];
        self.imageView.frame = CGRectMake(0, 0, self.horizontalOffset, self.frame.size.height);
    }

    self.textLabel.frame = CGRectMake(self.horizontalOffset, self.textLabel.frame.origin.y, self.textLabel.frame.size.width, self.textLabel.frame.size.height);
}

@end


text:
conditionizr.add('android', /android/i.test(navigator.userAgent));
conditionizr.config({
    tests: {
        'ios': ['class'],
        'android': ['class'],
    }
});

$(document).ready(function(){
    var search = function () {
        var search_type = document.getElementById('search-type').value || 'students';
        var url = '/search/' + search_type + '/';

        var search_text = document.getElementById('search-text').value;
        if (search_text) {
            url += '?search=' + search_text;
        }
        window.location = url;
    }

    $('#search-text').keypress(function(event) {
        if (event.which == 13) {
            event.preventDefault();
            search();
        }
    });

    $('#search-button').click(function() {
        search();
    });

    // CAROUSEL OF LOGOS
    $('.companies-and-institutions-logos').slick({
        infinite: true,
        slidesToShow: 6,
        slidesToScroll: 6,
        responsive: [
            {
                breakpoint: 900,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                }
            },
            {
                breakpoint: 560,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            },
            {
                breakpoint: 400,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
        ]
    });
});


text:
package org.turbogwt.mvp.databind.client.validation;

import javax.annotation.Nullable;

/**
 * Interface used to validate databind flushes from view.
 *

 * You should implement one validator for each property that requires a specific validation. The property is assumed to
 * be known outside its validator.
 *
 * @param <T> Model type
 * @param <F> Field type
 *
 * @author Danilo Reinert
 */
public interface Validator<T, F> {

    /**
     * Validates a value to be set in a model and returns a {@link Validation}. The validation contains a flag informing
     * if it was valid or not and a {@link ValidationMessage} provided with a textual user-friendly message and a {@link
     * ValidationMessage.Type}.
     *

     * The lack of an property's id argument does not limits its implementation because the property is known by the
     * time of binding.
     *
     * @param t model which will hold (or not) the value
     * @param value  value being passed to the model
     *
     * @return validation result
     */
    Validation validate(T t, @Nullable F value);
}


text:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

client = Client(account_sid, auth_token)

trigger = client.usage.triggers("UT33c6aeeba34e48f38d6899ea5b765ad4").fetch()
print(trigger.current_value)


text:
package Moose::Exception::CreateMOPClassTakesArrayRefOfAttributes;
our $VERSION = '2.1404';

use Moose;
extends 'Moose::Exception';
with 'Moose::Exception::Role::RoleForCreateMOPClass';

sub _build_message {
    "You must pass an ARRAY ref of attributes";
}

1;


text:
{% extends "general/homeBeta.html" %}

{{ form.media.css }}

{% load static %}

{% block local %}
{% endblock %}
{{ form.media.css }}

{% block content %}

                   Santiago, Chile

                   info@medgo.cl

                  +56 224 194 464
                  +56 985 001 005

                  Acceso profesional

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

            </button>

                Home

Acceso profesional

                Nuestros profesionales

                Conózcanos

Nuestro Servicio

Dudas frecuentes

                Escríbanos

Preguntas de Salud

Contáctenos

                Trabaja con nosotros

            Home

            Acceso profesional

            Nuestros profesionales

            Conózcanos

Nuestro Servicio

Dudas frecuentes

            Escríbanos

Preguntas de Salud

Contáctenos

            Trabaja con nosotros

Trabaja con nosotros

Si te quieres unir a nuestro gran equipo de trabajo, si tienes ideas nuevas para desarrollarnos, convenios de trabajo, alianzas, etc. Por favor no dudes en escribirnos! Están las puertas abiertas.

Home

Trabaja con nosotros

            <form id="form-signin" action="" method="post">

Envianos tus datos

              {% csrf_token %}

                    Nombre (requerido)
                    {{contacto_form.nombre}}
                    {{contacto_form.nombre.errors}}

                    Correo (requerido)
                    {{contacto_form.email}}
                    {{contacto_form.email.errors}}

                    Carrera (requerido)
                    {{contacto_form.especialidad}}
                    {{contacto_form.especialidad.errors}}

                    Universidad (requerido)
                    {{contacto_form.universidad}}
                    {{contacto_form.universidad.errors}}

                    Mensaje (requerido)
                    {{contacto_form.texto}}
                    {{contacto_form.texto.errors}}

                  <button class="btn btn-system btn-large" type="submit">Enviar mensaje</button>

            </form>

{% endblock %}


text:
package org.ajabshahar.platform.resources;

import com.google.gson.Gson;
import com.ninja_squad.dbsetup.DbSetup;
import com.ninja_squad.dbsetup.destination.DataSourceDestination;
import com.ninja_squad.dbsetup.operation.Operation;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import io.dropwizard.testing.junit.DropwizardAppRule;
import net.minidev.json.JSONObject;
import org.ajabshahar.DataSetup;
import org.ajabshahar.api.*;
import org.ajabshahar.platform.PlatformApplication;
import org.ajabshahar.platform.PlatformConfiguration;
import org.ajabshahar.platform.models.Gathering;
import org.ajabshahar.platform.models.Song;
import org.ajabshahar.platform.models.SongText;
import org.ajabshahar.platform.models.Title;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import javax.ws.rs.core.NewCookie;
import java.util.HashSet;
import java.util.Set;

import static com.ninja_squad.dbsetup.Operations.sequenceOf;
import static org.ajabshahar.DataSetup.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class SongResourceIT {

    @ClassRule
    public static final DropwizardAppRule<PlatformConfiguration> RULE =
            new DropwizardAppRule<>(PlatformApplication.class, resourceFilePath("test-config.yaml"));

    private Client client;
    private JdbcDataSource dataSource;

    private static String resourceFilePath(String resource) {
        return ClassLoader.getSystemClassLoader().getResource(resource).getFile();
    }

    @Before
    public void setUp() throws Exception {
        client = new Client();
        dataSource = new JdbcDataSource();
        dataSource.setUrl("jdbc:h2:./test");
        dataSource.setUser("sa");
        dataSource.setPassword("");
    }

    @Test
    public void shouldBeAbleToSaveASong() {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_CATEGORY, INSERT_SONG_TITLE_CATEGORY,
                INSERT_UMBRELLA_TITLE_CATEGORY, INSERT_SONG_TITLE, INSERT_UMBRELLA_TITLE, INSERT_GATHERINGS, INSERT_SONGS);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        Title title = new Title();
        title.setEnglishTranslation("whatever in english");
        title.setEnglishTranslation("whatever in hindi");

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("songTitle", title);
        jsonReflection.put("soundCloudTrackId", "1");

        jsonReflection.put("umbrellaTitle", title);
        jsonReflection.put("duration", "2");

        ClientResponse songResponse = loginAndPost("http://localhost:%d/api/songs", jsonReflection);

        Song song = getSong(songResponse);

        assertThat(song.getId(), is(not(0)));
        assertThat(song.getUmbrellaTitle().getId(), is(not(0)));
        assertThat(song.getDuration(), is("2"));
        assertThat(song.getSoundCloudTrackId(), is("1"));
    }

    @Test
    public void shouldGetSongRepresentationWithWords() throws Exception {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_CATEGORY, DataSetup.INSERT_PERSON, INSERT_GATHERINGS, INSERT_SONGS_AND_TITLE, INSERT_REFLECTIONS, INSERT_WORDS, INSERT_SONG_WORD);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/getPublishedSongs", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsRepresentation responseEntity = getSongsRepresentation(response);

        assertEquals(1, responseEntity.getSongs().iterator().next().getWords().size());
    }

    @Test
    public void shouldHaveEmptyPrimaryOccupationIfThereIsNoPrimaryOccupationForAPerson() throws Exception {
        Operation operation = sequenceOf(DELETE_ALL,
                INSERT_CATEGORY,
                INSERT_GATHERINGS,
                INSERT_SONGS_AND_TITLE,
                INSERT_PERSON,
                INSERT_SONG_SINGER);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/getPublishedSongs", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsRepresentation responseEntity = getSongsRepresentation(response);

        Set<PersonSummaryRepresentation> singers = responseEntity.getSongs().iterator().next().getSingers();
        for (PersonSummaryRepresentation singer : singers) {
            assertEquals("", singer.getPrimaryOccupation());
        }
    }

    @Test
    public void shouldGetSongIfItIsNotRelatedWithAnyWord() throws Exception {
        Operation operation = sequenceOf(DELETE_ALL,
                INSERT_CATEGORY,
                INSERT_GATHERINGS,
                INSERT_SONGS_AND_TITLE);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/getPublishedSongs", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsRepresentation responseEntity = getSongsRepresentation(response);

        assertEquals(0, responseEntity.getSongs().iterator().next().getWords().size());

    }

    @Test
    public void shouldGiveEmptyResponseIfSongNotFound() throws Exception {
        Operation operation = sequenceOf(DELETE_ALL, DELETE_SONG_WORD, DELETE_SONGS, DELETE_CATEGORY,
                INSERT_CATEGORY, INSERT_GATHERINGS, INSERT_SONGS_AND_TITLE);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs?personId=1", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsSummaryRepresentation songs = response.getEntity(SongsSummaryRepresentation.class);
        assertEquals(0, songs.getSongs().size());

    }

    @Test
    public void shouldBeAbleToLinkGatheringWithASong() {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_CATEGORY, INSERT_SONG_TITLE_CATEGORY,
                INSERT_UMBRELLA_TITLE_CATEGORY, INSERT_SONG_TITLE, INSERT_UMBRELLA_TITLE, INSERT_GATHERINGS, INSERT_SONGS);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        Title title = new Title();
        title.setEnglishTranslation("something1");
        title.setEnglishTransliteration("something12");

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("songTitle", title);
        jsonReflection.put("soundCloudTrackId", "1");

        jsonReflection.put("umbrellaTitle", title);
        jsonReflection.put("duration", "2");
        Gathering gathering = new Gathering();
        gathering.setId(11);
        jsonReflection.put("gathering", gathering);

        ClientResponse songResponse = loginAndPost("http://localhost:%d/api/songs", jsonReflection);

        Song song = getSong(songResponse);

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/" + song.getId(), RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongRepresentation songRepresentation = response.getEntity(SongRepresentation.class);
        assertThat(songRepresentation.getGathering().getEnglish(), is("Rajasthan"));

    }

    @Test
    public void shouldFetchGatheringWithAllSongs() {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_CATEGORY, INSERT_SONG_TITLE_CATEGORY,
                INSERT_UMBRELLA_TITLE_CATEGORY, INSERT_SONG_TITLE, INSERT_UMBRELLA_TITLE, INSERT_GATHERINGS, INSERT_SONGS);

        final int SONG_WITH_GATHERING = 1;
        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/getPublishedSongs", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsRepresentation songsRepresentation = response.getEntity(SongsRepresentation.class);
        Set<SongRepresentation> songs = songsRepresentation.getSongs();
        SongRepresentation songFromDb = null;
        for (SongRepresentation song : songs) {
            if (song.getId() == SONG_WITH_GATHERING) {
                songFromDb = song;
                break;
            }
        }

        assertNotNull(songFromDb.getGathering());
        assertThat(songFromDb.getGathering().getId(), is(11L));
    }

    @Test
    public void shouldBeAbleToAddAndEditSongText() {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_CATEGORY, INSERT_SONG_TITLE_CATEGORY,
                INSERT_UMBRELLA_TITLE_CATEGORY, INSERT_SONG_TITLE, INSERT_UMBRELLA_TITLE, INSERT_GATHERINGS, INSERT_SONGS);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        SongRepresentation songRepresentation = new Gson().fromJson(getSongWithSongText(), SongRepresentation.class);

        ClientResponse songResponse = loginAndPost("http://localhost:%d/api/songs", songRepresentation);
        Song song = getSong(songResponse);

        long songId = song.getId();
        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs/" + songId, RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);
        songRepresentation = getSongRepresentation(response);

        assertThat(songRepresentation.getId(), is(not(0)));
        assertThat(songRepresentation.getSongText(), notNullValue());
        assertThat(songRepresentation.getSongText().getTranslation(), is("Lost Lost Moon, Clear Eyes will be all night How will you sleep?"));

        SongText songText = songRepresentation.getSongText();
        songText.setOriginal(songText.getOriginal() + " - 2");
        songText.setTranslation(songText.getTranslation() + " - 2");
        songText.setTransliteration(songText.getTransliteration() + " - 2");

        songResponse = loginAndPost("http://localhost:%d/api/songs", songRepresentation);

        response = client.resource(
                String.format("http://localhost:%d/api/songs/" + songId, RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);
        songRepresentation = getSongRepresentation(response);

        assertThat(songRepresentation.getId(), is(songId));
        assertThat(songRepresentation.getSongText(), notNullValue());
        assertThat(songRepresentation.getSongText().getTranslation(), is("Lost Lost Moon, Clear Eyes will be all night How will you sleep? - 2"));

    }

    @Test
    public void shouldFetchGivenSongWithRelatedContent() {
        Operation operation = sequenceOf(DELETE_ALL, INSERT_COMPLETE_STARTER_SET);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        SongRepresentation song = getSong("1");

        assertNotNull(song);
        assertThat(song.getWords().size(), is(1));
        assertThat(song.getSingers().size(), is(1));
        assertNotNull(song.getSongTitle());
        assertNotNull(song.getUmbrellaTitle());
        assertNotNull(song.getGathering());
        assertThat(song.getReflections().size(), is(1));
    }

    @Test
    public void shouldGetSongsBasedOnPersonId() {
        Operation operation = sequenceOf(DELETE_ALL, DELETE_SONG_WORD, DELETE_SONGS, DELETE_CATEGORY,
                INSERT_CATEGORY, INSERT_GATHERINGS, INSERT_SONGS_AND_TITLE, INSERT_PERSON,INSERT_PERSON_CATEGORY,
                INSERT_SONG_SINGER);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/songs?personId=1", RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class);

        SongsSummaryRepresentation songs = response.getEntity(SongsSummaryRepresentation.class);
        assertEquals(1, songs.getSongs().size());

    }

    private SongRepresentation getSong(String id) {
        return getSongRepresentation(client.resource(
                String.format("http://localhost:%d/api/songs/" + id, RULE.getLocalPort())).header("Content-type", "application/json")
                .get(ClientResponse.class));
    }

    private String getSongWithSongText() {
        return "{\n" +
                "  \"isAuthoringComplete\": true,\n" +
                "  \"soundCloudTrackId\": \"174024475\",\n" +
                "  \"songText\" :{\n" +
                "       \"original\": \"खोया खोया चाँद, खुला आसमान आँखों में सारी रात जाएगी तुम को भी कैसे नींद आएगी?\"," +
                "       \"translation\":\"Lost Lost Moon, Clear Eyes will be all night How will you sleep?\"," +
                "       \"transliteration\":\"Khoya khoya chaand, khula aasmaan Aankhon mein saari raat jaayegi Tumko bhi kaise neend aayegi\"" +
                "   }," +
                "  \"songTitle\": {\n" +
                "    \"id\": 3\n" +
                "  }\n" +
                "}";
    }

    private SongsRepresentation getSongsRepresentation(ClientResponse response) {
        return response.getEntity(SongsRepresentation.class);
    }

    private ClientResponse loginAndPost(String postUrl, Object jsonObj) {
        String userCredentials = "{\"username\":\"admin\",\"password\":\"password\"}";
        ClientResponse response = client.resource(
                String.format("http://localhost:%d/api/login", RULE.getLocalPort())).header("Content-type", "application/json")
                .post(ClientResponse.class, userCredentials);

        NewCookie sessionCookie = geCookie(response);
        return client.resource(
                String.format(postUrl, RULE.getLocalPort()))
                .header("Content-type", "application/json")
                .cookie(sessionCookie)
                .post(ClientResponse.class, jsonObj);
    }

    private Song getSong(ClientResponse response) {
        return response.getEntity(Song.class);
    }

    private SongRepresentation getSongRepresentation(ClientResponse response) {
        return response.getEntity(SongRepresentation.class);
    }

    private NewCookie geCookie(ClientResponse response) {
        return getCookie(response, "JSESSIONID");
    }

    private NewCookie getCookie(ClientResponse response, String name) {
        NewCookie sessionCookie = null;
        for (NewCookie cookie : response.getCookies()) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                sessionCookie = cookie;
            }
        }
        return sessionCookie;
    }

}


text:
namespace ui {

#define EVDEV_LONG_BITS (CHAR_BIT * sizeof(long))
#define EVDEV_BITS_TO_LONGS(x) (((x) + EVDEV_LONG_BITS - 1) / EVDEV_LONG_BITS)

static inline bool EvdevBitIsSet(const unsigned long* data, int bit) {
  return data[bit / EVDEV_LONG_BITS] & (1UL << (bit % EVDEV_LONG_BITS));
}

}  // namespace ui

#endif  // UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_UTIL_H_


text:
[![Build Status](https://travis-ci.org/tildeio/route-recognizer.png)](https://travis-ci.org/tildeio/route-recognizer)

# About
`route-recognizer` is a lightweight JavaScript library (under 2k!) that
can be used as the recognizer for a more comprehensive router system
(such as [`router.js`](https://github.com/tildeio/router.js)).

In keeping with the Unix philosophy, it is a modular library that does one
thing and does it well.

# Usage

Create a new router:

```javascript
var router = new Router();
```

Add a simple new route description:

```javascript
router.add([{ path: "/posts", handler: handler }]);
```

The handler is an opaque object with no specific meaning to
`route-recognizer`. A module using `route-recognizer` could
use functions or other objects with domain-specific semantics
for what to do with the handler.

A route description can have handlers at various points along
the path:

```javascript
router.add([
  { path: "/admin", handler: admin },
  { path: "/posts", handler: posts }
]);
```

Recognizing a route will return a list of the handlers and
their associated parameters:

```javascript
var result = router.recognize("/admin/posts");
result === [
  { handler: admin, params: {} },
  { handler: posts, params: {} }
];
```

Dynamic segments:

```javascript
router.add([
  { path: "/posts/:id", handler: posts },
  { path: "/comments", handler: comments }
]);

result = router.recognize("/posts/1/comments");
result === [
  { handler: posts, params: { id: "1" } },
  { handler: comments, params: {} }
];
```

A dynamic segment matches any character but `/`.

Star segments:

```javascript
router.add([{ path: "/pages/*path", handler: page }]);

result = router.recognize("/pages/hello/world");
result === [{ handler: page, params: { path: "hello/world" } }];
```

# Sorting

If multiple routes all match a path, `route-recognizer`
will pick the one with the fewest dynamic segments:

```javascript
router.add({ path: "/posts/edit", handler: editPost });
router.add({ path: "/posts/:id", handler: showPost });
router.add({ path: "/posts/new", handler: newPost });

var result1 = router.recognize("/posts/edit");
result1 === [{ handler: editPost, params: {} }];

var result2 = router.recognize("/posts/1");
result2 === [{ handler: showPost, params: { id: "1" } }];

var result3 = router.recognize("/posts/new");
result3 === [{ handler: newPost, params: {} }];
```

As you can see, this has the expected result. Explicit
static paths match more closely than dynamic paths.

This is also true when comparing star segments and other
dynamic segments. The recognizer will prefer fewer star
segments and prefer using them for less of the match (and,
consequently, using dynamic and static segments for more
of the match).


text:
package com.microsoft.azure.management.appservice;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Database connection string value to type pair.
 */
public class ConnStringValueTypePair {
    /**
     * Value of pair.
     */
    @JsonProperty(value = "value", required = true)
    private String value;

    /**
     * Type of database. Possible values include: 'MySql', 'SQLServer',
     * 'SQLAzure', 'Custom', 'NotificationHub', 'ServiceBus', 'EventHub',
     * 'ApiHub', 'DocDb', 'RedisCache', 'PostgreSQL'.
     */
    @JsonProperty(value = "type", required = true)
    private ConnectionStringType type;

    /**
     * Get the value value.
     *
     * @return the value value
     */
    public String value() {
        return this.value;
    }

    /**
     * Set the value value.
     *
     * @param value the value value to set
     * @return the ConnStringValueTypePair object itself.
     */
    public ConnStringValueTypePair withValue(String value) {
        this.value = value;
        return this;
    }

    /**
     * Get the type value.
     *
     * @return the type value
     */
    public ConnectionStringType type() {
        return this.type;
    }

    /**
     * Set the type value.
     *
     * @param type the type value to set
     * @return the ConnStringValueTypePair object itself.
     */
    public ConnStringValueTypePair withType(ConnectionStringType type) {
        this.type = type;
        return this;
    }

}


text:
package org.opensingular.requirement.commons.wicket.error;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.mock.MockApplication;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.tester.WicketTestCase;
import org.junit.Test;
import org.opensingular.lib.wicket.util.template.admin.SingularAdminApp;
import org.opensingular.requirement.module.wicket.error.Page500;
import org.opensingular.requirement.module.wicket.view.template.Footer;

public class Page500Test extends WicketTestCase {

    @Test
    public void testRender() throws Exception {
        Page500 page500 = new Page500(null);
        tester.startPage(page500);
    }

    @Override
    protected WebApplication newApplication() {
        return new AdminApp();
    }

    private class AdminApp extends MockApplication implements SingularAdminApp {
        @Override
        public MarkupContainer buildPageFooter(String id) {
            return new Footer(id);
        }
    }
}


text:
(function () {

    Contour.export('sankey', function (ds, layer, options) {

        var links = ds.links();
        var nodes = ds.nodes();
        var countries = _.filter(nodes, function (n) { return n.inbound.length > 0; });
        var clubs = _.filter(nodes, function (n) { return n.outbound.length > 2; });
        var numClubs = clubs.length;
        var lineHeight = 16;
        var padding = 7;
        var half = options.chart.plotWidth / 2;
        var countriesIndex = {};
        var clubIndex = {};

        _.each(countries, function (c, i) {
            countriesIndex[c.node] = _.extend({}, c, { index: i });
        });

        _.each(clubs, function (c, i) {
            clubIndex[c.node] = _.extend({}, c, { index: i });
        });

        var countryY = function (d, i) { return i * (lineHeight + padding) + lineHeight; };

        var clubY = function (d, i) { return (i/2) * (lineHeight + padding)  + lineHeight; };
        var clubX = function (d, i) {return i % 2 === 0 ? options.chart.plotWidth - 150 : 150; };

        var path = function(d) {
            var club = clubIndex[nodes[d.source].node];
            var country = countriesIndex[nodes[d.target].node];
            if (!club || !country) return;
            return ['M',clubX(d,club.index), ',', clubY(d,club.index), 'L', half, ',',  countryY(d, country.index)].join('');
        };

        var highlight = function () {
            var node = this.__data__.node.replace(/[\s\d\.]/g, '_');
            layer.selectAll('.club, .link, .country').classed('active', false);
            d3.selectAll('.' + node).classed('active', true);
        };

        layer.selectAll('.link').data(links)
            .enter().append('path')
                .attr('class', function (d) {
                    var src = nodes[d.source];
                    var dst = nodes[d.target];

                    return ['link', src.node.replace(/[\s\d\.]/g, '_'), dst.node.replace(/[\s\d\.]/g, '_')].join(' ');
                })
                .attr('d', path)
                .on('mouseover', function () {
                    var _this = d3.event.target;
                    layer.selectAll('.link, .club, .country').classed('active', false);
                    d3.select(_this).classed('active', true);
                });

        layer.selectAll('.country').data(countries)
            .enter().append('text')
                .attr('class', function (d) { return 'country ' + d.node.replace(/[\s\d\.]/g, '_'); })
                .attr('x', half)
                .attr('y', countryY)
                .text(function (d) { return d.name; })
                .on('mouseover', highlight);

        layer.selectAll('.club').data(clubs)
            .enter().append('text')
                .attr('class', function (d) { return 'club '  + d.node.replace(/[\s\d\.]/g, '_'); })
                .attr('x', clubX)
                .attr('y', clubY)
                .attr('style', function (d, i) {
                    var anchor = i % 2 === 0 ? 'start' : 'end';
                    return 'text-anchor: ' + anchor;
                })
                .text(function (d) { return d.name; })
                .on('mouseover', highlight);

    });

})();


text:
package org.hisp.dhis.program;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.GridHeader;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.i18n.I18n;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.message.MessageConversation;
import org.hisp.dhis.message.MessageService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.sms.SmsSender;
import org.hisp.dhis.sms.SmsServiceException;
import org.hisp.dhis.sms.outbound.OutboundSms;
import org.hisp.dhis.system.grid.ListGrid;
import org.hisp.dhis.system.util.MathUtils;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceReminder;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceReminderService;
import org.hisp.dhis.user.CurrentUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Abyot Asalefew
 */
@Transactional
public class DefaultProgramStageInstanceService
    implements ProgramStageInstanceService
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private ProgramStageInstanceStore programStageInstanceStore;

    public void setProgramStageInstanceStore( ProgramStageInstanceStore programStageInstanceStore )
    {
        this.programStageInstanceStore = programStageInstanceStore;
    }

    private ProgramInstanceService programInstanceService;

    public void setProgramInstanceService( ProgramInstanceService programInstanceService )
    {
        this.programInstanceService = programInstanceService;
    }

    private SmsSender smsSender;

    public void setSmsSender( SmsSender smsSender )
    {
        this.smsSender = smsSender;
    }

    private CurrentUserService currentUserService;

    public void setCurrentUserService( CurrentUserService currentUserService )
    {
        this.currentUserService = currentUserService;
    }

    private TrackedEntityInstanceReminderService reminderService;

    public void setReminderService( TrackedEntityInstanceReminderService reminderService )
    {
        this.reminderService = reminderService;
    }

    private MessageService messageService;

    public void setMessageService( MessageService messageService )
    {
        this.messageService = messageService;
    }

    // -------------------------------------------------------------------------
    // Implementation methods
    // -------------------------------------------------------------------------

    @Override
    public int addProgramStageInstance( ProgramStageInstance programStageInstance )
    {
        programStageInstance.setAutoFields();
        return programStageInstanceStore.save( programStageInstance );
    }

    @Override
    public void deleteProgramStageInstance( ProgramStageInstance programStageInstance )
    {
        programStageInstanceStore.delete( programStageInstance );
    }

    @Override
    public ProgramStageInstance getProgramStageInstance( int id )
    {
        return programStageInstanceStore.get( id );
    }

    @Override
    public ProgramStageInstance getProgramStageInstance( String uid )
    {
        return programStageInstanceStore.getByUid( uid );
    }

    @Override
    public ProgramStageInstance getProgramStageInstance( ProgramInstance programInstance, ProgramStage programStage )
    {
        return programStageInstanceStore.get( programInstance, programStage );
    }

    @Override
    public void updateProgramStageInstance( ProgramStageInstance programStageInstance )
    {
        programStageInstance.setAutoFields();
        programStageInstanceStore.update( programStageInstance );
    }

    @Override
    public Collection<ProgramStageInstance> getProgramStageInstances( Collection<ProgramInstance> programInstances,
        EventStatus status )
    {
        return programStageInstanceStore.get( programInstances, status );
    }

    @Override
    public List<ProgramStageInstance> getProgramStageInstances( TrackedEntityInstance entityInstance, EventStatus status )
    {
        return programStageInstanceStore.get( entityInstance, status );
    }

    @Override
    public long getProgramStageInstanceCount( int days )
    {
        Calendar cal = PeriodType.createCalendarInstance();
        cal.add( Calendar.DAY_OF_YEAR, ( days * -1 ) );

        return programStageInstanceStore.getProgramStageInstanceCountLastUpdatedAfter( cal.getTime() );
    }

    @Override
    public Collection<SchedulingProgramObject> getSendMesssageEvents()
    {
        return programStageInstanceStore.getSendMesssageEvents();
    }

    @Override
    public Grid getStatisticalReport( Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate,
        I18n i18n, I18nFormat format )
    {
        Grid grid = new ListGrid();
        grid.setTitle( i18n.getString( "program_overview" ) + " - " + program.getDisplayName() );
        grid.setSubtitle( i18n.getString( "from" ) + " " + format.formatDate( startDate ) + "  "
            + i18n.getString( "to" ) + " " + format.formatDate( endDate ) );

        grid.addHeader( new GridHeader( "", false, true ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );
        grid.addHeader( new GridHeader( "", false, false ) );

        // Total new enrollments in the period

        int total = programInstanceService.countProgramInstances( program, orgunitIds, startDate, endDate );
        grid.addRow();
        grid.addValue( i18n.getString( "total_new_enrollments_in_this_period" ) );
        grid.addValue( total ).addEmptyValues( 6 );

        // Total programs completed in this period

        int totalCompleted = programInstanceService.countProgramInstancesByStatus( ProgramInstance.STATUS_COMPLETED,
            program, orgunitIds, startDate, endDate );
        grid.addRow();
        grid.addValue( i18n.getString( "total_programs_completed_in_this_period" ) );
        grid.addValue( totalCompleted ).addEmptyValues( 6 );

        // Total programs discontinued (un-enrollments)

        int totalDiscontinued = programInstanceService.countProgramInstancesByStatus( ProgramInstance.STATUS_CANCELLED,
            program, orgunitIds, startDate, endDate );
        grid.addRow();
        grid.addValue( i18n.getString( "total_programs_discontinued_unenrollments" ) );
        grid.addValue( totalDiscontinued ).addEmptyValues( 6 );

        // Average number of stages for complete programs

        grid.addRow();
        grid.addValue( i18n.getString( "average_number_of_stages_for_complete_programs" ) );
        double percent = 0.0;
        if ( totalCompleted != 0 )
        {
           int stageCompleted =  programStageInstanceStore.averageNumberCompleted( program, orgunitIds, startDate, endDate,
                ProgramInstance.STATUS_ACTIVE );
            percent = (stageCompleted + 0.0) / totalCompleted;
        }
        grid.addValue( MathUtils.getRounded( percent ) ).addEmptyValues( 6 );

        // Add empty row

        grid.addRow().addEmptyValues( 8 );

        // Summary by stage

        grid.addRow();
        grid.addValue( i18n.getString( "summary_by_stage" ) ).addEmptyValues( 7 );

        // Add titles for stage details

        grid.addRow();
        grid.addValue( i18n.getString( "program_stages" ) );
        grid.addValue( i18n.getString( "visits_scheduled_all" ) );
        grid.addValue( i18n.getString( "visits_done" ) );
        grid.addValue( i18n.getString( "visits_done_percent" ) );
        grid.addValue( i18n.getString( "forms_completed" ) );
        grid.addValue( i18n.getString( "forms_completed_percent" ) );
        grid.addValue( i18n.getString( "visits_overdue" ) );
        grid.addValue( i18n.getString( "visits_overdue_percent" ) );

        // Add values for stage details

        for ( ProgramStage programStage : program.getProgramStages() )
        {
            grid.addRow();
            grid.addValue( programStage.getDisplayName() );

            // Visits scheduled (All)
            int totalAll = programStageInstanceStore.count( programStage, orgunitIds, startDate, endDate, null );
            grid.addValue( totalAll );

            // Visits done (#) = Incomplete + Complete stages.
            int totalCompletedEvent = programStageInstanceStore.count( programStage, orgunitIds, startDate, endDate,
                true );
            int totalVisit = totalCompletedEvent
                + programStageInstanceStore.count( programStage, orgunitIds, startDate, endDate, false );
            grid.addValue( totalVisit );

            // Visits done (%)

            percent = 0.0;
            if ( totalAll != 0 )
            {
                percent = (totalVisit + 0.0) * 100 / totalAll;
            }
            grid.addValue( MathUtils.getRounded( percent ) + "%" );

            // Forms completed (#) = Program stage instances where the user has
            // clicked complete.

            grid.addValue( totalCompletedEvent );

            // Forms completed (%)
            if ( totalAll != 0 )
            {
                percent = (totalCompletedEvent + 0.0) * 100 / totalAll;
            }
            grid.addValue( MathUtils.getRounded( percent ) + "%" );

            // Visits overdue (#)
            int overdue = programStageInstanceStore.getOverDueCount( programStage, orgunitIds, startDate, endDate );
            grid.addValue( overdue );

            // Visits overdue (%)

            percent = 0.0;
            if ( totalAll != 0 )
            {
                percent = (overdue + 0.0) * 100 / totalAll;
            }
            grid.addValue( MathUtils.getRounded( percent ) + "%" );
        }

        return grid;
    }

    @Override
    public Grid getCompletenessProgramStageInstance( Collection<Integer> orgunitIds, Program program, String startDate,
        String endDate, I18n i18n )
    {
        return programStageInstanceStore.getCompleteness( orgunitIds, program, startDate, endDate, i18n );
    }

    @Override
    public void completeProgramStageInstance( ProgramStageInstance programStageInstance, I18nFormat format )
    {
        Calendar today = Calendar.getInstance();
        PeriodType.clearTimeOfDay( today );
        Date date = today.getTime();

        programStageInstance.setStatus( EventStatus.COMPLETED );
        programStageInstance.setCompletedDate( date );
        programStageInstance.setCompletedUser( currentUserService.getCurrentUsername() );

        // ---------------------------------------------------------------------
        // Send sms-message when to completed the event
        // ---------------------------------------------------------------------

        List<OutboundSms> outboundSms = programStageInstance.getOutboundSms();

        if ( outboundSms == null )
        {
            outboundSms = new ArrayList<>();
        }

        outboundSms.addAll( sendMessages( programStageInstance,
            TrackedEntityInstanceReminder.SEND_WHEN_TO_C0MPLETED_EVENT, format ) );

        // ---------------------------------------------------------------------
        // Send DHIS message when to completed the event
        // ---------------------------------------------------------------------

        List<MessageConversation> messageConversations = programStageInstance.getMessageConversations();

        if ( messageConversations == null )
        {
            messageConversations = new ArrayList<>();
        }

        messageConversations.addAll( sendMessageConversations( programStageInstance,
            TrackedEntityInstanceReminder.SEND_WHEN_TO_C0MPLETED_EVENT, format ) );

        // ---------------------------------------------------------------------
        // Update the event
        // ---------------------------------------------------------------------

        updateProgramStageInstance( programStageInstance );

        // ---------------------------------------------------------------------
        // Check Completed status for all of ProgramStageInstance of
        // ProgramInstance
        // ---------------------------------------------------------------------

        if ( !programStageInstance.getProgramInstance().getProgram().getType()
            .equals( Program.SINGLE_EVENT_WITHOUT_REGISTRATION ) )
        {
            boolean canCompleted = programInstanceService.canAutoCompleteProgramInstanceStatus( programStageInstance
                .getProgramInstance() );
            if ( canCompleted )
            {
                programInstanceService.completeProgramInstanceStatus( programStageInstance.getProgramInstance() );
            }
        }

    }

    @Override
    public void setExecutionDate( ProgramStageInstance programStageInstance, Date executionDate,
        OrganisationUnit organisationUnit )
    {
        programStageInstance.setExecutionDate( executionDate );
        programStageInstance.setOrganisationUnit( organisationUnit );

        if ( programStageInstance.getProgramInstance().getProgram().isSingleEvent() )
        {
            programStageInstance.setDueDate( executionDate );
        }

        updateProgramStageInstance( programStageInstance );
    }

    /**
     * For the first case of an anonymous program, the program-instance doesn't
     * exist, So system has to create a program-instance and
     * program-stage-instance. The similar thing happens for single event with
     * registration.
     */
    @Override
    public ProgramStageInstance createProgramStageInstance( TrackedEntityInstance instance, Program program,
        Date executionDate, OrganisationUnit organisationUnit )
    {
        ProgramStage programStage = null;

        if ( program.getProgramStages() != null )
        {
            programStage = program.getProgramStages().iterator().next();
        }

        int type = program.getType();
        ProgramInstance programInstance = null;

        if ( type == Program.SINGLE_EVENT_WITH_REGISTRATION )
        {
            // Add a new program instance
            programInstance = new ProgramInstance();
            programInstance.setEnrollmentDate( executionDate );
            programInstance.setDateOfIncident( executionDate );
            programInstance.setProgram( program );
            programInstance.setStatus( ProgramInstance.STATUS_ACTIVE );
            programInstance.setEntityInstance( instance );

            programInstanceService.addProgramInstance( programInstance );
        }
        else if ( type == Program.SINGLE_EVENT_WITHOUT_REGISTRATION )
        {
            Collection<ProgramInstance> programInstances = programInstanceService.getProgramInstances( program );
            if ( programInstances == null || programInstances.size() == 0 )
            {
                // Add a new program instance if it doesn't exist
                programInstance = new ProgramInstance();
                programInstance.setEnrollmentDate( executionDate );
                programInstance.setDateOfIncident( executionDate );
                programInstance.setProgram( program );
                programInstance.setStatus( ProgramInstance.STATUS_ACTIVE );
                programInstanceService.addProgramInstance( programInstance );
            }
            else
            {
                programInstance = programInstanceService.getProgramInstances( program ).iterator().next();
            }
        }

        // Add a new program stage instance
        ProgramStageInstance programStageInstance = new ProgramStageInstance();
        programStageInstance.setProgramInstance( programInstance );
        programStageInstance.setProgramStage( programStage );
        programStageInstance.setDueDate( executionDate );
        programStageInstance.setExecutionDate( executionDate );
        programStageInstance.setOrganisationUnit( organisationUnit );

        addProgramStageInstance( programStageInstance );

        return programStageInstance;
    }

    // -------------------------------------------------------------------------
    // Supportive methods
    // -------------------------------------------------------------------------

    private OutboundSms sendEventMessage( TrackedEntityInstanceReminder reminder,
        ProgramStageInstance programStageInstance, TrackedEntityInstance entityInstance, I18nFormat format )
    {
        Set<String> phoneNumbers = reminderService.getPhonenumbers( reminder, entityInstance );
        OutboundSms outboundSms = null;

        if ( phoneNumbers.size() > 0 )
        {
            String msg = reminderService.getMessageFromTemplate( reminder, programStageInstance, format );
            try
            {
                outboundSms = new OutboundSms();
                outboundSms.setMessage( msg );
                outboundSms.setRecipients( phoneNumbers );
                outboundSms.setSender( currentUserService.getCurrentUsername() );
                smsSender.sendMessage( outboundSms, null );
            }
            catch ( SmsServiceException e )
            {
                e.printStackTrace();
            }
        }

        return outboundSms;
    }

    private Collection<OutboundSms> sendMessages( ProgramStageInstance programStageInstance, int status,
        I18nFormat format )
    {
        TrackedEntityInstance entityInstance = programStageInstance.getProgramInstance().getEntityInstance();
        Collection<OutboundSms> outboundSmsList = new HashSet<>();

        Collection<TrackedEntityInstanceReminder> reminders = programStageInstance.getProgramStage()
            .getReminders();
        for ( TrackedEntityInstanceReminder rm : reminders )
        {
            if ( rm != null
                && rm.getWhenToSend() != null
                && rm.getWhenToSend() == status
                && (rm.getMessageType() == TrackedEntityInstanceReminder.MESSAGE_TYPE_DIRECT_SMS || rm.getMessageType() == TrackedEntityInstanceReminder.MESSAGE_TYPE_BOTH) )
            {
                OutboundSms outboundSms = sendEventMessage( rm, programStageInstance, entityInstance, format );
                if ( outboundSms != null )
                {
                    outboundSmsList.add( outboundSms );
                }
            }
        }

        return outboundSmsList;
    }

    private Collection<MessageConversation> sendMessageConversations( ProgramStageInstance programStageInstance,
         int status, I18nFormat format )
     {
         Collection<MessageConversation> messageConversations = new HashSet<>();

         Collection<TrackedEntityInstanceReminder> reminders = programStageInstance.getProgramStage()
             .getReminders();
         for ( TrackedEntityInstanceReminder rm : reminders )
         {
             if ( rm != null
                 && rm.getWhenToSend() != null
                 && rm.getWhenToSend() == status
                 && (rm.getMessageType() == TrackedEntityInstanceReminder.MESSAGE_TYPE_DHIS_MESSAGE || rm
                     .getMessageType() == TrackedEntityInstanceReminder.MESSAGE_TYPE_BOTH) )
             {
                 int id = messageService.sendMessage( programStageInstance.getProgramStage().getDisplayName(),
                     reminderService.getMessageFromTemplate( rm, programStageInstance, format ), null,
                     reminderService.getUsers( rm, programStageInstance.getProgramInstance().getEntityInstance() ),
                     null, false, true );
                 messageConversations.add( messageService.getMessageConversation( id ) );
             }
         }

         return messageConversations;
     }
}


text:
from RunJob import RunJob                        # Parent RunJob class
from pUtil import tolog                          # Logging method that sends text to the pilot log

# Standard python modules
#import re
#import os
#import commands

class RunJobNormal(RunJob):

    # private data members
    __runjob = "Normal2"                         # String defining the sub class
    __instance = None                            # Boolean used by subclasses to become a Singleton
#    __error = PilotErrors()                     # PilotErrors object

    # Required methods

    def __init__(self):
        """ Default initialization """

        # e.g. self.__errorLabel = errorLabel
        pass

    def __new__(cls, *args, **kwargs):
        """ Override the __new__ method to make the class a singleton """

        if not cls.__instance:
            cls.__instance = super(RunJobNormal, cls).__new__(cls, *args, **kwargs)

        return cls.__instance

    def getRunJob(self):
        """ Return a string with the experiment name """

        return self.__runjob

    def getRunJobFileName(self):
        """ Return the filename of the module """

        return super(RunJobNormal, self).getRunJobFileName()

    # def argumentParser(self):  <-- see example in RunJob.py

    def allowLoopingJobKiller(self):
        """ Should the pilot search for looping jobs? """

        # The pilot has the ability to monitor the payload work directory. If there are no updated files within a certain
        # time limit, the pilot will consider the as stuck (looping) and will kill it. The looping time limits are set
        # in environment.py (see e.g. loopingLimitDefaultProd)

        return True

if __name__ == "__main__":

    tolog("Starting RunJobNormal")


text:
package gv.jleon
package domain

import java.nio.file.{ Files, StandardOpenOption }

import scala.language.{ implicitConversions }

import shapeless.{ HNil, :: }

import gv.jleon.{ Path ⇒ jPath }

import `type`.{ TaggedType }

import crypto.Digestion.SHA512

final case class Storage(
    basePath: Storage.Path
) {
  def storagePath(uri: Uri): Storage.Path =
    basePath resolve SHA512.hexDigest(uri.toString)

  def storagePathWithExt(uri: Uri, ext: String): Storage.Path = {
    val storagePath: Path = this.storagePath(uri)
    val name: Path = storagePath.getFileName
    val nameWithExt: String = s"$name.$ext"
    val pathWithExt: Path = storagePath resolveSibling nameWithExt
    pathWithExt
  }

  def fetch(uri: Uri): Try[ReadableByteChannel] =
    nonFatalCatch
      .withTry {
        val storagePath: Path = this.storagePath(uri)
        if (Files.exists(storagePath))
          Success { Files.newByteChannel(storagePath, StandardOpenOption.READ) }
        else
          Failure { new IOException(s"File not found: $storagePath") }
      }
      .flatten

  def write(uri: Uri): Sink[ByteString, Future[IOResult]] =
    FileIO.toPath(storagePath(uri))
}

object Storage extends AnyRef
    with StorageFactory {

  final implicit object Path extends TaggedType[jPath]
  final type Path = Path.t

  trait Interpretation[T] extends Any {
    final type Self = T

    def basePath(self: Self): Path.t
  }

  final implicit def apply[T: Interpretation](self: T): Storage = {
    val i: Interpretation[T] = implicitly
    Storage(
      basePath = i basePath self
    )
  }

  final implicit def recordI = new Interpretation[Path :: HNil] {
    override def basePath(self: Self): Path = self match {
      case p :: _ ⇒ p
    }
  }

}