text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
//
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at the following url:           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Stig Bakken <ssb@php.net>                                   |
// |          Tomas V.V.Cox <cox@idecnet.com>                             |
// +----------------------------------------------------------------------+
//
// $Id: Common.php,v 1.1 2013-09-30 09:46:12 raphael Exp $

require_once 'cms-inc/lib/pear/PEAR.php';
require_once 'cms-inc/lib/pear/Archive/Tar.php';
require_once 'cms-inc/lib/pear/System.php';
require_once 'cms-inc/lib/pear/PEAR/Config.php';

// {{{ constants and globals

define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^([A-Z][a-zA-Z0-9_]+|[a-z][a-z0-9_]+)$/');

/**
 * List of temporary files and directories registered by
 * PEAR_Common::addTempFile().
 * @var array
 */
$GLOBALS['_PEAR_Common_tempfiles'] = array();

/**
 * Valid maintainer roles
 * @var array
 */
$GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper');

/**
 * Valid release states
 * @var array
 */
$GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel');

/**
 * Valid dependency types
 * @var array
 */
$GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi');

/**
 * Valid dependency relations
 * @var array
 */
$GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge');

/**
 * Valid file roles
 * @var array
 */
$GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script');

/**
 * Valid replacement types
 * @var array
 */
$GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info');

/**
 * Valid "provide" types
 * @var array
 */
$GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api');

/**
 * Valid "provide" types
 * @var array
 */
$GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup');

// }}}

/**
 * Class providing common functionality for PEAR adminsitration classes.
 */
class PEAR_Common extends PEAR
{
    // {{{ properties

    /** stack of elements, gives some sort of XML context */
    var $element_stack = array();

    /** name of currently parsed XML element */
    var $current_element;

    /** array of attributes of the currently parsed XML element */
    var $current_attributes = array();

    /** assoc with information about a package */
    var $pkginfo = array();

    /**
     * User Interface object (PEAR_Frontend_* class).  If null,
     * the log() method uses print.
     * @var object
     */
    var $ui = null;

    /**
     * Configuration object (PEAR_Config).
     * @var object
     */
    var $config = null;

    var $current_path = null;

    /**
     * PEAR_SourceAnalyzer instance
     * @var object
     */
    var $source_analyzer = null;

    // }}}

    // {{{ constructor

    /**
     * PEAR_Common constructor
     *
     * @access public
     */
    function PEAR_Common()
    {
        parent::PEAR();
        $this->config = &PEAR_Config::singleton();
        $this->debug = $this->config->get('verbose');
    }

    // }}}
    // {{{ destructor

    /**
     * PEAR_Common destructor
     *
     * @access private
     */
    function _PEAR_Common()
    {
        // doesn't work due to bug #14744
        //$tempfiles = $this->_tempfiles;
        $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles'];
        while ($file = array_shift($tempfiles)) {
            if (@is_dir($file)) {
                System::rm(array('-rf', $file));
            } elseif (file_exists($file)) {
                unlink($file);
            }
        }
    }

    // }}}
    // {{{ addTempFile()

    /**
     * Register a temporary file or directory.  When the destructor is
     * executed, all registered temporary files and directories are
     * removed.
     *
     * @param string  $file  name of file or directory
     *
     * @return void
     *
     * @access public
     */
    function addTempFile($file)
    {
        $GLOBALS['_PEAR_Common_tempfiles'][] = $file;
    }

    // }}}
    // {{{ mkDirHier()

    /**
     * Wrapper to System::mkDir(), creates a directory as well as
     * any necessary parent directories.
     *
     * @param string  $dir  directory name
     *
     * @return bool TRUE on success, or a PEAR error
     *
     * @access public
     */
    function mkDirHier($dir)
    {
        $this->log(2, "+ create dir $dir");
        return System::mkDir(array('-p', $dir));
    }

    // }}}
    // {{{ log()

    /**
     * Logging method.
     *
     * @param int    $level  log level (0 is quiet, higher is noisier)
     * @param string $msg    message to write to the log
     *
     * @return void
     *
     * @access public
     */
    function log($level, $msg)
    {
        if ($this->debug >= $level) {
            if (is_object($this->ui)) {
                $this->ui->log($msg);
            } else {
                print "$msg\n";
            }
        }
    }

    // }}}
    // {{{ mkTempDir()

    /**
     * Create and register a temporary directory.
     *
     * @param string $tmpdir (optional) Directory to use as tmpdir.
     *                       Will use system defaults (for example
     *                       /tmp or c:\windows\temp) if not specified
     *
     * @return string name of created directory
     *
     * @access public
     */
    function mkTempDir($tmpdir = '')
    {
        if ($tmpdir) {
            $topt = array('-t', $tmpdir);
        } else {
            $topt = array();
        }
        $topt = array_merge($topt, array('-d', 'pear'));
        if (!$tmpdir = System::mktemp($topt)) {
            return false;
        }
        $this->addTempFile($tmpdir);
        return $tmpdir;
    }

    // }}}
    // {{{ setFrontendObject()

    /**
     * Set object that represents the frontend to be used.
     *
     * @param  object Reference of the frontend object
     * @return void
     * @access public
     */
    function setFrontendObject(&$ui)
    {
        $this->ui = &$ui;
    }

    // }}}

    // {{{ _unIndent()

    /**
     * Unindent given string (?)
     *
     * @param string $str The string that has to be unindented.
     * @return string
     * @access private
     */
    function _unIndent($str)
    {
        // remove leading newlines
        $str = preg_replace('/^[\r\n]+/', '', $str);
        // find whitespace at the beginning of the first line
        $indent_len = strspn($str, " \t");
        $indent = substr($str, 0, $indent_len);
        $data = '';
        // remove the same amount of whitespace from following lines
        foreach (explode("\n", $str) as $line) {
            if (substr($line, 0, $indent_len) == $indent) {
                $data .= substr($line, $indent_len) . "\n";
            }
        }
        return $data;
    }

    // }}}
    // {{{ _element_start()

    /**
     * XML parser callback for starting elements.  Used while package
     * format version is not yet known.
     *
     * @param resource  $xp       XML parser resource
     * @param string    $name     name of starting element
     * @param array     $attribs  element attributes, name => value
     *
     * @return void
     *
     * @access private
     */
    function _element_start($xp, $name, $attribs)
    {
        array_push($this->element_stack, $name);
        $this->current_element = $name;
        $spos = sizeof($this->element_stack) - 2;
        $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : '';
        $this->current_attributes = $attribs;
        switch ($name) {
            case 'package': {
                if (isset($attribs['version'])) {
                    $vs = preg_replace('/[^0-9a-z]/', '_', $attribs['version']);
                } else {
                    $vs = '1_0';
                }
                $elem_start = '_element_start_'. $vs;
                $elem_end = '_element_end_'. $vs;
                $cdata = '_pkginfo_cdata_'. $vs;
                xml_set_element_handler($xp, $elem_start, $elem_end);
                xml_set_character_data_handler($xp, $cdata);
                break;
            }
        }
    }

    // }}}
    // {{{ _element_end()

    /**
     * XML parser callback for ending elements.  Used while package
     * format version is not yet known.
     *
     * @param resource  $xp    XML parser resource
     * @param string    $name  name of ending element
     *
     * @return void
     *
     * @access private
     */
    function _element_end($xp, $name)
    {
    }

    // }}}

    // Support for package DTD v1.0:
    // {{{ _element_start_1_0()

