text:
/**
 ***********************************************************************************************************************
 * @file  palHashSet.h
 * @brief PAL utility collection HashSet class declaration.
 ***********************************************************************************************************************
 */

#pragma once

#include "palHashBase.h"

namespace Util
{

/// Encapsulates one entry of a hash set.
template<typename Key>
struct HashSetEntry
{
    Key key;  ///< Hash set entry key.
};

/**
 ***********************************************************************************************************************
 * @brief Templated hash set container.
 *
 * This is meant for storing elements of an arbitrary (but uniform) key type. Supported operations:
 *
 * - Searching
 * - Insertion
 * - Deletion
 * - Iteration
 *
 * HashFunc is a functor for hashing keys.  Built-in choices for HashFunc are:
 *
 * - DefaultHashFunc: Good choice when the key is a pointer.
 * - JenkinsHashFunc: Good choice when the key is arbitrary binary data.
 * - StringJenkinsHashFunc: Good choice when the key is a C-style string.
 *
 * EqualFunc is a functor for comparing keys.  Built-in choices for EqualFunc are:
 *
 * - DefaultEqualFunc: Determines keys are equal by bitwise comparison.
 * - StringEqualFunc: Treats keys as a char* and compares them as C-style strings.
 *
 * @warning This class is not thread-safe for Insert, Erase, or iteration!
 * @warning Init() must be called before using this container. Begin() and Reset() can be safely called before
 *          initialization and Begin() will always return an iterator that points to null.
 *
 * For more details please refer to @ref HashBase.
 ***********************************************************************************************************************
 */
template<typename Key,
         typename Allocator,
         template<typename> class HashFunc = DefaultHashFunc,
         template<typename> class EqualFunc = DefaultEqualFunc,
         typename AllocFunc = HashAllocator<Allocator>,
         size_t GroupSize = PAL_CACHE_LINE_BYTES * 2>
class HashSet : public HashBase<Key,
                                HashSetEntry<Key>,
                                Allocator,
                                HashFunc<Key>,
                                EqualFunc<Key>,
                                AllocFunc,
                                GroupSize>
{
public:
    /// Convenience typedef for a templated entry of this hash set.
    typedef HashSetEntry<Key> Entry;

    /// @internal Constructor
    ///
    /// @param [in] numBuckets Number of buckets to allocate for this hash container.  The initial hash container will
    ///                        take (buckets * PAL_CACHELINE_BYTES) bytes.
    /// @param [in] pAllocator Pointer to an allocator that will create system memory requested by this hash container.
    explicit HashSet(uint32 numBuckets, Allocator*const pAllocator) : Base::HashBase(numBuckets, pAllocator) {}
    virtual ~HashSet() { }

    /// Returns true if the specified key exists in the set.
    ///
    /// @param [in] key Key to search for.
    ///
    /// @returns True if the specified key exists in the set.
    bool Contains(const Key& key) const;

    /// Inserts an entry.
    ///
    /// No action will be taken if an entry matching this key already exists in the set.
    ///
    /// @param [in] key New entry to insert.
    ///
    /// @returns @ref Success if the operation completed successfully, or @ref ErrorOutOfMemory if the operation failed
    ///          because an internal memory allocation failed.
    Result Insert(const Key& key);

    /// Removes an entry that matches the specified key.
    ///
    /// @param [in] key Key of the entry to erase.
    ///
    /// @returns True if the erase completed successfully, false if an entry for this key did not exist.
    bool Erase(const Key& key);

private:
    // Typedef for the specialized 'HashBase' object we're inheriting from so we can use properly qualified names when
    // accessing members of HashBase.
    typedef HashBase<Key, HashSetEntry<Key>, Allocator, HashFunc<Key>, EqualFunc<Key>, AllocFunc, GroupSize> Base;

    PAL_DISALLOW_DEFAULT_CTOR(HashSet);
    PAL_DISALLOW_COPY_AND_ASSIGN(HashSet);
};

} // Util


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace Microsoft.VisualStudio.R.Package.DataInspect {
    /// <summary>
    /// Text that appears in grid header. Tracks sorting order
    /// and displays the appropriate sort order glyph.
    /// </summary>
    public sealed class HeaderTextVisual : TextVisual {
        private const char ArrowUp = (char)0x25B4;
        private const char ArrowDown = (char)0x25BE;
        private const char Nbsp = (char)0x00A0;
        private char _arrowChar = Nbsp;

        #region Dependency Properties
        public static readonly DependencyProperty SortOrderProperty =
            DependencyProperty.Register("SortOrder", typeof(SortOrderType), typeof(TextVisual), new PropertyMetadata(SortOrderType.None));

        public SortOrderType SortOrder {
            get { return (SortOrderType)GetValue(SortOrderProperty); }
            set {
                SetValue(SortOrderProperty, value);
                SetArrowDisplay();
            }
        }
        #endregion

        public HeaderTextVisual(long columnIndex) {
            ColumnIndex = columnIndex;
        }

        public long ColumnIndex { get; }

        /// <summary>
        /// Name of the column
        /// </summary>
        public string Name => base.Text;

        public override string Text {
            get { return base.Text + _arrowChar; }
            set { base.Text = value; }
        }
        /// <summary>
        /// Calculates column header render size taking into account
        /// optional sorting arrow, if any.
        /// </summary>
        protected override Size GetRenderSize(FormattedText formattedText, out double offset) {
            var baseSize = base.GetRenderSize(formattedText, out offset);

            var currentArrowGlyph = new FormattedText(_arrowChar.ToString(), CultureInfo.CurrentUICulture,
                                               FlowDirection.LeftToRight, Typeface, FontSize, Foreground);
            var largestArrowGlyph = new FormattedText(ArrowUp.ToString(), CultureInfo.CurrentUICulture,
                                               FlowDirection.LeftToRight, Typeface, FontSize, Foreground);

            offset = largestArrowGlyph.Width;
            return new Size(baseSize.Width - currentArrowGlyph.Width + 2* largestArrowGlyph.Width, baseSize.Height);
        }

        private void SetArrowDisplay() {
            switch (SortOrder) {
                case SortOrderType.None:
                    _arrowChar = Nbsp;
                    break;

                case SortOrderType.Ascending:
                    _arrowChar = ArrowUp;
                    break;

                case SortOrderType.Descending:
                    _arrowChar = ArrowDown;
                    break;
            }
            Invalidate();
        }

        private static bool HasArrow(string text) {
            return text.Length > 0 && (text[text.Length - 1] == ArrowUp || text[text.Length - 1] == ArrowDown);
        }

        public void ToggleSortOrder() {
            switch (SortOrder) {
                case SortOrderType.None:
                    SortOrder = SortOrderType.Ascending;
                    break;
                case SortOrderType.Ascending:
                    SortOrder = SortOrderType.Descending;
                    break;
                case SortOrderType.Descending:
                    SortOrder = SortOrderType.Ascending;
                    break;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'miniparser'
require 'pry'


text:
//
// Copyright © 2012-2018 Guy M. Allard
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.jms.Session;

/**
 * Sends messages on the queue.
 */
public class Sender
{

  public static void main(String[] args) throws Exception
  {
 		System.out.println("Sends messages on the queue...");
    new Sender().go();
  } // end of main

  private void go() throws NamingException, JMSException
  {
    Context ictx = new InitialContext();
    QueueConnectionFactory qcf = (QueueConnectionFactory) ictx.lookup("ConnectionFactory");
    Queue queue = (Queue) ictx.lookup("queue/exampleQueue");
    ictx.close();

    QueueConnection qconn = qcf.createQueueConnection();
    QueueSession qsess = qconn.createQueueSession(true, 0);

    QueueSender qsend = qsess.createSender(queue);
    TextMessage msg = qsess.createTextMessage();

    int i;
    for (i = 0; i < Constants.NUM_MESSAGES; i++) {
    	if (Constants.DO_WORK_WAIT)
    	{
      	try
		    {
        		Thread.sleep(Constants.WORK_WAIT_MS); // Simulate message build
		    }
        	catch(InterruptedException ie)
		    {
        		// Ignore
		    }
    	}
    	String s = "Java Sender Test Number " + i;
    	msg.setText(s);
    	qsend.send(msg);
   		System.out.println("Sent: " + s);
    	qsess.commit();	//
    }
   	System.out.println(i + " messages sent.");
    qconn.close();

  } // end of go
} // end of class Sender


text:
package com.thetestpeople.trt.utils.http

import java.io.File
import java.net.URI
import java.net.URL

import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.FileUtils

object PathCachingHttp {

  def relativePath(urlString: String): String = {
    val url = new URL(urlString)
    val host = url.getHost
    val path = url.getPath
    val chunks = host +: path.split("/").toSeq :+ DigestUtils.md5Hex(urlString)
    chunks.mkString("/")
  }

}

/**
 * Useful for testing offline -- caches URLs on the filesystem
 */
class PathCachingHttp(delegate: Http) extends Http {

  private val cacheRoot = new File("./webcache")
  cacheRoot.mkdirs()

  private def cacheFile(urlString: String): File =
    new File(cacheRoot, PathCachingHttp.relativePath(urlString))

  def get(url: URI, basicAuthOpt: Option[Credentials] = None): HttpResponse = {
    val file = cacheFile(url.toString)
    if (!file.exists)
      FileUtils.write(file, delegate.get(url).body)
    HttpResponse(200, "OK", FileUtils.readFileToString(file))
  }

  def post(url: URI, basicAuthOpt: Option[Credentials] = None, bodyParams: Map[String, Seq[String]]): HttpResponse =
    throw new HttpException

}


text:
GravityGolf
======================

GravityGolf is a 2-d game that simulates the movement of objects in space, where they are affected by the gravitational pull of other planets.

The goal of the game is to launch the ball (typically a small red ball) to a Goal (usually white).

The basic premise of the game is relatively simple; the above mechanics are implemented is less than 100 lines of code.
However, the addition of many small features into one project has made management and design significant challenges.

Running from a jar in the Releases Section
-----------------------------------------------

Download and extract the folder. Change into the folder and run:

		java -jar GravityGolf.jar

Building and Running in Eclipse
-------------------------------------

I wrote the project using Eclipse. When the Scala portions were added
the Scala IDE for Eclipse plugin (http://scala-ide.org/index.html) was used.

To import into Eclipse after a git clone:

* Create a new project named GravityGolf
* Import the resources in the cloned folder to the project you created
* Right click the project, select configure, add Scala nature
* You may also need to add JUnit 4, help on errors on JUnit statements/imports
  will let you add it to the build path easily

Building and Running with SBT
---------------------------------------
This is a work in progress. Currently working:

The game can be launched using:

		sbt run

Testing and packaging using sbt are not yet implemented.


text:
#pragma checksum "..\..\..\..\Modules\View\DesktopLyric.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "02C9A77FCA76BF8938BE6D2168970C0A"
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.42000
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

using GalaSoft.MvvmLight.Command;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using ZN.iKuPlayer.WPF.Modules.ComManage;
using ZN.iKuPlayer.WPF.Modules.View;

namespace ZN.iKuPlayer.WPF.Modules.View {

    /// <summary>
    /// DesktopLyric
    /// </summary>
    public partial class DesktopLyric : System.Windows.Window, System.Windows.Markup.IComponentConnector {

        #line 48 "..\..\..\..\Modules\View\DesktopLyric.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ProgressBar LrcTop;

        #line default
        #line hidden

        #line 50 "..\..\..\..\Modules\View\DesktopLyric.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ProgressBar LrcBottom;

        #line default
        #line hidden

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/ZN.iKuPlayer.WPF;component/modules/view/desktoplyric.xaml", System.UriKind.Relative);

            #line 1 "..\..\..\..\Modules\View\DesktopLyric.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:

            #line 15 "..\..\..\..\Modules\View\DesktopLyric.xaml"
            ((ZN.iKuPlayer.WPF.Modules.View.DesktopLyric)(target)).MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(this.Window_MouseLeftButtonDown);

            #line default
            #line hidden
            return;
            case 2:
            this.LrcTop = ((System.Windows.Controls.ProgressBar)(target));
            return;
            case 3:
            this.LrcBottom = ((System.Windows.Controls.ProgressBar)(target));
            return;
            }
            this._contentLoaded = true;
        }
    }
}


text:
#ifndef BERRYIINTROREGISTRY_H_
#define BERRYIINTROREGISTRY_H_

#include "berryIIntroDescriptor.h"

#include <vector>

namespace berry {

/**
 * Registry for introduction elements.
 *
 * @since 3.0
 */
struct BERRY_UI_QT IIntroRegistry {

    virtual ~IIntroRegistry();
    /**
     * Return the number of introduction extensions known by this registry.
     *
     * @return the number of introduction extensions known by this registry
     */
    virtual int GetIntroCount() const = 0;

    /**
     * Return the introduction extensions known by this registry.
     *
     * @return the introduction extensions known by this registry
     */
    virtual QList<IIntroDescriptor::Pointer> GetIntros() const = 0;

    /**
     * Return the introduction extension that is bound to the given product.
     *
     * @param productId the product identifier
     * @return the introduction extension that is bound to the given product,
     * or null if there is no such binding
     */
    virtual IIntroDescriptor::Pointer GetIntroForProduct(const QString& productId) const = 0;

    /**
     * Find an intro descriptor with the given identifier.
     *
     * @param id the id
     * @return the intro descriptor, or null
     */
    virtual IIntroDescriptor::Pointer GetIntro(const QString& id) const = 0;
};

}

#endif /* BERRYIINTROREGISTRY_H_ */


text:
@extends('admin.layouts.master')
@section('title', 'Smart Panel')

@section('css')
    <link href="/cms/css/icons/fontawesome/styles.min.css" rel="stylesheet" type="text/css">
    <link href="/cms/css/datatables_buttons.css" rel="stylesheet" type="text/css">
    @endsection

    @section('page-header')

 Slide Yönetimi /
                    Slide Listesi

                    Yeni Slide Ekle

 Anasayfa

Slide Yönetimi

Slide Listesi

                        Filtrele

 'list']) }}"> Sıralamaya Göre

 'desc']) }}"> ID'ye göre

 'active']) }}"> Aktifler

 'passive']) }}"> Pasifler

 'all']) }}"> Tümü

