text:
require.config({
  paths: {
    jquery: "jquery-2.1.4.min"
  }
});

require(["jquery", "tabs"], function($, tabs) {
	var tabber1, tabber2;

	tabber1 = tabs.create(document.getElementById("controller1"), document.getElementById("viewport1"), [
	  {
		  title: "Tab #1",
		  content: "This is the first tab created."
	  },
	  {
		  title: "Tab #2",
		  content: "This is the second tab created."
	  },
	  {
		  title: "Another Tab",
		  content: "Yet another tab for your viewing pleasure."
	  },
	  {
		  title: "A Really Large Tab",
		  content: "B-e-a-utiful?"
	  }
	], {});

	tabber2 = tabs.create(document.getElementById("controller2"), document.getElementById("viewport2"), [
	  {
		  title: "Bacon",
		  content: "It's what's for breakfast."
	  },
	  {
		  title: "Breakfast",
		  content: "It had better include bacon."
	  },
	  {
		  title: "Dinosaurs",
		  content: "I bet a few of them made some delicious bacon."
	  },
	  {
		  title: "Honey Badgers",
		  content: "They're your friends for life.  When's the last time you hugged a honey badger?"
	  }
	], {});

	tabber1.remove_tab(1);
	tabber1.add_tab("A New Tab", "This was a tab added after tabber creation through use of the control expression returned to the tabber1 variable.");

	tabber2.add_tab("Default", "This tab is selected by default manually via tabber2->click.  This is the intended behavior because it's possible to create a tabber with no tabs initially, so it's not always possible to \"default select\" the first tab.");

  /* forcing a click to the first tab is not necessary because the control will
   * automatically select the first indexed tab in the list upon creation if you
   * create a control with at least one tab
   */
//	tabber1.get_tab(0).click();

  /* this is necessary to make the default selected tab something other than the
   * first indexed tab
   */
	tabber2.get_tab(4).click();
});

redpajama_set_name: RedPajamaGithub


text:
const YoutubeDL = require('youtube-dl');
const ytdl = require('ytdl-core');
var YouTube = require('youtube-node');

var config = require('./config.json');
var youTube = new YouTube();
youTube.setKey(config.youtube_api_key);
var volum = 50;
/**
 * Takes a discord.js client and turns it into a music bot.
 * Thanks to 'derekmartinez18' for helping.
 *
 * @param {Client} client - The discord.js client.
 * @param {object} options - (Optional) Options to configure the music bot. Acceptable options are:
 * 							prefix: The prefix to use for the commands (default '!').
 * 							global: Whether to use a global queue instead of a server-specific queue (default false).
 * 							maxQueueSize: The maximum queue size (default 20).
 * 							anyoneCanSkip: Allow anybody to skip the song.
 * 							clearInvoker: Clear the command message.
 * 							volume: The default volume of the player.
 *							channel: Name of default voice channel to join.
 */
module.exports = function (client, options) {
	// Get all options.
	let PREFIX = (options && options.prefix) || '!';
	let GLOBAL = (options && options.global) || false;
	let MAX_QUEUE_SIZE = (options && options.maxQueueSize) || 20;
	let DEFAULT_VOLUME = (options && options.volume) || 50;
	let ALLOW_ALL_SKIP = (options && options.anyoneCanSkip) || false;
	let CLEAR_INVOKER = (options && options.clearInvoker) || false;
	let CHANNEL = (options && options.channel) || false;

	// Create an object of queues.
	let queues = {};

	// Catch message events.
	client.on('message', msg => {
		if (typeof msg.channel.guild == 'undefined') {
	    return;
	  }
		if (config.bot_channel.enabled) {
			if (msg.channel.name !== config.bot_channel.channel && !serverAdmin(msg)) {
				return; //not in proper channel
			}
		}

		const message = msg.content.trim();

		// Check if the message is a command.
		if (message.toLowerCase().startsWith(PREFIX.toLowerCase())) {
			// Get the command and suffix.
			const command = message.substring(PREFIX.length).split(/[ \n]/)[0].toLowerCase().trim();
			const suffix = message.substring(PREFIX.length + command.length).trim();

			// Process the commands.
			switch (command) {
				case 'play':
					return play(msg, suffix);
				case 'skip':
					return skip(msg, suffix);
				case 'queue':
					return queue(msg, suffix);
				case 'pause':
					return pause(msg, suffix);
				case 'resume':
					return resume(msg, suffix);
				case 'volume':
					return volume(msg, suffix);
				case 'leave':
					return leave(msg, suffix);
				case 'clearqueue':
					return clearqueue(msg, suffix);
			}
		}
	});

	/**
	 * Checks if a user is an admin.
	 *
	 * @param {GuildMember} member - The guild member
	 * @returns {boolean} -
	 */

	function isAdmin(member) {
		return member.hasPermission("ADMINISTRATOR");
	}

	function serverAdmin(msg) {
	  if (typeof msg.channel.guild == 'undefined') {
	    return true; //pm so allow
	  }
	  if (!msg.member.hasPermission("ADMINISTRATOR")) {
	    return false;
	  } else {
	    return true;
	  }
	}

	/**
	 * Checks if the user can skip the song.
	 *
	 * @param {GuildMember} member - The guild member
	 * @param {array} queue - The current queue
	 * @returns {boolean} - If the user can skip
	 */
	function canSkip(member, queue) {
		if (ALLOW_ALL_SKIP) return true;
		else if (queue[0].requester === member.id) return true;
		else if (isAdmin(member)) return true;
		else return false;
	}

	/**
	 * Gets the song queue of the server.
	 *
	 * @param {integer} server - The server id.
	 * @returns {object} - The song queue.
	 */
	function getQueue(server) {
		// Check if global queues are enabled.
		if (GLOBAL) server = '_'; // Change to global queue.

		// Return the queue.
		if (!queues[server]) queues[server] = [];
		return queues[server];
	}

	/**
	 * The command for adding a song to the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response edit.
	 */
	function play(msg, suffix) {
		// Make sure the user is in a voice channel.
		if (!CHANNEL && msg.member.voiceChannel === undefined) return msg.channel.send(wrap('You\'re not in a voice channel.'));

		// Make sure the suffix exists.
		if (!suffix) return msg.channel.send(wrap('No video specified!'));

		// Get the queue.
		const queue = getQueue(msg.guild.id);

		// Check if the queue has reached its maximum size.
		if (queue.length >= MAX_QUEUE_SIZE) {
			return msg.channel.send(wrap('Maximum queue size reached!'));
		}

		// Get the video information.
		msg.channel.send(wrap('Searching...')).then(response => {
			var searchstring = suffix
			if (!suffix.toLowerCase().startsWith('http')) {
				searchstring = 'gvsearch1:' + suffix;
			}

			// YoutubeDL.getInfo(searchstring, ['-q', '--no-warnings', '--force-ipv4'], (err, info) => {
			// 	// Verify the info.
			// 	if (err || info.format_id === undefined || info.format_id.startsWith('0')) {
			// 		return response.edit(wrap('Invalid video!'));
			// 	}
			//
			// 	info.requester = msg.author.id;
			//
			// 	// Queue the video.
				// response.edit(wrap('Queued: ' + info.title)).then(() => {
				// 	queue.push(info);
				// 	// Play if only one element in the queue.
				// 	if (queue.length === 1) executeQueue(msg, queue);
				// }).catch(console.log);
			// });

			youTube.search(suffix, 1, function(error, res) {
			if (error) {
				msg.channel.send("¯\\_(ツ)_/¯");
			}
			else {
				if (!res || !res.items || res.items.length < 1) {
					response.edit(wrap('No results ¯\\_(ツ)_/¯')).then(() => {
					});
				} else {
					var info = new Object();
					info.requester = msg.author.id;
 					info.format_id = res.items[0].id.videoId;
					info.title = res.items[0].snippet.title;
					info.webpage_url = "https://www.youtube.com/view?v="+info.format_id;
					// queue.push(info);
					response.edit(wrap('Queued: ' + info.title)).then(() => {
						queue.push(info);
						// Play if only one element in the queue.
						if (queue.length === 1) executeQueue(msg, queue);
					}).catch(console.log);
					//msg.channel.send("http://www.youtube.com/watch?v=" + info.items[0].id.videoId );
				}
			}
		});
		}).catch(console.log);
	}

	/**
	 * The command for skipping a song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
	function skip(msg, suffix) {
		// Get the voice connection.
		const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
		if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));

		// Get the queue.
		const queue = getQueue(msg.guild.id);

		if (!canSkip(msg.member, queue)) return msg.channel.send(wrap('You cannot skip this as you didn\'t queue it.')).then((response) => {
			response.delete(5000);
		});

		// Get the number to skip.
		let toSkip = 1; // Default 1.
		if (!isNaN(suffix) && parseInt(suffix) > 0) {
			toSkip = parseInt(suffix);
		}
		toSkip = Math.min(toSkip, queue.length);

		// Skip.
		queue.splice(0, toSkip - 1);

		// Resume and stop playing.
		const dispatcher = voiceConnection.player.dispatcher;
		if (voiceConnection.paused) dispatcher.resume();
		dispatcher.end();

		msg.channel.send(wrap('Skipped ' + toSkip + '!'));
	}

	/**
	 * The command for listing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
	function queue(msg, suffix) {
		// Get the queue.
		const queue = getQueue(msg.guild.id);

		// Get the queue text.
		const text = queue.map((video, index) => (
			(index + 1) + ': ' + video.title
		)).join('\n');

		// Get the status of the queue.
		let queueStatus = 'Stopped';
		const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
		if (voiceConnection !== null) {
			const dispatcher = voiceConnection.player.dispatcher;
			queueStatus = dispatcher.paused ? 'Paused' : 'Playing';
		}

		// Send the queue and status.
		msg.channel.send(wrap('Queue (' + queueStatus + '):\n' + text));
	}

	/**
	 * The command for pausing the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
	function pause(msg, suffix) {
		// Get the voice connection.
		const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
		if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));

		if (!isAdmin(msg.member))
			return msg.channel.send(wrap('You are not authorized to use this.'));

		// Pause.
		msg.channel.send(wrap('Playback paused.'));
		const dispatcher = voiceConnection.player.dispatcher;
		if (!dispatcher.paused) dispatcher.pause();
	}

	/**
	 * The command for leaving the channel and clearing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
	function leave(msg, suffix) {
		if (isAdmin(msg.member)) {
			const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
			if (voiceConnection === null) return msg.channel.send(wrap('I\'m not in any channel!.'));
			// Clear the queue.
			const queue = getQueue(msg.guild.id);
			queue.splice(0, queue.length);

			// End the stream and disconnect.
			voiceConnection.player.dispatcher.end();
			voiceConnection.disconnect();
		} else {
			msg.channel.send(wrap('You don\'t have permission to use that command!'));
		}
	}

	/**
	 * The command for clearing the song queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
	function clearqueue(msg, suffix) {
		if (isAdmin(msg.member)) {
			const queue = getQueue(msg.guild.id);

			queue.splice(0, queue.length);
			msg.channel.send(wrap('Queue cleared!'));
		} else {
			msg.channel.send(wrap('You don\'t have permission to use that command!'));
		}
	}

	/**
	 * The command for resuming the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
	function resume(msg, suffix) {
		// Get the voice connection.
		const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
		if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));

		if (!isAdmin(msg.member))
			return msg.channel.send(wrap('You are not authorized to use this.'));

		// Resume.
		msg.channel.send(wrap('Playback resumed.'));
		const dispatcher = voiceConnection.player.dispatcher;
		if (dispatcher.paused) dispatcher.resume();
	}

	/**
	 * The command for changing the song volume.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
	function volume(msg, suffix) {
		// Get the voice connection.
		const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
		if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));

		if (!isAdmin(msg.member))
			return msg.channel.send(wrap('You are not authorized to use this.'));

		// Get the dispatcher
		const dispatcher = voiceConnection.player.dispatcher;

		if (suffix > 200 || suffix < 0) return msg.channel.send(wrap('Volume out of range!')).then((response) => {
			response.delete(5000);
		});

		msg.channel.send(wrap("Volume set to " + suffix));
		dispatcher.setVolume((suffix/100));
		volum = suffix;
	}

	/**
	 * Executes the next song in the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {object} queue - The song queue for this server.
	 * @returns {<promise>} - The voice channel.
	 */
	function executeQueue(msg, queue) {
		// If the queue is empty, finish.
		if (queue.length === 0) {
			msg.channel.send(wrap('Playback finished.'));

			// Leave the voice channel.
			const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
			if (voiceConnection !== null) return voiceConnection.disconnect();
		}

		new Promise((resolve, reject) => {
			// Join the voice channel if not already in one.
			const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
			if (voiceConnection === null) {
				if (CHANNEL) {
					msg.guild.channels.find('name', CHANNEL).join().then(connection => {
						resolve(connection);
					}).catch((error) => {
						console.log(error);
					});

				// Check if the user is in a voice channel.
				} else if (msg.member.voiceChannel) {
					msg.member.voiceChannel.join().then(connection => {
						resolve(connection);
					}).catch((error) => {
						console.log(error);
					});
				} else {
					// Otherwise, clear the queue and do nothing.
					queue.splice(0, queue.length);
					reject();
				}
			} else {
				resolve(voiceConnection);
			}
		}).then(connection => {
			// Get the first item in the queue.
			const video = queue[0];

			console.log(video.webpage_url);

			// Play the video.
			msg.channel.send(wrap('Now Playing: ' + video.title)).then(() => {
				let dispatcher = connection.playStream(ytdl(video.webpage_url, {filter: 'audioonly'}), {seek: 0, volume: (DEFAULT_VOLUME/100)});
				dispatcher.setVolume((volum/100));

				connection.on('error', (error) => {
					// Skip to the next song.
					console.log(error);
					queue.shift();
					executeQueue(msg, queue);
				});

				dispatcher.on('error', (error) => {
					// Skip to the next song.
					console.log(error);
					queue.shift();
					executeQueue(msg, queue);
				});

				dispatcher.on('end', () => {
					// Wait a second.
					setTimeout(() => {
						if (queue.length > 0) {
							// Remove the song from the queue.
							queue.shift();
							// Play the next song in the queue.
							executeQueue(msg, queue);
						}
					}, 1000);
				});
			}).catch((error) => {
				console.log(error);
			});
		}).catch((error) => {
			console.log(error);
		});
	}
}

