text:
Param([Bool]$testMode=$false)

#################################################
# Functions                                     #
#################################################

Function WriteLog {
    param(  [string]$log,
            [string]$loglevel="INFO")

    $now = Get-Date -f "dd/MM/yyyy HH:mm:ss"

    Write-Host "$now | $loglevel | $log"
}

Function ResolveMasks {
    param(  [string]$pattern,
            [string]$package="")

    $pattern = $pattern -replace "%PACKAGE", $package
    $pattern = $pattern -replace "%DATE", (Get-Date -f "yyyyMMdd")
    $pattern = $pattern -replace "%TIME", (Get-Date -f "HHmmss")

    return $pattern
}

Function GetFileToArchive {
    param(  [string]$folder,
            [string]$pattern,
            [int]$archiveDelay,
            [int]$deleteDelay,
            [bool]$recursive)

    $files = @()

    if(!(Test-Path $folder -pathtype container)) {
        WriteLog "The folder $pathToScan doesn't exists" "ERROR"
    } else {
        foreach($item in Get-ChildItem $folder) {
            if((Test-Path "$folder\$item" -pathtype container) -and $recursive) {
                $data = getFileToArchive "$folder\$item" $pattern $archiveDelay $deleteDelay $recursive
                if(!($data -eq $null)){
                    $files += $data
                }
            } else {
                if($item -match $pattern) {
                    $toArchive = $false
                    $toDelete = $false

                    #Should we archive this file ?
                    if($archiveAfter -gt 0 -and (Get-Date ($item.LastWriteTime)) -lt ((Get-Date).AddDays(-1 * $archiveDelay))) {
                       $toArchive = $true
                       WriteLog "$folder\$item will be archived"
                    }

                    #Shoudl we delete this file ?
                    if($deleteAfter -gt 0 -and (Get-Date ($item.LastWriteTime)) -lt ((Get-Date).AddDays(-1 * $deleteDelay))) {
                       $toDelete = $true
                       WriteLog "$folder\$item will be deleted"
                    }

                    if($toArchive -or $toDelete) {
                        $lastModificationdate = "{0:yyyyMMdd}" -f (Get-Date ($item.LastWriteTime))
                        $files += ,("$folder\$item",$lastModificationdate,$toArchive,$toDelete)
                    }
                }
            }
        }
    }

    return (,($files))
}

Function ProcessFile {
    param(  $file,
            [string]$archivePath,
            [string]$packageName,
            [bool]$testMode)

}

#################################################
# Main sripts                                   #
#################################################

$configFile = "housekeeper.xml"

#Open the config files
if(!(Test-Path $configFile)) {
    WriteLog "Unable to open the config file $configFile"
    exit 1
}

WriteLog "Parsing the config file $configFile"
$config = [xml](get-content $configFile)

#get 7Zip path
$compressionTool = $config.configuration.compress.Value

#Get the logging information
$logPath = $config.configuration.logging.path.Value
$logTemplate = $config.configuration.logging.filename.Value

#Get the packages configs
foreach ($packageNode in $config.configuration.packages.package) {
    $packageName = $packageNode.Value
    $archiveAfter = $packageNode.archiveafter
    $deleteAfter = $packageNode.deleteafter
    $archivePath = $packageNode.archivepath

    if(!($archiveAfter -match "^\d+$") -or ([int]$archiveAfter) -lt 1) { $archiveAfter = -1 }
    if(!($deleteAfter -match "^\d+$") -or ([int]$deleteAfter) -lt 1) { $deleteAfter = -1 }

    #Initiate the log file
    $logFile = ResolveMasks $logTemplate $packageName
    $logFile = "$logFile.log"

    #Start the transcript
    Start-Transcript "$logPath\$logFile" -Append

    if($testMode) { WriteLog "TEST MODE - No file will be archived or deleted !!!!" }

    WriteLog "Package : $packageName"
    WriteLog "Archive After : $archiveAfter"
    WriteLog "Delete After : $deleteAfter"

    #Getting all pattern
    foreach ($patternNode in $packageNode.pattern) {
        #parse the pattern
        $pathToScan = $patternNode.path
        $pattern = $patternNode.pattern
        $recursive = $patternNode.recursive

        WriteLog "Pattern : [$pathToScan] [$pattern] [$recursive]"

        WriteLog "Set location to $pathToScan"
        set-location "$pathToScan"

        if($recursive -eq "true") {
            $recursive = $true
        } else {
            $recursive = $false
        }

        #Retreive the list of file to archive or delete
        $result = GetFileToArchive "." $pattern $archiveAfter $deleteAfter $recursive

        if ($result -and $result.length -gt 0)
        {
            WriteLog ("Number of results :" + $result.length)

            foreach ($file in $result) {
                if($file -and $file.length -gt 0) {
                    $fileName = $file[0]
                    $fileDate = $file[1]
                    $fileToArchive = $file[2]
                    $fileToDelete = $file[3]

                    if($fileToArchive) {
                        $args=@()
                        $args += "a"
                        $args += "`"$archivePath\$fileDate\$packageName`_$fileDate.rar`""
                        $args +=  "`"$fileName`""

                        #Creating the archive folder
                        if(!(Test-Path "$archivePath\$fileDate" -pathtype container)){
                            WriteLog "Creating directory $archivePath\$fileDate"
                            New-Item "$archivePath\$fileDate" -ItemType directory
                        }

                        WriteLog "Adding $fileName to $archivePath\$fileDate\$packageName`_$fileDate.rar"
                        #WriteLog "$compressionTool $args"

                        if(! $testMode) { start-process $compressionTool -argument $args -Wait }
                    }

                    if($fileToDelete) {
                        WriteLog "Deleting $fileName"

                        if(! $testMode) { remove-item $fileName }
                    }
                }
            }
        } else {
            WriteLog "Nothing to archive or delete with this pattern"
        }

    }
    Stop-Transcript
}


text:
FROM nginx
# Install dependencies
RUN apt-get update -qq && apt-get -y install apache2-utils

# establish where Nginx should look for files
ENV RAILS_ROOT /var/www/app

# Set our working directory inside the image
WORKDIR $RAILS_ROOT

# create log directory
RUN mkdir log

# copy over static assets
COPY public public/

# Copy Nginx config template
COPY docker/web/nginx.conf /tmp/docker.nginx

# substitute variable references in the Nginx config template for real values from the environment
# put the final config in its place
RUN envsubst '$RAILS_ROOT' < /tmp/docker.nginx > /etc/nginx/conf.d/default.conf

EXPOSE 80

# Use the "exec" form of CMD so Nginx shuts down gracefully on SIGTERM (i.e. `docker stop`)
CMD [ "nginx", "-g", "daemon off;" ]

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Stubborn\Exceptions;

/**
 * Non-default exception as to avoid and try/catch statement Stubborn might be
 * run inside.
 */
class StubbornException extends \Exception
{
}


text:
class FAndPProcessor
  def initialize(benchmark_date, educator_id, options = {})
    @benchmark_date = benchmark_date
    @educator_id = educator_id
    @log = options.fetch(:log, Rails.env.test? ? LogHelper::FakeLog.new : STDOUT)
    @matcher = options.fetch(:matcher, ImportMatcher.new)
  end

  def import(file_text, options = {})
    # parse
    rows = []
    StreamingCsvTransformer.from_text(@log, file_text).each_with_index do |row, index|
      maybe_row = maybe_parse_row(row.to_h, index)
      next if maybe_row.nil?
      rows << maybe_row
      @matcher.count_valid_row
    end
    log "matcher#stats: #{@matcher.stats}"

    # write to database
    f_and_ps = nil
    FAndPAssessment.transaction do
      FAndPAssessment.where(benchmark_date: @benchmark_date).destroy_all
      f_and_ps = rows.map {|row| FAndPAssessment.create!(row) }
    end
    f_and_ps
  end

  private
  def maybe_parse_row(row, index)
    student_id = @matcher.find_student_id(row['LASID'])
    return nil if student_id.nil?

    {
      student_id: student_id,
      benchmark_date: @benchmark_date,
      instructional_level: row['F&P Instructional Level'],
      f_and_p_code: row['F&P Code'],
      uploaded_by_educator_id: @educator_id
    }
  end

  def log(msg)
    text = if msg.class == String then msg else JSON.pretty_generate(msg) end
    @log.puts "FandPProcessor: #{text}"
  end
end


text:
package controle;
public class Premier {

	public static void main(String[] args) {
		fronteira.Sortie.print("Ça marche bien");
	}
}