    /**
     * XML parser callback for ending elements.  Used for version 1.0
     * packages.
     *
     * @param resource  $xp    XML parser resource
     * @param string    $name  name of ending element
     *
     * @return void
     *
     * @access private
     */
    function _element_start_1_0($xp, $name, $attribs)
    {
        array_push($this->element_stack, $name);
        $this->current_element = $name;
        $spos = sizeof($this->element_stack) - 2;
        $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : '';
        $this->current_attributes = $attribs;
        $this->cdata = '';
        switch ($name) {
            case 'dir':
                if ($this->in_changelog) {
                    break;
                }
                if ($attribs['name'] != '/') {
                    $this->dir_names[] = $attribs['name'];
                }
                if (isset($attribs['baseinstalldir'])) {
                    $this->dir_install = $attribs['baseinstalldir'];
                }
                if (isset($attribs['role'])) {
                    $this->dir_role = $attribs['role'];
                }
                break;
            case 'file':
                if ($this->in_changelog) {
                    break;
                }
                if (isset($attribs['name'])) {
                    $path = '';
                    if (count($this->dir_names)) {
                        foreach ($this->dir_names as $dir) {
                            $path .= $dir . DIRECTORY_SEPARATOR;
                        }
                    }
                    $path .= $attribs['name'];
                    unset($attribs['name']);
                    $this->current_path = $path;
                    $this->filelist[$path] = $attribs;
                    // Set the baseinstalldir only if the file don't have this attrib
                    if (!isset($this->filelist[$path]['baseinstalldir']) &&
                        isset($this->dir_install))
                    {
                        $this->filelist[$path]['baseinstalldir'] = $this->dir_install;
                    }
                    // Set the Role
                    if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) {
                        $this->filelist[$path]['role'] = $this->dir_role;
                    }
                }
                break;
            case 'replace':
                if (!$this->in_changelog) {
                    $this->filelist[$this->current_path]['replacements'][] = $attribs;
                }
                break;
            case 'maintainers':
                $this->pkginfo['maintainers'] = array();
                $this->m_i = 0; // maintainers array index
                break;
            case 'maintainer':
                // compatibility check
                if (!isset($this->pkginfo['maintainers'])) {
                    $this->pkginfo['maintainers'] = array();
                    $this->m_i = 0;
                }
                $this->pkginfo['maintainers'][$this->m_i] = array();
                $this->current_maintainer =& $this->pkginfo['maintainers'][$this->m_i];
                break;
            case 'changelog':
                $this->pkginfo['changelog'] = array();
                $this->c_i = 0; // changelog array index
                $this->in_changelog = true;
                break;
            case 'release':
                if ($this->in_changelog) {
                    $this->pkginfo['changelog'][$this->c_i] = array();
                    $this->current_release = &$this->pkginfo['changelog'][$this->c_i];
                } else {
                    $this->current_release = &$this->pkginfo;
                }
                break;
            case 'deps':
                if (!$this->in_changelog) {
                    $this->pkginfo['release_deps'] = array();
                }
                break;
            case 'dep':
                // dependencies array index
                if (!$this->in_changelog) {
                    $this->d_i++;
                    $this->pkginfo['release_deps'][$this->d_i] = $attribs;
                }
                break;
            case 'configureoptions':
                if (!$this->in_changelog) {
                    $this->pkginfo['configure_options'] = array();
                }
                break;
            case 'configureoption':
                if (!$this->in_changelog) {
                    $this->pkginfo['configure_options'][] = $attribs;
                }
                break;
            case 'provides':
                if (empty($attribs['type']) || empty($attribs['name'])) {
                    break;
                }
                $attribs['explicit'] = true;
                $this->pkginfo['provides']["$attribs[type];$attribs[name]"] = $attribs;
                break;
        }
    }

    // }}}
    // {{{ _element_end_1_0()

    /**
     * XML parser callback for ending elements.  Used for version 1.0
     * packages.
     *
     * @param resource  $xp    XML parser resource
     * @param string    $name  name of ending element
     *
     * @return void
     *
     * @access private
     */
    function _element_end_1_0($xp, $name)
    {
        $data = trim($this->cdata);
        switch ($name) {
            case 'name':
                switch ($this->prev_element) {
                    case 'package':
                        // XXX should we check the package name here?
                        $this->pkginfo['package'] = ereg_replace('[^a-zA-Z0-9._]', '_', $data);
                        break;
                    case 'maintainer':
                        $this->current_maintainer['name'] = $data;
                        break;
                }
                break;
            case 'summary':
                $this->pkginfo['summary'] = $data;
                break;
            case 'description':
                $data = $this->_unIndent($this->cdata);
                $this->pkginfo['description'] = $data;
                break;
            case 'user':
                $this->current_maintainer['handle'] = $data;
                break;
            case 'email':
                $this->current_maintainer['email'] = $data;
                break;
            case 'role':
                $this->current_maintainer['role'] = $data;
                break;
            case 'version':
                $data = ereg_replace ('[^a-zA-Z0-9._\-]', '_', $data);
                if ($this->in_changelog) {
                    $this->current_release['version'] = $data;
                } else {
                    $this->pkginfo['version'] = $data;
                }
                break;
            case 'date':
                if ($this->in_changelog) {
                    $this->current_release['release_date'] = $data;
                } else {
                    $this->pkginfo['release_date'] = $data;
                }
                break;
            case 'notes':
                // try to "de-indent" release notes in case someone
                // has been over-indenting their xml ;-)
                $data = $this->_unIndent($this->cdata);
                if ($this->in_changelog) {
                    $this->current_release['release_notes'] = $data;
                } else {
                    $this->pkginfo['release_notes'] = $data;
                }
                break;
            case 'warnings':
                if ($this->in_changelog) {
                    $this->current_release['release_warnings'] = $data;
                } else {
                    $this->pkginfo['release_warnings'] = $data;
                }
                break;
            case 'state':
                if ($this->in_changelog) {
                    $this->current_release['release_state'] = $data;
                } else {
                    $this->pkginfo['release_state'] = $data;
                }
                break;
            case 'license':
                if ($this->in_changelog) {
                    $this->current_release['release_license'] = $data;
                } else {
                    $this->pkginfo['release_license'] = $data;
                }
                break;
            case 'dep':
                if ($data && !$this->in_changelog) {
                    $this->pkginfo['release_deps'][$this->d_i]['name'] = $data;
                }
                break;
            case 'dir':
                if ($this->in_changelog) {
                    break;
                }
                array_pop($this->dir_names);
                break;
            case 'file':
                if ($this->in_changelog) {
                    break;
                }
                if ($data) {
                    $path = '';
                    if (count($this->dir_names)) {
                        foreach ($this->dir_names as $dir) {
                            $path .= $dir . DIRECTORY_SEPARATOR;
                        }
                    }
                    $path .= $data;
                    $this->filelist[$path] = $this->current_attributes;
                    // Set the baseinstalldir only if the file don't have this attrib
                    if (!isset($this->filelist[$path]['baseinstalldir']) &&
                        isset($this->dir_install))
                    {
                        $this->filelist[$path]['baseinstalldir'] = $this->dir_install;
                    }
                    // Set the Role
                    if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) {
                        $this->filelist[$path]['role'] = $this->dir_role;
                    }
                }
                break;
            case 'maintainer':
                if (empty($this->pkginfo['maintainers'][$this->m_i]['role'])) {
                    $this->pkginfo['maintainers'][$this->m_i]['role'] = 'lead';
                }
                $this->m_i++;
                break;
            case 'release':
                if ($this->in_changelog) {
                    $this->c_i++;
                }
                break;
            case 'changelog':
                $this->in_changelog = false;
                break;
            case 'summary':
                $this->pkginfo['summary'] = $data;
                break;
        }
        array_pop($this->element_stack);
        $spos = sizeof($this->element_stack) - 1;
        $this->current_element = ($spos > 0) ? $this->element_stack[$spos] : '';
        $this->cdata = '';
    }

    // }}}
    // {{{ _pkginfo_cdata_1_0()

    /**
     * XML parser callback for character data.  Used for version 1.0
     * packages.
     *
     * @param resource  $xp    XML parser resource
     * @param string    $name  character data
     *
     * @return void
     *
     * @access private
     */
    function _pkginfo_cdata_1_0($xp, $data)
    {
        if (isset($this->cdata)) {
            $this->cdata .= $data;
        }
    }

    // }}}

    // {{{ infoFromTgzFile()

    /**
     * Returns information about a package file.  Expects the name of
     * a gzipped tar file as input.
     *
     * @param string  $file  name of .tgz file
     *
     * @return array  array with package information
     *
     * @access public
     *
     */
    function infoFromTgzFile($file)
    {
        if (!@is_file($file)) {
            return $this->raiseError("could not open file \"$file\"");
        }
        $tar = new Archive_Tar($file);
        if ($this->debug <= 1) {
            $tar->pushErrorHandling(PEAR_ERROR_RETURN);
        }
        $content = $tar->listContent();
        if ($this->debug <= 1) {
            $tar->popErrorHandling();
        }
        if (!is_array($content)) {
            $file = realpath($file);
            return $this->raiseError("Could not get contents of package \"$file\"".
                                     '. Invalid tgz file.');
        }
        $xml = null;
        foreach ($content as $file) {
            $name = $file['filename'];
            if ($name == 'package.xml') {
                $xml = $name;
                break;
            } elseif (ereg('package.xml$', $name, $match)) {
                $xml = $match[0];
                break;
            }
        }
        $tmpdir = System::mkTemp('-d pear');
        $this->addTempFile($tmpdir);
        if (!$xml || !$tar->extractList(array($xml), $tmpdir)) {
            return $this->raiseError('could not extract the package.xml file');
        }
        return $this->infoFromDescriptionFile("$tmpdir/$xml");
    }

    // }}}
    // {{{ infoFromDescriptionFile()

    /**
     * Returns information about a package file.  Expects the name of
     * a package xml file as input.
     *
     * @param string  $descfile  name of package xml file
     *
     * @return array  array with package information
     *
     * @access public
     *
     */
    function infoFromDescriptionFile($descfile)
    {
        if (!@is_file($descfile) || !is_readable($descfile) ||
             (!$fp = @fopen($descfile, 'r'))) {
            return $this->raiseError("Unable to open $descfile");
        }

        // read the whole thing so we only get one cdata callback
        // for each block of cdata
        $data = fread($fp, filesize($descfile));
        return $this->infoFromString($data);
    }

    // }}}
    // {{{ infoFromString()

    /**
     * Returns information about a package file.  Expects the contents
     * of a package xml file as input.
     *
     * @param string  $data  name of package xml file
     *
     * @return array   array with package information
     *
     * @access public
     *
     */
    function infoFromString($data)
    {
        require_once('PEAR/Dependency.php');
        if (PEAR_Dependency::checkExtension($error, 'xml')) {
            return $this->raiseError($error);
        }
        $xp = @xml_parser_create();
        if (!$xp) {
            return $this->raiseError('Unable to create XML parser');
        }
        xml_set_object($xp, $this);
        xml_set_element_handler($xp, '_element_start', '_element_end');
        xml_set_character_data_handler($xp, '_pkginfo_cdata');
        xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, false);

        $this->element_stack = array();
        $this->pkginfo = array('provides' => array());
        $this->current_element = false;
        unset($this->dir_install);
        $this->pkginfo['filelist'] = array();
        $this->filelist =& $this->pkginfo['filelist'];
        $this->dir_names = array();
        $this->in_changelog = false;
        $this->d_i = 0;
        $this->cdata = '';

        if (!xml_parse($xp, $data, 1)) {
            $code = xml_get_error_code($xp);
            $msg = sprintf("XML error: %s at line %d",
                           xml_error_string($code),
                           xml_get_current_line_number($xp));
            xml_parser_free($xp);
            return $this->raiseError($msg, $code);
        }

        xml_parser_free($xp);

        foreach ($this->pkginfo as $k => $v) {
            if (!is_array($v)) {
                $this->pkginfo[$k] = trim($v);
            }
        }
        return $this->pkginfo;
    }
    // }}}
    // {{{ infoFromAny()

    /**
     * Returns package information from different sources
     *
     * This method is able to extract information about a package
     * from a .tgz archive or from a XML package definition file.
     *
     * @access public
     * @param  string Filename of the source ('package.xml', '<package>.tgz')
     * @return string
     */
    function infoFromAny($info)
    {
        if (is_string($info) && file_exists($info)) {
            $tmp = substr($info, -4);
            if ($tmp == '.xml') {
                $info = $this->infoFromDescriptionFile($info);
            } elseif ($tmp == '.tar' || $tmp == '.tgz') {
                $info = $this->infoFromTgzFile($info);
            } else {
                $fp = fopen($info, "r");
                $test = fread($fp, 5);
                fclose($fp);
                if ($test == "<?xml") {
                    $info = $this->infoFromDescriptionFile($info);
                } else {
                    $info = $this->infoFromTgzFile($info);
                }
            }
            if (PEAR::isError($info)) {
                return $this->raiseError($info);
            }
        }
        return $info;
    }

    // }}}
    // {{{ xmlFromInfo()

    /**
     * Return an XML document based on the package info (as returned
     * by the PEAR_Common::infoFrom* methods).
     *
     * @param array  $pkginfo  package info
     *
     * @return string XML data
     *
     * @access public
     */
    function xmlFromInfo($pkginfo)
    {
        static $maint_map = array(
            "handle" => "user",
            "name" => "name",
            "email" => "email",
            "role" => "role",
            );
        $ret = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
        $ret .= "<!DOCTYPE package SYSTEM \"http://pear.php.net/dtd/package-1.0\">\n";
        $ret .= "<package version=\"1.0\">
  <name>$pkginfo[package]</name>
  <summary>".htmlspecialchars($pkginfo['summary'])."</summary>
  <description>".htmlspecialchars($pkginfo['description'])."</description>
  <maintainers>
";
        foreach ($pkginfo['maintainers'] as $maint) {
            $ret .= "    <maintainer>\n";
            foreach ($maint_map as $idx => $elm) {
                $ret .= "      <$elm>";
                $ret .= htmlspecialchars($maint[$idx]);
                $ret .= "</$elm>\n";
            }
            $ret .= "    </maintainer>\n";
        }
        $ret .= "  </maintainers>\n";
        $ret .= $this->_makeReleaseXml($pkginfo);
        if (@sizeof($pkginfo['changelog']) > 0) {
            $ret .= "  <changelog>\n";
            foreach ($pkginfo['changelog'] as $oldrelease) {
                $ret .= $this->_makeReleaseXml($oldrelease, true);
            }
            $ret .= "  </changelog>\n";
        }
        $ret .= "</package>\n";
        return $ret;
    }

    // }}}
    // {{{ _makeReleaseXml()

    /**
     * Generate part of an XML description with release information.
     *
     * @param array  $pkginfo    array with release information
     * @param bool   $changelog  whether the result will be in a changelog element
     *
     * @return string XML data
     *
     * @access private
     */
    function _makeReleaseXml($pkginfo, $changelog = false)
    {
        // XXX QUOTE ENTITIES IN PCDATA, OR EMBED IN CDATA BLOCKS!!
        $indent = $changelog ? "  " : "";
        $ret = "$indent  <release>\n";
        if (!empty($pkginfo['version'])) {
            $ret .= "$indent    <version>$pkginfo[version]</version>\n";
        }
        if (!empty($pkginfo['release_date'])) {
            $ret .= "$indent    <date>$pkginfo[release_date]</date>\n";
        }
        if (!empty($pkginfo['release_license'])) {
            $ret .= "$indent    <license>$pkginfo[release_license]</license>\n";
        }
        if (!empty($pkginfo['release_state'])) {
            $ret .= "$indent    <state>$pkginfo[release_state]</state>\n";
        }
        if (!empty($pkginfo['release_notes'])) {
            $ret .= "$indent    <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n";
        }
        if (!empty($pkginfo['release_warnings'])) {
            $ret .= "$indent    <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n";
        }
        if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) {
            $ret .= "$indent    <deps>\n";
            foreach ($pkginfo['release_deps'] as $dep) {
                $ret .= "$indent      <dep type=\"$dep[type]\" rel=\"$dep[rel]\"";
                if (isset($dep['version'])) {
                    $ret .= " version=\"$dep[version]\"";
                }
                if (isset($dep['name'])) {
                    $ret .= ">$dep[name]</dep>\n";
                } else {
                    $ret .= "/>\n";
                }
            }
            $ret .= "$indent    </deps>\n";
        }
        if (isset($pkginfo['configure_options'])) {
            $ret .= "$indent    <configureoptions>\n";
            foreach ($pkginfo['configure_options'] as $c) {
                $ret .= "$indent      <configureoption name=\"".
                    htmlspecialchars($c['name']) . "\"";
                if (isset($c['default'])) {
                    $ret .= " default=\"" . htmlspecialchars($c['default']) . "\"";
                }
                $ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\"";
                $ret .= "/>\n";
            }
            $ret .= "$indent    </configureoptions>\n";
        }
        if (isset($pkginfo['provides'])) {
            foreach ($pkginfo['provides'] as $key => $what) {
                $ret .= "$indent    <provides type=\"$what[type]\" ";
                $ret .= "name=\"$what[name]\" ";
                if (isset($what['extends'])) {
                    $ret .= "extends=\"$what[extends]\" ";
                }
                $ret .= "/>\n";
            }
        }
        if (isset($pkginfo['filelist'])) {
            $ret .= "$indent    <filelist>\n";
            foreach ($pkginfo['filelist'] as $file => $fa) {
                @$ret .= "$indent      <file role=\"$fa[role]\"";
                if (isset($fa['baseinstalldir'])) {
                    $ret .= ' baseinstalldir="' .
                        htmlspecialchars($fa['baseinstalldir']) . '"';
                }
                if (isset($fa['md5sum'])) {
                    $ret .= " md5sum=\"$fa[md5sum]\"";
                }
                if (isset($fa['platform'])) {
                    $ret .= " platform=\"$fa[platform]\"";
                }
                if (!empty($fa['install-as'])) {
                    $ret .= ' install-as="' .
                        htmlspecialchars($fa['install-as']) . '"';
                }
                $ret .= ' name="' . htmlspecialchars($file) . '"';
                if (empty($fa['replacements'])) {
                    $ret .= "/>\n";
                } else {
                    $ret .= ">\n";
                    foreach ($fa['replacements'] as $r) {
                        $ret .= "$indent        <replace";
                        foreach ($r as $k => $v) {
                            $ret .= " $k=\"" . htmlspecialchars($v) .'"';
                        }
                        $ret .= "/>\n";
                    }
                    @$ret .= "$indent      </file>\n";
                }
            }
            $ret .= "$indent    </filelist>\n";
        }
        $ret .= "$indent  </release>\n";
        return $ret;
    }

    // }}}
    // {{{ validatePackageInfo()

    /**
     * Validate XML package definition file.
     *
     * @param  string $info Filename of the package archive or of the
     *                package definition file
     * @param  array $errors Array that will contain the errors
     * @param  array $warnings Array that will contain the warnings
     * @param  string $dir_prefix (optional) directory where source files
     *                may be found, or empty if they are not available
     * @access public
     * @return boolean
     */
    function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '')
    {
        global $_PEAR_Common_maintainer_roles,
               $_PEAR_Common_release_states,
               $_PEAR_Common_dependency_types,
               $_PEAR_Common_dependency_relations,
               $_PEAR_Common_file_roles,
               $_PEAR_Common_replacement_types;
        if (PEAR::isError($info = $this->infoFromAny($info))) {
            return $this->raiseError($info);
        }
        if (!is_array($info)) {
            return false;
        }
        $errors = array();
        $warnings = array();
        if (empty($info['package'])) {
            $errors[] = 'missing package name';
        }
        if (empty($info['summary'])) {
            $errors[] = 'missing summary';
        } elseif (strpos(trim($info['summary']), "\n") !== false) {
            $warnings[] = 'summary should be on a single line';
        }
        if (empty($info['description'])) {
            $errors[] = 'missing description';
        }
        if (empty($info['release_license'])) {
            $errors[] = 'missing license';
        }
        if (empty($info['version'])) {
            $errors[] = 'missing version';
        }
        if (empty($info['release_state'])) {
            $errors[] = 'missing release state';
        } elseif (!in_array($info['release_state'], $_PEAR_Common_release_states)) {
            $errors[] = "invalid release state `$info[release_state]', should be one of: ".implode(' ', $_PEAR_Common_release_states);
        }
        if (empty($info['release_date'])) {
            $errors[] = 'missing release date';
        } elseif (!preg_match('/^\d{4}-\d\d-\d\d$/', $info['release_date'])) {
            $errors[] = "invalid release date `$info[release_date]', format is YYYY-MM-DD";
        }
        if (empty($info['release_notes'])) {
            $errors[] = "missing release notes";
        }
        if (empty($info['maintainers'])) {
            $errors[] = 'no maintainer(s)';
        } else {
            $i = 1;
            foreach ($info['maintainers'] as $m) {
                if (empty($m['handle'])) {
                    $errors[] = "maintainer $i: missing handle";
                }
                if (empty($m['role'])) {
                    $errors[] = "maintainer $i: missing role";
                } elseif (!in_array($m['role'], $_PEAR_Common_maintainer_roles)) {
                    $errors[] = "maintainer $i: invalid role `$m[role]', should be one of: ".implode(' ', $_PEAR_Common_maintainer_roles);
                }
                if (empty($m['name'])) {
                    $errors[] = "maintainer $i: missing name";
                }
                if (empty($m['email'])) {
                    $errors[] = "maintainer $i: missing email";
                }
                $i++;
            }
        }
        if (!empty($info['deps'])) {
            $i = 1;
            foreach ($info['deps'] as $d) {
                if (empty($d['type'])) {
                    $errors[] = "depenency $i: missing type";
                } elseif (!in_array($d['type'], $_PEAR_Common_dependency_types)) {
                    $errors[] = "dependency $i: invalid type, should be one of: ".implode(' ', $_PEAR_Common_depenency_types);
                }
                if (empty($d['rel'])) {
                    $errors[] = "dependency $i: missing relation";
                } elseif (!in_array($d['rel'], $_PEAR_Common_dependency_relations)) {
                    $errors[] = "dependency $i: invalid relation, should be one of: ".implode(' ', $_PEAR_Common_dependency_relations);
                }
                if ($d['rel'] != 'has' && empty($d['version'])) {
                    $warnings[] = "dependency $i: missing version";
                } elseif ($d['rel'] == 'has' && !empty($d['version'])) {
                    $warnings[] = "dependency $i: version ignored for `has' dependencies";
                }
                if ($d['type'] == 'php' && !empty($d['name'])) {
                    $warnings[] = "dependency $i: name ignored for php type dependencies";
                } elseif ($d['type'] != 'php' && empty($d['name'])) {
                    $errors[] = "dependency $i: missing name";
                }
                $i++;
            }
        }
        if (!empty($info['configure_options'])) {
            $i = 1;
            foreach ($info['configure_options'] as $c) {
                if (empty($c['name'])) {
                    $errors[] = "configure option $i: missing name";
                }
                if (empty($c['prompt'])) {
                    $errors[] = "configure option $i: missing prompt";
                }
                $i++;
            }
        }
        if (empty($info['filelist'])) {
            $errors[] = 'no files';
        } else {
            foreach ($info['filelist'] as $file => $fa) {
                if (empty($fa['role'])) {
                    $errors[] = "file $file: missing role";
                    continue;
                } elseif (!in_array($fa['role'], $_PEAR_Common_file_roles)) {
                    $errors[] = "file $file: invalid role, should be one of: ".implode(' ', $_PEAR_Common_file_roles);
                }
                if ($fa['role'] == 'php' && $dir_prefix) {
                    $this->log(1, "Analyzing $file");
                    $srcinfo = $this->analyzeSourceCode($dir_prefix . DIRECTORY_SEPARATOR . $file);
                    if ($srcinfo) {
                        $this->buildProvidesArray($srcinfo);
                    }
                }
                // (ssb) Any checks we can do for baseinstalldir?
                // (cox) Perhaps checks that either the target dir and
                //       baseInstall doesn't cointain "../../"
            }
        }
        $pn = $info['package'];
        $pnl = strlen($pn);
        foreach ((array)$this->pkginfo['provides'] as $key => $what) {
            if (isset($what['explicit'])) {
                // skip conformance checks if the provides entry is
                // specified in the package.xml file
                continue;
            }
            extract($what);
            if ($type == 'class') {
                if (!strncasecmp($name, $pn, $pnl)) {
                    continue;
                }
                $warnings[] = "in $file: class \"$name\" not prefixed with package name \"$pn\"";
            } elseif ($type == 'function') {
                if (strstr($name, '::') || !strncasecmp($name, $pn, $pnl)) {
                    continue;
                }
                $warnings[] = "in $file: function \"$name\" not prefixed with package name \"$pn\"";
            }
            //print "$file: provides $what[type] $what[name]\n";
        }
        return true;
    }

    // }}}
    // {{{ buildProvidesArray()

    /**
     * Build a "provides" array from data returned by
     * analyzeSourceCode().  The format of the built array is like
     * this:
     *
     *  array(
     *    'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'),
     *    ...
     *  )
     *
     *
     * @param array $srcinfo array with information about a source file
     * as returned by the analyzeSourceCode() method.
     *
     * @return void
     *
     * @access public
     *
     */
    function buildProvidesArray($srcinfo)
    {
        foreach ($srcinfo['declared_classes'] as $class) {
            $key = "class;$class";
            if (isset($this->pkginfo['provides'][$key])) {
                continue;
            }
            $this->pkginfo['provides'][$key] =
                array('type' => 'class', 'name' => $class);
            if (isset($srcinfo['inheritance'][$class])) {
                $this->pkginfo['provides'][$key]['extends'] =
                    $srcinfo['inheritance'][$class];
            }
        }
        foreach ($srcinfo['declared_methods'] as $class => $methods) {
            foreach ($methods as $method) {
                $function = "$class::$method";
                $key = "function;$function";
                if ($method{0} == '_' || !strcasecmp($method, $class) ||
                    isset($this->pkginfo['provides'][$key])) {
                    continue;
                }
                $this->pkginfo['provides'][$key] =
                    array('type' => 'function', 'name' => $function);
            }
        }
        foreach ($srcinfo['declared_functions'] as $function) {
            $key = "function;$function";
            if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) {
                continue;
            }
            $this->pkginfo['provides'][$key] =
                array('type' => 'function', 'name' => $function);
        }
    }

    // }}}
    // {{{ analyzeSourceCode()

    /**
     * Analyze the source code of the given PHP file
     *
     * @param  string Filename of the PHP file
     * @return mixed
     * @access public
     */
    function analyzeSourceCode($file)
    {
        if (!function_exists("token_get_all")) {
            return false;
        }
        if (!$fp = @fopen($file, "r")) {
            return false;
        }
        $contents = fread($fp, filesize($file));
        $tokens = token_get_all($contents);
/*
        for ($i = 0; $i < sizeof($tokens); $i++) {
            @list($token, $data) = $tokens[$i];
            if (is_string($token)) {
                var_dump($token);
            } else {
                print token_name($token) . ' ';
                var_dump(rtrim($data));
            }
        }
*/
        $look_for = 0;
        $paren_level = 0;
        $bracket_level = 0;
        $brace_level = 0;
        $lastphpdoc = '';
        $current_class = '';
        $current_class_level = -1;
        $current_function = '';
        $current_function_level = -1;
        $declared_classes = array();
        $declared_functions = array();
        $declared_methods = array();
        $used_classes = array();
        $used_functions = array();
        $extends = array();
        $nodeps = array();
        for ($i = 0; $i < sizeof($tokens); $i++) {
            if (is_array($tokens[$i])) {
                list($token, $data) = $tokens[$i];
            } else {
                $token = $tokens[$i];
                $data = '';
            }
            switch ($token) {
                case T_CURLY_OPEN:
                case T_DOLLAR_OPEN_CURLY_BRACES:
                case '{': $brace_level++; continue 2;
                case '}':
                    $brace_level--;
                    if ($current_class_level == $brace_level) {
                        $current_class = '';
                        $current_class_level = -1;
                    }
                    if ($current_function_level == $brace_level) {
                        $current_function = '';
                        $current_function_level = -1;
                    }
                    continue 2;
                case '[': $bracket_level++; continue 2;
                case ']': $bracket_level--; continue 2;
                case '(': $paren_level++;   continue 2;
                case ')': $paren_level--;   continue 2;
                case T_CLASS:
                case T_FUNCTION:
                case T_NEW:
                case T_EXTENDS:
                    $look_for = $token;
                    continue 2;
                case T_STRING:
                    if ($look_for == T_CLASS) {
                        $current_class = $data;
                        $current_class_level = $brace_level;
                        $declared_classes[] = $current_class;
                    } elseif ($look_for == T_EXTENDS) {
                        $extends[$current_class] = $data;
                    } elseif ($look_for == T_FUNCTION) {
                        if ($current_class) {
                            $current_function = "$current_class::$data";
                            $declared_methods[$current_class][] = $data;
                        } else {
                            $current_function = $data;
                            $declared_functions[] = $current_function;
                        }
                        $current_function_level = $brace_level;
                        $m = array();
                    } elseif ($look_for == T_NEW) {
                        $used_classes[$data] = true;
                    }
                    $look_for = 0;
                    continue 2;
                case T_VARIABLE:
                    $look_for = 0;
                    continue 2;
                case T_COMMENT:
                    if (preg_match('!^/\*\*\s!', $data)) {
                        $lastphpdoc = $data;
                        if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) {
                            $nodeps = array_merge($nodeps, $m[1]);
                        }
                    }
                    continue 2;
                case T_DOUBLE_COLON:
                    $class = $tokens[$i - 1][1];
                    if (strtolower($class) != 'parent') {
                        $used_classes[$class] = true;
                    }
                    continue 2;
            }
        }
        return array(
            "declared_classes" => $declared_classes,
            "declared_methods" => $declared_methods,
            "declared_functions" => $declared_functions,
            "used_classes" => array_diff(array_keys($used_classes), $nodeps),
            "inheritance" => $extends,
            );
    }

    // }}}
    // {{{ detectDependencies()

    function detectDependencies($any, $status_callback = null)
    {
        if (!function_exists("token_get_all")) {
            return false;
        }
        if (PEAR::isError($info = $this->infoFromAny($any))) {
            return $this->raiseError($info);
        }
        if (!is_array($info)) {
            return false;
        }
        $deps = array();
        $used_c = $decl_c = $decl_f = $decl_m = array();
        foreach ($info['filelist'] as $file => $fa) {
            $tmp = $this->analyzeSourceCode($file);
            $used_c = @array_merge($used_c, $tmp['used_classes']);
            $decl_c = @array_merge($decl_c, $tmp['declared_classes']);
            $decl_f = @array_merge($decl_f, $tmp['declared_functions']);
            $decl_m = @array_merge($decl_m, $tmp['declared_methods']);
            $inheri = @array_merge($inheri, $tmp['inheritance']);
        }
        $used_c = array_unique($used_c);
        $decl_c = array_unique($decl_c);
        $undecl_c = array_diff($used_c, $decl_c);
        return array('used_classes' => $used_c,
                     'declared_classes' => $decl_c,
                     'declared_methods' => $decl_m,
                     'declared_functions' => $decl_f,
                     'undeclared_classes' => $undecl_c,
                     'inheritance' => $inheri,
                     );
    }

    // }}}
    // {{{ getUserRoles()

    /**
     * Get the valid roles for a PEAR package maintainer
     *
     * @return array
     * @static
     */
    function getUserRoles()
    {
        return $GLOBALS['_PEAR_Common_maintainer_roles'];
    }

    // }}}
    // {{{ getReleaseStates()

    /**
     * Get the valid package release states of packages
     *
     * @return array
     * @static
     */
    function getReleaseStates()
    {
        return $GLOBALS['_PEAR_Common_release_states'];
    }

    // }}}
    // {{{ getDependencyTypes()

    /**
     * Get the implemented dependency types (php, ext, pkg etc.)
     *
     * @return array
     * @static
     */
    function getDependencyTypes()
    {
        return $GLOBALS['_PEAR_Common_dependency_types'];
    }

    // }}}
    // {{{ getDependencyRelations()

    /**
     * Get the implemented dependency relations (has, lt, ge etc.)
     *
     * @return array
     * @static
     */
    function getDependencyRelations()
    {
        return $GLOBALS['_PEAR_Common_dependency_relations'];
    }

    // }}}
    // {{{ getFileRoles()

    /**
     * Get the implemented file roles
     *
     * @return array
     * @static
     */
    function getFileRoles()
    {
        return $GLOBALS['_PEAR_Common_file_roles'];
    }

    // }}}
    // {{{ getReplacementTypes()

    /**
     * Get the implemented file replacement types in
     *
     * @return array
     * @static
     */
    function getReplacementTypes()
    {
        return $GLOBALS['_PEAR_Common_replacement_types'];
    }

    // }}}
    // {{{ getProvideTypes()

    /**
     * Get the implemented file replacement types in
     *
     * @return array
     * @static
     */
    function getProvideTypes()
    {
        return $GLOBALS['_PEAR_Common_provide_types'];
    }

    // }}}
    // {{{ getScriptPhases()

    /**
     * Get the implemented file replacement types in
     *
     * @return array
     * @static
     */
    function getScriptPhases()
    {
        return $GLOBALS['_PEAR_Common_script_phases'];
    }

    // }}}
    // {{{ validPackageName()

    /**
     * Test whether a string contains a valid package name.
     *
     * @param string $name the package name to test
     *
     * @return bool
     *
     * @access public
     */
    function validPackageName($name)
    {
        return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name);
    }

    // }}}

    // {{{ downloadHttp()

    /**
     * Download a file through HTTP.  Considers suggested file name in
     * Content-disposition: header and can run a callback function for
     * different events.  The callback will be called with two
     * parameters: the callback type, and parameters.  The implemented
     * callback types are:
     *
     *  'setup'       called at the very beginning, parameter is a UI object
     *                that should be used for all output
     *  'message'     the parameter is a string with an informational message
     *  'saveas'      may be used to save with a different file name, the
     *                parameter is the filename that is about to be used.
     *                If a 'saveas' callback returns a non-empty string,
     *                that file name will be used as the filename instead.
     *                Note that $save_dir will not be affected by this, only
     *                the basename of the file.
     *  'start'       download is starting, parameter is number of bytes
     *                that are expected, or -1 if unknown
     *  'bytesread'   parameter is the number of bytes read so far
     *  'done'        download is complete, parameter is the total number
     *                of bytes read
     *  'connfailed'  if the TCP connection fails, this callback is called
     *                with array(host,port,errno,errmsg)
     *  'writefailed' if writing to disk fails, this callback is called
     *                with array(destfile,errmsg)
     *
     * If an HTTP proxy has been configured (http_proxy PEAR_Config
     * setting), the proxy will be used.
     *
     * @param string  $url       the URL to download
     * @param object  $ui        PEAR_Frontend_* instance
     * @param object  $config    PEAR_Config instance
     * @param string  $save_dir  (optional) directory to save file in
     * @param mixed   $callback  (optional) function/method to call for status
     *                           updates
     *
     * @return string  Returns the full path of the downloaded file or a PEAR
     *                 error on failure.  If the error is caused by
     *                 socket-related errors, the error object will
     *                 have the fsockopen error code available through
     *                 getCode().
     *
     * @access public
     */
    function downloadHttp($url, &$ui, $save_dir = '.', $callback = null)
    {
        if ($callback) {
            call_user_func($callback, 'setup', array(&$ui));
        }
        if (preg_match('!^http://([^/:?#]*)(:(\d+))?(/.*)!', $url, $matches)) {
            list(,$host,,$port,$path) = $matches;
        }
        if (isset($this)) {
            $config = &$this->config;
        } else {
            $config = &PEAR_Config::singleton();
        }
        $proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
        if ($proxy = parse_url($config->get('http_proxy'))) {
            $proxy_host = @$proxy['host'];
            $proxy_port = @$proxy['port'];
            $proxy_user = @$proxy['user'];
            $proxy_pass = @$proxy['pass'];

            if ($proxy_port == '') {
                $proxy_port = 8080;
            }
            if ($callback) {
                call_user_func($callback, 'message', "Using HTTP proxy $host:$port");
            }
        }
        if (empty($port)) {
            $port = 80;
        }
        if ($proxy_host != '') {
            $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr);
            if (!$fp) {
                if ($callback) {
                    call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port,
                                                                  $errno, $errstr));
                }
                return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno);
            }
            $request = "GET $url HTTP/1.0\r\n";
        } else {
            $fp = @fsockopen($host, $port, $errno, $errstr);
            if (!$fp) {
                if ($callback) {
                    call_user_func($callback, 'connfailed', array($host, $port,
                                                                  $errno, $errstr));
                }
                return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno);
            }
            $request = "GET $path HTTP/1.0\r\n";
        }
        $request .= "Host: $host:$port\r\n".
            "User-Agent: PHP/".PHP_VERSION."\r\n";
        if ($proxy_host != '' && $proxy_user != '') {
            $request .= 'Proxy-Authorization: Basic ' .
                base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n";
        }
        $request .= "\r\n";
        fwrite($fp, $request);
        $headers = array();
        while (trim($line = fgets($fp, 1024))) {
            if (preg_match('/^([^:]+):\s+(.*)\s*$/', $line, $matches)) {
                $headers[strtolower($matches[1])] = trim($matches[2]);
            } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
                if ($matches[1] != 200) {
                    return PEAR::raiseError("File http://$host:$port$path not valid (received: $line)");
                }
            }
        }
        if (isset($headers['content-disposition']) &&
            preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|$)/', $headers['content-disposition'], $matches)) {
            $save_as = basename($matches[1]);
        } else {
            $save_as = basename($url);
        }
        if ($callback) {
            $tmp = call_user_func($callback, 'saveas', $save_as);
            if ($tmp) {
                $save_as = $tmp;
            }
        }
        $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
        if (!$wp = @fopen($dest_file, 'wb')) {
            fclose($fp);
            if ($callback) {
                call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
            }
            return PEAR::raiseError("could not open $dest_file for writing");
        }
        if (isset($headers['content-length'])) {
            $length = $headers['content-length'];
        } else {
            $length = -1;
        }
        $bytes = 0;
        if ($callback) {
            call_user_func($callback, 'start', $length);
        }
        while ($data = @fread($fp, 1024)) {
            $bytes += strlen($data);
            if ($callback) {
                call_user_func($callback, 'bytesread', $bytes);
            }
            if (!@fwrite($wp, $data)) {
                fclose($fp);
                if ($callback) {
                    call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
                }
                return PEAR::raiseError("$dest_file: write failed ($php_errormsg)");
            }
        }
        fclose($fp);
        fclose($wp);
        if ($callback) {
            call_user_func($callback, 'done', $bytes);
        }
        return $dest_file;
    }

    // }}}
}

