text:
// Copyright 2015, EMC, Inc.
/* jshint node: true */

'use strict';

describe("SNMP PDU Power Metric", function () {
    var sandbox = sinon.sandbox.create();
    var waterline;
    var SnmpPduPowerMetric;
    var metric;
    var eventsProtocol = {
        publishExternalEvent: sandbox.stub().resolves()
    };
    var env = {
        get: sandbox.stub().resolves([['mib-x'],['mib-y']])
    };

    before('SNMP PDU Power Metric before', function () {
        helper.setupInjector([
            helper.require('/lib/utils/metrics/base-metric.js'),
            helper.require('/lib/utils/metrics/snmp-pdu-power-status.js'),
            helper.require('/lib/utils/job-utils/net-snmp-tool.js'),
            helper.require('/lib/utils/job-utils/net-snmp-parser.js'),
            helper.di.simpleWrapper(eventsProtocol, 'Protocol.Events'),
            helper.di.simpleWrapper(env, 'Services.Environment')
        ]);

        SnmpPduPowerMetric =
            helper.injector.get('JobUtils.Metrics.Snmp.PduPowerMetric');
        waterline = helper.injector.get('Services.Waterline');
    });

    beforeEach('SNMP PDU Power Metric beforeEach', function() {
        metric = new SnmpPduPowerMetric('testnodeid', 'testhost', 'testcommunity');
        waterline.catalogs = {
            findMostRecent: sandbox.stub().resolves()
        };
        waterline.nodes = {
            needByIdentifier: sandbox.stub().resolves({sku:'abc-xyz'})
        };
        waterline.environment = {
            findOne: sandbox.stub().resolves()
        };
        eventsProtocol.publishExternalEvent.reset();
    });

    it('should have a collectMetricData function', function() {
        expect(metric).to.have.property('collectMetricData').that.is.a('function');
    });

    it('should collect pdu power data for Sinetica(Panduit) iPDU', function() {
        metric.snmptool = { collectHostSnmp: sandbox.stub() };
        var values = { testoid1: '1'};
        var expectValues = {
             pdusResult: [
                {
                    values: {
                        'testoid1': '1'
                    }
                }
            ],
            outletsResult: [
                {
                    values: {
                        'testoid1': '1'
                    }
                }
            ]
        };
        metric.snmptool.collectHostSnmp.resolves([ { values: values } ]);

        return expect(metric._collectSineticaPowerData()).to.eventually.deep.equal(expectValues);
    });

    it('should calculate pdu power data for Sinetica(Panduit) iPDU', function() {
        var values = {
            pdusResult: [
                {
                    source: 'HAWK-I2-MIB::pduRMSVoltsValue',
                    values: {
                        'HAWK-I2-MIB::pduRMSVoltsValue.1': '200'
                    }
                }

            ],
            outletsResult: [
                {
                    source: 'HAWK-I2-MIB::pduOutRMSAmpsValue',
                    values: {
                        'HAWK-I2-MIB::pduOutRMSAmpsValue.1.2': '10'
                    }
                }
            ]
        };
        expect(metric._calculateSineticaPowerData(values)).to.deep.equal({
            'PDU_1': {
                'pduRMSVoltsValue': '200 Volts',
                'outlets': {
                    'outlet_2': {
                        'pduOutRMSAmpsValue': '1 Amps'
                    }
                }
            }
        });
    });

    it('should call correct power collection function based on node type', function() {
        metric._collectSineticaPowerData = sandbox.stub();

        metric.nodeType = 'sinetica';
        metric.collectPowerData({});
        expect(metric._collectSineticaPowerData).to.have.been.calledOnce;
    });

    it('should call correct power calculation function based on node type', function(done) {
        var currentResult = {
            'PDU_1': {
                'outlets': {
                    'outlet_1': {
                        'pduOutOn': 'on',
                        'pduOutName': 'A01'
                    }
                }
            },
            'PDU_Aggregate': {}
        };
        var lastResult = _.cloneDeep(currentResult);
        lastResult['PDU_1']['outlets']['outlet_1']['pduOutOn'] = 'off';
        var testData = {
            cache: { 'abc': { 'snmp-pdu-power-status': lastResult } },
            config: { metric: 'snmp-pdu-power-status' },
            workItemId: 'abc',
            routingKey: '0e2c320f-f29e-47c6-be18-0c833e0f080c'
        };
        metric._calculateSineticaPowerData = sandbox.stub().resolves(currentResult);
        metric.data = testData;
        metric.nodeType = 'sinetica';
        metric.calculatePowerData(testData)
        .then(function(result) {
            expect(result).to.deep.equal(currentResult);
            expect(metric._calculateSineticaPowerData).to.have.been.calledOnce;
            expect(eventsProtocol.publishExternalEvent).to.have.been.calledOnce;
            expect(eventsProtocol.publishExternalEvent).to.have.been
                .calledWith();
            done();
        })
        .catch(done);
    });
});


text:
.. _adding-new-scales:

***********************************************
Adding new scales and projections to matplotlib
***********************************************

.. ::author Michael Droettboom

Matplotlib supports the addition of custom procedures that transform
the data before it is displayed.

There is an important distinction between two kinds of
transformations.  Separable transformations, working on a single
dimension, are called "scales", and non-separable transformations,
that handle data in two or more dimensions at a time, are called
"projections".

From the user's perspective, the scale of a plot can be set with
:meth:`~matplotlib.axes.Axes.set_xscale` and
:meth:`~matplotlib.axes.Axes.set_yscale`.  Projections can be chosen
using the ``projection`` keyword argument to the
:func:`~matplotlib.pylab.plot` or :func:`~matplotlib.pylab.subplot`
functions, e.g.::

    plot(x, y, projection="custom")

This document is intended for developers and advanced users who need
to create new scales and projections for matplotlib.  The necessary
code for scales and projections can be included anywhere: directly
within a plot script, in third-party code, or in the matplotlib source
tree itself.

.. _creating-new-scale:

Creating a new scale
====================

Adding a new scale consists of defining a subclass of
:class:`matplotlib.scale.ScaleBase`, that includes the following
elements:

  - A transformation from data coordinates into display coordinates.

  - An inverse of that transformation.  This is used, for example, to
    convert mouse positions from screen space back into data space.

  - A function to limit the range of the axis to acceptable values
    (``limit_range_for_scale()``).  A log scale, for instance, would
    prevent the range from including values less than or equal to
    zero.

  - Locators (major and minor) that determine where to place ticks in
    the plot, and optionally, how to adjust the limits of the plot to
    some "good" values.  Unlike ``limit_range_for_scale()``, which is
    always enforced, the range setting here is only used when
    automatically setting the range of the plot.

  - Formatters (major and minor) that specify how the tick labels
    should be drawn.

Once the class is defined, it must be registered with matplotlib so
that the user can select it.

A full-fledged and heavily annotated example is in
:file:`examples/api/custom_scale_example.py`.  There are also some classes
in :mod:`matplotlib.scale` that may be used as starting points.

.. _creating-new-projection:

Creating a new projection
=========================

Adding a new projection consists of defining a projection axes which
subclasses :class:`matplotlib.axes.Axes` and includes the following
elements:

  - A transformation from data coordinates into display coordinates.

  - An inverse of that transformation.  This is used, for example, to
    convert mouse positions from screen space back into data space.

  - Transformations for the gridlines, ticks and ticklabels.  Custom
    projections will often need to place these elements in special
    locations, and matplotlib has a facility to help with doing so.

  - Setting up default values (overriding
    :meth:`~matplotlib.axes.Axes.cla`), since the defaults for a
    rectilinear axes may not be appropriate.

  - Defining the shape of the axes, for example, an elliptical axes,
    that will be used to draw the background of the plot and for
    clipping any data elements.

  - Defining custom locators and formatters for the projection.  For
    example, in a geographic projection, it may be more convenient to
    display the grid in degrees, even if the data is in radians.

  - Set up interactive panning and zooming.  This is left as an
    "advanced" feature left to the reader, but there is an example of
    this for polar plots in :mod:`matplotlib.projections.polar`.

  - Any additional methods for additional convenience or features.

Once the projection axes is defined, it can be used in one of two ways:

  - By defining the class attribute ``name``, the projection axes can be
    registered with :func:`matplotlib.projections.register_projection`
    and subsequently simply invoked by name::

        plt.axes(projection='my_proj_name')

  - For more complex, parameterisable projections, a generic "projection"
    object may be defined which includes the method ``_as_mpl_axes``.
    ``_as_mpl_axes`` should take no arguments and return the projection's
    axes subclass and a dictionary of additional arguments to pass to the
    subclass' ``__init__`` method.  Subsequently a parameterised projection
    can be initialised with::

        plt.axes(projection=MyProjection(param1=param1_value))

    where MyProjection is an object which implements a ``_as_mpl_axes`` method.

A full-fledged and heavily annotated example is in
:file:`examples/api/custom_projection_example.py`.  The polar plot
functionality in :mod:`matplotlib.projections.polar` may also be of
interest.

API documentation
=================

matplotlib.scale
----------------

.. automodule:: matplotlib.scale
   :members:
   :show-inheritance:

matplotlib.projections
----------------------

.. automodule:: matplotlib.projections
   :members:
   :show-inheritance:

matplotlib.projections.polar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. automodule:: matplotlib.projections.polar
   :members:
   :show-inheritance:

redpajama_set_name: RedPajamaGithub


text:
This repo is no longer being maintained. Users are welcome to fork it, but we make no warranty of its functionality.

