text:
DATABASENAME=oc_autotest$EXECUTOR_NUMBER
DATABASEUSER=oc_autotest$EXECUTOR_NUMBER
ADMINLOGIN=admin$EXECUTOR_NUMBER
BASEDIR=$PWD

DBCONFIGS="sqlite mysql pgsql oci"
if test -z "$PHPUNIT"; then
	PHPUNIT=$(which phpunit)
fi

_XDEBUG_CONFIG=$XDEBUG_CONFIG
unset XDEBUG_CONFIG

function print_syntax {
	echo -e "Syntax: ./autotest-external.sh [dbconfigname] [startfile]\n" >&2
	echo -e "\t\"dbconfigname\" can be one of: $DBCONFIGS" >&2
	echo -e "\t\"startfile\" is the name of a start file inside the env/ folder in the files_external tests" >&2
	echo -e "\nExample: ./autotest.sh sqlite webdav-ownCloud" >&2
	echo "will run the external suite from \"apps/files_external/tests/env/start-webdav-ownCloud.sh\"" >&2
	echo -e "\nIf no arguments are specified, all available external backends will be run with all database configs" >&2
	echo -e "\nIf you specify 'common-tests' as startfile it will just run the tests that are independent from the backends" >&2
}

if ! [ -x "$PHPUNIT" ]; then
	echo "phpunit executable not found, please install phpunit version >= 8.5" >&2
	exit 3
fi

PHPUNIT_VERSION=$("$PHPUNIT" --version | cut -d" " -f2)
PHPUNIT_MAJOR_VERSION=$(echo $PHPUNIT_VERSION | cut -d"." -f1)
PHPUNIT_MINOR_VERSION=$(echo $PHPUNIT_VERSION | cut -d"." -f2)

if ! [ $PHPUNIT_MAJOR_VERSION -gt 8 -o \( $PHPUNIT_MAJOR_VERSION -eq 8 -a $PHPUNIT_MINOR_VERSION -ge 5 \) ]; then
	echo "phpunit version >= 8.5 required. Version found: $PHPUNIT_VERSION" >&2
	exit 4
fi

if ! [ \( -w config -a ! -f config/config.php \) -o \( -f config/config.php -a -w config/config.php \) ]; then
	echo "Please enable write permissions on config and config/config.php" >&2
	exit 1
fi

if [ "$1" ]; then
	FOUND=0
	for DBCONFIG in $DBCONFIGS; do
		if [ "$1" = $DBCONFIG ]; then
			FOUND=1
			break
		fi
	done
	if [ $FOUND = 0 ]; then
		echo -e "Unknown database config name \"$1\"\n" >&2
		print_syntax
		exit 2
	fi
fi

# Back up existing (dev) config if one exists and backup not already there
if [ -f config/config.php ] && [ ! -f config/config-autotest-backup.php ]; then
	mv config/config.php config/config-autotest-backup.php
fi

function cleanup_config {
	cd "$BASEDIR"
	# Restore existing config
	if [ -f config/config-autotest-backup.php ]; then
		mv config/config-autotest-backup.php config/config.php
	fi
	# Remove autotest config
	if [ -f config/autoconfig.php ]; then
		rm config/autoconfig.php
	fi
}

# restore config on exit
trap cleanup_config EXIT

# use tmpfs for datadir - should speedup unit test execution
if [ -d /dev/shm ]; then
  DATADIR=/dev/shm/data-autotest$EXECUTOR_NUMBER
else
  DATADIR=$BASEDIR/data-autotest
fi

echo "Using database $DATABASENAME"

function execute_tests {
	echo "Setup environment for $1 testing ..."
	# back to root folder
	cd "$BASEDIR"

	# revert changes to tests/data
	git checkout tests/data

	# reset data directory
	rm -rf "$DATADIR"
	mkdir "$DATADIR"

	# remove the old config file
	#rm -rf config/config.php
	cp tests/preseed-config.php config/config.php

	# drop database
	if [ "$1" == "mysql" ] ; then
		mysql -u $DATABASEUSER -powncloud -e "DROP DATABASE IF EXISTS $DATABASENAME" || true
	fi
	if [ "$1" == "pgsql" ] ; then
		dropdb -U $DATABASEUSER $DATABASENAME || true
	fi
	if [ "$1" == "oci" ] ; then
		echo "drop the database"
		sqlplus -s -l / as sysdba <<EOF
			drop user $DATABASENAME cascade;
EOF

		echo "create the database"
		sqlplus -s -l / as sysdba <<EOF
			create user $DATABASENAME identified by owncloud;
			alter user $DATABASENAME default tablespace users
			temporary tablespace temp
			quota unlimited on users;
			grant create session
			, create table
			, create procedure
			, create sequence
			, create trigger
			, create view
			, create synonym
			, alter session
			to $DATABASENAME;
			exit;
EOF
		DATABASEUSER=$DATABASENAME
		DATABASENAME='XE'
	fi

	# copy autoconfig
	cp "$BASEDIR/tests/autoconfig-$1.php" "$BASEDIR/config/autoconfig.php"

	# trigger installation
	echo "Installing ...."
	./occ maintenance:install -vvv --database=$1 --database-name=$DATABASENAME --database-host=localhost --database-user=$DATABASEUSER --database-pass=owncloud --database-table-prefix=oc_ --admin-user=$ADMINLOGIN --admin-pass=admin --data-dir=$DATADIR

	#test execution
	echo "Testing with $1 ..."

	if [ -n "$2" ]; then
		echo "Run only $2 ..."
	fi

	cd tests
	rm -rf "coverage-external-html-$1"
	mkdir "coverage-external-html-$1"
	# just enable files_external
	php ../occ app:enable -vvv files_external
	if [[ "$_XDEBUG_CONFIG" ]]; then
		export XDEBUG_CONFIG=$_XDEBUG_CONFIG
	fi
	if [ -z "$NOCOVERAGE" ]; then
		"$PHPUNIT" --configuration phpunit-autotest-external.xml --log-junit "autotest-external-results-$1.xml" --coverage-clover "autotest-external-clover-$1.xml" --coverage-html "coverage-external-html-$1"
		RESULT=$?
	else
		echo "No coverage"
		"$PHPUNIT" --configuration phpunit-autotest-external.xml --log-junit "autotest-external-results-$1.xml"
		RESULT=$?
	fi

	if [ -n "$2" -a "$2" == "common-tests" ]; then
		return;
	fi

	FILES_EXTERNAL_BACKEND_PATH=../apps/files_external/tests/Storage
	FILES_EXTERNAL_BACKEND_ENV_PATH=../apps/files_external/tests/env

	for startFile in `ls -1 $FILES_EXTERNAL_BACKEND_ENV_PATH | grep start`; do
		name=`echo $startFile | sed 's/start-//' | sed 's/\.sh//'`

		if [ -n "$2" -a "$2" != "$name" ]; then
			echo "skip: $startFile"
			continue;
		fi

		echo "start: $startFile"
		echo "name: $name"

		# execute start file
		./$FILES_EXTERNAL_BACKEND_ENV_PATH/$startFile
		if [ $? -eq 0 ]; then
			# getting backend to test from filename
			# it's the part between the dots startSomething.TestToRun.sh
			testToRun=`echo $startFile | cut -d '-' -f 2`
			# capitalize first letter
			testToRun="${testToRun^}"
			testToRun="${testToRun}Test.php"

			# run the specific test
			if [ -z "$NOCOVERAGE" ]; then
				rm -rf "coverage-external-html-$1-$name"
				mkdir "coverage-external-html-$1-$name"
				"$PHPUNIT" --configuration phpunit-autotest-external.xml --log-junit "autotest-external-results-$1-$name.xml" --coverage-clover "autotest-external-clover-$1-$name.xml" --coverage-html "coverage-external-html-$1-$name" "$FILES_EXTERNAL_BACKEND_PATH/$testToRun"
				RESULT=$?
			else
				echo "No coverage"
				"$PHPUNIT" --configuration phpunit-autotest-external.xml --log-junit "autotest-external-results-$1-$name.xml" "$FILES_EXTERNAL_BACKEND_PATH/$testToRun"
				RESULT=$?
			fi
		else
		    DOEXIT=1
		fi

		# calculate stop file
		stopFile=`echo "$startFile" | sed 's/start/stop/'`
		echo "stop: $stopFile"
		if [ -f $FILES_EXTERNAL_BACKEND_ENV_PATH/$stopFile ]; then
			# execute stop file if existent
			./$FILES_EXTERNAL_BACKEND_ENV_PATH/$stopFile
		fi
		if [ "$DOEXIT" ]; then
		    echo "Error during start file execution ... terminating"
		    exit $DOEXIT
		fi
	done;
}

#
# start test execution
#
if [ -z "$1" ]; then
	# run all known database configs
	for DBCONFIG in $DBCONFIGS; do
		execute_tests $DBCONFIG "$2"
	done
else
	execute_tests "$1" "$2"
fi

#
# NOTES on mysql:
#  - CREATE DATABASE oc_autotest;
#  - CREATE USER 'oc_autotest'@'localhost' IDENTIFIED BY 'owncloud';
#  - grant all on oc_autotest.* to 'oc_autotest'@'localhost';
#
#  - for parallel executor support with EXECUTOR_NUMBER=0:
#  - CREATE DATABASE oc_autotest0;
#  - CREATE USER 'oc_autotest0'@'localhost' IDENTIFIED BY 'owncloud';
#  - grant all on oc_autotest0.* to 'oc_autotest0'@'localhost';
#
# NOTES on pgsql:
#  - su - postgres
#  - createuser -P oc_autotest (enter password and enable superuser)
#  - to enable dropdb I decided to add following line to pg_hba.conf (this is not the safest way but I don't care for the testing machine):
# local	all	all	trust
#
#  - for parallel executor support with EXECUTOR_NUMBER=0:
#  - createuser -P oc_autotest0 (enter password and enable superuser)
#
# NOTES on oci:
#  - it's a pure nightmare to install Oracle on a Linux-System
#  - DON'T TRY THIS AT HOME!
#  - if you really need it: we feel sorry for you
#