/**
 * Wrap text in a code block and escape grave characters.
 *
 * @param {string} text - The input text.
 * @returns {string} - The wrapped text.
 */
function wrap(text) {
	return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```';
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int_max_add_84_goodG2B.cpp
Label Definition File: CWE190_Integer_Overflow__int.label.xml
Template File: sources-sinks-84_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: max Set data to the max value for int
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE190_Integer_Overflow__int_max_add_84.h"

namespace CWE190_Integer_Overflow__int_max_add_84
{
CWE190_Integer_Overflow__int_max_add_84_goodG2B::CWE190_Integer_Overflow__int_max_add_84_goodG2B(int dataCopy)
{
    data = dataCopy;
    /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */
    data = 2;
}

CWE190_Integer_Overflow__int_max_add_84_goodG2B::~CWE190_Integer_Overflow__int_max_add_84_goodG2B()
{
    {
        /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */
        int result = data + 1;
        printIntLine(result);
    }
}
}
#endif /* OMITGOOD */


text:
package com.prade.service.impl;

import com.prade.model.User;
import com.prade.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
 * Created by fan.jin on 2016-10-31.
 */

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return user;
        }
    }
}


text:
package Sisimai::RFC3464;
use feature ':5.10';
use strict;
use warnings;
use Sisimai::Lhost;

# http://tools.ietf.org/html/rfc3464
sub description { 'Fallback Module for MTAs' };
sub make {
    # Detect an error for RFC3464
    # @param    [Hash] mhead    Message headers of a bounce email
    # @param    [String] mbody  Message body of a bounce email
    # @return   [Hash]          Bounce data list and message/rfc822 part
    # @return   [Undef]         failed to parse or the arguments are missing
    my $class = shift;
    my $mhead = shift // return undef;
    my $mbody = shift // return undef;
    my $match = 0;

    return undef unless keys %$mhead;
    return undef unless ref $mbody eq 'SCALAR';

    state $indicators = Sisimai::Lhost->INDICATORS;
    state $markingsof = {
        'command' => qr/[ ](RCPT|MAIL|DATA)[ ]+command\b/,
        'message' => qr{\A(?>
             content-type:[ ]*(?:
                  message/x?delivery-status
                 |message/disposition-notification
                 |text/plain;[ ]charset=
                 )
            |the[ ]original[ ]message[ ]was[ ]received[ ]at[ ]
            |this[ ]report[ ]relates[ ]to[ ]your[ ]message
            |your[ ]message[ ](?:
                could[ ]not[ ]be[ ]delivered
               |was[ ]not[ ]delivered[ ]to[ ]the[ ]following[ ]recipients
               )
            )
        }x,
        'error'  => qr/\A(?:[45]\d\d[ \t]+|[<][^@]+[@][^@]+[>]:?[ \t]+)/,
        'rfc822' => qr{\A(?>
             content-type:[ ]*(?:message/rfc822|text/rfc822-headers)
            |return-path:[ ]*[<].+[>]
            )\z
        }x,
    };

    my $dscontents = [Sisimai::Lhost->DELIVERYSTATUS];
    my $rfc822text = '';    # (String) message/rfc822 part text
    my $maybealias = '';    # (String) Original-Recipient field
    my $blanklines = 0;     # (Integer) The number of blank lines
    my $readcursor = 0;     # (Integer) Points the current cursor position
    my $recipients = 0;     # (Integer) The number of 'Final-Recipient' header
    my $itisbounce = 0;     # (Integer) Flag for that an email is a bounce
    my $connheader = {
        'date'    => '',    # The value of Arrival-Date header
        'rhost'   => '',    # The value of Reporting-MTA header
        'lhost'   => '',    # The value of Received-From-MTA header
    };
    my $v = undef;
    my $p = '';

    for my $e ( split("\n", $$mbody) ) {
        # Read each line between the start of the message and the start of rfc822 part.
        my $d = lc $e;
        unless( $readcursor ) {
            # Beginning of the bounce message or message/delivery-status part
            if( $d =~ $markingsof->{'message'} ) {
                $readcursor |= $indicators->{'deliverystatus'};
                next;
            }
        }

        unless( $readcursor & $indicators->{'message-rfc822'} ) {
            # Beginning of the original message part(message/rfc822)
            if( $d =~ $markingsof->{'rfc822'} ) {
                $readcursor |= $indicators->{'message-rfc822'};
                next;
            }
        }

        if( $readcursor & $indicators->{'message-rfc822'} ) {
            # message/rfc822 OR text/rfc822-headers part
            unless( length $e ) {
                last if ++$blanklines > 1;
                next;
            }
            $rfc822text .= sprintf("%s\n", $e);

        } else {
            # message/delivery-status part
            next unless $readcursor & $indicators->{'deliverystatus'};
            next unless length $e;

            $v = $dscontents->[-1];
            if( $e =~ /\A(Original|Final)-[Rr]ecipient:[ ]*.+;[ ]*([^ ]+)\z/ ) {
                # 2.3.2 Final-Recipient field
                #   The Final-Recipient field indicates the recipient for which this set
                #   of per-recipient fields applies.  This field MUST be present in each
                #   set of per-recipient data.
                #   The syntax of the field is as follows:
                #
                #       final-recipient-field =
                #           "Final-Recipient" ":" address-type ";" generic-address
                #
                # 2.3.1 Original-Recipient field
                #   The Original-Recipient field indicates the original recipient address
                #   as specified by the sender of the message for which the DSN is being
                #   issued.
                #
                #       original-recipient-field =
                #           "Original-Recipient" ":" address-type ";" generic-address
                #
                #       generic-address = *text
                if( $1 eq 'Original' ) {
                    # Original-Recipient: ...
                    $maybealias = $2;

                } else {
                    # Final-Recipient: ...
                    my $x = $v->{'recipient'} || '';
                    my $y = Sisimai::Address->s3s4($2);
                       $y = $maybealias unless Sisimai::RFC5322->is_emailaddress($y);

                    if( $x && $x ne $y ) {
                        # There are multiple recipient addresses in the message body.
                        push @$dscontents, Sisimai::Lhost->DELIVERYSTATUS;
                        $v = $dscontents->[-1];
                    }
                    $v->{'recipient'} = $y;
                    $recipients++;
                    $itisbounce ||= 1;

                    $v->{'alias'} ||= $maybealias;
                    $maybealias = '';
                }
            } elsif( $e =~ /\AX-Actual-Recipient:[ ]*(?:RFC|rfc)822;[ ]*([^ ]+)\z/ ) {
                # X-Actual-Recipient: RFC822; |IFS=' ' && exec procmail -f- || exit 75 ...
                # X-Actual-Recipient: rfc822; kijitora@neko.example.jp
                $v->{'alias'} = $1 unless $1 =~ /[ \t]+/;

            } elsif( $e =~ /\AAction:[ ]*(.+)\z/ ) {
                # 2.3.3 Action field
                #   The Action field indicates the action performed by the Reporting-MTA
                #   as a result of its attempt to deliver the message to this recipient
                #   address.  This field MUST be present for each recipient named in the
                #   DSN.
                #   The syntax for the action-field is:
                #
                #       action-field = "Action" ":" action-value
                #       action-value =
                #           "failed" / "delayed" / "delivered" / "relayed" / "expanded"
                #
                #   The action-value may be spelled in any combination of upper and lower
                #   case characters.
                $v->{'action'} = lc $1;
                $v->{'action'} = $1 if $v->{'action'} =~ /\A([^ ]+)[ ]/; # failed (bad destination mailbox address)

            } elsif( $e =~ /\AStatus:[ ]*(\d[.]\d+[.]\d+)/ ) {
                # 2.3.4 Status field
                #   The per-recipient Status field contains a transport-independent
                #   status code that indicates the delivery status of the message to that
                #   recipient.  This field MUST be present for each delivery attempt
                #   which is described by a DSN.
                #
                #   The syntax of the status field is:
                #
                #       status-field = "Status" ":" status-code
                #       status-code = DIGIT "." 1*3DIGIT "." 1*3DIGIT
                $v->{'status'} = $1;

            } elsif( $e =~ /\AStatus:[ ]*(\d+[ ]+.+)\z/ ) {
                # Status: 553 Exceeded maximum inbound message size
                $v->{'alterrors'} = $1;

            } elsif( $e =~ /Remote-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/ ) {
                # 2.3.5 Remote-MTA field
                #   The value associated with the Remote-MTA DSN field is a printable
                #   ASCII representation of the name of the "remote" MTA that reported
                #   delivery status to the "reporting" MTA.
                #
                #       remote-mta-field = "Remote-MTA" ":" mta-name-type ";" mta-name
                #
                #   NOTE: The Remote-MTA field preserves the "while talking to"
                #   information that was provided in some pre-existing nondelivery
                #   reports.
                #
                #   This field is optional.  It MUST NOT be included if no remote MTA was
                #   involved in the attempted delivery of the message to that recipient.
                $v->{'rhost'} = lc $1;

            } elsif( $e =~ /\ALast-Attempt-Date:[ ]*(.+)\z/ ) {
                # 2.3.7 Last-Attempt-Date field
                #   The Last-Attempt-Date field gives the date and time of the last
                #   attempt to relay, gateway, or deliver the message (whether successful
                #   or unsuccessful) by the Reporting MTA.  This is not necessarily the
                #   same as the value of the Date field from the header of the message
                #   used to transmit this delivery status notification: In cases where
                #   the DSN was generated by a gateway, the Date field in the message
                #   header contains the time the DSN was sent by the gateway and the DSN
                #   Last-Attempt-Date field contains the time the last delivery attempt
                #   occurred.
                #
                #       last-attempt-date-field = "Last-Attempt-Date" ":" date-time
                $v->{'date'} = $1;

            } else {
                if( $e =~ /\ADiagnostic-Code:[ ]*(.+?);[ ]*(.+)\z/ ) {
                    # 2.3.6 Diagnostic-Code field
                    #   For a "failed" or "delayed" recipient, the Diagnostic-Code DSN field
                    #   contains the actual diagnostic code issued by the mail transport.
                    #   Since such codes vary from one mail transport to another, the
                    #   diagnostic-type sub-field is needed to specify which type of
                    #   diagnostic code is represented.
                    #
                    #       diagnostic-code-field =
                    #           "Diagnostic-Code" ":" diagnostic-type ";" *text
                    $v->{'spec'} = uc $1;
                    $v->{'diagnosis'} = $2;

                } elsif( $e =~ /\ADiagnostic-Code:[ ]*(.+)\z/ ) {
                    # No value of "diagnostic-type"
                    # Diagnostic-Code: 554 ...
                    $v->{'diagnosis'} = $1;

                } elsif( index($p, 'Diagnostic-Code:') == 0 && $e =~ /\A[ \t]+(.+)\z/ ) {
                    # Continued line of the value of Diagnostic-Code header
                    $v->{'diagnosis'} .= ' '.$1;
                    $e = 'Diagnostic-Code: '.$e;

                } else {
                    if( $e =~ /\AReporting-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/ ) {
                        # 2.2.2 The Reporting-MTA DSN field
                        #
                        #       reporting-mta-field =
                        #           "Reporting-MTA" ":" mta-name-type ";" mta-name
                        #       mta-name = *text
                        #
                        #   The Reporting-MTA field is defined as follows:
                        #
                        #   A DSN describes the results of attempts to deliver, relay, or gateway
                        #   a message to one or more recipients.  In all cases, the Reporting-MTA
                        #   is the MTA that attempted to perform the delivery, relay, or gateway
                        #   operation described in the DSN.  This field is required.
                        $connheader->{'rhost'} ||= lc $1;

                    } elsif( $e =~ /\AReceived-From-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/ ) {
                        # 2.2.4 The Received-From-MTA DSN field
                        #   The optional Received-From-MTA field indicates the name of the MTA
                        #   from which the message was received.
                        #
                        #       received-from-mta-field =
                        #           "Received-From-MTA" ":" mta-name-type ";" mta-name
                        #
                        #   If the message was received from an Internet host via SMTP, the
                        #   contents of the mta-name sub-field SHOULD be the Internet domain name
                        #   supplied in the HELO or EHLO command, and the network address used by
                        #   the SMTP client SHOULD be included as a comment enclosed in
                        #   parentheses.  (In this case, the MTA-name-type will be "dns".)
                        $connheader->{'lhost'} = lc $1;

                    } elsif( $e =~ /\AArrival-Date:[ ]*(.+)\z/ ) {
                        # 2.2.5 The Arrival-Date DSN field
                        #   The optional Arrival-Date field indicates the date and time at which
                        #   the message arrived at the Reporting MTA.  If the Last-Attempt-Date
                        #   field is also provided in a per-recipient field, this can be used to
                        #   determine the interval between when the message arrived at the
                        #   Reporting MTA and when the report was issued for that recipient.
                        #
                        #       arrival-date-field = "Arrival-Date" ":" date-time
                        $connheader->{'date'} = $1;

                    } else {
                        # Get error message
                        next if $e =~ /\A[ -]+/;
                        next unless $e =~ $markingsof->{'error'};

                        # 500 User Unknown
                        # <kijitora@example.jp> Unknown
                        $v->{'alterrors'} .= ' '.$e;
                    }
                }
            }
        } # End of message/delivery-status
    } continue {
        # Save the current line for the next loop
        $p = $e;
    }

    BODY_PARSER_FOR_FALLBACK: {
        # Fallback, parse entire message body
        last if $recipients;

        # Failed to get a recipient address at code above
        $match ||= 1 if lc($mhead->{'from'}) =~ /\b(?:postmaster|mailer-daemon|root)[@]/;
        $match ||= 1 if lc($mhead->{'subject'}) =~ qr{(?>
             delivery[ ](?:failed|failure|report)
            |failure[ ]notice
            |mail[ ](?:delivery|error)
            |non[-]delivery
            |returned[ ]mail
            |undeliverable[ ]mail
            |warning:[ ]
            )
        }x;
        if( defined $mhead->{'return-path'} ) {
            # Check the value of Return-Path of the message
            $match ||= 1 if lc($mhead->{'return-path'}) =~ /(?:[<][>]|mailer-daemon)/;
        }
        last unless $match;

        state $re_skip = qr{(?>
             \A[-]+=
            |\A\s+\z
            |\A\s*--
            |\A\s+[=]\d+
            |\Ahi[ ][!]
            |content-(?:description|disposition|transfer-encoding|type):[ ]
            |(?:name|charset)=
            |--\z
            |:[ ]--------
            )
        }x;
        state $re_stop  = qr{(?:
             \A[*][*][*][ ].+[ ].+[ ][*][*][*]
            |\Acontent-type:[ ]message/delivery-status
            |\Ahere[ ]is[ ]a[ ]copy[ ]of[ ]the[ ]first[ ]part[ ]of[ ]the[ ]message
            |\Athe[ ]non-delivered[ ]message[ ]is[ ]attached[ ]to[ ]this[ ]message.
            |\Areceived:[ \t]*
            |\Areceived-from-mta:[ \t]*
            |\Areporting-mta:[ \t]*
            |\Areturn-path:[ \t]*
            |\Aa[ ]copy[ ]of[ ]the[ ]original[ ]message[ ]below[ ]this[ ]line:
            |attachment[ ]is[ ]a[ ]copy[ ]of[ ]the[ ]message
            |below[ ]is[ ]a[ ]copy[ ]of[ ]the[ ]original[ ]message:
            |below[ ]this[ ]line[ ]is[ ]a[ ]copy[ ]of[ ]the[ ]message
            |message[ ]contains[ ].+[ ]file[ ]attachments
            |message[ ]text[ ]follows:[ ]
            |original[ ]message[ ]follows
            |the[ ]attachment[ ]contains[ ]the[ ]original[ ]mail[ ]headers
            |the[ ]first[ ]\d+[ ]lines[ ]
            |unsent[ ]message[ ]below
            |your[ ]message[ ]reads[ ][(]in[ ]part[)]:
            )
        }x;
        state $re_addr = qr{(?:
             \A\s*
            |\A["].+["]\s*
            |\A[ \t]*recipient:[ \t]*
            |\A[ ]*address:[ ]
            |addressed[ ]to[ ]
            |could[ ]not[ ]be[ ]delivered[ ]to:[ ]
            |delivered[ ]to[ ]+
            |delivery[ ]failed:[ ]
            |did[ ]not[ ]reach[ ]the[ ]following[ ]recipient:[ ]
            |error-for:[ ]+
            |failed[ ]recipient:[ ]
            |failed[ ]to[ ]deliver[ ]to[ ]
            |intended[ ]recipient:[ ]
            |mailbox[ ]is[ ]full:[ ]
            |rcpt[ ]to:
            |smtp[ ]server[ ][<].+[>][ ]rejected[ ]recipient[ ]
            |the[ ]following[ ]recipients[ ]returned[ ]permanent[ ]errors:[ ]
            |the[ ]following[ ]message[ ]to[ ]
            |unknown[ ]User:[ ]
            |undeliverable[ ]to[ ]
            |undeliverable[ ]address:[ ]*
            |you[ ]sent[ ]mail[ ]to[ ]
            |your[ ]message[ ]to[ ]
            )
            ['"]?[<]?([^\s\n\r@=<>]+[@][-.0-9a-z]+[.][0-9a-z]+)[>]?['"]?
        }x;

        my $b = $dscontents->[-1];
        for my $e ( split("\n", $$mbody) ) {
            # Get the recipient's email address and error messages.
            my $d = lc $e;
            last if $d =~ $markingsof->{'rfc822'};
            last if $d =~ $re_stop;

            next unless length $e;
            next if $d =~ $re_skip;
            next if index($e, '*') == 0;

            if( $d =~ $re_addr ) {
                # May be an email address
                my $x = $b->{'recipient'} || '';
                my $y = Sisimai::Address->s3s4($1);
                next unless Sisimai::RFC5322->is_emailaddress($y);

                if( $x && $x ne $y ) {
                    # There are multiple recipient addresses in the message body.
                    push @$dscontents, Sisimai::Lhost->DELIVERYSTATUS;
                    $b = $dscontents->[-1];
                }
                $b->{'recipient'} = $y;
                $recipients++;
                $itisbounce ||= 1;

            } elsif( $e =~ /[(](?:expanded|generated)[ ]from:?[ ]([^@]+[@][^@]+)[)]/ ) {
                # (expanded from: neko@example.jp)
                $b->{'alias'} = Sisimai::Address->s3s4($1);
            }
            $b->{'diagnosis'} .= ' '.$e;
        }
    } # END OF BODY_PARSER_FOR_FALLBACK
    return undef unless $itisbounce;

    if( $recipients == 0 && $rfc822text =~ /^To:[ ]*(.+)/m ) {
        # Try to get a recipient address from "To:" header of the original message
        if( my $r = Sisimai::Address->find($1, 1) ) {
            # Found a recipient address
            push @$dscontents, Sisimai::Lhost->DELIVERYSTATUS if scalar(@$dscontents) == $recipients;
            my $b = $dscontents->[-1];
            $b->{'recipient'} = $r->[0]->{'address'};
            $recipients++;
        }
    }
    return undef unless $recipients;

    require Sisimai::MDA;
    my $mdabounced = Sisimai::MDA->make($mhead, $mbody);
    for my $e ( @$dscontents ) {
        # Set default values if each value is empty.
        $e->{ $_ } ||= $connheader->{ $_ } || '' for keys %$connheader;

        if( exists $e->{'alterrors'} && $e->{'alterrors'} ) {
            # Copy alternative error message
            $e->{'diagnosis'} ||= $e->{'alterrors'};
            if( index($e->{'diagnosis'}, '-') == 0 || substr($e->{'diagnosis'}, -2, 2) eq '__') {
                # Override the value of diagnostic code message
                $e->{'diagnosis'} = $e->{'alterrors'} if $e->{'alterrors'};
            }
            delete $e->{'alterrors'};
        }
        $e->{'diagnosis'} = Sisimai::String->sweep($e->{'diagnosis'});

        if( $mdabounced ) {
            # Make bounce data by the values returned from Sisimai::MDA->make()
            $e->{'agent'}     = $mdabounced->{'mda'} || 'RFC3464';
            $e->{'reason'}    = $mdabounced->{'reason'} || 'undefined';
            $e->{'diagnosis'} = $mdabounced->{'message'} if $mdabounced->{'message'};
            $e->{'command'}   = '';
        }
        $e->{'date'}   ||= $mhead->{'date'};
        $e->{'status'} ||= Sisimai::SMTP::Status->find($e->{'diagnosis'}) || '';
        $e->{'command'}  = $1 if $e->{'diagnosis'} =~ $markingsof->{'command'};
    }
    return { 'ds' => $dscontents, 'rfc822' => $rfc822text };
}

1;
__END__
=encoding utf-8

=head1 NAME

Sisimai::RFC3464 - bounce mail parser class for Fallback.

=head1 SYNOPSIS

    use Sisimai::RFC3464;

=head1 DESCRIPTION

Sisimai::RFC3464 is a class which called from called from only Sisimai::Message
when other Sisimai::Lhost::* modules did not detected a bounce reason.

=head1 CLASS METHODS

=head2 C<B<description()>>

C<description()> returns description string of this module.

    print Sisimai::RFC3464->description;

=head2 C<B<make(I<header data>, I<reference to body string>)>>

C<make()> method parses a bounced email and return results as a array reference.
See Sisimai::Message for more details.

=head1 AUTHOR

azumakuniyuki

=head1 COPYRIGHT

Copyright (C) 2014-2020 azumakuniyuki, All rights reserved.

=head1 LICENSE

This software is distributed under The BSD 2-Clause License.

=cut


text:
package com.google.api.gbase.client;

import com.google.gdata.util.common.xml.XmlWriter;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.PubControl;
import com.google.gdata.data.extensions.FeedLink;
import com.google.gdata.data.media.mediarss.MediaContent;
import com.google.gdata.data.media.mediarss.MediaThumbnail;

/**
 * Constants for GoogleBase-specific namespaces.
 */
class GoogleBaseNamespaces {

  /**
   * URI of the gm: namespace.
   */
  public static final String GM_URI = "http://base.google.com/ns-metadata/1.0";

  /**
   * URI of the g: namespace.
   */
  public static final String G_URI = "http://base.google.com/ns/1.0";

  /**
   * Default prefix for the gm: namespace.
   */
  public static final String GM_ALIAS = "gm";

  /**
   * The Google Base gm: namespace used in metadata entries
   */
  public static final XmlWriter.Namespace GM =
      new XmlWriter.Namespace(GM_ALIAS, GM_URI);

  /**
   * Default prefix for the g: namespace.
   */
  public static final String G_ALIAS = "g";

  /**
   * The Google Base g: namespace used for attributes.
   */
  public static final XmlWriter.Namespace G =
      new XmlWriter.Namespace(G_ALIAS, G_URI);

  /**
   * Declares both g: and gm: extensions into the extension profile.
   *
   * @param extProfile extension profile
   */
  public static void declareAllExtensions(ExtensionProfile extProfile) {
    declareGExtensions(extProfile);
    declareGMExtensions(extProfile);
    declareMediaExtensions(extProfile);
  }

  /**
   * Declares the g: extension into the extension profile, both for feeds
   * and for entries.
   *
   * @param extProfile extension profile
   */
  public static void declareGExtensions(ExtensionProfile extProfile) {
    extProfile.declareEntryExtension(GoogleBaseAttributesExtension.DESCRIPTION);
    extProfile.declareFeedExtension(GoogleBaseAttributesExtension.DESCRIPTION);

    ExtensionDescription feedLinkExtDesc =
        ExtensionDescription.getDefaultDescription(FeedLink.class);
    feedLinkExtDesc.setRepeatable(true);
    extProfile.declare(GoogleBaseEntry.class, feedLinkExtDesc);
  }

  /**
   * Declares all gm: extensions into the extension profile.
   *
   * @param extProfile extension profile
   */
  public static void declareGMExtensions(ExtensionProfile extProfile) {
    extProfile.declareEntryExtension(Stats.class);
    extProfile.declareEntryExtension(AttributeHistogram.class);
    extProfile.declareEntryExtension(GmAttributes.class);
    extProfile.declareEntryExtension(GmItemType.class);
    extProfile.declare(PubControl.class, GmDisapproved.getDefaultDescription());
    extProfile.declare(PubControl.class,
        GmPublishingPriority.getDefaultDescription());
  }

  public static void declareMediaExtensions(ExtensionProfile extProfile) {
    extProfile.declare(GoogleBaseMediaEntry.class, MediaContent.class);
    extProfile.declare(MediaContent.class, MediaThumbnail.class);
  }
}


text:
<?php

namespace Steelbot\Protocol\Telegram;

use Steelbot\ClientInterface;

/**
 * Class Client
 */
class Client implements ClientInterface
{
    private $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getId();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright 2015 Yunus Emre Şeker. All rights reserved.
  ~
  ~ 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.
  -->

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cancel_row_card"
    style="@style/CardViewStyle">

    <android.support.v7.widget.AppCompatCheckBox
        android:id="@+id/cancel_row_checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</android.support.v7.widget.CardView>


text:
Invoice

				Invoice page has no additional elements or classes and is basically a widget box with a table.

				.invoice-info and .invoice-info-label elements
				are inside invoice widget header:

       Customer Invoice

       Invoice:
       #121212

       Date:
       04/04/2014

 ...


text:
You come upon a factory in which many robots are [zooming around] handing small microchips to each other. Upon closer examination, you notice that each bot only proceeds when it has **two** microchips, and once it does, it gives each one to a different bot or puts it in a marked "output" bin. Sometimes, bots take microchips from "input" bins, too.

Inspecting one of the microchips, it seems like they each contain a single number; the bots must use some logic to decide what to do with each chip. You access the local control computer and download the bots' instructions (i.e., `input10.txt`).

Some of the instructions indicate that a specific-valued microchip should be given to a specific bot; the rest of the instructions indicate what a given bot should do with its **lower-value** or **higher-value** chip.

**For example:**

value 5 goes to bot 2
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
bot 1 gives low to output 1 and high to bot 0
bot 0 gives low to output 2 and high to output 0
value 2 goes to bot 2

Considering the instructions above,
- Initially, `bot 1` starts with a value-3 chip, and `bot 2` starts with a value-2 chip and a value-5 chip.
- Because `bot 2` has two microchips, it gives its lower one (i.e., `2`) to `bot 1` and its higher one (i.e., `5`) to `bot 0`.
- Then, `bot 1` has two microchips; it puts the value-2 chip in `output 1` and gives the value-3 chip to `bot 0`.
- Finally, `bot 0` has two microchips; it puts the `3` in `output 2` and the `5` in `output 0`.

In the end, bin `output 0` contains a value-5 microchip, bin `output 1` contains a value-2 microchip, and bin `output 2` contains a value-3 microchip. In this configuration, bot number `2` is responsible for comparing value-5 microchips with value-2 microchips.

Based on the instructions in `input10.txt`, _**what is the number of the bot** that is responsible for comparing value-61 microchips with value-17 microchips?_

### Part 2
What do you get if you multiply together the values of one chip in each of outputs 0, 1, and 2?

## Advent of Code Credits

**Design \& Code:** [Eric Wastl]

**Beta Testing:** [Tim Giannetti] and Ben Lucek

**Community Managers:** [Danielle Lucek] and [Aneurysm9]

**Playing:** My implemented solution to the problem, ©2017 under the [MIT license]

## My Approach to the Problem
The program reads the input file line-by-line into a vector of strings. This vector is passed to a BotNetwork object to parse each instruction. For `value X goes to bot Y` type instructions, pairs containing a microchip input bin and a bot number added to a vector. For `bot X gives low to TYPE Y and high to TYPE Z` type instructions, each bot number is used as a key to store the bot's microchip outputs (i.e., bot/output bin and number) in a hashmap.

Following this, the BotNetwork object uses the input bin vector to give microchips to each bot taking one from an input bin. After finding the bot which takes two microchips from input bins, the microchips are propagated through the network by recursively passing pairs of microchips to each of their outputs until they end up in an output bin.

To solve the first part with two given microchips, the input bin for the low value microchip is first found in the input bin vector. Starting from the bot associated with the input bin found, the output matching the low value microchip is recursively searched until a bot holding both microchips is found. This returns the answer for the first part.

To solve the second part, the output bins are placed in a hashmap with their microchip when the bots recursively pass microchips through the network. Thus, the output bins can be used as keys to retrieve their corresponding microchip. Retrieving these for the different output bins and multiplying them provides the answer to the second part.

### Required Tools:
- Make build automation tool
- C++11 compiler such as [g++] or eqivalent

### Program Compilation:

$ make

### Program Execution:

$ ./AoC_10.exe input10.txt
Advent of Code, Day 10: Balance Bots
Part 1: What is the number of the bot that is responsible for comparing
value-61 microchips with value-17 microchips?
  The number of the bot comparing value-61 microchips with value-17 microchips
  is 116
What do you get if you multiply together the values of one microchip in each
of output bins 0, 1, and 2?
  Output bin 0 is for value-53 microchips
  Output bin 1 is for value-41 microchips
  Output bin 2 is for value-11 microchips
  Multiplying 53, 41, and 11 gives an answer of 23903

### Notes \& Assumptions:
- The instruction file contains no blank lines or ill-formed instructions
- Every bot compares a single pair of microchips
- Every microchip from an input bin is unique and has a single corresponding output bin
- Only a single bot gets both of its microchips from input bins
- All microchips values and bots numbers are non-negative integers

[Day 10: Balance Bots]: http://adventofcode.com/2016/day/10
[zooming around]: http://www.youtube.com/watch?v=JnkMyfQ5YfY&t=40
[Eric Wastl]: http://twitter.com/ericwastl
[Tim Giannetti]: http://twitter.com/Sr_Giannetti
[Danielle Lucek]: http://www.reddit.com/user/daggerdragon
[Aneurysm9]: http://twitter.com/Aneurysm9
[MIT license]: http://www.opensource.org/licenses/mit-license.php
[g++]: http://gcc.gnu.org/


text:
package org.elasticsearch.xpack.core.security.action.role;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;

import java.io.IOException;

/**
 * A response for the {@code Get Roles} API that holds the retrieved role descriptors.
 */
public class GetRolesResponse extends ActionResponse {

    private RoleDescriptor[] roles;

    public GetRolesResponse(StreamInput in) throws IOException {
        super(in);
        int size = in.readVInt();
        roles = new RoleDescriptor[size];
        for (int i = 0; i < size; i++) {
            roles[i] = new RoleDescriptor(in);
        }
    }

    public GetRolesResponse(RoleDescriptor... roles) {
        this.roles = roles;
    }

    public RoleDescriptor[] roles() {
        return roles;
    }

    public boolean hasRoles() {
        return roles.length > 0;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVInt(roles.length);
        for (RoleDescriptor role : roles) {
            role.writeTo(out);
        }
    }
}


text:
package net.m_kawato.tabletpos;

import java.io.File;
import java.util.List;

import android.R.drawable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class StockListAdapter extends BaseAdapter {
    private static final String TAG = "StockListAdapter";
    private Stock stockActivity;
    private List<Product> stockList;

    public StockListAdapter(Stock stockActivity, List<Product> stockList) {
        this.stockActivity = stockActivity;
        this.stockList = stockList;
    }

    @Override
    public int getCount() {
        return this.stockList.size();
    }

    @Override
    public Object getItem(int position) {
        return this.stockList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) this.stockActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.stock_item, null);
        }
        Product p = this.stockList.get(position);
        TextView productNameView = (TextView) view.findViewById(R.id.product_name);
        productNameView.setText(String.format("%d, %s", p.productId, p.productName));
        String imgFilePath =
                String.format("%s/%s/%s-%d.jpg",
                Globals.SDCARD_DIRNAME,
                Globals.IMAGE_DIRNAME,
                Globals.PRODUCT_IMAGE_PREFIX,
                p.productId);
        File imgFile = new File(Environment.getExternalStorageDirectory(), imgFilePath);
        ImageView imageView = (ImageView) view.findViewById(R.id.image);
        if (imgFile.canRead()) {
            Log.d(TAG, "image file = " + imgFile.toString());
            Bitmap bm = BitmapFactory.decodeFile(imgFile.getPath());
            imageView.setImageBitmap(bm);
        } else {
            imageView.setImageResource(drawable.ic_menu_gallery);
        }

        EditText stockView = (EditText) view.findViewById(R.id.stock);
        stockView.setText(Integer.toString(p.stock));
        stockView.setTag(position);
        stockView.setOnEditorActionListener(this.stockActivity);
        stockView.setOnFocusChangeListener(this.stockActivity);
        Button buttonView = (Button) view.findViewById(R.id.btn_update_stock);
        buttonView.setOnClickListener(this.stockActivity);
        return view;
    }

}


text:
```
Usage: jagen image <command> <options...>

  Manages filesystem images.

COMMANDS

  create  Create images

  The 'create' command creates filesystem images according to configuration.
  Currently the only possible command is:

    jagen image create rootfs

  in 'hi-linux' build root which creates rootfs image.
```


text:
@interface PodsDummy_Blabber : NSObject
@end
@implementation PodsDummy_Blabber
@end


text:
from flask import Flask, request, jsonify
import kociemba
import requests
import json

app = Flask(__name__)

#Command to send the information to this server:
#curl -i -H "Content-Type: application/json" -X POST -d '{"configuration":"DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD"}' http://10.1.7.18:5000/solver

@app.route('/solver', methods=['POST'])
def generate_orders():
  if not request.json or not 'configuration' in request.json:
    abort(400)

  result = kociemba.solve(request.json['configuration'])
  solution = {
    'CubeToSolve': request.json['configuration'],
    'sol': result
  }

  #Command to send the information to the next server:
  headers = {'content-type': 'application/json'}
  url = 'http://10.1.7.20:5000/control'
  data = {'solution':result}
  requests.post(url, data=json.dumps(data), headers=headers)

  return jsonify({'solution':solution}), 201

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


text:
layout: redirect
locale: es
permalink: /es/home/
---


text:
/**
 * Holds the current bounding volume factory {@link Grape2D.BVFactory}
 *
 * @class
 */
Grape2D.BVFactorySingleton = {
	/**
	 * Factory being used.
	 *
	 * @type {!Grape2D.BVFactory}
	 * @private
	 * @static
	 */
	bvfactory: new Grape2D.AabbBVFactory(),
	/**
	 * Gets the factory
	 *
	 * @return {!Grape2D.BVFactory} A bounding volume factory instance.
	 * @public
	 * @static
	 */
	getFactory: function(){
		return Grape2D.BVFactorySingleton.bvfactory;
	},
	/**
	 * Sets the factory
	 *
	 * @param  {!Grape2D.BVFactory} factory A bounding volume factory
	 *   instance.
	 * @public
	 * @static
	 */
	setFactory: function(factory){
		Grape2D.BVFactorySingleton.bvfactory = factory;
	},
	/**
	 * Sintax sugar for shape.createBV(Grape2D.BVFactorySingleton.getFactory()).
	 *
	 * @param  {!Grape2D.Shape} shape Shape to create a bounding volume
	 * @return {!Grape2D.Shape} Bounding volume.
	 * @public
	 * @static
	 */
	create: function(shape){
		return shape.createBV(Grape2D.BVFactorySingleton.bvfactory);
	},
	/**
	 * Returns a place holder shape, of the type of the factory.
	 *   It should only be used to avoid using null
	 *
	 * @return {!Grape2D.Shape} A shape has a place holder.
	 * @public
	 * @static
	 */
	getPlaceHolder: function(){
		return Grape2D.BVFactorySingleton.bvfactory.getPlaceHolder();
	}
};


text:
void initializeEEPROM(bool erase)
{
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_EEPROM0);
    MAP_IntDisable(INT_FLASH);
    MAP_EEPROMInit();
    if (erase)
        MAP_EEPROMMassErase();
}

// Read one word from EEPROM
uint32_t eepromRead(uint32_t address)
{
    uint32_t data;
    MAP_EEPROMRead(&data, address, 4U);
    return data;
}

// Write one word to EEPROM
void eepromWrite(uint32_t address, uint32_t *data)
{
    feedWatchdog();
    MAP_EEPROMProgram(data, address, 4U);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Contr. biol. Lab. Sci. Soc. China Bot. 20: (1889)

#### Original name
Epichloea divisa Giard

### Remarks
null


text:
"""
A script that adds claims to Wikidata items based on a tab-separated table of values

It is heavily influenced by claimit.py.
------------------------------------------------------------------------------

Usage:

    python pwb.py tsv_claims -tsv <tsvFile>

Where
<tsvFile> is a tab-delimited file in this format:
<Q-number> [<P-number> <Value>]+

Where:
<Q-number> := "Q[0-9]+", referring to an existing WD item
<P-number> := "P[0-0]+", referring to an existing WD property
<Value> := "{<coord>|<date>|<quantity>}[@<sourceP>:<sourceQ>]"  is a specification for a value for <P-number>, with optional source specification
<sourceP> is the P-number like P143 (imported From)
<sourceQ> is a Q-number like Q465 (DBpedia)
<coord> :=  see 'geographic coordinates', below
<date> := [watch this space]
<quantity> := "<number>:<units of measure Q>"
<units of measure Q> is the Q-number of a unit of measure such as Q25343 (sq. meters)

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

For geographic coordinates:

    <Q number> P625 [lat-dec],[long-dec],[prec]

[lat-dec] and [long-dec] represent the latitude and longitude respectively,
and [prec] represents the precision. All values are in decimal degrees,
not DMS. If [prec] is omitted, the default precision is 0.0001 degrees.

Example:

    <Q number> P625 -23.3991,-52.0910,0.0001@P143:Q465

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

By default, tsv_claims.py does not add a claim if one with the same property
already exists on the page. To override this behavior, use the 'exists' option:

     <some item>  P246 "string example" -exists:p

Suppose the claim you want to add has the same property as an existing claim
and the "-exists:p" argument is used. Now, tsv_claims.py will not add the claim
if it has the same target, sources, and/or qualifiers as the existing claim.
To override this behavior, add 't' (target), 's' (sources), or 'q' (qualifiers)
to the 'exists' argument.

For instance, to add the claim to each page even if one with the same
property, target, and qualifiers already exists:

    <Q-number>  P246 "string example" -exists:ptq

Note that the ordering of the letters in the 'exists' argument does not matter,
but 'p' must be included.

"""
# NOTE: this code owes heavily to 'claimit.py'
# by Legoktm, 2013 and
# Pywikibot team, 2013-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

#__version__ = '$Id: cd2993cb637ec639aee276f8458aa6d03078f7dd $'
#
import codecs
import pywikibot
from pywikibot import pagegenerators, WikidataBot, config

# This is required for the text that is shown when you run this script
# with the parameter -help or without parameters.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp,
}

import sys
def trace (s):
    try:
        sys.stderr.write ("tsv_claims.py:%s\n" % s)
    except Exception:
        pass

class TsvClaimRobot(WikidataBot):

    """A bot to add Wikidata claims."""

    def __init__(self, generator, item_to_claim_to_source, exists_arg=''):
        """
        Constructor.

        Arguments:
            * generator    - A tsv generator G =yield=> [<page>, ...]
            * item_to_claim_to_source {<q number> {<claim> : <source claim>, ...}, ...}
            * exists_arg   - String specifying how to handle duplicate claims

         Where
        <page> is an instance of Page.
        <claim> is an instance of Claim.
        <source claim> is a claim with a predicate like P143 (imported from)
          and a target derived from something like Q465 (DBpedia).
        """
        super(TsvClaimRobot, self).__init__(use_from_page=None)
        self.generator = generator
        self.exists_arg = exists_arg
        self.item_to_claim_to_source = item_to_claim_to_source
        self.cacheSources()
        if self.exists_arg:
            pywikibot.output('\'exists\' argument set to \'%s\'' % self.exists_arg)

    def treat(self, page, item):
        """Treat each page."""
        self.current_page = page

        if item:
            q_number = item.getID()

            for claim in self.item_to_claim_to_source[q_number].keys():
                skip = False
                # If claim with same property already exists...
                if claim.getID() in item.claims:
                    if self.exists_arg is None or 'p' not in self.exists_arg:
                        pywikibot.log(
                            'Skipping %s because claim with same property '
                            'already exists' % (claim.getID(),))
                        pywikibot.log(
                            'Use -exists:p option to override this behavior')
                        skip = True
                    else:
                        # Existing claims on page of same property
                        existing_claims = item.claims[claim.getID()]
                        for existing in existing_claims:
                            skip = True  # Default value
                            # If some attribute of the claim being added
                            # matches some attribute in an existing claim of
                            # the same property, skip the claim, unless the
                            # 'exists' argument overrides it.
                            if (claim.getTarget() == existing.getTarget() and
                                    't' not in self.exists_arg):
                                pywikibot.log(
                                    'Skipping %s because claim with same target already exists'
                                    % (claim.getID(),))
                                pywikibot.log(
                                    'Append \'t\' to -exists argument to override this behavior')
                                break
                            if (listsEqual(claim.getSources(), existing.getSources()) and
                                    's' not in self.exists_arg):
                                pywikibot.log(
                                    'Skipping %s because claim with same sources already exists'
                                    % (claim.getID(),))
                                pywikibot.log(
                                    'Append \'s\' to -exists argument to override this behavior')
                                break
                            if (listsEqual(claim.qualifiers, existing.qualifiers) and
                                    'q' not in self.exists_arg):
                                pywikibot.log(
                                    'Skipping %s because claim with same '
                                    'qualifiers already exists' % (claim.getID(),))
                                pywikibot.log(
                                    'Append \'q\' to -exists argument to override this behavior')
                                break
                            skip = False
                if not skip:
                    pywikibot.output('Adding %s --> %s'
                                     % (claim.getID(), claim.getTarget()))
                    item.addClaim(claim)
                    # A generator might yield pages from multiple languages
                    source = self.getSource(page.site)
                    if source:
                        claim.addSource(source, bot=True)
                    elif claim in self.item_to_claim_to_source[q_number]:
                        claim.addSource(self.item_to_claim_to_source[q_number][claim])
                    # TODO FIXME: We need to check that we aren't adding a
                    # duplicate

def listsEqual(list1, list2):
    """
    Return true if the lists are probably equal, ignoring order.

    Works for lists of unhashable items (like dictionaries).
    """
    if len(list1) != len(list2):
        return False
    if sorted(list1) != sorted(list2):
        return False
    for item in list1:
        if item not in list2:
            return False
    return True

def chunk(sequence, size):
    """
    Returns [[<firstItem>, ...<size'thItem>], ...]

    Where:
    <sequence> is a sequence of items
    <size> is the maximum size of each chunk
    """
    def chunker():
        for i in xrange(0, len(sequence), size):
            yield sequence[i:i+size]
    return list(chunker())

def parse_value_source_spec(valueSourceSpec):
    """
    Returns [<valueSpec>, <sourceSpec>]
    """
    atSplit = valueSourceSpec.split('@')
    assert (len(atSplit) < 3)
    return atSplit + ([] if len(atSplit) == 2 else [None])

def get_records (tsvFile):
    """
    Returns a generator G => [<record>, ...] parsed from <tsvFile>

    Where
    <tsvFile> is a tab-delimited text file
    <record> := [<Q>, <P1>, <V1>, <P2>, <V2>, ....]
    """
    f = codecs.open(tsvFile, 'r', config.textfile_encoding)
    linkmatch = None
    for linkmatch in pywikibot.link_regex.finditer(f.read()):
        # If the link is in interwiki format, the Page object may reside
        # on a different Site than the default.
        # This makes it possible to work on different wikis using a single
        # text file, but also could be dangerous because you might
        # inadvertently change pages on another wiki!
        raise NotImplemented()
        yield pywikibot.Page(pywikibot.Link(linkmatch.group("title"), site))
    if linkmatch is None:
        f.seek(0)
        for line in f:
            rec = map (lambda x: x.strip(), line.split ('\t'))
            yield rec
    f.close()

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    exists_arg = ''
    commandline_claims = list()

    # Process global args and prepare generator args parser
    local_args = pywikibot.handle_args(args)
    trace("Local_args:%s" % local_args)
    [arg, tsvFile] = local_args[0].split(':')
    assert tsvFile
    gen = pagegenerators.GeneratorFactory()

    for arg in local_args:
        # Handle args specifying how to handle duplicate claims
        if arg.startswith('-exists:'):
            raise NotImplemented()
            exists_arg = arg.split(':')[1].strip('"')
            continue
        # Handle page generator args
        if gen.handleArg(arg):
            trace ("Handled %s" % arg)
            continue
        commandline_claims.append(arg)

    assert not commandline_claims

    repo = pywikibot.Site().data_repository()

    assert repo

    def infer_target (claimType, valueSpec):
        # returns target appropriate to <claimType> and <valueSpec>
        # where
        # <claimType> is a <claim>.type, for some <claim>
        # <valueSpec> should be a string appropriate to <claimType>
        if claimType == 'wikibase-item':
            return pywikibot.ItemPage(repo, valueSpec)
        elif claimType == 'string':
            return propertySpec
        elif claimType == 'globe-coordinate':
            coord_args = [float(c) for c in valueSpec.split(',')]
            if len(coord_args) >= 3:
                precision = coord_args[2]
            else:
                precision = 0.0001  # Default value (~10 m at equator)
            return pywikibot.Coordinate(coord_args[0], coord_args[1], precision=precision)
        elif claimType == "quantity":
            [quantity, unitQ] = valueSpec.split(':')
            # [] TODO: check these formats
            return pywikibot.WbQuantity(quantity, unit = "http://www.wikidata.org/entity/%s" % unitQ)
        else:
            raise NotImplementedError(
                "%s datatype is not yet supported by claimit.py"
                % claimType)

    def infer_source_claim (sourceSpec):
        # returns a <source claim> to be asserted as source of the main claim
        # based on <sourceSpec>
        # where
        # <sourceSpec> is a string :~ "<sourceP>:<sourceQ>"
        [sourceP, sourceQ] = sourceSpec.split(':')
        # [] TODO: check these formats and maybe check against a list
        #   of valid values
        if sourceP and sourceQ:
            sourceClaim = pywikibot.Claim(repo, sourceP)
            sourceItem = pywikibot.ItemPage(repo, sourceQ)
            sourceClaim.setTarget(sourceItem)
            return sourceClaim

    def collect_items (accum, nextRecord):
        # Returns {<q number> : {<claim> : <sourceClaim>, ...}, ...}
        # where
        # nextRecord := [<Q>, <p1>, <v1>, <p2>, <v2>, ...]
        #   as parsed from  a line from a tab-delimited file
        def collect_claims (accum, nextProperty_value):
            # returns {<claim> : <sourceClaim>, ...}
            # where
            # <nextProperty_value> := [<propertySpec>, <valueSpec>]
            # <sourceClaim> is a claim, or None if there is no spec.
            [propertySpec, valueSourceSpec] = nextProperty_value
            [valueSpec, sourceSpec] = parse_value_source_spec(valueSourceSpec)
            claim = pywikibot.Claim(repo, propertySpec)
            claim.setTarget(infer_target(claim.type, valueSpec))
            sourceClaim = infer_source_claim(sourceSpec)
            accum[claim] = sourceClaim
            return accum

        q_number = nextRecord[0]
        p_spex = nextRecord[1:]
        assert (len(p_spex) >= 2) and (len(p_spex) % 2 == 0)
        itemClaims = accum[q_number] if q_number in accum else {}
        accum [q_number] = reduce(collect_claims,
                                  chunk(p_spex, 2), #[[p, v], ...]
                                  itemClaims)
        return accum

    item_to_claim_to_source = reduce(collect_items, get_records(tsvFile), {})
    generator = gen.getCombinedGenerator()
    if not generator:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
    bot = TsvClaimRobot(generator, item_to_claim_to_source, exists_arg)
    bot.run()
    return True

if __name__ == "__main__":
    main()


text:
import {ListWrapper} from '../../facade/collection';
import * as ml from '../../ml_parser/ast';
import {HtmlParser} from '../../ml_parser/html_parser';
import {InterpolationConfig} from '../../ml_parser/interpolation_config';
import {XmlParser} from '../../ml_parser/xml_parser';
import {ParseError} from '../../parse_util';
import * as i18n from '../i18n_ast';
import {MessageBundle} from '../message_bundle';
import {I18nError} from '../parse_util';

import {Serializer, extractPlaceholderToIds, extractPlaceholders} from './serializer';
import * as xml from './xml_helper';

const _VERSION = '1.2';
const _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
// TODO(vicb): make this a param (s/_/-/)
const _SOURCE_LANG = 'en';
const _PLACEHOLDER_TAG = 'x';
const _SOURCE_TAG = 'source';
const _TARGET_TAG = 'target';
const _UNIT_TAG = 'trans-unit';
const _CR = (ws: number = 0) => new xml.Text(`\n${new Array(ws).join(' ')}`);

// http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
// http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
export class Xliff implements Serializer {
  constructor(private _htmlParser: HtmlParser, private _interpolationConfig: InterpolationConfig) {}

  write(messageMap: {[id: string]: i18n.Message}): string {
    const visitor = new _WriteVisitor();

    const transUnits: xml.Node[] = [];

    Object.keys(messageMap).forEach((id) => {
      const message = messageMap[id];

      let transUnit = new xml.Tag(_UNIT_TAG, {id: id, datatype: 'html'});
      transUnit.children.push(
          _CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), _CR(8),
          new xml.Tag(_TARGET_TAG));

      if (message.description) {
        transUnit.children.push(
            _CR(8),
            new xml.Tag(
                'note', {priority: '1', from: 'description'}, [new xml.Text(message.description)]));
      }

      if (message.meaning) {
        transUnit.children.push(
            _CR(8),
            new xml.Tag('note', {priority: '1', from: 'meaning'}, [new xml.Text(message.meaning)]));
      }

      transUnit.children.push(_CR(6));

      transUnits.push(_CR(6), transUnit);
    });

    const body = new xml.Tag('body', {}, [...transUnits, _CR(4)]);
    const file = new xml.Tag(
        'file', {'source-language': _SOURCE_LANG, datatype: 'plaintext', original: 'ng2.template'},
        [_CR(4), body, _CR(2)]);
    const xliff = new xml.Tag('xliff', {version: _VERSION, xmlns: _XMLNS}, [_CR(2), file, _CR()]);

    return xml.serialize([new xml.Declaration({version: '1.0', encoding: 'UTF-8'}), _CR(), xliff]);
  }

  load(content: string, url: string, messageBundle: MessageBundle): {[id: string]: ml.Node[]} {
    // Parse the xtb file into xml nodes
    const result = new XmlParser().parse(content, url);

    if (result.errors.length) {
      throw new Error(`xtb parse errors:\n${result.errors.join('\n')}`);
    }

    // Replace the placeholders, messages are now string
    const {messages, errors} = new _LoadVisitor().parse(result.rootNodes, messageBundle);

    if (errors.length) {
      throw new Error(`xtb parse errors:\n${errors.join('\n')}`);
    }

    // Convert the string messages to html ast
    // TODO(vicb): map error message back to the original message in xtb
    let messageMap: {[id: string]: ml.Node[]} = {};
    const parseErrors: ParseError[] = [];

    Object.keys(messages).forEach((id) => {
      const res = this._htmlParser.parse(messages[id], url, true, this._interpolationConfig);
      parseErrors.push(...res.errors);
      messageMap[id] = res.rootNodes;
    });

    if (parseErrors.length) {
      throw new Error(`xtb parse errors:\n${parseErrors.join('\n')}`);
    }

    return messageMap;
  }
}

class _WriteVisitor implements i18n.Visitor {
  private _isInIcu: boolean;

  visitText(text: i18n.Text, context?: any): xml.Node[] { return [new xml.Text(text.value)]; }

  visitContainer(container: i18n.Container, context?: any): xml.Node[] {
    const nodes: xml.Node[] = [];
    container.children.forEach((node: i18n.Node) => nodes.push(...node.visit(this)));
    return nodes;
  }

  visitIcu(icu: i18n.Icu, context?: any): xml.Node[] {
    if (this._isInIcu) {
      // nested ICU is not supported
      throw new Error('xliff does not support nested ICU messages');
    }
    this._isInIcu = true;

    // TODO(vicb): support ICU messages
    // https://lists.oasis-open.org/archives/xliff/201201/msg00028.html
    // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-po/xliff-profile-po-1.2-cd02.html
    const nodes: xml.Node[] = [];

    this._isInIcu = false;

    return nodes;
  }

  visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): xml.Node[] {
    const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {id: ph.startName, ctype: ph.tag});
    if (ph.isVoid) {
      // void tags have no children nor closing tags
      return [startTagPh];
    }

    const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {id: ph.closeName, ctype: ph.tag});

    return [startTagPh, ...this.serialize(ph.children), closeTagPh];
  }

  visitPlaceholder(ph: i18n.Placeholder, context?: any): xml.Node[] {
    return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name})];
  }

  visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): xml.Node[] {
    return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name})];
  }

  serialize(nodes: i18n.Node[]): xml.Node[] {
    this._isInIcu = false;
    return ListWrapper.flatten(nodes.map(node => node.visit(this)));
  }
}

// TODO(vicb): add error management (structure)
// TODO(vicb): factorize (xtb) ?
class _LoadVisitor implements ml.Visitor {
  private _messageNodes: [string, ml.Node[]][];
  private _translatedMessages: {[id: string]: string};
  private _msgId: string;
  private _target: ml.Node[];
  private _errors: I18nError[];
  private _placeholders: {[name: string]: string};
  private _placeholderToIds: {[name: string]: string};

  parse(nodes: ml.Node[], messageBundle: MessageBundle):
      {messages: {[k: string]: string}, errors: I18nError[]} {
    this._messageNodes = [];
    this._translatedMessages = {};
    this._msgId = '';
    this._target = [];
    this._errors = [];

    // Find all messages
    ml.visitAll(this, nodes, null);

    const messageMap = messageBundle.getMessageMap();
    const placeholders = extractPlaceholders(messageBundle);
    const placeholderToIds = extractPlaceholderToIds(messageBundle);

    this._messageNodes
        .filter(message => {
          // Remove any messages that is not present in the source message bundle.
          return messageMap.hasOwnProperty(message[0]);
        })
        .sort((a, b) => {
          // Because there could be no ICU placeholders inside an ICU message,
          // we do not need to take into account the `placeholderToMsgIds` of the referenced
          // messages, those would always be empty
          // TODO(vicb): overkill - create 2 buckets and [...woDeps, ...wDeps].process()
          if (Object.keys(messageMap[a[0]].placeholderToMsgIds).length == 0) {
            return -1;
          }

          if (Object.keys(messageMap[b[0]].placeholderToMsgIds).length == 0) {
            return 1;
          }

          return 0;
        })
        .forEach(message => {
          const id = message[0];
          this._placeholders = placeholders[id] || {};
          this._placeholderToIds = placeholderToIds[id] || {};
          // TODO(vicb): make sure there is no `_TRANSLATIONS_TAG` nor `_TRANSLATION_TAG`
          this._translatedMessages[id] = ml.visitAll(this, message[1]).join('');
        });

    return {messages: this._translatedMessages, errors: this._errors};
  }

  visitElement(element: ml.Element, context: any): any {
    switch (element.name) {
      case _UNIT_TAG:
        this._target = null;
        const msgId = element.attrs.find((attr) => attr.name === 'id');
        if (!msgId) {
          this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`);
        } else {
          this._msgId = msgId.value;
        }
        ml.visitAll(this, element.children, null);
        if (this._msgId !== null) {
          this._messageNodes.push([this._msgId, this._target]);
        }
        break;

      case _SOURCE_TAG:
        // ignore source message
        break;

      case _TARGET_TAG:
        this._target = element.children;
        break;

      case _PLACEHOLDER_TAG:
        const idAttr = element.attrs.find((attr) => attr.name === 'id');
        if (!idAttr) {
          this._addError(element, `<${_PLACEHOLDER_TAG}> misses the "id" attribute`);
        } else {
          const id = idAttr.value;
          if (this._placeholders.hasOwnProperty(id)) {
            return this._placeholders[id];
          }
          if (this._placeholderToIds.hasOwnProperty(id) &&
              this._translatedMessages.hasOwnProperty(this._placeholderToIds[id])) {
            return this._translatedMessages[this._placeholderToIds[id]];
          }
          // TODO(vicb): better error message for when
          // !this._translatedMessages.hasOwnProperty(this._placeholderToIds[id])
          this._addError(element, `The placeholder "${id}" does not exists in the source message`);
        }
        break;

      default:
        ml.visitAll(this, element.children, null);
    }
  }

  visitAttribute(attribute: ml.Attribute, context: any): any {
    throw new Error('unreachable code');
  }

  visitText(text: ml.Text, context: any): any { return text.value; }

  visitComment(comment: ml.Comment, context: any): any { return ''; }

  visitExpansion(expansion: ml.Expansion, context: any): any {
    throw new Error('unreachable code');
  }

  visitExpansionCase(expansionCase: ml.ExpansionCase, context: any): any {
    throw new Error('unreachable code');
  }

  private _addError(node: ml.Node, message: string): void {
    this._errors.push(new I18nError(node.sourceSpan, message));
  }
}