text:
window.switchserialportID = 0;
(function() {
	var valueStyle = freeboard.getStyleString("values");

	freeboard.addStyle('.widget-big-text', valueStyle + "font-size:75px;");

	freeboard.addStyle('.tw-display', 'width: 100%; height:100%; display:table; table-layout:fixed;');

	freeboard.addStyle('.tw-tr',
		'display:table-row;');

	freeboard.addStyle('.tw-tg',
		'display:table-row-group;');

	freeboard.addStyle('.tw-tc',
		'display:table-caption;');

	freeboard.addStyle('.tw-td',
		'display:table-cell;');

	freeboard.addStyle('.tw-value',
		valueStyle +
		'overflow: hidden;' +
		'display: inline-block;' +
		'text-overflow: ellipsis;');

	freeboard.addStyle('.tw-unit',
		'display: inline-block;' +
		'padding-left: 10px;' +
		'padding-bottom: 1.1em;' +
		'vertical-align: bottom;');

	freeboard.addStyle('.tw-value-wrapper',
		'position: relative;' +
		'vertical-align: middle;' +
		'height:100%;');

    var switchserialportWidget = function (settings) {
        var thisswitchserialportID = window.switchserialportID++;
		var displayElement = $('

');
        var titleElement = $('

');
        var switchButtonTitleElement1 = $('

');
        var switchButtonTitleElement2 = $('

');
        var switchElement = $('

');
        var switchserialportElement = switchElement;
        var warningElement = $('

');

        var switchserialportObject;
        var rendered = false;
        var sw;

		var switchserialport;
        var currentSettings = settings;
        var messageValue = "";
        var previousMessageValue = messageValue;
        var arraySerialPort = (currentSettings.serialport).split(",");
        //console.log(arraySerialPort);
        for (var i = 0; i < arraySerialPort.length; i++) {
        	tabSwitchSerialPort[arraySerialPort[i]] = -1;
        }

        // The datasource must be a serial port
        for (var i = 0; i < arraySerialPort.length; i++) {
	        if (freeboard.getDatasourceType(arraySerialPort[i]) !== "serialport") {
	        	alert("Problem with switch serial port widget: datasource " + arraySerialPort[i] + " is not a serial port");
	        }
	    }

 		function sendDataOn() {
			sessionStorage.setItem(currentSettings.variable1, currentSettings.value1);
			sessionStorage.setItem(currentSettings.variable2, currentSettings.value2);
 		};

 		function sendDataOff() {
			sessionStorage.setItem(currentSettings.switchoff_variable1, currentSettings.switchoff_value1);
			sessionStorage.setItem(currentSettings.switchoff_variable2, currentSettings.switchoff_value2);
 		};

        function createSwitchSerialPort(mySettings) {
            if (!rendered) {
                return;
            }

            switchserialportElement.empty();

            sendDataOff();

            var style = (_.isUndefined(mySettings.style) ? "switch" : mySettings.style);
            // console.log(style);
            // console.log(style == "switch");

        	switchserialportElement = switchElement;
        	var checkedStr = '';
        	if (mySettings.initialstate) {
        		checkedStr = 'checked="checked"';
        	}

			var switchserialportElementStr = '<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="' + thisswitchserialportID + '-serialportonoff" ' + checkedStr + '>
' + mySettings.ontext + '' + mySettings.offtext + '

';
            document.getElementById('switchserialport-' + thisswitchserialportID).innerHTML = switchserialportElementStr;

			$( "#" + thisswitchserialportID + "-serialportonoff" ).change(function() {
				for (var i = 0; i < arraySerialPort.length; i++) {
					if (($( "#" + thisswitchserialportID + "-serialportonoff" )).prop("checked")) {
						tabSwitchSerialPort[arraySerialPort[i]] = 1;
						sendDataOn();
					}
					else {
						tabSwitchSerialPort[arraySerialPort[i]] = -1;
						sendDataOff();
					}
				}
			});
        }

        this.render = function (element) {
            rendered = true;
			$(element).empty();

            $(displayElement).append(titleElement)
				.append($('

').append(switchButtonTitleElement1).append(switchButtonTitleElement2).append($('

')))
				.append($('

')
					.append($('

').append(switchserialportElement))
					.append($('

').append(warningElement))
					.append($('

'))
				);

			$(element).append(displayElement);

            //$(element).append(titleElement).append(switchserialportElement);
            createSwitchSerialPort(currentSettings);
        };

        this.onSettingsChanged = function (newSettings) {
            if ((newSettings.style != currentSettings.style)
            	|| (newSettings.ontext != currentSettings.ontext)
            	|| (newSettings.offtext != currentSettings.offtext)
            	|| (newSettings.caption != currentSettings.caption)) {
                createSwitchSerialPort(newSettings);
            }

            if (newSettings.serialport != currentSettings.serialport) {
            	arraySerialPort = (newSettings.serialport).split(",");
            }

			currentSettings = newSettings;
            titleElement.html(currentSettings.title);
        };

        this.onCalculatedValueChanged = function (settingName, newValue) {
            if (settingName == "message") {
            	messageValue = newValue;
				if (previousMessageValue != messageValue) {
	                warningElement.html(messageValue);
	            }
	            previousMessageValue = messageValue;
            }
        };

        this.onDispose = function () {
			for (var i = 0; i < arraySerialPort.length; i++) {
				tabSwitchSerialPort[arraySerialPort[i]] = -1;
			}
        };

        this.getHeight = function () {
            return 1;
        };

        this.onSettingsChanged(settings);

		function checkIsOpen(refreshTime) {
			updateTimer = setInterval(function () {
				for (var i = 0; i < arraySerialPort.length; i++) {
					if (tabSerialPortIsOpen[arraySerialPort[i]] == true) {
						($( "#" + thisswitchserialportID + "-serialportonoff" )).prop("checked", true);
					}
					else {
						($( "#" + thisswitchserialportID + "-serialportonoff" )).prop("checked", false);
					}
				}
			}, refreshTime);
		}
		checkIsOpen(500);
    };

    freeboard.loadWidgetPlugin({
        type_name: "switchserialport",
        display_name: _t("Switch Serial Port"),
		description : _t("A Switchbutton widget for serial communications."),
        settings: [
            {
                name: "title",
                display_name: _t("Title"),
                type: "text"
            },
			{
				name: "serialport",
				display_name: _t("Serial datasource"),
                type: "text",
				description: _t("Datasource name corresponding to the serial port to switch. You *must* create first a datasource with the same name")
			},
            {
                name: "ontext",
                display_name: _t('"ON" text'),
                type: "text",
                default_value: "ON"
            },
            {
                name: "offtext",
                display_name: _t('"OFF" text'),
                type: "text",
                default_value: "OFF"
            },
            {
                name: "initialstate",
                display_name: _t("Initial state"),
                type: "boolean",
                default_value: false
            },
            {
                name: "variable1",
                display_name: _t("Switch On Variable #1"),
                type: "calculated",
				description: _t("(Optional) Variable #1 to send when the serial port is switched on")
            },
            {
                name: "value1",
                display_name: _t('Switch On Value #1'),
                type: "text",
                description: _t('Value to send when the switch on variable #1 is defined above')
            },
            {
                name: "switchoff_variable1",
                display_name: _t("Switch Off Variable #1"),
                type: "calculated",
				description: _t("(Optional) Variable #1 to send when the serial port is switched off")
            },
            {
                name: "switchoff_value1",
                display_name: _t('Switch Off Value #1'),
                type: "text",
                description: _t('Value to send when the switch off variable #1 is defined above')
            },
            {
                name: "variable2",
                display_name: _t("Switch On Variable #2"),
                type: "calculated",
				description: _t("(Optional) Variable #2 to send when the serial port is switched on")
            },
            {
                name: "value2",
                display_name: _t('Switch On Value #2'),
                type: "text",
                description: _t('Value to send when the switch on variable #2 is defined above')
            },
            {
                name: "switchoff_variable2",
                display_name: _t("Switch Off Variable #2"),
                type: "calculated",
				description: _t("(Optional) Variable #2 to send when the serial port is switched off")
            },
            {
                name: "switchoff_value2",
                display_name: _t('Switch Off Value #2'),
                type: "text",
                description: _t('Value to send when the switch off variable #2 is defined above')
            },
            {
                name: "message",
                display_name: _t("Message"),
                type: "calculated",
				description: _t("(Optional) Message to display aside the button")
            }
        ],
        newInstance: function (settings, newInstanceCallback) {
            newInstanceCallback(new switchserialportWidget(settings));
        }
    });

}());


text:
import cv2
import numpy as np
import math

# Get the number of pixels with specific characteristica
def get_num_of_pixels(image):
    sum_white_pixels = len(np.where(image == 255)[0])
    sum_black_pixels = len(np.where(image < 255)[0])
    sum_zero_pixels = len(np.where(image == 0)[0])
    sum_total_pixels = image.shape[0] * image.shape[1]
    sum_gray_pixels = sum_total_pixels - sum_white_pixels - sum_zero_pixels

    return sum_total_pixels, sum_white_pixels, sum_black_pixels, sum_gray_pixels

# Get the horizontal center of the glpyh
def get_horizontal_center(image):
    width = get_width(image)
    left_edge = get_left_edge_pos(image)
    center = width / 2

    return left_edge + center

# Get the vertical center of the glpyh
def get_vertical_center(image):
    height = get_height(image)
    top_edge = get_top_edge_pos(image)
    center = height / 2

    return top_edge + center

# Get the width of the glyph
def get_width(image):
    return get_height( np.transpose(image) )

# Get the height of the glyph
def get_height(image):
    height = 0
    height_begin = None
    height_end = None
    for i, line in enumerate(image):
        if height_begin == None:
            if np.any(line < 255):
                height_begin = i
                height_end = i
        if height_begin != None:
            if np.any(line < 255):
                height_end = i
    height_end += 1

    return height_end - height_begin

# Get the Horizontal Pos from the left edge to the begin of the glpyh
def get_left_edge_pos(image):
    return get_top_edge_pos( np.transpose(image) )

# Get the Vertical Pos from the top edge to the begin of the glyph
def get_top_edge_pos(image):
    start_pos = None
    for i, line in enumerate(image):
        if np.any(line < 255):
                start_pos = i
                break
    return start_pos

# Get the mean horizontal position of all 'on' pixels
def get_mean_horizontal_position(image):
    center = get_horizontal_center(image)
    width = get_width(image)

    dist_on_pix_center = np.where(image < 255)[1] - center
    dist_on_pix_center = dist_on_pix_center / width

    mean_horizontal_pos = np.mean(dist_on_pix_center)

    return mean_horizontal_pos

# Get the mean vertical position of all 'on' pixels
def get_mean_vertical_position(image):
    center = get_vertical_center(image)
    height = get_height(image)

    dist_on_pix_center = np.where(image < 255)[0] - center
    dist_on_pix_center = dist_on_pix_center / height

    mean_vertical_pos = np.mean(dist_on_pix_center)

    return mean_vertical_pos

# Get the horizontal variance of all 'on' pixels
def get_horizontal_variance(image):
    dist =  np.where(image < 255)[1]
    return np.var(dist)

# Get the vertical variance of all 'on' pixels
def get_vertical_variance(image):
    dist =  np.where(image < 255)[0]
    return np.var(dist)

# Get the sum of all vertical edges in the picture
# a vertical edge is a 'on' pixel with a 'off' pixel directly to right
def get_sum_of_vertical_edges(image):
    pos_on_pix_v = np.where(image < 255)[0]
    pos_on_pix_h = np.where(image < 255)[1]

    max_width = image.shape[1] - 1
    edge_counter = 0

    for i in range(0, len(pos_on_pix_v)):
        if pos_on_pix_h[i] < max_width:
            if image[ pos_on_pix_v[i] ][ pos_on_pix_h[i]+1 ] == 255:
                edge_counter += 1

    return edge_counter

# Get the sum of all vertical edges in the picture
# a vertical edge is a 'on' pixel with a 'off' pixel directly below
def get_sum_of_horizontal_edges(image):
    return get_sum_of_vertical_edges( np.transpose(image) )

# Get the perimter of all contours in the image
def get_sum_perimeter(image):
    perimeter = 0
    binary = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 9, 1)
    im2, contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        perimeter += cv2.arcLength(contour,True)

    return perimeter

# Get the number of holes in the image
# a hohle is e.g. the inner of an O
def get_num_holes(image):
    regions = 0
    binary = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 9, 1)
    im2, contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    for idx, contour in enumerate(contours):
        if hierarchy[0][idx][3] != -1:
            regions += 1

    return regions

# Get the number of all connected components with on pixels in the image
def get_num_comps(image):
    regions = 0
    binary = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 9, 1)
    im2, contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    for idx, contour in enumerate(contours):
        if hierarchy[0][idx][3] == -1:
            regions += 1

    return regions

# Reduce the 'on' areas in the pixel in order to get the skelet of each reagion
def get_skeletation(image):
    size = np.size(image)
    skel = np.zeros(image.shape,np.uint8)

    ret,img = cv2.threshold(image,127,255,cv2.THRESH_BINARY_INV)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))

    done = False

    i = 0
    zeros = cv2.countNonZero(img)
    while( zeros != size):
        eroded = cv2.erode(img,element)
        temp = cv2.dilate(eroded,element)
        temp = cv2.subtract(img,temp)
        skel = cv2.bitwise_or(skel,temp)
        img = eroded.copy()

        zeros = size - cv2.countNonZero(img)

    return cv2.countNonZero(skel)

# Creates the feautre vector
def get_feature_vector(image):
    feature_vector = []

    height = get_height(image)
    width = get_width(image)
    norm, _, black, gray = get_num_of_pixels(image)

    feature_vector.append( get_sum_perimeter(image) / (width + height) )

    skel = get_skeletation(image)
    if skel != 0:
        feature_vector.append( get_sum_perimeter(image) / get_skeletation(image) )
    else:
       feature_vector.append( 0 )

    feature_vector.append( get_mean_horizontal_position(image) )
    feature_vector.append( get_mean_vertical_position(image) )
    feature_vector.append( get_sum_of_horizontal_edges(image) / black )
    feature_vector.append( get_num_holes(image) )
    feature_vector.append( get_num_comps(image) )
    feature_vector.append( get_vertical_variance(image) / height )
    feature_vector.append( get_horizontal_variance(image) / width )

    return feature_vector


text:
Single perceptron based ann in Python.
####Usage:
```python
>>> from annsp import annsp
>>> k = annsp(train_data, train_labels)
>>> k.classify(vector)
>>> ...
```


text: """Excel spreadsheet extraction maps for EIA 860M."""


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <amendments />
    <createDate>2017-02-15T05:13:05Z</createDate>
    <latestAction>
      <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
      <actionDate>2017-02-14</actionDate>
      <links />
    </latestAction>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <name>Veterans' Affairs Committee</name>
          <chamber>Senate</chamber>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-02-14T17:14:04Z</date>
            </item>
          </activities>
          <systemCode>ssva00</systemCode>
          <subcommittees />
        </item>
      </billCommittees>
    </committees>
    <committeeReports />
    <notes />
    <actions>
      <item>
        <actionDate>2017-02-14</actionDate>
        <committee>
          <systemCode>ssva00</systemCode>
          <name>Veterans' Affairs Committee</name>
        </committee>
        <links />
        <sourceSystem>
          0
          <name>Senate</name>
        </sourceSystem>
        <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <text>Introduced in Senate</text>
        <actionCode>10000</actionCode>
        <actionDate>2017-02-14</actionDate>
        <committee />
        <links />
        <type>IntroReferral</type>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
      </item>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
    </actions>
    <title>BRAVE Act</title>
    <calendarNumbers />
    <summaries>
      <billSummaries>
        <item>
          <name>Introduced in Senate</name>
          <lastSummaryUpdateDate>2017-03-11T16:18:53Z</lastSummaryUpdateDate>
          <updateDate>2017-02-14T05:00:00Z</updateDate>
          <actionDesc>Introduced in Senate</actionDesc>
          <actionDate>2017-02-14</actionDate>
          <versionCode>00</versionCode>
          <text><![CDATA[
Boosting Rates of American Veteran Employment Act or the BRAVE Act

 This bill authorizes the Department of Veterans Affairs (VA), in awarding a contract for the procurement of goods or services, to give preference to offerors based on the percentage of the offeror's full-time employees who are veterans.

The VA is authorized to debar from VA contracting for at least five years any offeror determined to have willfully and intentionally misrepresented the veteran status of its employees.
]]></text>
        </item>
      </billSummaries>
    </summaries>
    <recordedVotes />
    <congress>115</congress>
    <cboCostEstimates />
    <titles>
      <item>
        <chamberCode />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberName />
        <title>BRAVE Act</title>
        <parentTitleType />
      </item>
      <item>
        <chamberCode />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberName />
        <title>Boosting Rates of American Veteran Employment Act</title>
        <parentTitleType />
      </item>
      <item>
        <chamberCode />
        <titleType>Short Titles as Introduced</titleType>
        <chamberName />
        <title>BRAVE Act</title>
        <parentTitleType />
      </item>
      <item>
        <chamberCode />
        <titleType>Short Titles as Introduced</titleType>
        <chamberName />
        <title>Boosting Rates of American Veteran Employment Act</title>
        <parentTitleType />
      </item>
      <item>
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <chamberName />
        <title>A bill to amend title 38, United States Code, to authorize the Secretary of Veterans Affairs, in awarding a contract for the procurement of goods or services, to give a preference to offerors that employ veterans, and for other purposes.</title>
        <parentTitleType />
      </item>
      <item>
        <chamberCode />
        <titleType>Display Title</titleType>
        <chamberName />
        <title>BRAVE Act</title>
        <parentTitleType />
      </item>
    </titles>
    <updateDate>2017-06-19T21:00:13Z</updateDate>
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Armed Forces and National Security</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Department of Veterans Affairs</name>
          </item>
          <item>
            <name>Fraud offenses and financial crimes</name>
          </item>
          <item>
            <name>Public contracts and procurement</name>
          </item>
          <item>
            <name>Veterans' education, employment, rehabilitation</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <version>1.0.0</version>
    <billNumber>369</billNumber>
    <laws />
    <introducedDate>2017-02-14</introducedDate>
    <policyArea>
      <name>Armed Forces and National Security</name>
    </policyArea>
    <sponsors>
      <item>
        <state>WI</state>
        <middleName />
        <byRequestType />
        <party>D</party>
        <firstName>TAMMY</firstName>
        <fullName>Sen. Baldwin, Tammy [D-WI]</fullName>
        <identifiers>
          <gpoId>8215</gpoId>
          <bioguideId>B001230</bioguideId>
          <lisID>1558</lisID>
        </identifiers>
        <lastName>BALDWIN</lastName>
        <bioguideId>B001230</bioguideId>
      </item>
    </sponsors>
    <relatedBills>
      <item>
        <number>974</number>
        <latestAction>
          <actionDate>2017-02-14</actionDate>
          <text>Received in the Senate and Read twice and referred to the Committee on Veterans' Affairs.</text>
        </latestAction>
        <congress>115</congress>
        <type>HR</type>
        <latestTitle>BRAVE Act</latestTitle>
        <relationshipDetails>
          <item>
            <identifiedBy>CRS</identifiedBy>
            <type>Identical bill</type>
          </item>
        </relationshipDetails>
      </item>
    </relatedBills>
    <originChamber>Senate</originChamber>
    <billType>S</billType>
    <cosponsors>
      <item>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <identifiers>
          <gpoId />
          <bioguideId>T000476</bioguideId>
          <lisID>2291</lisID>
        </identifiers>
        <middleName>Roland</middleName>
        <sponsorshipWithdrawnDate />
        <state>NC</state>
        <sponsorshipDate>2017-02-14</sponsorshipDate>
        <bioguideId>T000476</bioguideId>
        <fullName>Sen. Tillis, Thom [R-NC]</fullName>
        <firstName>Thomas</firstName>
        <party>R</party>
        <lastName>Tillis</lastName>
      </item>
      <item>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <identifiers>
          <bioguideId>C001070</bioguideId>
          <lisID>1828</lisID>
          <gpoId>8282</gpoId>
        </identifiers>
        <middleName />
        <sponsorshipWithdrawnDate />
        <state>PA</state>
        <sponsorshipDate>2017-05-25</sponsorshipDate>
        <bioguideId>C001070</bioguideId>
        <fullName>Sen. Casey, Robert P., Jr. [D-PA]</fullName>
        <firstName>Bob</firstName>
        <party>D</party>
        <lastName>Casey</lastName>
      </item>
    </cosponsors>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
LinearAllocator::LinearAllocator(std::size_t sizeBytes)
    : _memPtr(new char[sizeBytes])
    , _currentPtr(_memPtr)
    , _memSize(sizeBytes)
{}

LinearAllocator::~LinearAllocator()
{
    delete[] _memPtr;
}

void* LinearAllocator::alloc(std::size_t sizeBytes)
{
    void* ptr = _currentPtr;

    _currentPtr += sizeBytes;
    Assert(_currentPtr <= _memPtr + _memSize, "Out of memory!");
    return ptr;
}

void LinearAllocator::clear()
{
    _currentPtr = _memPtr;
}


text:
using DNTProfiler.CommandsByMemoryUsage.ViewModels;
using DNTProfiler.PluginsBase;

namespace DNTProfiler.CommandsByMemoryUsage
{
    public partial class Main
    {
        public Main(ProfilerPluginBase pluginContext)
        {
            InitializeComponent();
            this.DataContext = new MainViewModel(pluginContext);
        }
    }
}


text: Multi-processing Job Manager written by Perl


text:
use std::env;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::io::prelude::*;
use std::os;
use std::path::{Path, PathBuf};
use std::process::Output;
use std::str;
use std::usize;

use url::Url;
use hamcrest as ham;
use cargo::util::ProcessBuilder;
use cargo::util::ProcessError;
use cargo::util::process;

use support::paths::CargoPathExt;

pub mod paths;
pub mod git;
pub mod registry;

/*
 *
 * ===== Builders =====
 *
 */

#[derive(PartialEq,Clone)]
struct FileBuilder {
    path: PathBuf,
    body: String
}

impl FileBuilder {
    pub fn new(path: PathBuf, body: &str) -> FileBuilder {
        FileBuilder { path: path, body: body.to_string() }
    }

    fn mk(&self) -> Result<(), String> {
        try!(mkdir_recursive(&self.dirname()));

        let mut file = try!(
            fs::File::create(&self.path)
                .with_err_msg(format!("Could not create file; path={}",
                                      self.path.display())));

        file.write_all(self.body.as_bytes())
            .with_err_msg(format!("Could not write to file; path={}",
                                  self.path.display()))
    }

    fn dirname(&self) -> &Path {
        self.path.parent().unwrap()
    }
}

#[derive(PartialEq,Clone)]
struct SymlinkBuilder {
    dst: PathBuf,
    src: PathBuf,
}

impl SymlinkBuilder {
    pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
        SymlinkBuilder { dst: dst, src: src }
    }

    #[cfg(unix)]
    fn mk(&self) -> Result<(), String> {
        try!(mkdir_recursive(&self.dirname()));

        os::unix::fs::symlink(&self.dst, &self.src)
            .with_err_msg(format!("Could not create symlink; dst={} src={}",
                                   self.dst.display(), self.src.display()))
    }

    #[cfg(windows)]
    fn mk(&self) -> Result<(), String> {
        try!(mkdir_recursive(&self.dirname()));

        os::windows::fs::symlink_file(&self.dst, &self.src)
            .with_err_msg(format!("Could not create symlink; dst={} src={}",
                                   self.dst.display(), self.src.display()))
    }

    fn dirname(&self) -> &Path {
        self.src.parent().unwrap()
    }
}

#[derive(PartialEq,Clone)]
pub struct ProjectBuilder {
    name: String,
    root: PathBuf,
    files: Vec<FileBuilder>,
    symlinks: Vec<SymlinkBuilder>
}

impl ProjectBuilder {
    pub fn new(name: &str, root: PathBuf) -> ProjectBuilder {
        ProjectBuilder {
            name: name.to_string(),
            root: root,
            files: vec![],
            symlinks: vec![]
        }
    }

    pub fn root(&self) -> PathBuf {
        self.root.clone()
    }

    pub fn url(&self) -> Url { path2url(self.root()) }

    pub fn bin(&self, b: &str) -> PathBuf {
        self.build_dir().join("debug").join(&format!("{}{}", b,
                                                     env::consts::EXE_SUFFIX))
    }

    pub fn release_bin(&self, b: &str) -> PathBuf {
        self.build_dir().join("release").join(&format!("{}{}", b,
                                                       env::consts::EXE_SUFFIX))
    }

    pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
        self.build_dir().join(target).join("debug")
                        .join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
    }

    pub fn build_dir(&self) -> PathBuf {
        self.root.join("target")
    }

    pub fn process<T: AsRef<OsStr>>(&self, program: T) -> ProcessBuilder {
        let mut p = ::process(program);
        p.cwd(self.root());
        return p
    }

    pub fn cargo(&self, cmd: &str) -> ProcessBuilder {
        let mut p = self.process(&cargo_dir().join("cargo"));
        p.arg(cmd);
        return p;
    }

    pub fn cargo_process(&self, cmd: &str) -> ProcessBuilder {
        self.build();
        self.cargo(cmd)
    }

    pub fn file<B: AsRef<Path>>(mut self, path: B,
                                body: &str) -> ProjectBuilder {
        self.files.push(FileBuilder::new(self.root.join(path), body));
        self
    }

    pub fn symlink<T: AsRef<Path>>(mut self, dst: T,
                                   src: T) -> ProjectBuilder {
        self.symlinks.push(SymlinkBuilder::new(self.root.join(dst),
                                               self.root.join(src)));
        self
    }

    // TODO: return something different than a ProjectBuilder
    pub fn build(&self) -> &ProjectBuilder {
        match self.build_with_result() {
            Err(e) => panic!(e),
            _ => return self
        }
    }

    pub fn build_with_result(&self) -> Result<(), String> {
        // First, clean the directory if it already exists
        try!(self.rm_root());

        // Create the empty directory
        try!(mkdir_recursive(&self.root));

        for file in self.files.iter() {
            try!(file.mk());
        }

        for symlink in self.symlinks.iter() {
            try!(symlink.mk());
        }

        Ok(())
    }

    fn rm_root(&self) -> Result<(), String> {
        if self.root.c_exists() {
            rmdir_recursive(&self.root)
        } else {
            Ok(())
        }
    }
}

// Generates a project layout
pub fn project(name: &str) -> ProjectBuilder {
    ProjectBuilder::new(name, paths::root().join(name))
}

// === Helpers ===

pub fn mkdir_recursive(path: &Path) -> Result<(), String> {
    fs::create_dir_all(path)
        .with_err_msg(format!("could not create directory; path={}",
                              path.display()))
}

pub fn rmdir_recursive(path: &Path) -> Result<(), String> {
    path.rm_rf()
        .with_err_msg(format!("could not rm directory; path={}",
                              path.display()))
}

pub fn main_file(println: &str, deps: &[&str]) -> String {
    let mut buf = String::new();

    for dep in deps.iter() {
        buf.push_str(&format!("extern crate {};\n", dep));
    }

    buf.push_str("fn main() { println!(");
    buf.push_str(&println);
    buf.push_str("); }\n");

    buf.to_string()
}

trait ErrMsg<T> {
    fn with_err_msg(self, val: String) -> Result<T, String>;
}

impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
    fn with_err_msg(self, val: String) -> Result<T, String> {
        match self {
            Ok(val) => Ok(val),
            Err(err) => Err(format!("{}; original={}", val, err))
        }
    }
}

// Path to cargo executables
pub fn cargo_dir() -> PathBuf {
    env::var_os("CARGO_BIN_PATH").map(PathBuf::from).or_else(|| {
        env::current_exe().ok().as_ref().and_then(|s| s.parent())
            .map(|s| s.to_path_buf())
    }).unwrap_or_else(|| {
        panic!("CARGO_BIN_PATH wasn't set. Cannot continue running test")
    })
}

/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
/*
 *
 * ===== Matchers =====
 *
 */

#[derive(Clone)]
pub struct Execs {
    expect_stdout: Option<String>,
    expect_stdin: Option<String>,
    expect_stderr: Option<String>,
    expect_exit_code: Option<i32>,
    expect_stdout_contains: Vec<String>
}

impl Execs {

    pub fn with_stdout<S: ToString>(mut self, expected: S) -> Execs {
        self.expect_stdout = Some(expected.to_string());
        self
    }

    pub fn with_stderr<S: ToString>(mut self, expected: S) -> Execs {
        self.expect_stderr = Some(expected.to_string());
        self
    }

    pub fn with_status(mut self, expected: i32) -> Execs {
        self.expect_exit_code = Some(expected);
        self
    }

    pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs {
        self.expect_stdout_contains.push(expected.to_string());
        self
    }

    fn match_output(&self, actual: &Output) -> ham::MatchResult {
        self.match_status(actual)
            .and(self.match_stdout(actual))
            .and(self.match_stderr(actual))
    }

    fn match_status(&self, actual: &Output) -> ham::MatchResult {
        match self.expect_exit_code {
            None => ham::success(),
            Some(code) => {
                ham::expect(
                    actual.status.code() == Some(code),
                    format!("exited with {}\n--- stdout\n{}\n--- stderr\n{}",
                            actual.status,
                            String::from_utf8_lossy(&actual.stdout),
                            String::from_utf8_lossy(&actual.stderr)))
            }
        }
    }

    fn match_stdout(&self, actual: &Output) -> ham::MatchResult {
        try!(self.match_std(self.expect_stdout.as_ref(), &actual.stdout,
                            "stdout", &actual.stderr, false));
        for expect in self.expect_stdout_contains.iter() {
            try!(self.match_std(Some(expect), &actual.stdout, "stdout",
                                &actual.stderr, true));
        }
        Ok(())
    }

    fn match_stderr(&self, actual: &Output) -> ham::MatchResult {
        self.match_std(self.expect_stderr.as_ref(), &actual.stderr,
                       "stderr", &actual.stdout, false)
    }

    #[allow(deprecated)] // connect => join in 1.3
    fn match_std(&self, expected: Option<&String>, actual: &[u8],
                 description: &str, extra: &[u8],
                 partial: bool) -> ham::MatchResult {
        let out = match expected {
            Some(out) => out,
            None => return ham::success(),
        };
        let actual = match str::from_utf8(actual) {
            Err(..) => return Err(format!("{} was not utf8 encoded",
                                       description)),
            Ok(actual) => actual,
        };
        // Let's not deal with \r\n vs \n on windows...
        let actual = actual.replace("\r", "");
        let actual = actual.replace("\t", "<tab>");

        let mut a = actual.lines();
        let e = out.lines();

        let diffs = if partial {
            let mut min = self.diff_lines(a.clone(), e.clone(), partial);
            while let Some(..) = a.next() {
                let a = self.diff_lines(a.clone(), e.clone(), partial);
                if a.len() < min.len() {
                    min = a;
                }
            }
            min
        } else {
            self.diff_lines(a, e, partial)
        };
        ham::expect(diffs.len() == 0,
                    format!("differences:\n\
                            {}\n\n\
                            other output:\n\
                            `{}`", diffs.connect("\n"),
                            String::from_utf8_lossy(extra)))

    }

    fn diff_lines<'a>(&self, actual: str::Lines<'a>, expected: str::Lines<'a>,
                      partial: bool) -> Vec<String> {
        let actual = actual.take(if partial {
            expected.clone().count()
        } else {
            usize::MAX
        });
        zip_all(actual, expected).enumerate().filter_map(|(i, (a,e))| {
            match (a, e) {
                (Some(a), Some(e)) => {
                    if lines_match(&e, &a) {
                        None
                    } else {
                        Some(format!("{:3} - |{}|\n    + |{}|\n", i, e, a))
                    }
                },
                (Some(a), None) => {
                    Some(format!("{:3} -\n    + |{}|\n", i, a))
                },
                (None, Some(e)) => {
                    Some(format!("{:3} - |{}|\n    +\n", i, e))
                },
                (None, None) => panic!("Cannot get here")
            }
        }).collect()
    }
}

fn lines_match(expected: &str, mut actual: &str) -> bool {
    for part in expected.split("[..]") {
        match actual.find(part) {
            Some(i) => actual = &actual[i + part.len()..],
            None => {
                return false
            }
        }
    }
    actual.len() == 0 || expected.ends_with("[..]")
}

struct ZipAll<I1: Iterator, I2: Iterator> {
    first: I1,
    second: I2,
}

impl<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>> Iterator for ZipAll<I1, I2> {
    type Item = (Option<T>, Option<T>);
    fn next(&mut self) -> Option<(Option<T>, Option<T>)> {
        let first = self.first.next();
        let second = self.second.next();

        match (first, second) {
            (None, None) => None,
            (a, b) => Some((a, b))
        }
    }
}

fn zip_all<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>>(a: I1, b: I2) -> ZipAll<I1, I2> {
    ZipAll {
        first: a,
        second: b,
    }
}

impl fmt::Display for Execs {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "execs")
    }
}

impl ham::Matcher<ProcessBuilder> for Execs {
    fn matches(&self, mut process: ProcessBuilder) -> ham::MatchResult {
        self.matches(&mut process)
    }
}

impl<'a> ham::Matcher<&'a mut ProcessBuilder> for Execs {
    fn matches(&self, process: &'a mut ProcessBuilder) -> ham::MatchResult {
        let res = process.exec_with_output();

        match res {
            Ok(out) => self.match_output(&out),
            Err(ProcessError { output: Some(ref out), .. }) => {
                self.match_output(out)
            }
            Err(e) => {
                let mut s = format!("could not exec process {}: {}", process, e);
                match e.cause() {
                    Some(cause) => s.push_str(&format!("\ncaused by: {}",
                                                       cause.description())),
                    None => {}
                }
                Err(s)
            }
        }
    }
}

pub fn execs() -> Execs {
    Execs {
        expect_stdout: None,
        expect_stderr: None,
        expect_stdin: None,
        expect_exit_code: None,
        expect_stdout_contains: vec![]
    }
}

#[derive(Clone)]
pub struct ShellWrites {
    expected: String
}

impl fmt::Display for ShellWrites {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "`{}` written to the shell", self.expected)
    }
}

impl<'a> ham::Matcher<&'a [u8]> for ShellWrites {
    fn matches(&self, actual: &[u8])
        -> ham::MatchResult
    {
        let actual = String::from_utf8_lossy(actual);
        let actual = actual.to_string();
        ham::expect(actual == self.expected, actual)
    }
}

pub fn shell_writes<T: fmt::Display>(string: T) -> ShellWrites {
    ShellWrites { expected: string.to_string() }
}

pub trait Tap {
    fn tap<F: FnOnce(&mut Self)>(mut self, callback: F) -> Self;
}

impl<T> Tap for T {
    fn tap<F: FnOnce(&mut Self)>(mut self, callback: F) -> T {
        callback(&mut self);
        self
    }
}

pub fn basic_bin_manifest(name: &str) -> String {
    format!(r#"
        [package]

        name = "{}"
        version = "0.5.0"
        authors = ["wycats@example.com"]

        [[bin]]

        name = "{}"
    "#, name, name)
}

pub fn basic_lib_manifest(name: &str) -> String {
    format!(r#"
        [package]

        name = "{}"
        version = "0.5.0"
        authors = ["wycats@example.com"]

        [lib]

        name = "{}"
    "#, name, name)
}

pub fn path2url(p: PathBuf) -> Url {
    Url::from_file_path(&*p).ok().unwrap()
}

pub static RUNNING:     &'static str = "     Running";
pub static COMPILING:   &'static str = "   Compiling";
pub static DOCUMENTING: &'static str = " Documenting";
pub static FRESH:       &'static str = "       Fresh";
pub static UPDATING:    &'static str = "    Updating";
pub static ADDING:      &'static str = "      Adding";
pub static REMOVING:    &'static str = "    Removing";
pub static DOCTEST:     &'static str = "   Doc-tests";
pub static PACKAGING:   &'static str = "   Packaging";
pub static DOWNLOADING: &'static str = " Downloading";
pub static UPLOADING:   &'static str = "   Uploading";
pub static VERIFYING:   &'static str = "   Verifying";
pub static ARCHIVING:   &'static str = "   Archiving";
pub static INSTALLING:  &'static str = "  Installing";


text:
<?php

namespace TestApp\Model\Table;

use Cake\ORM\Table;

/**
 * Tag table class
 */
class TagsTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Authors');
        $this->belongsToMany('Articles');
        $this->hasMany('ArticlesTags', ['propertyName' => 'extraInfo']);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="320dp"
    android:layout_gravity="center"
    android:layout_height="wrap_content">

    <!-- b/144298723 -->

    <androidx.constraintlayout.helper.widget.Flow
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:background="#FFC107"
        app:flow_horizontalBias="0"
        app:flow_horizontalGap="10dp"
        app:flow_horizontalStyle="packed"
        app:flow_verticalBias="0"
        app:flow_verticalGap="10dp"
        app:flow_wrapMode="chain"
        app:constraint_referenced_ids="frameLayout1,frameLayout2,frameLayout3,frameLayout4,frameLayout5" />

    <FrameLayout
        android:id="@+id/frameLayout1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        tools:ignore="MissingConstraints" />

    <FrameLayout
        android:id="@+id/frameLayout2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        tools:ignore="MissingConstraints" />

    <FrameLayout
        android:id="@+id/frameLayout3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        tools:ignore="MissingConstraints" />

    <FrameLayout
        android:id="@+id/frameLayout4"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        tools:ignore="MissingConstraints" />

    <FrameLayout
        android:id="@+id/frameLayout5"
        android:layout_width="210dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
<?php declare(strict_types=1);

namespace Rostenkowski\Translate;

use Nette\Localization\ITranslator;

interface TranslatorInterface extends ITranslator
{

	public function setLocale(string $locale): TranslatorInterface;

}


text:
module Fuse #:nodoc:

  # This is an interface to the sitecopy program
  #
  # it uses sitecopy to keep a local directory syncronized with
  # a FTP or webDAV server
  #
  # Example usage
  # -------------
  #
  #   rcfile = <<-EOF
  #     server ftp.example.com
  #     username example
  #     password 12345
  #     ...
  #   EOF
  #   t = Rake::SitecopyTask.new("site", rcfile)
  #
  # it generates rake tasks to download, upload or check the
  # contents on the remote server
  #
  # see `rake --tasks` for information the generated rules
  #
  class SitecopyTask

    def initialize(name, rcfile)
      @site = name

      # Sitecopy configuration
      @rc = "site #{@site}\n" << rcfile

      @rcfile = ".sitecopyrc.tmp"
      @state_dir = ".sitecopy.tmp"

      # sitecopy-command
      @sitecopy = "sitecopy -r #{@rcfile} -p #{@state_dir} "

      define
    end

    def fetch
      sh "#{@sitecopy} --fetch #{@site}"
    end

    # list all differences between the local files and the
    # remote copy
    #
    def list
      sh "#{@sitecopy} --list #{@site}"
    end

    # update the remote copy of this site
    #
    def upload
      sh "#{@sitecopy} --update #{@site}"
    end

    # update the local site from the remote copy
    # WARNING: this will overwrite local files
    #
    def download
      sh "#{@sitecopy} --synchronize #{@site}"
    end

    def define
      namespace :sitecopy do

        # Create sitecopy .rcfile
        task @rcfile do
          File.open(@rcfile,"w+", 0600) { |f| f.write(@rc) }
        end

        # Create sitecopy storage directory
        file @state_dir do
          Dir.mkdir(@state_dir, 0700)
          fetch # check state on server
        end

        # Remove sitecopy configfile and state cache
        desc "Clean temporary files"
        task :clobber do
          rm_r @state_dir rescue nil
          rm @rcfile rescue nil
        end

        task :prepare => [@rcfile, @state_dir]

        desc "Resyncronize sitecopy state with remote server"
        task :check_server => [:clobber, :prepare] do
          list
        end
        desc "List changes between local directory and remote server"
        task :list => [:prepare] do
          list
        end

        desc "Fetches the remote site"
        task :fetch => [:prepare] do
          fetch
        end

        task "upload_#{@site}" => [:prepare] do
          upload
        end
        desc "Upload all sites to remote server"
        task :upload => ["upload_#{@site}"]

        task "download_#{@site}" => [:prepare] do
          download
        end
        desc "Download all sites from remote server"
        task :download => ["download_#{@site}"]

      end
    end
  end
end


text:
class Bar < Formula
  desc "Provide progress bars for shell scripts"
  homepage "http://www.theiling.de/projects/bar.html"
  url "http://www.theiling.de/downloads/bar-1.4-src.tar.bz2"
  sha1 "00b55ca1d52ca6ed099937692697c2257833c73c"

  def install
    bin.install "bar"
  end

  test do
    (testpath/"test1").write "pumpkin"
    (testpath/"test2").write "latte"
    assert_match /latte/, shell_output("#{bin}/bar test1 test2")
  end
end


text:
import random
import netaddr
import six

from consts import ResourceType
from rally.common import sshutils
from rally.common import objects
from rally.common import utils

from rally.common import db

cidr_incr = utils.RAMInt()

'''
    Find credential resource from DB by deployment uuid, and return
    info as a dict.

    :param deployment deployment uuid
'''
def get_credential_from_resource(deployment):

    res = None
    if not isinstance(deployment, objects.Deployment):
        deployment = objects.Deployment.get(deployment)

    res = deployment.get_resources(type=ResourceType.CREDENTIAL)

    return res["info"]

def get_ssh_from_credential(cred):
    sshcli = sshutils.SSH(cred["user"], cred["host"],
                       port = cred["port"],
                       key_filename = cred["key"],
                       password = cred["password"])
    return sshcli

def get_ssh_client_from_deployment(deployment):
    cred = get_credential_from_resource(deployment)

    return get_ssh_from_credential(cred)

def get_random_sandbox(sandboxes):
    info = random.choice(sandboxes)
    sandbox = random.choice(info["sandboxes"])

    return info["farm"], sandbox

def get_random_mac(base_mac):
    mac = [int(base_mac[0], 16), int(base_mac[1], 16),
           int(base_mac[2], 16), random.randint(0x00, 0xff),
           random.randint(0x00, 0xff), random.randint(0x00, 0xff)]
    if base_mac[3] != '00':
        mac[3] = int(base_mac[3], 16)
    return ':'.join(["%02x" % x for x in mac])

def generate_cidr(start_cidr="10.2.0.0/24"):
    """Generate next CIDR for network or subnet, without IP overlapping.

    This is process and thread safe, because `cidr_incr' points to
    value stored directly in RAM. This guarantees that CIDRs will be
    serial and unique even under hard multiprocessing/threading load.

    :param start_cidr: start CIDR str
    :returns: next available CIDR str
    """
    cidr = str(netaddr.IPNetwork(start_cidr).next(next(cidr_incr)))
    return cidr

def py_to_val(pyval):
    """Convert python value to ovs-vsctl value argument"""
    if isinstance(pyval, bool):
        return 'true' if pyval is True else 'false'
    elif pyval == '':
        return '""'
    else:
        return pyval

def get_farm_nodes(deploy_uuid):
    deployments = db.deployment_list(parent_uuid=deploy_uuid)

    farm_nodes = []
    for dep in deployments:
        res = db.resource_get_all(dep["uuid"], type=ResourceType.SANDBOXES)
        if len(res) == 0 or len(res[0].info["sandboxes"]) == 0:
            continue

        farm_nodes.append(res[0].info["farm"])

    return farm_nodes

def get_sandboxes(deploy_uuid, farm="", tag=""):

    sandboxes = []
    deployments = db.deployment_list(parent_uuid=deploy_uuid)
    for dep in deployments:
        res = db.resource_get_all(dep["uuid"], type=ResourceType.SANDBOXES)
        if len(res) == 0 or len(res[0].info["sandboxes"]) == 0:
            continue

        info = res[0].info

        if farm and farm != info["farm"]:
            continue

        for k,v in six.iteritems(info["sandboxes"]):
            if tag and tag != v:
                continue

            sandbox = {"name": k, "tag": v, "farm": info["farm"]}
            sandboxes.append(sandbox)

    return sandboxes


text:
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Common.Mail.Common;

namespace Common.Mail.Imap.Command
{
    /// <summary>
    ///
    /// </summary>
    public class CapabilityResult : ImapCommandResult
    {
        /// <summary>
        ///
        /// </summary>
        public ReadOnlyCollection<String> Features { get; private set; }
        /// <summary>
        ///
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="text"></param>
        public CapabilityResult(String tag, String text)
            : base(tag, text)
        {
            const string s = "* Capability ";
            if (text.StartsWith(s, StringComparison.OrdinalIgnoreCase) == false)
            { throw new MailClientException(); }

            string line;
            using (var sr = new StringReader(text))
            {
                line = sr.ReadLine();
            }
            var index = s.Length;
            if (line != null)
            {
                var ss = line.Substring(index, line.Length - index);
                var l = ss.Split(' ').Where(el => String.IsNullOrEmpty(el) != true).ToList();
                Features = new ReadOnlyCollection<string>(l);
            }
        }
    }
}


text:
This directory contains deprecated classes, structs and typedefs, and test doubles for
those deprecated classes. New code should not import headers from this directory and no
new functionality should be added to deprecated classes and functions.

This directory can be used as a temporary place for retiring public classes, structs and
typedefs.


text:
{% extends "admin/_base.html" %}
{% block title %}
用户编辑
{% endblock %}
{%- from "macros/common.html" import input_csrf_token %}
{% block content %}

      <form action="" method="post">
        {{ input_csrf_token() }}
        <input type="hidden" name="user_id" id="user_id" {%if user.id %}value="{{user.id}}"{%endif%}/>

          邮箱
          <input type="text"  name="email" value="{{ user.email }}" class="form-control" placeholder="邮箱">

          用户名
          <input type="text"  name="username" value="{{ user.username}}" class="form-control" placeholder="用户名">

          角色
          <input type="text"  name="role_id" value="{{ user.role_id}}" class="form-control" placeholder="角色">

          姓名
          <input type="text"  name="name" value="{{ user.name}}" class="form-control" placeholder="姓名">

              <input type="checkbox" name="confirmed"
                {% if user.confirmed %} checked {% endif %}
                value="confirmed"/>
                用户已确认

            <button type="submit" class="btn btn-danger">
              提交
            </button>

      </form>

{% endblock %}


text:
package com.chrisdoyle.validation.tests;

import com.chrisdoyle.validation.Main;

import org.junit.Assert;
import org.junit.Test;

import java.io.File;

/**
 * Created by alex on 9/2/16.
 */
public class Test_Issue12Sigs {

    @Test
    public void verifyGpgSignatures() throws Exception{

        for (int i=0; i < Main.allSignedArtifacts.length; i++){

            File f= new File(Main.allSignedArtifacts[i]);
            Assert.assertTrue(Main.allSignedArtifacts[i] + " does not exist", f.exists());

            f= new File(Main.allSignedArtifacts[i] + ".asc");
            Assert.assertTrue(Main.allSignedArtifacts[i] + " does not exist", f.exists());

            Process p = Runtime.getRuntime().exec(new String[]{Main.gpg, f.getAbsolutePath()});
            int exitcode =p.waitFor();
            p.destroy();
            Assert.assertEquals("Signature validation failed for " + f.getAbsolutePath(), 0, exitcode);
        }

    }
}


text:
<?php
require_once '../dbInterface.php';
if(isset($_POST['id']) && isset($_POST['operateType'])){
	switch($_POST['operateType']){
		case 'detele':
			$db->query('delete from user where id='.$_POST['id']);
			break;
		case 'forbid':
			$db->query('update user set forbid="1" where id='.$_POST['id']);
			break;
	}
	echo '1';
}else{
	echo '0';
}
?>


text:
<?php
require("../php/jdb.inc.php");
// See: http://jakemadethis.com/p/database-class

require("../php/login.php");
// This file needs one function 'login_is()', returns true if logged in.

require("../php/config.php");
// Global variables: $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME

require("./quickerubb.php");
require("./ubbextend.php");

/*

pages
-----

slug   varchar(255)
title  varchar(255)
body   text
excerpt   varchar(1024)
lastupdate   int

pages_tags
-----------

id		smallint
slug	varchar(255)
tag		varchar(255)

blog
----

slug	varchar(255)
title	varchar(255)
body	text
excerpt varchar(1024)
created	int

*/

function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
function array_place($str, $arr) {
	return array_map(create_function('$k,$v', 'return '.$str.';'),
					array_keys($arr), array_values($arr));
}
function is_blog($page) {	// 20110101 or 201101011
	return ctype_digit($page) && (strlen($page) == 8 || strlen($page) == 9);
}
function redirect($url) {
	header("Location: $url");
	exit();
}

// Time how long it takes to run script
$start_time = microtime_float();

// Start dir
$pages_dir = "/p/";

// Merge $_GET and $_POST, latter has precedence.
$request = array_merge($_GET, $_POST);

// Page is requested page or default to home
$page = $request["page"] or $page = "home";

// Set $action to one of edit, view, rename, delete, if exists in query string
$action = reset(array_intersect(array_keys($request), explode(",", "edit,view,rename,delete")));

// Connect to main database
$db = new Database($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, true);

// Set up base array. Fill out later for current page.
$page_array = array(
	"isspecial" => false,	// If the page is special
	"isreal" => false,		// If the page is real, ie exists in database
	"slug" => $page,		// Slug for template use
	"title" => "",			// Title
	"body" => "",			// Raw page body
	"html" => "",			// Generated HTML
	"excerpt" => "",		// Short body
	"lastupdate" => 0,		// UTS of last update
	"created" => 0,			// UTS of creation for blogs
	"isblog" => false,		// is this page a blog post or not
	"tags" => array(),		// array of tags as array("tag1","tag2","tag3")
	"childs" => array(),	// array of children as arrays of arrays like $page_array
	"blogposts" => array()	// array of blog posts
);

$message = array();

/// Special Pages ///////////////////

if($page == "all")
{
	// Get all pages and merge special data with page array
	$page_array = array_merge($page_array, array(
		"isspecial" => true,
		"title" => "All pages",
		"html" => "",
		"childs" => $db->select_rows("SELECT slug,title,excerpt FROM pages ORDER BY title ASC")
	));
}

else if ($page == "blog")
{
	$blogs = $db->select_rows("SELECT slug,title,body,excerpt,created FROM blog ORDER BY created DESC");
	$page_array = array_merge(array_merge($page_array, array_shift($blogs)), array(
		"isblog" => true,
		"isspecial" => true,
		"blogposts" => $blogs
	));
}

/// Regular Pages ///////////////////

if(!$page_array["isspecial"])
{
	$page_array["isblog"] = is_blog($page);
	$page_escape = mysql_real_escape_string($page);

	$table = ($page_array["isblog"] ? "blog" : "pages");

	// Merge with $page_array
	if($newarray = $db->select_row("SELECT * FROM $table WHERE slug='$page_escape' LIMIT 1"))
		$page_array = array_merge($page_array, $newarray);

	// Page if database result carries a lastupdate variable
	$page_array["isreal"] = ($page_array["isblog"] ? ($page_array["created"] != 0)
		: ($page_array["lastupdate"] != 0));

	// Pages can exist without being in the database,
	// If they exist in database:
	if($page_array["isreal"])
	{
		// SQL returns the tags as array(array("tag" => "page1"), array("tag" => "page2"));
		// So place each value of "tag" into a new array
		$page_array["tags"] = array_place('$v[tag]',
			$db->select_rows("SELECT tag FROM pages_tags WHERE slug='$page_escape' ORDER BY tag")
		);
	}

	// Get all child pages
	$page_array["childs"] = $db->select_rows(
		"SELECT pages.slug, pages.title, pages.excerpt
		 FROM pages, pages_tags
		 WHERE pages.slug = pages_tags.slug AND pages_tags.tag = '$page_escape'
		 ORDER BY pages.title");

	if ($page == "home") {
		$page_array["blogposts"] = $db->select_rows("SELECT slug,title,excerpt,created FROM blog ORDER BY created DESC");
	}
	else {// Get any blog posts tagged to this page
		$page_array["blogposts"] = $db->select_rows(
			"SELECT blog.slug, blog.title, blog.excerpt, blog.created
			FROM blog, pages_tags
			WHERE blog.slug = pages_tags.slug AND pages_tags.tag = '$page_escape'
			ORDER BY blog.created DESC");
	}

	/// Actions to perform on page ///////////////////

	// ACTION : view
	if($action == "view") {
		// This lets anyone view the source of the page.
		// Handle that in the output PHP, but do nothing here
	}

	// Everything else should require a password (Use elseif under here)
	elseif($action != "" && !login_is()) {
		$messages[] = "You're not logged in, silly";
	}

	// ACTION : delete
	elseif($action == "delete") {

		// We can delete pages. A confirmation button is needed to make it
		// harder to accidently delete pages

		// Error and skip down is the page doesn't even exist
		if(!$page_array["isreal"]) {
			$messages[] = "This page doesn't exist in the database";
		}

		// Only continue if confirmed
		elseif(isset($_POST["confirm"])) {

			// Do the page deletion
			$result = $db->query("DELETE FROM $table WHERE slug='$page_escape'");

			if(!$result) {
				$messages[] = "".mysql_error()."";
			}
			elseif(mysql_affected_rows() == 0) {
				$messages[] = "Didn't affect any rows. This is odd behaviour.";
			}
			else {

				if(!empty($request["deletetags"])) {
					// Delete tags associated to this page
					$result = $db->query("DELETE FROM `pages_tags` WHERE slug='$page_escape'");

					// Error if it didn't work
					if(!$result) {
							$messages[] = "".mysql_error()."";
					}
				}

				// If all goes well, redirect to the deleted page
				// I don't know why.
				if(empty($messages))
					redirect($pages_dir.$page);
			}
		}

	}

	// ACTION : rename
	elseif($action == "rename") {
		if(!$page_array["isreal"]) {
			$messages[] = "This page doesn't exist in the database";
		}

		elseif($page_array["isblog"]) {
			$messages[] = "Can't rename a blog post";
		}

		// Only rename if new name is posted
		elseif(isset($_POST["new"]))  // Commit edit
		{
			$newpage_escape = mysql_real_escape_string($_POST["new"]);

			// Do the renaming
			// Set slug to newpage wherever it was oldpage
			// Limit 1
			$result = $db->query("UPDATE pages SET slug='$newpage_escape'
										WHERE slug='$page_escape' LIMIT 1");

			if(!$result) {
				$messages[] = "".mysql_error()."";
			}
			elseif(mysql_affected_rows() == 0) {
				$messages[] = "Didn't affect any rows. This is odd behaviour.";
			}
			else {

				if(!empty($request["movetags"])) {
					// We have to move all the tags to the new page aswell
					// By this I mean rename the rows in the database
					$result = $db->query("UPDATE `pages_tags` SET slug='$newpage_escape'
											WHERE slug='$page_escape'");

					if(!$result) {
						$messages[] = "".mysql_error()."";
					}
				}
				if(!empty($request["movechilds"])) {
					// Move all child pages too
					$result = $db->query("UPDATE `pages_tags` SET tag='$newpage_escape'
											WHERE tag='$page_escape'");

					if(!$result) {
						$messages[] = "".mysql_error()."";
					}
				}

				// If both successful, redirect to the new page
				if(empty($messages))
					redirect($pages_dir.$_POST["new"]);
			}
		}

	}

	// ACTION : edit
	elseif($action == "edit") {
		if(isset($_POST["body"]))  // Commit edit
		{

			// Perform mysql_real_escape_string on all values
			$arraytoinsert = array_map("mysql_real_escape_string", array(
				"slug" => $page,
				"title" => stripslashes($_POST["title"]),
				"body" => stripslashes($_POST["body"]),
				"excerpt" => stripslashes($_POST["excerpt"])
			));

			// Non blog posts have a last update time
			if (!$page_array["isblog"])
				$arraytoinsert["lastupdate"] = time();

			// Doesn't exist yet but it is a blog
			else if (!$page_array["isreal"])
				$arraytoinsert["created"] = time();

			// Update or insert depends on if page is in database.
			// Hope to god database hasn't changed.
			$result = $page_array["isreal"] ?
				$db->update_rows("UPDATE $table SET %s WHERE slug='$page_escape'", $arraytoinsert) :
				$db->insert_row("INSERT INTO $table %s VALUES %s", $arraytoinsert);

			if(!$result)
				$messages[] = "".mysql_error()."";
			else
			{
				// Page has been updated/created successfull,
				// Add tags

				// Strip, explode, trim and remove empties
				// This makes string "    tag1,        tag2, ,   , tag3" into
				// array("tag1", "tag2", "tag3")
				$newtags = array_filter(array_map("trim", explode(",", stripslashes($_POST["tags"]))));

				// Use old tag array or an empty one
				$oldtags = $page_array["tags"] ? array_filter($page_array["tags"]) : array();

				// Collect all of $newtags which aren't in $oldtags
				$tagstoinsert = array_diff($newtags, $oldtags);

				// Collect all of $oldtags which aren't in $newtags
				$tagstodelete = array_diff($oldtags, $newtags);

				if(count($tagstoinsert) > 0)
				{
					// Create a string looking like ('mypage', 'tag1'), ('mypage', 'tag2'), ('mypage', 'tag3')
					$tagstr = implode(",", array_place('"(\''.$page_escape.'\', \'$v\')"', $tagstoinsert));

					if(!$db->query("INSERT INTO `pages_tags` (slug,tag) VALUES $tagstr"))
						$messages[] = "".mysql_error()."";
				}

				if(count($tagstodelete) > 0)
				{
					// This string will look like: tag1','tag2','tag3
					$tagstr = implode("','", $tagstodelete);

					if(!$db->query("DELETE FROM `pages_tags` WHERE slug='$page_escape' AND tag IN ('$tagstr')"))
						$messages[] = "".mysql_error()."";
				}

			}

			// No errors? redirect back to same page.
			if(count($messages) == 0)
				redirect("$pages_dir$page?edit");
		}
	}

}

// Close the database now.
// We're done with it
$db->close();

// Parse the HTML unless we already have HTML (Special pages)
if(!$page_array["html"])
{
	$parser or $parser = new ubbPagesParser();

	$parser->pagename = $page;
	$parser->allowHTML = true;
	$page_array["html"] = $parser->parse($page_array["body"]);
}

$time_taken = microtime_float() - $start_time;

// view.php takes
include("./view.php");
?>


text:
<!doctype html>

    <title>GK's Sample Angular App</title>
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/bootstrap-responsive.css">
    <link rel="stylesheet" href="css/starrating.css">
    <link rel="stylesheet" href="css/app.css">

                24x7 eStore

                Sample Angular JS SPA Application


text:
import React from 'react';

class Counter extends React.Component {
  render() {
    const { count, increment, decrement } = this.props;
    return (

{count}

        <button onClick={increment}>+1</button>
        <button onClick={decrement}>-1</button>

    );
  }
}

Counter.propTypes = {
  increment: React.PropTypes.func.isRequired,
  decrement: React.PropTypes.func.isRequired
};

export default Counter;


text:
package org.drools.eclipse.flow.common.view.datatype.editor.impl;

import java.lang.reflect.InvocationTargetException;

import org.drools.eclipse.DroolsEclipsePlugin;
import org.drools.eclipse.flow.common.datatype.DataTypeRegistry;
import org.drools.eclipse.flow.common.view.datatype.editor.Editor;
import org.drools.core.process.core.datatype.DataType;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

/**
 * Container for an editor.
 */
public class EditorComposite extends Composite {

    private DataTypeRegistry registry;
    private Editor editor;

    public EditorComposite(Composite parent, int style, DataTypeRegistry registry) {
        super(parent, style);
        this.registry = registry;
        setLayout(new FillLayout());
        editor = new EmptyEditor(this);
    }

    public void setDataType(DataType type) {
        ((Composite) editor).dispose();
        if (type == null) {
            editor = new EmptyEditor(this);
        } else {
            Class<?> editorClass = null;
            try {
                editorClass = registry.getDataTypeInfo(type.getClass()).getValueEditorClass();
                editor = (Editor) editorClass.getConstructor(
                    new Class[] { Composite.class }).newInstance(new Object[] { this });
            } catch (IllegalArgumentException e) {
                // "Could not find data type info for type " + type.getClass()
                DroolsEclipsePlugin.log(e);
                editor = new EmptyEditor(this);
            } catch (InstantiationException e) {
                // "Could not create editor for editor " + editorClass
                DroolsEclipsePlugin.log(e);
                editor = new EmptyEditor(this);
            } catch (NoSuchMethodException e) {
                // "Could not create editor for editor " + editorClass
                DroolsEclipsePlugin.log(e);
                editor = new EmptyEditor(this);
            } catch (InvocationTargetException e) {
                // "Could not create editor for editor " + editorClass
                DroolsEclipsePlugin.log(e);
                editor = new EmptyEditor(this);
            } catch (IllegalAccessException e) {
                // "Could not create editor for editor " + editorClass
                DroolsEclipsePlugin.log(e);
                editor = new EmptyEditor(this);
            }
            editor.setDataType(type);
            layout();
        }
    }

    public void setValue(Object value) {
        editor.setValue(value);
    }

    public Object getValue() {
        return editor.getValue();
    }

    public void reset() {
        editor.reset();
    }

    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        ((Composite) editor).setEnabled(enabled);
    }
}


text:
import os
import logging
import math

import numpy

try:
    from rdkit import Chem
    from rdkit.Chem import AllChem
except ImportError:
    logging.debug("To use QM calculations you must correctly install rdkit.")

import rmgpy.quantity
from rmgpy.thermo import ThermoData
import rmgpy.statmech
import rmgpy.thermo
import rmgpy.molecule
import symmetry
import qmdata
from qmdata import CCLibData

class Geometry:
    """
    A geometry, used for quantum calculations.

    Created from a molecule. Geometry estimated by RDKit.

    The attributes are:

    =================== ======================= ====================================
    Attribute           Type                    Description
    =================== ======================= ====================================
    `settings`          :class:`QMSettings`     Settings for QM calculations
    `uniqueID`          ``str``                 A short ID such as an augmented InChI Key
    `molecule`          :class:`Molecule`       RMG Molecule object
    `uniqueIDlong`      ``str``                 A long, truly unique ID such as an augmented InChI
    =================== ======================= ====================================

    """
    def __init__(self, settings, uniqueID, molecule, uniqueIDlong=None):
        self.settings = settings
        #: A short unique ID such as an augmented InChI Key.
        self.uniqueID = uniqueID
        self.molecule = molecule
        if uniqueIDlong is None:
            self.uniqueIDlong = uniqueID
        else:
            #: Long, truly unique, ID, such as the augmented InChI.
            self.uniqueIDlong = uniqueIDlong

        if self.settings:
            self.fileStore = self.settings.fileStore
            self.scratchDirectory = self.settings.scratchDirectory
        else:
            self.fileStore = None
            self.scratchDirectory = None

        if self.fileStore and not os.path.exists(self.fileStore):
            logging.info("Creating permanent directory %s for qm files."%os.path.abspath(self.fileStore))
            os.makedirs(self.fileStore)

        if self.scratchDirectory and not os.path.exists(self.scratchDirectory):
            logging.info("Creating scratch directory %s for qm files."%os.path.abspath(self.scratchDirectory))
            os.makedirs(self.scratchDirectory)

    def getFilePath(self, extension):
        """
        Returns the path to the file with the given extension.

        The provided extension should include the leading dot.
        """
        return os.path.join(self.settings.scratchDirectory, self.uniqueID  + extension)

    def getCrudeMolFilePath(self):
        "Returns the path of the crude mol file."
        return self.getFilePath('.crude.mol')

    def getRefinedMolFilePath(self):
        "Returns the path the the refined mol file."
        return self.getFilePath('.refined.mol')

    def generateRDKitGeometries(self):
        """
        Use RDKit to guess geometry.

        Save mol files of both crude and refined.
        Saves coordinates on atoms.
        """
        rdmol, rdAtIdx = self.rd_build()

        atoms = len(self.molecule.atoms)
        distGeomAttempts=1
        if atoms > 3:#this check prevents the number of attempts from being negative
            distGeomAttempts = 5*(atoms-3) #number of conformer attempts is just a linear scaling with molecule size, due to time considerations in practice, it is probably more like 3^(n-3) or something like that

        rdmol, minEid = self.rd_embed(rdmol, distGeomAttempts)
        self.saveCoordinatesFromRDMol(rdmol, minEid, rdAtIdx)

    def rd_build(self):
        """
        Import rmg molecule and create rdkit molecule with the same atom labeling.
        """
        return self.molecule.toRDKitMol(removeHs=False, returnMapping=True)

    def rd_embed(self, rdmol, numConfAttempts):
        """
        Embed the RDKit molecule and create the crude molecule file.
        """
        AllChem.EmbedMultipleConfs(rdmol, numConfAttempts,randomSeed=1)

        energy=0.0
        minEid=0;
        lowestE=9.999999e99;#start with a very high number, which would never be reached

        crude = Chem.Mol(rdmol.ToBinary())

        for i in range(rdmol.GetNumConformers()):
            AllChem.UFFOptimizeMolecule(rdmol,confId=i)
            energy=AllChem.UFFGetMoleculeForceField(rdmol,confId=i).CalcEnergy()
            if energy < lowestE:
                minEid = i
                lowestE = energy

        with open(self.getCrudeMolFilePath(), 'w') as out3Dcrude:
            out3Dcrude.write(Chem.MolToMolBlock(crude,confId=minEid))

        with open(self.getRefinedMolFilePath(), 'w') as out3D:
            out3D.write(Chem.MolToMolBlock(rdmol,confId=minEid))

        return rdmol, minEid

    def saveCoordinatesFromRDMol(self, rdmol, minEid, rdAtIdx):
        # Save xyz coordinates on each atom in molecule ****
        for atom in self.molecule.atoms:
            point = rdmol.GetConformer(minEid).GetAtomPosition(atom.sortingLabel)
            atom.coords = numpy.array([point.x, point.y, point.z])

    def saveCoordinatesFromQMData(self, qmdata):
        """
        Save geometry info from QMData (eg CCLibData)
        """
        raise NotImplementedError

def loadThermoDataFile(filePath):
    """
    Load the specified thermo data file and return the dictionary of its contents.

    Returns `None` if the file is invalid or missing.

    Checks that the returned dictionary contains at least InChI, adjacencyList, thermoData.
    """
    if not os.path.exists(filePath):
        return None
    try:
        with open(filePath) as resultFile:
            logging.info('Reading existing thermo file {0}'.format(filePath))
            global_context = { '__builtins__': None }
            local_context = {
                '__builtins__': None,
                'True': True,
                'False': False,
                'ThermoData': rmgpy.thermo.ThermoData,
                'PointGroup': symmetry.PointGroup,
                'QMData': qmdata.QMData,
                'array': numpy.array,
                'int32': numpy.int32,
            }
            exec resultFile in global_context, local_context
    except IOError, e:
        logging.info("Couldn't read thermo file {0}".format(filePath))
        return None
    except (NameError, TypeError, SyntaxError), e:
        logging.error('The thermo file "{0}" was invalid:'.format(filePath))
        logging.exception(e)
        return None
    if not 'InChI' in local_context:
        logging.error('The thermo file "{0}" did not contain an InChI.'.format(filePath))
        return None
    if not 'adjacencyList' in local_context:
        logging.error('The thermo file "{0}" did not contain adjacencyList.'.format(filePath))
        return None
    if not 'thermoData' in local_context:
        logging.error('The thermo file "{0}" did not contain thermoData.'.format(filePath))
        return None
    return local_context

class QMMolecule:
    """
    A base class for QM Molecule calculations.

    Specific programs and methods should inherit from this and define some
    extra attributes and methods:

     * outputFileExtension
     * inputFileExtension
     * generateQMData() ...and whatever else is needed to make this method work.

    The attributes are:

    =================== ======================= ====================================
    Attribute           Type                    Description
    =================== ======================= ====================================
    `molecule`          :class:`Molecule`       RMG Molecule object
    `settings`          :class:`QMSettings`     Settings for QM calculations
    `uniqueID`          ``str``                 A short ID such as an augmented InChI Key
    `uniqueIDlong`      ``str``                 A long, truly unique ID such as an augmented InChI
    =================== ======================= ====================================

    """

    def __init__(self, molecule, settings):
        self.molecule = molecule
        self.settings = settings

        self.uniqueID = self.molecule.toAugmentedInChIKey()
        self.uniqueIDlong = self.molecule.toAugmentedInChI()

    def getFilePath(self, extension):
        """
        Returns the path to the file with the given extension.

        The provided extension should include the leading dot.
        """
        return os.path.join(self.settings.scratchDirectory, self.uniqueID  + extension)

    @property
    def outputFilePath(self):
        """Get the output file name."""
        return self.getFilePath(self.outputFileExtension)

    @property
    def inputFilePath(self):
        """Get the input file name."""
        return self.getFilePath(self.inputFileExtension)

    def getThermoFilePath(self):
        "Returns the path the thermo data file."
        return os.path.join(self.settings.fileStore, self.uniqueID  + '.thermo')

    @property
    def scriptAttempts(self):
        "The number of attempts with different script keywords"
        return len(self.keywords)

    @property
    def maxAttempts(self):
        "The total number of attempts to try"
        return 2 * len(self.keywords)

    def initialize(self):
        """
        Do any startup tasks.
        """
        self.checkReady()

    def checkReady(self):
        """
        Check that it's ready to run calculations.
        """
        self.settings.checkAllSet()
        self.checkPaths()

    def checkPaths(self):
        """
        Check the paths in the settings are OK. Make folders as necessary.
        """
        if not os.path.exists(self.settings.RMG_bin_path):
            raise Exception("RMG-Py 'bin' directory {0} does not exist.".format(self.settings.RMG_bin_path))
        if not os.path.isdir(self.settings.RMG_bin_path):
            raise Exception("RMG-Py 'bin' directory {0} is not a directory.".format(self.settings.RMG_bin_path))

        self.settings.fileStore = os.path.expandvars(self.settings.fileStore) # to allow things like $HOME or $RMGpy
        self.settings.scratchDirectory = os.path.expandvars(self.settings.scratchDirectory)
        for path in [self.settings.fileStore, self.settings.scratchDirectory]:
            if not os.path.exists(path):
                logging.info("Creating directory %s for QM files."%os.path.abspath(path))
                os.makedirs(path)

    def createGeometry(self):
        """
        Creates self.geometry with RDKit geometries
        """
        self.geometry = Geometry(self.settings, self.uniqueID, self.molecule, uniqueIDlong=self.uniqueIDlong)
        self.geometry.generateRDKitGeometries()
        return self.geometry

    def parse(self):
        """
        Parses the results of the Mopac calculation, and returns a CCLibData object.
        """
        parser = self.getParser(self.outputFilePath)
        parser.logger.setLevel(logging.ERROR) #cf. http://cclib.sourceforge.net/wiki/index.php/Using_cclib#Additional_information
        cclibData = parser.parse()
        radicalNumber = self.molecule.getRadicalCount()
        qmData = CCLibData(cclibData, radicalNumber+1) # Should `radicalNumber+1` be `self.molecule.multiplicity` in the next line of code? It's the electronic ground state degeneracy.
        return qmData

    def generateQMData(self):
        """
        Calculate the QM data somehow and return a CCLibData object, or None if it fails.
        """
        raise NotImplementedError("This should be defined in a subclass that inherits from QMMolecule")
        return qmdata.QMData() or None

    def generateThermoData(self):
        """
        Generate Thermo Data via a QM calc.

        Returns None if it fails.
        """
        self.initialize()

        # First, see if we already have it.
        if self.loadThermoData():
            return self.thermo

        # If not, generate the QM data
        self.qmData = self.generateQMData()

        # If that fails, give up and return None.
        if self.qmData  is None:
            return None

        self.determinePointGroup()

        # If that fails, give up and return None.
        if self.pointGroup is None:
            return None

        self.calculateThermoData()
        Cp0 = self.molecule.calculateCp0()
        CpInf = self.molecule.calculateCpInf()
        self.thermo.Cp0 = (Cp0,"J/(mol*K)")
        self.thermo.CpInf = (CpInf,"J/(mol*K)")
        self.saveThermoData()
        return self.thermo

    def saveThermoData(self):
        """
        Save the generated thermo data.
        """
        self.thermo.H298.units = 'kcal/mol'
        self.thermo.S298.units = 'cal/mol/K'
        self.thermo.Cpdata.units = 'cal/mol/K'
        with open(self.getThermoFilePath(), 'w') as resultFile:
            resultFile.write('InChI = "{0!s}"\n'.format(self.uniqueIDlong))
            resultFile.write("thermoData = {0!r}\n".format(self.thermo))
            resultFile.write("pointGroup = {0!r}\n".format(self.pointGroup))
            resultFile.write("qmData = {0!r}\n".format(self.qmData))
            resultFile.write('adjacencyList = """\n{0!s}"""\n'.format(self.molecule.toAdjacencyList(removeH=False)))

    def loadThermoData(self):
        """
        Try loading a thermo data from a previous run.
        """
        filePath = self.getThermoFilePath()
        local_context = loadThermoDataFile(filePath)
        if local_context is None:
            # file does not exist or is invalid
            return None
        if local_context['InChI'] != self.uniqueIDlong:
            logging.error('The InChI in the thermo file {0} did not match the current molecule {1}'.format(filePath,self.uniqueIDlong))
            return None
        loadedMolecule = rmgpy.molecule.Molecule().fromAdjacencyList(local_context['adjacencyList'])
        if not loadedMolecule.isIsomorphic(self.molecule):
            logging.error('The adjacencyList in thermo file {0} did not match the current molecule {1}'.format(filePath,self.uniqueIDlong))
            return None
        thermo = local_context['thermoData']
        assert isinstance(thermo, rmgpy.thermo.ThermoData)
        self.thermo = thermo

        self.pointGroup = symmetry.pointGroupDictionary[local_context['pointGroup'].pointGroup] # point to the one in the module level dictionary with the same name
        self.qmData = local_context['qmData']
        return thermo

    def getInChiKeyAug(self):
        """
        Returns the augmented InChI from self.molecule
        """
        return self.molecule.toAugmentedInChIKey()

    def getMolFilePathForCalculation(self, attempt):
        """
        Get the path to the MOL file of the geometry to use for calculation `attempt`.

        If attempt <= self.scriptAttempts then we use the refined coordinates,
        then we start to use the crude coordinates.
        """
        if attempt <= self.scriptAttempts: # use UFF-refined coordinates
            return self.geometry.getRefinedMolFilePath()
        else:
            return self.geometry.getCrudeMolFilePath()

    def determinePointGroup(self):
        """
        Determine point group using the SYMMETRY Program

        Stores the resulting :class:`PointGroup` in self.pointGroup
        """
        assert self.qmData, "Need QM Data first in order to calculate point group."
        pgc = symmetry.PointGroupCalculator(self.settings, self.uniqueID, self.qmData)
        self.pointGroup = pgc.calculate()

    def calculateChiralityCorrection(self):
        """
        Returns the chirality correction to entropy (R*ln(2) if chiral) in J/mol/K.
        """
        if self.pointGroup.chiral:
            return rmgpy.quantity.constants.R * math.log(2)
        else:
            return 0.

    def calculateThermoData(self):
        """
        Calculate the thermodynamic properties.

        Stores and returns a ThermoData object as self.thermo.
        self.qmData and self.pointGroup need to be generated before this method is called.
        """
        assert self.qmData, "Need QM Data first in order to calculate thermo."
        assert self.pointGroup, "Need Point Group first in order to calculate thermo."

        trans = rmgpy.statmech.IdealGasTranslation( mass=self.qmData.molecularMass )
        if self.pointGroup.linear:
            # there should only be one rotational constant for a linear rotor
            rotationalConstant = rmgpy.quantity.Frequency(max(self.qmData.rotationalConstants.value), self.qmData.rotationalConstants.units)
            rot = rmgpy.statmech.LinearRotor(
                                         rotationalConstant = rotationalConstant,
                                         symmetry = self.pointGroup.symmetryNumber,
                                        )
        else:
            rot = rmgpy.statmech.NonlinearRotor(
                                         rotationalConstant = self.qmData.rotationalConstants,
                                         symmetry = self.pointGroup.symmetryNumber,
                                        )
        # @todo: should we worry about spherical top rotors?
        vib = rmgpy.statmech.HarmonicOscillator( frequencies=self.qmData.frequencies )

        # @todo: We need to extract or calculate E0 somehow from the qmdata
        E0 = (0, "kJ/mol")
        self.statesmodel = rmgpy.statmech.Conformer(E0=E0,
                                                    modes=[trans, rot, vib],
                                spinMultiplicity = self.qmData.groundStateDegeneracy )

        #we will use number of atoms from above (alternatively, we could use the chemGraph); this is needed to test whether the species is monoatomic
        # SI units are J/mol, but converted to kJ/mol for generating the thermo.
        Hf298 = self.qmData.energy.value_si / 1000

        S298 = self.statesmodel.getEntropy(298.0)
        Tdata = [300.0, 400.0, 500.0, 600.0, 800.0, 1000.0, 1500.0]
        Cp = [self.statesmodel.getHeatCapacity(T) for T in Tdata]
        S298 = S298 + self.calculateChiralityCorrection()
        comment = self.qmData.source or "QM calculation of some sort."

        thermo = ThermoData(
                           Tdata = (Tdata,"K"),
                           Cpdata = (Cp,"J/(mol*K)"),
                           H298 = (Hf298,"kJ/mol"),
                           S298 = (S298,"J/(mol*K)"),
                           Tmin = (300.0,"K"),
                           Tmax = (2000.0,"K"),
                           comment = comment
                          )
        self.thermo = thermo
        return thermo


text:
name: Feature request
about: Suggest an idea or improvement
labels: enhancement

---

<!--
## Before reporting
 - Search for the suggestion here. It's possible someone's suggested it before!
-->

## Useful information to include:
 - Explanation of how the feature/change should work.
 - Some rationale/use case for a feature. Everything takes time to implement, so I like to have a solid justification for each feature.