text:
namespace android_webview {
namespace AwResource {

std::vector<std::string> GetConfigKeySystemUuidMapping() {
  JNIEnv* env = base::android::AttachCurrentThread();
  std::vector<std::string> key_system_uuid_mappings;
  ScopedJavaLocalRef<jobjectArray> mappings =
      Java_AwResource_getConfigKeySystemUuidMapping(env);
  base::android::AppendJavaStringArrayToStringVector(env, mappings.obj(),
                                                     &key_system_uuid_mappings);
  return key_system_uuid_mappings;
}

bool RegisterAwResource(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace AwResource
}  // namespace android_webview

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Controls\Display\assets\scripts\ImageZoom.js 源码</title>
		<link href="../../assets/styles/prettify.css" type="text/css" rel="stylesheet" />
		<script src="../../assets/scripts/prettify.js" type="text/javascript"></script>
		<style type="text/css">.highlight { display: block; background-color: #ddd; }</style>
</head>
<body onload="setTimeout('prettyPrint()', 0);var node = document.getElementById(location.hash.replace(/#/, ''));if(node)node.className = 'highlight';"><pre class="prettyprint lang-js">/**
 * @author xuld
 */

Dom.implement({

	imageZoom: function(getUrlCallback){

	    return this.addClass('x-imagezoom-small').on('click', function (e) {
	    	if(this.hasClass('x-imagezoom-small')){
	    		this.removeClass('x-imagezoom-small').addClass('x-imagezoom-large');
	    		var oldState;
	    		if(getUrlCallback){
	    			this.dataField().imageZoomSrc = this.node.src;
	    			this.node.src = getUrlCallback(this.node.src);
	    		} else {
	    			this.dataField().imageZoomWidth = this.getWidth();
	    			this.dataField().imageZoomHeight = this.getHeight();
	    			this.node.style.width = this.node.style.height = 'auto';
	    		}
	    	} else {
	    		this.addClass('x-imagezoom-small').removeClass('x-imagezoom-large');
	    		if(getUrlCallback){
	    			this.node.src = this.dataField().imageZoomSrc;
	    		} else {
	    			this.setWidth(this.dataField().imageZoomWidth);
	    			this.setHeight(this.dataField().imageZoomHeight);
	    		}
	    	}
	    });
	}

});

</pre>
</body>
</html>


text:
package com.iamacitizen.core.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author felipe
 */
public class ImageUtils {

	/**
	 * Gera uma miniatura de um imagem.
	 * @param btyes array de bytes que representa a imagem
	 * @param width largura da imagem
	 * @param height altura da imagem
	 * @return a miniatura
	 */
	public static Image getThumb(byte[] btyes, int width, int height) {
		Image img = null;
		try {
			img = ImageIO.read(new ByteArrayInputStream(btyes));
			img = img.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);

		} catch (IOException ex) {
			//TODO: Desenhar uma imagem de erro padrão para retorno
		}
		return img;
	}
}


text:
    <title>Color Bot</title>

    <link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono|Roboto+Slab:400,700" rel="stylesheet">

            <input id="color_input" title="color" placeholder="Start Typing a Color" />

                    Chartreuse

What is this?

            This is an experiment using machine learning techniques to generate color based on a color name. Using over existing 12,000 color names
            scraped on the internet, I trained a model that accepted character-level input and generated a RGB color as the output. I've found it to
            be very accurate with existing colors, and can get pretty close to coming up with some reasonable for made up color names.

            Want to learn more? Click here for the blog post.


text:
package com.huawei.esdk.fusionmanager.local.impl.utils;

import com.huawei.esdk.fusionmanager.local.bean.ClientProviderBean;
/**
 * 线程对象缓存
 * @author k00207574
 * @since eSDK Cloud V100R003C20
 */
public class FMOutHeaderHolder
{

    public static final ThreadLocal<ClientProviderBean> fmHeaderHolder = new ThreadLocal<ClientProviderBean>();

    public static void set(ClientProviderBean holder)
    {
        fmHeaderHolder.set(holder);
    }

    public static void unset()
    {
        fmHeaderHolder.remove();
    }

