text:
<?php $this->load->view('include/header.php'); ?>

<?php $this->load->view('include/navbar.php'); ?>
<?php $this->load->view('include/sidebar.php'); ?>

                            Ajouter un site web

                                <form class="form-horizontal " id="form-add-website" method="post" action="<?php echo site_url('/add-website/submit'); ?>">

 General Information

                                        Nom (required)

                                          <input class="form-control" type="text" name="nom" placeholder="Nom" required />

                                        URL (required)

                                            <input class="form-control" type="text" name="url" placeholder="Site Web" required />

                                        Langages (optional)

                                          <select name="languages" class="form-control">
                                          <?php foreach ($all_languages->result() as $row){  ?>
                                              <option value="<?php echo $row->l_id; ?>"><?php echo $row->l_title; ?></option>
                                          <?php } ?>
                                          </select>

                                        Catégories (optional)

                                          <select name="categories" class="form-control">
                                          <?php foreach ($all_categories->result() as $row){  ?>
                                              <option value="<?php echo $row->c_id; ?>"><?php echo $row->c_title; ?></option>
                                          <?php } ?>
                                          </select>

 FTP

                                        Host FTP

                                            <input class="form-control" type="text" name="hostftp" placeholder="Host FTP">

                                        Login FTP

                                          <input class="form-control" type="text" name="loginftp" placeholder="Login FTP">

                                        Password FTP

                                            <input class="form-control" type="text" name="passwordftp" placeholder="Mot de Passe FTP">

 SQL

                                        Host SQL

                                            <input class="form-control" type="text" name="hostsql" placeholder="Host SQL">

                                        Base de Donnée

                                            <input class="form-control" type="text" name="namedatabase" placeholder="Nom de la base">

                                        Login SQL

                                            <input class="form-control" type="text" name="loginsql" placeholder="Login SQL">

                                        Password SQL

                                            <input class="form-control" type="text" name="passwordsql" placeholder="Mot de Passe SQL">

 Back Office

                                        Login Back Office

                                            <input class="form-control" type="text" name="adminlogin" placeholder="Admin Login">

                                        Password Back Office

                                            <input class="form-control" type="text" name="adminpassword" placeholder="Admin Mot de Passe">

                                          <button class="btn btn-primary" type="submit">Save</button>
                                          <button class="btn btn-default" type="button">Cancel</button>

                                </form>

Votre site web a bien été enregistré !

<?php $this->load->view('include/footer.php'); ?>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace TwitchLeecher.Gui.Views
{
    public partial class LogView : UserControl
    {
        public LogView()
        {
            InitializeComponent();

            IsVisibleChanged += SearchView_IsVisibleChanged;
        }

        private void SearchView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() =>
                {
                    txtLog.CaretIndex = txtLog.Text.Length;
                    txtLog.ScrollToEnd();
                }));
            }
        }
    }
}


text:
/******************************************************************************
 *
 *
 * @file top.cpp
 *
 * HLS Description of the LFC-W1A2 overlay, with axi-lite based parameter loading (DoMemInit)
 * and  dataflow architecture of the image inference (DoCompute)
 *
 *
 *****************************************************************************/

#include "config.h"
#include "bnn-library.h"
#include "dma.h"
#include "fclayer.h"
#include "weights.hpp"
#include "activations.hpp"
#include "interpret.hpp"

static BinaryWeights<L0_SIMD,L0_PE,L0_WMEM> weights0;
static BinaryWeights<L1_SIMD,L1_PE,L1_WMEM> weights1;
static BinaryWeights<L2_SIMD,L2_PE,L2_WMEM> weights2;
static BinaryWeights<L3_SIMD,L3_PE,L3_WMEM> weights3;

static ThresholdsActivation<L0_TMEM,L0_PE,L0_API,ap_int<16>,ap_int<L0_API>,-1> threshs0;
static ThresholdsActivation<L1_TMEM,L1_PE,L1_API,ap_int<16>,ap_int<L1_API>,-1> threshs1;
static ThresholdsActivation<L2_TMEM,L2_PE,L2_API,ap_int<16>,ap_int<L2_API>,-1> threshs2;
static ThresholdsActivation<L3_TMEM,L3_PE,L3_API,ap_int<16>,ap_int<L3_API>>    threshs3;

unsigned int paddedSizeHW(unsigned int in, unsigned int padTo) {
  if(in % padTo == 0) {
    return in;
  } else {
    return in + padTo - (in % padTo);
  }
}

void DoMemInit(unsigned int targetLayer, unsigned int targetMem, unsigned int targetInd, unsigned int targetThresh, ap_uint<64> val) {
  switch(targetLayer) {
    case 0:
      weights0.m_weights[targetMem][targetInd] = val;
      break;
    case 1:
      threshs0.m_thresholds[targetMem][targetInd][targetThresh] = val;
      break;
    case 2:
      weights1.m_weights[targetMem][targetInd] = val;
      break;
    case 3:
      threshs1.m_thresholds[targetMem][targetInd][targetThresh] = val;
      break;
    case 4:
      weights2.m_weights[targetMem][targetInd] = val;
      break;
    case 5:
      threshs2.m_thresholds[targetMem][targetInd][targetThresh] = val;
      break;
    case 6:
      weights3.m_weights[targetMem][targetInd] = val;
      break;
    case 7:
      threshs3.m_thresholds[targetMem][targetInd][targetThresh] = val;
      break;
  }
}

void DoCompute(ap_uint<64> *in, ap_uint<64> *out, const unsigned int numReps) {

  hls::stream<ap_uint<64>> memInStrm("DoCompute.memInStrm");
  hls::stream<ap_uint<L0_PE * (L0_API + L0_APF)>>  inter0("DoCompute.inter0");
  hls::stream<ap_uint<L1_PE * (L1_API + L1_APF)>>  inter1("DoCompute.inter1");
  hls::stream<ap_uint<L2_PE * (L2_API + L2_APF)>>  inter2("DoCompute.inter2");
  hls::stream<ap_uint<64>> memOutStrm("DoCompute.memOutStrm");

  // TODO: These values are just for comparability and produce the same amount
  //       of FIFO buffer as in the preceding design.
  //       If the resources allow, these depths should eventually go up to
  //       Lx_DEPTH = Lx_MH/Lx_PE for a smooth operation.
  unsigned const  L0_DEPTH = 512 / L0_PE;
  unsigned const  L1_DEPTH = 512 / L1_PE;
  unsigned const  L2_DEPTH = 512 / L2_PE;

#pragma HLS DATAFLOW
#pragma HLS stream depth=1024 variable=memInStrm     	// mask memory latency
#pragma HLS stream depth=L0_DEPTH variable=inter0
#pragma HLS stream depth=L1_DEPTH variable=inter1
#pragma HLS stream depth=L2_DEPTH variable=inter2
#pragma HLS stream depth=1024 variable=memOutStrm		// mask memory latency

  const unsigned int inBits = 28 * 28;
  const unsigned int inBitsPadded = 832; // paddedSizeHW(inBits, 64)
  const unsigned int inBytesPadded = inBitsPadded / 8;
  const unsigned int outBits = 64;
  const unsigned int outBitsPadded = 64; // paddedSizeHW(outBits, 64)
  const unsigned int outBytesPadded = outBitsPadded / 8;
  const unsigned int inWordsPerImg = inBitsPadded / 64;
  const unsigned int outWordsPerImg = outBitsPadded / 64;

  Mem2Stream_Batch<64, inBytesPadded>(in, memInStrm, numReps);
  StreamingFCLayer_Batch<L0_MW, L0_MH, L0_SIMD, L0_PE, Recast<Binary>, Slice<ap_int<2>>, Recast<Binary>>
    (memInStrm, inter0, weights0, threshs0, numReps, ap_resource_lut());
  StreamingFCLayer_Batch<L1_MW, L1_MH, L1_SIMD, L1_PE, Slice<ap_int<2>>, Slice<ap_int<2>>, Recast<Binary>>
    (inter0, inter1, weights1, threshs1, numReps, ap_resource_lut());
  StreamingFCLayer_Batch<L2_MW, L2_MH, L2_SIMD, L2_PE, Slice<ap_int<2>>, Slice<ap_int<2>>, Recast<Binary>>
    (inter1, inter2, weights2, threshs2, numReps, ap_resource_lut());
  StreamingFCLayer_Batch<L3_MW, L3_MH, L3_SIMD, L3_PE, Slice<ap_int<2>>, Slice<ap_int<1>>, Recast<Binary>>
    (inter2, memOutStrm, weights3, threshs3, numReps, ap_resource_lut());
  Stream2Mem_Batch<64, outBytesPadded>(memOutStrm, out, numReps);
}