text:
/**
 * Created by bluewaitor on 16/1/1.
 */

var q = require('q');

var json = process.argv[2];

function parsePromised ( json ) {
    var def = q.defer();
    var result;

    try{
        result = JSON.parse(json);
    }catch (e){
        def.reject(e);
    }

    def.resolve(result);
    return def.promise;
}

parsePromised(json)
    .then(null, console.log);


text:
/* TODO: add thread support?? */

#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

// Riot includes
#include <sched.h>
#include <xtimer.h>

#ifdef THREADS
#include <mutex.h>
#include <thread.h>
#endif

#include "sol-mainloop-common.h"
#include "sol-interrupt_scheduler_riot.h"
#include "sol-mainloop-impl.h"
#include "sol-vector.h"

#define DEFAULT_USLEEP_TIME 10000

#define MSG_BUFFER_SIZE 32
static msg_t msg_buffer[MSG_BUFFER_SIZE];

#ifdef THREADS
static mutex_t _lock;
static kernel_pid_t _main_pid;
#endif

void
sol_mainloop_impl_lock(void)
{
#ifdef THREADS
    mutex_lock(&_lock);
#endif
}

void
sol_mainloop_impl_unlock(void)
{
#ifdef THREADS
    mutex_unlock(&_lock);
#endif
}

