http://stackoverflow.com/questions/2998784/
355028
function numberPad(num, size) {
  var s = "000000000" + num;
  return s.substr(s.length-size);
}
457922
function(url, base) {
			if (!url || url.indexOf('://') !== -1) { return url; }

			var anchor = document.createElement('a');
			anchor.href = (base || location.href);

			var protocol	= anchor.protocol + '//',
				host		= anchor.host,
				path		= anchor.pathname,
				parts		= filter(path.split('/'), function(part) { return part !== ''; });

			each(url.replace(/\?.*/, '').split('/'), function(part, index) {
				switch(part) {
					case '..':
						if (!parts.length) {
							throw new Error('Path outside of root: ' + url);
						}
						parts.length--;
						break;
					case '.':	break;
					default:	parts.push(part); break
				}
			});
			return protocol + host + '/' + parts.join('/');
		}
1277221
public function moveLeft() //#777C
    {
        $sArticleId = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('aid');
        if ($sArticleId && ($aItems = $this->getCompareItems())) {
            $sPrevArticleId = null;

            $blFound = false;
            foreach ($aItems as $sOxid => $sVal) {
                if ($sOxid == $sArticleId) {
                    $blFound = true;
                }
                if (!$blFound) {
                    $sPrevArticleId = $sOxid;
                }
            }

            if ($sPrevArticleId) {
                $aNewItems = [];
                foreach ($aItems as $sOxid => $sVal) {
                    if ($sOxid == $sPrevArticleId) {
                        $aNewItems[$sArticleId] = true;
                    } elseif ($sOxid == $sArticleId) {
                        $aNewItems[$sPrevArticleId] = true;
                    } else {
                        $aNewItems[$sOxid] = true;
                    }
                }

                $this->setCompareItems($aNewItems);
            }
        }
    }
892114
public function init()
    {
        $grav = Grav::instance();

        /** @var Config $config */
        $config = $grav['config'];

        /** @var Language $language */
        $language = $grav['language'];

        // add the port to the base for non-standard ports
        if ($this->port !== null && $config->get('system.reverse_proxy_setup') === false) {
            $this->base .= ':' . (string)$this->port;
        }

        // Handle custom base
        $custom_base = rtrim($grav['config']->get('system.custom_base_url'), '/');

        if ($custom_base) {
            $custom_parts = parse_url($custom_base);
            $orig_root_path = $this->root_path;
            $this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : '';
            if (isset($custom_parts['scheme'])) {
                $this->base = $custom_parts['scheme'] . '://' . $custom_parts['host'];
                $this->root = $custom_base;
            } else {
                $this->root = $this->base . $this->root_path;
            }
            $this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri);
        } else {
            $this->root = $this->base . $this->root_path;
        }

        $this->url = $this->base . $this->uri;

        $uri = str_replace(static::filterPath($this->root), '', $this->url);

        // remove the setup.php based base if set:
        $setup_base = $grav['pages']->base();
        if ($setup_base) {
            $uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri);
        }

        // process params
        $uri = $this->processParams($uri, $config->get('system.param_sep'));

        // set active language
        $uri = $language->setActiveFromUri($uri);

        // split the URL and params
        $bits = parse_url($uri);

        //process fragment
        if (isset($bits['fragment'])) {
            $this->fragment = $bits['fragment'];
        }

        // Get the path. If there's no path, make sure pathinfo() still returns dirname variable
        $path = $bits['path'] ?? '/';

        // remove the extension if there is one set
        $parts = pathinfo($path);

        // set the original basename
        $this->basename = $parts['basename'];

        // set the extension
        if (isset($parts['extension'])) {
            $this->extension = $parts['extension'];
        }

        // Strip the file extension for valid page types
        if ($this->isValidExtension($this->extension)) {
            $path = Utils::replaceLastOccurrence(".{$this->extension}", '', $path);
        }

        // set the new url
        $this->url = $this->root . $path;
        $this->path = static::cleanPath($path);
        $this->content_path = trim(str_replace($this->base, '', $this->path), '/');
        if ($this->content_path !== '') {
            $this->paths = explode('/', $this->content_path);
        }

        // Set some Grav stuff
        $grav['base_url_absolute'] = $config->get('system.custom_base_url') ?: $this->rootUrl(true);
        $grav['base_url_relative'] = $this->rootUrl(false);
        $grav['base_url'] = $config->get('system.absolute_urls') ? $grav['base_url_absolute'] : $grav['base_url_relative'];

        RouteFactory::setRoot($this->root_path);
        RouteFactory::setLanguage($language->getLanguageURLPrefix());
    }