WETTY - AWS CLI
==============
[![](https://badge.imagelayers.io/centurylink/aws-cli-wetty.svg)](https://imagelayers.io/?images=centurylink/aws-cli-wetty:latest 'Get your own badge on imagelayers.io')

AWS CLI install leveraging centurylinklabs/wetty-cli


text:
<?php
namespace Newsletter\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Newsletter\Model\Newsletter;          // <-- Add this import
use Newsletter\Form\NewsletterForm;       // <-- Add this import
use Zend\Form\Element;
use Zend\View\Model\JsonModel;
class NewsletterController extends AbstractActionController
{
    public function indexAction()
    {
        $form = new NewsletterForm();
        $this->layout()->setVariable('activeMenuTab', 'newsletter');
        $this->layout()->setTemplate('layout\ajax');
        return new ViewModel(array('form' => $form));
    }

    // Add content to this method:
    public function addAction()
    {
        $data = $this->getRequest()->getPost();
        $this->layout()->setTemplate('layout\ajax');
        $model = new Newsletter();
        $is_email_valid = preg_match('#^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{1,1})+$#',$data['email']);
        if ($is_email_valid){
            $email = strip_tags($data['email']);
            $email = trim($email);
          if ($data['remove'] === 'true'){
              $response = $model->unsubscribe($email);
              print_r($response);
              return false;
          }else{
              $response = $model->subscribe($email);
              print_r($response);
              return false;
          }
        }else{
            echo "Your email is not valid";
            return false;
        }
    }

}


text:
namespace cyder {

    class NativeApplication : public ScriptWrappable {
    DEFINE_WRAPPERTYPEINFO();

    public:
        static NativeApplication* nativeApplication() {
            return _nativeApplication;
        };

        NativeApplication() {
            _nativeApplication = this;
        }

        ~NativeApplication() {
        }

    private:
        static NativeApplication* _nativeApplication;
    };

}

#endif //CYDER_NATIVEAPPLICATION_H


text:
When(/^I navigate to elemental selenium website$/) do
  @browser.goto "http://the-internet.herokuapp.com/hovers"
end

And(/^I hover over avatar$/) do
  avatar = @browser.element(class: 'figure')
  avatar.when_present.hover

end

Then(/^I wait for caption to appear before progressing$/) do
  Selenium::WebDriver::Wait.new(timeout: 2).until do
    @browser.element(class: 'figcaption').exists?
  end
  user_url = @browser.element(css: '.figcaption > a').attribute_value('href')
  expect(user_url).to eq('http://the-internet.herokuapp.com/users/1')
end


text:
package org.apache.giraph.examples;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.giraph.graph.EdgeListVertex;
import org.apache.giraph.examples.SimpleTriangleClosingVertex.IntArrayWritable;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.HashSet;

/**
 * Demonstrates triangle closing in simple,
 * unweighted graphs for Giraph.
 *
 * Triangle Closing: Vertex A and B maintain out-edges to C and D
 * The algorithm, when finished, populates all vertices' value with an
 * array of Writables representing all the vertices that each
 * should form an out-edge to (connect with, if this is a social
 * graph.)
 * In this example, vertices A and B would hold empty arrays
 * since they are already connected with C and D. Results:
 * If the graph is undirected, C would hold value, D and D would
 * hold value C, since both are neighbors of A and B and yet both
 * were not previously connected to each other.
 *
 * In a social graph, the result values for vertex X would represent people
 * that are likely a part of a person X's social circle (they know one or more
 * people X is connected to already) but X had not previously met them yet.
 * Given this new information, X can decide to connect to vertices (peoople) in
 * the result array or not.
 *
 * Results at each vertex are ordered in terms of the # of neighbors
 * who are connected to each vertex listed in the final vertex value.
 * The more of a vertex's neighbors who "know" someone, the stronger
 * your social relationship is presumed to be to that vertex (assuming
 * a social graph) and the more likely you should connect with them.
 *
 * In this implementation, Edge Values are not used, but could be
 * adapted to represent additional qualities that could affect the
 * ordering of the final result array.
 */
public class SimpleTriangleClosingVertex extends EdgeListVertex<
  IntWritable, SimpleTriangleClosingVertex.IntArrayWritable,
  NullWritable, IntWritable> {
  /** Vertices to close the triangle, ranked by frequency of in-msgs */
  private Map<IntWritable, Integer> closeMap =
    new TreeMap<IntWritable, Integer>();
  /** Set of vertices you already recieved @ least once */
  private Set<Integer> recvSet = new HashSet<Integer>();

  @Override
  public void compute(Iterator<IntWritable> msgIterator) {
    if (getSuperstep() == 0) {
      // obtain list of all out-edges from THIS vertex
      Iterator<IntWritable> iterator = iterator();
      while (iterator.hasNext()) {
        sendMsgToAllEdges(iterator.next());
      }
    } else {
      while (msgIterator.hasNext()) {
        IntWritable iw = msgIterator.next();
        int inId = iw.get();
        if (recvSet.contains(inId)) {
          int current = closeMap.get(iw) == null ? 0 : inId;
          closeMap.put(iw, current + 1);
        }
        if (inId != getVertexId().get()) {
          recvSet.add(inId);
        }
      }
      int ndx = closeMap.size();
      IntWritable[] temp = new IntWritable[ndx];
      for (IntWritable w: closeMap.keySet()) {
        temp[--ndx] = w;
      }
      IntArrayWritable result = new IntArrayWritable();
      result.set(temp);
      setVertexValue(result);
    }
    voteToHalt();
  }

  /** Utility class for delivering the array of vertices THIS vertex
    * should connect with to close triangles with neighbors */
  public static class IntArrayWritable extends ArrayWritable {
    /** default constructor */
    public IntArrayWritable() {
      super(IntWritable.class);
    }

    @Override
    public String toString() {
      StringBuilder sb = new StringBuilder();
      Writable[] iwArray = get();
      for (int i = 0; i < iwArray.length; ++i) {
        IntWritable iw = (IntWritable) iwArray[i];
        sb.append(iw.get() + "  ");
      }
      return sb.toString();
    }
  }
}


text:
        Developers:

        Overview:

                    Total
                     of

                    Critical
                     of  ( ppm)

                    Major
                     of  ( ppm)

                    Minor
                     of

                    CRC
                     of

                    Etc
                     of

                    LOC

                    Class

                     Method

                    File

Checker Status (fixed defects / total defects):

Defects of All Modules (total defect counts):

Defects of Selected Modules: X(class), Y(loc), Radius(defect)

Defects of Selected Files: X(max complexity), Y(loc), Radius(defect)

                    File (group by Module, top 100)
                    Class
Count
                    Defects
(New/Total)
                    Dismissed
                    Severity
(Critical | Major)
                    Max
Complexity
                    Line of
Code
                    Comment
 Ratio
                    Last
 Modifier

            <button style="width : 200px" class="btn btn-xs btn-default" ng-click="toggleShowFileList()">
                 {{toggleShowFileListTitle}}
            </button>

                <button style="width : 200px" id="exportFileListBtn"  class="btn btn-xs btn-success">
                     Export File List
                </button>


text:
<?php
require_once __DIR__ . '/../../../../vendor/autoload.php';
$loader = require_once 'vendor/autoload.php';

\VCR\VCR::turnOn();
\VCR\VCR::turnOff();


text:
uapi::long_t sys_rt_sigreturn(const Context* context);

//-----------------------------------------------------------------------------
// sys_sigreturn
//
// Returns from a signal handler and restores the thread
//
// Arguments:
//
//	context		- System call context object

uapi::long_t sys_sigreturn(const Context* context)
{
	return -LINUX_ENOSYS;

	//// Currently this system call is directly equivalent to sys_rt_sigreturn
	//// TODO: find out if this is indeed the case!
	//return sys_rt_sigreturn(context);
}

// sys32_sigreturn
//
sys32_long_t sys32_sigreturn(sys32_context_t context)
{
	return static_cast<sys32_long_t>(SystemCall::Invoke(sys_sigreturn, context));
}

//---------------------------------------------------------------------------

#pragma warning(pop)


text:
from celery import Celery
from .common import *  # NOQA

BROKER_URL = 'amqp://guest:guest@localhost:5672//'
# BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'amqp://guest:guest@localhost:5672//'
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1'

CELERY_TIMEZONE = 'Europe/Madrid'
CELERY_ENABLE_UTC = True

CELERYBEAT_MAX_LOOP_INTERVAL = 2
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'

CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_ENGINE_OPTIONS = {'echo': True}

CELERY_DEFAULT_EXCHANGE = 'kolekti'
CELERY_DEFAULT_EXCHANGE_TYPE = 'direct'

CELERY_DEFAULT_QUEUE = 'kolekti'
CELERY_DEFAULT_ROUTING_KEY = 'kolekti'
CELERY_TASK_RESULT_EXPIRES = 30
CELERY_RESULT_EXCHANGE = 'kolekti_result'

# CELERY_ACKS_LATE = True
CELERY_REDIRECT_STDOUTS_LEVEL = "DEBUG"
app = Celery('kolekti')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: INSTALLED_APPS)

# To run a celery worker:
#   python manage.py celery worker -B -l DEBUG


text:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon\Carbon;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Carbon::setlocale('zh');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
module Specjour::Rspec::Runner
  def self.run(spec, output)
    options = Spec::Runner::OptionParser.parse(
      ['--format=Specjour::Rspec::DistributedFormatter', spec],
      $stderr,
      output
    )
    Spec::Runner.use options
    options.run_examples
  end
end


text:
package aws

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
	"sync"

	"provider/utils"

	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/fatih/flags"
	"github.com/hashicorp/go-multierror"
)

type listFlags struct {
	output   utils.OutputMode
	imageIds []string
	owners   []string

	helpMsg string
	flagSet *flag.FlagSet
}

func newListFlags() *listFlags {
	l := &listFlags{}

	flagSet := flag.NewFlagSet("list", flag.ContinueOnError)
	flagSet.Var(utils.NewOutputValue(utils.Simplified, &l.output), "output", "Output mode")
	flagSet.Var(flags.NewStringSlice(nil, &l.imageIds), "ids", "Images to be listed. Default case is all images")
	flagSet.Var(flags.NewStringSlice(nil, &l.owners), "owners", "Filters the images by the owner. By ddefault self is being used")
	l.helpMsg = `Usage: images list --providers aws [options]

   List AMI properties.

Options:

  -ids     "ami-123,..."       Images to be listed. By default all images are shown.
  -owners  "self,..."          Filters the images by the owner. By default self is being used.
  -output  "json"              Output mode of images. (default: "simplified")
                               Available options: "json","table" or "simplified"
`

	flagSet.Usage = func() {
		fmt.Fprintf(os.Stderr, l.helpMsg)
	}
	flagSet.SetOutput(ioutil.Discard) // don't print anything without my permission
	l.flagSet = flagSet
	return l
}

func (a *AwsImages) Images(input *ec2.DescribeImagesInput) (Images, error) {
	var (
		wg sync.WaitGroup
		mu sync.Mutex

		multiErrors error
	)

	images := make(map[string][]*ec2.Image)

	for r, s := range a.services.regions {
		wg.Add(1)
		go func(region string, svc *ec2.EC2) {
			resp, err := svc.DescribeImages(input)
			mu.Lock()

			if err != nil {
				multiErrors = multierror.Append(multiErrors, err)
			} else {
				// sort from oldest to newest
				if len(resp.Images) > 1 {
					sort.Sort(byTime(resp.Images))
				}

				images[region] = resp.Images
			}

			mu.Unlock()
			wg.Done()
		}(r, s)
	}

	wg.Wait()

	return images, multiErrors
}

func (a *AwsImages) ownerImages() (Images, error) {
	input := &ec2.DescribeImagesInput{
		Owners: stringSlice("self"),
	}

	return a.Images(input)
}


text:
<?php
/*
 *  Made by Samerton
 *  https://github.com/NamelessMC/Nameless/
 *  NamelessMC version 2.0.0-pr13
 *
 *  License: MIT
 *
 *  User alerts page
 */

// Must be logged in
if (!$user->isLoggedIn()) {
    Redirect::to(URL::build('/'));
}

// Always define page name for navbar
const PAGE = 'cc_alerts';
$page_title = $language->get('user', 'user_cp');
require_once(ROOT_PATH . '/core/templates/frontend_init.php');

$timeago = new TimeAgo(TIMEZONE);

