text:
--[[
	The MIT License (MIT)

	Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization)

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
]]

local _outputChatBox = outputChatBox
function outputChatBox( text, visibleTo, r, g, b, colorCoded )
	if ( string.len( text ) > 128 ) then
		_outputChatBox( string.sub( text, 1, 127 ), visibleTo, r, g, b, colorCoded )
		outputChatBox( " " .. string.sub( text, 128 ), visibleTo, r, g, b, colorCoded )
	else
		_outputChatBox( text, visibleTo, r, g, b, colorCoded )
	end
end

function outputLocalChat( player, message, originalDistance )
	if ( not exports.common:isPlayerPlaying( player ) ) then
		return
	end

	local posX, posY, posZ = getElementPosition( player )

	local vehicle = getPedOccupiedVehicle( player )
	local vehicleModel, vehicleType = "", "Vehicle"

	local isBike = false
	local isWindowless = false
	local isRoofless = false

	if ( vehicle ) then
		vehicleModel = getElementModel( vehicle ) or false
		vehicleType = getVehicleType( vehicle ) or false

		isBike = exports.vehicles:getBikeModels( )[ vehicleModel ] or false
		isWindowless = exports.vehicles:getWindowlessModels( )[ vehicleModel ] or false
		isRoofless = exports.vehicles:getRooflessModels( )[ vehicleModel ] or false
	end

	local vehiclePrefix = ""

	if ( vehicle ) then
		if ( isBike ) then
			vehiclePrefix = "(On Bike) "
		else
			if ( vehicleType == "Automobile" ) then
				vehiclePrefix = "(In Car) "
			else
				vehiclePrefix = "(In " .. vehicleType .. ") "
			end
		end
	end

	local senderLanguage, senderSkill = getPlayerLanguage( player, 1 )

	if ( not senderLanguage ) then
		outputChatBox( "Wops, you do not have a language!", player, 230, 95, 95 )
		return
	end

	local senderLanguageName = getLanguageName( senderLanguage )

	local languagePrefix = "[" .. senderLanguageName .. "] "

	distance = tonumber( originalDistance ) or 3000 * 3000 * 2

	for _, targetPlayer in ipairs( getElementsByType( "player" ) ) do
		local targetX, targetY, targetZ = getElementPosition( targetPlayer )
		local targetDistance = getDistanceBetweenPoints3D( posX, posY, posZ, targetX, targetY, targetZ )

		if ( distance == 10000 ) or ( targetDistance < distance ) and ( ( getElementInterior( targetPlayer ) == getElementInterior( player ) ) and ( getElementDimension( targetPlayer ) == getElementDimension( player ) ) ) then
			local r, g, b = 240, 240, 240

			if ( targetDistance > 8 ) then
				r, g, b = r - targetDistance * 2, g - targetDistance * 2, b - targetDistance * 2
			end

			if ( not hasLanguage( targetPlayer, senderLanguage ) ) then
				if ( player ~= targetPlayer ) then
					local length = string.len( message )
					local percent = 100 - math.min( getPlayerLanguageSkill( targetPlayer, senderLanguage ), senderSkill )
					local replace = ( percent / 100 ) * length

					if ( senderLanguage == 1337 ) then
						message = hash( "md5", message )
					else
						local i = 1

						while ( i < replace ) do
							local letter = string.sub( message, i, i )

							if ( letter ~= "" ) and ( letter ~= " " ) then
								local replaceLetter

								if ( string.byte( letter ) >= 65 ) and ( string.byte( letter ) <= 90 ) then
									replaceLetter = string.char(math.random( 65, 90 ) )
								elseif ( string.byte( letter ) >= 97 ) and ( string.byte( letter ) <= 122 ) then
									replaceLetter = string.char( math.random( 97, 122 ) )
								end

								if ( string.byte( letter ) >= 65 and string.byte( letter ) <= 90 ) or ( string.byte( letter ) >= 97 and string.byte( letter ) <= 122 ) then
									message = string.gsub( message, tostring( letter ), replaceLetter, 1 )
								end
							end

							i = i + 1
						end
					end
				end
			else
				if ( senderSkill < 100 ) then
					if ( senderSkill > getPlayerLanguageSkill( targetPlayer, senderLanguage ) ) or ( getPlayerLanguageSkill( targetPlayer, senderLanguage ) < 85 ) then
						increaseLanguageSkill( player, senderLanguage )
					end
				end
			end

			local typePrefix = ""

			if ( distance == 0.9 ) then
				typePrefix = "(Close Whisper) "
			elseif ( distance == 3 ) then
				typePrefix = "(Whisper) "
			elseif ( distance == 40 ) then
				typePrefix = "(Shout) "
			elseif ( distance == 60 ) then
				typePrefix = "(Megaphone) "
			end

			local isOnDuty = exports.common:isOnDuty( targetPlayer )
			local prefixes = typePrefix .. vehiclePrefix .. ( isOnDuty and languagePrefix or "" )

			message = exports.common:cleanString( message )

			local firstLetter, restMessage = string.upper( message:sub( 1, 1 ) ), message:sub( 2 )

			message = firstLetter .. restMessage

			if ( distance <= 60 ) then
				if ( ( vehicle ) and ( ( isOnDuty ) or ( ( not isOnDuty ) and ( exports.vehicles:isVehicleWindowsDown( vehicle ) or isBike or isWindowless or isRoofless or getPedOccupiedVehicle( targetPlayer ) == vehicle ) ) ) or ( not vehicle ) ) then
					outputChatBox( prefixes .. exports.common:getPlayerName( player ) .. " says: " .. message, targetPlayer, r, g, b, false )
				end
			else
				if ( originalDistance ) then
					if ( string.find( originalDistance, "r" ) ) then
						local frequency = string.gsub( originalDistance, "r", "" )

						if ( exports.items:hasItem( targetPlayer, 13, frequency ) ) or ( getDistanceBetweenPoints3D( posX, posY, posZ, targetX, targetY, targetZ ) <= 20 ) then
							outputChatBox( "[#" .. frequency .. "] " .. prefixes .. exports.common:getPlayerName( player ) .. " says: " .. message, targetPlayer, 95, 95, 220, false )
						end
					end
				end
			end
		end
	end
end

function outputLocalActionMe( player, action )
	if ( exports.common:isPlayerPlaying( player ) ) then
		local x, y, z = getElementPosition( player )
		local affected = ""

		action = exports.common:cleanString( action )

		for _, targetPlayer in ipairs( getElementsByType( "player" ) ) do
			local px, py, pz = getElementPosition( targetPlayer )
			local distance = getDistanceBetweenPoints3D( px, py, pz, x, y, z )

			if ( distance < 30 ) and ( getElementInterior( player ) == getElementInterior( targetPlayer ) ) and ( getElementDimension( player ) == getElementDimension( targetPlayer ) ) then
				outputChatBox( " *" .. exports.common:getPlayerName( player ) .. " " .. action, targetPlayer, 237, 116, 136, false )
			end
		end
	end
end


text:
var groupName;

function connectToBackend(backendURL) {
    jQuery.noConflict();
    var url = "connect_member_ajaxprocessor.jsp?backendURL=" + backendURL;
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while connecting to ' + backendURL + ". " + responseText);
        } else {
            CARBON.showInfoDialog('Successfully connected to ' + backendURL);
        }
    });
}

function shutdownGroupGracefully(_groupName) {
    jQuery.noConflict();
    groupName = _groupName;
    CARBON.showConfirmationDialog('Do you really want to gracefully shutdown the '+ groupName +' group?',shutdownGroupGracefullyCallback,null);
}

function shutdownGroupGracefullyCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=shutdownGracefully&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while gracefully shutting down the '+ groupName +' group');
        } else {
            CARBON.showInfoDialog('The '+ groupName +' is being gracefully shutdown.');
        }
    });
}

function shutdownGroup(_groupName) {
    jQuery.noConflict();
    groupName = _groupName;
    CARBON.showConfirmationDialog('Do you really want to shutdown the '+ groupName +' group?',shutdownGroupCallback,null);
}

function shutdownGroupCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=shutdown&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while shutting down the group');
        } else {
            CARBON.showInfoDialog('The group is being shutdown.');
        }
    });
}

function restartGroupGracefully(_groupName) {
    jQuery.noConflict();
    groupName = _groupName;
    CARBON.showConfirmationDialog('Do you really want to gracefully restart the ' + groupName + ' group?',restartGroupGracefullyCallback,null);
}

function restartGroupGracefullyCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=restartGracefully&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while gracefully restarting the ' + groupName +' group.');
        } else {
            CARBON.showInfoDialog('The '+ groupName +' group is being gracefully restarted.');
        }
    });
}

function restartGroup(_groupName) {
    jQuery.noConflict();
    groupName = _groupName;
    CARBON.showConfirmationDialog('Do you really want to restart the ' + groupName + ' group?',restartGroupCallback,null);
}

function restartGroupCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=restart&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while restarting group ' + groupName);
        } else {
            CARBON.showInfoDialog('The '+ groupName +' group is being restarted.');
        }
    });
}

function shutdownClusterGracefully() {
    jQuery.noConflict();
    CARBON.showConfirmationDialog('Do you really want to gracefully shutdown the cluster?',shutdownClusterGracefullyCallback,null);
}

function shutdownClusterGracefullyCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=shutdownGracefully";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while gracefully shutting down the cluster');
        } else {
            CARBON.showInfoDialog('The cluster is being gracefully shutdown.');
        }
    });
}

function shutdownCluster() {
    jQuery.noConflict();
    CARBON.showConfirmationDialog('Do you really want to shutdown cluster?',shutdownClusterCallback,null);
}

function shutdownClusterCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=shutdown";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while shutting down the cluster');
        } else {
            CARBON.showInfoDialog('The cluster is being shutdown.');
        }
    });
}

function restartClusterGracefully() {
    jQuery.noConflict();
    CARBON.showConfirmationDialog('Do you really want to gracefully restart the cluster?',restartClusterGracefullyCallback,null);
}

function restartClusterGracefullyCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=restartGracefully";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while gracefully restarting the cluster.');
        } else {
            CARBON.showInfoDialog('The cluster is being gracefully restarted.');
        }
    });
}

function restartCluster() {
    jQuery.noConflict();
    CARBON.showConfirmationDialog('Do you really want to restart the cluster?',restartClusterCallback,null);
}

function restartClusterCallback() {
    var url = "proxy_ajaxprocessor.jsp?action=restart";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while restarting cluster ');
        } else {
            CARBON.showInfoDialog('The cluster is being restarted.');
        }
    });
}