?>


text:
use super::common::describe_cv;
use crate::{DecodeError, FieldInfo};

/// Decodes the ISS value for an MCR or MRC access.
pub fn decode_iss_mcr(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
    let cv =
        FieldInfo::get_bit(iss, "CV", Some("Condition code valid"), 24).describe_bit(describe_cv);
    let cond = FieldInfo::get(
        iss,
        "COND",
        Some("Condition code of the trapped instruction"),
        20,
        24,
    );
    let opc2 = FieldInfo::get(iss, "Opc2", None, 17, 20);
    let opc1 = FieldInfo::get(iss, "Opc1", None, 14, 17);
    let crn = FieldInfo::get(iss, "CRn", None, 10, 14);
    let rt = FieldInfo::get(iss, "Rt", None, 5, 10);
    let crm = FieldInfo::get(iss, "CRm", None, 1, 5);
    let direction = FieldInfo::get_bit(
        iss,
        "Direction",
        Some("Direction of the trapped instruction"),
        0,
    )
    .describe_bit(describe_direction);

    Ok(vec![cv, cond, opc2, opc1, crn, rt, crm, direction])
}

/// Decodes the ISS value for an MCRR or MRRC access.
pub fn decode_iss_mcrr(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
    let cv =
        FieldInfo::get_bit(iss, "CV", Some("Condition code valid"), 24).describe_bit(describe_cv);
    let cond = FieldInfo::get(
        iss,
        "COND",
        Some("Condition code of the trapped instruction"),
        20,
        24,
    );
    let opc1 = FieldInfo::get(iss, "Opc2", None, 16, 20);
    let res0 = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 15).check_res0()?;
    let rt2 = FieldInfo::get(iss, "Rt2", None, 10, 15);
    let rt = FieldInfo::get(iss, "Rt", None, 5, 10);
    let crm = FieldInfo::get(iss, "CRm", None, 1, 5);
    let direction = FieldInfo::get_bit(
        iss,
        "Direction",
        Some("Direction of the trapped instruction"),
        0,
    )
    .describe_bit(describe_direction);

    Ok(vec![cv, cond, opc1, res0, rt2, rt, crm, direction])
}

