text:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 *	Contains a simple container class.
 *	\file		IceContainer.h
 *	\author		Pierre Terdiman
 *	\date		February, 5, 2000
 */
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef __ICECONTAINER_H__
#define __ICECONTAINER_H__

	#define CONTAINER_STATS

	class ICECORE_API Container
	{
		public:
		// Constructor / Destructor
								Container();
								Container(udword size, float growth_factor);
								~Container();
		// Management
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	A O(1) method to add a value in the container. The container is automatically resized if needed.
		 *	The method is inline, not the resize. The call overhead happens on resizes only, which is not a problem since the resizing operation
		 *	costs a lot more than the call overhead...
		 *
		 *	\param		entry		[in] a udword to store in the container
		 *	\see		Add(float entry)
		 *	\see		Empty()
		 *	\see		Contains(udword entry)
		 *	\return		Self-Reference
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		inline_	Container&		Add(udword entry)
				{
					// Resize if needed
					if(mCurNbEntries==mMaxNbEntries)	Resize();

					// Add _new_ entry
					mEntries[mCurNbEntries++]	= entry;
					return *this;
				}

		inline_	Container&		Add(const udword* entries, udword nb)
				{
					// Resize if needed
					if(mCurNbEntries+nb>mMaxNbEntries)	Resize(nb);

					// Add _new_ entry
					CopyMemory(&mEntries[mCurNbEntries], entries, nb*sizeof(udword));
					mCurNbEntries+=nb;
					return *this;
				}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	A O(1) method to add a value in the container. The container is automatically resized if needed.
		 *	The method is inline, not the resize. The call overhead happens on resizes only, which is not a problem since the resizing operation
		 *	costs a lot more than the call overhead...
		 *
		 *	\param		entry		[in] a float to store in the container
		 *	\see		Add(udword entry)
		 *	\see		Empty()
		 *	\see		Contains(udword entry)
		 *	\return		Self-Reference
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		inline_	Container&		Add(float entry)
				{
					// Resize if needed
					if(mCurNbEntries==mMaxNbEntries)	Resize();

					// Add _new_ entry
					mEntries[mCurNbEntries++]	= IR(entry);
					return *this;
				}

		inline_	Container&		Add(const float* entries, udword nb)
				{
					// Resize if needed
					if(mCurNbEntries+nb>mMaxNbEntries)	Resize(nb);

					// Add _new_ entry
					CopyMemory(&mEntries[mCurNbEntries], entries, nb*sizeof(float));
					mCurNbEntries+=nb;
					return *this;
				}

		//! Add unique [slow]
				Container&		AddUnique(udword entry)
				{
					if(!Contains(entry))	Add(entry);
					return *this;
				}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	Clears the container. All stored values are deleted, and it frees used ram.
		 *	\see		Reset()
		 *	\return		Self-Reference
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		inline_	Container&		Empty()
				{
					#ifdef CONTAINER_STATS
					mUsedRam-=mMaxNbEntries*sizeof(udword);
					#endif
					xr_free			(mEntries);
					mCurNbEntries	= mMaxNbEntries = 0;
					return *this;
				}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	Resets the container. Stored values are discarded but the buffer is kept so that further calls don't need resizing again.
		 *	That's a kind of temporal coherence.
		 *	\see		Empty()
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		inline_	void			Reset()
				{
					// Avoid the write if possible
					// ### CMOV
					if(mCurNbEntries)	mCurNbEntries = 0;
				}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	Sets the initial size of the container. If it already contains something, it's discarded.
		 *	\param		nb		[in] Number of entries
		 *	\return		true if success
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				bool			SetSize(udword nb);

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 *	Refits the container and get rid of unused bytes.
		 *	\return		true if success
		 */
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				bool			Refit();

		// Checks whether the container already contains a given value.
				bool			Contains(udword entry, udword* location=null) const;
		// Deletes an entry - doesn't preserve insertion order.
				bool			Delete(udword entry);
		// Deletes an entry - does preserve insertion order.
				bool			DeleteKeepingOrder(udword entry);
		//! Deletes the very last entry.
		inline_	void			DeleteLastEntry()						{ if(mCurNbEntries)	mCurNbEntries--;			}
		//! Deletes the entry whose index is given
		inline_	void			DeleteIndex(udword index)				{ mEntries[index] = mEntries[--mCurNbEntries];	}

		// Helpers
				Container&		FindNext(udword& entry, bool wrap=false);
				Container&		FindPrev(udword& entry, bool wrap=false);
		// Data access.
		inline_	udword			GetNbEntries()					const	{ return mCurNbEntries;		}	//!< Returns the current number of entries.
		inline_	udword			GetEntry(udword i)				const	{ return mEntries[i];		}	//!< Returns ith entry
		inline_	udword*			GetEntries()					const	{ return mEntries;			}	//!< Returns the list of entries.

		// Growth control
		inline_	float			GetGrowthFactor()				const	{ return mGrowthFactor;		}	//!< Returns the growth factor
		inline_	void			SetGrowthFactor(float growth)			{ mGrowthFactor = growth;	}	//!< Sets the growth factor

		//! Access as an array
		inline_	udword&			operator[](udword i)			const	{ ASSERT(i>=0 && i<mCurNbEntries); return mEntries[i];	}

		// Stats
				udword			GetUsedRam()					const;

		//! Operator for Container A = Container B
				void			operator = (const Container& object)
				{
					SetSize(object.GetNbEntries());
					CopyMemory(mEntries, object.GetEntries(), mMaxNbEntries*sizeof(udword));
					mCurNbEntries = mMaxNbEntries;
				}

#ifdef CONTAINER_STATS
		inline_	udword			GetNbContainers()				const	{ return mNbContainers;		}
		inline_	udword			GetTotalBytes()					const	{ return mUsedRam;			}
		private:

		static	udword			mNbContainers;		//!< Number of containers around
		static	udword			mUsedRam;			//!< Amount of bytes used by containers in the system
#endif
		private:
		// Resizing
				bool			Resize(udword needed=1);
		// Data
				udword			mMaxNbEntries;		//!< Maximum possible number of entries
				udword			mCurNbEntries;		//!< Current number of entries
				udword*			mEntries;			//!< List of entries
				float			mGrowthFactor;		//!< Resize: _new_ number of entries = old number * mGrowthFactor
	};

	class ICECORE_API Pairs : public Container
	{
		public:
		// Constructor / Destructor
		inline_				Pairs()						{}
		inline_				~Pairs()					{}

		inline_	udword		GetNbPairs()	const		{ return GetNbEntries()>>1;					}
		inline_	Pair*		GetPairs()		const		{ return (Pair*)GetEntries();				}

				Pairs&		AddPair(const Pair& p)		{ Add(p.id0).Add(p.id1);	return *this;	}
	};

#endif // __ICECONTAINER_H__


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Page](./puppeteer.protocol.page.md) > [Viewport](./puppeteer.protocol.page.viewport.md)

## Protocol.Page.Viewport interface

Viewport for capturing screenshot.

<b>Signature:</b>

```typescript
export interface Viewport
```

## Properties

|  Property | Type | Description |
|  --- | --- | --- |
|  [height](./puppeteer.protocol.page.viewport.height.md) | number | Rectangle height in device independent pixels (dip). |
|  [scale](./puppeteer.protocol.page.viewport.scale.md) | number | Page scale factor. |
|  [width](./puppeteer.protocol.page.viewport.width.md) | number | Rectangle width in device independent pixels (dip). |
|  [x](./puppeteer.protocol.page.viewport.x.md) | number | X offset in device independent pixels (dip). |
|  [y](./puppeteer.protocol.page.viewport.y.md) | number | Y offset in device independent pixels (dip). |

redpajama_set_name: RedPajamaGithub


text:
package com.coolweather.app.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.coolweather.app.db.CoolWeatherOpenHelper;
import com.coolweather.app.model.CityBean;
import com.coolweather.app.model.CountyBean;
import com.coolweather.app.model.ProvinceBean;

/**
 * @项目名称: CoolWeather
 * @包名: com.coolweather.app.dao
 * @类名: CoolWeatherDBDao
 * @时间: 下午1:40:12
 * @作者: AnElse
 *
 * @描述: 这个类把一些常用的数据库操作封装起来,以方便我们在程序中使用.
 *
 * @当前版本号: $Rev$
 * @更新人: $Author$
 * @更新的时间: $Date$
 * @更新的描述: TODO
 *
 */
public class CoolWeatherDBDao {
	/**
	 * 数据库名
	 */
	public static final String		DB_NAME	= "cool_weather";

	/**
	 * 数据库版本
	 */
	public static final int			VERSION	= 1;

	private static CoolWeatherDBDao	coolWeatherDBDao;
	private SQLiteDatabase			db;

	/**
	 * 将构造方法私有化
	 *
	 * @param context
	 *            上下文
	 */
	private CoolWeatherDBDao(Context context) {
		CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION);
		db = dbHelper.getWritableDatabase();
	}

	/**
	 * 获取CoolweatherDBDao的实例
	 *
	 * @param context
	 * @return
	 */
	public synchronized static CoolWeatherDBDao getInstance(Context context) {
		if (coolWeatherDBDao == null) {
			coolWeatherDBDao = new CoolWeatherDBDao(context);
		}
		return coolWeatherDBDao;
	}

	/**
	 * 将province实例存储到数据库
	 *
	 * @param provinceBean
	 *            省类实体bean
	 */
	public void saveProvince(ProvinceBean provinceBean) {
		if (provinceBean != null) {
			ContentValues values = new ContentValues();
			values.put("province_name", provinceBean.getProvinceName());
			values.put("province_code", provinceBean.getProvinceCode());
			db.insert("Province", null, values);
		}
	}

	/**
	 * 从数据库读取全国所有的省份信息
	 *
	 * @return 返回全国所有的省份信息的集合
	 */
	public List<ProvinceBean> loadProvince() {
		List<ProvinceBean> list = new ArrayList<ProvinceBean>();
		Cursor cursor = db.query("Province", null, null, null, null, null, null, null);
		while (cursor.moveToNext()) {
			ProvinceBean bean = new ProvinceBean();
			bean.setId(cursor.getInt(cursor.getColumnIndex("id")));
			bean.setProvinceName(cursor.getString(cursor.getColumnIndex("Province_name")));
			bean.setProvinceCode(cursor.getString(cursor.getColumnIndex("Province_code")));
			list.add(bean);
		}

		if (cursor != null) {
			cursor.close();
		}
		return list;
	}

	/**
	 * 将city实例存储到数据库
	 *
	 * @param cityBean
	 *            城市实体bean
	 */
	public void saveCity(CityBean cityBean) {
		if (cityBean != null) {
			ContentValues values = new ContentValues();
			values.put("city_name", cityBean.getCityName());
			values.put("city_code", cityBean.getCityCode());
			values.put("province_id", cityBean.getProvinceId());
			db.insert("City", null, values);
		}
	}

	/**
	 * 根据省编号从数据库读取所有的城市信息
	 *
	 * @param provinceId
	 *            省编号
	 * @return
	 */
	public List<CityBean> loadCities(int provinceId) {
		List<CityBean> list = new ArrayList<CityBean>();
		Cursor cursor = db.query("City", null, "province_id = ?", new String[] { String.valueOf(provinceId) }, null, null, null, null);
		while (cursor.moveToNext()) {
			CityBean bean = new CityBean();
			bean.setId(cursor.getInt(cursor.getColumnIndex("id")));
			bean.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
			bean.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
			bean.setProvinceId(provinceId);
			list.add(bean);
		}

		if (cursor != null) {
			cursor.close();
		}
		return list;
	}

	/**
	 * 将county实例存入都数据库
	 *
	 * @param countyBean
	 */
	public void saveCounty(CountyBean countyBean) {
		if (countyBean != null) {
			ContentValues values = new ContentValues();
			values.put("county_name", countyBean.getCountyName());
			values.put("county_code", countyBean.getCountyCode());
			values.put("city_id", countyBean.getCityId());
			db.insert("County", null, values);
		}
	}

	/**
	 * 根据城市编号从数据库读取所有的县信息
	 *
	 * @param cityId 城市id
	 * @return
	 */
	public List<CountyBean> loadCounty(int cityId) {
		List<CountyBean> list = new ArrayList<CountyBean>();
		Cursor cursor = db.query("County", null, "city_Id = ?", new String[] { String.valueOf(cityId) }, null, null, null, null);
		while (cursor.moveToNext()) {
			CountyBean bean = new CountyBean();
			bean.setId(cursor.getInt(cursor.getColumnIndex("id")));
			bean.setCountyName(cursor.getString(cursor.getColumnIndex("County_name")));
			bean.setCountyCode(cursor.getString(cursor.getColumnIndex("CountyB_code")));
			bean.setCityId(cityId);
			list.add(bean);
		}

		if (cursor != null) {
			cursor.close();
		}
		return list;
	}
}