@endsection

@section('content')

    @if(Session::has('sort') && Session::get('sort') == 'list')

            <button type="button" class="close" data-dismiss="alert">×Close</button>
            Sürükle bırak seçeneği ile sıralamayı değiştirebilirsiniz.

        @endif

Slide Listesi

                The Responsive extension for DataTables can be applied to a DataTable in one of two ways; with
                a specific class name on the table, or using the DataTables initialisation options. This method
                shows the latter, with the responsive option being set to the boolean value true.
                The responsive option can be given as a boolean value, or as an object with configuration
                options.

            {{ Form::open(['id' => 'datatable-form']) }}

                    <input value="1" type="checkbox" id="select-all">
                    Id
                    Aktif
                    Önizleme
                    Başlık
                    Oluşturulma Tar.
                    Güncelleme Tar.
                    İşlem

                        <select class="select" name="action">
                            <optgroup label="Toplu işlemler ">
                                <option value="">İşlem türü seçiniz ?</option>
                                <option value="active">Seçili öğeleri aktif et</option>
                                <option value="passive">Seçili öğeleri pasif et</option>
                                <option value="destroy">Seçili öğeleri sil</option>
                            </optgroup>
                        </select>

                        <button class="btn bg-slate-600"></button>

            {{ Form::close() }}

        @endsection

        @section('js')

@endsection


text: Free Access laboratory


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Thieves Take Paintings

						Expand All | Collapse All

Thieves Take Paintings

  The thieves used a ladder, a flashlight, and a knife. And they were lucky. They broke into a famous museum. All they had to do was to break a window. They left half an hour later. They left with five paintings worth $200 million. The thieves cut the paintings out of their frames. "They knew what they were doing," said a museum spokesman. But how did they do it so easily? Where was security? Where was the alarm? Where was the camera? One security guard was stationed in that part of the museum. He was asleep during the robbery. He was fired. The security alarm was broken. The museum was waiting for a replacement part. The thieves wore ski masks. The police are studying the videotape for clues to identify the two thieves. The broken window had no steel bars because it was on a busy street, said the spokesman.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
  {% if include.items %}
    {% for item in include.items %}

{% include schedule_item.html item=item %}

    {% endfor %}
  {% else %}

{% include schedule_item.html item=include.default %}

  {% endif %}


text:
export function outputHeroImg() {

  /**
   * Define method to randomize hero images:
   */
  const randomizeImage = function() {
    return Math.floor(Math.random()*69) + 1;
  };
  let randomImg = randomizeImage();
  /**
   * Set random image on page:
   */
  let imagePath = "./images/barrels/img-";
  if (window.innerWidth > 767) imagePath = "./images/barrels-ipad/img-";
  $('.hero').css('background-image', 'url(' + imagePath + randomImg + '.jpg)');
}


text: docker exec -it -w /application anycontent-client-php56 /bin/bash


text:
<!DOCTYPE HTML>