1313653
public function hPrintFooter() {
	    $wt_tree = Globals::getTree();
	    $html = '';
	    if($this->getSetting('MAJ_DISPLAY_CNIL', 0) == 1){
	        $html .= '<br/>';
	        $html .= '<div class="center">';
	        $cnil_ref = $this->getSetting('MAJ_CNIL_REFERENCE', '');
	        if($cnil_ref != ''){
	            $html .= I18N::translate('This site has been notified to the French National Commission for Data protection (CNIL) and registered under number %s. ', $cnil_ref);
	        }
	        $html .= I18N::translate('In accordance with the French Data protection Act (<em>Loi Informatique et Libertés</em>) of January 6th, 1978, you have the right to access, modify, rectify and delete personal information that pertains to you. To exercice this right, please contact %s, and provide your name, address and a proof of your identity.',
	            Theme::theme()->contactLink(User::find($wt_tree->getPreference('WEBMASTER_USER_ID'))));
	        $html .= '</div>';
	    }
	    
	    if($this->getSetting('MAJ_ADD_HTML_FOOTER', 0) == 1){
	        if(Auth::accessLevel($wt_tree) >= $this->getSetting('MAJ_SHOW_HTML_FOOTER', Auth::PRIV_HIDE)  && !Filter::getBool('nofooter')){
	            $html .= $this->getSetting('MAJ_HTML_FOOTER', '');
	        }
	    }
	    return $html;
	}
499507
function Censoring() {

    /**
     * The string to replaces found matches with. Defaults to ***
     *
     * @type {String}
     */
    this.replacementString = '***';

    /**
     * The color used for highlighting
     *
     * @type {string}
     */
    this.highlightColor = 'F2B8B8';

    /**
     * Holds the currently matched text.
     *
     * @type {{replace: string, hasMatches: boolean}}
     */
    this.currentMatch = {
      replace: '',
      hasMatches: false,
      matches: []
    };

    /**
     * The available patterns. These are as follows:
     *  [name]              [description]
     *  - long_number       ; Matches long, consecutive numbers
     *  - phone_number      ; Matches phone numbers.
     *  - email_address     ; Matches email addresses in many formats.
     *  - url               ; Matches URL patterns/
     *  - words             ; Finds words, even when in disguise.
     *
     * @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}}
     */
    this.patterns = {
      long_number: {
        pattern: /\d{8,}/,
        enabled: false
      },
      phone_number: {
        pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi,
        enabled: false
      },
      email_address: {
        pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi,
        enabled: false
      },
      url: {
        pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi,
        enabled: false
      },
      words: {
        pattern: [],
        enabled: false
      }
    };

    /**
     * A mapping that maps regular characters to 1337 characters.
     *
     * @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}}
     */
    this.map1337 = {
      o: '0',
      g: '9',
      b: ['8', '6'],
      t: '7',
      s: '5',
      a: '4',
      e: '3',
      z: '2',
      i: '1',
      l: '1'
    };
  }