fn describe_direction(direction: bool) -> &'static str {
    if direction {
        "Read from system register (MRC or VMRS)"
    } else {
        "Write to system register (MCR)"
    }
}

redpajama_set_name: RedPajamaGithub


text:
    (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
     (__GNUC__ >= 4))  // GCC supports "pragma once" correctly since 3.4
#pragma once
#endif

#include "setting.h"
#include "yaml-cpp/emitterdef.h"
#include "yaml-cpp/emittermanip.h"

#include <cassert>
#include <memory>
#include <stack>
#include <stdexcept>
#include <vector>

namespace YAML {
struct FmtScope {
  enum value { Local, Global };
};
struct GroupType {
  enum value { NoType, Seq, Map };
};
struct FlowType {
  enum value { NoType, Flow, Block };
};

class EmitterState {
 public:
  EmitterState();
  ~EmitterState();

  // basic state checking
  bool good() const { return m_isGood; }
  const std::string GetLastError() const { return m_lastError; }
  void SetError(const std::string& error) {
    m_isGood = false;
    m_lastError = error;
  }

  // node handling
  void SetAnchor();
  void SetTag();
  void SetNonContent();
  void SetLongKey();
  void ForceFlow();
  void StartedDoc();
  void EndedDoc();
  void StartedScalar();
  void StartedGroup(GroupType::value type);
  void EndedGroup(GroupType::value type);