text:
using Cauldron.Interception.Cecilator;
using System.Collections;

namespace Cauldron.ActivatorInterceptors
{
    internal static class Extensions
    {
        public static bool IsIDictionary(this BuilderType builderType) => builderType.Implements(typeof(IDictionary));

        public static bool IsIEnumerable(this BuilderType builderType) =>
                    BuilderTypes
                        .IEnumerable
                        .BuilderType
                        .AreReferenceAssignable(builderType) || builderType.IsArray;

        public static bool IsParameterless(this InjectAttributeValues injectAttribute) =>
            (injectAttribute.Arguments == null || injectAttribute.Arguments.Length == 0);
    }
}


text:
package denominator.model.rdata;

import java.util.LinkedHashMap;

import static denominator.common.Preconditions.checkNotNull;

/**
 * Corresponds to the binary representation of the {@code PTR} (Pointer) RData
 *
 *

 Example

 *
 *

 * PTRData rdata = PTRData.create("ptr.foo.com.");
 *

 *
 * See RFC 1035
 */
public final class PTRData extends LinkedHashMap<String, Object> {

  private static final long serialVersionUID = 1L;

  PTRData(String ptrdname) {
    put("ptrdname", checkNotNull(ptrdname, "ptrdname"));
  }

  public static PTRData create(String ptrdname) {
    return new PTRData(ptrdname);
  }

  /**
   * domain-name which points to some location in the domain name space.
   *
   * @since 1.3
   */
  public String ptrdname() {
    return get("ptrdname").toString();
  }
}


text:
This folder contains the static libraies for:

* Visual Studio 2015
* MacOSX


text:
package eus.ixa.ixa.pipe.ml.features;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import eus.ixa.ixa.pipe.ml.resources.SequenceModelResource;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.featuregen.ArtifactToSerializerMapper;
import opennlp.tools.util.featuregen.CustomFeatureGenerator;
import opennlp.tools.util.featuregen.FeatureGeneratorResourceProvider;
import opennlp.tools.util.model.ArtifactSerializer;

/**
 * This feature generator can also be placed in a sliding window.
 *
 * @author ragerri
 * @version 2016-04-07
 */
public class LemmaModelFeatureGenerator extends CustomFeatureGenerator
    implements ArtifactToSerializerMapper {

  private SequenceModelResource seqModelResource;
  private String[] currentSentence;
  private String[] currentLemmas;

  public LemmaModelFeatureGenerator() {
  }

  @Override
  public void createFeatures(final List<String> features, final String[] tokens,
      final int index, final String[] previousOutcomes) {

    // cache annotations for each sentence
    if (this.currentSentence != tokens) {
      this.currentSentence = tokens;
      this.currentLemmas = this.seqModelResource.lemmatize(tokens);
    }
    final String lemma = this.currentLemmas[index];
    features.add("lemmaModel=" + lemma);
    // System.err.println("-> Model Lemma: " + tokens[index] + " " + lemma);
  }

  @Override
  public void updateAdaptiveData(final String[] tokens,
      final String[] outcomes) {
  }

  @Override
  public void clearAdaptiveData() {
  }

  @Override
  public void init(final Map<String, String> properties,
      final FeatureGeneratorResourceProvider resourceProvider)
      throws InvalidFormatException {
    final Object posResource = resourceProvider
        .getResource(properties.get("model"));
    if (!(posResource instanceof SequenceModelResource)) {
      throw new InvalidFormatException(
          "Not a SequenceModelResource for key: " + properties.get("model"));
    }
    this.seqModelResource = (SequenceModelResource) posResource;
  }

  @Override
  public Map<String, ArtifactSerializer<?>> getArtifactSerializerMapping() {
    final Map<String, ArtifactSerializer<?>> mapping = new HashMap<>();
    mapping.put("seqmodelserializer",
        new SequenceModelResource.SequenceModelResourceSerializer());
    return Collections.unmodifiableMap(mapping);
  }
}


text:
ifndef SNAP_ROOT
# check if we are in sw folder of an action (three directories below snap root)
ifneq ("$(wildcard ../../../ActionTypes.md)","")
SNAP_ROOT=$(abspath ../../../)
else
$(info You are not building your software from the default directory (/path/to/snap/actions/<action_name>/sw) or specified a wrong $$SNAP_ROOT.)
$(error Please make sure that $$SNAP_ROOT is set up correctly.)
endif
endif

# This is solution specific. Check if we can replace this by generics too.

snap_helloworld: action_lowercase.o
snap_helloworld_objs = action_lowercase.o

projs += snap_helloworld