349390
public function info() {
        /**
         * avatar	用户头像	String	如果没有数据的时候不会返回该数据，请做好容错	可空	https://tfsimg.alipay.com/images/partner/T1k0xiXXRnXXXXXXXX
        nick_name	用户昵称	String	如果没有数据的时候不会返回该数据，请做好容错	可空	张三
        province	省份	String	用户注册时填写的省份 如果没有数据的时候不会返回该数据，请做好容错	可空	浙江省
        city	城市	String	用户注册时填写的城市， 如果没有数据的时候不会返回该数据，请做好容错	可空	杭州
        gender	用户性别	String	M为男性，F为女性， 如果没有数据的时候不会返回该数据，请做好容错	可空	M
        user_type_value	用户类型	String	（1/2），1代表公司账户；2代表个人账户	不可空	1
        is_licence_auth	是否经过营业执照认证	String	T为通过营业执照认证，F为没有通过	不可空	T
        is_certified	是否通过实名认证	String	T是通过；F是没有实名认证	不可空	F
        is_certify_grade_a	是否A类认证	String	T表示是A类认证，F表示非A类认证，A类认证用户是指上传过身份证照片并且通过审核的支付宝用户	不可空	T
        is_student_certified	是否是学生	String	T表示是学生，F表示不是学生	不可空	T
        is_bank_auth	是否经过银行卡认证	String	T为经过银行卡认证，F为未经过银行卡认证	不可空	T
        is_mobile_auth	是否经过手机认证	String	T为经过手机认证，F为未经过手机认证	不可空	T
        alipay_user_id	当前用户的userId	String	支付宝用户的userId	不可空	2088411964574197
        user_id	已废弃，请勿使用	String	已废弃，请勿使用	不可空	已废弃，请勿使用
        user_status	用户状态（Q/T/B/W）	String	Q代表快速注册用户；T代表已认证用户；B代表被冻结账户；W代表已注册，未激活的账户	不可空	T
        is_id_auth	是否身份证认证	String	T为是身份证认证，F为非身份证认证	不可空	T
         */
        $user = (new OAuth())->info($this->get('access_token'));
        if (!is_array($user) || $user['code'] != 10000) {
            return false;
        }
        $user['username'] = $user['nick_name'];
        $user['sex'] = $user['gender'];
        $this->set($user);
        return $user;
    }
766136
public function _uri() {
        //处理requestUri
        $requestUri = '/';

        if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
            $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];
        }
        elseif (
            // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
            isset($_SERVER['IIS_WasUrlRewritten'])
            && $_SERVER['IIS_WasUrlRewritten'] == '1'
            && isset($_SERVER['UNENCODED_URL'])
            && $_SERVER['UNENCODED_URL'] != ''
        ) {
            $requestUri = $_SERVER['UNENCODED_URL'];
        }
        elseif (isset($_SERVER['REQUEST_URI'])) {
            $requestUri = $_SERVER['REQUEST_URI'];
            $parts = @parse_url($requestUri);

            if (isset($_SERVER['HTTP_HOST']) && strstr($requestUri, $_SERVER['HTTP_HOST'])) {
                if (false !== $parts) {
                    $requestUri = (empty($parts['path']) ? '' : $parts['path'])
                        . ((empty($parts['query'])) ? '' : '?' . $parts['query']);
                }
            }
            elseif (!empty($_SERVER['QUERY_STRING']) && empty($parts['query'])) {
                // fix query missing
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
            }
        }
        elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
            if (!empty($_SERVER['QUERY_STRING'])) {
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
            }
        }

        return $requestUri;
    }
1373441
public function detect_links()
	{
		$this->loop_text_nodes(function($child) {
			preg_match_all("/(?:(?:https?|ftp):\/\/|(?:www|ftp)\.)(?:[a-zA-Z0-9\-\.]{1,255}\.[a-zA-Z]{1,20})(?::[0-9]{1,5})?(?:\/[^\s'\"]*)?(?:(?<![,\)\.])|[\S])/",
				$child->get_text(),
				$matches,
				PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);

			if(count($matches[0]) == 0)
				return;

			$replacment = array();
			$last_pos   = 0;

			foreach($matches[0] as $match)
			{
				if(substr($match[0], 0, 3) === 'ftp' && $match[0][3] !== ':')
					$url = 'ftp://' . $match[0];
				else if($match[0][0] === 'w')
					$url = 'http://' . $match[0];
				else
					$url = $match[0];

				$url      = new Node_Container_Tag('url', array('default' => htmlentities($url, ENT_QUOTES | ENT_IGNORE, "UTF-8")));
				$url_text = new Node_Text($match[0]);
				$url->add_child($url_text);

				$replacment[] = new Node_Text(substr($child->get_text(), $last_pos, $match[1] - $last_pos));
				$replacment[] = $url;
				$last_pos = $match[1] + strlen($match[0]);
			}

			$replacment[] = new Node_Text(substr($child->get_text(), $last_pos));
			$child->parent()->replace_child($child, $replacment);
		}, $this->get_excluded_tags(BBCode::AUTO_DETECT_EXCLUDE_URL));

		return $this;
	}