  EmitterNodeType::value NextGroupType(GroupType::value type) const;
  EmitterNodeType::value CurGroupNodeType() const;

  GroupType::value CurGroupType() const;
  FlowType::value CurGroupFlowType() const;
  int CurGroupIndent() const;
  std::size_t CurGroupChildCount() const;
  bool CurGroupLongKey() const;

  int LastIndent() const;
  int CurIndent() const { return m_curIndent; }
  bool HasAnchor() const { return m_hasAnchor; }
  bool HasTag() const { return m_hasTag; }
  bool HasBegunNode() const {
    return m_hasAnchor || m_hasTag || m_hasNonContent;
  }
  bool HasBegunContent() const { return m_hasAnchor || m_hasTag; }

  void ClearModifiedSettings();

  // formatters
  void SetLocalValue(EMITTER_MANIP value);

  bool SetOutputCharset(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetOutputCharset() const { return m_charset.get(); }

  bool SetStringFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetStringFormat() const { return m_strFmt.get(); }

  bool SetBoolFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetBoolFormat() const { return m_boolFmt.get(); }

  bool SetBoolLengthFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetBoolLengthFormat() const { return m_boolLengthFmt.get(); }

  bool SetBoolCaseFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetBoolCaseFormat() const { return m_boolCaseFmt.get(); }

  bool SetIntFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetIntFormat() const { return m_intFmt.get(); }

  bool SetIndent(std::size_t value, FmtScope::value scope);
  int GetIndent() const { return m_indent.get(); }

  bool SetPreCommentIndent(std::size_t value, FmtScope::value scope);
  int GetPreCommentIndent() const { return m_preCommentIndent.get(); }
  bool SetPostCommentIndent(std::size_t value, FmtScope::value scope);
  int GetPostCommentIndent() const { return m_postCommentIndent.get(); }

  bool SetFlowType(GroupType::value groupType, EMITTER_MANIP value,
                   FmtScope::value scope);
  EMITTER_MANIP GetFlowType(GroupType::value groupType) const;

  bool SetMapKeyFormat(EMITTER_MANIP value, FmtScope::value scope);
  EMITTER_MANIP GetMapKeyFormat() const { return m_mapKeyFmt.get(); }

  bool SetFloatPrecision(int value, FmtScope::value scope);
  std::size_t GetFloatPrecision() const { return m_floatPrecision.get(); }
  bool SetDoublePrecision(int value, FmtScope::value scope);
  std::size_t GetDoublePrecision() const { return m_doublePrecision.get(); }

 private:
  template <typename T>
  void _Set(Setting<T>& fmt, T value, FmtScope::value scope);

  void StartedNode();

 private:
  // basic state ok?
  bool m_isGood;
  std::string m_lastError;

  // other state
  Setting<EMITTER_MANIP> m_charset;
  Setting<EMITTER_MANIP> m_strFmt;
  Setting<EMITTER_MANIP> m_boolFmt;
  Setting<EMITTER_MANIP> m_boolLengthFmt;
  Setting<EMITTER_MANIP> m_boolCaseFmt;
  Setting<EMITTER_MANIP> m_intFmt;
  Setting<std::size_t> m_indent;
  Setting<std::size_t> m_preCommentIndent, m_postCommentIndent;
  Setting<EMITTER_MANIP> m_seqFmt;
  Setting<EMITTER_MANIP> m_mapFmt;
  Setting<EMITTER_MANIP> m_mapKeyFmt;
  Setting<int> m_floatPrecision;
  Setting<int> m_doublePrecision;

  SettingChanges m_modifiedSettings;
  SettingChanges m_globalModifiedSettings;

  struct Group {
    explicit Group(GroupType::value type_)
        : type(type_), indent(0), childCount(0), longKey(false) {}

    GroupType::value type;
    FlowType::value flowType;
    int indent;
    std::size_t childCount;
    bool longKey;

    SettingChanges modifiedSettings;

    EmitterNodeType::value NodeType() const {
      if (type == GroupType::Seq) {
        if (flowType == FlowType::Flow)
          return EmitterNodeType::FlowSeq;
        else
          return EmitterNodeType::BlockSeq;
      } else {
        if (flowType == FlowType::Flow)
          return EmitterNodeType::FlowMap;
        else
          return EmitterNodeType::BlockMap;
      }

      // can't get here
      assert(false);
      return EmitterNodeType::NoType;
    }
  };

  std::vector<std::unique_ptr<Group>> m_groups;
  std::size_t m_curIndent;
  bool m_hasAnchor;
  bool m_hasTag;
  bool m_hasNonContent;
  std::size_t m_docCount;
};

template <typename T>
void EmitterState::_Set(Setting<T>& fmt, T value, FmtScope::value scope) {
  switch (scope) {
    case FmtScope::Local:
      m_modifiedSettings.push(fmt.set(value));
      break;
    case FmtScope::Global:
      fmt.set(value);
      m_globalModifiedSettings.push(
          fmt.set(value));  // this pushes an identity set, so when we restore,
      // it restores to the value here, and not the previous one
      break;
    default:
      assert(false);
  }
}
}

#endif  // EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ViewChanger : MonoBehaviour {