<title>Uses of Interface javax.money.MonetaryQuery (JSR 354 (Money and Currency API) 1.1.1-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2020-07-22">
<meta name="description" content="use: module: java.money, package: javax.money, interface: MonetaryQuery">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Interface
javax.money.MonetaryQuery

Packages that use MonetaryQuery

Package
Description

javax.money

Main package of the Money and Currency API.

javax.money.format

Money and Currency format API.

Uses of MonetaryQuery in javax.money

Methods in javax.money with parameters of type MonetaryQuery

Modifier and Type
Method
Description

default <R> R
MonetaryAmount.query(MonetaryQuery<R> query)

Queries this monetary amount for a value.

Uses of MonetaryQuery in javax.money.format

Subinterfaces of MonetaryQuery in javax.money.format

Modifier and Type
Interface
Description

interface
MonetaryAmountFormat

 Formats instances of MonetaryAmount to a String or an Appendable.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

Copyright © 2012–2020 JSR 354 - Expert Group. All rights reserved.


text:
#include "mapDeploymentDLLHelper.h"
#include "mapDiscreteElements.h"
#include "mapITKFastSymmetricForcesDemonsMultiResRegistrationAlgorithm.h"
#include "mapConfigure.h"

#include "MITK_FastSymmetricForcesDemons_MultiRes_default_ProfileResource.h"
typedef map::core::discrete::Elements<3>::InternalImageType ImageType;
typedef map::algorithm::boxed::ITKFastSymmetricForcesDemonsMultiResRegistrationAlgorithm<ImageType, map::algorithm::MITK_FastSymmetricForcesDemons_MultiRes_defaultUIDPolicy>
AlgorithmType;

mapDeployAlgorithmMacro(AlgorithmType);


text:
layout: page
title: "JavaScript assert function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/assert:831
- /functions/view/assert
- /functions/view/831
- /functions/assert:831
- /functions/831
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's assert

{% codeblock info/assert.js lang:js https://raw.github.com/kvz/phpjs/master/functions/info/assert.js raw on github %}
function assert (assertion) {
  // From: http://phpjs.org/functions
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // %          note 1: Do not pass untrusted user input to assert() in string form (you can test it beforehand though)
  // %          note 2: Does not provide perfect arguments to the assertion callback, as far as file location or line number
  // *     example 1: assert('false === true');
  // *     returns 1: false

  var result = false,
    callback, retVal, err = undefined;

  // BEGIN REDUNDANT
  this.php_js = this.php_js || {};
  this.php_js.ini = this.php_js.ini || {};
  this.php_js.assert_values = this.php_js.assert_values || {};
  // END REDUNDANT

  var getOption = function (value) {
    if (this.php_js.assert_values[value]) {
      return this.php_js.assert_values[value];
    }
    if (this.php_js.ini[value]) {
      return this.php_js.ini[value].local_value;
    }
    switch (value) {
    case 'assert.active':
      return 1;
    case 'assert.warning':
      // Don't need this now
      //return 1;
      throw 'We have not yet implemented warnings in JavaScript (assert())';
    case 'assert.bail':
      return 0;
    case 'assert.quiet_eval':
      return 0;
    case 'assert.callback':
      return null;
    default:
      throw 'There was some problem';
    }
  };

  if (!getOption('assert.active')) {
    return false; // is this correct? should callbacks still execute? Should still bail if on?
  }

  try { // Less overhead to use string when assertion checking is off, allows message of exact code to callback
    result = typeof assertion === 'string' ? eval(assertion) : assertion;
  } catch (e) {
    if (!getOption('assert.quiet_eval')) {
      throw e;
    }
    err = e;
    result = false;
  }
  retVal = result !== false; // return false if false, otherwise, return true
  if (retVal === false) {
    if (getOption('assert.bail')) { // Todo: Will the function bail before a callback or after?
      throw 'Assertion bailed'; // No way to bail without throwing an exception (and there are no "warnings" in JavaScript for us to throw)
    }
    callback = getOption('assert.callback');
    if (typeof callback === 'string') {
      callback = this.window[callback];
    }
    // Not perfect for file location (might also use __FILE__()) or line number
    callback(this.window.location.href, err && err.lineNumber, (typeof assertion === 'string' ? assertion : '')); // From the docs, what does this mean?: "the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)"
  }
  return retVal;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/info/assert.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.

Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/info/assert.js)

### Example 1
This code
{% codeblock lang:js example %}
assert('false === true');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
false
{% endcodeblock %}

### Other PHP functions in the info extension
{% render_partial _includes/custom/info.html %}


text:
import { Coordinate } from './coordinate';
import { Extent } from './extent';

export type Type = (p0: Coordinate | undefined) => Coordinate | undefined;
export function createExtent(extent: Extent): Type;
export function none(center?: Coordinate): Coordinate | undefined;


text:
package fileutils_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestApp(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Fileutils Suite")
}


text:
using System;
using System.Text;

//Describe the strings in C#.What is typical for the string data type?Describe the most important methods of the String class.

class StringInCSharp
{
    static void Main()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine(new string('-', 15));
        sb.AppendLine(@"A string is an object of type String whose value is text. Internally,
the text is stored as a sequential read-only collection of Char objects.
The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters.
To access the individual Unicode code points in a string, use the StringInfo object.");
        sb.AppendLine(new string('-',15));
        sb.AppendLine("Important C# string methods:");
        sb.AppendLine("string.Compare(): Compares String objects.Has different overloads.");
        sb.AppendLine("string.Equals(): Determines whether two specified String objects have the same value.");
        sb.AppendLine("string.IndexOf(): Finding a character or substring within given string.");
        sb.AppendLine("string.Substring(): Extract substring from the String object.");
        sb.AppendLine("string.Split(): Splits string object by given separator.");
        sb.AppendLine(new string('-', 15));

        Console.WriteLine(sb.ToString());
    }
}


text:
using Moq;
using NUnit.Framework;

namespace SEV.DI.Web.LightInject.Tests
{
    [TestFixture]
    public class DIContainerExtentionsTests
    {
        [Test]
        public void WhenCallRegisterWebConfigurator_ThenShouldCallRegisterOfDIContainerForIDIContainerWebConfigurator()
        {
            var containerMock = new Mock<IDIContainer>();
            IDIContainer container = containerMock.Object;

            container.RegisterWebConfigurator();

            containerMock.Verify(x => x.Register<IDIContainerWebConfigurator, LightInjectWebConfigurator>(),
                                    Times.Once);
        }
    }
}


text:
var roomy = module.exports = {};

//
// `roomy.parse(string)`
//
// The only argument is a string like `1LDK`. The return value is an object
// like the following:
//
// ```json
// {
//   "rooms": 1,
//   "living_room": true,
//   "dining_room": true,
//   "kitchen": true
// }
// ```
//

roomy.parse = function parse(string) {
  var parts = string.toUpperCase().replace(/\s+/g, "").split(/(\D)/).filter(function(e) { return e.length > 0; });

  var res = {};

  if (parts[0].match(/^\d+$/)) {
    res.rooms = parseInt(parts.shift(), 10);
  }

  parts.forEach(function(part) {
    switch (part) {
      case "R": if (!res.rooms) { res.rooms = 1; } break;
      case "L": res.living_room = true; break;
      case "D": res.dining_room = true; break;
      case "K": res.kitchen = true; break;
      default: break;
    }
  });

  return res;
};

//
// `roomy.generate(object)`
//
// The only argument is an object with the same format as the output of `parse`.
// The return value is a string like `1LDK`.
//

roomy.generate = function generate(object) {
  return [
    object.rooms ? object.rooms.toString() : "",
    object.living_room ? "L" : "",
    object.dining_room ? "D" : "",
    object.kitchen ? "K" : "",
  ].join("");
};


text:
<?php

namespace Drupal\devel\Plugin\Devel\Dumper;

use Drupal\Component\Utility\Variable;
use Drupal\devel\DevelDumperBase;

/**
 * Provides a DrupalVariable dumper plugin.
 *
 * @DevelDumper(
 *   id = "drupal_variable",
 *   label = @Translation("Drupal variable."),
 *   description = @Translation("Wrapper for Drupal Variable class.")
 * )
 */
class DrupalVariable extends DevelDumperBase {

  /**
   * {@inheritdoc}
   */
  public function export($input, $name = NULL) {
    $name = $name ? $name . ' => ' : '';
    $dump = '
' . $name . Variable::export($input) . '
';
    return $this->setSafeMarkup($dump);
  }

  /**
   * {@inheritdoc}
   */
  public function exportAsRenderable($input, $name = NULL) {
    $output['container'] = [
      '#type' => 'details',
      '#title' => $name ? : $this->t('Variable'),
      '#attached' => [
        'library' => ['devel/devel']
      ],
      '#attributes' => [
        'class' => ['container-inline', 'devel-dumper', 'devel-selectable'],
      ],
      'export' => [
        '#markup' => $this->export($input),
      ],
    ];

    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public static function checkRequirements() {
    return TRUE;
  }

}


text:
"""Module containing the template for documents.
"""

from soc.views.template import Template
from soc.logic.helper import prefixes
from soc.views.helper import lists

import soc.models.document

class Document(Template):
  def __init__(self, data, entity):
    assert(entity != None)
    self.data = data
    self.entity = entity

  def context(self):
    return {
        'content': self.entity.content,
        'title': self.entity.title,
    }

  def templatePath(self):
    return "v2/soc/_document.html"

def validateForm(data, document_form):
  if not document_form.is_valid():
    return

  cleaned_data = document_form.cleaned_data
  cleaned_data['modified_by'] = data.user

  if data.document:
    document = document_form.save()
  else:
    prefix = data.kwargs['prefix']
    cleaned_data['link_id'] = data.kwargs['document']
    cleaned_data['author'] = data.user
    cleaned_data['prefix'] = prefix
    cleaned_data['scope'] = prefixes.getScopeForPrefix(prefix, data.scope_path)
    cleaned_data['scope_path'] = data.scope_path
    document = document_form.create(key_name=data.key_name)

  return document

class DocumentList(Template):
  """Template for list of documents.
  """

  def __init__(self, request, data, edit_name):
    self.request = request
    self.data = data
    r = data.redirect

    list_config = lists.ListConfiguration()
    list_config.addSimpleColumn('title', 'Title')
    list_config.addSimpleColumn('link_id', 'Link ID', hidden=True)
    list_config.addSimpleColumn('short_name', 'Short Name')
    list_config.setRowAction(
        lambda e, *args: r.document(e).urlOf(edit_name))

    list_config.setDefaultPagination(False)
    list_config.setDefaultSort('title')

    self._list_config = list_config

  def context(self):
    description = 'List of documents for %s' % (
            self.data.program.name)

    list = lists.ListConfigurationResponse(
        self.data, self._list_config, 0, description)

    return {
        'lists': [list],
    }

  def getListData(self):
    idx = lists.getListIndex(self.request)
    if idx == 0:
      q = soc.models.document.Document.all()
      q.filter('scope', self.data.program)

      response_builder = lists.RawQueryContentResponseBuilder(
          self.request, self._list_config, q, lists.keyStarter)

      return response_builder.build()
    else:
      return None


text:
namespace caffe {

template <typename TypeParam>
class OctreeGrowLayerTest : public OctreeTest<TypeParam> {
  typedef typename TypeParam::Dtype Dtype;

 protected:
  OctreeGrowLayerTest() {}
  virtual void SetUp() {}
};

TYPED_TEST_CASE(OctreeGrowLayerTest, TestDtypesAndDevices);

TYPED_TEST(OctreeGrowLayerTest, TestFullOctree) {
  typedef typename TypeParam::Dtype Dtype;

  // prepare testing data
  string octree1("octree_3");
  size_t sz1 = 0;
  const char* oct_ptr1 = get_test_octree(octree1.c_str(), &sz1);
  OctreeParser parser1;
  parser1.set_cpu(oct_ptr1);

  // generate full octree
  const int full_octree = true;
  const int curr_depth = 2, batch_size = 1;

  LayerParameter layer_param;
  layer_param.mutable_octree_param()->set_curr_depth(curr_depth);
  layer_param.mutable_octree_param()->set_batch_size(batch_size);
  layer_param.mutable_octree_param()->set_full_octree(full_octree);

  OctreeGrowLayer<Dtype> layer(layer_param);
  vector<Blob<Dtype>*> blob_bottom_vec, blob_top_vec;
  blob_top_vec.push_back(new Blob<Dtype>());
  layer.SetUp(blob_bottom_vec, blob_top_vec);
  layer.Forward(blob_bottom_vec, blob_top_vec);

  // test octree info.
  OctreeParser parser;
  parser.set_cpu(blob_top_vec[0]->cpu_data());
  ASSERT_EQ(parser.info().batch_size(), batch_size);
  ASSERT_EQ(parser.info().depth(), curr_depth);
  ASSERT_EQ(parser.info().full_layer(), curr_depth);
  ASSERT_EQ(parser.info().is_adaptive(), false);
  ASSERT_EQ(parser.info().key2xyz(), true);

  // test key
  const unsigned int* key1 = parser1.key_cpu(curr_depth);
  const unsigned int* key_batch = parser.key_cpu(curr_depth);
  int nnum1 = parser1.info().node_num(curr_depth);
  int nnum_batch = parser.info().node_num(curr_depth);
  ASSERT_EQ(nnum1, nnum_batch);
  for (int i = 0; i < nnum1; ++i) {
    const char* ptr1 = reinterpret_cast<const char*>(key1 + i);
    const char* ptr_batch = reinterpret_cast<const char*>(key_batch + i);
    for (int c = 0; c < 3; ++c) {
      ASSERT_EQ(ptr1[c], ptr_batch[c]) << "Key : " << i;
    }
  }

  // check children
  const int* child_batch = parser.children_cpu(curr_depth);
  for (int i = 0; i < nnum1; ++i) {
    ASSERT_EQ(child_batch[i], i) << "Children : " << i;
  }

  // release
  delete blob_top_vec[0];
}

}  // namespace caffe


text:
package com.palantir.atlasdb.transaction.impl;

import com.palantir.atlasdb.transaction.api.Transaction;

public class StdoutTracingTransaction extends TracingTransaction {
    public StdoutTracingTransaction(Transaction delegate) {
        super(delegate);
    }

    @Override
    protected boolean isTraceEnabled() {
        return true;
    }

    @Override
    protected void trace(String format, Object... args) {
        System.out.println(String.format(format, args)); // (authorized)
    }
}


text:
package com.dexterapps.android.translator;

import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

/**
 *
 * @author Pranay Airan
 * http://www.dexterapps.in/
 * pranay.airan@iiitb.net
 *
 * This Class Calls the Azure Webservice for translating strings using Microsoft Translate JAVA API Library
 * Microsoft Translation API can take Single Strings or Group of Strings for translation
 */

public class TranslateText {

    String azureClientID;
    String azureClientSecret;

    public TranslateText(String clientID,String clientSecret)
    {
        azureClientID = clientID;
        azureClientSecret = clientSecret;
    }

     public String[] translateTextArrays(String[] sourceTexts, Language from, Language to) {

        // Set your Windows Azure Marketplace client info - See http://msdn.microsoft.com/en-us/library/hh454950.aspx

        //Translate.setClientId("thisisinsaneineedtogeneratemyownclientid");
        //Translate.setClientSecret("81+DZxvj/VGO4gPlfYpKSrbBHLdyB4F7BXGq++ttI9I=");

        Translate.setClientId(azureClientID);
        Translate.setClientSecret(azureClientSecret);

        // Call the translate.execute method, passing an array of source texts
        String[] translatedTexts;
        try {
            translatedTexts = Translate.execute(sourceTexts, from, to);
           // System.out.println("Translation Successful");
        } catch (Exception e) {
            translatedTexts = null;
            System.out.println(e.getMessage());
        }

        return translatedTexts;
    }

}


text:
<?php

namespace Sonata\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Sonata\UserBundle\Model\UserInterface;

class ProfileType extends AbstractType
{
    private $class;

    /**
     * @param string $class The User class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('gender', 'sonata_user_gender', array(
                'required' => true,
                'translation_domain' => 'SonataUserBundle',
                'choices' => array(
                    UserInterface::GENDER_FEMALE => 'gender_female',
                    UserInterface::GENDER_MALE   => 'gender_male',
                )
            ))
            ->add('firstname', null, array('required' => false))
            ->add('lastname', null, array('required' => false))
            ->add('dateOfBirth', 'birthday', array('required' => false, 'widget' => 'single_text'))
            ->add('website', 'url', array('required' => false))
            ->add('biography', 'textarea', array('required' => false))
            ->add('locale', 'locale', array('required' => false))
            ->add('timezone', 'timezone', array('required' => false))
            ->add('phone', null, array('required' => false))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => $this->class
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sonata_user_profile';
    }
}


text:
#include "UnaryTimeExpr.h"
#include<lang/log/LogLevel.h>

#include <commonlib/commonlib.h>
#include <lang/model/allmodel.h>

#include <lang/exception/ScriptUsageException.h>

namespace IAS {
namespace Lang {
namespace Interpreter {
namespace Exe {
namespace Expr {

/*************************************************************************/
UnaryTimeExpr::UnaryTimeExpr(Expr* pExpr):
		UnaryExprFamily(pExpr){
	IAS_TRACER;
}
/*************************************************************************/
UnaryTimeExpr::~UnaryTimeExpr() throw(){
	IAS_TRACER;
}
/*************************************************************************/
UnaryTimeExpr* UnaryTimeExpr::Create(Expr* pExpr, TypeInfoProxy aTypeInfoProxy){
	IAS_TRACER;
	IAS_DFT_FACTORY<UnaryTimeExpr>::PtrHolder ptrUnaryTimeExpr;

	IAS_THROW(ScriptUsageException("Bad operator for a time argument."));
}
/*************************************************************************/
}
}
}
}
}


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

    <string name="app_name">Hello Droid</string>
    <string name="action_settings">Settings</string>
    <string name="hello_droid">Hello droid, you\'re on "Main" Activity !</string>