    public static ClientProviderBean get()
    {
        return fmHeaderHolder.get();
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="The Bootstrap sweetest native Javascript library for vanilla Javascript lovers.">
    <meta name="keywords" content="Javascript,Native Javascript,native,Bootstrap,plugins,jQuery">
    <meta name="author" content="dnp_theme">
    <title>Native Javascript for Bootstrap</title>

	<link href="./assets/css/bootstrap.min.css" rel="stylesheet">

	<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

    <link href="./assets/css/theme.css" rel="stylesheet">

	<link href="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeEclipse.css" rel="stylesheet">

	<link rel="shortcut icon" href="./assets/img/favicon.ico">
	<link rel="apple-touch-icon" href="./assets/img/apple-touch-icon.png">

			  <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
				Toggle navigation

			  </button>
			  Native JavascriptJS for BootstrapNative Javascript for Bootstrap

Use

Examples

About

Github

Fork

Download

Dude, Welcome to Native Javascript!!

These are the jQuery plugins for Bootstrap 3 redeveloped with native Javascript. There are some small differences but only to improve performance while keeping the same basic functionality.

More

HTML5 please!

All scripts have been developed for today's standards, for a workflow careless about legacy browsers thanks to polyfill services that Upgrade the web. Automatically. A helping hand for the legacy browsers.

More

What's the fuzz?

If you use mainly Bootstrap plugins in your projects, you may drop jQuery right away. What I am talking about is that the comfort of using jQuery has a huge impact on performance. See it to believe it!

See Now

Explore the freedom

Not to worry, the internet is full of scripts and tutorials, native Javascript is literally the coolest thing ever! Far more powerful and requires almost zero maintenance on very long periods of time.

Get started Full Reference

This was a Carousel example

				A script like all the others here were developed from scratch. It works just as the original version with just about the same amount of code, and some smart optimizations.

How to use

Use

Load from CDN

Thanks to jsdelivr we have a CDN link, so drop this line before your ending </body> tag. Latest releases come here.

					<script type="text/javascript" src="https://cdn.jsdelivr.net/bootstrap.native/0.9.3/bootstrap-native.min.js"></script>

As most of the scripts manipulate the DOM when ready, there is no need to include a document.ready statement or link the script(s) in the <head>. That's your first performance tip if you are new around here.

Working locally

If you host the file on your project folders, download the package at github, unpack it, copy the file from the dist/ folder into your application's assets folder, then simply drop this line (according to your application assets folders) before your ending </body> tag.

					<script type="text/javascript" src="../assets/js/bootstrap-native.min.js"></script>

Alternatively you can link individual scripts, exactly the scripts required for your specific page. The lib folder comes with all scripts in both raw and minified distribution formats, perhaps you are using require.js or module loaders, check the next section.

npm, Bower, RequireJS, CommonJS

Thanks to Ingwie Phoenix, our scripts here can be easily loaded for npm, Bower , RequireJS or CommonJS, so if you are using a module loader, you can also use this package via require() as well. Here's how to do it:

                    var bsn = require("bootstrap.native");
                    // Create a button:
                    var btn = new bsn.Button(...);

This package can be installed using npm or Bower by using either of the commands below. You'll then be able to use the assets from the provided directory.

                    # Via bower:
                    $ bower install --save bootstrap.native

                    # Via NPM:
                    $ npm install --save bootstrap.native

Transitions

Since we are not using jQuery to do all the .slideToggle() or .animate() work, and in order to animate things, now we only need to enable the CSS3 transitions. Luckily, we only need one line, for collapse components, so copy this line in your application CSS files.

					/* enables CSS3 transition for simple collapses, accordion and also navbar in responsive view */
					.collapse { transition: height .3s ease-out; -webkit-transition: height .3s ease-out }

Browser Support

The scripts are tested to work perfect in all major browsers, and legacy browsers starting with IE8. Legacy browsers don't support CSS3 transitions and in order to make legacy browsers behave with the clean and fast code of today's HTML5 standards, make sure you include a polyfill that covers most of the scripts HTML5 code requirements for them. There are many more shims and polyfills out there, but this one below seems best, at least for me.

<script src="https://cdn.polyfill.io/v1/polyfill.min.js"></script>

OR give this one a try:

<script src="https://cdn.jsdelivr.net/polyfills/polyfill.js"></script>

OR include this one (locate polyfill.min.js) in your application assets folders, it does not cover Carousel's CustomEvent own events slid and slide.

Generally the scripts rely heavily on addEventListener, querySelector, classList, getBoundingClientRect, data- attributes, forEach, Event, dispatchEvent and other.

Remember that the polyfill link must be in your <head>. You can leave it there for all the browsers, but I think you should see this example here how I deleted the HTML5 shims link provided by default Bootstrap themes.

Before you go

All scripts run their specific functions right away, including Tooltip and Popover, as long as you use properly their DATA API attributes, so all except Button state/text toggle, you need to bind a handler for that, like the example shown here.

When a script targets an element via it's ID attribute, we always use getElementById, for obvious performance reasons. The other cases such as Collapse the target can also be invoked via it's className and querySelector is used.

Some functions have been dropped since I personally never found any use of them, each script example will provide detailed info on that.

Scripts doing transitions don't make use of any functions to detect transitionend, for performance and other reasons, we all know a fade is 150ms or carousel performs a 600ms slide animation, and most scripts have a simple option for that.

I personally don't use and don't recommend using Modernizr. However some scripts like carousel, collapse or tabs need to know if the browser is IE9- in order to avoid unwanted behaviour and not emulate transitionend when not supported. For that specific reason you should follow the example given here and add via Javascript the ie ie[version] class to your html tag like this:

<!--[if IE 8]><html class="ie ie8" lang="en"><![endif]-->

					or simply

<!--[if lt IE 10]><html class="ie" lang="en"><![endif]-->

					Since we only need the ie class really, this would do to some extent, but if you care to dig even deeper, here's a full reference on that. Remember: this isn't really a requirement, it's much more optional than you think. Scripts would perform perfect, but tabs for instance would have a 150ms delay of blank space while switching content. Still, this is the best practice I found so far for targeting specific functions to specific browsers.

Examples

Modal

						Modal has no events attached, such as show.bs.modal or shown.bs.modal, but if devs would need them, you can have a look at the code of carousel, it implements the events just like the original plugin.
						Modal also has no method as described in the documentation of the original script, except the options.

Options

content - the modal script comes with a template system instead of a load remote content function (Bootstrap 4 drops it). This option is only for Javascript invocation.

duration - if you are customizing the fade animation duration for Modal, you need to provide a duration via Javascript invoke function or data-duration="DURATION" attribute, an option to make sure everything is syncronized. This option is 300 by default, just like Bootstrap Modal fade duration.

keyboard - option to dismiss the current modal via Esc key. This option is true by default.

backdrop - option use / not the backdrop. This option is true by default.

Examples

Now let's have a look at some examples and write some more instructions.

							  <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

Title in a modal

This is a link inside modal, est non commodo luctus, nisi erat porttitor ligula.

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

If you click this link, you will close this modal.

							  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

						<button type="button" class="btn btn-warning btn-lg" data-toggle="modal" data-target="#myModal">Launch simple modal</button>
						<button id="custom-modal-template" type="button" data-toggle="modal" class="btn btn-default btn-lg" data-target="#myModal1">Launch modal from template</button>
						Same modal, other template

The first example above is just about the exact same as the first example at Bootstrap demo page, everything is exactly the same. The next two examples use the Modal template system. Here's how to do:

						<!-- first, you need to provide a basic modal structure -->
						<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
							<div class="modal-dialog">
							  <div class="modal-content">

							  </div>
							</div>
						</div>

The backdrop will be added automatically if not otherwise disabled. Ok now we need a trigger.

						<!-- the modal can be triggered via a button with data-target="#myModal" attribute (example 2) -->
						<button id="custom-modal-template" type="button" data-toggle="modal" class="btn btn-default btn-lg" data-target="#myModal">Launch modal from template</button>
						<!-- or a link with href="#myModal" attribute (example 3) -->
						<a id="custom-modal-template" data-toggle="modal" class="btn btn-default btn-lg" href="#myModal">Launch modal from template</a>

Finally we need a proper handler function to use the template system and fill the <div class="modal-content"> element. The example below can be found in the ../assets/js/scripts.js file.

						var modalFrame = document.getElementById('myModal'); // we need a blank modal to fill up
						var btnModal = document.getElementById('custom-modal-template'); // we grab the button trigger by it's ID
						btnModal.addEventListener('click', function() {
							//template content for modal example 2, should work for the third button as well
							var modal2 = new Modal(modalFrame, {
							content:
							'<div class="modal-header">'
							+'<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'
							+'<h4 class="modal-title" id="gridModalLabel">Modal title</h4>'
							+'</div>'
							+'<div class="modal-body">'
							+'<p>This is where you fill up content you know, etc.</p>'
							+'</div>'
							+'<div class="modal-footer">'
							+'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
							+'<button type="button" class="btn btn-primary">Save changes</button>'
							+'</div>'});
						});

By changing the innerHTML of the modal-header, modal-body or modal-footer with variables, you can achieve exactly the same as the other examples from the demo of the original plugin.

Dropdown

Dropdown opens the dropdown-menu on click and closes it on click/blur after a 200ms timeout, to properly handle click on it's menu items, including external links. Dropdown doesn't cover the original methods or events, it simply toggles the dropdown.

					  <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Simple Dropdown </button>

Action

Another action

Something else here

Separated link

					  <button type="button" class="btn btn-default">Split Dropdown</button>
					  <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-expanded="false"></button>

Action

Another action

Something else here

External link

							Pill

Action

Another action

Something else here

External link

							Dropdown

Action

Another action

Something else here

External link

Scrollspy

						ScrollSpy requires the element and all it's childNodes to have position: relative and fill the entire area, so it does not work on targeting headings. See the notes below the example.
						The script does not cover the original methods, events or option, can only be controlled via DATA API.

The object always targets a .nav component, where the original plugin targets it's wrapper, and this was creating lots of confusion.

Options

target - the only option for Scrollspy, is the target of the container with data-spy="scroll" attribute. Can be set as shown via DATA API or Javascript. See notes for the example below.

Example

							  <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#scrollSpy-nav">
								Toggle navigation

							  </button>
							  Project Name

@fat

@mdo

								  Dropdown

one

two

three

@fat

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

@mdo

Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

one

Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

two

In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

three

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.

The above example, is the exact same as for the original plugin. For this example we are having the scrollTarget as the element itself and above it the .nav component to target the Scrollspy object.

						<div data-spy="scroll" data-target="#navbar-example2" class="scrollspy-example">

						<ul id="navbar-example2" class="nav">

Generally for Scrollspy to work perfect, you would want to avoid incorrect behavior because the element's children don't fill their entire area, you may consider using:

.scrollspy-example > * { float: left; width: 100%; clear: both }

Also like the original plugin, the other example in this page is the side navigation on the right side that pins to top. This example uses the window as the internal scrollTarget, but you don't have to worry about that, it's just for you to know.

Tab

						Tab works with any kind of navigation components in Bootstrap as you can see in the example below.
						The script only works via DATA API, and has no support for the original methods or events.
						Unlike the original plugin, the animation is smooth because it waits for the current active tab to fade away first before animating the next.

Options

duration - the only option for Tab, is an internal 150ms duration setting to emulate transitionend. If you are using a different fade duration than the default plugin, this can be set via data-duration="DURATION" attribute.

Example

								<button type="button" class="btn btn-success btn-xs" data-toggle="dropdown">Toggle View</button>
								<button type="button" class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"></button>

Tabs

Pills Horizontal

Pills Stacked

Inline List

Navbar

Regular Nav

Panel

Home

Profile

						Dropdown

Some tab

Other tab

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

Tooltip

This here is an example Tooltip only using data-toggle="tooltip". Unlike the original Bootstrap Tooltip, the native Javascript version here can do automatic placement, without any additional options required. Another key difference is that this script will never bubble, also worth mentioning it works perfect with IE8+ and is half the size of the original script.

Now let's test all the other placement positions, we start with the bottom placement, then left, and right.

Options

animation - option to customize the Tooltip animation. If you are using a different animation other than fade, you can specify that via data-animation="ANIMATION" attribute. This will add an additional CSS class to the Tooltip to enable a custom transition. The default value is fade.

placement - option to set a specific Tooltip placement to top, bottom, left or right, relative to it's target. The default value is top.

duration - is an internal 150ms duration setting to emulate transitionend. If you are using a different duration than the default plugin, this can be set via data-duration="DURATION" attribute. The default value is 150.

delay - is an internal 100ms delay before generating the tooltip, helpful for legacy browsers to be able to compute the automatic positioning. Can be set via data-delay="DELAY" attribute. The default value is 100.

Examples

Let's put it to the test! Some heavy testing on the automatic repositioning with very very long tooltips.

					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Left</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Top</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">Bottom</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right">Right</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left
 Here we add more content for testing. Perhaps adding even more content would make the job more difficult? Nope, same as if this was a very very short tooltip. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas.">Left</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top
 Here we add more content for testing. Perhaps adding even more content would make the job more difficult? Nope, same as if this was a very very short tooltip. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas.">Top</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom
 Here we add more content for testing. Perhaps adding even more content would make the job more difficult? Nope, same as if this was a very very short tooltip. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas.">Bottom</button>
					  <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right
 Here we add more content for testing. Perhaps adding even more content would make the job more difficult? Nope, same as if this was a very very short tooltip. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas.">Right</button>

Additional Note

You can also enable Tooltip for elements not having the specific DATA API, but have a title="Not null title" attribute. You can do the following:

						// find all elements with title attribute
						var elementsTooltip = document.querySelectorAll('[title]');

						// attach a tooltip for each
						[].forEach.call(elementsTooltip, function(el) {
							var elTooltip = new Tooltip(el, {
								placement: 'top', //string
								animation: 'slideNfade', // CSS class
								duration: 200, // integer
								delay: 150, // integer
							})
						});

Tooltip always uses the document.body as the containe and doesn't cover template system like the original, and remember that it can do automatic placement without any additional options.

Popover

This here is an example Popover using data-toggle="popover". Unlike the original Bootstrap Popover, this script does not require the Tooltip script and works just about the same as the above except that Popover has, like the original script, the ability to work with templates and trigger options: hover (default), click and focus.

Without further talking, let's test all the options, and placement positions, we start with the bottom placement, then left, and right.

Options

template - via Javascript, you can dynamically create popovers via the template system. See examples below.

content - the data-content="CONTENT" attribute to fill the Popover. If the template is not specified via Javascript or the content option is not set, the Popover will not initiate.

title - the data-title="TITLE" attribute to fill the Popover title.

trigger - option to change the Popover trigger event: hover, focus and click. In some cases you may want to open Popover on focus for form elements or click for other buttons, you can specify that via data-trigger="EVENT" attribute. The default value is hover.

animation - option to customize the Popover animation. If you are using a different animation other than fade, you can specify that via data-animation="ANIMATION" attribute. This will add an additional CSS class to the Popover to enable a custom transition. The default value is fade.

placement - option to set a specific Popover placement to top, bottom, left or right, relative to it's target. The default value is top.

duration - is an internal 150ms duration setting to emulate transitionend. If you are using a different duration than the default plugin, this can be set via data-duration="DURATION" attribute. The default value is 150.

delay - is an internal 100ms delay before generating the Popover, helpful for legacy browsers to be able to compute the automatic positioning. Can be set via data-delay="DELAY" attribute. The default value is 100.

Examples

Now we are going to test buttons and Popover with large contents. The last two examples below are using the template system and different trigger options. The Popover generated for the last two examples can be dismissed on window resize or blur (focus out).

						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="left" data-content="Popover on left">Left</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="top" data-content="Popover on top">Top</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="bottom" data-content="Popover on bottom">Bottom</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="right" data-content="Popover on right">Right</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="left" data-content="Popover on left
 Here we add more content for testing. Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits.">Left</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="top" data-content="Popover on top
 Here we add more content for testing. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. ">Top</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="bottom" data-content="Popover on bottom
 Here we add more content for testing. Completely synergize resource sucking relationships via premier niche markets.">Bottom</button>
						<button type="button" class="btn btn-default" data-toggle="popover" data-placement="right" data-content="Popover on right
 Here we add more content for testing. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas.">Right</button>
						<input style="max-width: 180px; display: inline; width: auto" type="text" value="" class="form-control popover-via-template" placeholder="Focus me" data-toggle="popover">
						<button type="button" id="popover-via-click" class="btn btn-default" data-trigger="click" data-content="You clicked the button and as a result, this message box simply.. popped.
Now simply click anywhere to dismiss.">Click to open</button>

Additional Note

To use the template system, you can attach a custom handler to a target as the following:

						//define some variables or get their values from other scripts
						var someTitleFromOtherCode = 'Sample title';
						var someContentFromOuterSpace = '<p>Some sample message.</p>';

						//initiate Popover with the template
						var popover2 = new Popover('.popover-via-template', { // where .popover-via-template is the text input
							trigger: 'focus',
							template: '<div class="popover" role="tooltip">'
							+ '<div class="arrow"></div>'
							+ '<h3 class="popover-title">'+someTitleFromOtherCode+'</h3>'
							+ '<div class="popover-content">'+someContentFromOuterSpace+'</div>'
							+ '</div>'
						});

The above code can be found in the ../assets/js/scripts.js file.

Remember - Popover always uses the document.body as the container, just like the Tooltip and does automatic placement without options.

Alert

Alert does not have any events and methods, it's action simply dismisses the Alert component. Unlike the original plugin, this script can successfully handle later added alerts into the DOM. See Button first example below.

					  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
					  Holy guacamole! Best check yo self, you're not looking too good.

					  <button type="button" class="close" aria-label="Close">×</button>

Oh snap! You got an error!

Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.

						<button type="button" class="btn btn-danger">Take this action</button>
						<button type="button" class="btn btn-default">Or do this</button>

Alert also uses a 150ms internal duration to emulate transitionend. No option required or needed really.

Button

Button script allows you to change the text of a given button. If using a data-loading-text="Loading.." attribute, the button will also change it's state to disabled. The other function of the script is to toggle checkboxes and radio buttons, it's a most awaited form replacement for the good old checks and radios.

Options

STRING-text - the only option for Button, allows you to change a button's text via it's data-OPTION-text="Sample text" attribute.

Example

This is a quick example of button setting state via string options. Like the original script we make an example for loading state for the button. For the purpose of testing here, the button will come back to original state after a short setTimeout delay.

<button type="button" id="myButton" data-toggle="button" data-loading-text="Loading..." class="btn btn-primary">Loading state</button>

Basic Usage

						<button type="button" id="myButton" data-toggle="button" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">
							Loading state
						</button>

						//the method works like this
						var btn = document.getElementById('myButton');
						btn.addEventListener('click', function() {
							new Button(btn,'loading'); //this assumes button has a data-loading-text="Loading..." attribute
						})

This action will create an additional data-original-title="Loading state" attribute, required for the below reset method.

						//the reset method works like this
						new Button(btn,'reset');

Next we will toggle some checkboxes. You should open your console to test the handler functions bound by the change event of the following checkboxes and radio buttons.

							<input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)