bool
sol_mainloop_impl_main_thread_check(void)
{
#ifdef THREADS
    return thread_getpid() == _main_pid;
#else
    return true;
#endif
}

void
sol_mainloop_impl_main_thread_notify(void)
{
}

int
sol_mainloop_impl_platform_init(void)
{
#ifdef THREADS
    mutex_init(&_lock);
    _main_pid = thread_getpid();
#endif
    sol_interrupt_scheduler_set_pid(sched_active_pid);
    msg_init_queue(msg_buffer, MSG_BUFFER_SIZE);
    return 0;
}

void
sol_mainloop_impl_platform_shutdown(void)
{
#ifdef THREADS
    _main_pid = KERNEL_PID_UNDEF;
#endif
    sol_mainloop_common_source_shutdown();
}

static inline uint32_t
sleeptime_until_next_timeout(void)
{
    struct timespec ts;
    uint32_t sleeptime = DEFAULT_USLEEP_TIME;
    bool ret;

    sol_mainloop_impl_lock();
    ret = sol_mainloop_common_timespec_first(&ts);
    sol_mainloop_impl_unlock();

    if (ret) {
        if (ts.tv_sec < 0)
            sleeptime = 0;
        else
            sleeptime = ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC;
    }

    return sleeptime;
}

void
sol_mainloop_impl_iter(void)
{
    msg_t msg;
    uint32_t sleeptime;

    sol_mainloop_common_timeout_process();
    sol_mainloop_common_idler_process();
    sol_mainloop_common_timeout_process();

    if (!sol_mainloop_common_loop_check())
        return;

    sleeptime = sleeptime_until_next_timeout();
    if (xtimer_msg_receive_timeout(&msg, sleeptime) > 0)
        sol_interrupt_scheduler_process(&msg);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context=".activity.splash.SplashScreenActivity">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:contentDescription="@string/app_name"
        android:scaleType="center"
        android:src="@drawable/logo" />

    <com.pnikosis.materialishprogress.ProgressWheel
        android:id="@+id/progress_wheel"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="32dp"
        android:scaleType="center"
        wheel:matProg_barColor="@color/colorPrimaryLight"
        wheel:matProg_progressIndeterminate="true" />

</RelativeLayout>


text: nuget pack "Deque\Deque.nuspec" -symbols


text:
const int MGT_TRACKS = 80;
const int MGT_SIDES = 2;
const int MGT_SECTORS = 10;
const int MGT_TRACK_SIZE = MGT_SECTORS * SECTOR_SIZE;
const int MGT_DISK_SIZE = NORMAL_SIDES * NORMAL_TRACKS * MGT_TRACK_SIZE;
const int MGT_DISK_SECTORS = MGT_DISK_SIZE / SECTOR_SIZE;
const int MGT_DIR_TRACKS = 4;

// From SAM Technical Manual  (bType, wSize, wOffset, wUnused, bPages, bStartPage)
const int MGT_FILE_HEADER_SIZE = 9;

// Maximum size of a file that will fit on a SAM disk
const int MAX_SAM_FILE_SIZE = (MGT_TRACKS * MGT_SIDES - MGT_DIR_TRACKS) * MGT_SECTORS * (SECTOR_SIZE - 2) - MGT_FILE_HEADER_SIZE;

struct DIR_ZX
{
    uint8_t abUnk1;         // +210
    uint8_t abTypeZX;       // +211  ZX type byte
    uint8_t abZXLength[2];  // +212  ZX length
    uint8_t abZXStart[2];   // +214  ZX start address
    uint8_t abZXUnk2[2];    // +216  ?
    uint8_t abZXExec[2];    // +218  ZX autostart line number (BASIC) or address (code):
                            //       BASIC line active if b15+b14 are clear
                            //       CODE address active if not &0000 or &ffff
};

struct DIR_EXTRA
{
    uint8_t bDirTag;            // +250 Directory tag for directory entry; BDOS uses next 6 chars for disk name (fi$
    uint8_t bReserved;          // +251 Reserved
    uint8_t abSerial[2];        // +252 Random word for serial number (first entry only)
    uint8_t bDirCode;           // +254 Directory tag number for non-directory entries
    uint8_t bExtraDirTracks;    // +255 Number of directory tracks minus 4 (first entry only)
};

struct MGT_DIR
{
    uint8_t bType;              // +0   File type (b7=hidden, b6=protected)
    uint8_t abName[10];         // +1   Filename padded with spaces; first char is zero for unused

    uint8_t bSectorsHigh;       // +11  MSB of number of sectors used
    uint8_t bSectorsLow;        // +12  LSB of number of sectors used

    uint8_t bStartTrack;        // +13  Track number for start of file
    uint8_t bStartSector;       // +14  Sector number for start of file
    uint8_t abSectorMap[195];   // +15  Sector Address Map for file

    union
    {
        uint8_t abLabel[10];    // +210 +D/Disciple data, or disk label when in first entry (0|255 for none (SAMDOS/BDOS))
        DIR_ZX  zx;
    };
    uint8_t bFlags;             // +220 Flags (MGT use only) ; start of snapshot registers (22 bytes)
                                //  iy, ix, de', bc', hl', af', de, bc, hl, iff1+I, sp, (af from stack)

    uint8_t abFileInfo[11];     // +221 File type information; first byte is mode-1 for screen$

    uint8_t abBDOS[4];          // +232 Spare; holds "BDOS" for first entry on BDOS disks

    uint8_t bStartPage;         // +236 Start page number in b4-b0 (b7-b5 are undefined)
    uint8_t bPageOffsetLow;     // +237 Start offset in range 32768-49151
    uint8_t bPageOffsetHigh;

    uint8_t bLengthInPages;     // +239 Number of pages in length
    uint8_t bLengthOffsetLow;   // +240 Length MOD 16384 (b15 and b14 are undefined)
    uint8_t bLengthOffsetHigh;

    uint8_t bExecutePage;       // +242 Execution page for CODE files, or 255 if no autorun
    uint8_t bExecAddrLow;       // +243 Execution offset (32768-49151) or BASIC autorun line (or 65535)
    uint8_t bExecAddrHigh;

    uint8_t bDay;               // +245 Day of save (1-31), or 255 for invalid/none
    uint8_t bMonth;             // +246 Month (1-12); bit 7 set for BDOS 1.7a+ format: b6-b3 month, b2-b0 day-of-week (0=Sun)
    uint8_t bYear;              // +247 Year (year-1900); invalid if 255; MasterDOS has Y2K problem and uses (year%100)
    uint8_t bHour;              // +248 Hour; new BDOS: b7-b3 hour, b2-b0 low 3 bits of minute
    uint8_t bMinute;            // +249 Minute; new BDOS: b7-b5 upper 3 bits of minute, b4-b0 seconds/2
    union
    {
        DIR_EXTRA extra;
        char szLabelExtra[6];
    };
};

static_assert(sizeof(MGT_DIR) == 256, "MGT_DIR size is wrong");

const int BDOS_LABEL_SIZE = 16;     // Many things expect this to be 16
const int BDOS_SECTOR_SIZE = 512;
const int BDOS_RECORD_SECTORS = MGT_DISK_SECTORS;

struct BDOS_CAPS
{
    int list_sectors = 0;       // Sectors reserved for the record list
    int base_sectors = 0;       // Sectors used by boot sector plus record list
    int records = 0;            // Number of records, including possible partial last record
    int extra_sectors = 0;      // Extra sectors: >= 40 will form a small final record)
    bool need_byteswap = false; // True if this is an ATOM disk that needs byte-swapping
    bool bootable = false;      // True if the boot sector suggests the disk is bootable
    bool lba = false;           // True if disk needs LBA sector count instead of CHS
};

const int PRODOS_SECTOR_SIZE = 512;
const int PRODOS_BASE_SECTORS = 68;
const int PRODOS_RECORD_SECTORS = 2048;

struct PRODOS_CAPS
{
    int base_sectors;   // Sectors used by boot sector plus record list
    int records;        // Number of records, including possible partial last record
    bool bootable;      // True if the boot sector suggests the disk is bootable
};

enum class SamDosType { SAMDOS, MasterDOS, BDOS };

struct MGT_DISK_INFO
{
    SamDosType dos_type = SamDosType::SAMDOS;   // SAMDOS, MasterDOS or BDOS
    int dir_tracks = MGT_DIR_TRACKS;            // Number of tracks in directory listing (min=4, max=39)
    std::string disk_label{};                   // Up to BDOS_LABEL_SIZE (16) characters
    int serial_number = 0;                      // Serial number (MasterDOS only)
};

MGT_DISK_INFO* GetDiskInfo(const uint8_t* p, MGT_DISK_INFO& di);
bool SetDiskInfo(uint8_t* pb_, MGT_DISK_INFO& di);
bool GetFileTime(const MGT_DIR* p, struct tm* ptm_);

bool IsSDIDEDisk(const HDD& hdd);
bool IsProDOSDisk(const HDD& hdd, PRODOS_CAPS& pdc);
bool IsBDOSDisk(const HDD& hdd, BDOS_CAPS& bdc);

bool UpdateBDOSBootSector(uint8_t* pb_, const HDD& hdd);
void GetBDOSCaps(int64_t sectors, BDOS_CAPS& bdc);
int FindBDOSRecord(const HDD& hdd, const std::string& path, BDOS_CAPS& bdc);