</resources>


text:
{% extends "base.html" %}
{% load crispy from crispy_forms_tags %}
{% load i18n %}
{% load model_name from cobweb_look %}
{% load render_table from django_tables2 %}

{% block title %}Cobweb: {{ claim }}{% endblock %}

{% block content %}
    {% include "delete_modal.html" %}

            {% include "delete_button.html" %}
            Claim nominated URL{% if object.nomination.resource %}: {{object.nomination.resource}}{% endif %}

                {% crispy nomination_form %}

{% crispy form %}

{% endblock %}


text:
package org.elasticsearch.index.percolator;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TieredMergePolicy;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.IndexWarmer;
import org.elasticsearch.index.analysis.AnalysisRegistry;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.internal.SourceFieldMapper;
import org.elasticsearch.index.mapper.internal.TypeFieldMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.PercolatorQuery;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParser;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.warmer.ShardIndexWarmerService;
import org.elasticsearch.indices.IndicesModule;
import org.elasticsearch.indices.mapper.MapperRegistry;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.elasticsearch.threadpool.ThreadPool;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class PercolatorQueryCacheTests extends ESTestCase {

    private QueryShardContext queryShardContext;
    private PercolatorQueryCache cache;

    void initialize(Object... fields) throws IOException {
        Settings settings = Settings.builder()
                .put("node.name", PercolatorQueryCacheTests.class.toString())
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
                .build();

        Map<String, Tuple<ParseField, QueryParser<?>>> queryParsers = new HashMap<>();
        QueryParser<TermQueryBuilder> termParser = TermQueryBuilder::fromXContent;
        queryParsers.put(TermQueryBuilder.NAME, new Tuple<>(TermQueryBuilder.QUERY_NAME_FIELD, termParser));
        QueryParser<WildcardQueryBuilder> wildcardParser = WildcardQueryBuilder::fromXContent;
        queryParsers.put(WildcardQueryBuilder.NAME, new Tuple<>(WildcardQueryBuilder.QUERY_NAME_FIELD, wildcardParser));
        QueryParser<BoolQueryBuilder> boolQueryParser = BoolQueryBuilder::fromXContent;
        queryParsers.put(BoolQueryBuilder.NAME, new Tuple<>(BoolQueryBuilder.QUERY_NAME_FIELD, boolQueryParser));
        IndicesQueriesRegistry indicesQueriesRegistry = new IndicesQueriesRegistry(settings, queryParsers);

        Settings indexSettings = Settings.builder()
                .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
        IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(new Index("_index", ClusterState.UNKNOWN_UUID), indexSettings);
        SimilarityService similarityService = new SimilarityService(idxSettings, Collections.emptyMap());
        AnalysisService analysisService = new AnalysisRegistry(null, new Environment(settings)).build(idxSettings);
        MapperRegistry mapperRegistry = new IndicesModule().getMapperRegistry();
        MapperService mapperService = new MapperService(idxSettings, analysisService, similarityService, mapperRegistry,
                () -> queryShardContext);
        mapperService.merge("type", new CompressedXContent(PutMappingRequest.buildFromSimplifiedDef("type", fields).string()),
                MapperService.MergeReason.MAPPING_UPDATE, false);
        cache = new PercolatorQueryCache(idxSettings, () -> queryShardContext);
        queryShardContext = new QueryShardContext(idxSettings, null, null, mapperService, similarityService, null,
                    indicesQueriesRegistry, cache, null);
    }

    public void testLoadQueries() throws Exception {
        Directory directory = newDirectory();
        IndexWriter indexWriter = new IndexWriter(
                directory,
                newIndexWriterConfig(new MockAnalyzer(random()))
                        .setMergePolicy(NoMergePolicy.INSTANCE)
                        .setMaxBufferedDocs(16)
        );

        boolean legacyFormat = randomBoolean();
        Version version = legacyFormat ? Version.V_2_0_0 : Version.CURRENT;

        storeQuery("0", indexWriter, termQuery("field1", "value1"), true, legacyFormat);
        storeQuery("1", indexWriter, wildcardQuery("field1", "v*"), true, legacyFormat);
        storeQuery("2", indexWriter, boolQuery().must(termQuery("field1", "value1")).must(termQuery("field2", "value2")),
                true, legacyFormat);
        // dymmy docs should be skipped during loading:
        Document doc = new Document();
        doc.add(new StringField("dummy", "value", Field.Store.YES));
        indexWriter.addDocument(doc);
        storeQuery("4", indexWriter, termQuery("field2", "value2"), true, legacyFormat);
        // only documents that .percolator type should be loaded:
        storeQuery("5", indexWriter, termQuery("field2", "value2"), false, legacyFormat);
        storeQuery("6", indexWriter, termQuery("field3", "value3"), true, legacyFormat);
        indexWriter.forceMerge(1);

        // also include queries for percolator docs marked as deleted:
        indexWriter.deleteDocuments(new Term("id", "6"));
        indexWriter.close();

        ShardId shardId = new ShardId("_index", ClusterState.UNKNOWN_UUID, 0);
        IndexReader indexReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(directory), shardId);
        assertThat(indexReader.leaves().size(), equalTo(1));
        assertThat(indexReader.numDeletedDocs(), equalTo(1));
        assertThat(indexReader.maxDoc(), equalTo(7));

        initialize("field1", "type=keyword", "field2", "type=keyword", "field3", "type=keyword");

        PercolatorQueryCache.QueriesLeaf leaf = cache.loadQueries(indexReader.leaves().get(0), version);
        assertThat(leaf.queries.size(), equalTo(5));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("field1", "value1"))));
        assertThat(leaf.getQuery(1), equalTo(new WildcardQuery(new Term("field1", "v*"))));
        assertThat(leaf.getQuery(2), equalTo(new BooleanQuery.Builder()
                .add(new TermQuery(new Term("field1", "value1")), BooleanClause.Occur.MUST)
                .add(new TermQuery(new Term("field2", "value2")), BooleanClause.Occur.MUST)
                .build()
        ));
        assertThat(leaf.getQuery(4), equalTo(new TermQuery(new Term("field2", "value2"))));
        assertThat(leaf.getQuery(6), equalTo(new TermQuery(new Term("field3", "value3"))));

        indexReader.close();
        directory.close();
    }

    public void testGetQueries() throws Exception {
        Directory directory = newDirectory();
        IndexWriter indexWriter = new IndexWriter(
                directory,
                newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE)
        );

        storeQuery("0", indexWriter, termQuery("a", "0"), true, false);
        storeQuery("1", indexWriter, termQuery("a", "1"), true, false);
        storeQuery("2", indexWriter, termQuery("a", "2"), true, false);
        indexWriter.flush();
        storeQuery("3", indexWriter, termQuery("a", "3"), true, false);
        storeQuery("4", indexWriter, termQuery("a", "4"), true, false);
        storeQuery("5", indexWriter, termQuery("a", "5"), true, false);
        indexWriter.flush();
        storeQuery("6", indexWriter, termQuery("a", "6"), true, false);
        storeQuery("7", indexWriter, termQuery("a", "7"), true, false);
        storeQuery("8", indexWriter, termQuery("a", "8"), true, false);
        indexWriter.flush();
        indexWriter.close();

        ShardId shardId = new ShardId("_index", ClusterState.UNKNOWN_UUID , 0);
        IndexReader indexReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(directory), shardId);
        assertThat(indexReader.leaves().size(), equalTo(3));
        assertThat(indexReader.maxDoc(), equalTo(9));

        initialize("a", "type=keyword");

        try {
            cache.getQueries(indexReader.leaves().get(0));
            fail("IllegalStateException expected");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), equalTo("queries not loaded, queries should be have been preloaded during index warming..."));
        }

        IndexShard indexShard = mockIndexShard();
        ThreadPool threadPool = mockThreadPool();
        IndexWarmer.Listener listener = cache.createListener(threadPool);
        listener.warmReader(indexShard, new Engine.Searcher("test", new IndexSearcher(indexReader)));
        PercolatorQueryCacheStats stats = cache.getStats(shardId);
        assertThat(stats.getNumQueries(), equalTo(9L));

        PercolatorQuery.QueryRegistry.Leaf leaf = cache.getQueries(indexReader.leaves().get(0));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "0"))));
        assertThat(leaf.getQuery(1), equalTo(new TermQuery(new Term("a", "1"))));
        assertThat(leaf.getQuery(2), equalTo(new TermQuery(new Term("a", "2"))));

        leaf = cache.getQueries(indexReader.leaves().get(1));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "3"))));
        assertThat(leaf.getQuery(1), equalTo(new TermQuery(new Term("a", "4"))));
        assertThat(leaf.getQuery(2), equalTo(new TermQuery(new Term("a", "5"))));

        leaf = cache.getQueries(indexReader.leaves().get(2));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "6"))));
        assertThat(leaf.getQuery(1), equalTo(new TermQuery(new Term("a", "7"))));
        assertThat(leaf.getQuery(2), equalTo(new TermQuery(new Term("a", "8"))));

        indexReader.close();
        directory.close();
    }

    public void testInvalidateEntries() throws Exception {
        Directory directory = newDirectory();
        IndexWriter indexWriter = new IndexWriter(
                directory,
                newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE)
        );

        storeQuery("0", indexWriter, termQuery("a", "0"), true, false);
        indexWriter.flush();
        storeQuery("1", indexWriter, termQuery("a", "1"), true, false);
        indexWriter.flush();
        storeQuery("2", indexWriter, termQuery("a", "2"), true, false);
        indexWriter.flush();

        ShardId shardId = new ShardId("_index", ClusterState.UNKNOWN_UUID, 0);
        IndexReader indexReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId);
        assertThat(indexReader.leaves().size(), equalTo(3));
        assertThat(indexReader.maxDoc(), equalTo(3));

        initialize("a", "type=keyword");

        IndexShard indexShard = mockIndexShard();
        ThreadPool threadPool = mockThreadPool();
        IndexWarmer.Listener listener = cache.createListener(threadPool);
        listener.warmReader(indexShard, new Engine.Searcher("test", new IndexSearcher(indexReader)));
        assertThat(cache.getStats(shardId).getNumQueries(), equalTo(3L));

        PercolatorQuery.QueryRegistry.Leaf leaf = cache.getQueries(indexReader.leaves().get(0));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "0"))));

        leaf = cache.getQueries(indexReader.leaves().get(1));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "1"))));

        leaf = cache.getQueries(indexReader.leaves().get(2));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "2"))));

        // change merge policy, so that merges will actually happen:
        indexWriter.getConfig().setMergePolicy(new TieredMergePolicy());
        indexWriter.deleteDocuments(new Term("id", "1"));
        indexWriter.forceMergeDeletes();
        indexReader.close();
        indexReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId);
        assertThat(indexReader.leaves().size(), equalTo(2));
        assertThat(indexReader.maxDoc(), equalTo(2));
        listener.warmReader(indexShard, new Engine.Searcher("test", new IndexSearcher(indexReader)));
        assertThat(cache.getStats(shardId).getNumQueries(), equalTo(2L));

        leaf = cache.getQueries(indexReader.leaves().get(0));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "0"))));

        leaf = cache.getQueries(indexReader.leaves().get(1));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "2"))));

        indexWriter.forceMerge(1);
        indexReader.close();
        indexReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId);
        assertThat(indexReader.leaves().size(), equalTo(1));
        assertThat(indexReader.maxDoc(), equalTo(2));
        listener.warmReader(indexShard, new Engine.Searcher("test", new IndexSearcher(indexReader)));
        assertThat(cache.getStats(shardId).getNumQueries(), equalTo(2L));

        leaf = cache.getQueries(indexReader.leaves().get(0));
        assertThat(leaf.getQuery(0), equalTo(new TermQuery(new Term("a", "0"))));
        assertThat(leaf.getQuery(1), equalTo(new TermQuery(new Term("a", "2"))));

        indexWriter.close();
        indexReader.close();
        directory.close();
    }

    void storeQuery(String id, IndexWriter indexWriter, QueryBuilder queryBuilder, boolean typeField, boolean legacy) throws IOException {
        Document doc = new Document();
        doc.add(new StringField("id", id, Field.Store.NO));
        if (typeField) {
            doc.add(new StringField(TypeFieldMapper.NAME, PercolatorFieldMapper.TYPE_NAME, Field.Store.NO));
        }
        if (legacy) {
            BytesReference percolatorQuery = XContentFactory.jsonBuilder().startObject()
                    .field("query", queryBuilder)
                    .endObject().bytes();
            doc.add(new StoredField(
                    SourceFieldMapper.NAME,
                    percolatorQuery.array(), percolatorQuery.arrayOffset(), percolatorQuery.length())
            );
        } else {
            BytesRef queryBuilderAsBytes = new BytesRef(
                    XContentFactory.contentBuilder(PercolatorQueryCache.QUERY_BUILDER_CONTENT_TYPE).value(queryBuilder).bytes().toBytes()
            );
            doc.add(new BinaryDocValuesField(PercolatorFieldMapper.QUERY_BUILDER_FULL_FIELD_NAME, queryBuilderAsBytes));
        }
        indexWriter.addDocument(doc);
    }

    IndexShard mockIndexShard() {
        IndexShard indexShard = mock(IndexShard.class);
        ShardIndexWarmerService shardIndexWarmerService = mock(ShardIndexWarmerService.class);
        when(shardIndexWarmerService.logger()).thenReturn(logger);
        when(indexShard.warmerService()).thenReturn(shardIndexWarmerService);
        IndexSettings indexSettings = new IndexSettings(
                IndexMetaData.builder("_index").settings(Settings.builder()
                        .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                        .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
                        .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                ).build(),
                Settings.EMPTY
        );
        when(indexShard.indexSettings()).thenReturn(indexSettings);
        return indexShard;
    }

    ThreadPool mockThreadPool() {
        ThreadPool threadPool = mock(ThreadPool.class);
        when(threadPool.executor(anyString())).thenReturn(Runnable::run);
        return threadPool;
    }

}