    [SerializeField] private Camera firstCamera;
    [SerializeField] private Camera thirdCamera;
    private GameObject bluePanel;
    public bool firstperson = false;

    private void Start()
    {
        firstCamera.enabled = false;
        bluePanel = firstCamera.gameObject.transform.GetChild(0).gameObject;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown("joystick button 9"))
        {
            Debug.Log("if ok");
            firstCamera.enabled = !firstCamera.enabled;
            thirdCamera.enabled = !thirdCamera.enabled;
            firstperson = !firstperson;
            bluePanel.SetActive(firstperson);
        }
	}
}


text:
<!DOCTYPE html>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <meta name="description">
        <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="shortcut icon" href="/StrideToolkit/assets/img/favicon.ico" type="image/x-icon">
        <link rel="icon" href="/StrideToolkit/assets/img/favicon.ico" type="image/x-icon">
        <title>StrideToolkit - API - EntityExtensions Class</title>
        <link href="/StrideToolkit/assets/css/highlight.css" rel="stylesheet">
        <link href="/StrideToolkit/assets/css/bootstrap/bootstrap.css" rel="stylesheet">
        <link href="/StrideToolkit/assets/css/adminlte/AdminLTE.css" rel="stylesheet">
        <link href="/StrideToolkit/assets/css/theme/theme.css" rel="stylesheet">
        <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet">
        <link href="/StrideToolkit/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href="/StrideToolkit/assets/css/override.css" rel="stylesheet">

                            Toggle side menu

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
                            Toggle side menu

                        </button>

Documentation

API

 Source

On This Page

Summary

Syntax

Methods

            <input type="text" name="search" id="search" class="form-control" placeholder="Search Types...">

                <button class="btn btn-flat"></button>

Namespace

StrideToolkit<wbr>.Engine

Class Types

CameraExtensions

Entity<wbr>Component<wbr>Collection<wbr>Extensions

Entity<wbr>Component<wbr>Search<wbr>Extensions

EntityExtensions

GameExtensions

Model<wbr>Component<wbr>Extensions

PrefabExtensions

Script<wbr>System<wbr>Extensions

TransformExtensions

Enum Types

Space

EntityExtensions Class

Summary

    Extension methods for EntityComponent.

Namespace

StrideToolkit<wbr>.Engine

Base Types

object

							graph BT
	Type-->Base0["object"]
	Type["EntityExtensions"]
class Type type-node

Syntax

public static class EntityExtensions

Methods

								Name
								Value
								Summary

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14, <wbr>TComponent15, <wbr>TComponent16><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14, <wbr>TComponent15, <wbr>TComponent16)<wbr>

    Gets the sixteen specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14, <wbr>TComponent15><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14, <wbr>TComponent15)<wbr>

    Gets the fifteen specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13, <wbr>TComponent14)<wbr>

    Gets the fourteen specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12, <wbr>TComponent13)<wbr>

    Gets the thirteen specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11, <wbr>TComponent12)<wbr>

    Gets the twelve specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10, <wbr>TComponent11)<wbr>

    Gets the eleven specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9, <wbr>TComponent10)<wbr>

    Gets the ten specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8, <wbr>TComponent9)<wbr>

    Gets the nine specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7, <wbr>TComponent8)<wbr>

    Gets the eight specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6, <wbr>TComponent7)<wbr>

    Gets the seven specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5, <wbr>TComponent6)<wbr>

    Gets the six specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4, <wbr>TComponent5)<wbr>

    Gets the five specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3, <wbr>TComponent4)<wbr>

    Gets the four specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2, <wbr>TComponent3><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2, <wbr>TComponent3)<wbr>

    Gets the three specified components.

static

								Get<wbr><TComponent1, <wbr>TComponent2><wbr><wbr>(Entity)<wbr>
								<wbr>(TComponent1, <wbr>TComponent2)<wbr>

    Gets the two specified components.

static

     GitHub |
     Twitter

    Copyright © Daniel Keenan.

    Generated by Wyam


text:
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Azure.Core
{
    internal class StringRequestContent : RequestContent
    {
        private readonly byte[] _bytes;

        public StringRequestContent(string value)
        {
            _bytes = Encoding.UTF8.GetBytes(value);
        }

        public override async Task WriteToAsync(Stream stream, CancellationToken cancellation)
        {
            await stream.WriteAsync(_bytes, 0, _bytes.Length, cancellation).ConfigureAwait(false);
        }

        public override void WriteTo(Stream stream, CancellationToken cancellation)
        {
            stream.Write(_bytes, 0, _bytes.Length);
        }

        public override bool TryComputeLength(out long length)
        {
            length = _bytes.Length;
            return true;
        }

        public override void Dispose()
        {
        }
    }
}


text:
Diplomski rad iz PHP-a za Visoku ICT

-CMS za online shop-

Katarina Zečević 3/12
Biljana Domčić 5/12
Vladislav Hristodulo 65/12
Nikola Matić 75/12
Aleksa Novaković 92/12


text:
import numpy as np
import os
from nltk.tokenize import RegexpTokenizer
import re
from collections import Counter
from gensim.models import word2vec
import sys
import pandas as pd

w2vDir = './output/sgWord/sgWordPhrase'