							<input type="checkbox" autocomplete="off"> Checkbox 2

							<input type="checkbox" autocomplete="off"> Checkbox 3

Finally we toggle radio buttons.

							<input type="radio" name="options" id="option1" autocomplete="off"> Radio 1

							<input type="radio" name="options" id="option2" autocomplete="off" checked> Radio 2 (preselected)

							<input type="radio" name="options" id="option3" autocomplete="off"> Radio 3

As a quick note, here's the example for checkboxes.

						<div class="btn-group" data-toggle="buttons">
						  <label class="btn btn-default active">
							<input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
						  </label>
						  <label class="btn btn-default">
							<input type="checkbox" autocomplete="off"> Checkbox 2
						  </label>
						  <label class="btn btn-default">
							<input type="checkbox" autocomplete="off"> Checkbox 3
						  </label>
						</div>

The ../assets/js/scripts.js file has some console log functions bound by the change of the .btn-group components.

						//grab all checkboxes
						var checkBtns = document.querySelectorAll('input[type="checkbox"]');

						//attach a handler to first
						checkBtns[0].addEventListener('change',function() {
							// do your stuff when first checkbox changes
						})

						// OR
						//attach a handler to the first btn-group
						document.querySelectorAll('[data-toggle="buttons"]')[0].addEventListener('change', function(e) {
							console.log( 'The button group with checkboxes inside changed' );
							//do your stuff when btn-group changed
						});

Additional Notes

						Button will activate automatically for all .btn-group component instances if they have data-toggle="buttons" and the appropriate input elements inside like our examples here.
						The script properly covers the "change" event for checkbox and radio buttons, allowing other functions to bind into context. The event is also bound to the .btn-group component.
						The script doesn't have any method to control it's toggle functions for checkbox and radio buttons as described by the documentation of the original plugin.

Button also doesn't cover single toggle.

Collapse

Collapse is a great way to toggle content, and it's also used for collapsible navbar. It's not animating on modern browsers unless you use the provided CSS, and legacy browsers don't support transitions. Unlike other scripts, this is the only component that can be targeted by it's toggle links by it's className via the data-target=".className" attribute, along with the traditional data-target="#collapseId". The collapsible navbar in Bootstrap for instance works mostly via data-target=".bs-navbar-collapse" attribute.

Collapse requires proper wrapping of contents, similar to wells, accordion and responsive navbar examples. With other words, you cannot toggle a bunch of paragraphs at once unless you wrap them into a container and give it a unique ID and a collapse class.

Options

duration - the only option required is a 300ms duration internal setting just as in the provided CSS, to emulate transitionend for modern browsers. If you use a different duration, you can specify that via data-duration="DURATION" attribute.

Examples

Here's a quick collapse demonstration, but I would also recommend you to try the navbar on this page on a smaller screen size or on a mobile device.

					  Link with href
					  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="true" aria-controls="collapseExample">Button with data-target</button>

						Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Here's an Accordion component, basically a set of Panel components. When the toggle links are clicked, our Collapse object will look for the closest <div class="accordion-className" or <div id="accordion-id" via data-parent="selector".

							  Collapsible Group Item #1

							Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

							  Collapsible Group Item #2

							Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

							  Collapsible Group Item #3

							Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Remember that all toggle links must reference the accordion via data-parent="selector" as described above in order to collapse current opened container.

Carousel

Carousel is an excelent content showcase script, and as the original plugin, it handles both slid and slide events, just as shown in the example below.

The script uses an internal duration value (default Bootstrap Carousel transition duration) + 100ms more, needed to emulate transitionend, and during this time, all click handlers are disabled to prevent any animation issue or code bubbles, similar to the original script. On legacy browsers this duration is 100ms and your HTML tag needs a class ie for that.

When configured to pause on hover, it also adds a paused class to it to help prevent any anomalies. The script does not implement the original methods.

Options

duration - an option to customize the 600ms internal duration required to emulate transitionend for modern browsers. If you use a different duration, you can specify that via data-duration="DURATION" attribute. The default value is 600.

interval - the time delay between transitions. If you want to use a different interval, you can specify that via data-interval="INTERVAL" attribute. To disable automatic transition, simply use data-interval="false" attribute. The default value is 5000.

pause - makes possible to pause the carousel transition on mouse hover and touchdown. If you want to disable pause on hover, do that via data-pause="false" attribute. The default value is hover.

keyboard - enables the carousel to be controllable via left and right keyboard keys. If you want to enable this option, do that via data-keyboard="true" attribute. The default value is false.

Example

 This is a test demonstrating the carousel capabilities and it's events, so open your console, and start clicking, you will be noticed before and after the animation.

This is another carousel

This is a caption

This is another caption

							Previous

							Next

The handlers bound to Carousel's specific events explain what happens with the other example in this site's header. Let's have a quick look at it.

