text:
package kr.ac.kaist.jsaf.analysis.typing

import scala.collection.immutable.HashSet
import scala.collection.immutable.HashMap
import scala.collection.mutable.{Set => MSet}
import scala.collection.mutable.{HashSet => MHashSet}
import kr.ac.kaist.jsaf.analysis.typing.domain._
import kr.ac.kaist.jsaf.analysis.typing.models.builtin.{BuiltinError, BuiltinObject}

object Config {
  /**
   * File name.
   */
  var fileName: String = ""
  def setFileName(name: String) = fileName = name

  /**
   * Typing interface.
   */
  var typingInterface: TypingInterface = null
  def setTypingInterface(ti: TypingInterface) = typingInterface = ti

  /**
   * Quiet mode.
   */
  var quietMode = false
  def setQuietMode = quietMode = true

  /**
   * Verbose output.
   * If turned on, all built-in objects and predefined properties of #global will be
   * included when printing analysis results.
   */
  var verbose = 0
  def setVerbose(level: Int) = verbose = level
  val globalVerboseProp: MSet[String] = MHashSet()

  /**
   * Test mode.
   * If turned on, special values, such as value bottom and top, will be provided as
   * predefined global variables.
   */
  var testMode = false
  def setTestMode(flag: Boolean) = testMode = flag
  val testModeProp = HashMap[String, Value](
    ("__BOT", ValueBot),
    ("__TOP", Value(PValueTop)),
    ("__UInt", Value(UInt)),
    ("__Global", Value(GlobalLoc)),
    ("__BoolTop", Value(BoolTop)),
    ("__NumTop", Value(NumTop)),
    ("__StrTop", Value(StrTop)),
    ("__ObjConstLoc", Value(BuiltinObject.ConstLoc)),
    ("__ArrayConstLoc", Value(BuiltinObject.ConstLoc)),
    ("__RefErrLoc", Value(BuiltinError.RefErrLoc)),
    ("__RangeErrLoc", Value(BuiltinError.RangeErrLoc)),
    ("__TypeErrLoc", Value(BuiltinError.TypeErrLoc)),
    ("__URIErrLoc", Value(BuiltinError.URIErrLoc)),
    ("__RefErrProtoLoc", Value(BuiltinError.RefErrProtoLoc)),
    ("__RangeErrProtoLoc", Value(BuiltinError.RangeErrProtoLoc)),
    ("__TypeErrProtoLoc", Value(BuiltinError.TypeErrProtoLoc)),
    ("__URIErrProtoLoc", Value(BuiltinError.URIErrProtoLoc)),
    ("__ErrProtoLoc", Value(BuiltinError.ErrProtoLoc))
  )

  /** Library mode.
   *
   */
  var libMode = false
  def setLibMode(flag: Boolean) = libMode = flag
  val libModeProp = HashMap[String, Value](("<>TopVal<>", LibModeValueTop))

  /**
   * Assert flag.
   * If turned on, the program apply the assert semantics while analyzing JavaScript code.
   */
  var assertMode = true
  def setAssertMode(flag: Boolean) = assertMode = flag

  /**
   * PreAnalysis flag.
   */
  var preAnalysis = false
  def setPreAnalysisMode(flag: Boolean) = preAnalysis = flag

  /**
   * Context-sensitivity mode
   */
  val Context_Insensitive = 0
  val Context_OneCallsite = 1
  val Context_OneObject = 2
  val Context_OneObjectTAJS = 3
  val Context_OneCallsiteAndObject = 4
  val Context_OneCallsiteOrObject = 5
  val Context_KCallsite = 6
  val Context_KCallsiteAndObject = 7
  val Context_CallsiteSet = 8
  var contextSensitivityMode = Context_OneCallsite
  def setContextSensitivityMode(mode: Int) = contextSensitivityMode = mode

  /**
   * Context-sensitivity depth
   */
  var contextSensitivityDepth = 2
  def setContextSensitivityDepth(depth: Int) = contextSensitivityDepth = depth

  /**
   * Context-sensitivity flag for pre-analysis.
   * This flag turns on context-sensitivity for PureLocal object during pre-analysis.
   * The same context-sensitivity as main analysis is used for pre-analysis.
   * For TAJS-style context-sensitivity, this flag has no effect as its precision is
   * not comparable between pre and main analysis.
   * (Equal or strictly less precise context-sensitivity must be used for pre-analysis.)
   */
  var preContextSensitiveMode = false
  def setPreContextSensitiveMode(flag: Boolean) = preContextSensitiveMode = flag

  /**
   * Unsound flag.
   */
  var unsoundMode = false
  def setUnsoundMode(flag: Boolean) = unsoundMode = flag

  /**
   * Debug flag for internal checking and statistics.
   */
  val DEBUG = true

  var compare = false
  def setCompareMode(flag: Boolean) = compare = flag
  def setPreTyping(state: State) = preTyping = state
  var preTyping = StateBot
  var preDebug = false
  def setPreDebug(flag: Boolean) = preDebug = flag

  /**
   * DOM mode flag
   */
  var domMode = false
  def setDomMode = domMode = true

  /**
   * Tizen mode flag
   */
  var tizenMode = false
  def setTizenMode = tizenMode = true

  /**
   * jQuery mode flag
   */
  var jqMode = false
  def setJQueryMode = jqMode = true

  /**
   * temporary DOM property update mode flag
   */
  var domPropMode = false
  def setDOMPropMode = domPropMode = true

  /**
   * WIDL mode flag
   */
  var widlMode = false
  def setWIDLMode = widlMode = true

  /**
   * compare mode flag for html pre-analysis test
   */
  var compareMode = false
  def setCompareMode = compareMode = true

  /**
   * Loop unrolling count
   */
  var defaultUnrollingCount = 0
  def setDefaultUnrollingCount(unrollingCount: Int) = defaultUnrollingCount = unrollingCount
  var defaultForinUnrollingCount = 0
  def setDefaultForinUnrollingCount(unrollingCount: Int) = defaultForinUnrollingCount = unrollingCount

  /**
   * Console debugger mode
   */
  var debugger = false
  def setDebugger(b: Boolean) = debugger = b
}


text:
class RenderingQueue
{
public:
	RenderingQueue();
	~RenderingQueue();
};

redpajama_set_name: RedPajamaGithub