if (!isset($_GET['view'])) {
    if (!isset($_GET['action'])) {
        // Get alerts
        $alerts = DB::getInstance()->orderWhere('alerts', 'user_id = ' . $user->data()->id, 'created', 'DESC')->results();

        $alerts_limited = [];
        $n = 0;

        if (count($alerts) > 30) {
            $limit = 30;
        } else {
            $limit = count($alerts);
        }

        while ($n < $limit) {
            // Only display 30 alerts
            // Get date
            $alerts[$n]->date = date(DATE_FORMAT, $alerts[$n]->created);
            $alerts[$n]->date_nice = $timeago->inWords($alerts[$n]->created, $language);
            $alerts[$n]->view_link = URL::build('/user/alerts/', 'view=' . urlencode($alerts[$n]->id));

            $alerts_limited[] = $alerts[$n];

            $n++;
        }

        if (Session::exists('alerts_error')) {
            $smarty->assign('ERROR', Session::flash('alerts_error'));
        }

        // Language values
        $smarty->assign([
            'USER_CP' => $language->get('user', 'user_cp'),
            'ALERTS' => $language->get('user', 'alerts'),
            'ALERTS_LIST' => $alerts_limited,
            'DELETE_ALL' => $language->get('user', 'delete_all'),
            'DELETE_ALL_LINK' => URL::build('/user/alerts/', 'action=purge'),
            'CLICK_TO_VIEW' => $language->get('user', 'click_here_to_view'),
            'NO_ALERTS' => $language->get('user', 'no_alerts_usercp'),
            'TOKEN' => Token::get()
        ]);

        // Load modules + template
        Module::loadPage($user, $pages, $cache, $smarty, [$navigation, $cc_nav, $staffcp_nav], $widgets, $template);

        require(ROOT_PATH . '/core/templates/cc_navbar.php');

        $template->onPageLoad();

        require(ROOT_PATH . '/core/templates/navbar.php');
        require(ROOT_PATH . '/core/templates/footer.php');

        // Display template
        $template->displayTemplate('user/alerts.tpl', $smarty);

    } else {
        if ($_GET['action'] == 'purge') {
            if (Token::check()) {
                DB::getInstance()->delete('alerts', ['user_id', $user->data()->id]);
            } else {
                Session::flash('alerts_error', $language->get('general', 'invalid_token'));
            }

            Redirect::to(URL::build('/user/alerts'));
        }
    }

} else {
    // Redirect to alert, mark as read
    if (!is_numeric($_GET['view'])) {
        Redirect::to(URL::build('/user/alerts'));
    }

    // Check the alert belongs to the user..
    $alert = DB::getInstance()->get('alerts', ['id', $_GET['view']])->results();

    if (!count($alert) || $alert[0]->user_id != $user->data()->id) {
        Redirect::to(URL::build('/user/alerts'));
    }

    if ($alert[0]->read == 0) {
        DB::getInstance()->update('alerts', $alert[0]->id, [
            'read' => true,
        ]);
    }

    Redirect::to($alert[0]->url);
}


text:
// Copyright 2019 PingCAP, Inc.
//
// 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.

package bindinfo

import (
	"time"
	"unsafe"

	"github.com/pingcap/tidb/metrics"
	"github.com/pingcap/tidb/parser"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/hack"
	"github.com/pingcap/tidb/util/hint"
)

const (
	// Enabled is the bind info's in enabled status.
	// It is the same as the previous 'Using' status.
	// Only use 'Enabled' status in the future, not the 'Using' status.
	// The 'Using' status is preserved for compatibility.
	Enabled = "enabled"
	// Disabled is the bind info's in disabled status.
	Disabled = "disabled"
	// Using is the bind info's in use status.
	// The 'Using' status is preserved for compatibility.
	Using = "using"
	// deleted is the bind info's deleted status.
	deleted = "deleted"
	// Invalid is the bind info's invalid status.
	Invalid = "invalid"
	// PendingVerify means the bind info needs to be verified.
	PendingVerify = "pending verify"
	// Rejected means that the bind has been rejected after verify process.
	// We can retry it after certain time has passed.
	Rejected = "rejected"
	// Manual indicates the binding is created by SQL like "create binding for ...".
	Manual = "manual"
	// Capture indicates the binding is captured by TiDB automatically.
	Capture = "capture"
	// Evolve indicates the binding is evolved by TiDB from old bindings.
	Evolve = "evolve"
	// Builtin indicates the binding is a builtin record for internal locking purpose. It is also the status for the builtin binding.
	Builtin = "builtin"
)

// Binding stores the basic bind hint info.
type Binding struct {
	BindSQL string
	// Status represents the status of the binding. It can only be one of the following values:
	// 1. deleted: BindRecord is deleted, can not be used anymore.
	// 2. enabled, using: Binding is in the normal active mode.
	Status     string
	CreateTime types.Time
	UpdateTime types.Time
	Source     string
	Charset    string
	Collation  string
	// Hint is the parsed hints, it is used to bind hints to stmt node.
	Hint *hint.HintsSet
	// ID is the string form of Hint. It would be non-empty only when the status is `Using` or `PendingVerify`.
	ID string
}

func (b *Binding) isSame(rb *Binding) bool {
	if b.ID != "" && rb.ID != "" {
		return b.ID == rb.ID
	}
	// Sometimes we cannot construct `ID` because of the changed schema, so we need to compare by bind sql.
	return b.BindSQL == rb.BindSQL
}

// IsBindingEnabled returns whether the binding is enabled.
func (b *Binding) IsBindingEnabled() bool {
	return b.Status == Enabled || b.Status == Using
}

// IsBindingAvailable returns whether the binding is available.
// The available means the binding can be used or can be converted into a usable status.
// It includes the 'Enabled', 'Using' and 'Disabled' status.
func (b *Binding) IsBindingAvailable() bool {
	return b.IsBindingEnabled() || b.Status == Disabled
}

// SinceUpdateTime returns the duration since last update time. Export for test.
func (b *Binding) SinceUpdateTime() (time.Duration, error) {
	updateTime, err := b.UpdateTime.GoTime(time.Local)
	if err != nil {
		return 0, err
	}
	return time.Since(updateTime), nil
}

// BindRecord represents a sql bind record retrieved from the storage.
type BindRecord struct {
	OriginalSQL string
	Db          string

	Bindings []Binding
}

// HasEnabledBinding checks if there are any enabled bindings in bind record.
func (br *BindRecord) HasEnabledBinding() bool {
	for _, binding := range br.Bindings {
		if binding.IsBindingEnabled() {
			return true
		}
	}
	return false
}

// HasAvailableBinding checks if there are any available bindings in bind record.
// The available means the binding can be used or can be converted into a usable status.
// It includes the 'Enabled', 'Using' and 'Disabled' status.
func (br *BindRecord) HasAvailableBinding() bool {
	for _, binding := range br.Bindings {
		if binding.IsBindingAvailable() {
			return true
		}
	}
	return false
}

// FindEnabledBinding gets the enabled binding.
// There is at most one binding that can be used now.
func (br *BindRecord) FindEnabledBinding() *Binding {
	for _, binding := range br.Bindings {
		if binding.IsBindingEnabled() {
			return &binding
		}
	}
	return nil
}

// FindBinding find bindings in BindRecord.
func (br *BindRecord) FindBinding(hint string) *Binding {
	for i := range br.Bindings {
		binding := br.Bindings[i]
		if binding.ID == hint {
			return &binding
		}
	}
	return nil
}

// prepareHints builds ID and Hint for BindRecord. If sctx is not nil, we check if
// the BindSQL is still valid.
func (br *BindRecord) prepareHints(sctx sessionctx.Context) error {
	p := parser.New()
	for i, bind := range br.Bindings {
		if (bind.Hint != nil && bind.ID != "") || bind.Status == deleted {
			continue
		}
		hintsSet, stmt, warns, err := hint.ParseHintsSet(p, bind.BindSQL, bind.Charset, bind.Collation, br.Db)
		if err != nil {
			return err
		}
		if sctx != nil {
			paramChecker := &paramMarkerChecker{}
			stmt.Accept(paramChecker)
			if !paramChecker.hasParamMarker {
				_, err = getHintsForSQL(sctx, bind.BindSQL)
				if err != nil {
					return err
				}
			}
		}
		hintsStr, err := hintsSet.Restore()
		if err != nil {
			return err
		}
		// For `create global binding for select * from t using select * from t`, we allow it though hintsStr is empty.
		// For `create global binding for select * from t using select /*+ non_exist_hint() */ * from t`,
		// the hint is totally invalid, we escalate warning to error.
		if hintsStr == "" && len(warns) > 0 {
			return warns[0]
		}
		br.Bindings[i].Hint = hintsSet
		br.Bindings[i].ID = hintsStr
	}
	return nil
}

// `merge` merges two BindRecord. It will replace old bindings with new bindings if there are new updates.
func merge(lBindRecord, rBindRecord *BindRecord) *BindRecord {
	if lBindRecord == nil {
		return rBindRecord
	}
	if rBindRecord == nil {
		return lBindRecord
	}
	result := lBindRecord.shallowCopy()
	for i := range rBindRecord.Bindings {
		rbind := rBindRecord.Bindings[i]
		found := false
		for j, lbind := range lBindRecord.Bindings {
			if lbind.isSame(&rbind) {
				found = true
				if rbind.UpdateTime.Compare(lbind.UpdateTime) >= 0 {
					result.Bindings[j] = rbind
				}
				break
			}
		}
		if !found {
			result.Bindings = append(result.Bindings, rbind)
		}
	}
	return result
}

func (br *BindRecord) remove(deleted *BindRecord) *BindRecord {
	// Delete all bindings.
	if len(deleted.Bindings) == 0 {
		return &BindRecord{OriginalSQL: br.OriginalSQL, Db: br.Db}
	}
	result := br.shallowCopy()
	for j := range deleted.Bindings {
		deletedBind := deleted.Bindings[j]
		for i, bind := range result.Bindings {
			if bind.isSame(&deletedBind) {
				result.Bindings = append(result.Bindings[:i], result.Bindings[i+1:]...)
				break
			}
		}
	}
	return result
}

func (br *BindRecord) removeDeletedBindings() *BindRecord {
	result := BindRecord{OriginalSQL: br.OriginalSQL, Db: br.Db, Bindings: make([]Binding, 0, len(br.Bindings))}
	for _, binding := range br.Bindings {
		if binding.Status != deleted {
			result.Bindings = append(result.Bindings, binding)
		}
	}
	return &result
}

// shallowCopy shallow copies the BindRecord.
func (br *BindRecord) shallowCopy() *BindRecord {
	result := BindRecord{
		OriginalSQL: br.OriginalSQL,
		Db:          br.Db,
		Bindings:    make([]Binding, len(br.Bindings)),
	}
	copy(result.Bindings, br.Bindings)
	return &result
}

func (br *BindRecord) isSame(other *BindRecord) bool {
	return br.OriginalSQL == other.OriginalSQL
}

// size calculates the memory size of a BindRecord.
func (br *BindRecord) size() float64 {
	mem := float64(len(hack.Slice(br.OriginalSQL)) + len(hack.Slice(br.Db)))
	for _, binding := range br.Bindings {
		mem += binding.size()
	}
	return mem
}

var statusIndex = map[string]int{
	Enabled: 0,
	deleted: 1,
	Invalid: 2,
}

func (br *BindRecord) metrics() ([]float64, []int) {
	sizes := make([]float64, len(statusIndex))
	count := make([]int, len(statusIndex))
	if br == nil {
		return sizes, count
	}
	commonLength := float64(len(br.OriginalSQL) + len(br.Db))
	// We treat it as deleted if there are no bindings. It could only occur in session handles.
	if len(br.Bindings) == 0 {
		sizes[statusIndex[deleted]] = commonLength
		count[statusIndex[deleted]] = 1
		return sizes, count
	}
	// Make the common length counted in the first binding.
	sizes[statusIndex[br.Bindings[0].Status]] = commonLength
	for _, binding := range br.Bindings {
		sizes[statusIndex[binding.Status]] += binding.size()
		count[statusIndex[binding.Status]]++
	}
	return sizes, count
}

// size calculates the memory size of a bind info.
func (b *Binding) size() float64 {
	res := len(b.BindSQL) + len(b.Status) + 2*int(unsafe.Sizeof(b.CreateTime)) + len(b.Charset) + len(b.Collation) + len(b.ID)
	return float64(res)
}