						//demo myCarousel demonstrating the slid and slide events
						var mainSlider = document.getElementById('myCarousel');
						mainSlider.addEventListener('slid.bs.carousel', function(e) {
							// get the caption of current active item before slide
							var active = mainSlider.querySelector('.item.active .carousel-caption');
							active.classList.remove('slide')
						});
						mainSlider.addEventListener('slide.bs.carousel', function(e) {
							// get the caption of new active item after slide
							var active = mainSlider.querySelector('.item.active .carousel-caption');
							active.classList.add('slide')
						});

Additional Notes

Carousel does not use DATA API for previous and next navigation controls, which means you can ignore data-slide="prev" and data-slide="next" attributes, but they must have at least class="carousel-control".

Affix

Affix is the one little script pinning the side navigation to top once the scroll reaches a certain offset value. It works exactly like the original and requires some additional CSS in order to work properly. When scrolling the page, the given element will receive an affix class once the scroll reaches the target or given offset value, and further more an additional affix-bottom class once the scroll value reaches the maximum scroll height at the given bottom offset.

Options

target - Affix can pin an element to top once the scroll reaches it's target offsetTop. You can set the target via data-target="target-className" or data-target="#target-ID" attribute.

offsetTop - allows an element to pin to top when scroll reaches a specific value. This can be set via data-offset-top="OFFSET" attribute, where OFFSET is integer. Via Javascript you can also assign a function to our offsetTop option.

offsetBottom - allows an element to pin to bottom at a certain offset relative to the window maximum scroll. This can be set via data-offset-bottom="OFFSET" attribute, where OFFSET is integer. Via Javascript you can also assign a function to our offsetBottom option.

Example

Here we go, we'll have a look at our example here and explain things. First we configure an element to be pinned to top and / or bottom.

						<ul class="nav nav-stacked" data-spy="affix" data-target="#use" data-offset-bottom="200">

Alternatively, via Javascript we can achieve the same with:

						//grab the element by it's ID
						var elToAffix = document.getElementById('myNav');
						var theAffix = new Affix(elToAffix, {
							target: '#use',
							offsetBottom: 200,
						});

Similar to the original plugin, we can make use of a function, we can determine the offsetTop value from the height of the previous element above the initial target:

						var elToAffix = document.getElementById('myNav');
						var theAffix = new Affix(elToAffix, {
							offsetTop: function(){
								return document.getElementById('myCarousel').offsetHeight
							},
							offsetBottom: 200,
						});

Now we must make sure our element is properly styled to make sure it works properly.

						/* this style applies to mobile devices, on screens SMALLER than 768px */
						/* affix example */
						#side-nav {clear: both}
						#side-nav .nav.affix,
						#side-nav .nav.affix.affix-bottom { position: relative; margin: 20px 0; }

						/* this style applies to other devices, on screens LARGER than 768px */
						@media (min-width: 768px) {
							/* affix example */
							#side-nav .nav.affix { position: fixed !important;  width: 263px; top: 0; }
							#side-nav .nav.affix.affix-bottom { top: auto;  bottom: 150px; }
						}

Additional Note

Using static values for offsetTop and / or offsetBottom would work best on non-responsive websites, or when the elements don't change their height when window resize occurs.

The given ../assets/js/script.js also provides a way to automatically resize the pinned element when window resize occurs. Make sure you check that too.

About

Why Native Javascript?

					Mission | The Native Javascript for Bootstrap project was born to help. It doesn't totally and perfectly replace all the functions the jQuery Plugins have for Bootstrap, but the essential tools.
					In many cases it performs much better than the original code, like an upgraded version of the original. I've literally learned to code native Javascript developing these scripts here. To sum up, this aims to help me and you transition into a better developer, doing things right from the next big project.

					Context | Today's most popular HTML5 framework is Bootstrap and like any other there's ups and downs. We all know about the PROs, but one of the CONs is the jQuery dependency.
					Why in the world would you ever drop jQuery? What can you put in it's place? The answer is this this: clean Javascript code. All browsers on all devices support it or they damn should be, because nothing would work, not even jQuery, Zepto, Dojo, AngularJS, whatever.
					The latest trends indicate that jQuery already peaked and is becoming less and less relevant.

					Perspective | The standards are now generally adopted and mobile platforms are "on the wave". The future brings more changes and we cannot fix-n-hack or hack-to-fix anymore via jQuery.
					Performance is the one and only true goal to follow, so if dropping jQuery and cleaning up the code is the way to go, we'll go for it. jQuery is still so cool and efficient but I feel it's too overpowered with it's cross-browser solutions.
					With the new Javascript engines and HTML5 standards, really, why not code native code, it's really not that hard.

Really Write Less, Do More?

Why do I feel this sounds much too bold after only a few weeks of vanilla Javascript? With the given Javascript here and some CSS customizations you can now do alot more than jQuery with the original Bootstrap plugins. As I have shown here, I think I've completely blasted the "do more" myth.

If you forgot to check performance metrics, go ahead (there are lots more out there, plus a ton of guides on how to boost performance), there is also the page load speed issue I forgot to mention. Imagine you can be drastically improve the page load by dropping jQuery.

If we compare the size of jQuery v1.11.2 + Bootstrap v3.3.2 minified is just about 93Kb + 36Kb = 129Kb. Our scripts here are (depending on your browser) 18Kb + 33Kb = 38Kb - 51Kb, where 18Kb is the maximum size of the minified polyfill for IE8, mostly under 5kb for most modern browsers.

This being said, jQuery doesn't make any sense for many of us.

Navigation

Download

Use

					Examples

Modal

Dropdown

ScrollSpy

Tab

Tooltip

Popover

Alert

Button

Collapse

Carousel

Affix

About

Back to top

NJB © 2015 dnp_theme.


text:
import decimal
import random
from django.core.exceptions import ValidationError
from django.db import models
from django import forms
from staging.generators import BaseGenerator

class RandomCoordinateForm(forms.Form):
    base_coordinate = forms.DecimalField(help_text='center location latitude or longitude in degrees')
    max_distance = forms.DecimalField(help_text='max shift to latitude or longitude in degrees')

    def clean(self):
        data = super(RandomCoordinateForm, self).clean()
        if data.get('max_distance') < 0:
            raise ValidationError('Max distance should be positive')
        return data

class NotInitialized():
    pass

class Generator(BaseGenerator):
    name = 'Random coordinate'
    slug = 'random-coordinate'
    for_fields = [models.DecimalField]
    options_form = RandomCoordinateForm

    def __init__(self):
        self.numbers_left = NotInitialized

    def save(self, obj, field, form_data):
        setattr(obj, field.name, self._generate(form_data.get('base_coordinate', 0), form_data.get('max_distance', 1)))

    def _generate(self, base_coordinate, max_distance):
        max_distance = int(max_distance) * 1000000
        value = decimal.Decimal(base_coordinate) + decimal.Decimal(random.randrange(max_distance * 2) - max_distance) / 1000000
        if value > 180:
            value = 180
        if value < -180:
            value = -180
        return value


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.2.0/mocha.css">


text:
          Helium Jekyll - Bootstrap 4 UI Kit Crafted with  by Antonio Trento

                  {% if site.author.facebook %}{% endif %}
                  {% if site.author.twitter %}{% endif %}
                  {% if site.author.linkedin %}{% endif %}
                  {% if site.author.instagram %}{% endif %}


text:
#ifndef DART_UTILS_MJCF_DETAIL_JOINTATTRIBUTES_HPP_
#define DART_UTILS_MJCF_DETAIL_JOINTATTRIBUTES_HPP_

#include <Eigen/Core>
#include <tinyxml2.h>

#include "dart/common/Optional.hpp"
#include "dart/utils/mjcf/detail/Error.hpp"
#include "dart/utils/mjcf/detail/Types.hpp"

namespace dart {
namespace utils {
namespace MjcfParser {
namespace detail {

struct JointAttributes final
{
  std::optional<std::string> mName;

  JointType mType{JointType::HINGE};

  int mGroup{0};

  /// Position of the joint, specified in local or global coordinates as
  /// determined by the coordinate attribute of compiler. For free joints this
  /// attribute is ignored.
  Eigen::Vector3d mPos{Eigen::Vector3d::Zero()};

  /// This attribute specifies the axis of rotation for hinge joints and the
  /// direction of translation for slide joints. It is ignored for free and ball
  /// joints.
  Eigen::Vector3d mAxis{Eigen::Vector3d::UnitZ()};

  Eigen::Vector2d mSpringDamper{Eigen::Vector2d::Zero()};

  /// This attribute specifies if the joint has limits.
  bool mLimited{false};

  double mStiffness{0};

  /// The joint limits.
  Eigen::Vector2d mRange{Eigen::Vector2d::Zero()};

  double mMargin{0};

  double mRef{0};

  double mSpringRef{0};

  double mArmature{0};

  double mDamping{0};

  double mFrictionLoss{0};