void BlackBoxJam(ap_uint<64> *in, ap_uint<64> *out, bool doInit,
		         unsigned int targetLayer, unsigned int targetMem,
		         unsigned int targetInd, unsigned int targetThresh, ap_uint<64> val, unsigned int numReps) {
// pragmas for MLBP jam interface
// signals to be mapped to the AXI Lite slave port
#pragma HLS INTERFACE s_axilite port=return bundle=control
#pragma HLS INTERFACE s_axilite port=doInit bundle=control
#pragma HLS INTERFACE s_axilite port=targetLayer bundle=control
#pragma HLS INTERFACE s_axilite port=targetMem bundle=control
#pragma HLS INTERFACE s_axilite port=targetInd bundle=control
#pragma HLS INTERFACE s_axilite port=targetThresh bundle=control
#pragma HLS INTERFACE s_axilite port=val bundle=control
#pragma HLS INTERFACE s_axilite port=numReps bundle=control
// signals to be mapped to the AXI master port (hostmem)
#pragma HLS INTERFACE m_axi offset=slave port=in bundle=hostmem depth=256
#pragma HLS INTERFACE s_axilite port=in bundle=control
#pragma HLS INTERFACE m_axi offset=slave port=out bundle=hostmem depth=256
#pragma HLS INTERFACE s_axilite port=out bundle=control

// partition PE arrays
#pragma HLS ARRAY_PARTITION variable=weights0.m_weights complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs0.m_thresholds complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs0.m_thresholds complete dim=3
#pragma HLS ARRAY_PARTITION variable=weights1.m_weights complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs1.m_thresholds complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs1.m_thresholds complete dim=3
#pragma HLS ARRAY_PARTITION variable=weights2.m_weights complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs2.m_thresholds complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs2.m_thresholds complete dim=3
#pragma HLS ARRAY_PARTITION variable=weights3.m_weights complete dim=1
#pragma HLS ARRAY_PARTITION variable=threshs3.m_thresholds complete dim=1

  if (doInit) {
    DoMemInit(targetLayer, targetMem, targetInd, targetThresh, val);
  } else {
    DoCompute(in, out, numReps);
  }
}


text:
import json
from pathlib import Path
from typing import Optional

from azure.ai.ml._local_endpoints.utilities.wsl_utility import get_wsl_path, in_wsl
from azure.ai.ml._local_endpoints.vscode_debug.devcontainer_properties import (
    AppPort,
    Build,
    ContainerEnv,
    Extensions,
    ForwardPorts,
    Image,
    Mounts,
    OverrideCommand,
    RunArgs,
    Settings,
)
from azure.ai.ml.exceptions import ErrorCategory, ErrorTarget, ValidationException

class DevContainerResolver:
    """DevContainerResolver class represents the collection of properties of a
    devcontainer.json.

    Reference: https://code.visualstudio.com/docs/remote/devcontainerjson-reference
    """

    def __init__(
        self,
        image: str = None,
        dockerfile_path: str = "../Dockerfile",
        build_context: str = None,
        build_target: str = None,
        environment: dict = None,
        mounts: dict = None,
        labels: dict = None,
        port: int = 5001,
    ):
        """Resolves the devcontainer.json based on provided properties.

        :param image: name of local deployment
        :type image: str
        :param dockerfile_path: path to Dockerfile relative to devcontainer.json
        :type dockerfile_path: str
        :param build_context: build directory on user's local system
        :type build_context: str
        :param build_target: directory on user's local system where Dockerfile is located
        :type build_target: str
        :param environment: dictionary of docker environment variables to set in dev container
        :type environment: dict
        :param mounts: dictionary of volumes to mount to dev container
        :type mounts: dict
        :param labels: dictionary of labels to add to dev container
        :type labels: dict
        :param port: Port exposed in Docker image for AzureML service.
        :type port: int
        """
        if not (image or (build_context and dockerfile_path)):
            msg = "Must provide image or build context for devcontainer.json"
            raise ValidationException(
                message=msg,
                no_personal_data_message=msg,
                target=ErrorTarget.LOCAL_ENDPOINT,
                error_category=ErrorCategory.USER_ERROR,
            )
        self._local_path: Optional[str] = None
        self._properties: Optional[dict] = {}

        self._image: str = image
        self._dockerfile_path: str = dockerfile_path
        self._build_context: str = build_context
        self._build_target: str = build_target
        self._environment: dict = environment
        self._mounts: list = _reformat_mounts(mounts) if mounts else mounts
        self._labels: list = _reformat_labels(labels) if labels else labels
        self._port = port
        self._construct()

    @property
    def local_path(self) -> Optional[str]:
        """Returns the local path of the devcontainer.json.

        :return: str
        """
        return self._local_path

    def _construct(self) -> None:
        """Constructs the devcontainer properties based on attributes."""
        if self._image:
            self._properties = Image(image=self._image).to_dict()
        elif self._dockerfile_path and self._build_context:
            self._properties = Build(
                dockerfile_path=self._dockerfile_path,
                build_context=self._build_context,
                target=self._build_target,
            ).to_dict()

        self._properties.update(OverrideCommand().to_dict())
        self._properties.update(Extensions().to_dict())
        self._properties.update(Settings().to_dict())

        if self._environment:
            self._properties.update(ContainerEnv(environment_variables=self._environment).to_dict())
        if self._mounts:
            self._properties.update(Mounts(mounts=self._mounts).to_dict())
        if self._labels:
            self._properties.update(RunArgs(labels=self._labels).to_dict())
        if self._port:
            self._properties.update(AppPort(port=self._port).to_dict())
            self._properties.update(ForwardPorts(port=self._port).to_dict())

    def write_file(self, directory_path: str) -> None:
        """Writes this devcontainer.json to provided directory.

        :param directory_path: absolute path of local directory to write devcontainer.json.
        :type directory_path: str
        """
        self._local_path = get_wsl_path(directory_path) if in_wsl() else directory_path

        file_path = _get_devcontainer_file_path(directory_path=directory_path)
        with open(file_path, "w") as f:
            f.write(f"{json.dumps(self._properties, indent=4)}\n")

def _reformat_mounts(mounts: dict) -> list:
    """Reformat mounts from Docker format to DevContainer format.

    :param mounts: Dictionary with mount information for Docker container. For example,
        {
            "<unique mount key>": {
                "<local_source>": {
                    "<mount type i.e. bind>": "<container_dest>"
                }
            }
        }
    :type mounts: dict
    :returns dict: "mounts": ["source=${localWorkspaceFolder}/app-scripts,
        target=/usr/local/share/app-scripts,type=bind,consistency=cached"]
    """
    devcontainer_mounts = []
    for mount_dict in mounts.values():
        for source, dest in mount_dict.items():
            for mount_type, container_dest in dest.items():
                devcontainer_mounts.append(f"source={source},target={container_dest},type={mount_type}")
    return devcontainer_mounts

def _reformat_labels(labels: dict) -> list:
    """Reformat labels from Docker format to DevContainer format.

    :param labels: Dictionary with label information for Docker container. For example,
        {
            "key": "value",
            "key1": "value1"
        }
    :type labels: dict
    :returns dict: ["--label=key=value", "--label=key1=value1"]
    """
    devcontainer_labels = []
    for key, value in labels.items():
        devcontainer_labels.append(f"--label={key}={value}")
    return devcontainer_labels