794480
function LinkImageSort($_by,$sby,$soby,$soby2,$stitle) {
   if($_by==$sby)
    return <<<EOF
  <a href="{$_SERVER['PHP_SELF']}?sort={$soby}&amp;by={$sby}" class="formfont" onmouseover="if(document.getElementById('so{$sby}')){ document.getElementById('so{$sby}').src='./swat4query/images/server_{$soby}.gif'; }" onmouseout="if(document.getElementById('so{$sby}')){ document.getElementById('so{$sby}').src='./swat4query/images/server_{$soby2}.gif'; }"><b>{$stitle}</b> <img src="./swat4query/images/server_{$soby2}.gif" width="11" height="9" border="0" alt="{$soby}" id="so{$sby}" />
EOF;
   else return '<a href="'.$_SERVER['PHP_SELF'].'?sort='.$soby.'&amp;by='.$sby.'" class="formfont"><b>'.$stitle.'</b>';
  }
478999
static function viewCatalogUrl() {

		if ( isset( $_REQUEST['user_id'] ) ) {

			if ( false === current_user_can( 'edit_user', (int) $_REQUEST['user_id'] ) ) {
				wp_die( __( 'You do not have permission to do that.' ) );
			}

			$u = get_userdata( (int) $_REQUEST['user_id'] );
			if ( false === $u ) {
				wp_die( __( 'The requested user does not exist.' ) );
			}

			$user_login = get_userdata( (int) $_REQUEST['user_id'] )->user_login;
		} else {
			$user_login = get_userdata( get_current_user_id() )->user_login;
		}

		$view_url = network_home_url( "/catalog/$user_login" );

		return $view_url;
	}