func updateMetrics(scope string, before *BindRecord, after *BindRecord, sizeOnly bool) {
	beforeSize, beforeCount := before.metrics()
	afterSize, afterCount := after.metrics()
	for status, index := range statusIndex {
		metrics.BindMemoryUsage.WithLabelValues(scope, status).Add(afterSize[index] - beforeSize[index])
		if !sizeOnly {
			metrics.BindTotalGauge.WithLabelValues(scope, status).Add(float64(afterCount[index] - beforeCount[index]))
		}
	}
}


text:
/********************************/
/*                              */
/* Button User Interface Code   */
/*                              */
/********************************/

/**
 * Do not enclose in an anonymous function, as the compiler may create
 * global scope variables to replace true, false, null, whcih can then collide
 * with other variables.
 * Instead, use the --output-wrapper command during optimization, which will
 * add the anonymous function to enclose all code, including those optimized
 * variables which would otherwise have global scope.
 **/

try {
  // Declare KeymanWeb, OnScreen keyboard and Util objects
  var keymanweb=window['tavultesoft']['keymanweb'],osk=keymanweb['osk'],
    util=keymanweb['util'],dbg=keymanweb['debug'];

  // Disable UI for touch devices
  if(util['isTouchDevice']()) throw '';

  // User interface global and variables
  keymanweb['ui'] = {};
  var ui=keymanweb['ui'];
  ui['name'] = 'button';

  ui.init = false;
  ui.KeyboardSelector = null;

  ui.KeymanWeb_DefaultKeyboardHelp='KeymanWeb is not running.  Choose a keyboard from the list';
  ui._KeymanWeb_KbdList = null;
  ui._KMWSel = null;
  ui._IsHelpVisible = false;
  ui._DefaultKeyboardID = '';

  ui.updateTimer = null;
  ui.updateList = true;

  /**
   * Highlight the currently active keyboard in the list of keyboards
   **/
  ui._ShowSelected = function()
  {
    var _rv,kbd=keymanweb['getActiveKeyboard'](),lgc=keymanweb['getActiveLanguage'](),
      kList = ui._KeymanWeb_KbdList.childNodes,
      _r = /^KMWSel_(.*)\$(.*)$/;

    for(var i=1; i<kList.length; i++)
      kList[i].childNodes[0].className = '';

    for(var i=2; i<kList.length; i++)
    {
      _rv = _r.exec(kList[i].childNodes[0].id);
      if(_rv && (_rv[1] == kbd) && (_rv[2] == lgc)) break;
    }
    if(i >= kList.length) i=1;
    kList[i].childNodes[0].className = 'selected';
  }

  /**
   * Select keyboard by id
   *
   * @param       {Event}  _id   keyboard selection event
   * @return      {boolean}
   */
  ui._SelectKeyboard = function(_id)
  {
    if(typeof(_id) == 'object')
    {
      var t=null;
      if((typeof(_id.target) != 'undefined') && _id.target) t=_id.target;
      else if((typeof(_id.srcElement) != 'undefined') && _id.srcElement) t=_id.srcElement;
      if(t) _id=t.id;
    }

    var _r=/^KMWSel_(.*)\$(.*)$/;
    var _rv=_r.exec(_id),_lgc='',_name='';
    if(_rv !== null)
    {
      _name = _rv[1].split('$')[0]; //new code
      _lgc = _id.split('$')[1];
      if(ui._KMWSel != null) ui._KMWSel.className = '';
      var _k = document.getElementById(_id);
      if(_k) _k.className='selected';
      ui._KMWSel = _k;
      keymanweb['setActiveKeyboard'](_name,_lgc);
    }
    else
      _name=null;

    keymanweb['focusLastActiveElement']();
    if(osk['isEnabled']()) osk['show'](true);

    ui._ShowKeyboardButton(_name);
    return false;
  }

  /**
   * Set KMW UI activation state on mouse click
   *
   * @param       {Event}    e     event
   */
  ui._SelectorMouseDown = function(e)
  {
    var x=keymanweb['getLastActiveElement']();

    // Set the focus to an input field, to get correct OSK display behaviour
    if(!x) ui._FocusFirstInput(); else keymanweb['focusLastActiveElement']();

    if(keymanweb['activatingUI']) keymanweb['activatingUI'](1);
  }

  /**
   * Set focus on mouse up
   *
   * @param       {Event}    e     event
   */
  ui._SelectorMouseUp = function(e)
  {
    var x=keymanweb['getLastActiveElement']();

    // Set the focus to an input field, to get correct OSK display behaviour
    if(!x) ui._FocusFirstInput(); else keymanweb['focusLastActiveElement']();
  }

  /**
   * Set KMW UI activation state on mouse over
   *
   * @param       {Event}   e     event
   */
  ui._SelectorMouseOver = function(e)
  {
    // highlight the currently active keyboard
    ui._ShowSelected();

    if(keymanweb['activatingUI']) keymanweb['activatingUI'](1);
    document.getElementById("kmwico_li").className="sfhover";

    // Conditionally display keyboard button
    ui._ShowKeyboardButton();
  }

  /**
   * Sets the focus to the first input or textarea found on the current page
   * to ensure consistent keyboard selection and OSK display behaviour
   */
  ui._FocusFirstInput = function()
  {
    var i,ip=null,tp=null,
      iList=document.getElementsByTagName("input"),
      tList=document.getElementsByTagName("textarea");

    for(i=0; i<iList.length; i++)
      if(iList[i].type == 'text') break;

    if(i < iList.length) ip=iList[i];

    if(tList.length > 0) tp = tList[0];

    if((!ip) && (!tp))
      return;
    else if(ip && !tp)
      ip.focus();
    else if(tp && !ip)
      tp.focus();
    else if(ip.offsetTop < tp.offsetTop)
      ip.focus();
    else if(ip.offsetTop > tp.offsetTop)
      tp.focus();
    else if(ip.offsetLeft < tp.offsetLeft)
      ip.focus();
    else
      tp.focus();
  }

  /**
   * Clear KMW UI activation state on mouse out
   *
   * @param       {Event}    e     event
   */
  ui._SelectorMouseOut = function(e)
  {
    if(keymanweb['activatingUI']) keymanweb['activatingUI'](0);
    document.getElementById("kmwico_li").className="sfunhover";
  }

  /**
   * Disable the button to show/hide the OSK if no active keyboard or active keyboard is CJK (user cannot hide)
   *
   * @param       {?string=}  _name     current keyboard name
   */
  ui._ShowKeyboardButton = function(_name)
  {
    var kbdName = keymanweb['getActiveKeyboard'](), kbdId=document.getElementById("KMW_Keyboard");
    if(arguments.length > 0) kbdName = _name;
    if(kbdId)
    {
      if((kbdName == '') || keymanweb['isCJK']())
      {
        kbdId.className='kmw_disabled';
      }
      else
      {
        kbdId.className = osk['isEnabled']() ? 'kmw_show' : 'kmw_hide';
      }
    }
  }

  /**
   * UI Functions called by KeymanWeb or OSK
   */
  osk['addEventListener']('show',
    function(oskPosition)
    {
      var t=keymanweb['getLastActiveElement']();
      if(t)
      {
        if(!oskPosition['userLocated'])
        {
          oskPosition['x'] = util['getAbsoluteX'](t);
          oskPosition['y'] = util['getAbsoluteY'](t)+t.offsetHeight;
        }
      }

      ui._ShowKeyboardButton();
      return oskPosition;
    });
 /* TODO: why is this still needed??? Does it actually do anything?? */
  osk['addEventListener']('hide',
    function(hiddenByUser)
    {
      if((arguments.length > 0) && hiddenByUser)
      {
        var _a = document.getElementById('KMW_Keyboard');
        if(_a) _a.className = 'kmw_hide';
      }
    });

  /**
   * Show or hide the OSK (always visible for CJK keyboards)
   *
   * @param       {Object}    _anchor     anchor element (?)
   * @return      {boolean}
   **/
  ui._ShowKeymanWebKeyboard = function(_anchor)
  {
    var kbdId=document.getElementById("KMW_Keyboard");
    if((kbdId.className!='kmw_disabled') && osk['show'])
    {
      if(osk['isEnabled']()) osk['hide'](); else osk['show'](true);
    }
    if(window.event) window.event.returnValue=false;

    keymanweb['focusLastActiveElement']();
    return false;
  }

  /**
   * Initialize Button User Interface
   **/
  ui.Initialize = function()
  {
    //Never initialize UI before KMW (parameters will be undefined)
    if(!keymanweb['initialized'])
    {
      window.setTimeout(ui.Initialize,250); return;
    }

    if(ui.init || util['isTouchDevice']()) return;

    ui.init = true;

    util['addStyleSheet'](ui._Appearance);

    ui._KeymanWeb_KbdList = util['createElement']('ul');
    ui._KeymanWeb_KbdList.id = 'KeymanWeb_KbdList';

    var _elem = document.getElementById('KeymanWebControl');
    if(!_elem)
    {
      var _elems = document.getElementsByTagName('div');
      for(var _i = 0; _i < _elems.length; _i++)
      {
        if(_elems[_i].className == 'KeymanWebControl')
        {
          _elem = _elems[_i]; break;
        }
      }
    }

    // Insert as first child of body if not defined by user
    if(!_elem && (document.body != null))
    {
      _elem=document.createElement('DIV');
      _elem.id='KeymanWebControl';
      document.body.insertBefore(_elem,document.body.firstChild);
    }

    var imgPath=util['getOption']('resources')+'ui/button/';
    if(_elem)
    {
      // Append another DIV to follow the main control with clear:both to prevent selection over entire width of window
      var dx=document.createElement('DIV'),ds=dx.style;
      ds.clear='both';
      _elem.parentNode.insertBefore(dx,_elem.nextSibling);

      var _btn=util['createElement']('img'), _ul=util['createElement']('ul'),_li0=util['createElement']('li');
      _btn.id = 'kmwico_a';
      _btn.src = imgPath+'kmw_button.gif';
      _btn.onclick = function(){return false;}  //may want to use this in iOS *****
      _li0.appendChild(_btn);
      _li0.id = 'kmwico_li';
      _ul.appendChild(_li0);
      _ul.id = 'kmwico';
      _ul.style.display = 'block';
      _elem.appendChild(_ul);
    }
    // Do not define any UI behaviour if no controller element can be found
    else return;

    if(!keymanweb['iOS'])
    {
      var _li = util['createElement']('li');
      var _a = util['createElement']('a');
      var _img = util['createElement']('img');
      _img.src = imgPath+'kbdicon.gif';
      _a.appendChild(_img);

      var _txt1 = document.createTextNode(' Hide Keyboard');
      var _txt2 = document.createTextNode(' Show Keyboard');
      var _sp1 = util['createElement']('span');
      _sp1.id = 'KMW_KbdVisibleMsg';
      _sp1.appendChild(_txt1);
      _a.appendChild(_sp1);

      var _sp2 = util['createElement']('span');
      _sp2.id = 'KMW_KbdHiddenMsg';
      _sp2.appendChild(_txt2);
      _a.appendChild(_sp2);
      _a.onmousedown = ui._ShowKeymanWebKeyboard;
      _a.href = '#';
      _a.id = 'KMW_Keyboard';
      _li.id = 'KMW_ButtonUI_KbdIcon';
      _li.appendChild(_a);
      ui._KMWSel = _a;
      ui._KeymanWeb_KbdList.appendChild(_li);
    }

    var _li1 = util['createElement']('li');
    _li1.id = 'KMW_ButtonUI_KbdList';
    var _a1 = util['createElement']('a');
    _a1.appendChild(document.createTextNode('English'));

    _a1.onclick = ui._SelectKeyboard;
    _a1.href = '#';
    _a1.id='KMWSel_$';
    _a1.className='selected';
    _li1.appendChild(_a1);
    ui._KMWSel = _a1;
    ui._KeymanWeb_KbdList.appendChild(_li1);

    var _kbds = keymanweb['getKeyboards'](), _added = [];

    ui.updateKeyboardList();

    document.getElementById('kmwico_li').appendChild(ui._KeymanWeb_KbdList);

    var _sfEl = document.getElementById("kmwico_li");
    util['attachDOMEvent'](_sfEl,'mousedown',ui._SelectorMouseDown);
    util['attachDOMEvent'](_sfEl,'mouseover',ui._SelectorMouseOver);
    util['attachDOMEvent'](_sfEl,'mouseout',ui._SelectorMouseOut);
    util['attachDOMEvent'](_sfEl,'mouseup',ui._SelectorMouseUp);

    keymanweb['focusLastActiveElement']();  	//TODO: this needs to be extended - if no element is active, try and identify an enabled input element
  }

  /**
   * Keyboard registration event handler
   *
   * Set a timer to update the UI keyboard list on timeout after each keyboard is registered,
   * thus updating only once when only if multiple keyboards are registered together
   */
  keymanweb['addEventListener']('keyboardregistered',
    function(p)
    {
        ui.updateList = true;
        if(ui.updateTimer) clearTimeout(ui.updateTimer);
        ui.updateTimer = setTimeout(ui.updateKeyboardList,20);
    });

  /**
   * Update the entire menu when keyboards are registered or deregistered
   **/
  ui.updateKeyboardList = function()
  {
    ui.updateList = false;

    if(!ui.init) return;

    // Clear existing list first (first two nodes must be preserved)
    for(var i=ui._KeymanWeb_KbdList.childNodes.length; i>2; i--)
      ui._KeymanWeb_KbdList.removeChild(ui._KeymanWeb_KbdList.childNodes[i-1]);

    var kbds=keymanweb['getKeyboards']();
    if(kbds.length > 0)
    {
      for(var i=0; i<kbds.length; i++)
        ui.registerKeyboard(kbds[i]['InternalName'],kbds[i]['LanguageName'],kbds[i]['Name'],kbds[i]['LanguageCode'],kbds[i]['RegionCode']);
    }
  }

  /**
   * As each keyboard stub is registered, append it to the list
   *
   * @param       {string}    Lki     internal name
   * @param       {string}    Lkl     language name
   * @param       {string}    Lkn     keyboard name
   * @param       {string}    Lklc    language code
   * @param       {string}    Lkrc    region code
   **/
  ui.registerKeyboard = function(Lki,Lkl,Lkn,Lklc,Lkrc)
  {
    var _li2 = util['createElement']('li'),
      _a2 = util['createElement']('a'),
      _t = Lkn.replace(/\s?keyboard/i,'');

    if(Lkl)
    {
      var lg=Lkl.split(',')[0];
      if(Lkn.search(lg) == -1)
        _t = lg+' ('+_t+')';
    }
    if(_t.length > 26) _t=_t.substr(0,24)+'\u2026';
    _a2.appendChild(document.createTextNode(_t));
    _a2.onclick = ui._SelectKeyboard;
    _a2.href = '#';
    _a2.id='KMWSel_'+Lki+'$'+Lklc;
    _li2.appendChild(_a2);
    ui._KeymanWeb_KbdList.appendChild(_li2);
  }

  // Define appearance of this interface
  ui._Appearance =
    "#kmwico, #kmwkbd {"+
      "vertical-align: middle;"+
    "} "+

    "#KeymanWebControl {float:left;} "+

    "#KeymanWebControl * "+
    "{"+
      "letter-spacing: 0px !important;"+
      "line-height: 1li !important;"+
      "white-space: nowrap !important;"+
    "} "+

    "#KeymanWebControl #kmwico img {"+
      "vertical-align: top;"+
      "padding: 0;"+
      "margin: 0;"+
      "border: none;"+
    "} "+

    "#KeymanWebControl #kmwico, #kmwico ul {"+
      "padding: 0;"+
      "margin: 0;"+
      "list-style: none;"+
    "} "+

    "#KeymanWebControl #kmwico_a {"+
      "display: block;"+
  	//"border: none !important;"+
      "width: 22px; height: 23px; "+                                 /* sizes needed for kmw_button.gif */
    "} "+

    "#KeymanWebControl #kmwico li { "+
      "text-align: left;"+
    "} "+

    "#KeymanWebControl #kmwico li ul {"+
      "display: block;"+
      "position: absolute;"+
      "left: -5999px;"+
      "border: solid 2px #ad4a28;"+
      "background: white;"+
      "border-radius: 4px;"+
      "box-shadow: 4px 4px 2px #666;"+
      "z-index: 10011;"+ /* above the osk */
    "} "+

    "#KeymanWebControl #kmwico li.sfunhover ul {"+
      "display: none; left: -5999px;"+
    "} "+

    "#KeymanWebControl #kmwico li:hover ul, #kmwico li.sfhover ul {"+
      "display: block;"+
      "left: auto;"+
    "} "+

    "#KeymanWebControl #kmwico ul li {"+
      "float: none;"+
      "padding: 0 !important;"+
      "margin: 0 !important;"+
      "width: 136px !important;"+
    "} "+

    "#KeymanWebControl #KMW_LanguageName {"+
      "font-weight: bold;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a, #kmwico ul li a:visited {"+
      "display: block;"+
      "padding: 2px 4px !important;"+
    	"border: none !important;"+
    //  "width: auto;"+
      "color: #404040;"+
      "font-family: Tahoma,Verdana,Arial,sans-serif;"+
      "font-size: 8pt;"+
      "text-decoration: none;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.selected {"+
      "font-weight: bold;"+
      "color: black;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a:hover {"+
      "color: white;"+
      "background-color: #ad4a28;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.kmw_disabled, #KeymanWebControl #kmwico ul li a.kmw_disabled:hover {"+
      "color: #c0c0c0; cursor: default;"+
      "background-color: white;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.kmw_show span#KMW_KbdHiddenMsg, #KeymanWebControl #kmwico ul li a.kmw_disabled span#KMW_KbdVisibleMsg {"+
      "display: none;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.kmw_show span#KMW_KbdVisibleMsg {"+
      "display: inline;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.kmw_hide span#KMW_KbdHiddenMsg {"+
      "display: inline;"+
    "} "+

    "#KeymanWebControl #kmwico ul li a.kmw_hide span#KMW_KbdVisibleMsg {"+
      "display: none;"+
    "} "+

    "#KeymanWebControl #kmwico ul li#KMW_ButtonUI_KbdIcon {"+
      "border-bottom: solid 1px #ad4a28;"+
    "} ";

   // Initialize after KMW is fully initialized, if UI already loaded
  keymanweb['addEventListener']('loaduserinterface',ui.Initialize);

  // but also call initialization when script loaded, which is after KMW initialization for asynchronous script loading
  ui.Initialize();

} catch(err){}