class SentimentRetrofit(object):
    def __init__(self, vectors=None, vocab=None, dim=50, lambDa=0.05, vocabSize=16000):
        self.vectors = vectors
        self.vocab = vocab
        self.dim = dim
        self.lambDa = lambDa
        # {name: (pos or neg, {word_index: freq)}
        self.documentDictPos = Counter()
        self.documentDictNeg = Counter()
        self.documentDictTol = Counter()
        self.wordSet = set()
        self.vocabSize = vocabSize
        self.word2indx = {}
        self.wordNum = 0
        self.tokenizer = RegexpTokenizer(r"[\w'-]+")

    def loadVocab(self, fname):
        """
        load vocab in imdb
        """
        print 'loading imdb vocab...'
        with open(fname, 'r') as vocabFile:
            for line in vocabFile:
                token = line.strip(' \n')
                if len(token) > 0 and token not in self.wordSet and (self.vocab is None or token in self.vocab):
                    self.wordSet.add(token)

    def buildVocab(self):

        if self.vectors is None:
            # self.originalVec = np.zeros((len(self.word2indx), self.dim))
            self.documentDictTol.update(self.documentDictPos)
            self.documentDictTol.update(self.documentDictNeg)
            self.wordList = [word for word, freq in self.documentDictTol.most_common(self.vocabSize)]
            self.posWeight = [self.documentDictPos[word] for word in self.wordList]
            self.negWeight = [self.documentDictNeg[word] for word in self.wordList]
            self.originalVec = np.zeros(0)
            for word in self.wordList:
                vec = self.makeRandVector(self.dim)
                self.originalVec = np.append(self.originalVec, vec)
            self.originalVec = self.originalVec.reshape((self.vocabSize, self.dim))
        else:
            self.documentDictTol.update(self.documentDictPos)
            self.documentDictTol.update(self.documentDictNeg)
            self.wordList = [word for word, freq in self.documentDictTol.most_common(self.vocabSize)]
            self.posWeight = [self.documentDictPos[word] for word in self.wordList]
            self.negWeight = [self.documentDictNeg[word] for word in self.wordList]
            self.originalVec = np.zeros(0)
            for word in self.wordList:
                vec = self.vectors[word]
                self.originalVec = np.append(self.originalVec, vec)
            self.originalVec = self.originalVec.reshape((self.vocabSize, self.dim))

        print 'original vec is of dimension:', self.originalVec.shape

    def loadDocument(self, directory, polarity, trainCount):
        print 'loading document at ' + directory
        idx = 0
        for filename in os.listdir(directory):
            if idx >= trainCount / 2:
                break
            if filename.split('.')[-1] == "txt":
                idx += 1
                # {word_index: freq}
                with open(directory + filename, 'r') as file:
                    line = file.read()
                    bow = self.convertDocument2Bow(line)
                    if polarity == 'pos':
                        self.documentDictPos.update(bow)
                    else:
                        self.documentDictNeg.update(bow)

    def convertDocument2Bow(self, line):
        tokenList = self.tokenizer.tokenize(line.lower())
        bow = Counter()
        for token in tokenList:
            if token in self.wordSet:
                bow[token] += 1

        return bow

    def makeRandVector(self, dims):
        mu, sigma = 0, 1
        vec = np.random.normal(mu, sigma, dims)
        return self.normalize(vec)

    def normalize(self, v):
        norm = np.linalg.norm(v)
        if norm == 0:
            return v
        return v / norm

    def writeWordVectors(self, outputFileW2V, outputFilePos, outputFileNeg):
        print 'writing to file...'
        df = pd.DataFrame(data=self.originalVec,
                          index=self.wordList)
        df.to_csv(outputFileW2V, encoding='utf-8')

        dfPos = pd.DataFrame(self.posWeight)
        dfPos.to_csv(outputFilePos)

        dfNeg = pd.DataFrame(self.negWeight)
        dfNeg.to_csv(outputFileNeg)

if __name__ == '__main__':
    sys.stderr.write('Reading vectors from file...\n')

    model = word2vec.Word2Vec.load(w2vDir)
    vectorDim = len(model[model.vocab.iterkeys().next()])
    wordVectors = model
    sys.stderr.write('Loaded vectors from file...\n')
    vocab = {word: model.vocab[word].index for word in model.vocab}
    sys.stderr.write('Finished reading vectors.\n')

    trainCount = int(sys.argv[1])
    trainCountStr = sys.argv[1]

    retrofitter = SentimentRetrofit(vocab=vocab, dim=200)
    retrofitter.loadVocab('./aclImdb/imdb.vocab')
    retrofitter.loadDocument('./aclImdb/train/pos/', 'pos', trainCount)
    retrofitter.loadDocument('./aclImdb/train/neg/', 'neg', trainCount)
    retrofitter.buildVocab()
    retrofitter.writeWordVectors('./output/random{}.csv'.format(trainCountStr),
                                 './output/posRandom{}List.csv'.format(trainCountStr),
                                 './output/negRandom{}List.csv'.format(trainCountStr))


text:
import * as React from 'react';
import { makeStyles, Theme, useTheme, createStyles } from '@material-ui/core/styles';
import MobileStepper from '@material-ui/core/MobileStepper';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      maxWidth: 400,
      flexGrow: 1,
    },
    header: {
      display: 'flex',
      alignItems: 'center',
      height: 50,
      paddingLeft: theme.spacing(2),
      backgroundColor: theme.palette.background.default,
    },
    stepContent: {
      height: 255,
      maxWidth: 400,
      width: '100%',
      padding: theme.spacing(2),
    },
  }),
);

const steps = [
  {
    label: 'Select campaign settings',
    description: `For each ad campaign that you create, you can control how much
              you're willing to spend on clicks and conversions, which networks
              and geographical locations you want your ads to show on, and more.`,
  },
  {
    tabel: 'Create an ad group',
    description:
      'An ad group contains one or more ads which target a shared set of keywords.',
  },
  {
    label: 'Create an ad',
    description: `Try out different ad text to see what brings in the most customers,
              and learn how to enhance your ads using features like ad extensions.
              If you run into any problems with your ads, find out how to tell if
              they're running and how to resolve approval issues.`,
  },
];