function startClusterMaintenance(){
    jQuery.noConflict();
    CARBON.showConfirmationDialog('Do you really want to start cluster maintenance?',startClusterMaintenanceCallback,null);
}

function startClusterMaintenanceCallback(){
    var url = "proxy_ajaxprocessor.jsp?action=startMaintenance";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while starting cluster maintenance');
        } else {
            CARBON.showInfoDialog('Cluster has been switched to maintenance mode');
        }
    });
}

function endClusterMaintenance(){
   jQuery.noConflict();
   CARBON.showConfirmationDialog('Do you really want to end cluster maintenance?',endClusterMaintenanceCallback,null);
}

function endClusterMaintenanceCallback(){
    var url = "proxy_ajaxprocessor.jsp?action=endMaintenance";
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while ending cluster maintenance');
        } else {
            CARBON.showInfoDialog('Cluster has been switched to normal mode');
        }
    });
}

function startGroupMaintenance(_groupName){
    jQuery.noConflict();
    groupName = _groupName;
    CARBON.showConfirmationDialog('Do you really want to start group maintenance?',startGroupMaintenanceCallback,null);
}

function startGroupMaintenanceCallback(){
    var url = "proxy_ajaxprocessor.jsp?action=startMaintenance&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while starting group maintenance');
        } else {
            CARBON.showInfoDialog('Group ' + groupName + '  has been switched to maintenance mode');
        }
    });
}

function endGroupMaintenance(_groupName){
   jQuery.noConflict();
   groupName = _groupName;
   CARBON.showConfirmationDialog('Do you really want to end group maintenance?',endGroupMaintenanceCallback,null);
}

function endGroupMaintenanceCallback(){
    var url = "proxy_ajaxprocessor.jsp?action=endMaintenance&groupName=" + groupName;
    jQuery.noConflict();
    jQuery("#output").load(url, null, function (responseText, status, XMLHttpRequest) {
        if (jQuery(responseText).text().replace(/ /g,'') != '') {
            CARBON.showWarningDialog(responseText);
            return;
        }
        if (status != "success") {
            CARBON.showErrorDialog('Error occurred while ending group maintenance');
        } else {
            CARBON.showInfoDialog('Group '+ groupName +' has been switched to normal mode');
        }
    });
}

redpajama_set_name: RedPajamaGithub


text:
package com.nokia.xfolite.client.ui;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

import de.enough.polish.ui.*;

/**
 * Reusable separator custom item that contains a text.
 */

public class LabeledSeparator
//#if polish.LibraryBuild
     extends FakeCustomItem {
//#else
//#  extends Item {
//#endif

    /**
     * The entries to be displayed.
     */
    protected String displayString;

    /**
     * The font.
     */
    protected Font font;

    /**
     * The font color.
     */
    protected int fontColor;

    /**
     * The line padding.
     */
    protected int linePadding = 2;

    /**
     * Constructor
     *
     * @param label -
     *            the label for this item
     * @param icon -
     *            icon for this entry.
     * @param displayText -
     *            the text to be displayed.
     * @param display - the display instance.
     * @param id -
     *            the identifier for this instance.
     */
    public LabeledSeparator(String displayText) {
        super(null);
        this.displayString = displayText;
        setAppearanceMode(PLAIN);
    }

    /**
     * Constructor
     *
     * @param label -
     *            the label for this item
     * @param icon -
     *            icon for this entry.
     * @param displayText -
     *            the text to be displayed.
     * @param id -
     *            the identifier for this instance.
     * @param Style -
     *            the style to be applied for this instance.
     */
    public LabeledSeparator(String displayText, Style style) {
        //#ifdef polish.usePolishGui
        //# super(style);
        //#else
        //# super(); //$NON-NLS-1$
        //#endif

        this.displayString = displayText;
        setAppearanceMode(PLAIN);
    }

    /**
     * Get the String to be displayed on the button.
     *
     * @return the String to be displayed on the button.
     */
    public String getDisplayString() {
        return displayString;
    }

    protected String createCssSelector() {
        return "separator";
    }

    /**
     * Initialize the graphic elements needed for this item.
     */
    protected void initContent(int firstLineWidth, int availWidth, int availHeight){
        if (this.font == null)
        {
            this.font = Font.getDefaultFont();
            this.fontColor = 0x000000;
        }
        contentHeight = font.getHeight() + this.linePadding;
        contentWidth = availWidth;
    }

    /**
     * Calcuate the minimum height needed for this instance.
     *
     * @param forWidth
     * @return
     */
    protected int calculateHeight(final int forWidth) {
        return this.font.getHeight();
    }

    public String getText() {
        return displayString;
    }

    public void setText(String text) {
        displayString = text;
        requestInit();
    }

    /**
     * @see de.enough.polish.ui.CustomItem#paint(javax.microedition.lcdui.Graphics, int, int)
     */
    // protected void paint(Graphics g, int w, int h) {
    protected void paintContent( int x, int y, int leftBorder, int rightBorder, Graphics g ) {
        final int c = y + contentHeight / 2;

        g.setColor(0x949494);
        g.setFont(this.font);

        if (displayString == null || displayString.length() == 0) {
            g.drawLine(leftBorder, c, rightBorder, c);
            return;
        }

        int totalStringWidth = this.font.stringWidth(displayString) + this.linePadding;
        if (this.isLayoutCenter) {
            totalStringWidth += this.linePadding;
        }

        int lineLen = rightBorder - leftBorder - totalStringWidth;
        if (this.isLayoutCenter) {
            lineLen /= 2;
        }

        if (this.isLayoutCenter || this.isLayoutRight) {
            g.drawLine(leftBorder, c, leftBorder + lineLen, c);
        } else {
            g.drawLine(leftBorder + totalStringWidth, c, leftBorder + totalStringWidth + lineLen, c);
        }

        g.setColor(this.fontColor);
        if (this.isLayoutCenter) {
            g.drawString(displayString, leftBorder + lineLen + this.linePadding, y, Graphics.LEFT | Graphics.TOP);
        } else if (this.isLayoutRight) {
            g.drawString(displayString, rightBorder, y, Graphics.RIGHT | Graphics.TOP);
        } else {
            g.drawString(displayString, leftBorder, y, Graphics.LEFT | Graphics.TOP);
        }
        if (this.isLayoutCenter) {
            g.setColor(0x949494);
            g.drawLine(leftBorder + lineLen + totalStringWidth, c, rightBorder, c);
        }
    }

    //#ifdef polish.usePolishGui
    public void setStyle(Style style) {
        super.setStyle(style);
        this.font = style.getFont();
        this.linePadding = style.getPaddingHorizontal(10);
        this.fontColor = style.getFontColor();
        requestInit();
    }
    //#endif
}


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