text:
//- Copyright (c) 2010 James Grenning and Contributed to Unity Project

#include "unity_fixture.h"
#include "unity_output_Spy.h"
#include <stdlib.h>
#include <string.h>

extern UNITY_FIXTURE_T UnityFixture;

TEST_GROUP(UnityFixture);

TEST_SETUP(UnityFixture)
{
}

TEST_TEAR_DOWN(UnityFixture)
{
}

int my_int;
int* pointer1 = 0;
int* pointer2 = (int*)2;
int* pointer3 = (int*)3;
int int1;
int int2;
int int3;
int int4;

TEST(UnityFixture, PointerSetting)
{
    TEST_ASSERT_POINTERS_EQUAL(pointer1, 0);
    UT_PTR_SET(pointer1, &int1);
    UT_PTR_SET(pointer2, &int2);
    UT_PTR_SET(pointer3, &int3);
    TEST_ASSERT_POINTERS_EQUAL(pointer1, &int1);
    TEST_ASSERT_POINTERS_EQUAL(pointer2, &int2);
    TEST_ASSERT_POINTERS_EQUAL(pointer3, &int3);
    UT_PTR_SET(pointer1, &int4);
    UnityPointer_UndoAllSets();
    TEST_ASSERT_POINTERS_EQUAL(pointer1, 0);
    TEST_ASSERT_POINTERS_EQUAL(pointer2, (int*)2);
    TEST_ASSERT_POINTERS_EQUAL(pointer3, (int*)3);
}

TEST(UnityFixture, ForceMallocFail)
{
    void* m;
    void* mfails;
    UnityMalloc_MakeMallocFailAfterCount(1);
    m = malloc(10);
    CHECK(m);
    mfails = malloc(10);
    TEST_ASSERT_POINTERS_EQUAL(0, mfails);
    free(m);
}

TEST(UnityFixture, ReallocSmallerIsUnchanged)
{
    void* m1 = malloc(10);
    void* m2 = realloc(m1, 5);
    TEST_ASSERT_POINTERS_EQUAL(m1, m2);
    free(m2);
}

TEST(UnityFixture, ReallocSameIsUnchanged)
{
    void* m1 = malloc(10);
    void* m2 = realloc(m1, 10);
    TEST_ASSERT_POINTERS_EQUAL(m1, m2);
    free(m2);
}

TEST(UnityFixture, ReallocLargerNeeded)
{
    void* m1 = malloc(10);
    void* m2;
    strcpy((char*)m1, "123456789");
    m2 = realloc(m1, 15);
    CHECK(m1 != m2);
    STRCMP_EQUAL("123456789", m2);
    free(m2);
}

TEST(UnityFixture, ReallocNullPointerIsLikeMalloc)
{
    void* m = realloc(0, 15);
    CHECK(m != 0);
    free(m);
}

TEST(UnityFixture, ReallocSizeZeroFreesMemAndReturnsNullPointer)
{
    void* m1 = malloc(10);
    void* m2 = realloc(m1, 0);
    TEST_ASSERT_POINTERS_EQUAL(0, m2);
}

TEST(UnityFixture, CallocFillsWithZero)
{
    void* m = calloc(3, sizeof(char));
    char* s = (char*)m;
    TEST_ASSERT_BYTES_EQUAL(0, s[0]);
    TEST_ASSERT_BYTES_EQUAL(0, s[1]);
    TEST_ASSERT_BYTES_EQUAL(0, s[2]);
    free(m);
}

char *p1;
char *p2;

TEST(UnityFixture, PointerSet)
{
    char c1;
    char c2;
    char newC1;
    char newC2;
    p1 = &c1;
    p2 = &c2;

    UnityPointer_Init();
    UT_PTR_SET(p1, &newC1);
    UT_PTR_SET(p2, &newC2);
    TEST_ASSERT_POINTERS_EQUAL(&newC1, p1);
    TEST_ASSERT_POINTERS_EQUAL(&newC2, p2);
    UnityPointer_UndoAllSets();
    TEST_ASSERT_POINTERS_EQUAL(&c1, p1);
    TEST_ASSERT_POINTERS_EQUAL(&c2, p2);
}

//------------------------------------------------------------

TEST_GROUP(UnityCommandOptions);

int savedVerbose;
int savedRepeat;
const char* savedName;
const char* savedGroup;