def _get_devcontainer_file_path(directory_path: str) -> str:
    """Returns the path of the devcontainer in relation to provided
    directory path.

    :param directory_path: absolute path of local directory to write devcontainer.json.
    :type directory_path: str
    """
    devcontainer_path = Path(directory_path, ".devcontainer")
    devcontainer_path.mkdir(parents=True, exist_ok=True)
    file_path = str(Path(devcontainer_path, "devcontainer.json").resolve())
    return file_path


text:
details-shim
============

A pure JavaScript (no dependencies) solution to make HTML5
Details/Summary tags work in unsupportive browsers

Usage
=====

Include details-shim.js anywhere in your page, it runs on load.
Include details-shim.css (or its contents) in your styles.

Support
=======

Tested successfully in FireFox Win/Mac/Lin.
Non-interfering in Chrome Win/Mac/Lin, which supports details/summary.
Non-interfering in Safari Win/Mac, which supports details/summary.
Tested successfully in Internet Explorer 9.
Tested mostly successfully in Internet Explorer 8 with html5shiv.
 (IE doesn't like the unicode css :before content)
Tested unsuccessfully in IE7-, considered unsupported

Known Issues
============

FireFox changes <details open> to <details open="">
Safari supports <details> natively, but treats `open=""` as `open="open"`

License
=======

Released under MIT license, see included LICENSE.txt
or http://opensource.org/licenses/MIT


text:
/**
 *
 */
package gov.nih.nci.calims2.taglib.page;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import gov.nih.nci.calims2.uic.html.CompositeTag;
import gov.nih.nci.calims2.uic.html.ContentTag;
import gov.nih.nci.calims2.uic.html.HtmlElement;
import gov.nih.nci.calims2.uic.html.Tag;
import gov.nih.nci.calims2.uic.html.ContentTag.ContentType;

/**
 * Helper class to manage scripts in the PageTag.
 *
 * @author viseem
 *
 */
class PageScriptManager implements Serializable {

  private static final long serialVersionUID = -8055340745547362981L;

  private List<ScriptDescriptor> descriptors = new ArrayList<ScriptDescriptor>();

  /**
   * Adds a script to the page if it does not exist yet.
   *
   * @param type The type of script
   * @param source The source of the script
   * @param body The body of the script
   */
  public void addScript(String type, String source, String body) {
    ScriptDescriptor newDescriptor = new ScriptDescriptor(type, source, body);
    if (source != null) {
      for (ScriptDescriptor descriptor : descriptors) {
        if (source.equals(descriptor.getSource())) {
          return;
        }
      }
    }
    descriptors.add(newDescriptor);
  }

  /**
   * Renders the scripts in the given head tag.
   * @param headTag The head tag in which the rendering must be included.
   * @param context The name of the application context.
   */
  public void renderScripts(Tag headTag, String context) {
    for (ScriptDescriptor descriptor : descriptors) {
      Tag scriptTag = headTag.addChild(new CompositeTag(HtmlElement.SCRIPT));
      scriptTag.addAttribute("type", descriptor.getType());
      String source = descriptor.getSource();
      if (source != null) {
        scriptTag.addAttribute("src", (source.startsWith("/")) ? context + source : source);
      } else {
        ContentTag bodyTag = scriptTag.addChild(new ContentTag(descriptor.getBody()));
        bodyTag.setContentType(ContentType.COMMENTED_CDATA);
      }
    }

  }
}


text:
print "\nGenerating automated scripts for NetWare...\n\n\n";

use File::Basename;
use File::Copy;

chdir '/perl/scripts/';
$DirName = "t";

# These scripts have problems (either abend or hang) as of now (11 May 2001).
# So, they are commented out in the corresponding auto scripts, io.pl and lib.pl
@ScriptsNotUsed = ("t/io/openpid.t", "t/lib/filehandle.t", "t/lib/memoize/t/expire_module_t.t", "t/lib/NEXT/t/next.t", "t/lib/Math/BigInt/t/require.t", "t/ext/B/t/debug.t", "t/lib/IPC/Open3.t", "t/ext/B/t/showlex.t", "t/op/subst_wamp.t", "t/uni/upper.t", "t/lib/Net/t/ftp.t", "t/op/sort.t", "t/ext/POSIX/t/posix.t", "t/lib/CPAN/t/loadme.t", "t/lib/CPAN/t/vcmp.t");

opendir(DIR, $DirName);
@Dirs = readdir(DIR);
close(DIR);
foreach $DirItem(@Dirs)
{
	$DirItem1 = $DirName."/".$DirItem;
	push @DirNames, $DirItem1;	# All items under  $DirName  folder is copied into an array.

	if(-d $DirItem1)
	{	# If an item is a folder, then open it further.

		# Intemediary automated script like base.pl, lib.pl, cmd.pl etc.
		$IntAutoScript = "t/".$DirItem.".pl";

		# Open once in write mode since later files are opened in append mode,
		# and if there already exists a file with the same name, all further opens
		# will append to that file!!
		open(FHW, "> $IntAutoScript") or die "Unable to open the file,  $IntAutoScript  for writing.\n";
		seek(FHW, 0, 0);	# seek to the beginning of the file.
		close FHW;			# close the file.
	}
}

print "Generating  t/nwauto.pl ...\n\n\n";

open(FHWA, "> t/nwauto.pl") or die "Unable to open the file,  t/nwauto.pl  for writing.\n";
seek(FHWA, 0, 0);	# seek to the beginning of the file.

$version = sprintf("%vd",$^V);
print FHWA "\n\nprint \"Automated Unit Testing of Perl$version for NetWare\\n\\n\\n\"\;\n\n\n";

foreach $FileName(@DirNames)
{
	$index = 0;
	if(-d $FileName)
	{	# If an item is a folder, then open it further.

		$dir = dirname($FileName);		# Get the folder name

		foreach $DirItem1(@Dirs)
		{
			$DirItem2 = $DirItem1;
			if($FileName =~ m/$DirItem2/)
			{
				$DirItem = $DirItem1;

				# Intemediary automated script like base.pl, lib.pl, cmd.pl etc.
				$IntAutoScript = "t/".$DirItem.".pl";
			}
		}

		# Write into the intermediary auto script.
		open(FHW, ">> $IntAutoScript") or die "Unable to open the file,  $IntAutoScript  for appending.\n";
		seek(FHW, 0, 2);	# seek to the end of the file.

		$pos = tell(FHW);
		if($pos <= 0)
		{
			print "Generating  $IntAutoScript...\n";
			print FHW "\n\nprint \"Testing  $DirItem  folder:\\n\\n\\n\"\;\n\n\n";
		}

		opendir(SUBDIR, $FileName);
		@SubDirs = readdir(SUBDIR);
		close(SUBDIR);
		foreach $SubFileName(@SubDirs)
		{
			$SubFileName = $FileName."/".$SubFileName;
			if(-d $SubFileName)
			{
				push @DirNames, $SubFileName;	# If sub-folder, push it into the array.
			}
			else
			{
				&Process_File($SubFileName);	# If file, process it.
			}

			$index++;
		}

		close FHW;			# close the file.

		if($index <= 0)
		{
			# The folder is empty and delete the corresponding '.pl' file.
			unlink($IntAutoScript);
			print "Deleted  $IntAutoScript  since it corresponded to an empty folder.\n";
		}
		else
		{
			if($pos <= 0)
			{	# This logic to make sure that it is written only once.
				# Only if something is written into the intermediary auto script,
				# only then make an entry of the intermediary auto script in  nwauto.pl
				print FHWA "print \`perl $IntAutoScript\`\;\n";
				print FHWA "print \"\\n\\n\\n\"\;\n\n";
			}
		}
	}
	else
	{
		if(-f $FileName)
		{
			$dir = dirname($FileName);		# Get the folder name
			$base = basename($FileName);	# Get the base name
			($base, $dir, $ext) = fileparse($FileName, '\..*');	# Get the extension of the file passed.

			# Do the processing only if the file has '.t' extension.
			if($ext eq '.t')
			{
				print FHWA "print \`perl $FileName\`\;\n";
				print FHWA "print \"\\n\\n\\n\"\;\n\n";
			}
		}
	}
}

## Below adds the ending comments into all the intermediary auto scripts:

opendir(DIR, $DirName);
@Dirs = readdir(DIR);
close(DIR);
foreach $DirItem(@Dirs)
{
	$index = 0;

	$FileName = $DirName."/".$DirItem;
	if(-d $FileName)
	{	# If an item is a folder, then open it further.

		opendir(SUBDIR, $FileName);
		@SubDirs = readdir(SUBDIR);
		close(SUBDIR);

		# To not to write into the file if the corresponding folder was empty.
		foreach $SubDir(@SubDirs)
		{
			$index++;
		}

		if($index > 0)
		{
			# The folder not empty.

			# Intemediary automated script like base.pl, lib.pl, cmd.pl etc.
			$IntAutoScript = "t/".$DirItem.".pl";

			# Write into the intermediary auto script.
			open(FHW, ">> $IntAutoScript") or die "Unable to open the file,  $IntAutoScript  for appending.\n";
			seek(FHW, 0, 2);	# seek to the end of the file.

			# Write into the intermediary auto script.
			print FHW "\nprint \"Testing of  $DirItem  folder done!\\n\\n\"\;\n\n";

			close FHW;			# close the file.
		}
	}
}

# Write into  nwauto.pl
print FHWA "\nprint \"Automated Unit Testing of Perl$version for NetWare done!\\n\\n\"\;\n\n";

close FHWA;			# close the file.

print "\n\nGeneration of  t/nwauto.pl  Done!\n\n";

print "\nGeneration of automated scripts for NetWare DONE!\n";

# Process the file.
sub Process_File
{
	local($FileToProcess) = @_;		# File name.
	local($Script) = 0;
	local($HeadCut) = 0;

	## For example:
	## If the value of $FileToProcess is '/perl/scripts/t/pragma/warnings.t', then
		## $dir1 = '/perl/scripts/t/pragma/'
		## $base1 = 'warnings'
		## $ext1 = '.t'
	$dir1 = dirname($FileToProcess);	# Get the folder name
	$base1 = basename($FileToProcess);	# Get the base name
	($base1, $dir1, $ext1) = fileparse($FileToProcess, '\..*');	# Get the extension of the file passed.

	# Do the processing only if the file has '.t' extension.
	if($ext1 eq '.t')
	{
		foreach $Script(@ScriptsNotUsed)
		{
			# The variables are converted to lower case before they are compared.
			# This is done to remove the case-sensitive comparison done by 'eq'.
			$Script1 = lc($Script);
			$FileToProcess1 = lc($FileToProcess);
			if($Script1 eq $FileToProcess1)
			{
				$HeadCut = 1;
			}
		}

		if($HeadCut)
		{
			# Write into the intermediary auto script.
			print FHW "=head\n";
		}

		# Write into the intermediary auto script.
		print FHW "print \"Testing  $base1"."$ext1:\\n\\n\"\;\n";
		print FHW "print \`perl $FileToProcess\`\;\n";	# Write the changed array into the file.
		print FHW "print \"\\n\\n\\n\"\;\n";

		if($HeadCut)
		{
			# Write into the intermediary auto script.
			print FHW "=cut\n";
		}

		$HeadCut = 0;
		print FHW "\n";
	}
}


text:
students = ['Bob', 'Alice', 'Charles']

companies = ['Uniqlo', 'Target', 'CVS', 'Walmart']
events = ['Marathon', 'Driving test', 'Summer internship']

students.each do |name|
  u1 = User.find_by email: "#{name.downcase}@students.com"
  p = u1.profile
  p.profile_entries.map &:destroy

  company_name = companies[(Random.new().rand * companies.length).to_i]
  pe = ProfileEntry.new profile: p, entry_key: 'work',
                        entry_details: {
                          title: "Job at #{company_name}",
                          workplace: company_name
                        }
  pe.save

  accomp = events[(Random.new().rand * events.size).to_i]
  pe = ProfileEntry.new profile: p, entry_key: 'achievement',
                        entry_details: {
                          text: "Accomplished #{accomp}!",
                          type: 'event'
                        }
  pe.save
end


text:
<?php
require_once("../config/general.php");
?>

<?php echo $info_registro["activado"]["titulo"] ?>

<?php echo $info_registro["activado"]["descripcion"]?>

Volver a inicio


text:
"""7

Revision ID: f8d23cd8191
Revises: 3d8eec94b9a9
Create Date: 2014-03-28 20:41:13.107796

"""

# revision identifiers, used by Alembic.
revision = 'f8d23cd8191'
down_revision = '3d8eec94b9a9'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('student_teacher_association_table',
    sa.Column('teacher_id', sa.Integer(), nullable=False),
    sa.Column('student_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['student_id'], ['users.id'], ),
    sa.ForeignKeyConstraint(['teacher_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('teacher_id', 'student_id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('student_teacher_association_table')
    ### end Alembic commands ###


text:
var through = require('through2')

function makeMetricsStream() {
  var time = Date.now()
  var bytes = 0

  return through(function write (buf, enc, next) {
    bytes += buf.length
    this.push(buf)
    next()
  }, function end () {
    var delta = Date.now() - time
    console.log(bytes + ' bytes written ('
        + (delta / 1000).toFixed(2) + ' seconds)'
    )
    this.push(null)
  })
}

module.exports = makeMetricsStream


text:
package com.atlassian.jira.plugins.dvcs.service;

import com.atlassian.beehive.ClusterLock;
import com.atlassian.beehive.ClusterLockService;
import com.atlassian.jira.plugins.dvcs.activity.RepositoryPullRequestDao;
import com.atlassian.jira.plugins.dvcs.dao.RepositoryDao;
import com.atlassian.jira.plugins.dvcs.dao.SyncAuditLogDao;
import com.atlassian.jira.plugins.dvcs.event.CarefulEventService;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException;
import com.atlassian.jira.plugins.dvcs.model.DvcsUser;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.model.Repository;
import com.atlassian.jira.plugins.dvcs.model.RepositoryRegistration;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicator;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicatorProvider;
import com.atlassian.jira.plugins.dvcs.spi.github.service.GitHubEventService;
import com.atlassian.jira.plugins.dvcs.sync.Synchronizer;
import com.atlassian.sal.api.ApplicationProperties;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.mockito.ArgumentMatcher;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.atlassian.jira.plugins.dvcs.service.RepositoryServiceImpl.SYNC_REPOSITORY_LIST_LOCK;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class RepositoryServiceImplTest
{
    @Mock
    private DvcsCommunicatorProvider dvcsCommunicatorProvider;

    @Mock
    private RepositoryDao repositoryDao;

    @Mock
    private RepositoryPullRequestDao repositoryPullRequestDao;

    @Mock
    private BranchService branchService;

    @Mock
    private Synchronizer synchronizer;

    @Mock
    private ChangesetService changesetService;

    @Mock
    private ApplicationProperties applicationProperties;

    @Mock
    private DvcsCommunicator bitbucketCommunicator;

    @Mock
    private PluginSettingsFactory settings;

    @Mock
    private Synchronizer synchroizerMock;

    @Mock
    private SyncAuditLogDao syncAudit;

    @Mock
    private GitHubEventService gitHubEventService;

    @Mock
    private ClusterLockService clusterLockService;

    @Mock
    private CarefulEventService eventService;

    @Mock
    private Repository repository;

    // tested object
    @InjectMocks
    private RepositoryServiceImpl repositoryService;

    public RepositoryServiceImplTest()
    {
        super();
    }

    @BeforeMethod
    public void setup()
    {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testDestroy() throws Exception
    {
        BlockingQueue<Runnable> queue = mock(BlockingQueue.class);
        ThreadPoolExecutor executor = mock(ThreadPoolExecutor.class);
        when(executor.getQueue()).thenReturn(queue);

        repositoryService.setThreadPoolExecutor(executor);
        repositoryService.destroy();

        verify(executor).shutdown();
        verify(executor, never()).shutdownNow();
        verify(queue).clear();
        verify(executor).awaitTermination(anyLong(), any(TimeUnit.class));
    }

    @Test
    public void testDisableRepository()
    {

        Repository sampleRepository = createSampleRepository();
        when(repositoryDao.get(0)).thenReturn(sampleRepository);
        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");

        RepositoryRegistration registration = repositoryService.enableRepository(0, false);

        verify(repositoryDao).save(sampleRepository);
        verify(bitbucketCommunicator).removePostcommitHook(Mockito.eq(sampleRepository),
                Mockito.eq(createPostcommitUrl(sampleRepository)));
        Assert.assertFalse(registration.isCallBackUrlInstalled());
        Assert.assertEquals(registration.getRepository(), sampleRepository);
    }

    @Test
    public void testDisableRepositoryWithoutAdminRights()
    {
        Repository sampleRepository = createSampleRepository();
        when(repositoryDao.get(0)).thenReturn(sampleRepository);
        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        Mockito.doThrow(new SourceControlException.PostCommitHookRegistrationException("", null)).when(bitbucketCommunicator).removePostcommitHook(Mockito.any(Repository.class), Mockito.anyString());
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");

        RepositoryRegistration registration = repositoryService.enableRepository(0, false);

        verify(repositoryDao).save(sampleRepository);
        verify(bitbucketCommunicator).removePostcommitHook(Mockito.eq(sampleRepository),
                Mockito.eq(createPostcommitUrl(sampleRepository)));
        Assert.assertTrue(registration.isCallBackUrlInstalled());
        Assert.assertEquals(registration.getRepository(), sampleRepository);
    }

    @Test
    public void testEnableRepository()
    {

        Repository sampleRepository = createSampleRepository();
        when(repositoryDao.get(0)).thenReturn(sampleRepository);
        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");

        RepositoryRegistration registration = repositoryService.enableRepository(0, true);

        verify(repositoryDao).save(sampleRepository);
        verify(bitbucketCommunicator).ensureHookPresent(Mockito.eq(sampleRepository),
                Mockito.eq(createPostcommitUrl(sampleRepository)));
        Assert.assertTrue(registration.isCallBackUrlInstalled());
        Assert.assertNotNull(registration.getCallBackUrl());
        Assert.assertEquals(registration.getRepository(), sampleRepository);
    }

    @Test
    public void testEnableRepositoryWithoutAdminRights()
    {

        Repository sampleRepository = createSampleRepository();
        when(repositoryDao.get(0)).thenReturn(sampleRepository);
        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        Mockito.doThrow(new SourceControlException.PostCommitHookRegistrationException("", null)).when(bitbucketCommunicator).ensureHookPresent(Mockito.any(Repository.class), Mockito.anyString());
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");

        RepositoryRegistration registration = repositoryService.enableRepository(0, true);

        verify(repositoryDao).save(sampleRepository);
        verify(bitbucketCommunicator).ensureHookPresent(Mockito.eq(sampleRepository),
                Mockito.eq(createPostcommitUrl(sampleRepository)));
        Assert.assertFalse(registration.isCallBackUrlInstalled());
        Assert.assertNotNull(registration.getCallBackUrl());
        Assert.assertEquals(registration.getRepository(), sampleRepository);
    }

    @Test
    public void testSyncRepositoryList()
    {
        when(settings.createGlobalSettings()).thenReturn(mock(PluginSettings.class));
        Repository sampleRepository1 = createSampleRepository();
        sampleRepository1.setId(1);
        sampleRepository1.setSlug("sampleRepository1");

        Repository sampleRepository2 = createSampleRepository();
        sampleRepository2.setId(2);
        sampleRepository2.setSlug("sampleRepository2");

        Repository sampleRepository3 = createSampleRepository();
        sampleRepository3.setId(3);
        sampleRepository3.setSlug("sampleRepository3");

        Repository sampleRepository4 = createSampleRepository();
        sampleRepository4.setId(4);
        sampleRepository4.setSlug("sampleRepository4");

        List<Repository> storedRepos = new ArrayList<Repository>();
        storedRepos.add(sampleRepository1);
        storedRepos.add(sampleRepository2);
        List<Repository> remoteRepos = new ArrayList<Repository>();
        // first one deleted, 3, 4 added
        remoteRepos.add(sampleRepository2);
        remoteRepos.add(sampleRepository3);
        remoteRepos.add(sampleRepository4);

        Organization sampleOrganization = new Organization();
        sampleOrganization.setId(5);
        sampleOrganization.setDvcsType("bitbucket");
        sampleOrganization.setAutolinkNewRepos(true);

        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        when(bitbucketCommunicator.getRepositories(sampleOrganization, storedRepos)).thenReturn(remoteRepos);
        when(repositoryDao.getAllByOrganization(5, true)).thenReturn(storedRepos);
        when(repositoryDao.save(sampleRepository3)).thenReturn(sampleRepository3);
        when(repositoryDao.save(sampleRepository4)).thenReturn(sampleRepository4);
        when(repositoryDao.getAllByOrganization(5, false)).thenReturn(Lists.<Repository>newArrayList(Iterables.concat(storedRepos, remoteRepos)));
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");
        final ClusterLock mockLock = mock(ClusterLock.class);
        when(clusterLockService.getLockForName(SYNC_REPOSITORY_LIST_LOCK)).thenReturn(mockLock);

        repositoryService.syncRepositoryList(sampleOrganization);

        // 2 has been updated
        verify(repositoryDao, Mockito.times(1)).save(sampleRepository2);

        // 1 has been deleted
        verify(repositoryDao, Mockito.times(1)).save(Mockito.argThat(new ArgumentMatcher<Repository>()
        {
            @Override
            public boolean matches(Object argument)
            {
                Repository repo = (Repository) argument;
                return repo.getId() == 1 && repo.isDeleted();
            }
        }));

        // 3, 4 has been added
        verify(repositoryDao, Mockito.times(2)).save(Mockito.argThat(new ArgumentMatcher<Repository>()
        {
            @Override
            public boolean matches(Object argument)
            {
                Repository repo = (Repository) argument;
                return repo.getId() == 3 || repo.getId() == 4;
            }
        }));
        // ... with false linking
        verify(bitbucketCommunicator).ensureHookPresent(sampleRepository3, createPostcommitUrl(sampleRepository3));
        verify(bitbucketCommunicator).ensureHookPresent(sampleRepository4, createPostcommitUrl(sampleRepository4));
        verify(mockLock).unlock();
    }

    @Test
    public void testRemoveRepository()
    {
        Repository sampleRepository = createSampleRepository();
        sampleRepository.setId(8);

        repositoryService.remove(sampleRepository);

        verify(changesetService).removeAllInRepository(8);
        verify(repositoryDao).remove(8);
        verify(repositoryPullRequestDao).removeAll(sampleRepository);
    }

    @Test
    public void testRemoveRepositoryIsLinked()
    {
        Repository sampleRepository = createSampleRepository();
        sampleRepository.setId(8);
        sampleRepository.setLinked(true);
        when(dvcsCommunicatorProvider.getCommunicator("bitbucket")).thenReturn(bitbucketCommunicator);
        when(applicationProperties.getBaseUrl()).thenReturn("https://myjira.org");

        repositoryService.remove(sampleRepository);

        verify(changesetService).removeAllInRepository(8);
        verify(repositoryDao).remove(8);

        verify(bitbucketCommunicator).removePostcommitHook(Mockito.eq(sampleRepository),
                Mockito.eq(createPostcommitUrl(sampleRepository)));
    }

    /**
     * Unit tests related to {@link RepositoryServiceImpl#getUser(Repository, String, String)}.
     */
    @Test
    public void testGetUser()
    {
        Repository repository = mock(Repository.class);
        DvcsCommunicator testCommunicator = mock(DvcsCommunicator.class);

        String dvcsType = "test-dvcs-type";

        class BooleanFlag
        {
            private boolean flag;
        }
        final BooleanFlag wasInvoked = new BooleanFlag();

        when(repository.getDvcsType()).thenReturn(dvcsType);
        when(dvcsCommunicatorProvider.getCommunicator(dvcsType)).thenReturn(testCommunicator);
        when(testCommunicator.getUser(Mockito.eq(repository), Mockito.anyString())).thenAnswer(new Answer<DvcsUser>()
        {

            @Override
            public DvcsUser answer(InvocationOnMock invocation) throws Throwable
            {
                wasInvoked.flag = true;
                return new DvcsUser((String) invocation.getArguments()[1], "", "", "", "");
            }

        });

        DvcsUser user;

        wasInvoked.flag = false;
        user = repositoryService.getUser(repository, null, null);
        Assert.assertFalse(wasInvoked.flag);
        Assert.assertTrue(user instanceof DvcsUser.UnknownUser);

        wasInvoked.flag = false;
        user = repositoryService.getUser(repository, "", null);
        Assert.assertFalse(wasInvoked.flag);
        Assert.assertTrue(user instanceof DvcsUser.UnknownUser);

        wasInvoked.flag = false;
        user = repositoryService.getUser(repository, "test", null);
        Assert.assertTrue(wasInvoked.flag);
        Assert.assertFalse(user instanceof DvcsUser.UnknownUser);
    }

    @Test
    public void removingRepositoryShouldClearAssociatedEvents() throws Exception
    {
        repositoryService.remove(repository);
        verify(eventService).discardEvents(repository);
    }

    private Repository createSampleRepository()
    {
        Repository repository = new Repository();
        repository.setName("doesnotmatter_repo");
        repository.setDvcsType("bitbucket");
        repository.setOrganizationId(1);
        repository.setSlug("doesnotmatter-repo");
        return repository;
    }

    private String createPostcommitUrl(Repository forRepo)
    {
        return "https://myjira.org" + "/rest/bitbucket/1.0/repository/" + forRepo.getId() + "/sync";
    }

}


text:
package singleton;

public class MySingleton {

  private static MySingleton INSTANCE = null;

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    if (INSTANCE == null) {
      INSTANCE = new MySingleton();
    }
    return INSTANCE;
  }
}


text:
define([
    'asset/js/amcharts/amcharts'
], function(){
    AmCharts.isReady = true;

    return alt.component({
        name: 'prototyperChartAmcharts',
        templateUrl: 'component/prototyper/chart/amcharts/view.html',
        scope: {
            setting: '=?prototyperChartAmcharts',
            config: '=?'
        },
        isskip: true,
        link: ['$scope', '$log', '$element', '$timeout', function($scope, $log, $element, $timeout){
            $scope.setting      = alt.extend({
                isautoreload    : true,
                elementid       : "amcharts" + $scope.$id,
                objchart        : {},
                reload          : function(){
                    if($scope.setting.objchart.dataProvider){
                        $scope.setting.objchart.dataProvider = $scope.data;
                        $scope.setting.objchart.validateData();
                    }else{
                        $scope.setting.objchart = AmCharts.makeChart($scope.setting.elementid, alt.extend({
                            dataProvider: $scope.data
                        }, $scope.setting.chart));
                    }
                }
            }, $scope.setting);

            $scope.config = alt.extend({
                style: '',
                renderAt: $scope.setting.elementid,
                height: "100%",
                labelsEnabled: false,
                autoMargins: false,
                marginTop: 0,
                marginBottom: 0,
                marginLeft: 0,
                marginRight: 0,
                pullOutRadus: 0
            }, $scope.config);

            $timeout($scope.setting.reload);
        }]
    });
});


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

import { LinearFilter, NearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, ClampToEdgeWrapping, NearestMipmapLinearFilter, NearestMipmapNearestFilter } from '../../constants.js';
import { _Math } from '../../math/Math.js';

function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {

	var _videoTextures = new WeakMap();
	var _canvas;

	// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
	// also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!

	var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
		&& ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;

	function createCanvas( width, height ) {

		// Use OffscreenCanvas when available. Specially needed in web workers

		return useOffscreenCanvas ?
			new OffscreenCanvas( width, height ) :
			document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );

	}

	function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {

		var scale = 1;

		// handle case if texture exceeds max size

		if ( image.width > maxSize || image.height > maxSize ) {

			scale = maxSize / Math.max( image.width, image.height );

		}

		// only perform resize if necessary

		if ( scale < 1 || needsPowerOfTwo === true ) {

			// only perform resize for certain image types

			if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
				( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
				( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {

				var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;

				var width = floor( scale * image.width );
				var height = floor( scale * image.height );

				if ( _canvas === undefined ) _canvas = createCanvas( width, height );

				// cube textures can't reuse the same canvas

				var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;

				canvas.width = width;
				canvas.height = height;

				var context = canvas.getContext( '2d' );
				context.drawImage( image, 0, 0, width, height );

				console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );

				return canvas;

			} else {

				if ( 'data' in image ) {

					console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );

				}

				return image;

			}

		}

		return image;

	}

	function isPowerOfTwo( image ) {

		return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );

	}

	function textureNeedsPowerOfTwo( texture ) {

		if ( capabilities.isWebGL2 ) return false;

		return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
			( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );

	}

	function textureNeedsGenerateMipmaps( texture, supportsMips ) {

		return texture.generateMipmaps && supportsMips &&
			texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;

	}

	function generateMipmap( target, texture, width, height ) {

		_gl.generateMipmap( target );

		var textureProperties = properties.get( texture );

		// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
		textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;

	}

	function getInternalFormat( glFormat, glType ) {

		if ( ! capabilities.isWebGL2 ) return glFormat;

		var internalFormat = glFormat;

		if ( glFormat === _gl.RED ) {

			if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
			if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
			if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;

		}

		if ( glFormat === _gl.RGB ) {

			if ( glType === _gl.FLOAT ) internalFormat = _gl.RGB32F;
			if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGB16F;
			if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8;

		}

		if ( glFormat === _gl.RGBA ) {

			if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
			if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
			if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8;

		}

		if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
			internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {

			extensions.get( 'EXT_color_buffer_float' );

		} else if ( internalFormat === _gl.RGB16F || internalFormat === _gl.RGB32F ) {

			console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );

		}

		return internalFormat;

	}

	// Fallback filters for non-power-of-2 textures

	function filterFallback( f ) {

		if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {

			return _gl.NEAREST;

		}

		return _gl.LINEAR;

	}

	//

	function onTextureDispose( event ) {

		var texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

		if ( texture.isVideoTexture ) {

			_videoTextures.delete( texture );

		}

		info.memory.textures --;

	}

	function onRenderTargetDispose( event ) {

		var renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

		info.memory.textures --;

	}

	//

	function deallocateTexture( texture ) {

		var textureProperties = properties.get( texture );

		if ( textureProperties.__webglInit === undefined ) return;

		_gl.deleteTexture( textureProperties.__webglTexture );

		properties.remove( texture );

	}

	function deallocateRenderTarget( renderTarget ) {

		var renderTargetProperties = properties.get( renderTarget );
		var textureProperties = properties.get( renderTarget.texture );

		if ( ! renderTarget ) return;

		if ( textureProperties.__webglTexture !== undefined ) {

			_gl.deleteTexture( textureProperties.__webglTexture );

		}

		if ( renderTarget.depthTexture ) {

			renderTarget.depthTexture.dispose();

		}

		if ( renderTarget.isWebGLRenderTargetCube ) {

			for ( var i = 0; i < 6; i ++ ) {

				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
				if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );

			}

		} else {

			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
			if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );

		}

		if ( renderTarget.isWebGLMultiviewRenderTarget ) {

			_gl.deleteTexture( renderTargetProperties.__webglColorTexture );
			_gl.deleteTexture( renderTargetProperties.__webglDepthStencilTexture );

			info.memory.textures -= 2;

			for ( var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i ++ ) {

				_gl.deleteFramebuffer( renderTargetProperties.__webglViewFramebuffers[ i ] );

			}

		}

		properties.remove( renderTarget.texture );
		properties.remove( renderTarget );

	}

	//

	var textureUnits = 0;

	function resetTextureUnits() {

		textureUnits = 0;

	}

	function allocateTextureUnit() {

		var textureUnit = textureUnits;

		if ( textureUnit >= capabilities.maxTextures ) {

			console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );

		}

		textureUnits += 1;

		return textureUnit;

	}

	//

	function setTexture2D( texture, slot ) {

		var textureProperties = properties.get( texture );

		if ( texture.isVideoTexture ) updateVideoTexture( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			var image = texture.image;

			if ( image === undefined ) {

				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );

			} else if ( image.complete === false ) {

				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );

			} else {

				uploadTexture( textureProperties, texture, slot );
				return;

			}

		}

		state.activeTexture( _gl.TEXTURE0 + slot );
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );

	}

	function setTexture2DArray( texture, slot ) {

		var textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			uploadTexture( textureProperties, texture, slot );
			return;

		}

		state.activeTexture( _gl.TEXTURE0 + slot );
		state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture );

	}

	function setTexture3D( texture, slot ) {

		var textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			uploadTexture( textureProperties, texture, slot );
			return;

		}

		state.activeTexture( _gl.TEXTURE0 + slot );
		state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture );

	}

	function setTextureCube( texture, slot ) {

		if ( texture.image.length !== 6 ) return;

		var textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			initTexture( textureProperties, texture );

			state.activeTexture( _gl.TEXTURE0 + slot );
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );

			_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );

			var isCompressed = ( texture && texture.isCompressedTexture );
			var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );

			var cubeImage = [];

			for ( var i = 0; i < 6; i ++ ) {

				if ( ! isCompressed && ! isDataTexture ) {

					cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );

				} else {

					cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];

				}

			}

			var image = cubeImage[ 0 ],
				supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
				glFormat = utils.convert( texture.format ),
				glType = utils.convert( texture.type ),
				glInternalFormat = getInternalFormat( glFormat, glType );

			setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );

			var mipmaps;

			if ( isCompressed ) {

				for ( var i = 0; i < 6; i ++ ) {

					mipmaps = cubeImage[ i ].mipmaps;

					for ( var j = 0; j < mipmaps.length; j ++ ) {

						var mipmap = mipmaps[ j ];

						if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

							if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {

								state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

							} else {

								console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );

							}

						} else {

							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

						}

					}

				}

				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				mipmaps = texture.mipmaps;

				for ( var i = 0; i < 6; i ++ ) {

					if ( isDataTexture ) {

						state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );

						for ( var j = 0; j < mipmaps.length; j ++ ) {

							var mipmap = mipmaps[ j ];
							var mipmapImage = mipmap.image[ i ].image;

							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );

						}

					} else {

						state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );

						for ( var j = 0; j < mipmaps.length; j ++ ) {

							var mipmap = mipmaps[ j ];

							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );

						}

					}

				}

				textureProperties.__maxMipLevel = mipmaps.length;

			}

			if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

				// We assume images for cube map have the same size.
				generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height );

			}

			textureProperties.__version = texture.version;

			if ( texture.onUpdate ) texture.onUpdate( texture );

		} else {

			state.activeTexture( _gl.TEXTURE0 + slot );
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );

		}

	}

	function setTextureCubeDynamic( texture, slot ) {

		state.activeTexture( _gl.TEXTURE0 + slot );
		state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );

	}

	function setTextureParameters( textureType, texture, supportsMips ) {

		var extension;

		if ( supportsMips ) {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );

			if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {

				_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, utils.convert( texture.wrapR ) );

			}

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );

		} else {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );

			if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {

				_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );

			}

			if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {

				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );

			}

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );

			if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {

				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );

			}

		}

		extension = extensions.get( 'EXT_texture_filter_anisotropic' );

		if ( extension ) {

			if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
			if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;

			if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {

				_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
				properties.get( texture ).__currentAnisotropy = texture.anisotropy;

			}

		}

	}

	function initTexture( textureProperties, texture ) {

		if ( textureProperties.__webglInit === undefined ) {

			textureProperties.__webglInit = true;

			texture.addEventListener( 'dispose', onTextureDispose );

			textureProperties.__webglTexture = _gl.createTexture();

			info.memory.textures ++;

		}

	}

	function uploadTexture( textureProperties, texture, slot ) {

		var textureType = _gl.TEXTURE_2D;

		if ( texture.isDataTexture2DArray ) textureType = _gl.TEXTURE_2D_ARRAY;
		if ( texture.isDataTexture3D ) textureType = _gl.TEXTURE_3D;

		initTexture( textureProperties, texture );

		state.activeTexture( _gl.TEXTURE0 + slot );
		state.bindTexture( textureType, textureProperties.__webglTexture );

		_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
		_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
		_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );

		var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
		var image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );

		var supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
			glFormat = utils.convert( texture.format ),
			glType = utils.convert( texture.type ),
			glInternalFormat = getInternalFormat( glFormat, glType );

		setTextureParameters( textureType, texture, supportsMips );

		var mipmap, mipmaps = texture.mipmaps;

		if ( texture.isDepthTexture ) {

			// populate depth texture with dummy data

			glInternalFormat = _gl.DEPTH_COMPONENT;

			if ( texture.type === FloatType ) {

				if ( ! capabilities.isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
				glInternalFormat = _gl.DEPTH_COMPONENT32F;

			} else if ( capabilities.isWebGL2 ) {

				// WebGL 2.0 requires signed internalformat for glTexImage2D
				glInternalFormat = _gl.DEPTH_COMPONENT16;

			}

			if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {

				// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
				// DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {

					console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );

					texture.type = UnsignedShortType;
					glType = utils.convert( texture.type );

				}

			}

			// Depth stencil textures need the DEPTH_STENCIL internal format
			// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
			if ( texture.format === DepthStencilFormat ) {

				glInternalFormat = _gl.DEPTH_STENCIL;

				// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
				// DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				if ( texture.type !== UnsignedInt248Type ) {

					console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );

					texture.type = UnsignedInt248Type;
					glType = utils.convert( texture.type );

				}

			}

			state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );

		} else if ( texture.isDataTexture ) {

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && supportsMips ) {

				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

					mipmap = mipmaps[ i ];
					state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

				}

				texture.generateMipmaps = false;
				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
				textureProperties.__maxMipLevel = 0;

			}

		} else if ( texture.isCompressedTexture ) {

			for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

				mipmap = mipmaps[ i ];

				if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

					if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {

						state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

					} else {

						console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );

					}

				} else {

					state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

				}

			}

			textureProperties.__maxMipLevel = mipmaps.length - 1;

		} else if ( texture.isDataTexture2DArray ) {

			state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
			textureProperties.__maxMipLevel = 0;

		} else if ( texture.isDataTexture3D ) {

			state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
			textureProperties.__maxMipLevel = 0;

		} else {

			// regular Texture (image, video, canvas)

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && supportsMips ) {

				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

					mipmap = mipmaps[ i ];
					state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );

				}

				texture.generateMipmaps = false;
				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
				textureProperties.__maxMipLevel = 0;

			}

		}

		if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

			generateMipmap( _gl.TEXTURE_2D, texture, image.width, image.height );

		}

		textureProperties.__version = texture.version;

		if ( texture.onUpdate ) texture.onUpdate( texture );

	}

	// Render targets

	// Setup storage for target texture and bind it to correct framebuffer
	function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {

		var glFormat = utils.convert( renderTarget.texture.format );
		var glType = utils.convert( renderTarget.texture.type );
		var glInternalFormat = getInternalFormat( glFormat, glType );
		state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );

	}

	// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
	function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {

		_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );

		if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

			if ( isMultisample ) {

				var samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );

			}

			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

		} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

			if ( isMultisample ) {

				var samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );

			}

			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

		} else {

			var glFormat = utils.convert( renderTarget.texture.format );
			var glType = utils.convert( renderTarget.texture.type );
			var glInternalFormat = getInternalFormat( glFormat, glType );

			if ( isMultisample ) {

				var samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );

			}

		}

		_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );

	}

	// Setup resources for a Depth Texture for a FBO (needs an extension)
	function setupDepthTexture( framebuffer, renderTarget ) {

		var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
		if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );

		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );

		if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {

			throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );

		}

		// upload an empty depth texture with framebuffer size
		if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
				renderTarget.depthTexture.image.width !== renderTarget.width ||
				renderTarget.depthTexture.image.height !== renderTarget.height ) {

			renderTarget.depthTexture.image.width = renderTarget.width;
			renderTarget.depthTexture.image.height = renderTarget.height;
			renderTarget.depthTexture.needsUpdate = true;

		}

		setTexture2D( renderTarget.depthTexture, 0 );

		var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;

		if ( renderTarget.depthTexture.format === DepthFormat ) {

			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );

		} else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {

			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );

		} else {

			throw new Error( 'Unknown depthTexture format' );

		}

	}

	// Setup GL resources for a non-texture depth buffer
	function setupDepthRenderbuffer( renderTarget ) {

		var renderTargetProperties = properties.get( renderTarget );

		var isCube = ( renderTarget.isWebGLRenderTargetCube === true );

		if ( renderTarget.depthTexture ) {

			if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );

			setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );

		} else {

			if ( isCube ) {

				renderTargetProperties.__webglDepthbuffer = [];

				for ( var i = 0; i < 6; i ++ ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
					renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
					setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );

				}

			} else {

				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
				renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
				setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );

			}

		}

		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );

	}

	// Set up GL resources for the render target
	function setupRenderTarget( renderTarget ) {

		var renderTargetProperties = properties.get( renderTarget );
		var textureProperties = properties.get( renderTarget.texture );

		renderTarget.addEventListener( 'dispose', onRenderTargetDispose );

		textureProperties.__webglTexture = _gl.createTexture();

		info.memory.textures ++;

		var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
		var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
		var isMultiview = ( renderTarget.isWebGLMultiviewRenderTarget === true );
		var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;

		// Setup framebuffer

		if ( isCube ) {

			renderTargetProperties.__webglFramebuffer = [];

			for ( var i = 0; i < 6; i ++ ) {

				renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();

			}

		} else {

			renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();

			if ( isMultisample ) {

				if ( capabilities.isWebGL2 ) {

					renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
					renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();

					_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer );
					var glFormat = utils.convert( renderTarget.texture.format );
					var glType = utils.convert( renderTarget.texture.type );
					var glInternalFormat = getInternalFormat( glFormat, glType );
					var samples = getRenderTargetSamples( renderTarget );
					_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
					_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer );
					_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );

					if ( renderTarget.depthBuffer ) {

						renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
						setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );

					}

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );

				} else {

					console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

				}

			} else if ( isMultiview ) {

				var width = renderTarget.width;
				var height = renderTarget.height;
				var numViews = renderTarget.numViews;

				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );

				var ext = extensions.get( 'OVR_multiview2' );

				info.memory.textures += 2;

				var colorTexture = _gl.createTexture();
				_gl.bindTexture( _gl.TEXTURE_2D_ARRAY, colorTexture );
				_gl.texParameteri( _gl.TEXTURE_2D_ARRAY, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
				_gl.texParameteri( _gl.TEXTURE_2D_ARRAY, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
				_gl.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, _gl.RGBA8, width, height, numViews, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
				ext.framebufferTextureMultiviewOVR( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, colorTexture, 0, 0, numViews );

				var depthStencilTexture = _gl.createTexture();
				_gl.bindTexture( _gl.TEXTURE_2D_ARRAY, depthStencilTexture );
				_gl.texParameteri( _gl.TEXTURE_2D_ARRAY, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
				_gl.texParameteri( _gl.TEXTURE_2D_ARRAY, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
				_gl.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, _gl.DEPTH24_STENCIL8, width, height, numViews, 0, _gl.DEPTH_STENCIL, _gl.UNSIGNED_INT_24_8, null );
				ext.framebufferTextureMultiviewOVR( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, depthStencilTexture, 0, 0, numViews );

				var viewFramebuffers = new Array( numViews );
				for ( var i = 0; i < numViews; ++ i ) {

					viewFramebuffers[ i ] = _gl.createFramebuffer();
					_gl.bindFramebuffer( _gl.FRAMEBUFFER, viewFramebuffers[ i ] );
					_gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, colorTexture, 0, i );

				}

				renderTargetProperties.__webglColorTexture = colorTexture;
				renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
				renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;

				_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
				_gl.bindTexture( _gl.TEXTURE_2D_ARRAY, null );

			}

		}

		// Setup color buffer

		if ( isCube ) {

			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, supportsMips );

			for ( var i = 0; i < 6; i ++ ) {

				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );

			}

			if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

				generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height );

			}

			state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );

		} else if ( ! isMultiview ) {

			state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, supportsMips );
			setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );

			if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

				generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height );

			}

			state.bindTexture( _gl.TEXTURE_2D, null );

		}

		// Setup depth and stencil buffers

		if ( renderTarget.depthBuffer ) {

			setupDepthRenderbuffer( renderTarget );

		}

	}

	function updateRenderTargetMipmap( renderTarget ) {

		var texture = renderTarget.texture;
		var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;

		if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

			var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
			var webglTexture = properties.get( texture ).__webglTexture;

			state.bindTexture( target, webglTexture );
			generateMipmap( target, texture, renderTarget.width, renderTarget.height );
			state.bindTexture( target, null );

		}

	}

	function updateMultisampleRenderTarget( renderTarget ) {

		if ( renderTarget.isWebGLMultisampleRenderTarget ) {

			if ( capabilities.isWebGL2 ) {

				var renderTargetProperties = properties.get( renderTarget );

				_gl.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
				_gl.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );

				var width = renderTarget.width;
				var height = renderTarget.height;
				var mask = _gl.COLOR_BUFFER_BIT;

				if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
				if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;

				_gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );

			} else {

				console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

			}

		}

	}

	function getRenderTargetSamples( renderTarget ) {

		return ( capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
			Math.min( capabilities.maxSamples, renderTarget.samples ) : 0;

	}

	function updateVideoTexture( texture ) {

		var frame = info.render.frame;

		// Check the last frame we updated the VideoTexture

		if ( _videoTextures.get( texture ) !== frame ) {

			_videoTextures.set( texture, frame );
			texture.update();

		}

	}

	// backwards compatibility

	var warnedTexture2D = false;
	var warnedTextureCube = false;

	function safeSetTexture2D( texture, slot ) {

		if ( texture && texture.isWebGLRenderTarget ) {

			if ( warnedTexture2D === false ) {

				console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
				warnedTexture2D = true;

			}

			texture = texture.texture;

		}

		setTexture2D( texture, slot );

	}

	function safeSetTextureCube( texture, slot ) {

		if ( texture && texture.isWebGLRenderTargetCube ) {

			if ( warnedTextureCube === false ) {

				console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
				warnedTextureCube = true;

			}

			texture = texture.texture;

		}

		// currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
		// TODO: unify these code paths
		if ( ( texture && texture.isCubeTexture ) ||
			( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

			// CompressedTexture can have Array in image :/

			// this function alone should take care of cube textures
			setTextureCube( texture, slot );

		} else {

			// assumed: texture property of THREE.WebGLRenderTargetCube
			setTextureCubeDynamic( texture, slot );

		}

	}

	//

	this.allocateTextureUnit = allocateTextureUnit;
	this.resetTextureUnits = resetTextureUnits;

	this.setTexture2D = setTexture2D;
	this.setTexture2DArray = setTexture2DArray;
	this.setTexture3D = setTexture3D;
	this.setTextureCube = setTextureCube;
	this.setTextureCubeDynamic = setTextureCubeDynamic;
	this.setupRenderTarget = setupRenderTarget;
	this.updateRenderTargetMipmap = updateRenderTargetMipmap;
	this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;

	this.safeSetTexture2D = safeSetTexture2D;
	this.safeSetTextureCube = safeSetTextureCube;

}

export { WebGLTextures };