# If you have the host code outside of the default snap directory structure,
# change to /path/to/snap/actions/software.mk
include $(SNAP_ROOT)/actions/software.mk


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <aws/ec2/model/TransitGatewayPolicyTableEntry.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
  class AWS_EC2_API GetTransitGatewayPolicyTableEntriesResponse
  {
  public:
    GetTransitGatewayPolicyTableEntriesResponse();
    GetTransitGatewayPolicyTableEntriesResponse(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    GetTransitGatewayPolicyTableEntriesResponse& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
The entries for the transit gateway policy table.

     */
    inline const Aws::Vector<TransitGatewayPolicyTableEntry>& GetTransitGatewayPolicyTableEntries() const{ return m_transitGatewayPolicyTableEntries; }

    /**
     *
The entries for the transit gateway policy table.

     */
    inline void SetTransitGatewayPolicyTableEntries(const Aws::Vector<TransitGatewayPolicyTableEntry>& value) { m_transitGatewayPolicyTableEntries = value; }

    /**
     *
The entries for the transit gateway policy table.

     */
    inline void SetTransitGatewayPolicyTableEntries(Aws::Vector<TransitGatewayPolicyTableEntry>&& value) { m_transitGatewayPolicyTableEntries = std::move(value); }

    /**
     *
The entries for the transit gateway policy table.

     */
    inline GetTransitGatewayPolicyTableEntriesResponse& WithTransitGatewayPolicyTableEntries(const Aws::Vector<TransitGatewayPolicyTableEntry>& value) { SetTransitGatewayPolicyTableEntries(value); return *this;}

    /**
     *
The entries for the transit gateway policy table.

     */
    inline GetTransitGatewayPolicyTableEntriesResponse& WithTransitGatewayPolicyTableEntries(Aws::Vector<TransitGatewayPolicyTableEntry>&& value) { SetTransitGatewayPolicyTableEntries(std::move(value)); return *this;}

    /**
     *
The entries for the transit gateway policy table.

     */
    inline GetTransitGatewayPolicyTableEntriesResponse& AddTransitGatewayPolicyTableEntries(const TransitGatewayPolicyTableEntry& value) { m_transitGatewayPolicyTableEntries.push_back(value); return *this; }

    /**
     *
The entries for the transit gateway policy table.

     */
    inline GetTransitGatewayPolicyTableEntriesResponse& AddTransitGatewayPolicyTableEntries(TransitGatewayPolicyTableEntry&& value) { m_transitGatewayPolicyTableEntries.push_back(std::move(value)); return *this; }

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline GetTransitGatewayPolicyTableEntriesResponse& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline GetTransitGatewayPolicyTableEntriesResponse& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    Aws::Vector<TransitGatewayPolicyTableEntry> m_transitGatewayPolicyTableEntries;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
source ./env.sh

#Modify the /etc/nova/nova.conf
CONF_FILE=/etc/nova/nova.conf
./backup-file.sh $CONF_FILE

./set-config.py $CONF_FILE database           connection                    mysql://$NOVA_USER:$NOVA_PASS@$DATABASE_IP/nova
./set-config.py $CONF_FILE database           idle_timeout                  60
./set-config.py $CONF_FILE DEFAULT            rpc_backend                   rabbit
./set-config.py $CONF_FILE DEFAULT            rabbit_hosts                  $RABBIT_HOSTS
./set-config.py $CONF_FILE DEFAULT            rabbit_retry_interval         1
./set-config.py $CONF_FILE DEFAULT            rabbit_retry_backoff          2
./set-config.py $CONF_FILE DEFAULT            rabbit_max_retries            0
./set-config.py $CONF_FILE DEFAULT            rabbit_durable_queues         false
./set-config.py $CONF_FILE DEFAULT            rabbit_ha_queues              true
./set-config.py $CONF_FILE DEFAULT            my_ip                         $CONTROLLER_NODE_NOVA_MY_IP
./set-config.py $CONF_FILE DEFAULT            vncserver_listen              $CONTROLLER_NODE_VNCSERVER_LISTEN
./set-config.py $CONF_FILE DEFAULT            vncserver_proxyclient_address $CONTROLLER_NODE_VNCSERVER_PROXYCLIENT_ADDRESS
./set-config.py $CONF_FILE DEFAULT            auth_strategy                 keystone
./set-config.py $CONF_FILE keystone_authtoken auth_uri                      http://$KEYSTONE_HOST_IP:5000/v2.0
./set-config.py $CONF_FILE keystone_authtoken identity_uri                  http://$KEYSTONE_HOST_IP:35357
./set-config.py $CONF_FILE keystone_authtoken admin_tenant_name             service
./set-config.py $CONF_FILE keystone_authtoken admin_user                    nova
./set-config.py $CONF_FILE keystone_authtoken admin_password                $KEYSTONE_SERVICE_PASSWORD
./set-config.py $CONF_FILE glance             host                          $GLANCE_HOST_IP
./set-config.py $CONF_FILE DEFAULT            memcached_servers             $CONTROLLER_NODE_MANAGEMENT_IP:11211
./set-config.py $CONF_FILE DEFAULT            verbose                       True

if [ $NETWORK_API_CLASS = 'nova-network' ]; then
    echo "NETWORK_API_CLASS = nova-network"

    ./set-config.py $CONF_FILE DEFAULT network_api_class  nova.network.api.API
    ./set-config.py $CONF_FILE DEFAULT security_group_api nova

elif [ $NETWORK_API_CLASS = 'neutron' ]; then
    echo "NETWORK_API_CLASS = neutron"

    ./set-config.py $CONF_FILE DEFAULT network_api_class                     nova.network.neutronv2.api.API
    ./set-config.py $CONF_FILE DEFAULT security_group_api                    neutron
    ./set-config.py $CONF_FILE DEFAULT linuxnet_interface_driver             nova.network.linux_net.LinuxOVSInterfaceDriver
    ./set-config.py $CONF_FILE DEFAULT firewall_driver                       nova.virt.firewall.NoopFirewallDriver
    ./set-config.py $CONF_FILE neutron url                                   http://$CONTROLLER_NODE_MANAGEMENT_IP:9696
    ./set-config.py $CONF_FILE neutron auth_strategy                         keystone
    ./set-config.py $CONF_FILE neutron admin_auth_url                        http://$KEYSTONE_HOST_IP:35357/v2.0
    ./set-config.py $CONF_FILE neutron admin_tenant_name                     service
    ./set-config.py $CONF_FILE neutron admin_username                        neutron
    ./set-config.py $CONF_FILE neutron admin_password                        $KEYSTONE_SERVICE_PASSWORD
    ./set-config.py $CONF_FILE neutron service_metadata_proxy                True
    ./set-config.py $CONF_FILE neutron metadata_proxy_shared_secret          $METADATA_PROXY_SHARED_SECRET

    #
else
    echo "NETWORK_API_CLASS = unknown type"
fi

##Now modify authtoken section in the /etc/nova/api-paste.ini
#conf_file_01=/etc/nova/api-paste.ini
#./backup-file.sh $conf_file_01
#
#sed -i '/filter:authtoken/,$d' $conf_file_01
#echo "[filter:authtoken]"                                                                >> $conf_file_01
#echo "paste.filter_factory = keystoneclient.middleware.auth_token:filter_factory"        >> $conf_file_01
#echo "auth_host = $KEYSTONE_HOST_IP"                                                     >> $conf_file_01
#echo "auth_port = 35357"                                                                 >> $conf_file_01
#echo "auth_protocol = http"                                                              >> $conf_file_01
#echo "admin_tenant_name = service"                                                       >> $conf_file_01
#echo "admin_user = nova"                                                                 >> $conf_file_01
#echo "admin_password = $KEYSTONE_SERVICE_PASSWORD"                                       >> $conf_file_01
#echo "signing_dirname = /tmp/keystone-signing-nova"                                      >> $conf_file_01
#echo "# Workaround for https://bugs.launchpad.net/nova/+bug/1154809"                     >> $conf_file_01
#echo "auth_version = v2.0"                                                               >> $conf_file_01
#
##Modify the /etc/nova/nova.conf
#conf_file_02=/etc/nova/nova.conf
#./backup-file.sh $conf_file_02
#
#sed -i '/DEFAULT/,$d' $conf_file_02
#echo "[DEFAULT]"                                                                                >> $conf_file_02
#echo "logdir=/var/log/nova"                                                                               >> $conf_file_02
#echo "state_path=/var/lib/nova"                                                                           >> $conf_file_02
#echo "lock_path=/run/lock/nova"                                                                           >> $conf_file_02
#echo "verbose=True"                                                                                >> $conf_file_02
#echo "api_paste_config=/etc/nova/api-paste.ini"                                                           >> $conf_file_02
#echo "compute_scheduler_driver=nova.scheduler.simple.SimpleScheduler"                                     >> $conf_file_02
#echo "rabbit_host=$MESSAGE_QUEUE_IP"                                                                      >> $conf_file_02
#echo "nova_url=http://$CONTROLLER_NODE_NOVA_URL_IP:8774/v1.1/"                                            >> $conf_file_02
#echo "sql_connection=mysql://$NOVA_USER:$NOVA_PASS@$DATABASE_IP/nova"                                     >> $conf_file_02
#echo "root_helper=sudo nova-rootwrap /etc/nova/rootwrap.conf"                                             >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Auth"                                                                                >> $conf_file_02
#echo "use_deprecated_auth=false"                                                                          >> $conf_file_02
#echo "auth_strategy=keystone"                                                                             >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Imaging service"                                                                                >> $conf_file_02
#echo "glance_api_servers=$GLANCE_HOST_IP:9292"                                                            >> $conf_file_02
#echo "image_service=nova.image.glance.GlanceImageService"                                                 >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Vnc configuration"                                                                                >> $conf_file_02
#echo "novnc_enabled=true"                                                                                >> $conf_file_02
#echo "novncproxy_base_url=http://$CONTROLLER_NODE_NOVNCPROXY_BASE_URL_IP:6080/vnc_auto.html"              >> $conf_file_02
#echo "novncproxy_port=6080"                                                                               >> $conf_file_02
#echo "vncserver_proxyclient_address=$CONTROLLER_NODE_VNCSERVER_PROXYCLIENT_ADDRESS"                       >> $conf_file_02
#echo "vncserver_listen=0.0.0.0"                                                                           >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Network settings"                                                                                >> $conf_file_02
#echo "network_api_class=nova.network.neutronv2.api.API"                                                   >> $conf_file_02
#echo "neutron_url=http://$CONTROLLER_NODE_NEUTRON_URL_IP:9696"                                            >> $conf_file_02
#echo "neutron_auth_strategy=keystone"                                                                     >> $conf_file_02
#echo "neutron_admin_tenant_name=service"                                                                  >> $conf_file_02
#echo "neutron_admin_username=neutron"                                                                     >> $conf_file_02
#echo "neutron_admin_password=$KEYSTONE_SERVICE_PASSWORD"                                                  >> $conf_file_02
#echo "neutron_admin_auth_url=http://$KEYSTONE_HOST_IP:35357/v2.0"                                         >> $conf_file_02
#echo "libvirt_vif_driver=nova.virt.libvirt.vif.LibvirtHybridOVSBridgeDriver"                              >> $conf_file_02
#echo "linuxnet_interface_driver=nova.network.linux_net.LinuxOVSInterfaceDriver"                           >> $conf_file_02
#echo "#If you want Neutron + Nova Security groups"                                                        >> $conf_file_02
#echo "firewall_driver=nova.virt.firewall.NoopFirewallDriver"                                              >> $conf_file_02
#echo "security_group_api=neutron"                                                                         >> $conf_file_02
#echo "#If you want Nova Security groups only, comment the two lines above and uncomment line -1-."        >> $conf_file_02
#echo "#-1-firewall_driver=nova.virt.libvirt.firewall.IptablesFirewallDriver"                              >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "#Metadata"                                                                                >> $conf_file_02
#echo "service_neutron_metadata_proxy = True"                                                              >> $conf_file_02
#echo "neutron_metadata_proxy_shared_secret = helloOpenStack"                                              >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Compute #"                                                                                >> $conf_file_02
#echo "compute_driver=libvirt.LibvirtDriver"                                                               >> $conf_file_02
#echo ""                                                                                >> $conf_file_02
#echo "# Cinder #"                                                                                >> $conf_file_02
#echo "volume_api_class=nova.volume.cinder.API"                                                            >> $conf_file_02
#echo "osapi_volume_listen_port=5900"                                                                      >> $conf_file_02

exit 0


text:
declare namespace javax {
  namespace swing {

    class ProgressMonitorInputStream extends java.io.FilterInputStream {
      public constructor(arg0: java.awt.Component, arg1: java.lang.Object | any, arg2: java.io.InputStream)
      public getProgressMonitor(): javax.swing.ProgressMonitor
      public read(): number
      public read(arg0: number[] | java.lang.Byte[]): number
      public read(arg0: number[] | java.lang.Byte[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public skip(arg0: number | java.lang.Long): number
      public close(): void
      public reset(): void
    }

  }
}


text:
var views = require("mojo-views");

module.exports = views.Base.extend({
  paper: require("./message.pc")
})


text:
package org.commcare.android.javarosa;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import org.commcare.CommCareApplication;
import org.commcare.network.CommcareRequestGenerator;
import org.commcare.services.CommCareSessionService;
import org.commcare.util.LogTypes;
import org.commcare.utils.SessionUnavailableException;
import org.javarosa.core.model.User;
import org.javarosa.core.model.actions.FormSendCalloutHandler;
import org.javarosa.core.services.Logger;

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

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Implements the in-form HTTP requester on the android platform.
 *
 * Uses the logged in user credentials by default, if they are available.
 *
 * Created by ctsims on 10/25/2017.
 */

public class AndroidXFormHttpRequester implements FormSendCalloutHandler {

    @Override
    public String performHttpCalloutForResponse(String url, Multimap<String, String> paramMap) {
        CommcareRequestGenerator generator;
        try {
            CommCareSessionService session = CommCareApplication.instance().getSession();
            User user = session.getLoggedInUser();
            generator = new CommcareRequestGenerator(user);
        } catch(SessionUnavailableException sue) {
            //auth won't be possible.
            generator = CommcareRequestGenerator.buildNoAuthGenerator();
        }

        if (paramMap == null) {
            paramMap = ArrayListMultimap.create();
        }

        try {
            Response<ResponseBody> response = generator.simpleGet(url, paramMap, new HashMap<>());
            if(response.code() != 200) {
                Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS, "HTTP Callout failed w/Response code: " + response.code() + " | and message " + response.message());
                return null;
            }

            return response.body().string();
        } catch(IOException e) {
            e.printStackTrace();
            Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS, "Error performing HTTP Callout : " +
                    e.getMessage());
            return null;
        }
    }
}


text:
import dateutil.parser
import importlib
import json
import logging
import warnings
from re import compile

import django.conf
from django.contrib.auth import logout
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse, resolve
from django.http import HttpResponseRedirect, HttpResponse
from django.test.signals import setting_changed
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
import django.views.static

from ua_parser.user_agent_parser import ParseUserAgent

logger = logging.getLogger(__name__)
DJANGO_SECURITY_MIDDLEWARE_URL = ("https://docs.djangoproject.com/en/1.11/ref"
    "/middleware/#django.middleware.security.SecurityMiddleware")
DJANGO_CLICKJACKING_MIDDLEWARE_URL = ("https://docs.djangoproject.com/en/1.11/"
    "ref/clickjacking/")

class CustomLogoutMixin(object):
    """
    If the CUSTOM_LOGOUT_MODULE is set in Django config, import
    and use that when performing a logout.
    """

    class Messages(object):
        NOT_A_MODULE_PATH = (u"Invalid CUSTOM_LOGOUT_MODULE setting '{0}'. "
                             u"Expected module path to a function")
        FAILED_TO_LOAD = (u"Invalid CUSTOM_LOGOUT_MODULE setting. "
                          u"Failed to load module '{0}': {1}")
        MISSING_FUNCTION = (u"Invalid CUSTOM_LOGOUT_MODULE setting. "
                            u"Could not find function '{0}' in module '{1}'")

    def perform_logout(self, request):
        if not getattr(self, 'CUSTOM_LOGOUT_MODULE', None):
            logout(request)
            return

        try:
            module_path, function_name = self.CUSTOM_LOGOUT_MODULE.rsplit('.', 1)
        except ValueError:
            err = self.Messages.NOT_A_MODULE_PATH
            raise Exception(err.format(self.CUSTOM_LOGOUT_MODULE))

        if not module_path or not function_name:
            err = self.Messages.NOT_A_MODULE_PATH
            raise Exception(err.format(self.CUSTOM_LOGOUT_MODULE))

        try:
            module = importlib.import_module(module_path)
        except Exception as e:
            err = self.Messages.FAILED_TO_LOAD
            raise Exception(err.format(module_path, e))

        try:
            func = getattr(module, function_name)
        except AttributeError:
            err = self.Messages.MISSING_FUNCTION
            raise Exception(err.format(function_name, module_path))

        return func(request)

class BaseMiddleware(MiddlewareMixin):
    """
    Abstract class containing some functionality common to all middleware that
    require configuration.
    """

    REQUIRED_SETTINGS = ()
    OPTIONAL_SETTINGS = ()

    def load_setting(self, setting, value):
        """
        Called initially for each of the keys in REQUIRED_SETTINGS and
        OPTIONAL_SETTINGS, and again whenever any of these settings change
        (from the setting_changed signal). Passed the setting key and the new
        value, which may be None for the keys in OPTIONAL_SETTINGS. If no
        setting keys are defined then this method is never called.
        """
        raise NotImplementedError()

    def _on_setting_changed(self, sender, setting, value, **kwargs):
        if (
            setting in self.REQUIRED_SETTINGS or
            setting in self.OPTIONAL_SETTINGS
        ):
            self.load_setting(setting, value)

    def __init__(self, get_response=None):
        self.get_response = get_response

        if not self.REQUIRED_SETTINGS and not self.OPTIONAL_SETTINGS:
            return

        for key in self.REQUIRED_SETTINGS:
            if hasattr(django.conf.settings, key):
                self.load_setting(key, getattr(django.conf.settings, key))
            else:
                raise ImproperlyConfigured(
                    self.__class__.__name__ + " requires setting " + key
                )

        for key in self.OPTIONAL_SETTINGS:
            self.load_setting(
                key, getattr(django.conf.settings, key, None)
            )

        setting_changed.connect(self._on_setting_changed)

class DoNotTrackMiddleware(MiddlewareMixin):
    """
    When this middleware is installed Django views can access a new
    ``request.dnt`` parameter to check client's preference on user tracking as
    expressed by their browser configuration settings.

    The parameter can take True, False or None values based on the presence of
    the ``Do Not Track`` HTTP header in client's request, which in turn depends
    on browser's configuration. The header indicates client's general
    preference to opt-out from behavioral profiling and third-party tracking.

    The parameter does **not** change behaviour of Django in any way as its
    sole purpose is to pass the user's preference to application. It's then up
    to the owner to implement a particular policy based on this information.
    Compliant website should adapt its behaviour depending on one of user's
    preferences:

    - Explicit opt-out (``request.dnt`` is ``True``): Disable third party
      tracking for this request and delete all previously stored tracking data.
    - Explicit opt-in (``request.dnt`` is ``False``): Website may track user.
    - Header not present (``request.dnt`` is ``None``): Website may track user,
      but should not draw any definite conclusions on user's preferences as the
      user has not expressed it.

    For example, if ``request.dnt`` is `` True`` the website might respond by
    disabling template parts responsible for personalized statistics, targeted
    advertisements or switching to DNT aware ones.

    Examples:

    - `Do Not Track (DNT) tutorial for Django <http://ipsec.pl/node/1101>`_
    - `Do Not Track - Web Application Templates
      <http://donottrack.us/application>`_
    - `Opt-out of tailoring Twitter <https://dev.twitter.com/docs/tweet-
      button#optout>`_

    References:

    - `Web Tracking Protection <http://www.w3.org/Submission/web-tracking-
      protection/>`_
    - `Do Not Track: A Universal Third-Party Web Tracking Opt Out
      <http://tools.ietf.org/html/draft-mayer-do-not-track-00>`_
    """

    def process_request(self, request):
        """
        Read DNT header from browser request and create request attribute
        """
        request.dnt = None
        if 'HTTP_DNT' in request.META:
            request.dnt = request.META['HTTP_DNT'] == '1'
            # returns None in normal conditions

    def process_response(self, request, response):
        """
        Echo DNT header in response per section 8.4 of draft-mayer-do-not-
        track-00
        """
        if 'HTTP_DNT' in request.META:
            response['DNT'] = request.META['HTTP_DNT']
        return response

class XssProtectMiddleware(BaseMiddleware):
    """
    DEPRECATED: Will be removed in future releases. Consider
    django.middleware.security.SecurityMiddleware as a replacement for this via
    SECURE_BROWSER_XSS_FILTER setting.

    Sends X-XSS-Protection HTTP header that controls Cross-Site Scripting
    filter on MSIE. Use XSS_PROTECT option in settings file with the following
    values:

      ``sanitize``   enable XSS filter that tries to sanitize requests instead
      of blocking (*default*)

      ``on``         enable full XSS filter blocking XSS requests (may `leak
      document.referrer <http://homakov.blogspot.com/2013/02/hacking-with-xss-
      auditor.html>`_)

      ``off``        completely disable XSS filter

    **Note:** As of 1.8, Django's `SECURE_BROWSER_XSS_FILTER
    <https://docs.djangoproject.com/en/1.8/ref/settings/#secure-browser-xss-filter>`_
    controls the X-XSS-Protection header.

    Reference:

    - `Controlling the XSS Filter
      <http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-
      internet-explorer-xss-filter-with-the-x-xss-protection-http-
      header.aspx>`_
    """

    OPTIONAL_SETTINGS = ("XSS_PROTECT",)

    OPTIONS = {
        'on': '1; mode=block',
        'off': '0',
        'sanitize': '1',
    }

    DEFAULT = 'sanitize'

    def __init__(self, get_response=None):
        super().__init__(get_response)
        warnings.warn('DEPRECATED: The middleware "{name}" will no longer be '
        'supported in future releases of this library. Refer to {url} for an '
        'alternative approach with regards to the settings: {settings}'.format(
            name=self.__class__.__name__,
            url=DJANGO_SECURITY_MIDDLEWARE_URL,
            settings="SECURE_BROWSER_XSS_FILTER"))

    def load_setting(self, setting, value):
        if not value:
            self.option = self.DEFAULT
            return

        value = value.lower()

        if value in self.OPTIONS.keys():
            self.option = value
            return

        raise ImproperlyConfigured(
            self.__class__.__name__ + " invalid option for XSS_PROTECT."
        )

    def process_response(self, request, response):
        """
        Add X-XSS-Protection to the reponse header.
        """
        header = self.OPTIONS[self.option]
        response['X-XSS-Protection'] = header
        return response

class ClearSiteDataMiddleware(BaseMiddleware):
    """
    Sends Clear-Site-Data HTTP response header on requests that match
    CLEAR_SITE_DATA_URL_WHITELIST.

    Clears browsing data (cookies, storage, cache) associated with the
    requesting website. Allows web developers to have more control over the
    data stored locally by a browser for their origins.

    Reference:

    - Clear-Site-Data: "cache", "cookies", "storage", "executionContexts", "*"
      <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data>`_
    """

    REQUIRED_SETTINGS = ('CLEAR_SITE_DATA_URL_WHITELIST',)
    OPTIONAL_SETTINGS = ('CLEAR_SITE_DATA_DIRECTIVES')

    DEFAULT_DIRECTIVES = ['cookies', 'storage']
    ALLOWED_DIRECTIVES = (
        'cache', 'cookies', 'storage', 'executionContexts', '*'
    )

    def load_setting(self, setting, value):
        if setting == 'CLEAR_SITE_DATA_URL_WHITELIST':
            self.clear_site_urls = value

        directives = getattr(
            django.conf.settings,
            'CLEAR_SITE_DATA_DIRECTIVES',
            self.DEFAULT_DIRECTIVES
        )

        directives = [
            directive.strip()
            for directive in directives
            if directive.strip() in self.ALLOWED_DIRECTIVES
        ]

        self.clear_site_directives = ', '.join(
            '"{0}"'.format(directive)
            for directive in directives
        )

    def process_response(self, request, response):
        """
        Add ``Clear-Site-Data`` response header if request in
        CLEAR_SITE_DATA_URLS.
        """

        if request.path in self.clear_site_urls:
            response['Clear-Site-Data'] = self.clear_site_directives

        return response

class ContentNoSniff(MiddlewareMixin):
    """
    DEPRECATED: Will be removed in future releases. Consider
    django.middleware.security.SecurityMiddleware as a replacement for this via
    SECURE_CONTENT_TYPE_NOSNIFF setting.

    Sends X-Content-Options HTTP header to disable autodetection of MIME type
    of files returned by the server in Microsoft Internet Explorer.
    Specifically if this flag is enabled, MSIE will not load external CSS and
    JavaScript files unless server correctly declares their MIME type. This
    mitigates attacks where web page would for example load a script that was
    disguised as an user- supplied image.

    **Note:** As of 1.8, Django's `SECURE_CONTENT_TYPE_NOSNIFF
    <https://docs.djangoproject.com/en/1.8/ref/settings/#secure-content-type-nosniff>`_
    controls the X-Content-Type-Options header.

    Reference:

    - `MIME-Handling Change: X-Content-Type-Options: nosniff
      <http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx>`_
    """

    def __init__(self, get_response=None):
        super().__init__(get_response)
        warnings.warn('DEPRECATED: The middleware "{name}" will no longer be '
        'supported in future releases of this library. Refer to {url} for an '
        'alternative approach with regards to the settings: {settings}'.format(
            name=self.__class__.__name__,
            url=DJANGO_SECURITY_MIDDLEWARE_URL,
            settings="SECURE_CONTENT_TYPE_NOSNIFF"))

    def process_response(self, request, response):
        """
        Add ``X-Content-Options: nosniff`` to the response header.
        """
        response['X-Content-Options'] = 'nosniff'
        return response

class MandatoryPasswordChangeMiddleware(BaseMiddleware):
    """
    Redirects any request from an authenticated user to the password change
    form if that user's password has expired. Must be placed after
    ``AuthenticationMiddleware`` in the middleware list.

    Configured by dictionary ``MANDATORY_PASSWORD_CHANGE`` with the following
    keys:

        ``URL_NAME``            name of of the password change view

        ``EXEMPT_URL_NAMES``    list of URLs that do not trigger password
        change request

        ``INCLUDE_SUPERUSERS``  also check superusers for password change,
        default False
    """

    OPTIONAL_SETTINGS = ("MANDATORY_PASSWORD_CHANGE",)

    def load_setting(self, setting, value):
        if value and "URL_NAME" not in value:
            raise ImproperlyConfigured(
                self.__class__.__name__ + " requires the URL_NAME setting"
            )

        self.settings = value
        self.exempt_urls = [
            compile(url) for url in self.settings.get("EXEMPT_URLS", ())
        ]

    def process_view(self, request, view, *args, **kwargs):
        if not self.settings:
            return

        if not request.user.is_authenticated:
            return

        if view == django.views.static.serve:
            return

        # Check for an exempt URL before trying to resolve URL_NAME,
        # because the reason the URL is exempt may be because a special URL
        # config is in use (i.e. during a test) that doesn't have URL_NAME.

        path = request.path_info.lstrip('/')

        if any(m.match(path) for m in self.exempt_urls):
            return

        url_name = resolve(request.path_info).url_name

        if url_name in self.settings.get("EXEMPT_URL_NAMES", ()):
            return

        password_change_url = reverse(self.settings["URL_NAME"])

        if request.path == password_change_url:
            return

        from .password_expiry import password_is_expired
        if password_is_expired(request.user):
            return HttpResponseRedirect(password_change_url)

class NoConfidentialCachingMiddleware(BaseMiddleware):
    """
    Adds No-Cache and No-Store headers to confidential pages. You can either
    whitelist non-confidential pages and treat all others as non-confidential,
    or specifically blacklist pages as confidential. The behaviour is
    configured in ``NO_CONFIDENTIAL_CACHING`` dictionary in settings file with
    the following keys:

        ``WHITELIST_ON``        all pages are confifendialt, except for pages
                                explicitly whitelisted in ``WHITELIST_REGEXES``

        ``WHITELIST_REGEXES``   list of regular expressions defining pages
                                exempt from the no caching policy

        ``BLACKLIST_ON``        only pages defined in ``BLACKLIST_REGEXES``
                                will have caching disabled

        ``BLACKLIST_REGEXES``   list of regular expressions defining
                                confidential pages for which caching should be
                                prohibited

    **Note:** Django's `cache_control
    <https://docs.djangoproject.com/en/dev/topics/cache/#controlling-cache-
    using-other-headers>`_ decorator allows more granular control of caching on
    individual view level.

    Reference:

    - `HTTP/1.1 Header definitions - What is Cacheable
      <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1>`_
    """

    OPTIONAL_SETTINGS = ("NO_CONFIDENTIAL_CACHING",)

    def load_setting(self, setting, value):
        value = value or {}
        self.whitelist = value.get("WHITELIST_ON", False)
        if self.whitelist:
            self.whitelist_url_regexes = \
                [compile(x) for x in value['WHITELIST_REGEXES']]
        self.blacklist = value.get("BLACKLIST_ON", False)
        if self.blacklist:
            self.blacklist_url_regexes = \
                [compile(x) for x in value['BLACKLIST_REGEXES']]

    def process_response(self, request, response):
        """
        Add the Cache control no-store to anything confidential. You can either
        whitelist non-confidential pages and treat all others as non-
        confidential, or specifically blacklist pages as confidential
        """
        path = request.path.lstrip('/')
        if self.whitelist:
            if not any(re.match(path) for re in self.whitelist_url_regexes):
                self._remove_response_caching(response)
                return response
        if self.blacklist:
            if any(re.match(path) for re in self.blacklist_url_regexes):
                self._remove_response_caching(response)
        return response

    def _remove_response_caching(self, response):
        """
        Overwrites specific headers to make the HTTP response confidential.
        """
        response['Cache-control'] = \
            'no-cache, no-store, max-age=0, must-revalidate'
        response['Pragma'] = "no-cache"
        response['Expires'] = -1

# http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-01
# http://tools.ietf.org/html/draft-ietf-websec-frame-options-00
class XFrameOptionsMiddleware(BaseMiddleware):
    """
    Emits ``X-Frame-Options headers`` in HTTP response. These
    headers will instruct the browser to limit ability of this web page
    to be framed, or displayed within a FRAME or IFRAME tag. This mitigates
    password stealing attacks like Clickjacking and similar.

    Use ``X_FRAME_OPTIONS`` in settings file with the following values:

      - ``deny``              prohibit any framing of this page
      - ``sameorigin``        allow frames from the same domain (*default*)
      - ``allow-from URL``  allow frames from specified *URL*

    **Note:** Frames and inline frames are frequently used by ads, social media
    plugins and similar widgets so test these features after setting this flag.

    You can exclude certain URLs from this header by setting
    ``X_FRAME_OPTIONS_EXCLUDE_URLS`` to a list of URL regexes like so::

        X_FRAME_OPTIONS_EXCLUDE_URLS = (
            r'^/some/url/here$',        # Note the initial slash
            r'^/another/to/exclude$',
        )

    The header will be sent unless ``request.path`` matches any of the above
    list. For more granular control, use ContentSecurityPolicyMiddleware_.

    References:

      - `RFC 7034: HTTP Header Field X-Frame-Options
        <http://tools.ietf.org/html/rfc7034>`_
    """

    OPTIONAL_SETTINGS = ('X_FRAME_OPTIONS', 'X_FRAME_OPTIONS_EXCLUDE_URLS')

    DEFAULT = 'deny'

    def __init__(self, get_response=None):
        super().__init__(get_response)
        warnings.warn('An official middleware "{name}" is supported by Django.'
        ' Refer to {url} to see if its approach fits the use case.'.format(
            name="XFrameOptionsMiddleware",
            url=DJANGO_CLICKJACKING_MIDDLEWARE_URL))

    def load_setting(self, setting, value):
        if setting == 'X_FRAME_OPTIONS':
            if not value:
                self.option = XFrameOptionsMiddleware.DEFAULT
                return

            value = value.lower()
            options = ['sameorigin', 'deny']

            if value in options or value.startswith('allow-from:'):
                self.option = value
                return

            raise ImproperlyConfigured(
                self.__class__.__name__ + " invalid option for X_FRAME_OPTIONS"
            )

        elif setting == 'X_FRAME_OPTIONS_EXCLUDE_URLS':
            if not value:
                self.exclude_urls = []
                return

            try:
                self.exclude_urls = [compile(url) for url in value]
            except TypeError:
                raise ImproperlyConfigured(
                    self.__class__.__name__ +
                    " invalid option for X_FRAME_OPTIONS_EXCLUDE_URLS",
                )

    def process_response(self, request, response):
        """
        Add X-Frame-Options and Frame-Options to the response header.
        """
        for url in self.exclude_urls:
            if url.match(request.path):
                break
        else:
            response['X-Frame-Options'] = self.option

        return response

# preserve older django-security API
# new API uses "deny" as default to maintain compatibility
XFrameOptionsDenyMiddleware = XFrameOptionsMiddleware

class ContentSecurityPolicyMiddleware(MiddlewareMixin):
    """
    .. _ContentSecurityPolicyMiddleware:

    Adds Content Security Policy (CSP) header to HTTP response.
    CSP provides fine grained instructions to the browser on
    location of allowed resources loaded by the page, thus mitigating
    attacks based on loading of untrusted JavaScript code such
    as Cross-Site Scripting.

    The policy can be set in two modes, controlled by ``CSP_MODE`` options:

        ``CSP_MODE='enforce'``        browser will enforce policy settings and
                                      log violations (*default*)

        ``CSP_MODE='report-only'``    browser will not enforce policy, only
                                      report violations

    The policy itself is a dictionary of content type keys and values
    containing list of allowed locations. For example, ``img-src`` specifies
    locations of images allowed to be loaded by this page:

        ``'img-src' : [ 'img.example.com' ]``

    Content types and special location types (such as ``none`` or ``self``)
    are defined in CSP draft (see References_).

    Example of policy dictionary (suitable for long, complex policies), with
    all supported content types (but not listing all supported locations):

    ::

        CSP_DICT = {
            # arrays of allowed locations
            "default-src" : ["self", "https:" ],
            "script-src" : ["self", "http://js.example.com" ],
            "style-src" : ["self", "http://css.example.com" ],
            "img-src" : ["self", "https://img.example.com" ],
            "connect-src" : ["self" ],
            "font-src" : ["https://*.example.com" ],
            "object-src" : ["none" ],
            "media-src" : ["http://media.example.com" ],
            "frame-src" : ["self" ],

            # array of allowed sandbox features
            "sandbox" : [ "" ],

            # array of allowed MIME types
            "plugin-types" : [ "application/pdf" ],

            # these are **not** arrays
            "reflected-xss" : 'filter',
            "report-uri" : "http://example.com/csp-report",
        }

    You can also supply a raw policy string, which is more suitable for short
    policies:

        ``CSP_STRING="default-src 'self'; script-src *.google.com"``

    If both ``CSP_DICT`` and ``CSP_STRING`` are set the middleware will throw
    an exception.

    **Notes:**

    - The special locations ('self', 'none', 'unsafe-eval', 'unsafe-inline')
      come **without** the additional single quotes in `CSP_DICT` and they
      will be automatically quoted by the middleware in the HTTP header.
    - The ``CSP_STRING`` on the other hand should be a verbatim copy of the
      HTTP header contents. It's not going the be processed in any way.
    - This middleware only sets the standard HTTP header variants
      (``Content-Security-Policy``). The experimental ones (``X-WebKit-CSP``
      and ``Content-Security-Policy``) are now obsolete.
    - Enabling CSP has significant impact on browser behaviour - for example
      inline JavaScript is disabled. Read `Default Policy Restrictions
      <http://developer.chrome.com/extensions/contentSecurityPolicy.html>`_ to
      see how pages need to be adapted to work under CSP.
    - Browsers will log CSP violations in JavaScript console and to a remote
      server configured by ``report-uri`` option. This package provides a view
      (csp_report_) to collect these alerts in your application. They can be
      then viewed using Django admin interface. For more advanced analytics try
      `CspBuilder <https://cspbuilder.info/>`_.
    - The middleware partially supports CSP 1.1 draft syntax.

    .. _References:

    **References:**

    - `Content Security Policy Level 2 <http://www.w3.org/TR/CSP11/>`_,
    - `HTML5.1 - Sandboxing <http://www.w3.org/html/wg/drafts/html/master
      /single-page.html#sandboxing>`_
    """
    # these types accept CSP locations as arguments
    _CSP_LOC_TYPES = [
        'default-src',
        'connect-src',
        'child-src',
        'font-src',
        'form-action',
        'frame-ancestors',
        'frame-src',
        'img-src',
        'media-src',
        'object-src',
        'script-src',
        'style-src',
        'plugin-types',
        'worker-src'
    ]

    # arguments to location types
    _CSP_LOCATIONS = ['self', 'none', 'unsafe-eval', 'unsafe-inline']

    # sandbox allowed arguments
    # http://www.w3.org/html/wg/drafts/html/master/single-page.html#sandboxing
    # https://www.w3.org/TR/CSP2/
    _CSP_SANDBOX_ARGS = [
        '',
        'allow-forms',
        'allow-pointer-lock',
        'allow-popups',
        'allow-same-origin',
        'allow-scripts',
        'allow-top-navigation',
    ]

    # reflected-xss allowed arguments
    # http://www.w3.org/TR/CSP11/#directive-reflected-xss
    _CSP_XSS_ARGS = ['allow', 'block', 'filter']

    # referrer allowed arguments
    # http://www.w3.org/TR/CSP11/#directive-referrer
    _CSP_REF_ARGS = [
        "none",
        "none-when-downgrade",
        "origin",
        "origin-when-cross-origin",
        "unsafe-url",
    ]

    # operational variables
    _csp_string = None
    _csp_mode = None

    def _csp_loc_builder(self, key, value):
        if not isinstance(value, (list, tuple)):
            logger.warn('Arguments to %s must be given as list or tuple', key)
            raise django.core.exceptions.MiddlewareNotUsed

        csp_loc_string = "{0}".format(key)
        for loc in value:
            if loc in self._CSP_LOCATIONS:
                csp_loc_string += " '{0}'".format(loc)  # quoted
            elif loc == '*':
                csp_loc_string += ' *'                   # not quoted
            else:
                # XXX: check for valid hostname or URL
                csp_loc_string += " {0}".format(loc)   # not quoted

        return csp_loc_string

    def _csp_sandbox_builder(self, key, value):
        if not isinstance(value, (list, tuple)):
            logger.warn('Arguments to %s must be given as list or tuple', key)
            raise django.core.exceptions.MiddlewareNotUsed

        csp_sandbox_string = "{0}".format(key)
        for opt in value:
            if opt in self._CSP_SANDBOX_ARGS:
                csp_sandbox_string += " {0}".format(opt)
            else:
                logger.warn('Invalid CSP sandbox argument %s', opt)
                raise django.core.exceptions.MiddlewareNotUsed

        return csp_sandbox_string

    def _csp_report_uri_builder(self, key, value):
        # XXX: add valid URL check
        return '{0} {1}'.format(key, value)

    def _csp_referrer_builder(self, key, value):
        if value not in self._CSP_REF_ARGS:
            logger.warning('Invalid CSP %s value %s', key, value)
            raise django.core.exceptions.MiddlewareNotUsed

        return "{0} {1}".format(key, value)

    def _csp_reflected_xss_builder(self, key, value):
        if value not in self._CSP_XSS_ARGS:
            logger.warning('Invalid CSP %s value %s', key, value)
            raise django.core.exceptions.MiddlewareNotUsed

        return "{0} {1}".format(key, value)

    def _csp_builder(self, csp_dict):
        csp_components = []

        for key, value in csp_dict.items():

            if key in self._CSP_LOC_TYPES:
                csp_components.append(self._csp_loc_builder(key, value))

            elif key == 'sandbox':
                csp_components.append(self._csp_sandbox_builder(key, value))

            elif key == 'report-uri':
                csp_components.append(self._csp_report_uri_builder(key, value))

            elif key == 'referrer':
                csp_components.append(self._csp_referrer_builder(key, value))

            elif key == 'reflected-xss':
                csp_components.append(
                    self._csp_reflected_xss_builder(key, value),
                )

            else:
                logger.warning('Invalid CSP type %s', key)
                raise django.core.exceptions.MiddlewareNotUsed

        return '; '.join(csp_components)

    def __init__(self, get_response=None):
        # sanity checks
        self.get_response = get_response

        csp_mode = getattr(django.conf.settings, 'CSP_MODE', None)
        csp_string = getattr(django.conf.settings, 'CSP_STRING', None)
        csp_dict = getattr(django.conf.settings, 'CSP_DICT', None)
        err_msg = 'Middleware requires either CSP_STRING or CSP_DICT setting'

        if not csp_mode or csp_mode == 'enforce':
            self._enforce = True
        elif csp_mode == 'report-only':
            self._enforce = False
        else:
            logger.warn(
                'Invalid CSP_MODE %s, "enforce" or "report-only" allowed',
                csp_mode
            )
            raise django.core.exceptions.MiddlewareNotUsed

        if not (csp_dict or csp_string):
            logger.warning('%s, none found', err_msg)
            raise django.core.exceptions.MiddlewareNotUsed

        if csp_dict and csp_string:
            logger.warning('%s, not both', err_msg)
            raise django.core.exceptions.MiddlewareNotUsed

        # build or copy CSP as string
        if csp_string:
            self._csp_string = csp_string

        if csp_dict:
            self._csp_string = self._csp_builder(csp_dict)

    def process_response(self, request, response):
        """
        Add Content Security Policy policy to the response header. Use either
        enforcement or report-only headers in all currently used variants.
        """
        # choose headers based enforcement mode
        is_ie = False
        if 'HTTP_USER_AGENT' in request.META:
            parsed_ua = ParseUserAgent(request.META['HTTP_USER_AGENT'])
            is_ie = parsed_ua['family'] == 'IE'

        if self._enforce:
            if is_ie:
                header = 'X-Content-Security-Policy'
            else:
                header = 'Content-Security-Policy'
        else:
            header = 'Content-Security-Policy-Report-Only'

        # actually add appropriate headers
        response[header] = self._csp_string

        return response

class StrictTransportSecurityMiddleware(MiddlewareMixin):
    """
    DEPRECATED: Will be removed in future releases. Consider
    django.middleware.security.SecurityMiddleware as a replacement for this via
    SECURE_HSTS_SECONDS, SECURE_HSTS_INCLUDE_SUBDOMAINS and
    SECURE_HSTS_PRELOAD settings.

    Adds Strict-Transport-Security header to HTTP
    response that enforces SSL connections on compliant browsers. Two
    parameters can be set in settings file, otherwise reasonable
    defaults will be used:

      - ``STS_MAX_AGE``               time in seconds to preserve host's STS
        policy (default: 1 year)
      - ``STS_INCLUDE_SUBDOMAINS``    True if subdomains should be covered by
        the policy as well (default: True)
      - ``STS_PRELOAD``               add ``preload`` flag to the STS header
        so that your website can be added to preloaded websites list

    **Note:** As of 1.8, Django's `SECURE_HSTS_SECONDS
    <https://docs.djangoproject.com/en/1.8/ref/settings/#secure-hsts-seconds>`_
    controls the HTTP Strict Transport Security header.

    Reference:

    - `HTTP Strict Transport Security (HSTS)
     <https://datatracker.ietf.org/doc/rfc6797/>`_
    - `Preloaded HSTS sites <http://www.chromium.org/sts>`_
    """
    def __init__(self, get_response=None):
        warnings.warn('DEPRECATED: The middleware "{name}" will no longer be '
        'supported in future releases of this library. Refer to {url} for an '
        'alternative approach with regards to the settings: {settings}'.format(
            name=self.__class__.__name__,
            url=DJANGO_SECURITY_MIDDLEWARE_URL,
            settings=", ".join([
                "SECURE_HSTS_SECONDS",
                "SECURE_HSTS_INCLUDE_SUBDOMAINS",
                "SECURE_HSTS_PRELOAD",
            ])))

        self.get_response = get_response

        try:
            self.max_age = django.conf.settings.STS_MAX_AGE
        except AttributeError:
            self.max_age = 3600 * 24 * 365  # one year

        try:
            self.subdomains = django.conf.settings.STS_INCLUDE_SUBDOMAINS
        except AttributeError:
            self.subdomains = True

        try:
            self.preload = django.conf.settings.STS_PRELOAD
        except AttributeError:
            self.preload = True

        self.value = 'max-age={0}'.format(self.max_age)

        if self.subdomains:
            self.value += ' ; includeSubDomains'

        if self.preload:
            self.value += ' ; preload'

    def process_response(self, request, response):
        """
        Add Strict-Transport-Security header.
        """
        response['Strict-Transport-Security'] = self.value
        return response

class P3PPolicyMiddleware(BaseMiddleware):
    """
    DEPRECATED: Will be removed in future releases.

    Adds the HTTP header attribute specifying compact P3P policy
    defined in P3P_COMPACT_POLICY setting and location of full
    policy defined in P3P_POLICY_URL. If the latter is not defined,
    a default value is used (/w3c/p3p.xml). The policy file needs to
    be created by website owner.

    **Note:** P3P work stopped in 2002 and the only popular
    browser with **limited** P3P support is MSIE.

    Reference:

    - `The Platform for Privacy Preferences 1.0 (P3P1.0) Specification - The
      Compact Policies <http://www.w3.org/TR/P3P/#compact_policies>`_
    """

    REQUIRED_SETTINGS = ("P3P_COMPACT_POLICY",)
    OPTIONAL_SETTINGS = ("P3P_POLICY_URL",)

    def __init__(self, get_response=None):
        super().__init__(get_response)
        warnings.warn('DEPRECATED: The middleware "{name}" will no longer be '
        'supported in future releases of this library.'.format(
            name=self.__class__.__name__
        ))

    def load_setting(self, setting, value):
        if setting == 'P3P_COMPACT_POLICY':
            self.policy = value
        elif setting == 'P3P_POLICY_URL':
            self.policy_url = value or '/w3c/p3p.xml'

    def process_response(self, request, response):
        """
        Add P3P policy to the response header.
        """
        response['P3P'] = 'policyref="{0}" CP="{1}"'.format(
            self.policy_url,
            self.policy,
        )
        return response

class SessionExpiryPolicyMiddleware(CustomLogoutMixin, BaseMiddleware):
    """
    The session expiry middleware will let you expire sessions on
    browser close, and on expiry times stored in the cookie itself.
    (Expiring a cookie on browser close means you don't set the expiry
    value of the cookie.) The middleware will read SESSION_COOKIE_AGE
    and SESSION_INACTIVITY_TIMEOUT from the settings.py file to determine
    how long to keep a session alive.

    We will purge a session that has expired. This middleware should be run
    before the LoginRequired middleware if you want to redirect the expired
    session to the login page (if required).

    Exemptions to this requirement can optionally be specified in settings via
    a list of regular expressions in SESSION_EXPIRY_EXEMPT_URLS (which you can
    copy from your urls.py).

    By default this middleware will call the builtin Django logout function to
    perform the logout. You can customize which logout function will be called
    by specifying it in your django settings using the CUSTOM_LOGOUT_MODULE
    variable. The value should be the module path to the function,
    e.g. 'django.contrib.auth.logout'.
    """

    OPTIONAL_SETTINGS = ('SESSION_COOKIE_AGE', 'SESSION_INACTIVITY_TIMEOUT',
                         'SESSION_EXPIRY_EXEMPT_URLS', 'CUSTOM_LOGOUT_MODULE')

    SECONDS_PER_DAY = 86400
    SECONDS_PER_30MINS = 1800

    # Session keys
    START_TIME_KEY = 'starttime'
    LAST_ACTIVITY_KEY = 'lastactivity'

    @classmethod
    def _get_datetime_in_session(cls, key, session):
        return dateutil.parser.parse(session[key])

    @classmethod
    def _set_datetime_in_session(cls, key, value, session):
        session[key] = str(value)

    @classmethod
    def get_start_time(cls, request):
        return cls._get_datetime_in_session(
            cls.START_TIME_KEY,
            request.session
        )

    @classmethod
    def set_start_time(cls, request, date):
        cls._set_datetime_in_session(
            cls.START_TIME_KEY,
            date,
            request.session
        )

    @classmethod
    def get_last_activity(cls, request):
        return cls._get_datetime_in_session(
            cls.LAST_ACTIVITY_KEY,
            request.session
        )

    @classmethod
    def set_last_activity(cls, request, date):
        cls._set_datetime_in_session(
            cls.LAST_ACTIVITY_KEY,
            date,
            request.session
        )

    def load_setting(self, setting, value):
        if setting == 'SESSION_COOKIE_AGE':
            self.SESSION_COOKIE_AGE = value or self.SECONDS_PER_DAY
            logger.debug("Max Session Cookie Age is %d seconds",
                         self.SESSION_COOKIE_AGE
                         )
        elif setting == 'SESSION_INACTIVITY_TIMEOUT':
            # half an hour in seconds
            self.SESSION_INACTIVITY_TIMEOUT = value or self.SECONDS_PER_30MINS
            logger.debug("Session Inactivity Timeout is %d seconds",
                         self.SESSION_INACTIVITY_TIMEOUT
                         )
        elif setting == 'SESSION_EXPIRY_EXEMPT_URLS':
            self.exempt_urls = [compile(expr) for expr in (value or ())]
        else:
            setattr(self, setting, value)

    def process_request(self, request):
        """
        Verify that the session should be considered active. We check
        the start time and the last activity time to determine if this
        is the case. We set the last activity time to now() if the session
        is still active.
        """
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Login Required middleware "
                "requires authentication middleware to be installed."
            )

        path = request.path_info.lstrip('/')

        if any(m.match(path) for m in self.exempt_urls):
            return

        if (
            self.START_TIME_KEY not in request.session or
            self.LAST_ACTIVITY_KEY not in request.session or
            timezone.is_naive(self.get_start_time(request)) or
            timezone.is_naive(self.get_last_activity(request))
        ):
            response = self.process_new_session(request)
        else:
            response = self.process_existing_session(request)

        if response:
            return response

    def process_new_session(self, request):
        now = timezone.now()
        session = request.session

        logger.debug("New session %s started: %s", session.session_key, now)
        self.set_start_time(request, now)
        self.set_last_activity(request, now)

    def process_existing_session(self, request):
        now = timezone.now()
        session = request.session
        start_time = self.get_start_time(request)
        last_activity_time = self.get_last_activity(request)

        logger.debug("Session %s started: %s",
                     session.session_key,
                     start_time
                     )
        logger.debug("Session %s last active: %s",
                     session.session_key,
                     last_activity_time
                     )

        session_age = self.get_diff_in_seconds(now, start_time)
        session_too_old = session_age > self.SESSION_COOKIE_AGE

        session_lastactive = self.get_diff_in_seconds(now, last_activity_time)
        session_inactive = session_lastactive > self.SESSION_INACTIVITY_TIMEOUT

        if session_too_old or session_inactive:
            logger.debug("Session %s is inactive.", session.session_key)
            response = None

            if request.user.is_authenticated:
                # Store the current path in the session
                # so we can redirect the user after the logout
                response = self.perform_logout(request)
            else:
                request.session.flush()

            return response

        logger.debug("Session %s is still active.", session.session_key)
        self.set_last_activity(request, now)

    def get_diff_in_seconds(self, now, time):
        diff = now - time
        age = diff.days * self.SECONDS_PER_DAY + diff.seconds
        return age

# Modified a little bit by us.

# Copyright (c) 2008, Ryan Witt
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the organization nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

class LoginRequiredMiddleware(BaseMiddleware, CustomLogoutMixin):
    """
    Middleware that requires a user to be authenticated to view any page on
    the site that hasn't been white listed. (The middleware also ensures the
    user is 'active'. Disabled users will be logged out and redirected to
    the login page.

    Exemptions to this requirement can optionally be specified in settings via
    a list of regular expressions in LOGIN_EXEMPT_URLS (which you can copy from
    your urls.py).

    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.

    By default this middleware will call the builtin Django logout function to
    perform the logout. You can customize which logout function will be called
    by specifying it in your django settings using the CUSTOM_LOGOUT_MODULE
    variable. The value should be the module path to the function,
    e.g. 'django.contrib.auth.logout'.
    """

    REQUIRED_SETTINGS = ('LOGIN_URL',)
    OPTIONAL_SETTINGS = ('LOGIN_EXEMPT_URLS', 'CUSTOM_LOGOUT_MODULE')

    def load_setting(self, setting, value):
        if setting == 'LOGIN_URL':
            self.login_url = value
        elif setting == 'LOGIN_EXEMPT_URLS':
            self.exempt_urls = [compile(expr) for expr in (value or ())]
        else:
            setattr(self, setting, value)

    def assert_authentication_middleware_installed(self, request):
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Login Required middleware "
                "requires authentication middleware to be installed."
            )

    def process_request(self, request):
        self.assert_authentication_middleware_installed(request)

        if request.user.is_authenticated and not request.user.is_active:
            response = self.perform_logout(request)

            if response:
                return response

        if request.user.is_authenticated:
            return

        path = request.path_info.lstrip('/')

        if any(m.match(path) for m in self.exempt_urls):
            return

        if hasattr(request, 'login_url'):
            login_url = request.login_url
            next_url = None
        else:
            login_url = self.login_url
            next_url = request.path

        if request.is_ajax():
            return HttpResponse(
                json.dumps({"login_url": login_url}),
                status=401,
                content_type="application/json",
            )

        if next_url:
            login_url = login_url + '?next=' + next_url

        return HttpResponseRedirect(login_url)