TEST_SETUP(UnityCommandOptions)
{
    savedVerbose = UnityFixture.Verbose;
    savedRepeat = UnityFixture.RepeatCount;
    savedName = UnityFixture.NameFilter;
    savedGroup = UnityFixture.GroupFilter;
}

TEST_TEAR_DOWN(UnityCommandOptions)
{
    UnityFixture.Verbose = savedVerbose;
    UnityFixture.RepeatCount= savedRepeat;
    UnityFixture.NameFilter = savedName;
    UnityFixture.GroupFilter = savedGroup;
}

static const char* noOptions[] = {
        "testrunner.exe"
};

TEST(UnityCommandOptions, DefaultOptions)
{
    UnityGetCommandLineOptions(1, noOptions);
    TEST_ASSERT_EQUAL(0, UnityFixture.Verbose);
    TEST_ASSERT_POINTERS_EQUAL(0, UnityFixture.GroupFilter);
    TEST_ASSERT_POINTERS_EQUAL(0, UnityFixture.NameFilter);
    TEST_ASSERT_EQUAL(1, UnityFixture.RepeatCount);
}

static const char* verbose[] = {
        "testrunner.exe",
        "-v"
};

TEST(UnityCommandOptions, OptionVerbose)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(2, verbose));
    TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
}

static const char* group[] = {
        "testrunner.exe",
        "-g", "groupname"
};

TEST(UnityCommandOptions, OptionSelectTestByGroup)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, group));
    STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
}

static const char* name[] = {
        "testrunner.exe",
        "-n", "testname"
};

TEST(UnityCommandOptions, OptionSelectTestByName)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, name));
    STRCMP_EQUAL("testname", UnityFixture.NameFilter);
}

static const char* repeat[] = {
        "testrunner.exe",
        "-r", "99"
};

TEST(UnityCommandOptions, OptionSelectRepeatTestsDefaultCount)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(2, repeat));
    TEST_ASSERT_EQUAL(2, UnityFixture.RepeatCount);
}

TEST(UnityCommandOptions, OptionSelectRepeatTestsSpecificCount)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, repeat));
    TEST_ASSERT_EQUAL(99, UnityFixture.RepeatCount);
}

static const char* multiple[] = {
        "testrunner.exe",
        "-v",
        "-g", "groupname",
        "-n", "testname",
        "-r", "98"
};

TEST(UnityCommandOptions, MultipleOptions)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(8, multiple));
    TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
    STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
    STRCMP_EQUAL("testname", UnityFixture.NameFilter);
    TEST_ASSERT_EQUAL(98, UnityFixture.RepeatCount);
}

static const char* dashRNotLast[] = {
        "testrunner.exe",
        "-v",
        "-g", "gggg",
        "-r",
        "-n", "tttt",
};

TEST(UnityCommandOptions, MultipleOptionsDashRNotLastAndNoValueSpecified)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(7, dashRNotLast));
    TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
    STRCMP_EQUAL("gggg", UnityFixture.GroupFilter);
    STRCMP_EQUAL("tttt", UnityFixture.NameFilter);
    TEST_ASSERT_EQUAL(2, UnityFixture.RepeatCount);
}

static const char* unknownCommand[] = {
        "testrunner.exe",
        "-v",
        "-g", "groupname",
        "-n", "testname",
        "-r", "98",
        "-z"
};
TEST(UnityCommandOptions, UnknownCommandIsIgnored)
{
    TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(9, unknownCommand));
    TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
    STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
    STRCMP_EQUAL("testname", UnityFixture.NameFilter);
    TEST_ASSERT_EQUAL(98, UnityFixture.RepeatCount);
}

//------------------------------------------------------------

TEST_GROUP(LeakDetection);

TEST_SETUP(LeakDetection)
{
    UnityOutputCharSpy_Create(1000);
}

TEST_TEAR_DOWN(LeakDetection)
{
    UnityOutputCharSpy_Destroy();
}

#define EXPECT_ABORT_BEGIN \
  { \
    jmp_buf TestAbortFrame;   \
    memcpy(TestAbortFrame, Unity.AbortFrame, sizeof(jmp_buf)); \
    if (TEST_PROTECT()) \
    {

#define EXPECT_ABORT_END \
    } \
    memcpy(Unity.AbortFrame, TestAbortFrame, sizeof(jmp_buf)); \
  }

TEST(LeakDetection, DetectsLeak)
{
    void* m = malloc(10);
    UnityOutputCharSpy_Enable(1);
    EXPECT_ABORT_BEGIN
    UnityMalloc_EndTest();
    EXPECT_ABORT_END
    UnityOutputCharSpy_Enable(0);
    CHECK(strstr(UnityOutputCharSpy_Get(), "This test leaks!"));
    free(m);
    Unity.CurrentTestFailed = 0;
}

TEST(LeakDetection, BufferOverrunFoundDuringFree)
{
    void* m = malloc(10);
    char* s = (char*)m;
    s[10] = (char)0xFF;
    UnityOutputCharSpy_Enable(1);
    EXPECT_ABORT_BEGIN
    free(m);
    EXPECT_ABORT_END
    UnityOutputCharSpy_Enable(0);
    CHECK(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during free()"));
    Unity.CurrentTestFailed = 0;
}

TEST(LeakDetection, BufferOverrunFoundDuringRealloc)
{
    void* m = malloc(10);
    char* s = (char*)m;
    s[10] = (char)0xFF;
    UnityOutputCharSpy_Enable(1);
    EXPECT_ABORT_BEGIN
    m = realloc(m, 100);
    EXPECT_ABORT_END
    UnityOutputCharSpy_Enable(0);
    CHECK(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during realloc()"));
    Unity.CurrentTestFailed = 0;
}


text:
//========= Copyright 2016-2017, HTC Corporation. All rights reserved. ===========

using Valve.VR;

namespace HTC.UnityPlugin.Vive
{
    [ViveRoleEnum((int)TrackerRole.Invalid)]
    public enum TrackerRole
    {
        Invalid,
        Tracker1,
        Tracker2,
        Tracker3,
        Tracker4,
        Tracker5,
        Tracker6,
        Tracker7,
        Tracker8,
        Tracker9,
        Tracker10,
        Tracker11,
        Tracker12,
        Tracker13,
    }

    public class TrackerRoleHandler : ViveRole.MapHandler<TrackerRole>
    {
        private bool IsTracker(uint deviceIndex)
        {
            return ViveRole.GetDeviceClass(deviceIndex) == ETrackedDeviceClass.GenericTracker;
        }

        public override void OnInitialize()
        {
            UnmappingAll();

            MappingTrackers();
        }

        public override void OnConnectedDeviceChanged(uint deviceIndex, ETrackedDeviceClass deviceClass, string deviceSN, bool connected)
        {
            if (RoleMap.IsDeviceBound(deviceSN)) { return; }

            if (connected)
            {
                if (deviceClass != ETrackedDeviceClass.GenericTracker) { return; }

                // find unmapped role
                var role = RoleMap.RoleInfo.MinValidRole;
                while (!RoleMap.RoleInfo.IsValidRole(role) || RoleMap.IsRoleMapped(role))
                {
                    if (++role > RoleMap.RoleInfo.MaxValidRole) { return; }
                }

                MappingRole(role, deviceIndex);
            }
            else
            {
                UnmappingDevice(deviceIndex);
            }
        }

        public override void OnBindingChanged(TrackerRole role, string deviceSN, bool bound)
        {
            if (bound)
            {
                // it's possible that some device will be pushed out when binding
                MappingTrackers();
            }
            else
            {
                if (RoleMap.IsRoleMapped(role))
                {
                    UnmappingRole(role);

                    MappingTrackers();
                }
            }
        }

        public override void OnTrackedDeviceRoleChanged() { }

        private void MappingTrackers()
        {
            var role = RoleMap.RoleInfo.MinValidRole;
            var index = (uint)1;

            while (true)
            {
                while (!RoleMap.RoleInfo.IsValidRole(role) || RoleMap.IsRoleMapped(role) || RoleMap.IsRoleBound(role))
                {
                    if (++role > RoleMap.RoleInfo.MaxValidRole) { return; }
                }

                while (ViveRole.GetDeviceClass(index) != ETrackedDeviceClass.GenericTracker || RoleMap.IsDeviceMapped(index) || RoleMap.IsDeviceConnectedAndBound(index))
                {
                    if (++index >= ViveRole.MAX_DEVICE_COUNT) { return; }
                }

                MappingRole(role++, index++);

                if (role > RoleMap.RoleInfo.MaxValidRole || index >= ViveRole.MAX_DEVICE_COUNT) { return; }
            }
        }
    }
}


text:
The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog


text:
(function( $ ) {

module( "core - deprecated" );

test( "zIndex", function() {
	expect( 7 );
	var el = $( "#zIndexAutoWithParent" ),
		parent = el.parent();
	equal( el.zIndex(), 100, "zIndex traverses up to find value" );
	equal( parent.zIndex(200 ), parent, "zIndex setter is chainable" );
	equal( el.zIndex(), 200, "zIndex setter changed zIndex" );

	el = $( "#zIndexAutoWithParentViaCSS" );
	equal( el.zIndex(), 0, "zIndex traverses up to find CSS value, not found because not positioned" );

	el = $( "#zIndexAutoWithParentViaCSSPositioned" );
	equal( el.zIndex(), 100, "zIndex traverses up to find CSS value" );
	el.parent().zIndex( 200 );
	equal( el.zIndex(), 200, "zIndex setter changed zIndex, overriding CSS" );

	equal( $( "#zIndexAutoNoParent" ).zIndex(), 0, "zIndex never explicitly set in hierarchy" );
});

})( jQuery );


text:
package com.excelian.mache.jmeter.couch;

import com.excelian.mache.core.Mache;
import com.excelian.mache.core.SchemaOptions;
import com.excelian.mache.events.integration.KafkaMqConfig.KafkaMqConfigBuilder;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;

import java.util.Map;

import static com.couchbase.client.java.cluster.DefaultBucketSettings.builder;
import static com.excelian.mache.builder.MacheBuilder.mache;
import static com.excelian.mache.couchbase.builder.CouchbaseProvisioner.couchbase;
import static com.excelian.mache.events.integration.builder.KafkaMessagingProvisioner.kafka;
import static com.excelian.mache.guava.GuavaMacheProvisioner.guava;

/**
 * JMeter client for Cassandra/Kafka.
 */
@SuppressWarnings("serial")
public abstract class MacheAbstractCouchKafkaSamplerClient extends AbstractCouchSamplerClient {

    protected Mache<String, CouchTestEntity> cache1 = null;

    @Override
    public void setupTest(JavaSamplerContext context) {
        Map<String, String> mapParams = extractParameters(context);
        getLogger().info("mache setupTest started  \n");

        try {
            createCache(mapParams);
            getLogger().info("mache setupTest completed. ");

            getLogger().info("cache connection completed cache is " + cache1);
        } catch (Exception e) {
            getLogger().error("mache error building factory", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void teardownTest(JavaSamplerContext context) {
        if (cache1 != null) {
            cache1.close();
        }
    }

    @Override
    public Arguments getDefaultParameters() {
        Arguments defaultParameters = super.getDefaultParameters();

        defaultParameters.addArgument("kafka.connection", "192.168.3.4");
        defaultParameters.addArgument("kafka.topic", "Kafka_JmeterCassandraTest");
        return defaultParameters;
    }

    protected void createCache(Map<String, String> mapParams) throws Exception {
        final String keySpace = mapParams.get("keyspace.name");
        final String couchServer = mapParams.get("couch.server.ip.address");

        cache1 = mache(String.class, CouchTestEntity.class)
                .cachedBy(guava())
                .storedIn(couchbase()
                        .withBucketSettings(builder().name(keySpace).quota(150).build())
                        .withNodes(couchServer)
                        .withSchemaOptions(SchemaOptions.CREATE_SCHEMA_IF_NEEDED)
                        .build())
                .withMessaging(kafka()
                        .withKafkaMqConfig(KafkaMqConfigBuilder.builder()
                                .withZkHost(mapParams.get("kafka.connection"))
                                .build())
                        .withTopic(mapParams.get("kafka.topic"))
                        .build())
                .macheUp();
    }
}


text:
make html
rm -r ../../mirnylab_documentation/mirnylab.bitbucket.org/hiclib
mv  build/html  ../../mirnylab_documentation/mirnylab.bitbucket.org/hiclib
rm -r build
cd ../../mirnylab_documentation/mirnylab.bitbucket.org
hg add *
hg commit -m "Automatic commit from a new build"
hg push


text:
/**
 *
 */
package datastructures.disjointsets;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Sudharsanan Muralidharan
 */
public class DisjointSetNaive<T> {

    private Map<T, DisjointSetListNode<T>> nodesMap = null;

    public DisjointSetNaive() {
        nodesMap = new HashMap<T, DisjointSetListNode<T>>();
    }

    public DisjointSetListNode<T> makeSet(T data) {
        DisjointSetList<T> DisjointSetList = new DisjointSetList<T>();
        DisjointSetListNode<T> node = DisjointSetList.insert(data);
        nodesMap.put(data, node);
        return node;
    }

    public void union(T setElement1, T setElement2) {

        DisjointSetListNode<T> node1 = nodesMap.get(setElement1);
        DisjointSetListNode<T> node2 = nodesMap.get(setElement2);

        if (node1 == null || node2 == null) {
            return;
        }

        DisjointSetList<T> list1 = node1.listRef;
        DisjointSetList<T> list2 = node2.listRef;

        if (list1.equals(list2)) {
            return;
        }

        if (list1.size() >= list2.size()) {
            list1.append(list2);
        } else {
            list2.append(list1);
        }
    }

    public T findSet(T setElement) {
        DisjointSetListNode<T> node = nodesMap.get(setElement);
        if (node == null || node.listRef == null) {
            return null;
        }

        return node.listRef.head().data;
    }
}


text:
using Caliburn.Micro;
using csShared;
using csShared.Geo;
using csShared.Interfaces;
using System.ComponentModel.Composition;

namespace csCommon.MapPlugins.Timeline
{

    public interface ITimelineControl
    { }

    [Export(typeof(ITimelineControl))]
    public class TimelineControlViewModel : Screen, ITimelineControl
    {
        public AppStateSettings AppState { get { return AppStateSettings.Instance; } }
        public FloatingElement Element { get; set; }

        public MapViewDef ViewDef
        {
            get
            {
                return AppState.ViewDef;
            }
        }

        private TimelineControlView mtv;

        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);
            mtv = (TimelineControlView)view;
        }

        public void Custom()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Custom;
        }

        public void LastMonth()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Month;
        }

        public void LastYear()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Year;
        }

        public void LastWeek()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Week;
        }
        public void LastDay()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Day;
        }

        public void LastHour()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Hour;
        }

        public void Last15Min()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Min15;
        }

        public void Last5Min()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Min5;
        }

        public void Last1Min()
        {
            AppState.TimelineManager.TimelineFix = TimelineFixStyles.Min1;
        }

        public TimelineControlViewModel()
        {
            Caption = "Timeline";
        }

        public string Caption { get; set; }
    }
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'helper'))