  Eigen::VectorXd mUser;
};

Errors appendJointAttributes(
    JointAttributes& attributes, tinyxml2::XMLElement* element);

} // namespace detail
} // namespace MjcfParser
} // namespace utils
} // namespace dart

#endif // #ifndef DART_UTILS_MJCF_DETAIL_JOINTATTRIBUTES_HPP_


text:
/*
 *  S390 version
 *
 *  Derived from "include/asm-i386/mmu_context.h"
 */

#ifndef __S390_MMU_CONTEXT_H
#define __S390_MMU_CONTEXT_H

#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/tlbflush.h>
#include <asm/ctl_reg.h>

static inline int init_new_context(struct task_struct *tsk,
				   struct mm_struct *mm)
{
	atomic_set(&mm->context.attach_count, 0);
	mm->context.flush_mm = 0;
	mm->context.asce_bits = _ASCE_TABLE_LENGTH | _ASCE_USER_BITS;
#ifdef CONFIG_64BIT
	mm->context.asce_bits |= _ASCE_TYPE_REGION3;
#endif
	mm->context.has_pgste = 0;
	mm->context.asce_limit = STACK_TOP_MAX;
	crst_table_init((unsigned long *) mm->pgd, pgd_entry_type(mm));
	return 0;
}

#define destroy_context(mm)             do { } while (0)

#ifndef CONFIG_64BIT
#define LCTL_OPCODE "lctl"
#else
#define LCTL_OPCODE "lctlg"
#endif

static inline void update_mm(struct mm_struct *mm, struct task_struct *tsk)
{
	pgd_t *pgd = mm->pgd;

	S390_lowcore.user_asce = mm->context.asce_bits | __pa(pgd);
	/* Load primary space page table origin. */
	asm volatile(LCTL_OPCODE" 1,1,%0\n" : : "m" (S390_lowcore.user_asce));
	set_fs(current->thread.mm_segment);
}

static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next,
			     struct task_struct *tsk)
{
	cpumask_set_cpu(smp_processor_id(), mm_cpumask(next));
	update_mm(next, tsk);
	atomic_dec(&prev->context.attach_count);
	WARN_ON(atomic_read(&prev->context.attach_count) < 0);
	atomic_inc(&next->context.attach_count);
	/* Check for TLBs not flushed yet */
	__tlb_flush_mm_lazy(next);
}

#define enter_lazy_tlb(mm,tsk)	do { } while (0)
#define deactivate_mm(tsk,mm)	do { } while (0)

static inline void activate_mm(struct mm_struct *prev,
                               struct mm_struct *next)
{
        switch_mm(prev, next, current);
}

static inline void arch_dup_mmap(struct mm_struct *oldmm,
				 struct mm_struct *mm)
{
#ifdef CONFIG_64BIT
	if (oldmm->context.asce_limit < mm->context.asce_limit)
		crst_table_downgrade(mm, oldmm->context.asce_limit);
#endif
}

static inline void arch_exit_mmap(struct mm_struct *mm)
{
}

#endif /* __S390_MMU_CONTEXT_H */


text:
package com.wrmsr.wava.java.poet;

import org.junit.Ignore;
import org.junit.Test;

import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

public class TestAnnotatedTypeName
{

    private final static String NN = NeverNull.class.getCanonicalName();
    private final AnnotationSpec NEVER_NULL = AnnotationSpec.builder(NeverNull.class).build();

    @Test(expected = NullPointerException.class)
    public void nullAnnotationArray()
    {
        TypeName.BOOLEAN.annotated((AnnotationSpec[]) null);
    }

    @Test(expected = NullPointerException.class)
    public void nullAnnotationList()
    {
        TypeName.DOUBLE.annotated((List<AnnotationSpec>) null);
    }

    @Test
    public void annotated()
    {
        TypeName simpleString = TypeName.get(String.class);
        assertFalse(simpleString.isAnnotated());
        assertEquals(simpleString, TypeName.get(String.class));
        TypeName annotated = simpleString.annotated(NEVER_NULL);
        assertTrue(annotated.isAnnotated());
        assertEquals(annotated, annotated.annotated());
    }