text:
window.onload = function() {
  var game = new Phaser.Game(320, 480, Phaser.CANVAS, "", {
    preload: onPreload,
    create: onCreate,
    update: onUpdate
  });
  var ball; // the ball! Our hero
  var arrow; // rotating arrow
  var rotateDirection = 1; // rotate direction: 1-clockwise, 2-counterclockwise
  var power = 0; // power to fire the ball
  var hudText; // text to display game info
  var charging = false; // are we charging the power?
  var degToRad = 0.0174532925; // degrees-radians conversion
  var score = 0; // the score
  var coin; // the coin you have to collect
  var deadlyArray = []; // an array which will be filled with enemies
  var gameOver = false; // flag to know if the game is over
  // these settings can be modified to change gameplay
  var friction = 0.99; // friction affects ball speed
  var ballRadius = 10; // radius of all elements
  var rotateSpeed = 3; // arrow rotation speed
  var minPower = 50; // minimum power applied to ball
  var maxPower = 200; // maximum power applied to ball
  // when the game preloads, graphic assets are loaded
  function onPreload() {
    game.load.image("ball", "assets/ball.png");
    game.load.image("deadly", "assets/deadly.png");
    game.load.image("coin", "assets/coin.png");
    game.load.image("arrow", "assets/arrow.png");
  }
  // function to be executed when the game is created
  function onCreate() {
    // center and scale the stage
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;
    game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    game.scale.setScreenSize();
    // add the ball and set its anchor point in the center
    ball = game.add.sprite(game.world.centerX, game.world.centerY, "ball");
    ball.anchor.x = 0.5;
    ball.anchor.y = 0.5;
    // ball starting speed
    ball.xSpeed = 0;
    ball.ySpeed = 0;
    // the rotating arrow
    arrow = game.add.sprite(game.world.centerX, game.world.centerY, "arrow");
    arrow.anchor.x = -1;
    arrow.anchor.y = 0.5;
    // place an enemy
    placeDeadly();
    // create and place a coin
    coin = game.add.sprite(Math.random() * 400 + 40, Math.random() * 240 + 40, "coin");
    coin.anchor.x = 0.5;
    coin.anchor.y = 0.5;
    placeCoin();
    // create and place the text showing speed and score
    hudText = game.add.text(5, 0, "", {
      font: "11px Arial",
      fill: "#ffffff",
      align: "left"
    });
    // update text content
    updateHud();
    // listener for input down
    game.input.onDown.add(charge, this);
  }
  // place an enemy
  function placeDeadly() {
    // first, create the enemy and set its anchor point in the center
    var deadly = game.add.sprite(0, 0, "deadly");
    deadly.anchor.x = 0.5;
    deadly.anchor.y = 0.5;
    // add the newly created enemy in the enemy array
    deadlyArray.push(deadly);
    // assign it a random position until such position is legal
    do {
      var randomX = Math.random() * (game.width - 2 * ballRadius) + ballRadius;
      var randomY = Math.random() * (game.height - 2 * ballRadius) + ballRadius;
      deadlyArray[deadlyArray.length - 1].x = randomX;
      deadlyArray[deadlyArray.length - 1].y = randomY;
    } while (illegalDeadly());
  }
  // determine if an enemy position is illegal
  function illegalDeadly() {
    // if the distance between the enemy and the ball is less than three times the radius, it's NOT legal
    if (getDistance(ball, deadlyArray[deadlyArray.length - 1]) < (ballRadius * 3) * (ballRadius * 3)) {
      return true;
    }
    // if the distance between the enemy and any other enemy is less than two times the radius, it's NOT legal
    for (i = 0; i < deadlyArray.length - 1; i++) {
      if (getDistance(deadlyArray[i], deadlyArray[deadlyArray.length - 1]) < (ballRadius * 2) * (ballRadius * 2)) {
        return true
      }
    }
    // otherwise it's legal
    return false;
  }
  // the function to place a coin is similar to the one which places the enemy, but this time we don't need
  // to place it in an array because there's only one coin on the stage
  function placeCoin() {
    // assign the coin a random position until such position is legal
    do {
      coin.x = Math.random() * (game.width - 2 * ballRadius) + ballRadius;
      coin.y = Math.random() * (game.height - 2 * ballRadius) + ballRadius;
    } while (illegalCoin());
  }
  // determine if a coin position is illegal
  function illegalCoin() {
    // if the distance between the coin and any ball is less than 2.5 times the radius, it's NOT legal
    if (getDistance(ball, coin) < (ballRadius * 2.5) * (ballRadius * 2.5)) {
      return true;
    }
    // if the distance between the coin and any enemy is less than three times the radius, it's NOT legal
    for (i = 0; i < deadlyArray.length; i++) {
      if (getDistance(deadlyArray[i], coin) < (ballRadius * 3) * (ballRadius * 3)) {
        return true
      }
    }
    // otherwise it's legal
    return false;
  }
  // function to be executed each time the game is updated
  function onUpdate() {
    // the game is update only if it's not game over
    if (!gameOver) {
      // when the player is charging the power, this is increased until it reaches the maximum allowed
      if (charging) {
        power++;
        power = Math.min(power, maxPower)
          // then game text is updated
        updateHud();
      }
      // if the player is not charging, keep rotating the arrow
      else {
        arrow.angle += rotateSpeed * rotateDirection;
      }
      // update ball position according to its speed
      ball.x += ball.xSpeed;
      ball.y += ball.ySpeed;
      // handle wall bounce
      wallBounce();
      // reduce ball speed using friction
      ball.xSpeed *= friction;
      ball.ySpeed *= friction;
      // update arrow position
      arrow.x = ball.x;
      arrow.y = ball.y;
      // if the player picked a coin, then update score and text, change coin position and add an enemy
      if (getDistance(ball, coin) < (ballRadius * 2) * (ballRadius * 2)) {
        score += 1;
        placeDeadly();
        placeCoin();
        updateHud();
      }
      // if the player hits an enemy, it's game over
      for (i = 0; i < deadlyArray.length; i++) {
        if (getDistance(ball, deadlyArray[i]) < (ballRadius * 2) * (ballRadius * 2)) {
          gameOver = true;
        }
      }
    }
  }
  // function to handle bounces. Just check for game boundary collision
  function wallBounce() {
    if (ball.x < ballRadius) {
      ball.x = ballRadius;
      ball.xSpeed *= -1
    }
    if (ball.y < ballRadius) {
      ball.y = ballRadius;
      ball.ySpeed *= -1
    }
    if (ball.x > game.width - ballRadius) {
      ball.x = game.width - ballRadius;
      ball.xSpeed *= -1
    }
    if (ball.y > game.height - ballRadius) {
      ball.y = game.height - ballRadius;
      ball.ySpeed *= -1
    }
  }
  // simple function to get the distance between two sprites
  // does not use sqrt to save CPU
  function getDistance(from, to) {
    var xDist = from.x - to.x
    var yDist = from.y - to.y;
    return xDist * xDist + yDist * yDist;
  }
  // when the player is charging, set the power to min power allowed
  // and wait the player to release the input to fire the ball
  function charge() {
    power = minPower;
    game.input.onDown.remove(charge, this);
    game.input.onUp.add(fire, this);
    charging = true;
  }
  // FIRE!!
  // update ball speed according to arrow direction
  // invert arrow rotation
  // reset power and update game text
  // wait for the player to fire again
  function fire() {
    game.input.onUp.remove(fire, this);
    game.input.onDown.add(charge, this);
    ball.xSpeed += Math.cos(arrow.angle * degToRad) * power / 20;
    ball.ySpeed += Math.sin(arrow.angle * degToRad) * power / 20;
    power = 0;
    updateHud();
    charging = false;
    rotateDirection *= -1;
  }
  // function to update game text
  function updateHud() {
    hudText.text = "Power: " + power + " * Score: " + score
  }
};