text:
module UnsemanticRails
  VERSION = "0.0.2"
end


text:
Java library for parsing [Executable and Linkable Format (ELF)](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) files.

[![Build Status](https://github.com/fornwall/jelf/workflows/Java%20CI/badge.svg)](https://github.com/fornwall/jelf/actions?query=workflow%3A%22Java+CI%22)
[![MIT licensed](http://img.shields.io/:license-MIT-blue.svg)](LICENSE.txt)
[![Package on Maven Central](https://img.shields.io/maven-central/v/net.fornwall/jelf)](https://search.maven.org/artifact/net.fornwall/jelf/)
[![javadoc](https://www.javadoc.io/badge/net.fornwall/jelf.svg)](https://www.javadoc.io/doc/net.fornwall/jelf)

## Adding JElf to your build

JElf's Maven group ID is `net.fornwall` and its artifact ID is `jelf`.

To add a dependency on JElf using Maven, use the following:

```xml
<dependency>
    <groupId>net.fornwall</groupId>
    <artifactId>jelf</artifactId>
    <version>0.7.0</version>
</dependency>
```

To add a dependency using Gradle:

```gradle
dependencies {
    implementation 'net.fornwall:jelf:0.7.0'
}
```

## ELF Resources
- [Wikipedia entry on the ELF format](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format)
- [elf(5) man page](http://man7.org/linux/man-pages/man5/elf.5.html)
- [Anatomy of Linux dynamic libraries](https://www.ibm.com/developerworks/library/l-dynamic-libraries/)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__wchar_t_alloca_loop_67b.c
Label Definition File: CWE127_Buffer_Underread.stack.label.xml
Template File: sources-sink-67b.tmpl.c
*/
/*
 * @description
 * CWE: 127 Buffer Under-read
 * BadSource:  Set data pointer to before the allocated memory buffer
 * GoodSource: Set data pointer to the allocated memory buffer
 * Sinks: loop
 *    BadSink : Copy data to string using a loop
 * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

typedef struct _CWE127_Buffer_Underread__wchar_t_alloca_loop_67_structType
{
    wchar_t * structFirst;
} CWE127_Buffer_Underread__wchar_t_alloca_loop_67_structType;

#ifndef OMITBAD

void CWE127_Buffer_Underread__wchar_t_alloca_loop_67b_badSink(CWE127_Buffer_Underread__wchar_t_alloca_loop_67_structType myStruct)
{
    wchar_t * data = myStruct.structFirst;
    {
        size_t i;
        wchar_t dest[100];
        wmemset(dest, L'C', 100-1); /* fill with 'C's */
        dest[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
        for (i = 0; i < 100; i++)
        {
            dest[i] = data[i];
        }
        /* Ensure null termination */
        dest[100-1] = L'\0';
        printWLine(dest);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE127_Buffer_Underread__wchar_t_alloca_loop_67b_goodG2BSink(CWE127_Buffer_Underread__wchar_t_alloca_loop_67_structType myStruct)
{
    wchar_t * data = myStruct.structFirst;
    {
        size_t i;
        wchar_t dest[100];
        wmemset(dest, L'C', 100-1); /* fill with 'C's */
        dest[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
        for (i = 0; i < 100; i++)
        {
            dest[i] = data[i];
        }
        /* Ensure null termination */
        dest[100-1] = L'\0';
        printWLine(dest);
    }
}

#endif /* OMITGOOD */


text:
<?php

namespace Drupal\Core\Extension;

use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Extension\Discovery\RecursiveExtensionFilterIterator;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;

/**
 * Discovers available extensions in the filesystem.
 *
 * To also discover test modules, add
 * @code
 * $settings['extension_discovery_scan_tests'] = TRUE;
 * @encode
 * to your settings.php.
 *
 */
class ExtensionDiscovery {

  /**
   * Origin directory weight: Core.
   */
  const ORIGIN_CORE = 0;

  /**
   * Origin directory weight: Installation profile.
   */
  const ORIGIN_PROFILE = 1;

  /**
   * Origin directory weight: sites/all.
   */
  const ORIGIN_SITES_ALL = 2;

  /**
   * Origin directory weight: Site-wide directory.
   */
  const ORIGIN_ROOT = 3;

  /**
   * Origin directory weight: Parent site directory of a test site environment.
   */
  const ORIGIN_PARENT_SITE = 4;

  /**
   * Origin directory weight: Site-specific directory.
   */
  const ORIGIN_SITE = 5;

  /**
   * Regular expression to match PHP function names.
   *
   * @see http://php.net/manual/functions.user-defined.php
   */
  const PHP_FUNCTION_PATTERN = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/';

  /**
   * InfoParser instance for parsing .info.yml files.
   *
   * @var \Drupal\Core\Extension\InfoParser
   */
  protected $infoParser;

  /**
   * Previously discovered files keyed by origin directory and extension type.
   *
   * @var array
   */
  protected static $files = array();

  /**
   * List of installation profile directories to additionally scan.
   *
   * @var array
   */
  protected $profileDirectories;

  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

  /**
   * The file cache object.
   *
   * @var \Drupal\Component\FileCache\FileCacheInterface
   */
  protected $fileCache;

  /**
   * The site path.
   *
   * @var string
   */
  protected $sitePath;

  /**
   * Constructs a new ExtensionDiscovery object.
   *
   * @param string $root
   *   The app root.
   * @param bool $use_file_cache
   *   Whether file cache should be used.
   * @param string[] $profile_directories
   *   The available profile directories
   * @param string $site_path
   *   The path to the site.
   */
  public function __construct($root, $use_file_cache = TRUE, $profile_directories = NULL, $site_path = NULL) {
    $this->root = $root;
    $this->fileCache = $use_file_cache ? FileCacheFactory::get('extension_discovery') : NULL;
    $this->profileDirectories = $profile_directories;
    $this->sitePath = $site_path;
  }

  /**
   * Discovers available extensions of a given type.
   *
   * Finds all extensions (modules, themes, etc) that exist on the site. It
   * searches in several locations. For instance, to discover all available
   * modules:
   * @code
   * $listing = new ExtensionDiscovery(\Drupal::root());
   * $modules = $listing->scan('module');
   * @endcode
   *
   * The following directories will be searched (in the order stated):
   * - the core directory; i.e., /core
   * - the installation profile directory; e.g., /core/profiles/standard
   * - the legacy site-wide directory; i.e., /sites/all
   * - the site-wide directory; i.e., /
   * - the site-specific directory; e.g., /sites/example.com
   *
   * To also find test modules, add
   * @code
   * $settings['extension_discovery_scan_tests'] = TRUE;
   * @encode
   * to your settings.php.
   *
   * The information is returned in an associative array, keyed by the extension
   * name (without .info.yml extension). Extensions found later in the search
   * will take precedence over extensions found earlier - unless they are not
   * compatible with the current version of Drupal core.
   *
   * @param string $type
   *   The extension type to search for. One of 'profile', 'module', 'theme', or
   *   'theme_engine'.
   * @param bool $include_tests
   *   (optional) Whether to explicitly include or exclude test extensions. By
   *   default, test extensions are only discovered when in a test environment.
   *
   * @return \Drupal\Core\Extension\Extension[]
   *   An associative array of Extension objects, keyed by extension name.
   */
  public function scan($type, $include_tests = NULL) {
    // Determine the installation profile directories to scan for extensions,
    // unless explicit profile directories have been set. Exclude profiles as we
    // cannot have profiles within profiles.
    if (!isset($this->profileDirectories) && $type != 'profile') {
      $this->setProfileDirectoriesFromSettings();
    }

    // Search the core directory.
    $searchdirs[static::ORIGIN_CORE] = 'core';

    // Search the legacy sites/all directory.
    $searchdirs[static::ORIGIN_SITES_ALL] = 'sites/all';

    // Search for contributed and custom extensions in top-level directories.
    // The scan uses a whitelist to limit recursion to the expected extension
    // type specific directory names only.
    $searchdirs[static::ORIGIN_ROOT] = '';

    // Simpletest uses the regular built-in multi-site functionality of Drupal
    // for running web tests. As a consequence, extensions of the parent site
    // located in a different site-specific directory are not discovered in a
    // test site environment, because the site directories are not the same.
    // Therefore, add the site directory of the parent site to the search paths,
    // so that contained extensions are still discovered.
    // @see \Drupal\simpletest\WebTestBase::setUp()
    if ($parent_site = Settings::get('test_parent_site')) {
      $searchdirs[static::ORIGIN_PARENT_SITE] = $parent_site;
    }

    // Find the site-specific directory to search. Since we are using this
    // method to discover extensions including profiles, we might be doing this
    // at install time. Therefore Kernel service is not always available, but is
    // preferred.
    if (\Drupal::hasService('kernel')) {
      $searchdirs[static::ORIGIN_SITE] = \Drupal::service('site.path');
    }
    else {
      $searchdirs[static::ORIGIN_SITE] = $this->sitePath ?: DrupalKernel::findSitePath(Request::createFromGlobals());
    }

    // Unless an explicit value has been passed, manually check whether we are
    // in a test environment, in which case test extensions must be included.
    // Test extensions can also be included for debugging purposes by setting a
    // variable in settings.php.
    if (!isset($include_tests)) {
      $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
    }

    $files = array();
    foreach ($searchdirs as $dir) {
      // Discover all extensions in the directory, unless we did already.
      if (!isset(static::$files[$dir][$include_tests])) {
        static::$files[$dir][$include_tests] = $this->scanDirectory($dir, $include_tests);
      }
      // Only return extensions of the requested type.
      if (isset(static::$files[$dir][$include_tests][$type])) {
        $files += static::$files[$dir][$include_tests][$type];
      }
    }

    // If applicable, filter out extensions that do not belong to the current
    // installation profiles.
    $files = $this->filterByProfileDirectories($files);
    // Sort the discovered extensions by their originating directories.
    $origin_weights = array_flip($searchdirs);
    $files = $this->sort($files, $origin_weights);

    // Process and return the list of extensions keyed by extension name.
    return $this->process($files);
  }

  /**
   * Sets installation profile directories based on current site settings.
   *
   * @return $this
   */
  public function setProfileDirectoriesFromSettings() {
    $this->profileDirectories = array();
    $profile = drupal_get_profile();
    // For SimpleTest to be able to test modules packaged together with a
    // distribution we need to include the profile of the parent site (in
    // which test runs are triggered).
    if (drupal_valid_test_ua() && !drupal_installation_attempted()) {
      $testing_profile = \Drupal::config('simpletest.settings')->get('parent_profile');
      if ($testing_profile && $testing_profile != $profile) {
        $this->profileDirectories[] = drupal_get_path('profile', $testing_profile);
      }
    }
    // In case both profile directories contain the same extension, the actual
    // profile always has precedence.
    if ($profile) {
      $this->profileDirectories[] = drupal_get_path('profile', $profile);
    }
    return $this;
  }

  /**
   * Gets the installation profile directories to be scanned.
   *
   * @return array
   *   A list of installation profile directory paths relative to the system
   *   root directory.
   */
  public function getProfileDirectories() {
    return $this->profileDirectories;
  }

  /**
   * Sets explicit profile directories to scan.
   *
   * @param array $paths
   *   A list of installation profile directory paths relative to the system
   *   root directory (without trailing slash) to search for extensions.
   *
   * @return $this
   */
  public function setProfileDirectories(array $paths = NULL) {
    $this->profileDirectories = $paths;
    return $this;
  }

  /**
   * Filters out extensions not belonging to the scanned installation profiles.
   *
   * @param \Drupal\Core\Extension\Extension[] $all_files.
   *   The list of all extensions.
   *
   * @return \Drupal\Core\Extension\Extension[]
   *   The filtered list of extensions.
   */
  protected function filterByProfileDirectories(array $all_files) {
    if (empty($this->profileDirectories)) {
      return $all_files;
    }

    $all_files = array_filter($all_files, function ($file) {
      if (strpos($file->subpath, 'profiles') !== 0) {
        // This extension doesn't belong to a profile, ignore it.
        return TRUE;
      }

      foreach ($this->profileDirectories as $weight => $profile_path) {
        if (strpos($file->getPath(), $profile_path) === 0) {
          // Parent profile found.
          return TRUE;
        }
      }

      return FALSE;
    });

    return $all_files;
  }

  /**
   * Sorts the discovered extensions.
   *
   * @param \Drupal\Core\Extension\Extension[] $all_files.
   *   The list of all extensions.
   * @param array $weights
   *   An array of weights, keyed by originating directory.
   *
   * @return \Drupal\Core\Extension\Extension[]
   *   The sorted list of extensions.
   */
  protected function sort(array $all_files, array $weights) {
    $origins = array();
    $profiles = array();
    foreach ($all_files as $key => $file) {
      // If the extension does not belong to a profile, just apply the weight
      // of the originating directory.
      if (strpos($file->subpath, 'profiles') !== 0) {
        $origins[$key] = $weights[$file->origin];
        $profiles[$key] = NULL;
      }
      // If the extension belongs to a profile but no profile directories are
      // defined, then we are scanning for installation profiles themselves.
      // In this case, profiles are sorted by origin only.
      elseif (empty($this->profileDirectories)) {
        $origins[$key] = static::ORIGIN_PROFILE;
        $profiles[$key] = NULL;
      }
      else {
        // Apply the weight of the originating profile directory.
        foreach ($this->profileDirectories as $weight => $profile_path) {
          if (strpos($file->getPath(), $profile_path) === 0) {
            $origins[$key] = static::ORIGIN_PROFILE;
            $profiles[$key] = $weight;
            continue 2;
          }
        }
      }
    }
    // Now sort the extensions by origin and installation profile(s).
    // The result of this multisort can be depicted like the following matrix,
    // whereas the first integer is the weight of the originating directory and
    // the second is the weight of the originating installation profile:
    // 0   core/modules/node/node.module
    // 1 0 profiles/parent_profile/modules/parent_module/parent_module.module
    // 1 1 core/profiles/testing/modules/compatible_test/compatible_test.module
    // 2   sites/all/modules/common/common.module
    // 3   modules/devel/devel.module
    // 4   sites/default/modules/custom/custom.module
    array_multisort($origins, SORT_ASC, $profiles, SORT_ASC, $all_files);

    return $all_files;
  }

  /**
   * Processes the filtered and sorted list of extensions.
   *
   * Extensions discovered in later search paths override earlier, unless they
   * are not compatible with the current version of Drupal core.
   *
   * @param \Drupal\Core\Extension\Extension[] $all_files
   *   The sorted list of all extensions that were found.
   *
   * @return \Drupal\Core\Extension\Extension[]
   *   The filtered list of extensions, keyed by extension name.
   */
  protected function process(array $all_files) {
    $files = array();
    // Duplicate files found in later search directories take precedence over
    // earlier ones; they replace the extension in the existing $files array.
    foreach ($all_files as $file) {
      $files[$file->getName()] = $file;
    }
    return $files;
  }

  /**
   * Recursively scans a base directory for the requested extension type.
   *
   * @param string $dir
   *   A relative base directory path to scan, without trailing slash.
   * @param bool $include_tests
   *   Whether to include test extensions. If FALSE, all 'tests' directories are
   *   excluded in the search.
   *
   * @return array
   *   An associative array whose keys are extension type names and whose values
   *   are associative arrays of \Drupal\Core\Extension\Extension objects, keyed
   *   by absolute path name.
   *
   * @see \Drupal\Core\Extension\Discovery\RecursiveExtensionFilterIterator
   */
  protected function scanDirectory($dir, $include_tests) {
    $files = array();

    // In order to scan top-level directories, absolute directory paths have to
    // be used (which also improves performance, since any configured PHP
    // include_paths will not be consulted). Retain the relative originating
    // directory being scanned, so relative paths can be reconstructed below
    // (all paths are expected to be relative to $this->root).
    $dir_prefix = ($dir == '' ? '' : "$dir/");
    $absolute_dir = ($dir == '' ? $this->root : $this->root . "/$dir");

    if (!is_dir($absolute_dir)) {
      return $files;
    }
    // Use Unix paths regardless of platform, skip dot directories, follow
    // symlinks (to allow extensions to be linked from elsewhere), and return
    // the RecursiveDirectoryIterator instance to have access to getSubPath(),
    // since SplFileInfo does not support relative paths.
    $flags = \FilesystemIterator::UNIX_PATHS;
    $flags |= \FilesystemIterator::SKIP_DOTS;
    $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
    $flags |= \FilesystemIterator::CURRENT_AS_SELF;
    $directory_iterator = new \RecursiveDirectoryIterator($absolute_dir, $flags);

    // Filter the recursive scan to discover extensions only.
    // Important: Without a RecursiveFilterIterator, RecursiveDirectoryIterator
    // would recurse into the entire filesystem directory tree without any kind
    // of limitations.
    $filter = new RecursiveExtensionFilterIterator($directory_iterator);
    $filter->acceptTests($include_tests);

    // The actual recursive filesystem scan is only invoked by instantiating the
    // RecursiveIteratorIterator.
    $iterator = new \RecursiveIteratorIterator($filter,
      \RecursiveIteratorIterator::LEAVES_ONLY,
      // Suppress filesystem errors in case a directory cannot be accessed.
      \RecursiveIteratorIterator::CATCH_GET_CHILD
    );

    foreach ($iterator as $key => $fileinfo) {
      // All extension names in Drupal have to be valid PHP function names due
      // to the module hook architecture.
      if (!preg_match(static::PHP_FUNCTION_PATTERN, $fileinfo->getBasename('.info.yml'))) {
        continue;
      }

      if ($this->fileCache && $cached_extension = $this->fileCache->get($fileinfo->getPathName())) {
        $files[$cached_extension->getType()][$key] = $cached_extension;
        continue;
      }

      // Determine extension type from info file.
      $type = FALSE;
      $file = $fileinfo->openFile('r');
      while (!$type && !$file->eof()) {
        preg_match('@^type:\s*(\'|")?(\w+)\1?\s*$@', $file->fgets(), $matches);
        if (isset($matches[2])) {
          $type = $matches[2];
        }
      }
      if (empty($type)) {
        continue;
      }
      $name = $fileinfo->getBasename('.info.yml');
      $pathname = $dir_prefix . $fileinfo->getSubPathname();

      // Determine whether the extension has a main extension file.
      // For theme engines, the file extension is .engine.
      if ($type == 'theme_engine') {
        $filename = $name . '.engine';
      }
      // For profiles/modules/themes, it is the extension type.
      else {
        $filename = $name . '.' . $type;
      }
      if (!file_exists(dirname($pathname) . '/' . $filename)) {
        $filename = NULL;
      }

      $extension = new Extension($this->root, $type, $pathname, $filename);

      // Track the originating directory for sorting purposes.
      $extension->subpath = $fileinfo->getSubPath();
      $extension->origin = $dir;

      $files[$type][$key] = $extension;

      if ($this->fileCache) {
        $this->fileCache->set($fileinfo->getPathName(), $extension);
      }
    }
    return $files;
  }

  /**
   * Returns a parser for .info.yml files.
   *
   * @return \Drupal\Core\Extension\InfoParser
   *   The InfoParser instance.
   */
  protected function getInfoParser() {
    if (!isset($this->infoParser)) {
      $this->infoParser = new InfoParser();
    }
    return $this->infoParser;
  }

}


text:
<?php
require_once dirname(__FILE__) . '/util.php';

?>/**
 * standard_new_allocator.h
 *
 *  Created on: 2014年4月1日
 *      Author: owent
 *  @date <?php
date_default_timezone_set('UTC');
echo date('Y-m-d') . PHP_EOL;
?>
 *  Released under the MIT license
 */

#ifndef _COTASK_CORE_STANDARD_NEW_ALLOCATOR_H_
#define _COTASK_CORE_STANDARD_NEW_ALLOCATOR_H_

#include <libcopp/utils/features.h>

namespace cotask {
    namespace core {
        class standard_new_allocator
        {
        public:

#if defined(COPP_MACRO_ENABLE_VARIADIC_TEMPLATE) && COPP_MACRO_ENABLE_VARIADIC_TEMPLATE
            /**
             * @brief allocate a object
             * @param args construct parameters
             * @return pointer of new object
             */
            template<typename Ty, typename... TARGS>
            static Ty* allocate(Ty*, TARGS... args) {
                Ty* ret = new Ty(std::forward<TARGS>(args)...);
                return ret;
            }
#else
<?php
function gen_allocate_func($param_num) {?>
            /**
             * @brief allocate a object with <?php echo $param_num; ?> parameter(s).
<?php echo gen_template_params_comment($param_num, '            '); ?>
             * @return pointer of new object
             */
            template< typename Ty<?php echo gen_template_params_typename($param_num, ','); ?> >
            static Ty* allocate(Ty*<?php echo gen_template_params_type_param($param_num, ', '); ?>) {
                Ty* ret = new Ty(<?php echo gen_template_params_use_param($param_num); ?>);
                return ret;
            }

<?php
}

for ($i = 0; $i < $max_param_number; ++ $i) {
	gen_allocate_func($i);
}
?>
#endif
            template<typename Ty>
            static void deallocate(Ty* pt){
                delete pt;
            }
        };
    }
}

#endif /* STANDARD_NEW_ALLOCATOR_H_ */


text:
package editor;

import editor.util.EditorUtilities;
import gw.util.GosuObjectUtil;
import gw.util.GosuStringUtil;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Provides a simple copy buffer.
 *
 * @author cgross
 */
public class CopyBuffer
{
  List<String> _buffer = new ArrayList<>();

  private static final CopyBuffer INSTANCE = new CopyBuffer();
  private static final int MAX_SIZE = 10;
  private WindowListener _adapter;

  CopyBuffer()
  {
    _adapter =
      new WindowAdapter()
      {
        public void windowActivated( WindowEvent e )
        {
          if( e.getOppositeWindow() == null )
          {
            captureState();
          }
        }
      };
  }

  public static CopyBuffer instance()
  {
    return INSTANCE;
  }

  public void captureState()
  {
    try
    {
      if( !EditorUtilities.getClipboard().isDataFlavorAvailable( DataFlavor.stringFlavor ) )
      {
        return;
      }
    }
    catch( Exception e )
    {
      // sometimes the clipboard doesn't open
      return;
    }

    Transferable contents = editor.util.EditorUtilities.getClipboard().getContents( this );
    addToCopyBuffer( contents );
  }

  void addToCopyBuffer( Transferable contents )
  {
    try
    {
      String element = String.valueOf( contents.getTransferData( DataFlavor.stringFlavor ) );
      if( !GosuStringUtil.isEmpty( element ) )
      {
        if( _buffer.size() == 0 || !GosuObjectUtil.equals( element, _buffer.get( 0 ) ) )
        {
          _buffer.add( 0, element );
          if( _buffer.size() > MAX_SIZE )
          {
            _buffer.remove( MAX_SIZE );
          }
        }
      }
    }
    catch( Exception e )
    {
      editor.util.EditorUtilities.handleUncaughtException( "Unable to copy from clipboard", e );
      //igmore
    }
  }

  public List<String> getCopyBuffer()
  {
    return _buffer;
  }

  public void notifyOfPaste( int index )
  {
    if( index >= 0 && index < MAX_SIZE )
    {
      Collections.swap( _buffer, 0, index );
    }
  }

  public WindowListener getWindowAdapter()
  {
    return _adapter;
  }

}


text:
from collections import namedtuple
from io import BytesIO
from tarfile import TarFile
from tempfile import NamedTemporaryFile
from typing import IO
from typing import Callable
from typing import Iterable
from typing import Iterator
from typing import Optional
from typing import Tuple

from cached_property import cached_property
from libcloud.storage.base import Container
from libcloud.storage.base import Object
from libcloud.storage.base import StorageDriver
from libcloud.storage.providers import get_driver
from libcloud.storage.types import ContainerAlreadyExistsError
from libcloud.storage.types import ContainerDoesNotExistError
from libcloud.storage.types import ObjectDoesNotExistError
from libcloud.storage.types import Provider
from xtarfile import open as tarfile_open
from xtarfile.xtarfile import SUPPORTED_FORMATS

from opwen_email_server.utils.log import LogMixin
from opwen_email_server.utils.serialization import from_msgpack_bytes
from opwen_email_server.utils.serialization import gunzip_bytes
from opwen_email_server.utils.serialization import gzip_bytes
from opwen_email_server.utils.serialization import to_msgpack_bytes
from opwen_email_server.utils.temporary import create_tempfilename
from opwen_email_server.utils.temporary import removing

AccessInfo = namedtuple('AccessInfo', ['account', 'key', 'container'])

Upload = Tuple[str, Iterable[dict], Callable[[dict], bytes]]
Download = Tuple[str, Callable[[bytes], dict]]

class _Container:

    def __init__(self, wrapped: Container):
        self._wrapped = wrapped

    def get_object(self, object_name: str) -> Object:
        return self._wrapped.get_object(object_name)

    def iterate_objects(self, prefix: Optional[str] = None) -> Iterable[Object]:
        return self._wrapped.iterate_objects(prefix)

    def upload_object(self, file_path: str, object_name: str) -> Object:
        return self._wrapped.upload_object(file_path, object_name)

    def upload_object_via_stream(self, iterator: Iterator[bytes], object_name: str) -> Object:
        return self._wrapped.upload_object_via_stream(iterator, object_name)

class _CaseInsensitiveContainer(_Container):

    def get_object(self, object_name: str) -> Object:
        object_name = object_name.lower()
        return super().get_object(object_name)

    def iterate_objects(self, prefix: Optional[str] = None) -> Iterable[Object]:
        prefix = prefix.lower() if prefix is not None else None
        return super().iterate_objects(prefix)

    def upload_object(self, file_path: str, object_name: str) -> Object:
        object_name = object_name.lower()
        return super().upload_object(file_path, object_name)

    def upload_object_via_stream(self, iterator: Iterator[bytes], object_name: str) -> Object:
        object_name = object_name.lower()
        return super().upload_object_via_stream(iterator, object_name)

class _BaseAzureStorage(LogMixin):

    def __init__(self,
                 account: str,
                 key: str,
                 container: str,
                 provider: str,
                 host: Optional[str] = None,
                 secure: bool = True,
                 case_sensitive: bool = True) -> None:
        self._account = account
        self._key = key
        self._container = container
        self._provider = getattr(Provider, provider)
        self._host = host or None
        self._secure = secure
        self._case_sensitive = case_sensitive

    @cached_property
    def _driver(self) -> StorageDriver:
        driver = get_driver(self._provider)
        return driver(self._account, self._key, host=self._host, secure=self._secure)

    @cached_property
    def _client(self) -> _Container:
        try:
            container = self._driver.get_container(self._container)
        except ContainerDoesNotExistError:
            try:
                container = self._driver.create_container(self._container)
            except ContainerAlreadyExistsError:
                container = self._driver.get_container(self._container)
        return _Container(container) if self._case_sensitive else _CaseInsensitiveContainer(container)

    @property
    def _generated_suffix(self) -> str:
        return ''

    def access_info(self) -> AccessInfo:
        return AccessInfo(
            account=self._account,
            key=self._key,
            container=self._container,
        )

    def ensure_exists(self):
        # noinspection PyStatementEffect
        self._client

    def delete(self, resource_id: str):
        try:
            resource = self._client.get_object(resource_id)
        except ObjectDoesNotExistError:
            self.log_warning('deleted missing %s', resource_id)
        else:
            resource.delete()
            self.log_debug('deleted %s', resource_id)

    def iter(self, prefix: Optional[str] = None) -> Iterator[str]:
        resources = self._client.iterate_objects(prefix=prefix)

        for resource in resources:
            resource_id = resource.name

            if prefix is not None:
                resource_id = resource_id[len(prefix):]

            if resource_id.endswith(self._generated_suffix):
                resource_id = resource_id[:-len(self._generated_suffix)]

            yield resource_id
            self.log_debug('listed %s', resource_id)

class AzureFileStorage(_BaseAzureStorage):

    def store_file(self, resource_id: str, path: str):
        self.log_debug('storing file %s at %s', path, resource_id)
        self._client.upload_object(path, resource_id)

    def fetch_file(self, resource_id: str) -> str:
        resource = self._client.get_object(resource_id)
        path = create_tempfilename(resource_id)
        resource.download(path)
        self.log_debug('fetched file %s from %s', path, resource_id)
        return path

class _AzureBytesStorage(_BaseAzureStorage):
    _compression = 'gz'

    def store_bytes(self, resource_id: str, content: bytes):
        filename = self._to_filename(resource_id)
        self.log_debug('storing %d bytes at %s', len(content), filename)
        upload = BytesIO()
        upload.write(gzip_bytes(content))
        upload.seek(0)
        self._client.upload_object_via_stream(upload, filename)

    def fetch_bytes(self, resource_id: str) -> bytes:
        filename = self._to_filename(resource_id)
        download = BytesIO()
        resource = self._client.get_object(filename)
        for chunk in resource.as_stream():
            download.write(chunk)
        download.seek(0)
        content = gunzip_bytes(download.read())
        self.log_debug('fetched %d bytes from %s', len(content), filename)
        return content

    def delete(self, resource_id: str):
        filename = self._to_filename(resource_id)
        super().delete(filename)

    def _to_filename(self, resource_id: str) -> str:
        if resource_id.endswith(self._generated_suffix):
            return resource_id
        return f'{resource_id}{self._generated_suffix}'

    @property
    def _generated_suffix(self) -> str:
        return f'.{self._extension}.{self._compression}'

    @property
    def _extension(self) -> str:
        raise NotImplementedError  # pragma: no cover

class AzureTextStorage(_AzureBytesStorage):
    _encoding = 'utf-8'
    _extension = 'txt'

    def store_text(self, resource_id: str, text: str):
        content = text.encode(self._encoding)
        self.store_bytes(resource_id, content)

    def fetch_text(self, resource_id: str) -> str:
        content = self.fetch_bytes(resource_id)
        return content.decode(self._encoding)

class AzureObjectsStorage(LogMixin):
    _compression = 'zstd'
    _compression_level = 20

    def __init__(self, file_storage: AzureFileStorage, resource_id_source: Callable[[], str]):
        self._file_storage = file_storage
        self._resource_id_source = resource_id_source

    def _open_archive_file(self, archive: TarFile, name: str) -> IO[bytes]:
        while True:
            member = archive.next()
            if member is None:
                break
            if member.name == name:
                fobj = archive.extractfile(member)
                if fobj is None:
                    break
                return fobj

        # noinspection PyProtectedMember
        raise ObjectDoesNotExistError(f'File {name} is missing in archive', self._file_storage._driver, archive.name)

    @classmethod
    def _open_archive(cls, path: str, mode: str) -> TarFile:
        extension_index = path.rfind('.')
        if extension_index > -1:
            compression = path[extension_index + 1:]
        else:
            compression = cls._compression

        kwargs = {}
        if compression == 'zstd' and mode == 'w':
            kwargs['level'] = cls._compression_level

        mode = f'{mode}|{compression}'
        return tarfile_open(path, mode, **kwargs)

    def access_info(self) -> AccessInfo:
        return self._file_storage.access_info()

    def ensure_exists(self):
        return self._file_storage.ensure_exists()

    @classmethod
    def compression_formats(cls) -> Iterable[str]:
        return SUPPORTED_FORMATS

    def store_objects(self, upload: Upload, compression: Optional[str] = None) -> Optional[str]:

        compression = compression or self._compression

        resource_id = f'{self._resource_id_source()}.tar.{compression}'

        name, objs, encoder = upload

        num_stored = 0
        with removing(create_tempfilename(resource_id)) as path:
            with self._open_archive(path, 'w') as archive:
                with NamedTemporaryFile() as fobj:
                    num_bytes = 0
                    for obj in objs:
                        encoded = encoder(obj)
                        fobj.write(encoded)
                        num_bytes += len(encoded)
                        num_stored += 1

                    if num_bytes > 0:
                        fobj.seek(0)
                        archive.add(fobj.name, name)

            if num_stored > 0:
                self._file_storage.store_file(resource_id, path)

        self.log_debug('stored %d objects at %s', num_stored, resource_id)
        return resource_id if num_stored > 0 else None

    def fetch_objects(self, resource_id: str, download: Download) -> Iterable[dict]:

        name, decoder = download

        num_fetched = 0
        with removing(self._file_storage.fetch_file(resource_id)) as path:
            with self._open_archive(path, 'r') as archive:
                fobj = self._open_archive_file(archive, name)
                for encoded in fobj:
                    obj = decoder(encoded)
                    if obj is None:
                        continue
                    num_fetched += 1
                    yield obj
        self.log_debug('fetched %d objects from %s', num_fetched, resource_id)

    def delete(self, resource_id: str):
        self._file_storage.delete(resource_id)

class AzureObjectStorage(_AzureBytesStorage):
    _extension = 'msgpack'

    def fetch_object(self, resource_id: str) -> dict:
        serialized = self.fetch_bytes(resource_id)
        return from_msgpack_bytes(serialized)

    def store_object(self, resource_id: str, obj: dict) -> None:
        serialized = to_msgpack_bytes(obj)
        self.store_bytes(resource_id, serialized)