export default function TextMobileStepper() {
  const classes = useStyles();
  const theme = useTheme();
  const [activeStep, setActiveStep] = React.useState(0);
  const maxSteps = steps.length;

  const handleNext = () => {
    setActiveStep((prevActiveStep) => prevActiveStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  return (

      <Paper square elevation={0} className={classes.header}>
        <Typography>{steps[activeStep].label}</Typography>
      </Paper>

{steps[activeStep].description}

      <MobileStepper
        steps={maxSteps}
        position="static"
        activeStep={activeStep}
        nextButton={
          <Button
            size="small"
            onClick={handleNext}
            disabled={activeStep === maxSteps - 1}
          >
            Next
            {theme.direction === 'rtl' ? (
              <KeyboardArrowLeft />
            ) : (
              <KeyboardArrowRight />
            )}
          </Button>
        }
        backButton={
          <Button size="small" onClick={handleBack} disabled={activeStep === 0}>
            {theme.direction === 'rtl' ? (
              <KeyboardArrowRight />
            ) : (
              <KeyboardArrowLeft />
            )}
            Back
          </Button>
        }
      />

  );
}


text:
Blume is a static site generator meant to be used with [Sinatra](http://www.sinatrarb.com/). Blume is simmilar [Jekyll](http://jekyllrb.com/) in that content is stored in simple YAML + markdown text files. However, with Blume, there is an intermediate in which you read your text files into a MongoDB and develop your site "dynamically" using Sinatra and MongoDB. After the site is developed, you compile it into a self-contained directory which contains a static version of your site with optional compressed versions of all pages.

There may be a bit of additional overhead with learning Blume since you must also use Sinatra and MongoDB but if these are tools you like and/or you would simply like to have more freedom with the development of your static site, Blume may be a good choice for you.

## Installation

To install blume:

    $gem install blume

You also need [MondgoDB](http://docs.mongodb.org/manual/) installed and running.

## Usage

### Caveat

Blume uses a few conventions, most are optional and can be over-ridden but there is one convention that is necessary. All internal URLs must be root-relative. For instance, "/, /sub, sub/sub..." not "www.mysite.com/, www.mysite.com/sub...". This behaviour may change in later releases but it wasn't necessary to implement absolute URLs for my needs so it has taken a low priority.

### Convetions

It will be easiest if you follow the Sinatra default location for your public files (.css, .js, etc.) in the 'public' folder within your project. In addtion to this, the default folder structure for Blume is to keep your content in the 'content' folder and to output the static site to the 'site' folder. The default folder structure for a Blume project could therefor look like this

```
root
    |- content
    |- public
    |- site
    my_app.rb
```

### Content

posts folder structure and date structure

TODO: Write usage instructions here

## Migrations

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package node

import (
	"fmt"
	"sync"

	"github.com/golang/glog"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"

	clientv1 "k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/tools/record"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
	"k8s.io/kubernetes/pkg/cloudprovider"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/gce"
	nodeutil "k8s.io/kubernetes/pkg/util/node"
)

// cloudCIDRAllocator allocates node CIDRs according to IP address aliases
// assigned by the cloud provider. In this case, the allocation and
// deallocation is delegated to the external provider, and the controller
// merely takes the assignment and updates the node spec.
type cloudCIDRAllocator struct {
	lock sync.Mutex

	client clientset.Interface
	cloud  *gce.GCECloud

	recorder record.EventRecorder
}

var _ CIDRAllocator = (*cloudCIDRAllocator)(nil)

func NewCloudCIDRAllocator(
	client clientset.Interface,
	cloud cloudprovider.Interface) (ca CIDRAllocator, err error) {

	gceCloud, ok := cloud.(*gce.GCECloud)
	if !ok {
		err = fmt.Errorf("cloudCIDRAllocator does not support %v provider", cloud.ProviderName())
		return
	}

	ca = &cloudCIDRAllocator{
		client: client,
		cloud:  gceCloud,
		recorder: record.NewBroadcaster().NewRecorder(
			api.Scheme,
			clientv1.EventSource{Component: "cidrAllocator"}),
	}

	glog.V(0).Infof("Using cloud CIDR allocator (provider: %v)", cloud.ProviderName())

	return
}

func (ca *cloudCIDRAllocator) AllocateOrOccupyCIDR(node *v1.Node) error {
	glog.V(2).Infof("Updating PodCIDR for node %v", node.Name)

	cidrs, err := ca.cloud.AliasRanges(types.NodeName(node.Name))

	if err != nil {
		recordNodeStatusChange(ca.recorder, node, "CIDRNotAvailable")
		return fmt.Errorf("failed to allocate cidr: %v", err)
	}

	if len(cidrs) == 0 {
		recordNodeStatusChange(ca.recorder, node, "CIDRNotAvailable")
		glog.V(2).Infof("Node %v has no CIDRs", node.Name)
		return fmt.Errorf("failed to allocate cidr (none exist)")
	}

	node, err = ca.client.Core().Nodes().Get(node.Name, metav1.GetOptions{})
	if err != nil {
		glog.Errorf("Could not get Node object from Kubernetes: %v", err)
		return err
	}

	podCIDR := cidrs[0]

	if node.Spec.PodCIDR != "" {
		if node.Spec.PodCIDR == podCIDR {
			glog.V(3).Infof("Node %v has PodCIDR %v", node.Name, podCIDR)
			return nil
		}
		glog.Errorf("PodCIDR cannot be reassigned, node %v spec has %v, but cloud provider has assigned %v",
			node.Name, node.Spec.PodCIDR, podCIDR)
		// We fall through and set the CIDR despite this error. This
		// implements the same logic as implemented in the
		// rangeAllocator.
		//
		// See https://github.com/kubernetes/kubernetes/pull/42147#discussion_r103357248
	}

	node.Spec.PodCIDR = cidrs[0]
	if _, err := ca.client.Core().Nodes().Update(node); err == nil {
		glog.V(2).Infof("Node %v PodCIDR set to %v", node.Name, podCIDR)
	} else {
		glog.Errorf("Could not update node %v PodCIDR to %v: %v",
			node.Name, podCIDR, err)
		return err
	}

	err = nodeutil.SetNodeCondition(ca.client, types.NodeName(node.Name), v1.NodeCondition{
		Type:               v1.NodeNetworkUnavailable,
		Status:             v1.ConditionFalse,
		Reason:             "RouteCreated",
		Message:            "NodeController create implicit route",
		LastTransitionTime: metav1.Now(),
	})
	if err != nil {
		glog.Errorf("Error setting route status for node %v: %v",
			node.Name, err)
	}

	return err
}

func (ca *cloudCIDRAllocator) ReleaseCIDR(node *v1.Node) error {
	glog.V(2).Infof("Node %v PodCIDR (%v) will be released by external cloud provider (not managed by controller)",
		node.Name, node.Spec.PodCIDR)
	return nil
}


text:
<?php

namespace AppBundle\Enum;

final class OccupationTypes
{
    const EMPLOYED = 'employed';
    const STUDENT = 'student';
    const UNEMPLOYED = 'unemployed';
    const OTHER = 'other';

    private function __construct()
    {
    }

    /**
     * @return array
     */
    public static function listTypesWithTranslationKeys()
    {
        return [
            self::EMPLOYED => 'occupation.employed',
            self::STUDENT => 'occupation.student',
            self::UNEMPLOYED=> 'occupation.unemployed',
            self::OTHER=> 'occupation.other',
        ];
    }

    /**
     * @param string $type
     *
     * @return string
     */
    public static function translationKey($type)
    {
        return self::listTypesWithTranslationKeys()[$type];
    }
}


text:
require 'ext'
local exec = require 'exec'	-- TODO put this somewhere everyone can get it

local ffi = require 'ffi'
local unistd = require 'ffi.c.unistd'	-- getcwd, chdir
require 'ffi.c.stdlib'	-- free
local ccwd = unistd.getcwd(nil, 0)
local cwd = ffi.string(ccwd)
ffi.C.free(ccwd)
assert(unistd.chdir'../..' == 0)
print('cwd = '..cwd)

for _,coord in ipairs{
	'cartesian',
	'cylinder',
	'sphere',
} do
	for _,vectorComponent in ipairs{
		--'anholonomic',
		'cartesian',
	} do
		-- adjust grid size to produce less rows for coord charts like sphere that have small dx's near the center
		local gridSize = {32,32,32}
		if coord == 'sphere' then gridSize = {16,16,16} end

		local cfl = .1

		-- TODO also vary vectorComponent, gridSize, useCTU?
		local dest = table{
			'out',

		-- [[ matches below
			'coord='..coord,
			'vectorComponent='..vectorComponent,
			'gridSize={'..table.concat(gridSize,',')..'}',
			'cfl='..cfl,
		--]]
		}:concat' '..'.txt'

		-- for how long should this run?
		-- TODO pick coord ... and pick vectorComponent
		local cmd = table{
			'luajit',
			'run.lua',
			'sys=console',
			'exitTime=.5',
			'"trackvars=U E_g mag"',
			'"config='..cwd..'/config.lua"',

		-- [[ matches above
			'coord='..coord,
			'vectorComponent='..vectorComponent,
			'"gridSize={'..table.concat(gridSize,',')..'}"',	-- need ""'s to wrap {}'s ?
			'cfl='..cfl,
		--]]

			'> "'..cwd..'/'..dest..'"',
		}:concat' '
		exec(cmd)
	end
end


text:
namespace MoreDotNet.Tests.Extensions.Common.ConvertibleExtensions
{
    using System.Drawing;
    using MoreDotNet.Extensions.Common;
    using Xunit;

    public class ToOrNullTests
    {
        [Fact]
        public void ToOrNull_ConversionSucceeded_ShouldChangeTheObjectType()
        {
            var value = 10;
            var result = value.ToOrNull<string>();

            Assert.IsType(typeof(string), result);
            Assert.Equal("10", result);
        }

        [Fact]
        public void ToOrNull_ConversionFails_ShouldReturnNull()
        {
            var value = 10;
            var result = value.ToOrNull<Assert>();

            Assert.Null(result);
        }

        [Fact]
        public void ToOrNull_WithOutParam_ConversionSucceeded_ShouldChangeTheObjectType()
        {
            var value = 10;
            string newValue;
            var result = value.ToOrNull<string>(out newValue);

            Assert.True(result);
            Assert.IsType(typeof(string), newValue);
            Assert.Equal("10", newValue);
        }

        [Fact]
        public void ToOrNull_WithOutParam_ConversionFails_ShouldReturnNull()
        {
            var value = 10;
            Assert newValue;
            var result = value.ToOrNull<Assert>(out newValue);

            Assert.False(result);
            Assert.Null(newValue);
        }
    }
}


text:
// Load polyfills for IE Array.prototype.fill and Object.entries
require('./polyfills')();

/**
 * Returns a comparison function used to compare entries during ranking
 *
 * @param {boolean} reverse ranking in ascending order if true, descending order otherwise
 * @returns {function} the comparison function takes 2 params and return a signed number
 */
function getCompareFn(reverse) {
  if (reverse) return (a, b) => a[0] - b[0];
  return (a, b) => b[0] - a[0];
}

/**
 * Returns a ranking function. There are 5 ranking methods as explained at
 * https://en.wikipedia.org/wiki/Ranking#Strategies_for_assigning_rankings

 * @param {string} strategy used for ranking.
 * @returns {function} ranking function
 */
function getRankingFn(strategy) {
  if (strategy === 'modified-competition') {
    // Modified competition ranking ("1334" ranking)
    return (start, length) => ({
      current: Array(length).fill(start + (length - 1)),
      next: start + length,
    });
  }

  if (strategy === 'dense') {
    // Dense ranking ("1223" ranking)
    return (start, length) => ({
      current: Array(length).fill(start),
      next: start + 1,
    });
  }

  if (strategy === 'ordinal') {
    // Ordinal ranking ("1234" ranking)
    return (start, length) => ({
      current: Array(length).fill(null).map((_, i) => start + i),
      next: start + length,
    });
  }

  if (strategy === 'fractional') {
    // Fractional ranking ("1 2.5 2.5 4" ranking)
    return (start, length) => ({
      current: Array(length).fill(start + ((length - 1) / 2)),
      next: start + length,
    });
  }

  // Standard competition ranking ("1224" ranking)
  return (start, length) => ({
    current: Array(length).fill(start),
    next: start + length,
  });
}

module.exports = {

  /**
   * Assign ranking to every item of an array
   *
   * @param {array} items to be ranked
   * @param {function} scoreFn a function to extract the score from an item
   * @param {object} options optional parameters
   *   options.reverse: ranking in ascending order if true, descending order otherwise
   *   options.start: the first rank number. Default to 1
   *   options.strategy: to use for ranking. Valid values are:
   *     competition: Standard competition ranking ("1224" ranking)
   *     modified-competition: Modified competition ranking ("1334" ranking)
   *     dense: Dense ranking ("1223" ranking)
   *     ordinal: Ordinal ranking ("1234" ranking)
   *     fractional: Fractional ranking ("1 2.5 2.5 4" ranking)
   * @returns {array} items with their ranking
   */
  ranking(items, scoreFn, options) {
    const reverse = options && options.reverse !== undefined ? options.reverse : false;
    const strategy = options && options.strategy !== undefined ? options.strategy : 'competition';
    const start = options && options.start !== undefined ? options.start : 1;

    const compareFn = getCompareFn(reverse);
    const rankingFn = getRankingFn(strategy);

    let buckets = {};

    items.forEach((e) => {
      const score = scoreFn(e);
      if (buckets[score]) {
        buckets[score].push(e);
      } else {
        buckets[score] = [e];
      }
    });

    // convert to array for sorting
    buckets = Object.entries(buckets);

    // sort based on the score
    buckets.sort(compareFn);

    // assign ranks
    const ranked = [];
    let rank = { next: start };
    buckets.forEach((b) => {
      const bucket = b[1];
      rank = rankingFn(rank.next, bucket.length);
      bucket.forEach((item, index) => {
        ranked.push({ rank: rank.current[index], item });
      });
    });

    return ranked;
  },
};


text:
package io.oasp.gastronomy.restaurant.tablemanagement.common.api;

import io.oasp.gastronomy.restaurant.general.common.api.ApplicationEntity;
import io.oasp.gastronomy.restaurant.tablemanagement.common.api.datatype.TableState;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * This is the interface for a table of the restaurant. It has a unique {@link #getNumber() number} can be
 * {@link io.oasp.gastronomy.restaurant.tablemanagement.common.api.datatype.TableState#isReserved() reserved}, {@link io.oasp.gastronomy.restaurant.tablemanagement.common.api.datatype.TableState#isOccupied() occupied} and may have a
 * {@link #getWaiterId() waiter} assigned.
 *
 * @author hohwille
 */
public interface Table extends ApplicationEntity {

  /**
   * @return the unique table number.
   */
  @NotNull
  @Min(0)
  Long getNumber();

  /**
   * @param number is the new {@link #getNumber() number}.
   */
  void setNumber(Long number);

  /**
   * @return the current {@link io.oasp.gastronomy.restaurant.tablemanagement.common.api.datatype.TableState state} of this {@link io.oasp.gastronomy.restaurant.tablemanagement.common.api.Table}.
   */
  TableState getState();

  /**
   * @param state is the new {@link #getState() state}.
   */
  void setState(TableState state);

  /**
   * @return the {@link io.oasp.gastronomy.restaurant.staffmanagement.common.api.StaffMember#getId() ID} of the waiter
   *         currently responsible for this table.
   */
  Long getWaiterId();

  /**
   * Sets the field 'waiterId'.
   *
   * @param waiterId New value for waiterId
   */
  void setWaiterId(Long waiterId);

}