text:
using System.Linq;
using System.Windows;
using Smellyriver.TankInspector.Common.Wpf.Behaviors.DragDrop;

namespace Smellyriver.TankInspector.Pro.StatComparer
{
    partial class StatComparisonDocumentVM
    {
        private class AvailableStatsDropHandlerImpl : IDropTarget
        {
            private readonly StatsManagerVM _owner;

            public AvailableStatsDropHandlerImpl(StatsManagerVM owner)
            {
                _owner = owner;
            }

            public void DragOver(DropInfo dropInfo)
            {
                if (dropInfo.DragInfo.SourceCollection == _owner.SelectedStats)
                    dropInfo.Effects = DragDropEffects.Move;
                else
                    dropInfo.Effects = DragDropEffects.None;
            }

            public void Drop(DropInfo dropInfo)
            {
                if (dropInfo.DragInfo.SourceCollection == _owner.SelectedStats)
                {
                    var stats = dropInfo.GetEnumerableData<StatInfoVM>().ToList();
                    if (_owner.CanRemoveStat(stats))
                        _owner.RemoveStat(stats);
                }
            }
        }
    }
}


text:
package com.github.martincooper.datatable

/** Handles the output of a DataTable in a displayable format. */
object DataTableFormatter {

  private case class ColumnDetails(colIdx: Int, colName: String, width: Int)