context "Precious::Views::Editing" do
  include Rack::Test::Methods

  setup do
    @path = cloned_testpath('examples/revert.git')
    Precious::App.set(:gollum_path, @path)
    Precious::App.set(:wiki_options, {allow_editing: true, allow_uploads: true})
    @wiki = Gollum::Wiki.new(@path)
  end

  teardown do
    Precious::App.set(:wiki_options, {allow_editing: true, allow_uploads: true})
    FileUtils.rm_rf(@path)
  end

  test 'creating pages is not blocked' do
    post '/gollum/create',
      content: 'abc',
      format: 'markdown',
      message: 'def',
      page: 'D'

    assert_equal last_response.status, 302

    refute_nil @wiki.page('D')
  end

  test 'creating pages is blocked' do
    Precious::App.set(:wiki_options, {allow_editing: false, allow_uploads: false})

    post '/gollum/create',
      content: 'abc',
      format: 'markdown',
      message: 'def',
      page: 'D'

    assert last_response.body.include? 'Forbidden. This wiki is set to no-edit mode.'

    refute last_response.ok?

    assert_nil @wiki.page('D')
  end

  test ".redirects.gollum file should not be accessible" do
    get '/.redirects.gollum'
    assert_match /Accessing this resource is not allowed/, last_response.body
  end

  test ".redirects.gollum file should not be editable" do
    get '/gollum/edit/.redirects.gollum'
    assert_match /Changing this resource is not allowed/, last_response.body
  end

  test "frontend links for editing are not blocked" do
    get '/A'

    assert last_response.body.include? "Delete this Page"
    assert last_response.body.include? "New"
    assert last_response.body.include? "Upload"
    assert last_response.body.include? "Rename"
    assert last_response.body.include? "Edit"

    get '/gollum/overview'

    assert last_response.body.include? "New"

    get '/gollum/history/A'

    refute last_response.body.include? "Edit"

    get '/gollum/compare/A/fc665395..b26b791c'

    refute last_response.body.include? "Edit Page"

    assert last_response.body.include? "Revert Changes"
  end

  test "frontend links for editing blocked" do
    Precious::App.set(:wiki_options, {allow_editing: false, allow_uploads: false})

    get '/A'

    refute last_response.body.include? "Delete this Page"
    refute last_response.body.include? "Upload"
    refute last_response.body.include? "Rename"
    refute last_response.body.include? "Edit"
    refute last_response.body.include? "New"

    get '/gollum/overview'

    refute last_response.body.include? "New"

    get '/gollum/history/A'

    refute last_response.body.include? "Edit"

    get '/gollum/compare/A/fc665395..b26b791c'

    refute last_response.body.include? "Edit Page"
    refute last_response.body.include? "Revert Changes"
  end

  def app
    Precious::App
  end
end


text:
class CBlock;
class CScript;
class CTransaction;
struct CMutableTransaction;
struct PartiallySignedTransaction;
class uint256;
class UniValue;

// core_read.cpp
CScript ParseScript(const std::string& s);
std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode = false);
bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness = false, bool try_witness = true);
bool DecodeHexBlk(CBlock&, const std::string& strHexBlk);
uint256 ParseHashStr(const std::string&, const std::string& strName);
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName);
bool DecodePSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error);
int ParseSighashString(const UniValue& sighash);

// core_write.cpp
UniValue ValueFromAmount(const CAmount& amount);
std::string FormatScript(const CScript& script);
std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags = 0);
std::string SighashToStr(unsigned char sighash_type);
void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
void ScriptToUniv(const CScript& script, UniValue& out, bool include_address);
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0);

#endif // DIGIBYTE_CORE_IO_H


text:
<footer><span class='sitefooter'>Copyright (c) Everything about Adventure
</footer>


text:
=begin
 distributed Ruby --- Queue
 	Copyright (c) 1999-2000 Masatoshi SEKI
=end

require 'thread'
require 'drb/drb'

DRb.start_service(nil, Queue.new)
puts DRb.uri
DRb.thread.join


text:
<?xml version="1.0" encoding="utf-8"?>

<project name="jchemhub" default="usage">

	<property name="base.dir" location="." />
	<property name="build.dir" value="${base.dir}/build" />
	<property name="closure-library.dir" value="${base.dir}/third-party/closure/closure" />
	<property name="closure-compiler.jar" value="${base.dir}/../closure-compiler/compiler.jar" />
	<property name="js-src.dir" value="${base.dir}/jchemhub" />

	<path id="input-files">
		<filelist dir="${js-src.dir}/controller">
			<file name="reaction_editor.js" />
			<file name="defaulttoolbar.js" />
			<file name="toolbarcontroller.js" />
		</filelist>
		<fileset dir="${js-src.dir}/controller/plugins" />
		<filelist dir="${js-src.dir}/io">
			<file name="json.js" />
		</filelist>
		<filelist>
			<file name="export.js" />
		</filelist>
	</path>

	<pathconvert pathsep=' -i ' property="jsfiles" refid="input-files" />

	<macrodef name="calcdeps">
		<attribute name="outputfile" />
		<attribute name="compilerjarfile" default="${closure-compiler.jar}" />
		<attribute name="compilationlevel" default="ADVANCED_OPTIMIZATIONS" />
		<attribute name="outputmode" default="compiled" />
		<element name="extraflags" optional="yes" />
		<sequential>
			<mkdir dir="${build.dir}" />
			<exec executable="python" failonerror="true" logError="true" output="${build.dir}/@{outputfile}">
				<arg value="${closure-library.dir}/bin/calcdeps.py" />
				<arg line='-i ${jsfiles}' />
				<arg line='-p ${closure-library.dir}' />
				<arg line='-p ${js-src.dir}' />
				<arg line="-o @{outputmode}" />
				<arg line='-c "@{compilerjarfile}"' />
				<arg line='-f "--compilation_level=@{compilationlevel}"' />
				<arg line='-f "--jscomp_warning=checkTypes"' />
				<arg line='-f "--jscomp_warning=accessControls"' />
				<arg line='-f "--jscomp_warning=missingProperties"' />
				<arg line='-f "--jscomp_warning=unknownDefines"' />
				<arg line='-f "--jscomp_warning=strictModuleDepCheck"' />

				<extraflags />
			</exec>
		</sequential>
	</macrodef>

	<target name="clean" description="delete generated files">
		<delete dir="${build.dir}" />
	</target>

	<target name="build-deps" description="rebuild deps.js file">
		<exec executable="python" failonerror="true" logError="true" output="${js-src.dir}/deps.js">
			<arg value="${closure-library.dir}/bin/calcdeps.py" />
			<arg line='-p "${closure-library.dir}"' />
			<arg line='-p "${js-src.dir}"' />
			<arg line="-o deps" />
		</exec>
	</target>

	<target name='compile-check' description='check by compiling all jchemhub files'>
		<mkdir dir="${build.dir}" />
		<exec executable="python" failonerror="true" logError="true" output="${build.dir}/compile-check.js">
			<arg value="${closure-library.dir}/bin/calcdeps.py" />
			<arg line='-i ${js-src.dir}' />
			<arg line='-p ${closure-library.dir}' />
			<arg line='-p ${js-src.dir}' />
			<arg line="-o compiled" />
			<arg line='-c "${closure-compiler.jar}"' />
			<arg line='-f "--compilation_level=ADVANCED_OPTIMIZATIONS"' />
			<arg line='-f "--jscomp_warning=checkTypes"' />
		</exec>
	</target>

	<target name="compile-advanced" description="compile with ADVANCED_OPTIMIZATIONS setting">
		<calcdeps outputfile="jchemhub-advanced.js" />
	</target>

	<target name="compile-simple" description="compile with SIMPLE_OPTIMIZATIONS setting">
		<calcdeps outputfile="jchemhub-simple.js" compilationlevel="SIMPLE_OPTIMIZATIONS" />
	</target>

	<target name="compile-whitespace-only" description="compile with WHITESPACE_ONLY setting">
		<calcdeps outputfile="jchemhub-whitespace-only.js" compilationlevel="WHITESPACE_ONLY" />
	</target>

	<target name="usage" description="Display main targets by running 'ant -projecthelp'">
		<java classname="org.apache.tools.ant.Main">
			<arg value="-projecthelp" />
		</java>
	</target>