text:
ShareDrop is HTML5 clone of Apple [AirDrop](http://support.apple.com/kb/ht4783) service. It allows you to transfer files directly between devices, without having to upload them to any server first. It uses [WebRTC](http://www.webrtc.org) for secure peer-to-peer file transfer and [Firebase](https://www.firebase.com) for presence management and WebRTC signaling.

ShareDrop allows you to send files to other devices in the same local network (i.e. devices with the same public IP address) without any configuration - simply open https://www.sharedrop.io on all devices and they will see each other. It also allows you to send files between networks - just click + button in the top right corner of the page to create a room with unique URL and share this URL with other people you want to send a file to. Once they open this page in a browser on their devices, you'll see each other's avatars.

The main difference between ShareDrop and AirDrop is that ShareDrop requires Internet connection to discover other devices, while AirDrop doesn't need one - it creates ad-hoc wireless network between them. On the other hand, ShareDrop allows you to share files between mobile (Android) and desktop devices and between networks as well.

### Supported browsers
* Chrome (desktop and Android) 33+
* Opera (desktop and Android) 20+
* Firefox (desktop and Android) 28+ (though we suggest using Chrome or Opera for transferring larger files)

### How to set it up for local development
1. Setup Firebase:
    1. [Sign up](https://www.firebase.com) for a Firebase account and create a database.
    2. Go to "Security Rules" tab, click "Load Rules" button and select `firebase_rules.json` file.
    3. Take note of your database URL and its secret, which can be found in "Secrets" tab.
2. Run `npm -g install grunt-cli` to install Grunt.
3. Run `npm install` to install NodeJS dependencies.
4. Run `bundle install` to install Ruby dependencies.
5. Run `cp .env{.sample,}` to create `.env` file. This file will be used by Grunt to set environemnt variables when running the app locally. You only need `NEW_RELIC_*` variables in production.
6. Run `grunt serve` to start the app.
7. Run `grunt build` to build production version of the app to `dist` directory.

### Deployment
When deploying to Heroku, use [multi buildpack](https://github.com/ddollar/heroku-buildpack-multi.git).

For new apps:

`heroku create myapp --buildpack https://github.com/ddollar/heroku-buildpack-multi.git`

For existing apps:

`heroku config:set BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git`


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <TITLE>
        EncoderCache (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.protocol.http.util.EncoderCache class">

    <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

        org.apache.jmeter.protocol.http.util

    Class EncoderCache

java.lang.Object
  org.apache.jmeter.protocol.http.util.EncoderCache

public class EncoderCache

extends Object

            Field Summary

            static String
        URL_ARGUMENT_ENCODING

                      The encoding which should be usd for URLs,
            according to HTTP specification

            Constructor Summary

        EncoderCache(int cacheSize)

            Method Summary

             String
        getEncoded(String k)

                      Get the specified value URL encoded using UTF-8
            encoding

             String
        getEncoded(String k,
            String contentEncoding)

                      Get the specified value URL encoded using the
            specified encoding

        Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

            Field Detail

    URL_ARGUMENT_ENCODING

public static final String URL_ARGUMENT_ENCODING

The encoding which should be usd for URLs, according to HTTP specification

See Also:

                Constant
                    Field Values

            Constructor Detail

    EncoderCache

public EncoderCache(int cacheSize)

            Method Detail

    getEncoded

public String getEncoded(String k)

Get the specified value URL encoded using UTF-8 encoding

Parameters:

k - the value to encode

Returns:

the value URL encoded using UTF-8

    getEncoded

public String getEncoded(String k,
                         String contentEncoding)
                  throws UnsupportedEncodingException

Get the specified value URL encoded using the specified encoding

Parameters:

k - the value to encode

contentEncoding - the encoding to use when URL encoding

Returns:

the value URL encoded using the specified encoding

Throws:

UnsupportedEncodingException - if the
                specified encoding is not supported

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

Copyright © 1998-2009 Apache Software Foundation. All Rights Reserved.


text:
package example.nordicid.com.nursampleandroid;

import com.nordicid.nurapi.*;
import android.os.Handler;
import android.os.Looper;

public class TraceTagController {

	private NurApi mApi;
	private TracedTagInfo mTracedTagInfo = new TracedTagInfo();
	private TraceTagListener mTraceListener;
	private TraceAntennaSelector mTraceAntSelector = new TraceAntennaSelector();

	private long mUpdateInterVal = 100;

	private Handler mHandler;

	private NurApiListener mThisClassListener = new NurApiListener() {
		@Override
		public void traceTagEvent(NurEventTraceTag event) {
			handleTraceTag(event);
		}

		@Override public void IOChangeEvent(NurEventIOChange event) {
			if (mTraceListener != null) {
				mTraceListener.IOChangeEvent(event);
			}
		}

		@Override
		public void bootEvent(String arg0) { }

		@Override
		public void clientConnectedEvent(NurEventClientInfo arg0) { }

		@Override
		public void clientDisconnectedEvent(NurEventClientInfo arg0) { }

		@Override
		public void deviceSearchEvent(NurEventDeviceInfo arg0) { }

		@Override
		public void connectedEvent() {
			if (mTraceListener != null) {
				mTraceListener.readerConnected();
			}
		}

		@Override
		public void disconnectedEvent() {
			System.out.println("Trace controller: the reader is disconnected.");

			try {
				mApi.stopTraceTag();
			} catch (Exception err) {
				err.printStackTrace();
			}

			if (mTraceListener != null) {
				mTraceListener.readerDisconnected();
			}
		}

		@Override
		public void frequencyHopEvent(NurEventFrequencyHop arg0) { }
		@Override
		public void inventoryExtendedStreamEvent(NurEventInventory event) { }
		@Override
		public void inventoryStreamEvent(NurEventInventory event) { }
		@Override
		public void nxpEasAlarmEvent(NurEventNxpAlarm arg0) { }
		@Override
		public void programmingProgressEvent(NurEventProgrammingProgress arg0) { }
		@Override
		public void triggeredReadEvent(NurEventTriggeredRead arg0) { }
		@Override
		public void logEvent(int arg0, String arg1) { }
		@Override
		public void debugMessageEvent(String arg0) { }
		@Override
		public void epcEnumEvent(NurEventEpcEnum event) { }
		@Override
		public void autotuneEvent(NurEventAutotune event) { }
		@Override
		public void tagTrackingScanEvent(NurEventTagTrackingData event) { }
		@Override
		public void tagTrackingChangeEvent(NurEventTagTrackingChange event) { }
	};

	public TraceTagController(NurApi na) {
		mHandler = new Handler(Looper.getMainLooper());
		mApi = na;
	}

	public NurApiListener getNurApiListener() {
		return mThisClassListener;
	}

	private void handleTraceTag(NurEventTraceTag event)
	{
		int signalStrength = 0;
		try {
			signalStrength = mTraceAntSelector.adjust(event.scaledRssi);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mTracedTagInfo.scaledRssi = signalStrength;

		mHandler.removeCallbacksAndMessages(null);
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mTraceListener.traceTagEvent(mTracedTagInfo);
			}
		});
	}

	private NurEventTraceTag doTracePass()
    {
		NurEventTraceTag ret = new NurEventTraceTag();
		ret.antennaId = 0;
    	ret.rssi = -127;
    	ret.scaledRssi = 0;

    	//Log.d("TRACE", "doTracePass() +");

        for (int i = 0; i < 3 && mTraceRunning; i++)
        {
            try
            {
            	NurRespReadData data = mApi.traceTagByEpc(mTracedTagInfo.epc, mTracedTagInfo.epc.length, NurApi.TRACETAG_NO_EPC);
            	ret.antennaId = data.antennaID;
            	ret.rssi = data.rssi;
            	ret.scaledRssi = data.scaledRssi;
            	break;
            }
            catch (Exception ex)
            {
                // retry
            }
        }
    	//Log.d("TRACE", "doTracePass() - " + ret.scaledRssi);
        return ret;
    }

	boolean mTraceRunning = false;

	Runnable mBeeperThreadRunnable = new Runnable() {
		@Override
		public void run()
		{
			while (mTraceRunning)
			{
				int avgStrength = mTraceAntSelector.getSignalStrength();
				int sleepTime = 1000;
				int beepDuration = Beeper.BEEP_300MS;

				if (avgStrength > 70)
				{
					sleepTime = 150 - avgStrength;
					beepDuration = Beeper.BEEP_40MS;
				}
				else if (avgStrength > 0)
				{
					sleepTime = 200 - avgStrength;
					beepDuration = Beeper.BEEP_100MS;
				}

				Beeper.beep(beepDuration);

				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};
	Thread mBeeperThread;

	Runnable mTraceThreadRunnable = new Runnable() {
		@Override
		public void run() {

			try {
				mTraceAntSelector.begin(mApi);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			while (mTraceRunning)
			{
				long t1 = System.currentTimeMillis();
				NurEventTraceTag ev = doTracePass();
				long t2 = System.currentTimeMillis();
				if (mTraceRunning) {
					handleTraceTag(ev);

					try {
						int sleepTime = (int)(mUpdateInterVal - (t2-t1));
						if (sleepTime < 10)
							sleepTime = 10;
						Thread.sleep(sleepTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

			try {
				mTraceAntSelector.stop();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	Thread mTraceThread;

	public boolean setTagTrace(String epc)
	{
		try {
			byte []epcData = NurApi.hexStringToByteArray(epc);
			mTracedTagInfo.epc = epcData;
			return true;
		} catch (Exception e) { }
		return false;
	}

	public boolean startTagTrace(String epc)
	{
		if (isTracingTag())
			return true;

		if (mApi.isConnected() && epc.length() > 0) {
			try {
				setTagTrace(epc);

				mTraceRunning = true;
				mTraceThread = new Thread(mTraceThreadRunnable);
				mTraceThread.start();

				mBeeperThread = new Thread(mBeeperThreadRunnable);
				mBeeperThread.setPriority(Thread.MIN_PRIORITY);
				mBeeperThread.start();
			} catch (Exception err) {
				err.printStackTrace();
				return false;
			}

			return true;
		}

		return false;
	}

	public boolean stopTagTrace() {
		if (!isTracingTag())
			return true;

		try {
			mTraceRunning = false;
			if (mTraceThread != null)
			{
				mTraceThread.join(5000);
				mTraceThread = null;
			}
			if (mBeeperThread != null)
			{
				mBeeperThread.join(5000);
				mBeeperThread = null;
			}

		} catch (Exception err) {
			err.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean isTracingTag() {
		return mTraceRunning;
	}

	public void setUpdateInterval(int interval) {
		mUpdateInterVal = interval;
	}

	public void setListener(TraceTagListener l) {
		mTraceListener = l;
	}

	public interface TraceTagListener {
		public void traceTagEvent(TracedTagInfo data);
		public void readerDisconnected();
		public void readerConnected();
		public void IOChangeEvent(NurEventIOChange event);
	}

	public class TracedTagInfo {
		public int scaledRssi;
		public byte[] epc;
	}
}


text:
import * as LogManager from 'aurelia-logging';
const logger = LogManager.getLogger('sails');

export class CSRFInterceptor {

  /**
   * @constructor
   * @param url URL of the sails CSRF getter
   * @param {SailsSocketClient} client Client for getting CSRF from server
   * @param token Optional token - use when you have prefetched token, e.g. rendered in HTML
   */
  constructor(url, client, token) {
    this.url = url;
    this.client = client;
    this.token = token;
  }

  /**
   * Request message interceptor
   *
   * @param message
   * @returns {SocketRequestMessage}
   */
  request(message) {
    if (message.method === 'get' || message.url === this.url) {
      return message;
    }

    if (this.token) {
      this.setCsrfTokenHeader(message);
      return message;
    }

    return new Promise((resolve, reject) => {
      let promise;
      if (this._fetching) {
        promise = this._fetching;
      } else {
        promise = this._fetching = this.client.get(this.url);
      }
      promise.then(response => {
        this.token = response.content._csrf;
        this.setCsrfTokenHeader(message);
        resolve(message);
      }).catch(reject);
    });
  }

  setCsrfTokenHeader(message) {
    message.headers.add('X-Csrf-Token', this.token);
    return message;
  }

}

export class LoggerInterceptor {

  request(message) {
    logger.debug('Sending message to sails', message);
    return message;
  }

  response(response) {
    logger.debug('Receiving response from sails', response);
    return response;
  }

  responseError(response) {
    logger.error('There was an error during sails request', response);
    throw response;
  }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CWSStart.Web.Models
{
    public class ContactFormViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [MinLength(20, ErrorMessage = "Your message is less than 20 characters. Please provide more details to your message.")]
        public string Message { get; set; }

    }
}


text:
/**
 * Class which handles individual tabs
 */
var Tab = Backbone.View.extend({
    tagName: 'li',

    events: {
        'click a': 'select',
        'mousedown a': 'remove',
        'click .close_tab': 'remove'
    },

    template: function() {
        // Create tab
        return _.template("<a class='saikutab' href='#<%= id %>'><%= caption %>" +
                "Close tab")
            ({
                id: this.id,
                caption: this.caption
            });
    },

    /**
     * Assign a unique ID and assign a Backbone view
     * to handle the tab's contents
     * @param args
     */
    initialize: function(args) {
        _.extend(this, Backbone.Events);
        _.extend(this, args);
        this.content.tab = this;
        this.caption = this.content.caption();
        this.id = _.uniqueId('tab_');
        this.close = args.close;
    },

    /**
     * Render the tab and its contents
     * @returns tab
     */
    render: function() {
        var self = this;
        // Render the content
        this.content.render();

        // Generate the element
        $(this.el).html(this.template());
        if(this.close==false){
            $(this.el).find('.close_tab').hide();
            $(this.el).css('padding-right','10px')
        }
        var menuitems = {
            "new": {name: "New", i18n: true },
            "duplicate": { name: "Duplicate", i18n: true},
            "closeothers": {name: "Close Others", i18n: true },
            "closethis": {name: "Close This", i18n: true }
        };
        $.each(menuitems, function(key, item){
            recursive_menu_translate(item, Saiku.i18n.po_file);
        });

        $.contextMenu('destroy', '.saikutab');
        $.contextMenu({
                selector: '.saikutab',
                callback: function(key, options) {
                    var selected = options.$trigger.attr('href').replace('#','');
                    var tab = Saiku.tabs.find(selected);
                 	  if (key == "closethis") {
                        tab.remove();
                        self.select();
                        return;
                    } else if (key == "closeothers") {
                        tab.select();
                        Saiku.tabs.close_others(tab);
                    } else if (key == "duplicate") {
                        Saiku.tabs.duplicate(tab);
                    } else if (key == "new") {
                        Saiku.tabs.new_tab();
                    }
                    //self.workspace.chart.exportChart(key);
                },
                items: menuitems
            });

        return this;
    },

    set_caption: function(caption) {
        $(this.el).find('.saikutab').html(caption);
    },

    /**
     * Destroy any data associated with this tab and ensure proper
     * garbage collection to avoid memory leaks
     */
    destroy: function() {
        // Delete data
        if (this.content && this.content.query) {
            this.content.query.destroy();
        }
    },

    /**
     * Select a tab
     * @param el
     */
    select: function() {
        var self = this;
        // Deselect all tabs
        this.parent.select(this);

        // Select the selected tab
        $(this.el).addClass('selected');

        // Trigger select event
        this.trigger('tab:select');
        return false;
    },

    /**
     * Remove a tab
     * @returns {Boolean}
     */
    remove: function(event) {
        if (!event || event.which === 2 || $(event.target).hasClass('close_tab')) {
            // Remote the tab object from the container
            this.parent.remove(this);

            try {
                // Remove the tab element
                $(this.el).remove();

                // Remove the tab
                this.destroy();
            } catch (e) {
                Log.log(JSON.stringify({
                    Message: "Tab could not be removed",
                    Tab: JSON.stringify(this)
                }));
            }
        }

        return false;
    }
});

/**
 * Class which controls tab pager
 */
var TabPager = Backbone.View.extend({
    className: 'pager_contents',
    events: {
        'click a': 'select'
    },

    initialize: function(args) {
        this.tabset = args.tabset;
        $(this.el).hide().appendTo('body');

        // Hide when focus is lost
        $(window).click(function(event) {
            if (! $(event.target).hasClass('pager_contents')) {
                $('.pager_contents').hide();
            }
        });
    },

    render: function() {
        var pager = "";
        for (var i = 0, len = this.tabset._tabs.length; i < len; i++) {
            pager += "" +
                this.tabset._tabs[i].caption + "
";
        }
        $(this.el).html(pager);
        $(this.el).find(".i18n").i18n(Saiku.i18n.po_file);
    },

    select: function(event) {
        var index = $(event.target).attr('href').replace('#', '');
        this.tabset._tabs[index].select();
        $(this.el).hide();
        event.preventDefault();
        return false;
    }
});

/**
 * Class which controls the tab collection
 */
var TabSet = Backbone.View.extend({
    className: 'tabs',
    queryCount: 0,

    events: {
        'click a.pager': 'togglePager' ,
        'click a.new' : 'new_tab'
    },

    _tabs: [],

    /**
     * Render the tab containers
     * @returns tab_container
     */
    render: function() {
        $(this.el).html('

+

')
            .appendTo($('#header'));
        this.content = $('
').appendTo($('body'));
        this.pager = new TabPager({ tabset: this });
        return this;
    },

    /**
     * Add a tab to the collection
     * @param tab
     */
    add: function(content, close) {
        // Add it to the set
        this.queryCount++;

        var tab = new Tab({ content: content, close: close});
        this._tabs.push(tab);
        tab.parent = this;

        // Render it in the background, then select it
        tab.render().select();
        $(tab.el).insertBefore($(this.el).find('ul li.newtab'));

        // Trigger add event on session
        Saiku.session.trigger('tab:add', { tab: tab });
        this.pager.render();

        return tab;
    },

    find: function(id) {
        for (var i = 0, len = this._tabs.length; i < len; i++) {
            if (this._tabs[i].id == id) {
                return this._tabs[i];
            }
        }
        return null;
    },

    /**
     * Select a tab, and move its contents to the tab panel
     * @param tab
     */
    select: function(tab) {
        // Clear selections
        $(this.el).find('li').removeClass('selected');

        // Replace the contents of the tab panel with the new content

            this.content.children().detach();
            this.content.append($(tab.content.el));

    },

    /**
     * Remove a tab from the collection
     * @param tab
     */
    remove: function(tab) {
        // Add another tab if the last one has been deleted
        if (this._tabs.length == 1) {
            //this.add(new Workspace());

        }

        for (var i = 0, len = this._tabs.length; i < len; i++) {
            if (this._tabs[i] == tab) {
                // Remove the element
                this._tabs.splice(i, 1);

                Saiku.session.trigger('tab:remove', { tab: tab });
                this.pager.render();
                // Select the previous, or first tab
                var next = this._tabs[i] ? i : (this._tabs.length - 1);
                this._tabs[next].select();
            }
        }

        return true;
    },

    close_others: function(tab) {
        var index = _.indexOf(this._tabs, tab);
        this._tabs[index].select();

        // Remove tabs placed before and after selected tab
        var i = 0;
        while(1 < this._tabs.length){
            if (this._tabs[i] != tab)
                this._tabs[i].remove();
            else
                i++;
        }
    },

    close_all: function() {
        for (var i = 0, len = this._tabs.length; i < len; i++) {
            var otherTab = this._tabs[i];
            otherTab.remove();
        }
    },

    togglePager: function() {
        $(this.pager.el).toggle();
        return false;
    },

    new_tab: function() {
        this.add(new Workspace());
        var next = this._tabs.length - 1;
        this._tabs[next].select();
        return false;
    },

    duplicate: function(tab) {
        // Block UI to prevent other events
        Saiku.ui.block("Duplicating tab...");

        // Check for empty query
        if(tab.content.query){
            // For versions using Query2Resource
            this.add(new Workspace({
                query : new Query({
                    json : JSON.stringify(tab.content.query.model)
                }, Settings.PARAMS),
                viewState : tab.content.viewState
            }));

        } else {
            this.add(new Workspace());
        }

        // Unblock UI and restore functionality
        Saiku.ui.unblock();
        return false;
    }
});


text:
package ru.bildovich;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * bildovich
 * 01.03.2017.
 */
public class TeacherTest {

    /**
     * The teacherTest field.
     */
    private Teacher teacherTest;

    /**
     * Information method to test.
     */
    @Before
    public void infoForTest() {
        teacherTest = new Teacher("Училкина");
    }

    /**
     * Test method add pupil.
     */
    @Test
    public void whenAddNewPatient() {
        String checked = "Иванов";
        teacherTest.addPupil(checked);
        String result = teacherTest.getPupils().get(teacherTest.getPupils().size() - 1).getName();
        assertThat(result, is(checked));
    }

    /**
     * Test method delete pupil.
     */
    @Test
    public void whenDelPatient(){
        String checked = "Иванов";
        teacherTest.addPupil(checked);
        teacherTest.addPupil("Петров");
        teacherTest.deletPupils(checked);
        assertThat(1, is(teacherTest.getPupils().size()));
    }

    /**
     * Test method teach.
     */
    @Test
    public void teachTest() {
        boolean result = teacherTest.teach(new Pupil("Ivanov"));
        assertThat(true, is(result));

    }
}


text:
namespace gl {
class GLImage;
}

namespace content {

class CONTENT_EXPORT GpuMemoryBufferFactoryIOSurface
    : public GpuMemoryBufferFactory,
      public gpu::ImageFactory {
 public:
  GpuMemoryBufferFactoryIOSurface();
  ~GpuMemoryBufferFactoryIOSurface() override;

  static bool IsGpuMemoryBufferConfigurationSupported(gfx::BufferFormat format,
                                                      gfx::BufferUsage usage);

  // Overridden from GpuMemoryBufferFactory:
  gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer(
      gfx::GpuMemoryBufferId id,
      const gfx::Size& size,
      gfx::BufferFormat format,
      gfx::BufferUsage usage,
      int client_id,
      gfx::PluginWindowHandle surface_handle) override;
  gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferFromHandle(
      const gfx::GpuMemoryBufferHandle& handle,
      gfx::GpuMemoryBufferId id,
      const gfx::Size& size,
      gfx::BufferFormat format,
      int client_id) override;
  void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                              int client_id) override;
  gpu::ImageFactory* AsImageFactory() override;

  // Overridden from gpu::ImageFactory:
  scoped_refptr<gl::GLImage> CreateImageForGpuMemoryBuffer(
      const gfx::GpuMemoryBufferHandle& handle,
      const gfx::Size& size,
      gfx::BufferFormat format,
      unsigned internalformat,
      int client_id) override;

 private:
  typedef std::pair<gfx::IOSurfaceId, int> IOSurfaceMapKey;
  typedef base::hash_map<IOSurfaceMapKey, base::ScopedCFTypeRef<IOSurfaceRef>>
      IOSurfaceMap;
  // TOOD(reveman): Remove |io_surfaces_| and allow IOSurface backed GMBs to be
  // used with any GPU process by passing a mach_port to CreateImageCHROMIUM.
  IOSurfaceMap io_surfaces_;
  base::Lock io_surfaces_lock_;

  DISALLOW_COPY_AND_ASSIGN(GpuMemoryBufferFactoryIOSurface);
};

}  // namespace content

#endif  // CONTENT_COMMON_GPU_GPU_MEMORY_BUFFER_FACTORY_IO_SURFACE_H_


text:
"""This module contains regression tests for output plugins API handlers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from absl import app

from grr_response_core.lib import utils
from grr_response_server import instant_output_plugin
from grr_response_server import output_plugin
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_plugins import output_plugin as output_plugin_plugin
from grr_response_server.output_plugins import csv_plugin
from grr_response_server.output_plugins import email_plugin
from grr.test_lib import test_lib

class ApiListOutputPluginDescriptorsHandlerTest(
    api_regression_test_lib.ApiRegressionTest):
  """Regression test for ApiOutputPluginsListHandler."""

  api_method = "ListOutputPluginDescriptors"
  handler = output_plugin_plugin.ApiListOutputPluginDescriptorsHandler

  def Run(self):
    with utils.MultiStubber((output_plugin.OutputPlugin, "classes", {
        "EmailOutputPlugin": email_plugin.EmailOutputPlugin,
    }), (instant_output_plugin.InstantOutputPlugin, "classes", {
        "CSVInstantOutputPlugin": csv_plugin.CSVInstantOutputPlugin
    })):
      self.Check("ListOutputPluginDescriptors")

def main(argv):
  test_lib.main(argv)

if __name__ == "__main__":
  app.run(main)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Core.Data.Game.Characters;
using Core.Data.Game.World;

namespace Networking
{
    public class Connection : EventArgs
    {
        public static Connection None = new Connection(null);

        public TcpClient Socket = null;
        public NetworkStream DataStream = null;

        protected List<string> InboundMessages = new List<string>();
        protected List<string> OutboundMessages = new List<string>();

        public int LanguageID = 0;

        public object ProtocolTag = null;

        public bool SentHeader = true;

        public int UserID = -1;
        public List<string> AccessFlags = new List<string>();

        public PlayerCharacter ActiveCharacter = null;

        public ZoneInstance CurrentZoneProcessor = null;

        protected readonly bool DebugEcho = false;

        public object MessageProcessorTag { get; protected set; }

        protected Dictionary<string, object> MessageProcessorTags = new Dictionary<string, object>();

        public IMessageProcessor MessageProcessor { get; protected set; }

        public event EventHandler<Connection> Disconnected = null;

        public Connection(TcpClient soc)
        {
            MessageProcessorTag = null;
            MessageProcessor = null;
            Socket = soc;
            if (soc != null)
                DataStream = Socket.GetStream();
        }

        public void SetMessageProcessor(IMessageProcessor processor)
        {
            if (MessageProcessor != null)
                MessageProcessor.ProcessorDetatch(this);

            MessageProcessor = processor;
            if (MessageProcessor != null)
                MessageProcessor.ProcessorAttach(this);
        }

        public void SetMessageProcessorTag(string name, object tag)
        {
            if (MessageProcessorTags.ContainsKey(name))
                MessageProcessorTags[name] = tag;
            else
                MessageProcessorTags.Add(name, tag);

            MessageProcessorTag = tag;
        }

        public void SetMessageProcessorTag(string name)
        {
            if (MessageProcessorTags.ContainsKey(name))
                MessageProcessorTag = MessageProcessorTags[name];
            else
                MessageProcessorTag = null;
        }

        public object GetMesssageProcessorTag(string name)
        {
            if (MessageProcessorTags.ContainsKey(name))
                return MessageProcessorTags[name];
            else
                return null;
        }

        public T GetMesssageProcessorTag<T>() where T: class
        {
            return MessageProcessorTag as T;
        }

        public void PushInboundMessage(string msg)
        {
            if (msg == null || msg == string.Empty)
                return;

            lock (InboundMessages)
                InboundMessages.Add(msg);

            if (MessageProcessor != null)
                MessageProcessor.ProcessInbound(msg, this);

            if (DebugEcho)
                SendOutboundMessage(msg);
        }

        public string PopInboundMessage()
        {
            lock (InboundMessages)
            {
                if (InboundMessages.Count == 0)
                    return string.Empty;

                string msg = InboundMessages[0];
                InboundMessages.RemoveAt(0);
                return msg;
            }
        }

        public bool HasPendingInbound()
        {
            lock (InboundMessages)
                return InboundMessages.Count > 0;
        }

        public void SendOutboundMessage(string msg)
        {
            if (msg == null || msg == string.Empty)
                return;

            lock (OutboundMessages)
                OutboundMessages.Add(msg);
        }

        public string PopOutboundMessage()
        {
            lock(OutboundMessages)
            {
                if (OutboundMessages.Count == 0)
                    return string.Empty;

                string msg = OutboundMessages[0];
                OutboundMessages.RemoveAt(0);
                return msg;
            }
        }

        public string[] PopNOutboundMessages(int n)
        {
            string[] a = new string[0];

            lock (OutboundMessages)
            {
                if (OutboundMessages.Count == 0)
                    return a;

                if (n > OutboundMessages.Count)
                    n = OutboundMessages.Count;

                if (n == OutboundMessages.Count)
                {
                    a = OutboundMessages.ToArray();
                    OutboundMessages.Clear();
                }
                else
                {
                    a = OutboundMessages.GetRange(0, n).ToArray();
                    OutboundMessages.RemoveRange(0, n);
                }
            }
            return a;
        }

        public bool HasOutboundData()
        {
            lock (OutboundMessages)
                return OutboundMessages.Count > 0;
        }

        public virtual void OnDisconnect()
        {
            Disconnected?.Invoke(this, this);
        }

        public virtual void Disconnect()
        {
            Socket.Close();
            Socket.Dispose();
            Socket = null;
        }

        public bool HasAccessFlag(string flag)
        {
            lock (AccessFlags)
                return AccessFlags.Find(x => x.ToLower() == flag.ToLower()) != string.Empty;
        }
    }
}


text:
//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2011/05/15
// Author: Mike Ovsiannikov
//
// Copyright 2011-2012 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// "Atomic" variables of different sizes (well up to 64 bits on 64 bit
// platforms).
//
//----------------------------------------------------------------------------

#ifndef KFS_ATOMIC_H
#define KFS_ATOMIC_H

namespace KFS
{
#if ! defined(_KFS_ATOMIC_USE_MUTEX) && (\
        ! defined(__GNUC__) || (__GNUC__ < 4 || \
        (__GNUC__ == 4 && (__GNUC_MINOR__ < 1 || \
            (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ < 2)))))
#   define _KFS_ATOMIC_USE_MUTEX
#endif

#ifdef _KFS_ATOMIC_USE_MUTEX

namespace atomicmpl
{
void AtomicLock();
void AtomicUnlock();
}

template<typename T> T SyncAddAndFetch(volatile T& val, T inc)
{
    atomicmpl::AtomicLock();
    val += inc;
    const T ret = val;
    atomicmpl::AtomicUnlock();
    return ret;
}

#else

template<typename T> T SyncAddAndFetch(volatile T& val, T inc)
{
    return __sync_add_and_fetch(&val, inc);
}

#endif /* _KFS_ATOMIC_USE_MUTEX */
}

#endif /* KFS_ATOMIC_H */


text:
package android.hardware;

/**
 *

 * This class represents a {@link android.hardware.Sensor Sensor} event and
 * holds informations such as the sensor's type, the time-stamp, accuracy and of
 * course the sensor's {@link SensorEvent#values data}.
 *

 *
 *

 * Definition of the coordinate system used by the SensorEvent API.
 *

 *
 *

 * The coordinate-system is defined relative to the screen of the phone in its
 * default orientation. The axes are not swapped when the device's screen
 * orientation changes.
 *

 *
 *

 * The X axis is horizontal and points to the right, the Y axis is vertical and
 * points up and the Z axis points towards the outside of the front face of the
 * screen. In this system, coordinates behind the screen have negative Z values.
 *

 *
 *

 *
 *

 *
 *

 * Note: This coordinate system is different from the one used in the
 * Android 2D APIs where the origin is in the top-left corner.
 *

 *
 * @see SensorManager
 * @see SensorEvent
 * @see Sensor
 *
 */

public class SensorEvent {
    /**
     *

     * The length and contents of the {@link #values values} array depends on
     * which {@link android.hardware.Sensor sensor} type is being monitored (see
     * also {@link SensorEvent} for a definition of the coordinate system used).
     *

     *
     *
{@link android.hardware.Sensor#TYPE_ACCELEROMETER
     * Sensor.TYPE_ACCELEROMETER}:
 All values are in SI units (m/s^2)
     *
     *

     *

     * values[0]: Acceleration minus Gx on the x-axis
     *

     *

     * values[1]: Acceleration minus Gy on the y-axis
     *

     *

     * values[2]: Acceleration minus Gz on the z-axis
     *

     *

     *
     *

     * A sensor of this type measures the acceleration applied to the device
     * (Ad). Conceptually, it does so by measuring forces applied to the
     * sensor itself (Fs) using the relation:
     *

     *
     * Ad = - ∑Fs / mass
     *
     *

     * In particular, the force of gravity is always influencing the measured
     * acceleration:
     *

     *
     * Ad = -g - ∑F / mass
     *
     *

     * For this reason, when the device is sitting on a table (and obviously not
     * accelerating), the accelerometer reads a magnitude of g = 9.81
     * m/s^2
     *

     *
     *

     * Similarly, when the device is in free-fall and therefore dangerously
     * accelerating towards to ground at 9.81 m/s^2, its accelerometer reads a
     * magnitude of 0 m/s^2.
     *

     *
     *

     * It should be apparent that in order to measure the real acceleration of
     * the device, the contribution of the force of gravity must be eliminated.
     * This can be achieved by applying a high-pass filter. Conversely, a
     * low-pass filter can be used to isolate the force of gravity.
     *

     *
     *

     *
     *     public void onSensorChanged(SensorEvent event)
     *     {
     *          // alpha is calculated as t / (t + dT)
     *          // with t, the low-pass filter's time-constant
     *          // and dT, the event delivery rate
     *
     *          final float alpha = 0.8;
     *
     *          gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
     *          gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
     *          gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
     *
     *          linear_acceleration[0] = event.values[0] - gravity[0];
     *          linear_acceleration[1] = event.values[1] - gravity[1];
     *          linear_acceleration[2] = event.values[2] - gravity[2];
     *     }
     *

     *
     *

     * Examples:
     *

     *
When the device lies flat on a table and is pushed on its left side
     * toward the right, the x acceleration value is positive.

     *
     *
When the device lies flat on a table, the acceleration value is
     * +9.81, which correspond to the acceleration of the device (0 m/s^2) minus
     * the force of gravity (-9.81 m/s^2).

     *
     *
When the device lies flat on a table and is pushed toward the sky
     * with an acceleration of A m/s^2, the acceleration value is equal to
     * A+9.81 which correspond to the acceleration of the device (+A m/s^2)
     * minus the force of gravity (-9.81 m/s^2).

     *

     *
     *
     *
{@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD
     * Sensor.TYPE_MAGNETIC_FIELD}:

     * All values are in micro-Tesla (uT) and measure the ambient magnetic field
     * in the X, Y and Z axis.
     *
     *
{@link android.hardware.Sensor#TYPE_GYROSCOPE Sensor.TYPE_GYROSCOPE}:
     *
 All values are in radians/second and measure the rate of rotation
     * around the device's local X, Y and Z axis. The coordinate system is the
     * same as is used for the acceleration sensor. Rotation is positive in the
     * counter-clockwise direction. That is, an observer looking from some
     * positive location on the x, y or z axis at a device positioned on the
     * origin would report positive rotation if the device appeared to be
     * rotating counter clockwise. Note that this is the standard mathematical
     * definition of positive rotation and does not agree with the definition of
     * roll given earlier.
     *

     *

     * values[0]: Angular speed around the x-axis
     *

     *

     * values[1]: Angular speed around the y-axis
     *

     *

     * values[2]: Angular speed around the z-axis
     *

     *

     *

     * Typically the output of the gyroscope is integrated over time to
     * calculate a rotation describing the change of angles over the timestep,
     * for example:
     *

     *
     *

     *     private static final float NS2S = 1.0f / 1000000000.0f;
     *     private final float[] deltaRotationVector = new float[4]();
     *     private float timestamp;
     *
     *     public void onSensorChanged(SensorEvent event) {
     *          // This timestep's delta rotation to be multiplied by the current rotation
     *          // after computing it from the gyro sample data.
     *          if (timestamp != 0) {
     *              final float dT = (event.timestamp - timestamp) * NS2S;
     *              // Axis of the rotation sample, not normalized yet.
     *              float axisX = event.values[0];
     *              float axisY = event.values[1];
     *              float axisZ = event.values[2];
     *
     *              // Calculate the angular speed of the sample
     *              float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
     *
     *              // Normalize the rotation vector if it's big enough to get the axis
     *              if (omegaMagnitude > EPSILON) {
     *                  axisX /= omegaMagnitude;
     *                  axisY /= omegaMagnitude;
     *                  axisZ /= omegaMagnitude;
     *              }
     *
     *              // Integrate around this axis with the angular speed by the timestep
     *              // in order to get a delta rotation from this sample over the timestep
     *              // We will convert this axis-angle representation of the delta rotation
     *              // into a quaternion before turning it into the rotation matrix.
     *              float thetaOverTwo = omegaMagnitude * dT / 2.0f;
     *              float sinThetaOverTwo = sin(thetaOverTwo);
     *              float cosThetaOverTwo = cos(thetaOverTwo);
     *              deltaRotationVector[0] = sinThetaOverTwo * axisX;
     *              deltaRotationVector[1] = sinThetaOverTwo * axisY;
     *              deltaRotationVector[2] = sinThetaOverTwo * axisZ;
     *              deltaRotationVector[3] = cosThetaOverTwo;
     *          }
     *          timestamp = event.timestamp;
     *          float[] deltaRotationMatrix = new float[9];
     *          SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);
     *          // User code should concatenate the delta rotation we computed with the current rotation
     *          // in order to get the updated rotation.
     *          // rotationCurrent = rotationCurrent * deltaRotationMatrix;
     *     }
     *

     *

     * In practice, the gyroscope noise and offset will introduce some errors
     * which need to be compensated for. This is usually done using the
     * information from other sensors, but is beyond the scope of this document.
     *

     *
{@link android.hardware.Sensor#TYPE_LIGHT Sensor.TYPE_LIGHT}:

     *

     *

     * values[0]: Ambient light level in SI lux units
     *

     *
     *
{@link android.hardware.Sensor#TYPE_PRESSURE Sensor.TYPE_PRESSURE}:

     *

     *

     * values[0]: Atmospheric pressure in hPa (millibar)
     *

     *
     *
{@link android.hardware.Sensor#TYPE_PROXIMITY Sensor.TYPE_PROXIMITY}:
     *

     *
     *

     *

     * values[0]: Proximity sensor distance measured in centimeters
     *

     *
     *

     * Note: Some proximity sensors only support a binary near or
     * far measurement. In this case, the sensor should report its
     * {@link android.hardware.Sensor#getMaximumRange() maximum range} value in
     * the far state and a lesser value in the near state.
     *

     *
     *
{@link android.hardware.Sensor#TYPE_GRAVITY Sensor.TYPE_GRAVITY}:

     *
A three dimensional vector indicating the direction and magnitude of gravity.  Units
     *  are m/s^2. The coordinate system is the same as is used by the acceleration sensor.

     *
Note: When the device is at rest, the output of the gravity sensor should be identical
     *  to that of the accelerometer.

     *
     *
{@link android.hardware.Sensor#TYPE_LINEAR_ACCELERATION Sensor.TYPE_LINEAR_ACCELERATION}:

     *  A three dimensional vector indicating acceleration along each device axis, not including
     *  gravity.  All values have units of m/s^2.  The coordinate system is the same as is used by the
     *  acceleration sensor.
     *
The output of the accelerometer, gravity and  linear-acceleration sensors must obey the
     *  following relation:

     *

acceleration = gravity + linear-acceleration

     *
     *
{@link android.hardware.Sensor#TYPE_ROTATION_VECTOR Sensor.TYPE_ROTATION_VECTOR}:

     *
The rotation vector represents the orientation of the device as a combination of an angle
     *  and an axis, in which the device has rotated through an angle &#952 around an axis
     *  <x, y, z>.

     *
The three elements of the rotation vector are
     *  <x*sin(&#952/2), y*sin(&#952/2), z*sin(&#952/2)>, such that the magnitude of the rotation
     *  vector is equal to sin(&#952/2), and the direction of the rotation vector is equal to the
     *  direction of the axis of rotation.

     *
The three elements of the rotation vector are equal to
     *  the last three components of a unit quaternion
     *  <cos(&#952/2), x*sin(&#952/2), y*sin(&#952/2), z*sin(&#952/2)>.

     *
Elements of the rotation vector are unitless.
     *  The x,y, and z axis are defined in the same way as the acceleration
     *  sensor.

     *  The reference coordinate system is defined as a direct orthonormal basis,
     *  where:
     *

     *
     *

     *
X is defined as the vector product Y.Z (It is tangential to
     * the ground at the device's current location and roughly points East).

     *
Y is tangential to the ground at the device's current location and
     * points towards magnetic north.

     *
Z points towards the sky and is perpendicular to the ground.

     *

     *
     *

     *
     *

     *
     *

     *

     * values[0]: x*sin(&#952/2)
     *

     *

     * values[1]: y*sin(&#952/2)
     *

     *

     * values[2]: z*sin(&#952/2)
     *

     *

     * values[3]: cos(&#952/2) (optional: only if value.length = 4)
     *

     *

     *
     *
{@link android.hardware.Sensor#TYPE_ORIENTATION
     * Sensor.TYPE_ORIENTATION}:
 All values are angles in degrees.
     *
     *

     *

     * values[0]: Azimuth, angle between the magnetic north direction and the
     * y-axis, around the z-axis (0 to 359). 0=North, 90=East, 180=South,
     * 270=West
     *

     *
     *

     * values[1]: Pitch, rotation around x-axis (-180 to 180), with positive
     * values when the z-axis moves toward the y-axis.
     *

     *
     *

     * values[2]: Roll, rotation around y-axis (-90 to 90), with positive values
     * when the x-axis moves toward the z-axis.
     *

     *

     *
     *

     * Note: This definition is different from yaw, pitch and roll
     * used in aviation where the X axis is along the long side of the plane
     * (tail to nose).
     *

     *
     *

     * Note: This sensor type exists for legacy reasons, please use
     * {@link android.hardware.SensorManager#getRotationMatrix
     * getRotationMatrix()} in conjunction with
     * {@link android.hardware.SensorManager#remapCoordinateSystem
     * remapCoordinateSystem()} and
     * {@link android.hardware.SensorManager#getOrientation getOrientation()} to
     * compute these values instead.
     *

     *
     *

     * Important note: For historical reasons the roll angle is positive
     * in the clockwise direction (mathematically speaking, it should be
     * positive in the counter-clockwise direction).
     *

     *
     *
{@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY
     * Sensor.TYPE_RELATIVE_HUMIDITY}:

     *

     *

     * values[0]: Relative ambient air humidity in percent
     *

     *

     *

     * When relative ambient air humidity and ambient temperature are
     * measured, the dew point and absolute humidity can be calculated.
     *

     * Dew Point
     *

     * The dew point is the temperature to which a given parcel of air must be
     * cooled, at constant barometric pressure, for water vapor to condense
     * into water.
     *

     *

     *                    ln(RH/100%) + m·t/(Tn+t)
     * td(t,RH) = Tn · ------------------------------
     *                 m - [ln(RH/100%) + m·t/(Tn+t)]
     *

     *

     *
td

dew point temperature in °C

     *
t

actual temperature in °C

     *
RH

actual relative humidity in %

     *
m

17.62

     *
Tn

243.12 °C

     *

     *
for example:

     *

     * h = Math.log(rh / 100.0) + (17.62 * t) / (243.12 + t);
     * td = 243.12 * h / (17.62 - h);
     *

     * Absolute Humidity
     *

     * The absolute humidity is the mass of water vapor in a particular volume
     * of dry air. The unit is g/m3.
     *

     *

     *                    RH/100%·A·exp(m·t/(Tn+t))
     * dv(t,RH) = 216.7 · -------------------------
     *                           273.15 + t
     *

     *

     *
dv

absolute humidity in g/m3

     *
t

actual temperature in °C

     *
RH

actual relative humidity in %

     *
m

17.62

     *
Tn

243.12 °C

     *
A

6.112 hPa

     *

     *
for example:

     *

     * dv = 216.7 *
     * (rh / 100.0 * 6.112 * Math.exp(17.62 * t / (243.12 + t)) / (273.15 + t));
     *

     *
     *
{@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE Sensor.TYPE_AMBIENT_TEMPERATURE}:
     *

     *
     *

     *

     * values[0]: ambient (room) temperature in degree Celsius.
     *

     *
     * @see SensorEvent
     * @see GeomagneticField
     */

    public final float[] values;

    /**
     * The sensor that generated this event. See
     * {@link android.hardware.SensorManager SensorManager} for details.
     */
   public Sensor sensor;

    /**
     * The accuracy of this event. See {@link android.hardware.SensorManager
     * SensorManager} for details.
     */
    public int accuracy;

    /**
     * The time in nanosecond at which the event happened
     */
    public long timestamp;

    SensorEvent(int size) {
        values = new float[size];
    }
}


text:
package com.google.android.apps.exposurenotification.keydownload;

import com.google.android.apps.exposurenotification.common.logging.Logger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Parser for the download server configs for roaming servers.
 */
class RoamingConfigParser {

  private static final Logger logger = Logger.getLogger("RoamingConfigParser");

  /**
   * Parses a JSON string like:
   *
   *
{@code
   * {
   *   "US": [
   *     {"index": "https://my-key-server/exposureKeyExport-US/index.txt",
   *      "base": "https://my-key-serrver/exposureKeyExport-US"},
   *     {"index": "https://my-key-server/exposureKeyExport-TRAVEL/index.txt",
   *      "base": "https://my-key-server/exposureKeyExport-TRAVEL"},
   *   ],
   *   "DE": [
   *     {"index": "https://my-key-server/exposureKeyExport-DE/index.txt",
   *      "base": "https://my-key-server/exposureKeyExport-DE"},
   *     {"index": "https://my-key-server/exposureKeyExport-TRAVEL/index.txt",
   *      "base": "https://my-key-server/exposureKeyExport-TRAVEL"},
   *   ],
   * }
   * }

   *

   * into a map keyed by ISO-Alpha-2 country codes, containing lists of server configs.
   */
  static Map<String, List<DownloadUriPair>> parse(String config) {
    try {
      JSONObject roamingConfig = new JSONObject(config);
      ImmutableMap.Builder<String, List<DownloadUriPair>> outBuilder = ImmutableMap.builder();

      Iterator<String> jsonKeys = roamingConfig.keys();
      while (jsonKeys.hasNext()) {
        String countryCode = jsonKeys.next();
        JSONArray servers = roamingConfig.getJSONArray(countryCode);
        ImmutableList.Builder<DownloadUriPair> uriPairsBuilder = ImmutableList.builder();
        for (int i = 0; i < servers.length(); i++) {
          JSONObject server = servers.getJSONObject(i);
          DownloadUriPair uris =
              DownloadUriPair.create(server.getString("index"), server.getString("base"));
          uriPairsBuilder.add(uris);
        }
        outBuilder.put(countryCode, uriPairsBuilder.build());
      }

      logger.d("Parsed " + outBuilder.build().size() + " region(s) roaming config");
      return outBuilder.build();
    } catch (Exception e) {
      // Swallow all failures to parse this config and continue with no roaming servers.
      // TODO: log this failure to Firelog.
      logger.e(
          "Failed to parse JSON roaming download config, continuing with no roaming servers.", e);
      return new HashMap<>();
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<!-- $Id$ -->
<testcase>
  <info>
    <p>
      This test checks tables with table-layout="fixed" and when width is set but is less
      than the sum of all column widths.
    </p>
  </info>
  <fo>
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
      <fo:layout-master-set>
        <fo:simple-page-master master-name="normal" page-width="5in" page-height="5in" margin="20pt">
          <fo:region-body margin="0pt" background-color="lightgray"/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="normal" white-space-collapse="true">
        <fo:flow flow-name="xsl-region-body">
          <fo:table table-layout="fixed" width="100%" border-collapse="separate"
              border="solid 5pt red" border-separation.inline-progression-direction="10pt">
            <fo:table-column column-width="90pt"/>
            <fo:table-column column-width="90pt"/>
            <fo:table-column column-width="90pt"/>
            <fo:table-column column-width="60pt"/>
            <fo:table-body>
              <fo:table-row>
                <fo:table-cell border="solid 2.5pt">
                  <fo:block>cell1</fo:block>
                </fo:table-cell>
                <fo:table-cell border="solid 2.5pt" background-color="yellow">
                  <fo:block>cell2</fo:block>
                </fo:table-cell>
                <fo:table-cell border="solid 2.5pt">
                  <fo:block>cell3</fo:block>
                </fo:table-cell>
                <fo:table-cell border="solid 2.5pt" background-color="yellow">
                  <fo:block>cell4</fo:block>
                </fo:table-cell>
              </fo:table-row>
              <fo:table-row>
                <fo:table-cell background-color="orange">
                  <fo:block>cell5</fo:block>
                </fo:table-cell>
                <fo:table-cell>
                  <fo:block>cell6</fo:block>
                </fo:table-cell>
                <fo:table-cell background-color="orange">
                  <fo:block>cell7</fo:block>
                </fo:table-cell>
                <fo:table-cell>
                  <fo:block>cell8</fo:block>
                </fo:table-cell>
              </fo:table-row>
            </fo:table-body>
          </fo:table>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>
  </fo>
  <checks>
    <eval expected="340000" xpath="//flow/block[1]/@ipda"/>
    <eval expected="330000" xpath="//flow/block[1]/@ipd"/>
    <eval expected="80000" xpath="//flow/block[1]/block[1]/@ipda"/>
    <eval expected="7500" xpath="//flow/block[1]/block[1]/@left-offset"/>
    <eval expected="80000" xpath="//flow/block[1]/block[2]/@ipda"/>
    <eval expected="97500" xpath="//flow/block[1]/block[2]/@left-offset"/>
    <eval expected="80000" xpath="//flow/block[1]/block[3]/@ipda"/>
    <eval expected="187500" xpath="//flow/block[1]/block[3]/@left-offset"/>
    <eval expected="50000" xpath="//flow/block[1]/block[4]/@ipda"/>
    <eval expected="277500" xpath="//flow/block[1]/block[4]/@left-offset"/>
  </checks>
</testcase>


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala Parallel Testing               **
**    / __/ __// _ | / /  / _ |    (c) 2007-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.tools
package partest

import scala.tools.nsc.Properties.propOrFalse
import scala.tools.ant.sabbus.CompilationPathProperty
import java.lang.reflect.Method
import org.apache.tools.ant.Task
import org.apache.tools.ant.types.{ Reference, FileSet }
import org.apache.tools.ant.types.Commandline.Argument
import scala.tools.ant.ScalaTask
import nest.NestUI
import java.net.URLClassLoader

/** An Ant task to execute the Scala test suite (NSC).
 *
 *  This task can take the following parameters as attributes:
 *  - `srcdir`,
 *  - `classpath`,
 *  - `classpathref`,
 *  - `erroronfailed`,
 *  - `javacmd`,
 *  - `javaccmd`,
 *  - `scalacopts`,
 *  - `debug`,
 *  - `junitreportdir`.
 *
 *  It also takes the following parameters as nested elements:
 *  - `compilationpath`. -- TODO: this parameter is now redundant: it's the same as the classpath used to run the task
 *
 *  @author Philipp Haller, Adriaan Moors
 */
class PartestTask extends Task with CompilationPathProperty with ScalaTask {
  type Path = org.apache.tools.ant.types.Path

  private var kinds: Array[String] = Array.empty
  private var classpath: Option[Path] = None
  private var debug = false
  private var errorOnFailed: Boolean = true
  private var jUnitReportDir: Option[File] = None
  private var javaccmd: Option[File] = None
  private var javacmd: Option[File] = Option(sys.props("java.home")) map (x => new File(x, "bin/java"))
  private var scalacArgs: Option[Seq[Argument]] = None
  private var srcDir: Option[String] = None
  private var colors: Int = 0

  def setSrcDir(input: String) {
    srcDir = Some(input)
  }

  def setColors(input: String) {
    try colors = input.toInt catch { case _: NumberFormatException => () }
    if (colors > 0)
      sys.props("partest.colors") = colors.toString
  }

  def setClasspath(input: Path) {
    if (classpath.isEmpty)
      classpath = Some(input)
    else
      classpath.get.append(input)
  }

  def createClasspath(): Path = {
    if (classpath.isEmpty) classpath = Some(new Path(getProject()))
    classpath.get.createPath()
  }

  def setClasspathref(input: Reference) {
    createClasspath().setRefid(input)
  }
  def setErrorOnFailed(input: Boolean) {
    errorOnFailed = input
  }

  def setJavaCmd(input: File) {
    javacmd = Some(input)
  }

  def setKinds(input: String) {
    kinds = words(input).toArray
  }

  def setJavacCmd(input: File) {
    javaccmd = Some(input)
  }

  def setScalacOpts(input: String) {
    val s = input.split(' ').map { s => val a = new Argument; a.setValue(s); a }
    scalacArgs = Some(scalacArgs.getOrElse(Seq()) ++ s)
  }

  def createCompilerArg(): Argument = {
    val a = new Argument
    scalacArgs = Some(scalacArgs.getOrElse(Seq()) :+ a)
    a
  }

  def setDebug(input: Boolean) {
    debug = input
  }

  def setJUnitReportDir(input: File) {
    jUnitReportDir = Some(input)
  }

  override def execute() {
    if (debug || propOrFalse("partest.debug")) {
      NestUI.setDebug()
    }

    if (compilationPath.isEmpty) sys.error("Mandatory attribute 'compilationPath' is not set.")

    def scalacArgsFlat: Array[String] = scalacArgs.toArray flatMap (_ flatMap { a =>
      val parts = a.getParts
      if (parts eq null) Array.empty[String] else parts
    })

    var failureCount = 0
    val summary = new scala.tools.partest.nest.AntRunner(srcDir.getOrElse(null), new URLClassLoader(compilationPath.get.list.map(Path(_).toURL)), javacmd.getOrElse(null), javaccmd.getOrElse(null), scalacArgsFlat) {
      def echo(msg: String): Unit = PartestTask.this.log(msg)
      def log(msg: String): Unit = PartestTask.this.log(msg)

      def onFinishKind(kind: String, passed: Array[TestState], failed: Array[TestState]) = {
        failureCount += failed.size

        def oneResult(res: TestState) =
          <testcase name={ res.testIdent }>{
            if (res.isOk) scala.xml.NodeSeq.Empty
            else <failure message="Test failed"/>
          }</testcase>

        // create JUnit Report xml files if directory was specified
        jUnitReportDir foreach { d =>
          d.mkdir
          val report =
            <testsuite name={ kind } tests={ (passed.size + failed.size) toString } failures={ failed.size.toString }>
              <properties/>{ passed map oneResult }{ failed map oneResult }
            </testsuite>

          scala.xml.XML.save(d.getAbsolutePath + "/" + kind + ".xml", report)
        }
      }
    } execute (kinds)

    if (errorOnFailed && failureCount > 0) buildError(summary)
    else log(summary)

  }
}


text:
module Songdrop
  class Chart < Base
  end
end


text:
package com.angcyo.uiview.base;

import android.support.annotation.CallSuper;
import android.view.View;

import com.angcyo.uiview.container.UIParam;
import com.angcyo.uiview.net.NonetException;
import com.angcyo.uiview.net.RSubscriber;
import com.angcyo.uiview.receiver.NetworkStateReceiver;

import rx.Subscription;
import rx.observers.SafeSubscriber;
import rx.subscriptions.CompositeSubscription;

public abstract class UIBaseRxView extends UIBaseDataView {
    protected CompositeSubscription mSubscriptions;

    @CallSuper
    @Override
    public void onViewCreate(View rootView) {
        super.onViewCreate(rootView);
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void onViewCreate(View rootView, UIParam param) {
        super.onViewCreate(rootView, param);
    }

    @CallSuper
    @Override
    public void onViewUnload() {
        super.onViewUnload();
        if (!mSubscriptions.isUnsubscribed()) {
            mSubscriptions.unsubscribe();
        }
    }

    @Override
    public void release() {
        super.release();
        onCancel();
    }

    public void onCancel() {
        if (mSubscriptions != null) {
            mSubscriptions.clear();
        }
    }

    public void add(Subscription subscription) {
        add(subscription, false);
    }

    public void add(Subscription subscription, boolean checkToken) {
        if (mSubscriptions != null) {
            mSubscriptions.add(subscription);
        }
        if (NetworkStateReceiver.getNetType().value() < 2) {
            //2G网络以下, 取消网络请求
            onCancel();
            try {
                if (subscription instanceof SafeSubscriber) {
                    if (((SafeSubscriber) subscription).getActual() instanceof RSubscriber) {
                        ((SafeSubscriber) subscription).getActual().onError(new NonetException());
                    }
                }
            } catch (Exception e) {

            }
        }
    }
}


text:
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();

var Mustache = require('mustache');
var Plates = require('../lib/plates');

suite

  .add('mustache', function() {

  	var view = { "foo": "Hello, World" };
  	var template = '
{{foo}}

';

  	Mustache.to_html(template, view);

  })
  .add('plates', function() {

    var view = { "foo": "Hello, World" };
  	var template = '

';

  	Plates.bind(template, view);

  })

  .on('cycle', function(event, bench) {
    console.log(String(bench));
  })

  .on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'));
  })

  .add('mustache iterations', function() {

  	var view = {
      "stooges": [
        "Moe",
        "Larry",
        "Curly"
      ]
    };
  	var template = '{{#stooges}}{{name}}{{/stooges}}';

  	Mustache.to_html(template, view);

  })
  .add('plates iterations', function() {

    var view = {
      "stooges": [
        "Moe",
        "Larry",
        "Curly"
      ]
    };
  	var template = 'Name';

  	Plates.bind(template, view);

  })
  .run(true);


text:
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data

'-------------------------------------------------------------------------------------------'
' Inicio de clase "fCotizaciones_USA"
'-------------------------------------------------------------------------------------------'
Partial Class fCotizaciones_USA

    Inherits vis2formularios.frmReporte

    Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try

            Dim loComandoSeleccionar As New StringBuilder()

            loComandoSeleccionar.AppendLine(" SELECT	Cotizaciones.Cod_Cli, ")
            loComandoSeleccionar.AppendLine("           (CASE WHEN (Clientes.Generico = 0 AND CAST (Cotizaciones.Nom_Cli AS VARCHAR) = '') THEN Clientes.Nom_Cli ELSE ")
            loComandoSeleccionar.AppendLine("               (CASE WHEN (Cotizaciones.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE Cotizaciones.Nom_Cli END) END) AS  Nom_Cli, ")
            loComandoSeleccionar.AppendLine("           (CASE WHEN (Clientes.Generico = 0 AND CAST (Cotizaciones.Nom_Cli AS VARCHAR) = '') THEN Clientes.Rif ELSE ")
            loComandoSeleccionar.AppendLine("               (CASE WHEN (Cotizaciones.Rif = '') THEN Clientes.Rif ELSE Cotizaciones.Rif END) END) AS  Rif, ")
            loComandoSeleccionar.AppendLine("           Clientes.Nit, ")
            loComandoSeleccionar.AppendLine("           (CASE WHEN (Clientes.Generico = 0 AND CAST (Cotizaciones.Nom_Cli AS VARCHAR) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE ")
            loComandoSeleccionar.AppendLine("               (CASE WHEN (SUBSTRING(Cotizaciones.Dir_Fis,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE SUBSTRING(Cotizaciones.Dir_Fis,1, 200) END) END) AS  Dir_Fis, ")
            loComandoSeleccionar.AppendLine("           (CASE WHEN (Clientes.Generico = 0 AND CAST (Cotizaciones.Nom_Cli AS VARCHAR) = '') THEN Clientes.Telefonos ELSE ")
            loComandoSeleccionar.AppendLine("               (CASE WHEN (Cotizaciones.Telefonos = '') THEN Clientes.Telefonos ELSE Cotizaciones.Telefonos END) END) AS  Telefonos, ")
            loComandoSeleccionar.AppendLine("           Clientes.Fax, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Nom_Cli                    As  Nom_Gen, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Rif                        As  Rif_Gen, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Nit                        As  Nit_Gen, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Dir_Fis                    As  Dir_Gen, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Telefonos                  As  Tel_Gen, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Documento, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Fec_Ini, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Fec_Fin, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Mon_Bru, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Por_Des1, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Por_Rec1, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Mon_Des1, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Mon_Rec1, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Mon_Imp1, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Mon_Net, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Cod_For, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Dis_Imp, ")
            loComandoSeleccionar.AppendLine("           SUBSTRING(Formas_Pagos.Nom_For,1,20)    AS  Nom_For, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Cod_Ven, ")
            loComandoSeleccionar.AppendLine("           Cotizaciones.Comentario, ")
            loComandoSeleccionar.AppendLine("           Vendedores.Nom_Ven, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Cod_Art, ")

            loComandoSeleccionar.AppendLine("           CASE WHEN Articulos.Generico = 0 THEN Articulos.Nom_Art ")
            loComandoSeleccionar.AppendLine("			    ELSE Renglones_Cotizaciones.Notas END AS Nom_Art,  ")

            'loComandoSeleccionar.AppendLine("           Articulos.Nom_Art, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Renglon, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Comentario AS Comentario_renglon, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Can_Art1, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Cod_Uni, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Precio1, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Por_Des, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Mon_Net          As  Neto, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Por_Imp1         As  Por_Imp, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Cod_Imp, ")
            loComandoSeleccionar.AppendLine("           Renglones_Cotizaciones.Mon_Imp1         As  Impuesto ")
            loComandoSeleccionar.AppendLine(" FROM      Cotizaciones ")
            loComandoSeleccionar.AppendLine(" JOIN Renglones_Cotizaciones ON (Cotizaciones.Documento  =   Renglones_Cotizaciones.Documento) ")
            loComandoSeleccionar.AppendLine(" JOIN  Clientes ON (Cotizaciones.Cod_Cli    =   Clientes.Cod_Cli)")
            loComandoSeleccionar.AppendLine(" JOIN  Formas_Pagos ON (Cotizaciones.Cod_For    =   Formas_Pagos.Cod_For)")
            loComandoSeleccionar.AppendLine(" JOIN  Vendedores ON (Cotizaciones.Cod_Ven    =   Vendedores.Cod_Ven)")
            loComandoSeleccionar.AppendLine(" JOIN  Articulos ON (Articulos.Cod_Art       =   Renglones_Cotizaciones.Cod_Art)")
            loComandoSeleccionar.AppendLine(" WHERE      " & cusAplicacion.goFormatos.pcCondicionPrincipal)

            Dim loServicios As New cusDatos.goDatos
            Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(loComandoSeleccionar.ToString, "curReportes")

            Dim lcXml As String = "<impuesto></impuesto>"
            Dim lcPorcentajesImpueto As String
            Dim loImpuestos As New System.Xml.XmlDocument()

            lcPorcentajesImpueto = "("

            'Recorre cada renglon de la tabla
            For lnNumeroFila As Integer = 0 To laDatosReporte.Tables(0).Rows.Count - 1
                lcXml = laDatosReporte.Tables(0).Rows(lnNumeroFila).Item("dis_imp")

                If String.IsNullOrEmpty(lcXml.Trim()) Then
                    Continue For
                End If

                loImpuestos.LoadXml(lcXml)

                'En cada renglón lee el contenido de la distribució de impuestos
                For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto")
                    If lnNumeroFila = laDatosReporte.Tables(0).Rows.Count - 1 Then
                        If CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) <> 0 Then
                            lcPorcentajesImpueto = lcPorcentajesImpueto & ", " & CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) & "%"
                        End If
                    End If
                Next loImpuesto
            Next lnNumeroFila

            lcPorcentajesImpueto = lcPorcentajesImpueto & ")"
            lcPorcentajesImpueto = lcPorcentajesImpueto.Replace("(,", "(")
            lcPorcentajesImpueto = lcPorcentajesImpueto.Replace(".", ",")

            '--------------------------------------------------'
            ' Carga la imagen del logo en cusReportes          '
            '--------------------------------------------------'
            Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")

            '-------------------------------------------------------------------------------------------------------
            ' Verificando si el select (tabla nº0) trae registros
            '-------------------------------------------------------------------------------------------------------

            If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
                Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
                                          "No se Encontraron Registros para los Parámetros Especificados. ", _
                                            vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
                                           "350px", _
                                           "200px")
            End If

            loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fCotizaciones_USA", laDatosReporte)

            CType(loObjetoReporte.ReportDefinition.ReportObjects("Text38"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString

            Me.mTraducirReporte(loObjetoReporte)
            Me.mFormatearCamposReporte(loObjetoReporte)
            Me.crvfCotizaciones_USA.ReportSource = loObjetoReporte

        Catch loExcepcion As Exception

            Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
                          "No se pudo Completar el Proceso: " & loExcepcion.Message, _
                           vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
                           "auto", _
                           "auto")

        End Try

    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

        Try

            loObjetoReporte.Close()

        Catch loExcepcion As Exception

        End Try

    End Sub

End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' MAT: 15/09/11: Codigo inicial
'-------------------------------------------------------------------------------------------'


text:
/* chat view */
li.row-message {
  margin-bottom: 30px;
}
li.row-message p {
  display: table-cell;
}
form[name="message-form"] input[type="text"] {
  width: 80%;
}


text:
package com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile;

import com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentConfiguration;
import com.netflix.spinnaker.halyard.config.model.v1.security.ApiSecurity;
import com.netflix.spinnaker.halyard.config.model.v1.security.Security;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerArtifact;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.integrations.IntegrationsConfigWrapper;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.SpinnakerService.Type;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

public abstract class GateProfileFactory extends SpringProfileFactory {
  // Some versions of gate have integrations in the base halyard config; we'll generate an invalid
  // config
  // if we add another integrations block.  As a workaround we'll remove that block from the base
  // profile
  // if we encounter it.
  private static final String INTEGRATION_BLOCK =
      "integrations:\n  gremlin:\n    enabled: ${features.gremlin:false}\n    baseUrl: https://api.gremlin.com/v1\n";

  @Override
  public SpinnakerArtifact getArtifact() {
    return SpinnakerArtifact.GATE;
  }

  @Override
  public String getMinimumSecretDecryptionVersion(String deploymentName) {
    return "1.5.3";
  }

  @Override
  public void setProfile(
      Profile profile,
      DeploymentConfiguration deploymentConfiguration,
      SpinnakerRuntimeSettings endpoints) {
    super.setProfile(profile, deploymentConfiguration, endpoints);

    Security security = deploymentConfiguration.getSecurity();
    List<String> requiredFiles =
        backupRequiredFiles(security.getApiSecurity(), deploymentConfiguration.getName());
    requiredFiles.addAll(
        backupRequiredFiles(security.getAuthn(), deploymentConfiguration.getName()));
    requiredFiles.addAll(
        backupRequiredFiles(security.getAuthz(), deploymentConfiguration.getName()));
    GateConfig gateConfig = getGateConfig(endpoints.getServiceSettings(Type.GATE), security);
    gateConfig.getCors().setAllowedOriginsPattern(security.getApiSecurity());
    IntegrationsConfigWrapper integrationsConfig =
        new IntegrationsConfigWrapper(deploymentConfiguration.getFeatures());

    profile
        .appendContents(yamlToString(deploymentConfiguration.getName(), profile, gateConfig))
        .appendContents(
            yamlToString(deploymentConfiguration.getName(), profile, integrationsConfig))
        .appendContents(profile.getBaseContents().replace(INTEGRATION_BLOCK, ""))
        .setRequiredFiles(requiredFiles);
  }

  protected abstract GateConfig getGateConfig(ServiceSettings gate, Security security);

  @EqualsAndHashCode(callSuper = true)
  @Data
  protected static class GateConfig extends SpringProfileConfig {
    Cors cors = new Cors();
    SpringConfig spring;
    SamlConfig saml;
    LdapConfig ldap;
    X509Config x509;
    GoogleConfig google = new GoogleConfig();

    GateConfig(ServiceSettings gate, Security security) {
      super(gate);
      server.ssl = security.getApiSecurity().getSsl();
    }

    @Data
    static class Cors {
      private String allowedOriginsPattern;

      void setAllowedOriginsPattern(ApiSecurity apiSecurity) {
        String corsAccessPattern = apiSecurity.getCorsAccessPattern();
        if (!StringUtils.isEmpty(corsAccessPattern)) {
          allowedOriginsPattern = corsAccessPattern;
        }
      }
    }

    @Data
    static class GoogleConfig {
      IAPConfig iap;
    }
  }
}


text:
from django.htoken import verify_signature
from django.htoken import ACTIVE_USER_ID_KEY, PERMISSION_IDS, SUPER_STATUS

class ActiveUserAssert():
    def __init__(self, argument_position):
        self.position = argument_position
    def printerr(self, arg_list, token):
        return "User: args[%s] :: %s == %s" % \
            (self.position, arg_list[self.position], token.dict['hachi_active_user'])
    def check_assert(self, arg_list, token):
        # get active user?
        return arg_list[self.position] == token.dict['hachi_active_user']
    def __eq__(self, other):
        return ((isinstance(other, ActiveUserAssert) and
                 other.position == self.position))
    def __repr__(self):
        return "User(%s)" % (self.position)
    def __hash__(self):
        return hash("U%s" % self.position)

class NullAssert():
    def __init__(self, argument_position):
        self.position = argument_position
    def check_assert(self, arg_list, token):
        return true
    def __eq__(self, other):
        return ((isinstance(other, NullAssert) and
                 other.position == self.position))
    def __repr__(self):
        return "Null(%s)" % (self.position)
    def __hash__(self):
        return hash("N%s" % self.position)

def perm_validity_check(tdict, perms):
    return ( (tdict.get(SUPER_STATUS, 0) == 1) or
             (PERMISSION_IDS in tdict and \
                  all([ p in tdict[PERMISSION_IDS] for p in perms if p is not None ])) )

class ControlFlowAssert():
    def __init__(self, key, value):
        self.key = key
        self.value = value
    def __eq__(self, other):
        return ((isinstance(other, ControlFlowAssert) and
                 other.key == self.key and
                 other.value == self.value))
    def __hash__(self):
        return hash(self.__repr__())
    def __repr__(self):
        return "CF(%s, %s)" % (self.key, self.value)
    def printerr(self, arg_list, token):
        token_value_0 = token.dict.get(self.key)
        token_value_1 = token.dict.get(self.value)
        return "CF: t[%s] == t[%s] :: %s == %s" % \
            (self.key, self.value, token_value_0, token_value_1)
    def check_assert(self, arg_list, token):
        try:
            token_value_0 = token.dict[self.key]
            token_value_1 = token.dict[self.value]
        except KeyError:
            return False
        if isinstance(token_value_1, list) and isinstance(token_value_0, list):
            l1 = set([unicode(v) for v in token_value_1])
            l0 = set([unicode(v) for v in token_value_0])
            return l0.issubset(l1) or l1.issubset(l0)

        elif isinstance(token_value_1, list):
            return (unicode(token_value_0) in [unicode(v) for v in token_value_1])
        elif isinstance(token_value_0, list):
            return (unicode(token_value_1) in [unicode(v) for v in token_value_0])
        else:
            return unicode(token_value_0) == unicode(token_value_1)

class PermissionAssert():
    def __init__(self, perms, valid):
#        self.position = -1
        self.perms = perms
        self.valid = valid
    def printerr(self, arg_list, token):
        return self.__repr__
    def check_assert(self, arg_list, token):
        validity = perm_validity_check(token.dict, self.perms)
        return validity == self.valid
    def __eq__(self, other):
        return ((isinstance(other, PermissionAssert) and
                 other.perms == self.perms and
                 other.valid == self.valid))
    def __repr__(self):
        return "Perm(%s)" % (self.perms)
    def __hash__(self):
        return hash("P%s" % self.perms)

class ConstantAssert():
    def __init__(self, argument_position, value):
        """
        Values must be a list, guys!
        """
        self.position = argument_position
        self.value = value
    def printerr(self, arg_list, token):
        return "Cons: args[%s] == %s :: %s == %s" % \
            (self.position, self.value , arg_list[self.position], self.value)
    def check_assert(self, arg_list, token):
        r = ("%s" % arg_list[self.position]) == ("%s" % self.value)
        return r
    def __repr__(self):
        return "Constant(%s, %s)" % (self.position, self.value)
    def __hash__(self):
        return hash("C%s+%s" % (self.position, self.value))
    def __eq__(self, other):
        return (isinstance(other, ConstantAssert) and
                other.position == self.position and
                other.value == self.value)

class TokenAssert():
    def __init__(self, argument_position, index):
        """
        index may be a tuple (in the case of a db response value)
        """
        self.position = argument_position
        self.index = index

    def _atom_check(self, val_arg, token_ix, token):
        """
        Evaluates the token constraint for a single token index
        """
        try:
            val_arg = unicode(val_arg)
            val_token = token.dict[token_ix]
            if isinstance(val_token, list):
                val_token = [unicode(i) for i in val_token]
                return (val_arg in val_token)
            val_token = unicode(val_token)
            return (val_arg == val_token)
        except KeyError:
            return False
    def printerr(self, arg_list, token):
        if isinstance(self.index, list):
            ix_out = [token.dict.get(ix) for ix in self.index]
        else:
            ix_out = token.dict.get(self.index)

        return "DFlow: args[%s] == t[%s] :: %s == %s" % \
            (self.position, self.index , arg_list[self.position],
             ix_out)

    def _check_impl(self, val_arg, token):
        if isinstance(self.index, list):
            return any([self._atom_check(val_arg, ix, token)
                        for ix in self.index])
        else:
            return self._atom_check(val_arg, self.index, token)

    def check_assert(self, arg_list, token):
        if not verify_signature(token):
            return False
        val_arg = arg_list[self.position]
        if isinstance(val_arg, list):
            return all([self._check_impl(v, token) for v in val_arg])
        else:
            return self._check_impl(val_arg, token)

    def __repr__(self):
        return "Token(%s, %s)" % (self.position, self.index)
    def __hash__(self):
        return hash("P%s+%s" % (self.position, self.index))
    def __eq__(self, other):
        return (isinstance(other, TokenAssert) and
                other.position == self.position and
                other.index == self.index)


text:
module Crashbreak
  class RequestParser
    def initialize(request_data)
      @request = request_data
    end

    def request_data
      yield(request_method_sym, request_path, request_body, request_headers)
    end

    private

    def request_method_sym
      @request['REQUEST_METHOD'].underscore.to_sym
    end

    def request_path
      @request['PATH_INFO']
    end

    def request_body
      JSON.parse(request_hash_as_string.gsub('=>', ':')).symbolize_keys
    end

    def request_hash_as_string
      @request['rack.request.form_hash'] || @request['RAW_POST_DATA'] || '{}'
    end

    def request_headers
      {}.tap do |request_headers|
        @request.select{|key| key.start_with?('HTTP_')}.each do |key, value|
          request_headers[key.gsub('HTTP_', '')] = value
        end
      end
    end
  end
end