553029
public function show()
    {
        if ($mime = $this->getMime()) {
            $mime = is_array($mime) ? $mime[ 0 ] : $mime;
        } elseif (is_file($this->getRealPath())) {
            $mime = 'application/octet-stream';
        }

        $fileSize = filesize($this->getRealPath());
        $filename = pathinfo($this->getRealPath(), PATHINFO_BASENAME);

        // Common headers
        $expires = 604800; // (60*60*24*7)
        header('Expires:' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');

        header('Accept-Ranges: bytes', true);
        header("Cache-control: private", true);
        header('Pragma: private', true);

        header('Content-Type: ' . $mime);
        header('Content-Disposition: inline; filename="' . $filename . '"');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');

        $ETag = '"' . md5($filename) . '"';

        if ( ! empty($_SERVER[ 'HTTP_IF_NONE_MATCH' ])
            && $_SERVER[ 'HTTP_IF_NONE_MATCH' ] == $ETag
        ) {
            header('HTTP/1.1 304 Not Modified');
            header('Content-Length: ' . $fileSize);
            exit;
        }

        $expires = 604800; // (60*60*24*7)
        header('ETag: ' . $ETag);
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
        header('Expires:' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');

        // Open file
        // @readfile($file_path);
        $file = @fopen($filename, "rb");
        if ($file) {
            while ( ! feof($file)) {
                print(fread($file, 1024 * 8));
                flush();
                if (connection_status() != 0) {
                    @fclose($file);
                    die();
                }
            }
            @fclose($file);
        }
    }
393475
function(){
		// this.bodyが空の場合はEncode.jsの仕様により対象外
		// カンペンには以下のパズルは存在しないのでURL_KANPENPも対象外
		if(!this.body || (this.type!==URL_PZPRV3 && this.type!==URL_PZPRAPP)){ return;}
		
		switch(this.pid){
		case 'ichimaga':
			if     (this.pflag.indexOf('m')>=0){ this.pid = 'ichimagam';}
			else if(this.pflag.indexOf('x')>=0){ this.pid = 'ichimagax';}
			else                               { this.pid = 'ichimaga'; }
			break;
		case 'icelom':
			if(this.pflag.indexOf('a')<0){ this.pid = 'icelom2';}
			break;
		case 'pipelink':
			if(this.body.match(/[0-9]/)){ this.pid = 'pipelinkr';}
			break;
		case 'bonsan':
			if(this.pflag.indexOf('c')<0){
				var col = this.cols, row = this.rows;
				if(this.body.substr(0,((((col-1)*row+4)/5)|0)+(((col*(row-1)+4)/5)|0)||0).match(/[^0]/)){
					this.pid = 'heyabon';
				}
			}
			break;
		case 'kramma':
			if(this.pflag.indexOf('c')<0){
				var len=(this.cols-1)*(this.rows-1), cc=0;
				for(var i=0;i<this.body.length;i++){
					var ca = this.body.charAt(i);
					if(ca.match(/\w/)){
						cc += parseInt(ca,36);
						if(cc<len){ this.pid = 'kramman'; break;}
					}
					else if(ca === '.'){ cc+=36;}
					if(cc>=len){ break;}
				}
			}
			break;
		}
	}
579096
function() {
      var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
      if (this.isNew()) return base;
      return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
    }
561586
def _convert(reddit_session, data):
        """"""
        retval = Redditor(reddit_session, data['name'], fetch=False)
        retval.id = data['id'].split('_')[1]  # pylint: disable=C0103,W0201
        return retval
88292
public function moveRight() //#777C
    {
        $sArticleId = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('aid');
        if ($sArticleId && ($aItems = $this->getCompareItems())) {
            $sNextArticleId = 0;

            $blFound = false;
            foreach ($aItems as $sOxid => $sVal) {
                if ($blFound) {
                    $sNextArticleId = $sOxid;
                    $blFound = false;
                }
                if ($sOxid == $sArticleId) {
                    $blFound = true;
                }
            }

            if ($sNextArticleId) {
                $aNewItems = [];
                foreach ($aItems as $sOxid => $sVal) {
                    if ($sOxid == $sArticleId) {
                        $aNewItems[$sNextArticleId] = true;
                    } elseif ($sOxid == $sNextArticleId) {
                        $aNewItems[$sArticleId] = true;
                    } else {
                        $aNewItems[$sOxid] = true;
                    }
                }
                $this->setCompareItems($aNewItems);
            }
        }
    }
1119450
function () {

/*Line 57 - 'AtomDispatcher.js' */                //if (window.console) {
/*Line 58 - 'AtomDispatcher.js' */                //    window.console.log("Starting Web Atoms");
/*Line 59 - 'AtomDispatcher.js' */                //}

/*Line 61 - 'AtomDispatcher.js' */                var a = $('[data-atom-type],[atom-type]').first()[0];
/*Line 62 - 'AtomDispatcher.js' */                if (a.atomControl != undefined && a.atomControl != null)
/*Line 63 - 'AtomDispatcher.js' */                    return;
/*Line 64 - 'AtomDispatcher.js' */                var ct = AtomUI.getAtomType(a);
/*Line 65 - 'AtomDispatcher.js' */                $(a).removeAttr("atom-type");
/*Line 66 - 'AtomDispatcher.js' */                $(a).removeAttr("data-atom-type");
/*Line 67 - 'AtomDispatcher.js' */                var ctrl = new (WebAtoms[ct])(a);
/*Line 68 - 'AtomDispatcher.js' */                ctrl.setup();

/*Line 70 - 'AtomDispatcher.js' */            }