</project>


text:
__author__ = 'Joe Linn'

import pylastica.aggregation.abstractaggregation as abstract

class Global(abstract.AbstractAggregation):
    pass


text:
<?php

use opensrs\backwardcompatibility\dataconversion\domains\cookie\CookieDelete;

/**
 * @group backwardcompatibility
 * @group dataconversion
 * @group cookie
 * @group BC_CookieDelete
 */
class BC_CookieDeleteTest extends PHPUnit_Framework_TestCase
{
    protected $validSubmission = array(
        'data' => array(
            'cookie' => '',
//            "domain" => "",
            ),
        );

    /**
     * Valid conversion should complete with no
     * exception thrown.
     *
     *
     * @group validconversion
     */
    public function testValidDataConversion()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->data->cookie = md5(time());

        $shouldMatchNewDataObject = new \stdClass();
        $shouldMatchNewDataObject->cookie = $data->data->cookie;
        $shouldMatchNewDataObject->attributes = new \stdClass();

        $shouldMatchNewDataObject->attributes->cookie = $data->data->cookie;

        $ns = new CookieDelete();
        $newDataObject = $ns->convertDataObject($data);

        $this->assertTrue($newDataObject == $shouldMatchNewDataObject);
    }
}


text:
var assert = require('assert');
var jinqs = require('./../lib/jinqs');

exports.run = function(test) {
  // distinct(uniqueKeySelector)
  test.that("distinct: should return all elements in a fully unique array.", function() {
    var arr = [4,3,2,1];
    var j = jinqs.over(arr);
    assert.deepEqual(j.distinct().toArray(), arr);
  });

  test.that("distinct: should remove elements that have already been returned.", function() {
    var arr = [4,4,3,4,2,3,1,1,2];
    var expected = [4,3,2,1];

    var j = jinqs.over(arr);
    assert.deepEqual(j.distinct().toArray(), expected);
  });

  test.that("distinct: single repeated element should be returned once.", function() {
    var arr = [1,1,1,1,1];
    var expected = [1];

    var j = jinqs.over(arr);
    assert.deepEqual(j.distinct().toArray(), expected);
  });

  // where(predicate)
  test.that("where: repeat wheres should filter subset.", function()
  {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);

    var set = j.where(function(i) { return i > 1; })
               .where(function(i) { return i < 5; });
    assert.deepEqual(set.toArray(), [2]);
  });

  // skip(count)
  test.that("skip: should repeatedly skip.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    var result = j.skip(2);

    assert.equal(result.first(), 1);
    assert.equal(result.first(), 1);
  });

  test.that("skip: identical skips should get identical data.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    var skip1 = j.skip(2);
    var skip2 = j.skip(2);

    assert.deepEqual(skip1.toArray(), skip2.toArray());
  });

  // skipWhile(predicate)
  test.that("skipWhile: should stop at end of data.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    assert.deepEqual(j.skipWhile(function(){return true;}).toArray(), []);
  });
  test.that("skipWhile: should start after finding a match.", function() {
    var arr = [0,9,1,0,2];

    var j = jinqs.over(arr).skipWhile(function(v){return v<=0}).toArray();
    assert.deepEqual(j, [9,1,0,2]);
  });

  // take(count)
  test.that("take: should repeatedly cut.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    var taken = j.take(2);
    assert.deepEqual(taken.toArray(), [0,9]);
    assert.deepEqual(taken.toArray(), [0,9]);
  });

  test.that("take&skip: should work in a paging scenario.", function() {
    var arr = [1,2,3,4,5,6];
    var j = jinqs.over(arr);

    assert.deepEqual(j.skip(0).take(2).toArray(), [arr[0], arr[1]]);
    assert.deepEqual(j.skip(4).take(2).toArray(), [arr[4], arr[5]]);
    assert.deepEqual(j.skip(2).take(2).toArray(), [arr[2], arr[3]]);
  })

  test.that("take: should stop at end of data.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    var taken = j.take(2000).toArray();

    assert.deepEqual(taken, [0,9,1,0,2]);
  })

  test.that("take: identical takes should get identical data.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    var take1 = j.take(2).toArray();
    var take2 = j.take(2).toArray();

    assert.deepEqual(take1, take2);
    assert.deepEqual(take1, take2);
  });

  // takeWhile(predicate)
  test.that("takeWhile: should stop at end of data.", function() {
    var arr = [0,9,1,0,2];
    var j = jinqs.over(arr);
    assert.deepEqual(j.takeWhile(function(){return true;}).toArray(), arr);
  });
};


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>$title</title>
<link href="$relpath$tabs.css" rel="stylesheet" type="text/css"/>
<link href="$relpath$search/search.css" rel="stylesheet" type="text/css"/>

<link href="$relpath$doxystyle.css" rel="stylesheet" type="text/css"/>

Made on Kubuntu

MiniINI


text:
@implementation RZDebugMenuItem

- (instancetype)initWithTitle:(NSString *)title
{
    self = [super init];
    if ( self ) {
        _title = title;
    }

    return self;
}

@end


text:
package io.druid.query.aggregation.last;

import io.druid.collections.SerializablePair;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.java.util.common.Pair;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.TestLongColumnSelector;
import io.druid.query.aggregation.TestObjectColumnSelector;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.column.Column;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.nio.ByteBuffer;

public class LongLastAggregationTest
{
  private LongLastAggregatorFactory longLastAggFactory;
  private LongLastAggregatorFactory combiningAggFactory;
  private ColumnSelectorFactory colSelectorFactory;
  private TestLongColumnSelector timeSelector;
  private TestLongColumnSelector valueSelector;
  private TestObjectColumnSelector objectSelector;

  private long[] longValues = {23216, 8635, 1547123, Long.MAX_VALUE};
  private long[] times = {1467935723, 1467225653, 1601848932, 72515};
  private SerializablePair[] pairs = {
      new SerializablePair<>(12531L, 113267L),
      new SerializablePair<>(123L, 5437384L),
      new SerializablePair<>(125755L, 34583458L),
      new SerializablePair<>(124L, 34283452L)
  };

  @Before
  public void setup()
  {
    longLastAggFactory = new LongLastAggregatorFactory("billy", "nilly");
    combiningAggFactory = (LongLastAggregatorFactory) longLastAggFactory.getCombiningFactory();
    timeSelector = new TestLongColumnSelector(times);
    valueSelector = new TestLongColumnSelector(longValues);
    objectSelector = new TestObjectColumnSelector<>(pairs);
    colSelectorFactory = EasyMock.createMock(ColumnSelectorFactory.class);
    EasyMock.expect(colSelectorFactory.makeColumnValueSelector(Column.TIME_COLUMN_NAME)).andReturn(timeSelector);
    EasyMock.expect(colSelectorFactory.makeColumnValueSelector("nilly")).andReturn(valueSelector);
    EasyMock.expect(colSelectorFactory.makeColumnValueSelector("billy")).andReturn(objectSelector);
    EasyMock.replay(colSelectorFactory);
  }

  @Test
  public void testLongLastAggregator()
  {
    LongLastAggregator agg = (LongLastAggregator) longLastAggFactory.factorize(colSelectorFactory);

    aggregate(agg);
    aggregate(agg);
    aggregate(agg);
    aggregate(agg);

    Pair<Long, Long> result = (Pair<Long, Long>) agg.get();

    Assert.assertEquals(times[2], result.lhs.longValue());
    Assert.assertEquals(longValues[2], result.rhs.longValue());
    Assert.assertEquals(longValues[2], agg.getLong());
    Assert.assertEquals(longValues[2], agg.getFloat(), 1);
  }

  @Test
  public void testLongLastBufferAggregator()
  {
    LongLastBufferAggregator agg = (LongLastBufferAggregator) longLastAggFactory.factorizeBuffered(
        colSelectorFactory);

    ByteBuffer buffer = ByteBuffer.wrap(new byte[longLastAggFactory.getMaxIntermediateSize()]);
    agg.init(buffer, 0);

    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);

    Pair<Long, Long> result = (Pair<Long, Long>) agg.get(buffer, 0);

    Assert.assertEquals(times[2], result.lhs.longValue());
    Assert.assertEquals(longValues[2], result.rhs.longValue());
    Assert.assertEquals(longValues[2], agg.getLong(buffer, 0));
    Assert.assertEquals(longValues[2], agg.getFloat(buffer, 0), 1);
  }

  @Test
  public void testCombine()
  {
    SerializablePair pair1 = new SerializablePair<>(1467225000L, 64432L);
    SerializablePair pair2 = new SerializablePair<>(1467240000L, 99999L);
    Assert.assertEquals(pair2, longLastAggFactory.combine(pair1, pair2));
  }

  @Test
  public void testLongLastCombiningAggregator()
  {
    LongLastAggregator agg = (LongLastAggregator) combiningAggFactory.factorize(colSelectorFactory);

    aggregate(agg);
    aggregate(agg);
    aggregate(agg);
    aggregate(agg);

    Pair<Long, Long> result = (Pair<Long, Long>) agg.get();
    Pair<Long, Long> expected = (Pair<Long, Long>) pairs[2];

    Assert.assertEquals(expected.lhs, result.lhs);
    Assert.assertEquals(expected.rhs, result.rhs);
    Assert.assertEquals(expected.rhs.longValue(), agg.getLong());
    Assert.assertEquals(expected.rhs, agg.getFloat(), 1);
  }

  @Test
  public void testLongLastCombiningBufferAggregator()
  {
    LongLastBufferAggregator agg = (LongLastBufferAggregator) combiningAggFactory.factorizeBuffered(
        colSelectorFactory);

    ByteBuffer buffer = ByteBuffer.wrap(new byte[longLastAggFactory.getMaxIntermediateSize()]);
    agg.init(buffer, 0);

    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);
    aggregate(agg, buffer, 0);

    Pair<Long, Long> result = (Pair<Long, Long>) agg.get(buffer, 0);
    Pair<Long, Long> expected = (Pair<Long, Long>) pairs[2];

    Assert.assertEquals(expected.lhs, result.lhs);
    Assert.assertEquals(expected.rhs, result.rhs);
    Assert.assertEquals(expected.rhs.longValue(), agg.getLong(buffer, 0));
    Assert.assertEquals(expected.rhs, agg.getFloat(buffer, 0), 1);
  }

  @Test
  public void testSerde() throws Exception
  {
    DefaultObjectMapper mapper = new DefaultObjectMapper();
    String longSpecJson = "{\"type\":\"longLast\",\"name\":\"billy\",\"fieldName\":\"nilly\"}";
    Assert.assertEquals(longLastAggFactory, mapper.readValue(longSpecJson, AggregatorFactory.class));
  }

  private void aggregate(
      LongLastAggregator agg
  )
  {
    agg.aggregate();
    timeSelector.increment();
    valueSelector.increment();
    objectSelector.increment();
  }

  private void aggregate(
      LongLastBufferAggregator agg,
      ByteBuffer buff,
      int position
  )
  {
    agg.aggregate(buff, position);
    timeSelector.increment();
    valueSelector.increment();
    objectSelector.increment();
  }
}