<resources>

    <string name="app_name">packlist</string>
    <string name="demo_changelog_title_standarddialog">Journal des changements</string>
    <string name="about_ok">OK</string>
    <string name="title_activity_about">A propos</string>
    <string name="toast_update_failed_incompatible_format">La mise à jour a échouée, il s\'agit probablement
        d\'une incompatibilité de version, recréez cet item ou ce voyage.
    </string>

    <string name="action__whatsnew">Quoi de neuf</string>
    <string name="action__send_logs">Envoyer un rapport</string>
    <string name="action__about">A propos</string>
    <string name="action_trip__sort">Trier</string>
    <string name="action_trip__import">Importer un fichier texte</string>
    <string name="action_trip__unpack_all">dépaqueter tous les items</string>

    <string name="about__main">Packing list %1$s.\n%2$s\nCopyright © 2015–2016\nNBossard et autres
        contributeurs.\n Apache 2 Licensed.\n Votre aide et vos suggestions sont les bienvenues sur \n
        https://github.com/nbossard/packlist
    </string>
    <string name="about__many_thanks_to_contributors">Many thanks to\n -naofum, for Japanese translation\n
        -Christophe Paccolat for German translations
    </string>
    <string name="about__third_party__button">Librairies tierces</string>
    <string name="about_act__fab_go_to_website">Ouvrir le site Internet</string>

    <string name="main__welcome">Voici la liste de vos voyages prévus, cliquez sur un pour voir son détail
    </string>
    <string name="main__no_trip_yet__label">Pas de voyage prévu… encore,\ncliquez sur le bouton \"+\" pour
        ajouter un voyage.
    </string>
    <string name="action_main_cab__clone">Dupliquer</string>
    <string name="action_main_cab__delete">Supprimer</string>
    <string name="mainact__fab_add_a_trip">Ajouter un nouveau voyage</string>
    <plurals name="ta__in_x_days">
        <item quantity="one">Dans %d jour.</item>
        <item quantity="other">Dans %d jours.</item>
    </plurals>
    <plurals name="ta__x_days_ago">
        <item quantity="one">Il y a %d jour.</item>
        <item quantity="other">Il y a %d jours.</item>
    </plurals>

    <string name="new_trip__name">Votre destination</string>
    <string name="new_trip__start_date">Date de début</string>
    <string name="new_trip__start_date_access__button">Modifier la date de début</string>
    <string name="new_trip__end_date">Date de fin</string>
    <string name="new_trip__end_date_access__button">Modifier la date de fin</string>
    <string name="new_trip__note">Notes</string>
    <string name="new_trip__submit">En voyage…</string>

    <string name="trip_detail__main__titlebar">Liste pour %1s</string>
    <string name="trip_detail__end_date__label">au</string>
    <string name="trip_detail__start_date__label">du</string>
    <string name="trip_detail__add_item___button">Ajouter</string>
    <string name="trip_detail__add_item_detail___button">+ détails</string>
    <string name="trip_detail__no_item_yet__label">Rien dans votre sac encore, utilisez le bouton ci-dessous
        pour ajouter
    </string>
    <string name="trip_detail__edit_trip">Modifier</string>
    <string name="trip_detail__before_weight__label">poids du sac : plus de %1$dg (%2$dg empaqueté).</string>
    <string name="trip_detail__new_item__access">nom…</string>
    <string name="trip_detail__new_item_magic___access">Bouton. Suggérer un item</string>
    <string name="trip_detail__already_existing_item">Cet article est déjà dans la liste.</string>
    <string name="action_trip_cab__delete">@string/action_main_cab__delete</string>
    <string name="action_trip_cab__edit">Modifier</string>
    <string name="action_trip__share">Partager</string>
    <string name="sorting_mode">Les articles sont désormais triés par %s.</string>
    <string name="sorting_mode_default">défaut</string>
    <string name="sorting_mode_unpacked_first">empaquetés ou non</string>
    <string name="sorting_mode_alphabetical">ordre alphabetique</string>
    <string name="sorting_mode_category">catégorie</string>

    <string name="help_legal__third_party__title">Librairies tierces</string>
    <string name="help_legal__third_party__label">
        librairies tierces
    </string>
    <string name="help_legal__third_party_lib_hugo__label">Hugo\nCopyright © 2013 Jake Wharton,\n(https://github.com/JakeWharton/hugo)\n Hugo est
        distribué sous la licence Apache, Version 2.0\n(

            http://www.apache.org/licenses/LICENSE-2.0.html

        )
    </string>
    <string name="help_legal__third_party_lib_gson__label">Gson\n(https://code.google.com/p/google-gson/)\nCopyright ©
        2004 Google\nGson est distribué sous la License Apache , Version 2.0\n(

            http://www.apache.org/licenses/LICENSE-2.0.html

        )
    </string>
    <string name="help_legal__third_party_lib_changelog__label">Changelog\n(
        https://github.com/gabrielemariotti/changeloglib)\nCopyright © 2004 gabriele
        mariotti\n/changeloglib est distribuée sous la licence Apache, Version 2.0\n(

            http://www.apache.org/licenses/LICENSE-2.0.html

        )
    </string>
    <string name="help_legal__third_party_lib_datetimepicker__label">DateTimePicker\n(
        https://github.com/flavienlaurent/datetimepicker)\nCopyright © 2015 Flavien
        Laurent\n/DateTimePicker est distribuée sous la licence Apache, Version 2.0\n(

            http://www.apache.org/licenses/LICENSE-2.0.html

        )
    </string>
    <string name="help_legal__third_party_lib__groovy_android_gradle_plugin__label">Groovy language support
        for Android\n(
        https://github.com/groovy/groovy-android-gradle-plugin)\nCopyright © 2016 l\'auteur
        d\'origine\n/groovy-android-gradle-plugin est distribuée sous la licence Apache, Version 2.0\n(

            http://www.apache.org/licenses/LICENSE-2.0.html

        )
    </string>
    <string name="help_legal__third_party_lib__acra__label">Application Crash Reporting for Android
        \nCopyright © 2013 Kevin Gaudin\nApplication Crash Reporting for Android est distribué sous la licence
        Apache, Version 2.0\n(
            http://www.apache.org/licenses/LICENSE-2.0.html)
    </string>
    <string name="help_legal__third_party_lib__mli__label">Material Letter Icon\nCopyright © 2016
        IvBaranov\nMaterial Letter Icon est distribué sous la licence Apache License, Version 2.0\n(
            http://www.apache.org/licenses/LICENSE-2.0.html)
    </string>

    <string name="item_detail__name__label">nom</string>
    <string name="item_detail__weight__label">poids (en grammes)</string>
    <string name="item_detail__submit">MODIFIER</string>
    <string name="item_detail__category__label">Catégorie</string>

    <string name="mass_import__principle_explanation_new_trip__label">This dialog is for help of mass import
        of items into a new trip, paste your existing list of items below. One item per
        line.\n\ni.e.:\nVarious:Guide book (100g).
    </string>
    <string name="mass_import__principle_explanation_with_name__label">This dialog is for help of mass import
        of items into trip \"%1$s\", paste your existing list of items below. One item per
        line.\n\ni.e.:\nVarious:Guide book (100g).
    </string>
    <string name="mass_import__import__button">Importer</string>
    <string name="mass_import__items__hint">saisissez ou collez ici…</string>

    <string name="acra__crash_report_dialog__label">Cliquer sur OK pour envoyer les logs de l\'application
    </string>
</resources>


text:
"""Skia's Chromium DEPS roll script.

This script:
- searches through the last N Skia git commits to find out the hash that is
  associated with the SVN revision number.
- creates a new branch in the Chromium tree, modifies the DEPS file to
  point at the given Skia commit, commits, uploads to Rietveld, and
  deletes the local copy of the branch.
- creates a whitespace-only commit and uploads that to to Rietveld.
- returns the Chromium tree to its previous state.

Usage:
  %prog -c CHROMIUM_PATH -r REVISION [OPTIONAL_OPTIONS]
"""

import optparse
import os
import re
import shutil
import subprocess
import sys
import tempfile

class DepsRollConfig(object):
    """Contains configuration options for this module.

    Attributes:
        git: (string) The git executable.
        chromium_path: (string) path to a local chromium git repository.
        save_branches: (boolean) iff false, delete temporary branches.
        verbose: (boolean)  iff false, suppress the output from git-cl.
        search_depth: (int) how far back to look for the revision.
        skia_url: (string) Skia's git repository.
        self.skip_cl_upload: (boolean)
        self.cl_bot_list: (list of strings)
    """

    # pylint: disable=I0011,R0903,R0902
    def __init__(self, options=None):
        self.skia_url = 'https://skia.googlesource.com/skia.git'
        self.revision_format = (
            'git-svn-id: http://skia.googlecode.com/svn/trunk@%d ')

        if not options:
            options = DepsRollConfig.GetOptionParser()
        # pylint: disable=I0011,E1103
        self.verbose = options.verbose
        self.vsp = VerboseSubprocess(self.verbose)
        self.save_branches = not options.delete_branches
        self.search_depth = options.search_depth
        self.chromium_path = options.chromium_path
        self.git = options.git_path
        self.skip_cl_upload = options.skip_cl_upload
        # Split and remove empty strigns from the bot list.
        self.cl_bot_list = [bot for bot in options.bots.split(',') if bot]
        self.skia_git_checkout_path = options.skia_git_path
        self.default_branch_name = 'autogenerated_deps_roll_branch'

    @staticmethod
    def GetOptionParser():
        # pylint: disable=I0011,C0103
        """Returns an optparse.OptionParser object.

        Returns:
            An optparse.OptionParser object.

        Called by the main() function.
        """
        default_bots_list = [
            'android_clang_dbg',
            'android_dbg',
            'android_rel',
            'cros_daisy',
            'linux',
            'linux_asan',
            'linux_chromeos',
            'linux_chromeos_asan',
            'linux_gpu',
            'linux_heapcheck',
            'linux_layout',
            'linux_layout_rel',
            'mac',
            'mac_asan',
            'mac_gpu',
            'mac_layout',
            'mac_layout_rel',
            'win',
            'win_gpu',
            'win_layout',
            'win_layout_rel',
            ]

        option_parser = optparse.OptionParser(usage=__doc__)
        # Anyone using this script on a regular basis should set the
        # CHROMIUM_CHECKOUT_PATH environment variable.
        option_parser.add_option(
            '-c', '--chromium_path', help='Path to local Chromium Git'
            ' repository checkout, defaults to CHROMIUM_CHECKOUT_PATH'
            ' if that environment variable is set.',
            default=os.environ.get('CHROMIUM_CHECKOUT_PATH'))
        option_parser.add_option(
            '-r', '--revision', type='int', default=None,
            help='The Skia SVN revision number, defaults to top of tree.')
        option_parser.add_option(
            '-g', '--git_hash', default=None,
            help='A partial Skia Git hash.  Do not set this and revision.')

        # Anyone using this script on a regular basis should set the
        # SKIA_GIT_CHECKOUT_PATH environment variable.
        option_parser.add_option(
            '', '--skia_git_path',
            help='Path of a pure-git Skia repository checkout.  If empty,'
            ' a temporary will be cloned.  Defaults to SKIA_GIT_CHECKOUT'
            '_PATH, if that environment variable is set.',
            default=os.environ.get('SKIA_GIT_CHECKOUT_PATH'))
        option_parser.add_option(
            '', '--search_depth', type='int', default=100,
            help='How far back to look for the revision.')
        option_parser.add_option(
            '', '--git_path', help='Git executable, defaults to "git".',
            default='git')
        option_parser.add_option(
            '', '--delete_branches', help='Delete the temporary branches',
            action='store_true', dest='delete_branches', default=False)
        option_parser.add_option(
            '', '--verbose', help='Do not suppress the output from `git cl`.',
            action='store_true', dest='verbose', default=False)
        option_parser.add_option(
            '', '--skip_cl_upload', help='Skip the cl upload step; useful'
            ' for testing or with --save_branches.',
            action='store_true', default=False)

        default_bots_help = (
            'Comma-separated list of bots, defaults to a list of %d bots.'
            '  To skip `git cl try`, set this to an empty string.'
            % len(default_bots_list))
        default_bots = ','.join(default_bots_list)
        option_parser.add_option(
            '', '--bots', help=default_bots_help, default=default_bots)

        return option_parser

def test_git_executable(git_executable):
    """Test the git executable.

    Args:
        git_executable: git executable path.
    Returns:
        True if test is successful.
    """
    with open(os.devnull, 'w') as devnull:
        try:
            subprocess.call([git_executable, '--version'], stdout=devnull)
        except (OSError,):
            return False
    return True

class DepsRollError(Exception):
    """Exceptions specific to this module."""
    pass

class VerboseSubprocess(object):
    """Call subprocess methods, but print out command before executing.

    Attributes:
        verbose: (boolean) should we print out the command or not.  If
                 not, this is the same as calling the subprocess method
        quiet: (boolean) suppress stdout on check_call and call.
        prefix: (string) When verbose, what to print before each command.
    """

    def __init__(self, verbose):
        self.verbose = verbose
        self.quiet = not verbose
        self.prefix = '~~$ '

    @staticmethod
    def _fix(string):
        """Quote and escape a string if necessary."""
        if ' ' in string or '\n' in string:
            string = '"%s"' % string.replace('\n', '\\n')
        return string

    @staticmethod
    def print_subprocess_args(prefix, *args, **kwargs):
        """Print out args in a human-readable manner."""
        if 'cwd' in kwargs:
            print '%scd %s' % (prefix, kwargs['cwd'])
        print prefix + ' '.join(VerboseSubprocess._fix(arg) for arg in args[0])
        if 'cwd' in kwargs:
            print '%scd -' % prefix

    def check_call(self, *args, **kwargs):
        """Wrapper for subprocess.check_call().

        Args:
            *args: to be passed to subprocess.check_call()
            **kwargs: to be passed to subprocess.check_call()
        Returns:
            Whatever subprocess.check_call() returns.
        Raises:
            OSError or subprocess.CalledProcessError: raised by check_call.
        """
        if self.verbose:
            self.print_subprocess_args(self.prefix, *args, **kwargs)
        if self.quiet:
            with open(os.devnull, 'w') as devnull:
                return subprocess.check_call(*args, stdout=devnull, **kwargs)
        else:
            return subprocess.check_call(*args, **kwargs)

    def call(self, *args, **kwargs):
        """Wrapper for subprocess.check().

        Args:
            *args: to be passed to subprocess.check_call()
            **kwargs: to be passed to subprocess.check_call()
        Returns:
            Whatever subprocess.call() returns.
        Raises:
            OSError or subprocess.CalledProcessError: raised by call.
        """
        if self.verbose:
            self.print_subprocess_args(self.prefix, *args, **kwargs)
        if self.quiet:
            with open(os.devnull, 'w') as devnull:
                return subprocess.call(*args, stdout=devnull, **kwargs)
        else:
            return subprocess.call(*args, **kwargs)

    def check_output(self, *args, **kwargs):
        """Wrapper for subprocess.check_output().

        Args:
            *args: to be passed to subprocess.check_output()
            **kwargs: to be passed to subprocess.check_output()
        Returns:
            Whatever subprocess.check_output() returns.
        Raises:
            OSError or subprocess.CalledProcessError: raised by check_output.
        """
        if self.verbose:
            self.print_subprocess_args(self.prefix, *args, **kwargs)
        return subprocess.check_output(*args, **kwargs)

    def strip_output(self, *args, **kwargs):
        """Wrap subprocess.check_output and str.strip().

        Pass the given arguments into subprocess.check_output() and return
        the results, after stripping any excess whitespace.

        Args:
            *args: to be passed to subprocess.check_output()
            **kwargs: to be passed to subprocess.check_output()

        Returns:
            The output of the process as a string without leading or
            trailing whitespace.
        Raises:
            OSError or subprocess.CalledProcessError: raised by check_output.
        """
        if self.verbose:
            self.print_subprocess_args(self.prefix, *args, **kwargs)
        return str(subprocess.check_output(*args, **kwargs)).strip()

    def popen(self, *args, **kwargs):
        """Wrapper for subprocess.Popen().

        Args:
            *args: to be passed to subprocess.Popen()
            **kwargs: to be passed to subprocess.Popen()
        Returns:
            The output of subprocess.Popen()
        Raises:
            OSError or subprocess.CalledProcessError: raised by Popen.
        """
        if self.verbose:
            self.print_subprocess_args(self.prefix, *args, **kwargs)
        return subprocess.Popen(*args, **kwargs)

class ChangeDir(object):
    """Use with a with-statement to temporarily change directories."""
    # pylint: disable=I0011,R0903

    def __init__(self, directory, verbose=False):
        self._directory = directory
        self._verbose = verbose

    def __enter__(self):
        if self._verbose:
            print '~~$ cd %s' % self._directory
        cwd = os.getcwd()
        os.chdir(self._directory)
        self._directory = cwd

    def __exit__(self, etype, value, traceback):
        if self._verbose:
            print '~~$ cd %s' % self._directory
        os.chdir(self._directory)

class ReSearch(object):
    """A collection of static methods for regexing things."""

    @staticmethod
    def search_within_stream(input_stream, pattern, default=None):
        """Search for regular expression in a file-like object.

        Opens a file for reading and searches line by line for a match to
        the regex and returns the parenthesized group named return for the
        first match.  Does not search across newlines.

        For example:
            pattern = '^root(:[^:]*){4}:(?P<return>[^:]*)'
            with open('/etc/passwd', 'r') as stream:
                return search_within_file(stream, pattern)
        should return root's home directory (/root on my system).

        Args:
            input_stream: file-like object to be read
            pattern: (string) to be passed to re.compile
            default: what to return if no match

        Returns:
            A string or whatever default is
        """
        pattern_object = re.compile(pattern)
        for line in input_stream:
            match = pattern_object.search(line)
            if match:
                return match.group('return')
        return default

    @staticmethod
    def search_within_string(input_string, pattern, default=None):
        """Search for regular expression in a string.

        Args:
            input_string: (string) to be searched
            pattern: (string) to be passed to re.compile
            default: what to return if no match

        Returns:
            A string or whatever default is
        """
        match = re.search(pattern, input_string)
        return match.group('return') if match else default

    @staticmethod
    def search_within_output(verbose, pattern, default, *args, **kwargs):
        """Search for regular expression in a process output.

        Does not search across newlines.

        Args:
            verbose: (boolean) shoule we call
                     VerboseSubprocess.print_subprocess_args?
            pattern: (string) to be passed to re.compile
            default: what to return if no match
            *args: to be passed to subprocess.Popen()
            **kwargs: to be passed to subprocess.Popen()

        Returns:
            A string or whatever default is
        """
        if verbose:
            VerboseSubprocess.print_subprocess_args(
                '~~$ ', *args, **kwargs)
        proc = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
        return ReSearch.search_within_stream(proc.stdout, pattern, default)

def get_svn_revision(config, commit):
    """Works in both git and git-svn. returns a string."""
    svn_format = (
        '(git-svn-id: [^@ ]+@|SVN changes up to revision |'
        'LKGR w/ DEPS up to revision )(?P<return>[0-9]+)')
    svn_revision = ReSearch.search_within_output(
        config.verbose, svn_format, None,
        [config.git, 'log', '-n', '1', '--format=format:%B', commit])
    if not svn_revision:
        raise DepsRollError(
            'Revision number missing from Chromium origin/master.')
    return int(svn_revision)

class SkiaGitCheckout(object):
    """Class to create a temporary skia git checkout, if necessary.
    """
    # pylint: disable=I0011,R0903

    def __init__(self, config, depth):
        self._config = config
        self._depth = depth
        self._use_temp = None
        self._original_cwd = None

    def __enter__(self):
        config = self._config
        git = config.git
        skia_dir = None
        self._original_cwd = os.getcwd()
        if config.skia_git_checkout_path:
            skia_dir = config.skia_git_checkout_path
            ## Update origin/master if needed.
            if self._config.verbose:
                print '~~$', 'cd', skia_dir
            os.chdir(skia_dir)
            config.vsp.check_call([git, 'fetch', '-q', 'origin'])
            self._use_temp = None
        else:
            skia_dir = tempfile.mkdtemp(prefix='git_skia_tmp_')
            self._use_temp = skia_dir
            try:
                os.chdir(skia_dir)
                config.vsp.check_call(
                    [git, 'clone', '-q', '--depth=%d' % self._depth,
                     '--single-branch', config.skia_url, '.'])
            except (OSError, subprocess.CalledProcessError) as error:
                shutil.rmtree(skia_dir)
                raise error

    def __exit__(self, etype, value, traceback):
        if self._config.verbose:
            print '~~$', 'cd', self._original_cwd
        os.chdir(self._original_cwd)
        if self._use_temp:
            shutil.rmtree(self._use_temp)

def revision_and_hash(config):
    """Finds revision number and git hash of origin/master in the Skia tree.

    Args:
        config: (roll_deps.DepsRollConfig) object containing options.

    Returns:
        A tuple (revision, hash)
            revision: (int) SVN revision number.
            git_hash: (string) full Git commit hash.

    Raises:
        roll_deps.DepsRollError: if the revision can't be found.
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """
    with SkiaGitCheckout(config, 1):
        revision = get_svn_revision(config, 'origin/master')
        git_hash = config.vsp.strip_output(
            [config.git, 'show-ref', 'origin/master', '--hash'])
        if not git_hash:
            raise DepsRollError('Git hash can not be found.')
    return revision, git_hash

def revision_and_hash_from_revision(config, revision):
    """Finds revision number and git hash of a commit in the Skia tree.

    Args:
        config: (roll_deps.DepsRollConfig) object containing options.
        revision: (int) SVN revision number.

    Returns:
        A tuple (revision, hash)
            revision: (int) SVN revision number.
            git_hash: (string) full Git commit hash.

    Raises:
        roll_deps.DepsRollError: if the revision can't be found.
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """
    with SkiaGitCheckout(config, config.search_depth):
        revision_regex = config.revision_format % revision
        git_hash = config.vsp.strip_output(
            [config.git, 'log', '--grep', revision_regex,
             '--format=format:%H', 'origin/master'])
        if not git_hash:
            raise DepsRollError('Git hash can not be found.')
    return revision, git_hash

def revision_and_hash_from_partial(config, partial_hash):
    """Returns the SVN revision number and full git hash.

    Args:
        config: (roll_deps.DepsRollConfig) object containing options.
        partial_hash: (string) Partial git commit hash.

    Returns:
        A tuple (revision, hash)
            revision: (int) SVN revision number.
            git_hash: (string) full Git commit hash.

    Raises:
        roll_deps.DepsRollError: if the revision can't be found.
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """
    with SkiaGitCheckout(config, config.search_depth):
        git_hash = config.vsp.strip_output(
            ['git', 'log', '-n', '1', '--format=format:%H', partial_hash])
        if not git_hash:
            raise DepsRollError('Partial Git hash can not be found.')
        revision = get_svn_revision(config, git_hash)
    return revision, git_hash

class GitBranchCLUpload(object):
    """Class to manage git branches and git-cl-upload.

    This class allows one to create a new branch in a repository based
    off of origin/master, make changes to the tree inside the
    with-block, upload that new branch to Rietveld, restore the original
    tree state, and delete the local copy of the new branch.

    See roll_deps() for an example of use.

    Constructor Args:
        config: (roll_deps.DepsRollConfig) object containing options.
        message: (string) the commit message, can be multiline.
        set_brach_name: (string or none) if not None, the name of the
            branch to use.  If None, then use a temporary branch that
            will be deleted.

    Attributes:
        issue: a string describing the codereview issue, after __exit__
            has been called, othrwise, None.

    Raises:
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """
    # pylint: disable=I0011,R0903,R0902

    def __init__(self, config, message, set_branch_name):
        self._message = message
        self._file_list = []
        self._branch_name = set_branch_name
        self._stash = None
        self._original_branch = None
        self._config = config
        self.issue = None

    def stage_for_commit(self, *paths):
        """Calls `git add ...` on each argument.

        Args:
            *paths: (list of strings) list of filenames to pass to `git add`.
        """
        self._file_list.extend(paths)

    def __enter__(self):
        git = self._config.git
        vsp = self._config.vsp
        def branch_exists(branch):
            """Return true iff branch exists."""
            return 0 == vsp.call([git, 'show-ref', '--quiet', branch])
        def has_diff():
            """Return true iff repository has uncommited changes."""
            return bool(vsp.call([git, 'diff', '--quiet', 'HEAD']))

        self._stash = has_diff()
        if self._stash:
            vsp.check_call([git, 'stash', 'save'])
        try:
            full_branch = vsp.strip_output([git, 'symbolic-ref', 'HEAD'])
            self._original_branch = full_branch.split('/')[-1]
        except (subprocess.CalledProcessError,):
            self._original_branch = vsp.strip_output(
                [git, 'rev-parse', 'HEAD'])

        if not self._branch_name:
            self._branch_name = self._config.default_branch_name

        if branch_exists(self._branch_name):
            vsp.check_call([git, 'checkout', '-q', 'master'])
            vsp.check_call([git, 'branch', '-D', self._branch_name])

        vsp.check_call(
            [git, 'checkout', '-q', '-b', self._branch_name, 'origin/master'])

    def __exit__(self, etype, value, traceback):
        # pylint: disable=I0011,R0912
        git = self._config.git
        vsp = self._config.vsp
        svn_info = str(get_svn_revision(self._config, 'HEAD'))

        for filename in self._file_list:
            assert os.path.exists(filename)
            vsp.check_call([git, 'add', filename])
        vsp.check_call([git, 'commit', '-q', '-m', self._message])

        git_cl = [git, 'cl', 'upload', '-f', '--cc=skia-team@google.com',
                  '--bypass-hooks', '--bypass-watchlists']
        git_try = [git, 'cl', 'try', '--revision', svn_info]
        git_try.extend([arg for bot in self._config.cl_bot_list
                        for arg in ('-b', bot)])

        if self._config.skip_cl_upload:
            print 'You should call:'
            print '    cd %s' % os.getcwd()
            VerboseSubprocess.print_subprocess_args(
                '    ', [git, 'checkout', self._branch_name])
            VerboseSubprocess.print_subprocess_args('    ', git_cl)
            if self._config.cl_bot_list:
                VerboseSubprocess.print_subprocess_args('    ', git_try)
            print
            self.issue = ''
        else:
            vsp.check_call(git_cl)
            self.issue = vsp.strip_output([git, 'cl', 'issue'])
            if self._config.cl_bot_list:
                vsp.check_call(git_try)

        # deal with the aftermath of failed executions of this script.
        if self._config.default_branch_name == self._original_branch:
            self._original_branch = 'master'
        vsp.check_call([git, 'checkout', '-q', self._original_branch])

        if self._config.default_branch_name == self._branch_name:
            vsp.check_call([git, 'branch', '-D', self._branch_name])
        if self._stash:
            vsp.check_call([git, 'stash', 'pop'])

def change_skia_deps(revision, git_hash, depspath):
    """Update the DEPS file.

    Modify the skia_revision and skia_hash entries in the given DEPS file.

    Args:
        revision: (int) Skia SVN revision.
        git_hash: (string) Skia Git hash.
        depspath: (string) path to DEPS file.
    """
    temp_file = tempfile.NamedTemporaryFile(delete=False,
                                            prefix='skia_DEPS_ROLL_tmp_')
    try:
        deps_regex_rev = re.compile('"skia_revision": "[0-9]*",')
        deps_regex_hash = re.compile('"skia_hash": "[0-9a-f]*",')

        deps_regex_rev_repl = '"skia_revision": "%d",' % revision
        deps_regex_hash_repl = '"skia_hash": "%s",' % git_hash

        with open(depspath, 'r') as input_stream:
            for line in input_stream:
                line = deps_regex_rev.sub(deps_regex_rev_repl, line)
                line = deps_regex_hash.sub(deps_regex_hash_repl, line)
                temp_file.write(line)
    finally:
        temp_file.close()
    shutil.move(temp_file.name, depspath)

def roll_deps(config, revision, git_hash):
    """Upload changed DEPS and a whitespace change.

    Given the correct git_hash, create two Reitveld issues.

    Args:
        config: (roll_deps.DepsRollConfig) object containing options.
        revision: (int) Skia SVN revision.
        git_hash: (string) Skia Git hash.

    Returns:
        a tuple containing textual description of the two issues.

    Raises:
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """

    git = config.git
    with ChangeDir(config.chromium_path, config.verbose):
        config.vsp.check_call([git, 'fetch', '-q', 'origin'])

        old_revision = ReSearch.search_within_output(
            config.verbose, '"skia_revision": "(?P<return>[0-9]+)",', None,
            [git, 'show', 'origin/master:DEPS'])
        assert old_revision
        if revision == int(old_revision):
            print 'DEPS is up to date!'
            return None

        master_hash = config.vsp.strip_output(
            [git, 'show-ref', 'origin/master', '--hash'])
        master_revision = get_svn_revision(config, 'origin/master')

        branch = None

        # master_hash[8] gives each whitespace CL a unique name.
        message = ('whitespace change %s\n\n'
                   'Chromium base revision: %d / %s\n\n'
                   'This CL was created by Skia\'s roll_deps.py script.\n'
                  ) % (master_hash[:8], master_revision, master_hash[:8])
        if config.save_branches:
            branch = 'control_%s' % master_hash[:8]

        codereview = GitBranchCLUpload(config, message, branch)
        with codereview:
            with open('build/whitespace_file.txt', 'a') as output_stream:
                output_stream.write('\nCONTROL\n')
            codereview.stage_for_commit('build/whitespace_file.txt')
        whitespace_cl = codereview.issue
        if branch:
            whitespace_cl = '%s\n    branch: %s' % (whitespace_cl, branch)

        control_url = ReSearch.search_within_string(
            codereview.issue, '(?P<return>https?://[^) ]+)', '?')

        if config.save_branches:
            branch = 'roll_%d_%s' % (revision, master_hash[:8])
        message = (
            'roll skia DEPS to %d\n\n'
            'Chromium base revision: %d / %s\n'
            'Old Skia revision: %s\n'
            'New Skia revision: %d\n'
            'Control CL: %s\n\n'
            'This CL was created by Skia\'s roll_deps.py script.\n'
            % (revision, master_revision, master_hash[:8],
               old_revision, revision, control_url))
        codereview = GitBranchCLUpload(config, message, branch)
        with codereview:
            change_skia_deps(revision, git_hash, 'DEPS')
            codereview.stage_for_commit('DEPS')
        deps_cl = codereview.issue
        if branch:
            deps_cl = '%s\n    branch: %s' % (deps_cl, branch)

        return deps_cl, whitespace_cl

def find_hash_and_roll_deps(config, revision=None, partial_hash=None):
    """Call find_hash_from_revision() and roll_deps().

    The calls to git will be verbose on standard output.  After a
    successful upload of both issues, print links to the new
    codereview issues.

    Args:
        config: (roll_deps.DepsRollConfig) object containing options.
        revision: (int or None) the Skia SVN revision number or None
            to use the tip of the tree.
        partial_hash: (string or None) a partial pure-git Skia commit
            hash.  Don't pass both partial_hash and revision.

    Raises:
        roll_deps.DepsRollError: if the revision can't be found.
        OSError: failed to execute git or git-cl.
        subprocess.CalledProcessError: git returned unexpected status.
    """

    if revision and partial_hash:
        raise DepsRollError('Pass revision or partial_hash, not both.')

    if partial_hash:
        revision, git_hash = revision_and_hash_from_partial(
            config, partial_hash)
    elif revision:
        revision, git_hash = revision_and_hash_from_revision(config, revision)
    else:
        revision, git_hash = revision_and_hash(config)

    print 'revision=%r\nhash=%r\n' % (revision, git_hash)

    roll = roll_deps(config, revision, git_hash)

    if roll:
        deps_issue, whitespace_issue = roll
        print 'DEPS roll:\n    %s\n' % deps_issue
        print 'Whitespace change:\n    %s\n' % whitespace_issue

def main(args):
    """main function; see module-level docstring and GetOptionParser help.

    Args:
        args: sys.argv[1:]-type argument list.
    """
    option_parser = DepsRollConfig.GetOptionParser()
    options = option_parser.parse_args(args)[0]

    if not options.chromium_path:
        option_parser.error('Must specify chromium_path.')
    if not os.path.isdir(options.chromium_path):
        option_parser.error('chromium_path must be a directory.')
    if not test_git_executable(options.git_path):
        option_parser.error('Invalid git executable.')

    config = DepsRollConfig(options)
    find_hash_and_roll_deps(config, options.revision, options.git_hash)

if __name__ == '__main__':
    main(sys.argv[1:])


text:
"""
Tests for the depths module.
"""

import itertools

import astropy.units as u
import numpy as np
import pytest
from astropy.convolution import convolve
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils.exceptions import AstropyUserWarning
from numpy.testing import assert_allclose

from photutils.datasets import make_100gaussians_image
from photutils.segmentation import SourceFinder, make_2dgaussian_kernel
from photutils.utils._optional_deps import HAS_SCIPY  # noqa
from photutils.utils.depths import ImageDepth

bool_vals = (True, False)

@pytest.mark.skipif(not HAS_SCIPY, reason='scipy is required')
class TestImageDepth:
    def setup_class(self):
        bkg = 5.0
        data = make_100gaussians_image() - bkg
        kernel = make_2dgaussian_kernel(3.0, size=5)
        convolved_data = convolve(data, kernel)

        npixels = 10
        threshold = 3.2
        finder = SourceFinder(npixels=npixels, progress_bar=False)
        segment_map = finder(convolved_data, threshold)
        self.data = data
        self.mask = segment_map.make_source_mask()

    @pytest.mark.parametrize(('units', 'overlap'),
                             list(itertools.product(bool_vals, bool_vals)))
    def test_image_depth(self, units, overlap):
        radius = 4
        depth = ImageDepth(radius, nsigma=5.0, napers=100, niters=2,
                           overlap=overlap, seed=123, zeropoint=23.9,
                           progress_bar=False)

        if overlap:
            exp_limits = (66.60324687694235, 19.341261496655026)
        else:
            exp_limits = (67.65345151009167, 19.324275104703975)

        data = self.data
        fluxlim = exp_limits[0]
        if units:
            data = self.data * u.Jy
            fluxlim *= u.Jy

        limits = depth(data, self.mask)
        assert_allclose(limits[1], exp_limits[1])

        if not units:
            assert_allclose(limits[0], fluxlim)
        else:
            assert_quantity_allclose(limits[0], fluxlim)

    def test_mask_none(self):
        radius = 4
        depth = ImageDepth(radius, nsigma=5.0, napers=100, niters=2,
                           overlap=True, seed=123, zeropoint=23.9,
                           progress_bar=False)
        limits = depth(self.data, mask=None)
        assert_allclose(limits, (65.21122793974521, 19.36419405467095))

    def test_many_apertures(self):
        radius = 4
        depth = ImageDepth(radius, nsigma=5.0, napers=5000, niters=2,
                           overlap=True, seed=123, zeropoint=23.9,
                           progress_bar=False)
        mask = np.zeros(self.data.shape)
        mask[:, 20:] = True
        with pytest.raises(ValueError):
            depth(self.data, mask)

        depth = ImageDepth(radius, nsigma=5.0, napers=200, niters=2,
                           overlap=False, seed=123, zeropoint=23.9,
                           progress_bar=False)
        mask = np.zeros(self.data.shape)
        mask[:, 100:] = True
        with pytest.warns(AstropyUserWarning, match='Unable to generate'):
            depth(self.data, mask)

        # test for zero non-overlapping apertures before slow loop
        radius = 5
        depth = ImageDepth(radius, nsigma=5.0, napers=100, niters=2,
                           overlap=False, seed=123, zeropoint=23.9,
                           progress_bar=False)
        mask = np.zeros(self.data.shape)
        mask[:, 40:] = True
        with pytest.warns(AstropyUserWarning, match='Unable to generate'):
            depth(self.data, mask)

    def test_zero_data(self):
        radius = 4
        depth = ImageDepth(radius, napers=500, niters=2,
                           overlap=True, seed=123, progress_bar=False)
        data = np.zeros((300, 400))
        mask = None
        with pytest.warns(AstropyUserWarning,
                          match='One or more flux_limit values was zero'):
            limits = depth(data, mask)
            assert_allclose(limits, (0.0, np.inf))

    def test_all_masked(self):
        radius = 4
        depth = ImageDepth(radius, napers=500, niters=1,
                           overlap=True, seed=123, progress_bar=False)
        data = np.zeros(self.data.shape)
        mask = np.zeros(data.shape, dtype=bool)
        mask[:, 10:] = True
        with pytest.raises(ValueError):
            depth(data, mask)

    def test_inputs(self):
        with pytest.raises(ValueError):
            ImageDepth(0.0, nsigma=5.0, napers=500, niters=2,
                       overlap=True, seed=123, zeropoint=23.9,
                       progress_bar=False)

        with pytest.raises(ValueError):
            ImageDepth(-12.4, nsigma=5.0, napers=500, niters=2,
                       overlap=True, seed=123, zeropoint=23.9,
                       progress_bar=False)

        with pytest.raises(ValueError):
            ImageDepth(12.4, nsigma=5.0, napers=500, niters=2,
                       mask_pad=-7.1, overlap=True, seed=123, zeropoint=23.9,
                       progress_bar=False)


text:
/**
 * \file
 * Implementation of a redblack tree.
 */

#include <ldns/config.h>
#include <ldns/rbtree.h>
#include <ldns/util.h>
#include <stdlib.h>

/** Node colour black */
#define	BLACK	0
/** Node colour red */
#define	RED	1

/** the NULL node, global alloc */
ldns_rbnode_t	ldns_rbtree_null_node = {
	LDNS_RBTREE_NULL,	/* Parent.  */
	LDNS_RBTREE_NULL,	/* Left.  */
	LDNS_RBTREE_NULL,	/* Right.  */
	NULL,			/* Key.  */
	NULL,               /* Data. */
	BLACK		     /* Color.  */
};

/** rotate subtree left (to preserve redblack property) */
static void ldns_rbtree_rotate_left(ldns_rbtree_t *rbtree, ldns_rbnode_t *node);
/** rotate subtree right (to preserve redblack property) */
static void ldns_rbtree_rotate_right(ldns_rbtree_t *rbtree, ldns_rbnode_t *node);
/** Fixup node colours when insert happened */
static void ldns_rbtree_insert_fixup(ldns_rbtree_t *rbtree, ldns_rbnode_t *node);
/** Fixup node colours when delete happened */
static void ldns_rbtree_delete_fixup(ldns_rbtree_t* rbtree, ldns_rbnode_t* child, ldns_rbnode_t* child_parent);

/*
 * Creates a new red black tree, initializes and returns a pointer to it.
 *
 * Return NULL on failure.
 *
 */
ldns_rbtree_t *
ldns_rbtree_create (int (*cmpf)(const void *, const void *))
{
	ldns_rbtree_t *rbtree;

	/* Allocate memory for it */
	rbtree = (ldns_rbtree_t *) LDNS_MALLOC(ldns_rbtree_t);
	if (!rbtree) {
		return NULL;
	}

	/* Initialize it */
	ldns_rbtree_init(rbtree, cmpf);

	return rbtree;
}

void
ldns_rbtree_init(ldns_rbtree_t *rbtree, int (*cmpf)(const void *, const void *))
{
	/* Initialize it */
	rbtree->root = LDNS_RBTREE_NULL;
	rbtree->count = 0;
	rbtree->cmp = cmpf;
}

void
ldns_rbtree_free(ldns_rbtree_t *rbtree)
{
	LDNS_FREE(rbtree);
}

/*
 * Rotates the node to the left.
 *
 */
static void
ldns_rbtree_rotate_left(ldns_rbtree_t *rbtree, ldns_rbnode_t *node)
{
	ldns_rbnode_t *right = node->right;
	node->right = right->left;
	if (right->left != LDNS_RBTREE_NULL)
		right->left->parent = node;

	right->parent = node->parent;

	if (node->parent != LDNS_RBTREE_NULL) {
		if (node == node->parent->left) {
			node->parent->left = right;
		} else  {
			node->parent->right = right;
		}
	} else {
		rbtree->root = right;
	}
	right->left = node;
	node->parent = right;
}

/*
 * Rotates the node to the right.
 *
 */
static void
ldns_rbtree_rotate_right(ldns_rbtree_t *rbtree, ldns_rbnode_t *node)
{
	ldns_rbnode_t *left = node->left;
	node->left = left->right;
	if (left->right != LDNS_RBTREE_NULL)
		left->right->parent = node;

	left->parent = node->parent;

	if (node->parent != LDNS_RBTREE_NULL) {
		if (node == node->parent->right) {
			node->parent->right = left;
		} else  {
			node->parent->left = left;
		}
	} else {
		rbtree->root = left;
	}
	left->right = node;
	node->parent = left;
}

static void
ldns_rbtree_insert_fixup(ldns_rbtree_t *rbtree, ldns_rbnode_t *node)
{
	ldns_rbnode_t	*uncle;

	/* While not at the root and need fixing... */
	while (node != rbtree->root && node->parent->color == RED) {
		/* If our parent is left child of our grandparent... */
		if (node->parent == node->parent->parent->left) {
			uncle = node->parent->parent->right;

			/* If our uncle is red... */
			if (uncle->color == RED) {
				/* Paint the parent and the uncle black... */
				node->parent->color = BLACK;
				uncle->color = BLACK;

				/* And the grandparent red... */
				node->parent->parent->color = RED;

				/* And continue fixing the grandparent */
				node = node->parent->parent;
			} else {				/* Our uncle is black... */
				/* Are we the right child? */
				if (node == node->parent->right) {
					node = node->parent;
					ldns_rbtree_rotate_left(rbtree, node);
				}
				/* Now we're the left child, repaint and rotate... */
				node->parent->color = BLACK;
				node->parent->parent->color = RED;
				ldns_rbtree_rotate_right(rbtree, node->parent->parent);
			}
		} else {
			uncle = node->parent->parent->left;

			/* If our uncle is red... */
			if (uncle->color == RED) {
				/* Paint the parent and the uncle black... */
				node->parent->color = BLACK;
				uncle->color = BLACK;

				/* And the grandparent red... */
				node->parent->parent->color = RED;

				/* And continue fixing the grandparent */
				node = node->parent->parent;
			} else {				/* Our uncle is black... */
				/* Are we the right child? */
				if (node == node->parent->left) {
					node = node->parent;
					ldns_rbtree_rotate_right(rbtree, node);
				}
				/* Now we're the right child, repaint and rotate... */
				node->parent->color = BLACK;
				node->parent->parent->color = RED;
				ldns_rbtree_rotate_left(rbtree, node->parent->parent);
			}
		}
	}
	rbtree->root->color = BLACK;
}

void
ldns_rbtree_insert_vref(ldns_rbnode_t *data, void *rbtree)
{
	(void) ldns_rbtree_insert((ldns_rbtree_t *) rbtree,
						 data);
}

/*
 * Inserts a node into a red black tree.
 *
 * Returns NULL on failure or the pointer to the newly added node
 * otherwise.
 */
ldns_rbnode_t *
ldns_rbtree_insert (ldns_rbtree_t *rbtree, ldns_rbnode_t *data)
{
	/* XXX Not necessary, but keeps compiler quiet... */
	int r = 0;

	/* We start at the root of the tree */
	ldns_rbnode_t	*node = rbtree->root;
	ldns_rbnode_t	*parent = LDNS_RBTREE_NULL;

	/* Lets find the new parent... */
	while (node != LDNS_RBTREE_NULL) {
		/* Compare two keys, do we have a duplicate? */
		if ((r = rbtree->cmp(data->key, node->key)) == 0) {
			return NULL;
		}
		parent = node;

		if (r < 0) {
			node = node->left;
		} else {
			node = node->right;
		}
	}

	/* Initialize the new node */
	data->parent = parent;
	data->left = data->right = LDNS_RBTREE_NULL;
	data->color = RED;
	rbtree->count++;

	/* Insert it into the tree... */
	if (parent != LDNS_RBTREE_NULL) {
		if (r < 0) {
			parent->left = data;
		} else {
			parent->right = data;
		}
	} else {
		rbtree->root = data;
	}

	/* Fix up the red-black properties... */
	ldns_rbtree_insert_fixup(rbtree, data);

	return data;
}

/*
 * Searches the red black tree, returns the data if key is found or NULL otherwise.
 *
 */
ldns_rbnode_t *
ldns_rbtree_search (ldns_rbtree_t *rbtree, const void *key)
{
	ldns_rbnode_t *node;

	if (ldns_rbtree_find_less_equal(rbtree, key, &node)) {
		return node;
	} else {
		return NULL;
	}
}

/** helpers for delete: swap node colours */
static void swap_int8(uint8_t* x, uint8_t* y)
{
	uint8_t t = *x; *x = *y; *y = t;
}

/** helpers for delete: swap node pointers */
static void swap_np(ldns_rbnode_t** x, ldns_rbnode_t** y)
{
	ldns_rbnode_t* t = *x; *x = *y; *y = t;
}

/** Update parent pointers of child trees of 'parent' */
static void change_parent_ptr(ldns_rbtree_t* rbtree, ldns_rbnode_t* parent, ldns_rbnode_t* old, ldns_rbnode_t* new)
{
	if(parent == LDNS_RBTREE_NULL)
	{
		if(rbtree->root == old) rbtree->root = new;
		return;
	}
	if(parent->left == old) parent->left = new;
	if(parent->right == old) parent->right = new;
}
/** Update parent pointer of a node 'child' */
static void change_child_ptr(ldns_rbnode_t* child, ldns_rbnode_t* old, ldns_rbnode_t* new)
{
	if(child == LDNS_RBTREE_NULL) return;
	if(child->parent == old) child->parent = new;
}

ldns_rbnode_t*
ldns_rbtree_delete(ldns_rbtree_t *rbtree, const void *key)
{
	ldns_rbnode_t *to_delete;
	ldns_rbnode_t *child;
	if((to_delete = ldns_rbtree_search(rbtree, key)) == 0) return 0;
	rbtree->count--;

	/* make sure we have at most one non-leaf child */
	if(to_delete->left != LDNS_RBTREE_NULL &&
	   to_delete->right != LDNS_RBTREE_NULL)
	{
		/* swap with smallest from right subtree (or largest from left) */
		ldns_rbnode_t *smright = to_delete->right;
		while(smright->left != LDNS_RBTREE_NULL)
			smright = smright->left;
		/* swap the smright and to_delete elements in the tree,
		 * but the ldns_rbnode_t is first part of user data struct
		 * so cannot just swap the keys and data pointers. Instead
		 * readjust the pointers left,right,parent */

		/* swap colors - colors are tied to the position in the tree */
		swap_int8(&to_delete->color, &smright->color);

		/* swap child pointers in parents of smright/to_delete */
		change_parent_ptr(rbtree, to_delete->parent, to_delete, smright);
		if(to_delete->right != smright)
			change_parent_ptr(rbtree, smright->parent, smright, to_delete);

		/* swap parent pointers in children of smright/to_delete */
		change_child_ptr(smright->left, smright, to_delete);
		change_child_ptr(smright->left, smright, to_delete);
		change_child_ptr(smright->right, smright, to_delete);
		change_child_ptr(smright->right, smright, to_delete);
		change_child_ptr(to_delete->left, to_delete, smright);
		if(to_delete->right != smright)
			change_child_ptr(to_delete->right, to_delete, smright);
		if(to_delete->right == smright)
		{
			/* set up so after swap they work */
			to_delete->right = to_delete;
			smright->parent = smright;
		}

		/* swap pointers in to_delete/smright nodes */
		swap_np(&to_delete->parent, &smright->parent);
		swap_np(&to_delete->left, &smright->left);
		swap_np(&to_delete->right, &smright->right);

		/* now delete to_delete (which is at the location where the smright previously was) */
	}

	if(to_delete->left != LDNS_RBTREE_NULL) child = to_delete->left;
	else child = to_delete->right;

	/* unlink to_delete from the tree, replace to_delete with child */
	change_parent_ptr(rbtree, to_delete->parent, to_delete, child);
	change_child_ptr(child, to_delete, to_delete->parent);

	if(to_delete->color == RED)
	{
		/* if node is red then the child (black) can be swapped in */
	}
	else if(child->color == RED)
	{
		/* change child to BLACK, removing a RED node is no problem */
		if(child!=LDNS_RBTREE_NULL) child->color = BLACK;
	}
	else ldns_rbtree_delete_fixup(rbtree, child, to_delete->parent);

	/* unlink completely */
	to_delete->parent = LDNS_RBTREE_NULL;
	to_delete->left = LDNS_RBTREE_NULL;
	to_delete->right = LDNS_RBTREE_NULL;
	to_delete->color = BLACK;
	return to_delete;
}

static void ldns_rbtree_delete_fixup(ldns_rbtree_t* rbtree, ldns_rbnode_t* child, ldns_rbnode_t* child_parent)
{
	ldns_rbnode_t* sibling;
	int go_up = 1;

	/* determine sibling to the node that is one-black short */
	if(child_parent->right == child) sibling = child_parent->left;
	else sibling = child_parent->right;

	while(go_up)
	{
		if(child_parent == LDNS_RBTREE_NULL)
		{
			/* removed parent==black from root, every path, so ok */
			return;
		}

		if(sibling->color == RED)
		{	/* rotate to get a black sibling */
			child_parent->color = RED;
			sibling->color = BLACK;
			if(child_parent->right == child)
				ldns_rbtree_rotate_right(rbtree, child_parent);
			else	ldns_rbtree_rotate_left(rbtree, child_parent);
			/* new sibling after rotation */
			if(child_parent->right == child) sibling = child_parent->left;
			else sibling = child_parent->right;
		}

		if(child_parent->color == BLACK
			&& sibling->color == BLACK
			&& sibling->left->color == BLACK
			&& sibling->right->color == BLACK)
		{	/* fixup local with recolor of sibling */
			if(sibling != LDNS_RBTREE_NULL)
				sibling->color = RED;

			child = child_parent;
			child_parent = child_parent->parent;
			/* prepare to go up, new sibling */
			if(child_parent->right == child) sibling = child_parent->left;
			else sibling = child_parent->right;
		}
		else go_up = 0;
	}

	if(child_parent->color == RED
		&& sibling->color == BLACK
		&& sibling->left->color == BLACK
		&& sibling->right->color == BLACK)
	{
		/* move red to sibling to rebalance */
		if(sibling != LDNS_RBTREE_NULL)
			sibling->color = RED;
		child_parent->color = BLACK;
		return;
	}

	/* get a new sibling, by rotating at sibling. See which child
	   of sibling is red */
	if(child_parent->right == child
		&& sibling->color == BLACK
		&& sibling->right->color == RED
		&& sibling->left->color == BLACK)
	{
		sibling->color = RED;
		sibling->right->color = BLACK;
		ldns_rbtree_rotate_left(rbtree, sibling);
		/* new sibling after rotation */
		if(child_parent->right == child) sibling = child_parent->left;
		else sibling = child_parent->right;
	}
	else if(child_parent->left == child
		&& sibling->color == BLACK
		&& sibling->left->color == RED
		&& sibling->right->color == BLACK)
	{
		sibling->color = RED;
		sibling->left->color = BLACK;
		ldns_rbtree_rotate_right(rbtree, sibling);
		/* new sibling after rotation */
		if(child_parent->right == child) sibling = child_parent->left;
		else sibling = child_parent->right;
	}

	/* now we have a black sibling with a red child. rotate and exchange colors. */
	sibling->color = child_parent->color;
	child_parent->color = BLACK;
	if(child_parent->right == child)
	{
		sibling->left->color = BLACK;
		ldns_rbtree_rotate_right(rbtree, child_parent);
	}
	else
	{
		sibling->right->color = BLACK;
		ldns_rbtree_rotate_left(rbtree, child_parent);
	}
}

int
ldns_rbtree_find_less_equal(ldns_rbtree_t *rbtree, const void *key, ldns_rbnode_t **result)
{
	int r;
	ldns_rbnode_t *node;

	/* We start at root... */
	node = rbtree->root;

	*result = NULL;

	/* While there are children... */
	while (node != LDNS_RBTREE_NULL) {
		r = rbtree->cmp(key, node->key);
		if (r == 0) {
			/* Exact match */
			*result = node;
			return 1;
		}
		if (r < 0) {
			node = node->left;
		} else {
			/* Temporary match */
			*result = node;
			node = node->right;
		}
	}
	return 0;
}

/*
 * Finds the first element in the red black tree
 *
 */
ldns_rbnode_t *
ldns_rbtree_first(const ldns_rbtree_t *rbtree)
{
	ldns_rbnode_t *node = rbtree->root;

	if (rbtree->root != LDNS_RBTREE_NULL) {
		for (node = rbtree->root; node->left != LDNS_RBTREE_NULL; node = node->left);
	}
	return node;
}

ldns_rbnode_t *
ldns_rbtree_last(const ldns_rbtree_t *rbtree)
{
	ldns_rbnode_t *node = rbtree->root;

	if (rbtree->root != LDNS_RBTREE_NULL) {
		for (node = rbtree->root; node->right != LDNS_RBTREE_NULL; node = node->right);
	}
	return node;
}

/*
 * Returns the next node...
 *
 */
ldns_rbnode_t *
ldns_rbtree_next(ldns_rbnode_t *node)
{
	ldns_rbnode_t *parent;

	if (node->right != LDNS_RBTREE_NULL) {
		/* One right, then keep on going left... */
		for (node = node->right;
			node->left != LDNS_RBTREE_NULL;
			node = node->left);
	} else {
		parent = node->parent;
		while (parent != LDNS_RBTREE_NULL && node == parent->right) {
			node = parent;
			parent = parent->parent;
		}
		node = parent;
	}
	return node;
}

ldns_rbnode_t *
ldns_rbtree_previous(ldns_rbnode_t *node)
{
	ldns_rbnode_t *parent;

	if (node->left != LDNS_RBTREE_NULL) {
		/* One left, then keep on going right... */
		for (node = node->left;
			node->right != LDNS_RBTREE_NULL;
			node = node->right);
	} else {
		parent = node->parent;
		while (parent != LDNS_RBTREE_NULL && node == parent->left) {
			node = parent;
			parent = parent->parent;
		}
		node = parent;
	}
	return node;
}

/**
 * split off elements number of elements from the start
 * of the name tree and return a new tree
 */
ldns_rbtree_t *
ldns_rbtree_split(ldns_rbtree_t *tree,
			   size_t elements)
{
	ldns_rbtree_t *new_tree;
	ldns_rbnode_t *cur_node;
	ldns_rbnode_t *move_node;
	size_t count = 0;

	new_tree = ldns_rbtree_create(tree->cmp);

	cur_node = ldns_rbtree_first(tree);
	while (count < elements && cur_node != LDNS_RBTREE_NULL) {
		move_node = ldns_rbtree_delete(tree, cur_node->key);
		(void)ldns_rbtree_insert(new_tree, move_node);
		cur_node = ldns_rbtree_first(tree);
		count++;
	}

	return new_tree;
}

/*
 * add all node from the second tree to the first (removing them from the
 * second), and fix up nsec(3)s if present
 */
void
ldns_rbtree_join(ldns_rbtree_t *tree1, ldns_rbtree_t *tree2)
{
	ldns_traverse_postorder(tree2, ldns_rbtree_insert_vref, tree1);
}

/** recursive descent traverse */
static void
traverse_post(void (*func)(ldns_rbnode_t*, void*), void* arg,
	ldns_rbnode_t* node)
{
	if(!node || node == LDNS_RBTREE_NULL)
		return;
	/* recurse */
	traverse_post(func, arg, node->left);
	traverse_post(func, arg, node->right);
	/* call user func */
	(*func)(node, arg);
}

void
ldns_traverse_postorder(ldns_rbtree_t* tree,
	void (*func)(ldns_rbnode_t*, void*), void* arg)
{
	traverse_post(func, arg, tree->root);
}


text:
#pragma once
#include <string>
#include <vector>
#include <list>
#include <opencv2\opencv.hpp>
#include <iostream>
#include <fstream>
#include <time.h>

using namespace std;
using namespace cv;
using namespace cv::ml;

/*
Training.h contains functions to load, tranform training images and train a HOG SVM detector.
*/

void get_images_path(const string & prefix, const string & filename, vector< string > & img_lst);
void load_images(const string & prefix, const string & filename, vector< Mat > & img_lst);
void load_and_sample_negs(const string & prefix, const string & filename, const Size & size, int max_count, bool rand, vector< Mat > & img_lst);
void sample_neg(const Mat & origin, vector< Mat > & neg_lst, const Size & size);
void random_sample_neg(const Mat & origin, vector< Mat > & neg_lst, const Size & size);
void compute_hog(const vector< Mat > & img_lst, vector< Mat > & gradient_lst, const Size & size);
void convert_to_ml(const std::vector< cv::Mat > & train_samples, cv::Mat& trainData);
Ptr<SVM> train_svm(const vector< Mat > & gradient_lst, const vector< int > & labels);
Mat get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size);
void save_svm_to_file(Ptr<SVM> pSvm, const string & fileName);
Ptr<SVM> train_svm_from(const string & pos_dir, const string & pos, const string & neg_dir,
	const string & neg, const Size & size);

const static float NEG_POS_RATIO_THRESHOLD = 6.0;


text:
This page is intended to provide technical documentation for an ongoing citation analysis and collection development project at the Galter Health Sciences Library at Northwestern University's Feinberg School of Medicine. The scripts in this repository are designed to assist in performing basic citation analysis on cited references from citations exported from Web of Science (WOS). This project will be presented at the NASIG Annual Conference in June, 2017, after which slides will be made available.

## Getting started

It is assumed working files are in .txt format, exported from WOS as full records with cited references in tab-delimited (Win) format.

### System Requirements

These scripts should be run in a Python 3 environment.

### Basic instructions:

1. Run the WOS_clean_concat.py script, specifying the directory containing your WOS .txt files and the desired output directory. This will output .csv files corresponding to each .txt file, and a .pkl file for all of the data combined into one file.
2. Run the WOS_citation_analysis.py script using the output .pkl file.
3. OPTIONAL STEP: Add code snippet WOS_specific_journal.py to output publication year of a specific journal title(s). Must use WOS journal title abbreviation from MaxCitedJournals list, to be specified jn# ==. Expand code as needed to gather multiple titles at once.

### Outputs

The WOS_citation_analysis.py script will output several .csv data files and generate basic figures related to the analysis. Output file can be renamed per local conventions.

**Data**

- MaxCitedJournals.csv - List of most cited journals from the cited references list sorted by count. Modify p = cc.most_common() to specify number of journals desired in result
- OriginalArticle_Year_RefCount.csv - List giving publication year of citing (original) article and a count of the number of references cited by each article.
- CitedJournalAge.csv - List giving age of cited reference in years (in relation to publication date of citing article) and the publication year of the cited reference.
- ReferenceStats.csv - List giving the average number of references per article, per year, and the total number of cited references for each year.
- SpecificJournalYears.csv - Output if including code snippet from WOS_specific_journal.py. Returns year of cited references for all references to a specific journal title. Useful if interested in investigating library's coverage of a particular journal if heavily cited.

**Figures**

- Figure 1 - Number of articles published per year
- Figure 2 - Year of publication of cited reference articles
- Figure 3 - Age of cited articles (in years) compared to the date of publication of the citing article
- Figure 4 - Total number of citations per year
- Figure 5 - Average number of citations per article, per year

## Working with abbreviated titles

The journal titles as extracted from the WOS citations are abbreviated, and as such so is the output when working with the files using Python. One option to automate the retrieval of full titles and ISSN information from the abbreviated titles is to utilize the NLM E-utilities API. This allows you to query the NLM catalog, retrieve matching catalog records when available, and output Title, ISSN, and other fields of your choosing to a file.

**Brief instructions for using NLM's E-utilities**

1. In a Unix terminal, install EDirect software (see instructions
[here](https://dataguide.nlm.nih.gov/edirect/install.html))
2. Place a list of the journal title abbreviations in your working directory as a .txt file (in this example, titles.txt). The results will be more accurate if each title is enclosed with quotation marks (").
3. Execute the following search in your Unix terminal:

```
while read -u 10 list; do esearch -db nlmcatalog -query "$list" | efetch -format xml | xtract -pattern NLMCatalogRecord -element TitleMain/Title MedlineTA TitleAlternate/Title ISSN; done 10< titles.txt > FullJournalTitles.txt

```

For further documentation about E-Utilities, visit the
[NLM website](https://dataguide.nlm.nih.gov/)

## Authors

These scripts were written by Madhuri Kaul, with specifications provided by Joelen Pastva.

## Project Team

Members of the citation analysis project team:

- Karen Gutzman
- Madhuri Kaul
- Ramune Kubilius
- Joelen Pastva
- Jonathan Shank

## License

This project is licensed under the MIT License.


text:
package handlers

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/gamegos/gcmlib"
	"github.com/gamegos/jsend"
	"github.com/gamegos/scotty/server/context"
	"github.com/gorilla/mux"
)

// publishRequest represents http body of "publish" requests.
type publishRequest struct {
	Subscribers []string `json:"subscribers"`
	Channels    []string `json:"channels"`
	Message     *gcmlib.Message
}

func PublishMessage(jw jsend.JResponseWriter, r *http.Request, ctx *context.Context) {
	vars := mux.Vars(r)

	app, err := ctx.Storage.GetApp(vars["appId"])
	if app == nil {
		log.Println("App not found:", app, err)
		jw.Status(404).Message("App not found").Send()
		return
	}

	publishReq := new(publishRequest)
	decoder := json.NewDecoder(r.Body)

	if err := decoder.Decode(&publishReq); err != nil {
		log.Println("Could not decode message, ", err)
		jw.Status(400).Message("Could not decode message: " + err.Error()).Send()
		return
	}

	deviceTokens := make([]string, 0, len(publishReq.Subscribers))

	for _, subscriberID := range publishReq.Subscribers {
		log.Println(subscriberID)
		subscriberDevices, err := ctx.Storage.GetSubscriberDevices(app.ID, subscriberID)
		if err != nil {
			log.Println("Error, ", err)
		}

		for _, device := range subscriberDevices {
			deviceTokens = append(deviceTokens, device.Token)
		}

		log.Printf("Devices %#v\n", deviceTokens)
	}

	client := gcmlib.NewClient(gcmlib.Config{
		APIKey: app.GCM.APIKey,
	})

	msg := publishReq.Message
	msg.RegistrationIDs = deviceTokens

	if err := msg.Validate(); err != nil {
		jw.Status(400).Message(err.Error()).Send()
		return
	}

	result, gcmErr := client.Send(msg)
	log.Printf("GCM Request: %#v, %#v\n", result, err)

	if gcmErr != nil {
		jw.Status(400).Message(gcmErr.Error()).Send()
		return
	}

	jw.Data(result).Send()
}


text:
package com.kotcrab.vis.editor.util;

import java.lang.annotation.*;

/**
 * Types annotated by this annotation are considered as part of VisEditor public API and may be used in plugins. Those
 * types should also have complete Javadoc documentation.
 *

 * All changes to those types must be published in API_CHANGES file. Any changes that break public API should be avoided.
 * Method and field deprecation should be preferred over removing them as that would create incompatible changes.
 *

 * This annotation will be used to generate VisEditor Javadoc containing only public API classes. If you believe that some
 * class should be part of public API but doesn't have this annotation contact Kotcrab.
 *

 * Phrases such as: "MUST", "MUST NOT", "SHOULD", "SHOULD NOT" must be interpreted as defined in RFC2119.
 * @author Kotcrab
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@Documented
@PublicApi
public @interface PublicApi {
}


text:
using System.Windows.Forms;
using FlaUI.Core.WindowsAPI;

namespace FlaUI.Core.Overlay
{
    public class OverlayRectangleForm : Form
    {
        public OverlayRectangleForm()
        {
            FormBorderStyle = FormBorderStyle.None;
            ShowInTaskbar = false;
            Left = 0;
            Top = 0;
            Width = 1;
            Height = 1;
            Visible = false;
        }

        protected override bool ShowWithoutActivation => true;

        protected override CreateParams CreateParams
        {
            get
            {
                var createParams = base.CreateParams;
                createParams.ExStyle |= (int)WindowStyles.WS_EX_TOPMOST;
                return createParams;
            }
        }
    }
}


text:
def configure_client
  RoyalMailApi::Client.configure do |config|
    config.application_id = ENV['RM_APPLICATION_ID']
    config.username = ENV['RM_USERNAME']
    config.password = ENV['RM_PASSWORD']
    config.client_id = ENV['RM_CLIENT_ID']
    config.client_secret = ENV['RM_CLIENT_SECRET']
    config.adapter = :httpclient
    config.shipping_wsdl = File.join(RoyalMailApi.root, 'lib', 'wsdl', 'ShippingAPI_V2_0_9.wsdl')
    config.tracking_wsdl = File.join(RoyalMailApi.root, 'lib', 'wsdl', 'Tracking_API_V1.2.wsdl')
    config.shipping_endpoint = 'https://api.royalmail.net/shipping/v2'
    config.tracking_endpoint = 'https://api.royalmail.net/tracking'
    config.logger = Logger.new(STDOUT)
    config.logger.level = 0
    config.service_occurrence = 1
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javachen.spark</groupId>
    <artifactId>spark-examples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spark-examples</name>

    <repositories>
        <repository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </repository>
        <repository>
            <id>maven-hadoop</id>
            <name>Hadoop Releases</name>
            <url>https://repository.cloudera.com/content/repositories/releases/</url>
        </repository>
        <repository>
            <id>cloudera-repos</id>
            <name>Cloudera Repos</name>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.15.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.10.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.10</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>
</project>


text:
WebsitePolling
==============

This script is designed to send you an email when a given website has changed.
For instance, if you would like to see when isitchristmas.com has changed (on Dec. 25), this
script will send you an email.