  private val lineSeparator = System.getProperty("line.separator")

  /** Builds a string displaying the data in a DataView. */
  def prettyPrint(view: DataView): String = {
    prettyPrint(view.table, view.rows)
  }

  /** Builds a string displaying the data in a DataTable. */
  def prettyPrint(table: DataTable): String = {
    prettyPrint(table, table)
  }

  private def prettyPrint(table: DataTable, dataRows: IndexedSeq[DataRow]): String = {
    val colDetails = table.columns.zipWithIndex.map {
      case (column, index) => ColumnDetails(index, column.name, colWidth(index, column.name, dataRows))
    }

    val builder = new StringBuilder

    printHeader(builder, colDetails)
    printRows(builder, dataRows, colDetails)

    builder.mkString
  }

  private def printRows(builder: StringBuilder, dataRows: IndexedSeq[DataRow], colDetails: Seq[ColumnDetails]) = {
    dataRows.foreach(dataRow => printRow(builder, dataRow, colDetails))
  }

  private def printRow(builder: StringBuilder, dataRow: DataRow, colDetails: Seq[ColumnDetails]) = {
    val formattedValues = colDetails.map(details => {
      val textValue = dataRow(details.colIdx).toString
      "|" + colDataString(textValue, details.width)
    })

    writelnExt(builder, formattedValues)
  }