    @Test
    public void annotatedType()
    {
        String expected = "@" + NN + " java.lang.String";
        TypeName type = TypeName.get(String.class);
        String actual = type.annotated(NEVER_NULL).toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedTwice()
    {
        String expected = "@" + NN + " @java.lang.Override java.lang.String";
        TypeName type = TypeName.get(String.class);
        String actual =
                type.annotated(NEVER_NULL)
                        .annotated(AnnotationSpec.builder(Override.class).build())
                        .toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedParameterizedType()
    {
        String expected = "@" + NN + " java.util.List<java.lang.String>";
        TypeName type = ParameterizedTypeName.get(List.class, String.class);
        String actual = type.annotated(NEVER_NULL).toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedArgumentOfParameterizedType()
    {
        String expected = "java.util.List<@" + NN + " java.lang.String>";
        TypeName type = TypeName.get(String.class).annotated(NEVER_NULL);
        ClassName list = ClassName.get(List.class);
        String actual = ParameterizedTypeName.get(list, type).toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedWildcardTypeNameWithSuper()
    {
        String expected = "? super @" + NN + " java.lang.String";
        TypeName type = TypeName.get(String.class).annotated(NEVER_NULL);
        String actual = WildcardTypeName.supertypeOf(type).toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedWildcardTypeNameWithExtends()
    {
        String expected = "? extends @" + NN + " java.lang.String";
        TypeName type = TypeName.get(String.class).annotated(NEVER_NULL);
        String actual = WildcardTypeName.subtypeOf(type).toString();
        assertEquals(expected, actual);
    }

    @Test
    public void annotatedEquivalence()
    {
        annotatedEquivalence(TypeName.VOID);
        annotatedEquivalence(ArrayTypeName.get(Object[].class));
        annotatedEquivalence(ClassName.get(Object.class));
        annotatedEquivalence(ParameterizedTypeName.get(List.class, Object.class));
        annotatedEquivalence(TypeVariableName.get(Object.class));
        annotatedEquivalence(WildcardTypeName.get(Object.class));
    }

    private void annotatedEquivalence(TypeName type)
    {
        assertFalse(type.isAnnotated());
        assertEquals(type, type);
        assertEquals(type.annotated(NEVER_NULL), type.annotated(NEVER_NULL));
        assertNotEquals(type, type.annotated(NEVER_NULL));
        assertEquals(type.hashCode(), type.hashCode());
        assertEquals(type.annotated(NEVER_NULL).hashCode(), type.annotated(NEVER_NULL).hashCode());
        assertNotEquals(type.hashCode(), type.annotated(NEVER_NULL).hashCode());
    }

    // https://github.com/square/javapoet/issues/431
    @Ignore
    @Test
    public void annotatedNestedType()
    {
        String expected = "java.util.Map.@" + TypeUseAnnotation.class.getCanonicalName() + " Entry";
        AnnotationSpec typeUseAnnotation = AnnotationSpec.builder(TypeUseAnnotation.class).build();
        TypeName type = TypeName.get(Map.Entry.class).annotated(typeUseAnnotation);
        String actual = type.toString();
        assertEquals(expected, actual);
    }

    // https://github.com/square/javapoet/issues/431
    @Ignore
    @Test
    public void annotatedNestedParameterizedType()
    {
        String expected = "java.util.Map.@" + TypeUseAnnotation.class.getCanonicalName()
                + " Entry<java.lang.Byte, java.lang.Byte>";
        AnnotationSpec typeUseAnnotation = AnnotationSpec.builder(TypeUseAnnotation.class).build();
        TypeName type = ParameterizedTypeName.get(Map.Entry.class, Byte.class, Byte.class)
                .annotated(typeUseAnnotation);
        String actual = type.toString();
        assertEquals(expected, actual);
    }

    public @interface NeverNull {}

    // https://github.com/square/javapoet/issues/431
    // @Target(ElementType.TYPE_USE) requires Java 1.8
    public @interface TypeUseAnnotation {}
}


text:
using System;

namespace UnityEngine.Analytics.Experimental.Tracker
{
    public enum TriggerOperator{
        Equals,
        DoesNotEqual,
        IsGreaterThan,
        IsGreaterThanOrEqualTo,
        IsLessThan,
        IsLessThanOrEqualTo,
        IsBetween,
        IsBetweenOrEqualTo,
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/eventarc/v1/channel.proto

namespace Google\Cloud\Eventarc\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * A representation of the Channel resource.
 * A Channel is a resource on which event providers publish their events.
 * The published events are delivered through the transport associated with the
 * channel. Note that a channel is associated with exactly one event provider.
 *
 * Generated from protobuf message google.cloud.eventarc.v1.Channel
 */
class Channel extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The resource name of the channel. Must be unique within the
     * location on the project and must be in
     * `projects/{project}/locations/{location}/channels/{channel_id}` format.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED];
     */
    private $name = '';
    /**
     * Output only. Server assigned unique identifier for the channel. The value
     * is a UUID4 string and guaranteed to remain unchanged until the resource is
     * deleted.
     *
     * Generated from protobuf field string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $uid = '';
    /**
     * Output only. The creation time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $create_time = null;
    /**
     * Output only. The last-modified time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $update_time = null;
    /**
     * The name of the event provider (e.g. Eventarc SaaS partner) associated
     * with the channel. This provider will be granted permissions to publish
     * events to the channel. Format:
     * `projects/{project}/locations/{location}/providers/{provider_id}`.
     *
     * Generated from protobuf field string provider = 7;
     */
    private $provider = '';
    /**
     * Output only. The state of a Channel.
     *
     * Generated from protobuf field .google.cloud.eventarc.v1.Channel.State state = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $state = 0;
    /**
     * Output only. The activation token for the channel. The token must be used
     * by the provider to register the channel for publishing.
     *
     * Generated from protobuf field string activation_token = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $activation_token = '';
    /**
     * Optional. Resource name of a KMS crypto key (managed by the user) used to
     * encrypt/decrypt their event data.
     * It must match the pattern
     * `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
     *
     * Generated from protobuf field string crypto_key_name = 11 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = {
     */
    private $crypto_key_name = '';
    protected $transport;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The resource name of the channel. Must be unique within the
     *           location on the project and must be in
     *           `projects/{project}/locations/{location}/channels/{channel_id}` format.
     *     @type string $uid
     *           Output only. Server assigned unique identifier for the channel. The value
     *           is a UUID4 string and guaranteed to remain unchanged until the resource is
     *           deleted.
     *     @type \Google\Protobuf\Timestamp $create_time
     *           Output only. The creation time.
     *     @type \Google\Protobuf\Timestamp $update_time
     *           Output only. The last-modified time.
     *     @type string $provider
     *           The name of the event provider (e.g. Eventarc SaaS partner) associated
     *           with the channel. This provider will be granted permissions to publish
     *           events to the channel. Format:
     *           `projects/{project}/locations/{location}/providers/{provider_id}`.
     *     @type string $pubsub_topic
     *           Output only. The name of the Pub/Sub topic created and managed by
     *           Eventarc system as a transport for the event delivery. Format:
     *           `projects/{project}/topics/{topic_id}`.
     *     @type int $state
     *           Output only. The state of a Channel.
     *     @type string $activation_token
     *           Output only. The activation token for the channel. The token must be used
     *           by the provider to register the channel for publishing.
     *     @type string $crypto_key_name
     *           Optional. Resource name of a KMS crypto key (managed by the user) used to
     *           encrypt/decrypt their event data.
     *           It must match the pattern
     *           `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Eventarc\V1\Channel::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The resource name of the channel. Must be unique within the
     * location on the project and must be in
     * `projects/{project}/locations/{location}/channels/{channel_id}` format.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The resource name of the channel. Must be unique within the
     * location on the project and must be in
     * `projects/{project}/locations/{location}/channels/{channel_id}` format.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Output only. Server assigned unique identifier for the channel. The value
     * is a UUID4 string and guaranteed to remain unchanged until the resource is
     * deleted.
     *
     * Generated from protobuf field string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return string
     */
    public function getUid()
    {
        return $this->uid;
    }

    /**
     * Output only. Server assigned unique identifier for the channel. The value
     * is a UUID4 string and guaranteed to remain unchanged until the resource is
     * deleted.
     *
     * Generated from protobuf field string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param string $var
     * @return $this
     */
    public function setUid($var)
    {
        GPBUtil::checkString($var, True);
        $this->uid = $var;

        return $this;
    }

    /**
     * Output only. The creation time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function hasCreateTime()
    {
        return isset($this->create_time);
    }

    public function clearCreateTime()
    {
        unset($this->create_time);
    }

    /**
     * Output only. The creation time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setCreateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->create_time = $var;

        return $this;
    }

    /**
     * Output only. The last-modified time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getUpdateTime()
    {
        return $this->update_time;
    }

    public function hasUpdateTime()
    {
        return isset($this->update_time);
    }

    public function clearUpdateTime()
    {
        unset($this->update_time);
    }

    /**
     * Output only. The last-modified time.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setUpdateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->update_time = $var;

        return $this;
    }

    /**
     * The name of the event provider (e.g. Eventarc SaaS partner) associated
     * with the channel. This provider will be granted permissions to publish
     * events to the channel. Format:
     * `projects/{project}/locations/{location}/providers/{provider_id}`.
     *
     * Generated from protobuf field string provider = 7;
     * @return string
     */
    public function getProvider()
    {
        return $this->provider;
    }

    /**
     * The name of the event provider (e.g. Eventarc SaaS partner) associated
     * with the channel. This provider will be granted permissions to publish
     * events to the channel. Format:
     * `projects/{project}/locations/{location}/providers/{provider_id}`.
     *
     * Generated from protobuf field string provider = 7;
     * @param string $var
     * @return $this
     */
    public function setProvider($var)
    {
        GPBUtil::checkString($var, True);
        $this->provider = $var;

        return $this;
    }

    /**
     * Output only. The name of the Pub/Sub topic created and managed by
     * Eventarc system as a transport for the event delivery. Format:
     * `projects/{project}/topics/{topic_id}`.
     *
     * Generated from protobuf field string pubsub_topic = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return string
     */
    public function getPubsubTopic()
    {
        return $this->readOneof(8);
    }

    public function hasPubsubTopic()
    {
        return $this->hasOneof(8);
    }

    /**
     * Output only. The name of the Pub/Sub topic created and managed by
     * Eventarc system as a transport for the event delivery. Format:
     * `projects/{project}/topics/{topic_id}`.
     *
     * Generated from protobuf field string pubsub_topic = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param string $var
     * @return $this
     */
    public function setPubsubTopic($var)
    {
        GPBUtil::checkString($var, True);
        $this->writeOneof(8, $var);

        return $this;
    }

    /**
     * Output only. The state of a Channel.
     *
     * Generated from protobuf field .google.cloud.eventarc.v1.Channel.State state = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return int
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Output only. The state of a Channel.
     *
     * Generated from protobuf field .google.cloud.eventarc.v1.Channel.State state = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param int $var
     * @return $this
     */
    public function setState($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Eventarc\V1\Channel\State::class);
        $this->state = $var;

        return $this;
    }

    /**
     * Output only. The activation token for the channel. The token must be used
     * by the provider to register the channel for publishing.
     *
     * Generated from protobuf field string activation_token = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return string
     */
    public function getActivationToken()
    {
        return $this->activation_token;
    }

    /**
     * Output only. The activation token for the channel. The token must be used
     * by the provider to register the channel for publishing.
     *
     * Generated from protobuf field string activation_token = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param string $var
     * @return $this
     */
    public function setActivationToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->activation_token = $var;

        return $this;
    }

    /**
     * Optional. Resource name of a KMS crypto key (managed by the user) used to
     * encrypt/decrypt their event data.
     * It must match the pattern
     * `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
     *
     * Generated from protobuf field string crypto_key_name = 11 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = {
     * @return string
     */
    public function getCryptoKeyName()
    {
        return $this->crypto_key_name;
    }

    /**
     * Optional. Resource name of a KMS crypto key (managed by the user) used to
     * encrypt/decrypt their event data.
     * It must match the pattern
     * `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
     *
     * Generated from protobuf field string crypto_key_name = 11 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setCryptoKeyName($var)
    {
        GPBUtil::checkString($var, True);
        $this->crypto_key_name = $var;

        return $this;
    }

    /**
     * @return string
     */
    public function getTransport()
    {
        return $this->whichOneof("transport");
    }

}


text:
var updateNotifier = require('update-notifier');

var notifier = updateNotifier(
	{
		pkg: require('../package.json')
	}
);

if (notifier.update) {
	notifier.notify();
}

require('../lib/cli').init();


text:
<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Third party field
 */
class ACA_ACF_Field_ImageCrop extends ACA_ACF_Field {

	// Display

	public function get_value( $id ) {
		$value = get_field( $this->column->get_meta_key(), $this->column->get_formatted_id( $id ), true );

		if ( 'object' == $this->column->get_acf_field_option( 'save_format' ) ) {
			$value = $value['url'];
		}

		return $this->column->get_formatted_value( $value );
	}

	// Settings

	public function get_dependent_settings() {
		return array(
			new AC_Settings_Column_Image( $this->column ),
		);
	}

}


text:
@extends('layouts.default')

@section('content')

	@include('game.partials.header')

Charts

						Pos.
						Title
						Income €

					@foreach ($charts as $chartElement)
						@if ($chartElement->belongsToPlayer)

getPlayerAttribute()->getBgColorAttribute() }}>
						@else

						@endif
							{{ $chartElement->getCurrentPositionAttribute() }}
							{{ $chartElement->getMovieAttribute()->getTitleAttribute() }}
							{{ $chartElement->getIncomeAttribute() }}

					@endforeach

							{{ link_to_route('menu_path', 'Go back', null, ['class' => 'btn btn-sm btn-default'])}}

@stop


text:
<?php

// $Id: vpage_normal_form_ctrl.class.php 1570 2009-01-13 12:44:02Z ogrebg $

require_once(TANGRA_MAIN_DIR.'form/gform_ctrl_with_obj.class.php');

require_once('vpage_normal_form.class.php');
require_once('vpage_normal_form_view.class.php');

require_once(DIR_INC.'modules/tangra_cms/classes/vpt/vpage_normal_dbc.class.php');

class VPage_Normal_Form_Ctrl extends GForm_Ctrl_With_Object {
	private $attributes;

	function __construct($system_name, Vars_Manager $vm, DB_Connection $dbc, $object_id_capture = 'obj_id', $attributes) {
		$this->attributes = $attributes;
		parent::__construct($system_name, $vm, $dbc, $object_id_capture);
	}

	protected function create_form() {
		$form = new VPage_Normal_Form($this->attributes);

//		$form->generate_html();
		return $form;
	}

	protected function create_form_view() {
		$ret = new VPage_Normal_Form_View($this->form);

		return $ret;
	}

	protected function on_good_submit() {
		$ret = true;

		$form = $this->get_form();
		if ($form->get_field_value('title') != strip_tags($form->get_field_value('title'))) {
			$form->set_field_error('title', 'contains_html');
			$ret = false;
		}

		if ($form->get_field_value('meta_description') != strip_tags($form->get_field_value('meta_description'))) {
			$form->set_field_error('meta_description', 'contains_html');
			$ret = false;
		}

		return $ret;
	}

	protected function create_object() {
		$object = new VPage_Normal_DBC();

		return $object;
	}

	protected function transfer_obj2form() {
		$object = $this->get_object();
		$form = $this->get_form();

		$form->set_field_value('title', $object->get_title());
		$form->set_field_value('content', $object->get_content());
		$form->set_field_value('meta_description', $object->get_meta_description());
	}

	protected function transfer_form2obj() {
		$object = $this->get_object();
		$form = $this->get_form();

		$object->set_title($form->get_field_value('title'));
		$object->set_content($form->get_field_value('content'));
		$object->set_meta_description($form->get_field_value('meta_description'));
	}

	protected function _save_object(DB_Connection $dbc, I_DB_Storable $object) {
		$object->save($dbc, $this->get_permanent_external_param('user_id'));
	}
}


text:
package azure

import (
	"fmt"
	"strings"

	"github.com/Microsoft/azure-vhd-utils/vhdcore/validator"
	"github.com/spf13/cobra"
)

var (
	cmdUploadBlob = &cobra.Command{
		Use:   "upload-blob storage-account container blob-name file",
		Short: "Upload a blob to Azure storage",
		Run:   runUploadBlob,
	}

	// upload blob options
	ubo struct {
		storageacct string
		container   string
		blob        string
		vhd         string
		overwrite   bool
		validate    bool
	}
)

func init() {
	bv := cmdUploadBlob.Flags().BoolVar

	bv(&ubo.overwrite, "overwrite", false, "overwrite blob")
	bv(&ubo.validate, "validate", true, "validate blob as VHD file")

	Azure.AddCommand(cmdUploadBlob)
}

func runUploadBlob(cmd *cobra.Command, args []string) {
	if len(args) != 4 {
		plog.Fatalf("Expecting 4 arguments, got %d", len(args))
	}

	ubo.storageacct = args[0]
	ubo.container = args[1]
	ubo.blob = args[2]
	ubo.vhd = args[3]

	if ubo.validate {
		plog.Printf("Validating VHD %q", ubo.vhd)
		if !strings.HasSuffix(strings.ToLower(ubo.blob), ".vhd") {
			plog.Fatalf("Blob name should end with .vhd")
		}

		if err := validator.ValidateVhd(ubo.vhd); err != nil {
			plog.Fatal(err)
		}

		if err := validator.ValidateVhdSize(ubo.vhd); err != nil {
			plog.Fatal(err)
		}
	}

	kr, err := api.GetStorageServiceKeys(ubo.storageacct)
	if err != nil {
		plog.Fatalf("Fetching storage service keys failed: %v", err)
	}

	if err := api.UploadBlob(ubo.storageacct, kr.PrimaryKey, ubo.vhd, ubo.container, ubo.blob, ubo.overwrite); err != nil {
		plog.Fatalf("Uploading blob failed: %v", err)
	}

	uri := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s", ubo.storageacct, ubo.container, ubo.blob)

	plog.Printf("Blob uploaded to %q", uri)
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}

module PeerTrader.Route.User where

import           Control.Applicative               ((<|>))
import           Control.Concurrent                (forkIO)
import           Control.Concurrent.Async
import           Control.Monad                     (void)
import           Control.Monad.IO.Class            (liftIO)
import           Control.Monad.Representable.State (get)
import           Control.Monad.Trans.Reader

import           Data.Aeson
import qualified Data.ByteString.Lazy              as L
import           Data.Monoid                       ((<>))
import qualified Data.Text                         as T
import qualified Data.Text.Encoding                as T

import           Heist
import qualified Heist.Interpreted                 as I
import           Snap
import           Snap.Extras.JSON                  (writeJSON)
import           Snap.Snaplet.Auth
import           Snap.Snaplet.Heist
import           Snap.Snaplet.SES

import qualified Text.Blaze.Html5                  as H
import qualified Text.Blaze.Html5.Attributes       as A
import           Text.Blaze.Internal               (textValue)

import           Application
import qualified PeerTrader.Account.Handler        as A
import           PeerTrader.NewUser
import           PeerTrader.Types                  (UserLogin)

-- | Retrieve and Submit the password reset form
handleChangePassword :: AuthAppHandler ()
handleChangePassword =
    method GET handleGET <|>
    method POST handlePOST
  where
    handleGET  = currentUser >>= maybe the403 (\_ -> render "changepassword")
    handlePOST = currentUser >>= maybe the403 handleUser
    handleUser user@AuthUser{..} = do
        Just password <- getParam "password"
        _ <- saveUser =<< liftIO (setPassword user password)
        _ <- clearPasswordResetToken userLogin
        redirect "/"

the403 :: Handler App a ()
the403 = do
    modifyResponse $ setResponseCode 403
    render "403"

the404 :: Handler App a ()
the404 = do
    modifyResponse $ setResponseCode 404
    writeBS "404"

sendForgotPasswordEmail :: AppHandler ()
sendForgotPasswordEmail =
    method POST handlePOST <|>
    method GET (render "forgot")
  where
    handlePOST = do
        Just userLogin <- fmap T.decodeUtf8 <$> getParam "login"
        Just url       <- fmap T.decodeUtf8 <$> getParam "url"
        handleURL userLogin url =<< with auth (setPasswordResetToken userLogin)

    handleURL _ _ Nothing = render "usernotfound"
    handleURL userLogin url (Just token) = do
        let userEmail = L.fromStrict $ T.encodeUtf8 userLogin
            resetUrl  = url <> "/resetPassword?code=" <> token <> "&email=" <> userLogin
        keys <- with awsKeys get
        _ <- liftIO $ forkIO $ do
            let mail = flip runReaderT keys $
                    sendEmailBlaze [userEmail] subject (body resetUrl)
            void $ waitCatch =<< async mail -- TODO log error here
        render "sentResetEmail"

    subject = "PeerTrader Password Recovery"
    body resetUrl =
        H.html $
            H.body $ do
            H.h3 "To reset your password, follow the link and enter your new password:"
            H.a H.! A.href (textValue resetUrl) $ "Click here to reset your password"
            H.br
            H.p "If you did not request a password change you can safely ignore this email"
            H.p "Best regards,"
            H.p "PeerTrader team support@peertrader.com"

handleResetPassword :: AppHandler ()
handleResetPassword = method GET $ do
    Just token <- fmap T.decodeUtf8 <$> getParam "code"
    Just login <- fmap T.decodeUtf8 <$> getParam "email"
    authMgr <- with auth get
    result <- liftIO $ lookupByLogin authMgr login
    case result of
        Nothing -> the404
        Just user@AuthUser{..} ->
            if userResetToken /= Just token
                then the404
                else do
                    _ <- with auth $ forceLogin user
                    redirect "/changepassword"

-- | Render login form
handleLogin :: Maybe T.Text -> AuthAppHandler ()
handleLogin authError = heistLocal (I.bindSplices errs) $ render "login"
  where
    errs = maybe mempty splice authError
    splice err = "loginError" ## I.textSplice err

-- | Handle Login Submit
handleLoginSubmit :: AuthAppHandler ()
handleLoginSubmit = method GET handleGET <|> method POST handlePOST
  where
    handleGET = currentUser >>= maybe (render "login") (const $ redirect "/")
    handlePOST = loginUser "login" "password" Nothing
              (\_ -> handleLogin err) (redirect "/")
    err = Just "Unknown user or password"

-- | Logs out and redirects the user to the site index.
-- TODO remove account data streaming
handleLogout :: AuthAppHandler ()
handleLogout = logout >> redirect "/"

-- | Handle new user form submit
handleNewUser :: AppHandler ()
handleNewUser = method GET handleForm <|> method POST handleFormSubmit
  where
    handleForm = with auth $ render "new_user"
    handleFormSubmit = do
        -- TODO Pattern match correctly
        Just login <- fmap T.decodeUtf8 <$> getParam "login"
        Just password <- getParam "password"
        -- TODO Validate state isn't empty
        Just state <- fmap T.decodeUtf8 <$> getParam "state"

        newUser login password state >>= whenJust (sendVerifyEmail login)
        render "/verifyemailsent"
    whenJust = maybe (return ())

-- | Helper for 'handleNewUser'
-- Sends an email to a new user with a verification code.
sendVerifyEmail :: UserLogin -> T.Text -> AppHandler ()
sendVerifyEmail login verifyCode = do
    Just url <- fmap T.decodeUtf8 <$> getParam "url"
    let verifyUrl = url
            <> "/verifynewuser?verifycode=" <> verifyCode
            <> "&email=" <> login
    keys <- with awsKeys get
    void $ liftIO $ forkIO $ do
        let mail = flip runReaderT keys $
                sendEmailBlaze [userEmail] subject (body verifyUrl)
        void $ waitCatch =<< async mail -- TODO Log error
  where
    subject = "PeerTrader Registration Verification"
    userEmail = L.fromStrict $ T.encodeUtf8 login

    body verifyUrl = H.html $ H.body $ do
        H.h3 "To verify and login to your new PeerTrader account, follow this link: "
        H.a H.! A.href (textValue verifyUrl) $ "Click here to verify your account"
        H.br
        H.p "If you did not register with PeerTrader, you can safely ignore this email."
        H.p "Best regards,"
        H.p "PeerTrader team support@peertrader.com"

-- | Test if verifycode is equal to what's in the database.
-- Create a new user if they are verified.
handleVerify :: AppHandler ()
handleVerify = method GET $ do
    Just code <- fmap T.decodeUtf8 <$> getParam "verifycode"
    Just login <- fmap T.decodeUtf8 <$> getParam "email"
    verifyUser login code

-- | Check if the user needs to check the terms
-- and conditions of PeerTrader. If so, redirect them
-- to the terms page.
handleCheckTerms :: AppHandler ()
handleCheckTerms = method GET getCheckTerms <|> method POST setCheckTerms
  where
    setCheckTerms = withCurrentUser $ \n -> do
        -- TODO Just pattern
        Just checkTerm <- getParam "checkTerms"
        A.setCheckTerms n (readCheckTerm checkTerm)

    readCheckTerm "false" = False
    readCheckTerm "true" = True
    readCheckTerm _ = True

    getCheckTerms = withCurrentUser_ $ \n -> do
        Just terms <- A.getCheckTerms n
        writeJSON $ object [ "checkTerms" .= terms ]

-- | This handler requires the user to be logged in.
-- There is no database cost to this proceedure. This only requires
-- that the username be in the session.
-- TODO Perhaps should throw a 401 Unauthorized here.
requireLogIn :: AppHandler () -> AppHandler ()
requireLogIn = requireUser auth whenNotLoggedIn
  where whenNotLoggedIn = writeLBS "Error: Required to log in!"