  private def printHeader(builder: StringBuilder, colDetails: Seq[ColumnDetails]) = {
    val totalLength = colDetails.map(_.width).sum + (colDetails.length * 2)
    val headerFooter = padString("", totalLength, '-')

    writeln(builder)
    writelnExt(builder, headerFooter)

    val formattedHeaders = colDetails.map(col => "|" + colDataString(col.colName, col.width))

    writelnExt(builder, formattedHeaders)
    writelnExt(builder, headerFooter)
  }

  /** Returns the value correctly formatted according to the width. */
  private def colDataString(data: String, width: Int): String = {
    padString(data, width, ' ')
  }

  /** Calculates the column width to use for a column. */
  private def colWidth(colIdx: Int, colName: String, dataRows: IndexedSeq[DataRow]) = {
    val columnData = dataRows.map(row => row(colIdx))
    maxValueLength(colName +: columnData) + 2
  }

  /** Returns the max data length of all the data in a collection. */
  private def maxValueLength(values: Iterable[Any]): Int = {
    values.map(_.toString.length).max
  }

  private def writeln(builder: StringBuilder) = {
    builder ++= lineSeparator
  }

  private def writelnExt(builder: StringBuilder, value: Traversable[Any]) = {
    builder ++= value.mkString
    builder ++= lineSeparator
  }

  private def padString(value: String, width: Int, padString: Char): String = {
    value.padTo(width, padString).mkString
  }
}


text:
INSERT INTO match_scores (
    match, alliance_color,
    teleop_points, teleop_rotor_points, teleop_fuel_high, teleop_fuel_high_points, teleop_fuel_low, teleop_fuel_low_points, teleop_fuel_points, teleop_takeoff_points,
    auto_points, auto_rotor_points, auto_fuel_high, auto_fuel_high_points, auto_fuel_low, auto_fuel_low_points, auto_fuel_points, auto_mobility_points,
    rotor_bonus_points, rotor_bonus_rank_point, pressure_bonus_points, pressure_bonus_rank_point,
    foul_points, foul_count, tech_foul_count,
    total_points, adjust_points
) VALUES (
    (SELECT id FROM matches WHERE key == ?), ?,
    ?, ?, ?, ?, ?, ?, ?, ?,
    ?, ?, ?, ?, ?, ?, ?, ?,
    ?, ?, ?, ?,
    ?, ?, ?,
    ?, ?
);


text:
import { DataType } from '../data-type';
import { ChronoUnit, LocalDate } from '@js-joda/core';
import WritableTrackingBuffer from '../tracking-buffer/writable-tracking-buffer';

const EPOCH_DATE = LocalDate.ofYearDay(1, 1);

const DateTimeOffset: DataType & { resolveScale: NonNullable<DataType['resolveScale']> } = {
  id: 0x2B,
  type: 'DATETIMEOFFSETN',
  name: 'DateTimeOffset',
  declaration: function(parameter) {
    return 'datetimeoffset(' + (this.resolveScale(parameter)) + ')';
  },
  resolveScale: function(parameter) {
    if (parameter.scale != null) {
      return parameter.scale;
    } else if (parameter.value === null) {
      return 0;
    } else {
      return 7;
    }
  },

  generateTypeInfo(parameter) {
    return Buffer.from([this.id, parameter.scale!]);
  },

  generateParameterData: function*(parameter, options) {
    const value = parameter.value;
    let scale = parameter.scale;

    if (value != null) {
      const buffer = new WritableTrackingBuffer(16);
      scale = scale!;

      let timestamp;
      timestamp = ((value.getUTCHours() * 60 + value.getUTCMinutes()) * 60 + value.getUTCSeconds()) * 1000 + value.getMilliseconds();
      timestamp = timestamp * Math.pow(10, scale - 3);
      timestamp += (value.nanosecondDelta != null ? value.nanosecondDelta : 0) * Math.pow(10, scale);
      timestamp = Math.round(timestamp);

      switch (scale) {
        case 0:
        case 1:
        case 2:
          buffer.writeUInt8(8);
          buffer.writeUInt24LE(timestamp);
          break;
        case 3:
        case 4:
          buffer.writeUInt8(9);
          buffer.writeUInt32LE(timestamp);
          break;
        case 5:
        case 6:
        case 7:
          buffer.writeUInt8(10);
          buffer.writeUInt40LE(timestamp);
      }

      const date = LocalDate.of(value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate());
      const days = EPOCH_DATE.until(date, ChronoUnit.DAYS);
      buffer.writeUInt24LE(days);

      const offset = -value.getTimezoneOffset();
      buffer.writeInt16LE(offset);
      yield buffer.data;
    } else {
      const buffer = new WritableTrackingBuffer(1);
      buffer.writeUInt8(0);
      yield buffer.data;
    }
  },
  validate: function(value): null | number | TypeError {
    if (value == null) {
      return null;
    }

    if (!(value instanceof Date)) {
      value = new Date(Date.parse(value));
    }

    if (isNaN(value)) {
      return new TypeError('Invalid date.');
    }

    return value;
  }
};

export default DateTimeOffset;
module.exports = DateTimeOffset;


text:
////////////////////////////////////////////////////////////////////////////////
// FormatException

var ss_FormatException = function#? DEBUG FormatException$##(message, innerException) {
	ss_Exception.call(this, message || 'Invalid format.', innerException);
};
ss_FormatException.__typeName = 'ss.FormatException';
ss.FormatException = ss_FormatException;
ss.initClass(ss_FormatException, ss, {}, ss_Exception);


text:
{{ post.title }}

{{ post.date | date:'medium' }} by
        {{ post.author }}

      <button type="button" class="btn btn-xs btn-primary">Comment</button>

{{ comment.date }}

{{ comment.body }}

    The requested post does not exist.