text:
from numbers import Real
from xml.etree import ElementTree as ET

import openmc.checkvalue as cv
from openmc.stats.multivariate import UnitSphere, Spatial
from openmc.stats.univariate import Univariate
from ._xml import get_text

class Source:
    """Distribution of phase space coordinates for source sites.

    Parameters
    ----------
    space : openmc.stats.Spatial
        Spatial distribution of source sites
    angle : openmc.stats.UnitSphere
        Angular distribution of source sites
    energy : openmc.stats.Univariate
        Energy distribution of source sites
    filename : str
        Source file from which sites should be sampled
    library : str
        Path to a custom source library

        .. versionadded:: 0.12
    strength : float
        Strength of the source
    particle : {'neutron', 'photon'}
        Source particle type

    Attributes
    ----------
    space : openmc.stats.Spatial or None
        Spatial distribution of source sites
    angle : openmc.stats.UnitSphere or None
        Angular distribution of source sites
    energy : openmc.stats.Univariate or None
        Energy distribution of source sites
    file : str or None
        Source file from which sites should be sampled
    library : str or None
        Path to a custom source library
    strength : float
        Strength of the source
    particle : {'neutron', 'photon'}
        Source particle type

    """

    def __init__(self, space=None, angle=None, energy=None, filename=None,
                 library=None, strength=1.0, particle='neutron'):
        self._space = None
        self._angle = None
        self._energy = None
        self._file = None
        self._library = None

        if space is not None:
            self.space = space
        if angle is not None:
            self.angle = angle
        if energy is not None:
            self.energy = energy
        if filename is not None:
            self.file = filename
        if library is not None:
            self.library = library
        self.strength = strength
        self.particle = particle

    @property
    def file(self):
        return self._file

    @property
    def library(self):
        return self._library

    @property
    def space(self):
        return self._space

    @property
    def angle(self):
        return self._angle

    @property
    def energy(self):
        return self._energy

    @property
    def strength(self):
        return self._strength

    @property
    def particle(self):
        return self._particle

    @file.setter
    def file(self, filename):
        cv.check_type('source file', filename, str)
        self._file = filename

    @library.setter
    def library(self, library_name):
        cv.check_type('library', library_name, str)
        self._library = library_name

    @space.setter
    def space(self, space):
        cv.check_type('spatial distribution', space, Spatial)
        self._space = space

    @angle.setter
    def angle(self, angle):
        cv.check_type('angular distribution', angle, UnitSphere)
        self._angle = angle

    @energy.setter
    def energy(self, energy):
        cv.check_type('energy distribution', energy, Univariate)
        self._energy = energy

    @strength.setter
    def strength(self, strength):
        cv.check_type('source strength', strength, Real)
        cv.check_greater_than('source strength', strength, 0.0, True)
        self._strength = strength

    @particle.setter
    def particle(self, particle):
        cv.check_value('source particle', particle, ['neutron', 'photon'])
        self._particle = particle

    def to_xml_element(self):
        """Return XML representation of the source

        Returns
        -------
        element : xml.etree.ElementTree.Element
            XML element containing source data

        """
        element = ET.Element("source")
        element.set("strength", str(self.strength))
        if self.particle != 'neutron':
            element.set("particle", self.particle)
        if self.file is not None:
            element.set("file", self.file)
        if self.library is not None:
            element.set("library", self.library)
        if self.space is not None:
            element.append(self.space.to_xml_element())
        if self.angle is not None:
            element.append(self.angle.to_xml_element())
        if self.energy is not None:
            element.append(self.energy.to_xml_element('energy'))
        return element

    @classmethod
    def from_xml_element(cls, elem):
        """Generate source from an XML element

        Parameters
        ----------
        elem : xml.etree.ElementTree.Element
            XML element

        Returns
        -------
        openmc.Source
            Source generated from XML element

        """
        source = cls()

        strength = get_text(elem, 'strength')
        if strength is not None:
            source.strength = float(strength)

        particle = get_text(elem, 'particle')
        if particle is not None:
            source.particle = particle

        filename = get_text(elem, 'file')
        if filename is not None:
            source.file = filename

        library = get_text(elem, 'library')
        if library is not None:
            source.library = library

        space = elem.find('space')
        if space is not None:
            source.space = Spatial.from_xml_element(space)

        angle = elem.find('angle')
        if angle is not None:
            source.angle = UnitSphere.from_xml_element(angle)

        energy = elem.find('energy')
        if energy is not None:
            source.energy = Univariate.from_xml_element(energy)

        return source


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Created by thilina on 12/16/16.
 */
var core_1 = require("@angular/core");
var http_1 = require("@angular/http");
require("rxjs/add/operator/toPromise");
var AppSetting_1 = require("../../class/AppSetting");
var UserService = (function () {
    function UserService(http) {
        this.http = http;
        this.headers = new http_1.Headers({ 'Content-Type': 'application/json' });
        this.userDetailByNicUrl = AppSetting_1.AppSettings.DIRECT_PAY_ENDPOINT + '/user/detail/nic';
        this.merchantLastTransactions = AppSetting_1.AppSettings.DIRECT_PAY_ENDPOINT + '/transactions/last';
        this.merchantLastTransaction = AppSetting_1.AppSettings.DIRECT_PAY_ENDPOINT + '/transaction/last';
    }
    UserService.prototype.userDetailByBrNumber = function (nic) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            return _this.http
                .post(_this.userDetailByNicUrl, JSON.stringify({ nic: nic }), { headers: _this.headers })
                .toPromise()
                .then(function (response) {
                //noinspection TypeScriptUnresolvedFunction
                console.log(response.json());
                resolve(response.json());
            }, function (error) {
                console.log(error);
                reject(error);
            })
                .catch(function (err) {
                console.log(err);
                reject(err);
            });
        });
    };
    UserService.prototype.getLastTransaction = function (id) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            return _this.http
                .post(_this.merchantLastTransaction, JSON.stringify({ id: id }), { headers: _this.headers })
                .toPromise()
                .then(function (response) {
                console.log(response.json());
                resolve(response.json());
            }, function (error) {
                console.log(error);
                reject(error);
            })
                .catch(function (err) {
                console.log(err);
                reject(err);
            });
        });
    };
    UserService.prototype.getLastTransactions = function (id) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            return _this.http
                .post(_this.merchantLastTransactions, JSON.stringify({ id: id }), { headers: _this.headers })
                .toPromise()
                .then(function (response) {
                console.log(response.json());
                resolve(response.json());
            }, function (error) {
                console.log(error);
                reject(error);
            })
                .catch(function (err) {
                console.log(err);
                reject(err);
            });
        });
    };
    return UserService;
}());
UserService = __decorate([
    core_1.Injectable()
], UserService);
exports.UserService = UserService;

redpajama_set_name: RedPajamaGithub


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'SONG CITY' });
});

module.exports = router;


text:
<?php
function initialize_curl() {
	$ch = curl_init();
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_VERBOSE, true);
   return $ch;
}

/*
function getVIMSFac () {
	$content = file('VIMS_facilities_codes.csv');
	$rows = array_map('str_getcsv', $content,array_fill(0, count($content), ","));
	return $rows;
}
*/

function getVIMSFac () {
	$username = "";
	$password = "";
	$ch = initialize_curl();
	curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
	$url = 'https://vimstraining.elmis-dev.org:443/rest-api/facilities/'.$code;
	curl_setopt($ch, CURLOPT_URL, $url);
	$details = curl_exec($ch);
	$details = json_decode($details,true);
	return $details;
}

function createCSDFacility($facDetails) {
	$name = $facDetails['facility']['name'];
	$code = $facDetails['facility']['code'];
	$type = $facDetails['facility']['facilityType'];
	$geographicZone = $facDetails['facility']['geographicZone'];
	$gln = $facDetails['facility']['gln'];
	$id = $facDetails['facility']['id'];

	$post = '<csd:requestParams xmlns:csd="urn:ihe:iti:csd:2013">
  					<csd:facility id="'.$id.'">
    					<csd:code>'.$code.'</csd:code>
    					<csd:name>'.$name.'</csd:name>
    					<csd:district>'.$geographicZone.'</csd:district>
							<csd:gln>'.$gln.'</csd:gln>
							<csd:ftype>'.$type.'</csd:ftype>
  					</csd:facility>
					 </csd:requestParams>';
	$ch = initialize_curl();
	$url = "http://localhost:8984/CSD/csr/vims/careServicesRequest/update/urn:openhie.org:openinfoman-tz:facility_create_vims_tz";
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
	curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
	curl_setopt($ch, CURLOPT_URL, $url);
	$data = curl_exec($ch);
}

function getDetails ($code) {
	$username = "";
	$password = "";
	$ch = initialize_curl();
	curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
	$url = 'https://vimstraining.elmis-dev.org:443/rest-api/facilities/'.$code;
	curl_setopt($ch, CURLOPT_URL, $url);
	$details = curl_exec($ch);
	$details = json_decode($details,true);
	return $details;
}

$facilities = getVIMSFac();
foreach ($facilities as $key => $facility) {
	echo "processing =====>".$key;
	$facDet = getDetails ($facility['0']);
	if(!array_key_exists("facility",$facDet)) {
		echo $key;
		print_r($facility);
		exit;
	}
	createCSDFacility($facDet);
}
?>


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Security.EnterpriseData;
using Windows.Storage.Pickers;
using System.Threading.Tasks;
using SDKTemplate;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace EdpSample
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Scenario4 : Page
    {
        private MainPage rootPage;
        private string m_protectScenarioDesc = "App is an enterprise enlightened app.When it retrieves enterprise data in a file, it must protect the file " +
                                             "that contains said data.It does so by protecting the file to an enterprise identity. After this, the app " +
                                             "can use standard APIs to read or write from the file.The app generally gets the enterprise identity from an " +
                                             "external resource such as a mailbox";
        private string m_getProtectScenarioDesc = "\n\nAn app has attempted to access a resource that it previously protected. It is denied access and wants to "  +
                                                  "check the status of the file to see what went wrong.The app calls the GetProtectionInfoAsync API to query the status.";
        private string m_isRoamableScenarioDesc =  "\n\nAn app wants to roam its protected file to other devices.In order to do so, it must check if the file's protection " +
                                                  "can be roamed.The app calls GetProtectionInfoAsync on the file to retrieve this information.";
        private string m_copyProtectionScenarioDesc = "\n\nAn app wants to create multiple copies of a protected file in which enterprise data is stored.It can use the CopyProtectionAsync" +
                                                      "API to replicate protection from one file to another.";

        private StorageFile m_file = null;
        private string m_FileCopyName =  "Edpcopy.txt";

        public Scenario4()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ScenarioText.Text = m_protectScenarioDesc + m_getProtectScenarioDesc +
                               m_isRoamableScenarioDesc + m_copyProtectionScenarioDesc;
            rootPage = MainPage.Current;
        }

        private async void FilePickerBt_Click(object sender, RoutedEventArgs e)
        {
            string outputStr = "";

            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add("*");
            m_file = await openPicker.PickSingleFileAsync();
            if (m_file != null)
            {
                // Application now has read/write access to the picked file
                outputStr += "\nPicked file: " + m_file.Path;
                rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
            }
            else
            {
                outputStr += "\nPlease pick a file";
                rootPage.NotifyUser(outputStr, NotifyType.ErrorMessage);
            }
        }

        private async void CreateFileAndProtect()
        {
            string outputStr = "";

            FileProtectionInfo procInfo =  await FileProtectionManager.GetProtectionInfoAsync(m_file);
            if (procInfo.Status != FileProtectionStatus.Protected)
            {
                outputStr += "\nProtecting File: ";
                await FileProtectionManager.ProtectAsync(m_file, Scenario1.m_enterpriseId);
                procInfo =  await FileProtectionManager.GetProtectionInfoAsync(m_file);
                outputStr += "\nProtected File: " + m_file.Path + "Status:" + procInfo.Status;
            }
            else
            {
                outputStr += "\nFile protection status is: " + procInfo.Status;
            }

            rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
        }

        public async void CopyProtectionAsync()
        {
            if (m_file != null)
            {
                StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile destFile = await localFolder.CreateFileAsync(m_FileCopyName, CreationCollisionOption.OpenIfExists);

                if (destFile != null)
                {
                    await destFile.DeleteAsync();
                }

                // Recreate file
                destFile = await localFolder.CreateFileAsync(m_FileCopyName, CreationCollisionOption.ReplaceExisting);

                string outputStr = "Copying protection from source: " + m_file.Path + "\nTo destination: " + destFile.Path;
                bool result = await FileProtectionManager.CopyProtectionAsync(m_file, destFile);
                if (!result)
                {
                    rootPage.NotifyUser(outputStr + " Copy protection Failed", NotifyType.ErrorMessage);
                }
                else
                {
                    FileProtectionInfo sourceInfo = await FileProtectionManager.GetProtectionInfoAsync(m_file);
                    FileProtectionInfo destInfo = await FileProtectionManager.GetProtectionInfoAsync(destFile);
                    if (sourceInfo.Status != destInfo.Status)
                    {
                        outputStr += "\nsource and destination don't have same protection source status:" +
                                            sourceInfo.Status + " Destination status:" + destInfo.Status;
                        rootPage.NotifyUser(outputStr, NotifyType.ErrorMessage);
                    }
                    else
                    {
                        outputStr += "\nCopying protection succeeded";
                        rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
                    }
                }
            }
            else
            {
                rootPage.NotifyUser("Please pick a source file", NotifyType.ErrorMessage);
            }
        }

        public async Task<string> GetFileStatusStringAsync()
        {
            string outputStr = "";

            FileProtectionInfo protectionInfo = await FileProtectionManager.GetProtectionInfoAsync(m_file);
            if (protectionInfo.Status == FileProtectionStatus.Revoked)
            {
                outputStr += "\nFile " + m_file.Path + " is revoked";
            }
            else
            {
                outputStr += "\nFile protection status of: " + m_file.Path + " is " + protectionInfo.Status;
            }

            if (protectionInfo.IsRoamable)
            {
                outputStr += "\nFile " + m_file.Path + " is roamable";
            }
            else
            {
                outputStr += "\nFile " + m_file.Path + " is not roamable";
            }

            return outputStr;
        }

        private async void ProtectAsyncFileStatus_Click(object sender, RoutedEventArgs e)
        {
            if (m_file != null)
            {
                rootPage.NotifyUser(await GetFileStatusStringAsync(), NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Please pick a file", NotifyType.ErrorMessage);
            }
        }

        private void ProtectAsyncFile_Click(object sender, RoutedEventArgs e)
        {
            if (m_file != null)
            {
                CreateFileAndProtect();
            }
            else
            {
                rootPage.NotifyUser("Please pick a file", NotifyType.ErrorMessage);
            }
        }

        private void CopyProtectionAsync_Click(object sender, RoutedEventArgs e)
        {
            CopyProtectionAsync();
        }
    }
}


text:
using System.Collections.Immutable;
using Discord;

namespace Mitternacht.Services {
	public interface IBotCredentials {
		ulong                 ClientId           { get; }
		string                Token              { get; }
		ImmutableArray<ulong> OwnerIds           { get; }
		string                DbConnection       { get; }

		string                GoogleApiKey       { get; }
		string                MashapeKey         { get; }
		string                LoLApiKey          { get; }
		string                OsuApiKey          { get; }
		string                CleverbotApiKey    { get; }
		string                CarbonKey          { get; }
		string                PatreonCampaignId  { get; }
		string                PatreonAccessToken { get; }

		int                   TotalShards        { get; }
		string                ShardRunCommand    { get; }
		string                ShardRunArguments  { get; }
		int?                  ShardRunPort       { get; }

		string                ForumUsername      { get; }
		string                ForumPassword      { get; }

		bool IsOwner(IUser u);
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Contenta - Admin</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

	<link rel="shortcut icon" href="public/img/Logo_favicon.png"  type="image/png">

	<link rel="stylesheet" href="public/css/lib/select2.css" />
	<link rel="stylesheet" href="public/css/contenta.css" />
	<link rel="stylesheet" href="public/css/contenta-card.css" />
	<link rel="stylesheet" href="public/css/contenta-forms.css" />

Menu

Home

Admin

Series

                          menu item 3.1

                          menu item 3.2

menu item 3.2.1

menu item 3.2.2 with longer link name

menu item 3.2.3

menu item 3.2.4

menu item 3.2.5

menu item 3.3

menu item 3.4

                  Plain Page

Edit Series Title

Could not find Issue 5 of Abe Sapien(2013)

Uncaught exception: Traceback (most recent call last

Last Updated From ComicVine: Sep 08, 2015
        		    Refresh Metadata

				<form name="series_edit">
					<fieldset>
						<legend>Series Details</legend>

							Name
							<input type="text" id="name" placeholder="Batman"/>

							Publisher
							<select id="publisher">
								<option value="1" data-foo="pub_3.png" selected>DC Comics</option>
								<option value="2" data-foo="pub_7.jpeg">Marvel</option>
								<option value="3" data-foo="pub_11.jpeg" >Image</option>
								<option value="4" data-foo="pub_63.jpeg" >whatever</option>
								<option value="5" data-foo="pub_63.jpeg" >None</option>
							</select>

							Start Year
							<input type="text" id="year" placeholder="2000"/>

							Issues
							<input type="text" id="issues" placeholder="1"/>

							Description
							<textarea type="text" id="desc" placeholder="2000">Top comics writer Jeff Lemire teams with superstar artist Mike McKone for the all-new monthly series JUSTICE LEAGUE UNITED, starring the new team of powerful heroes Earth calls Justice League Canada! </textarea>

							<input class="flag_input" type="checkbox" name="series-pub_active" checked="">
								Actively publishing

							<input class="flag_input" type="checkbox" name="series-pub_wanted">
								Wanted for collection

							<input type="reset" onclick="ajaxFunction()" value="Reset"/>

							<input type="submit" onclick="ajaxFunction()" value="Save"/>

					</fieldset>
				</form>

			 Website |
			 Help |
			Report Issue

			Release: 0.4.0
4e5f1df094f610cbd2fb5260523845fa82adabf1

			Local site is 5 COMMITS BEHIND


text:
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.Project
{
	[CLSCompliant(false), ComVisible(true)]
	public class ProjectReferenceNode : ReferenceNode
	{
		#region fieds
		/// <summary>
		/// The name of the assembly this refernce represents
		/// </summary>
		private Guid referencedProjectGuid;

		private string referencedProjectName = String.Empty;

		private string referencedProjectRelativePath = String.Empty;

		private string referencedProjectFullPath = String.Empty;

		private BuildDependency buildDependency;

		/// <summary>
		/// This is a reference to the automation object for the referenced project.
		/// </summary>
		private EnvDTE.Project referencedProject;

		/// <summary>
		/// This state is controlled by the solution events.
		/// The state is set to false by OnBeforeUnloadProject.
		/// The state is set to true by OnBeforeCloseProject event.
		/// </summary>
		private bool canRemoveReference = true;

		/// <summary>
		/// Possibility for solution listener to update the state on the dangling reference.
		/// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false.
		/// </summary>
		private bool isNodeValid;

		#endregion

		#region properties

		public override string Url
		{
			get
			{
				return this.referencedProjectFullPath;
			}
		}

		public override string Caption
		{
			get
			{
				return this.referencedProjectName;
			}
		}

		internal Guid ReferencedProjectGuid
		{
			get
			{
				return this.referencedProjectGuid;
			}
		}

		/// <summary>
		/// Possiblity to shortcut and set the dangling project reference icon.
		/// It is ussually manipulated by solution listsneres who handle reference updates.
		/// </summary>
		internal protected bool IsNodeValid
		{
			get
			{
				return this.isNodeValid;
			}
			set
			{
				this.isNodeValid = value;
			}
		}

		/// <summary>
		/// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted.
		/// </summary>
		internal bool CanRemoveReference
		{
			get
			{
				return this.canRemoveReference;
			}
			set
			{
				this.canRemoveReference = value;
			}
		}

		internal string ReferencedProjectName
		{
			get { return this.referencedProjectName; }
		}

		/// <summary>
		/// Gets the automation object for the referenced project.
		/// </summary>
        internal EnvDTE.Project ReferencedProjectObject
        {
            get
            {
                // If the referenced project is null then re-read.
                if (this.referencedProject == null)
                {

                    // Search for the project in the collection of the projects in the
                    // current solution.
                    EnvDTE.DTE dte = (EnvDTE.DTE)this.ProjectMgr.GetService(typeof(EnvDTE.DTE));
                    if ((null == dte) || (null == dte.Solution))
                    {
                        return null;
                    }
                    foreach (EnvDTE.Project prj in dte.Solution.Projects)
                    {
                        //Skip this project if it is an umodeled project (unloaded)
                        if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, prj.Kind, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            continue;
                        }

                        // Get the full path of the current project.
                        EnvDTE.Property pathProperty = null;
                        try
                        {
                            if (prj.Properties == null)
                            {
                                continue;
                            }

                            pathProperty = prj.Properties.Item("FullPath");
                            if (null == pathProperty)
                            {
                                // The full path should alway be availabe, but if this is not the
                                // case then we have to skip it.
                                continue;
                            }
                        }
                        catch (ArgumentException)
                        {
                            continue;
                        }
                        string prjPath = pathProperty.Value.ToString();
                        EnvDTE.Property fileNameProperty = null;
                        // Get the name of the project file.
                        try
                        {
                            fileNameProperty = prj.Properties.Item("FileName");
                            if (null == fileNameProperty)
                            {
                                // Again, this should never be the case, but we handle it anyway.
                                continue;
                            }
                        }
                        catch (ArgumentException)
                        {
                            continue;
                        }
                        prjPath = System.IO.Path.Combine(prjPath, fileNameProperty.Value.ToString());

                        // If the full path of this project is the same as the one of this
                        // reference, then we have found the right project.
                        if (NativeMethods.IsSamePath(prjPath, referencedProjectFullPath))
                        {
                            this.referencedProject = prj;
                            break;
                        }
                    }
                }

                return this.referencedProject;
            }
            set
            {
                this.referencedProject = value;
            }
        }

		/// <summary>
		/// Gets the full path to the assembly generated by this project.
		/// </summary>
		internal string ReferencedProjectOutputPath
		{
			get
			{
				// Make sure that the referenced project implements the automation object.
				if(null == this.ReferencedProjectObject)
				{
					return null;
				}

				// Get the configuration manager from the project.
				EnvDTE.ConfigurationManager confManager = this.ReferencedProjectObject.ConfigurationManager;
				if(null == confManager)
				{
					return null;
				}

				// Get the active configuration.
				EnvDTE.Configuration config = confManager.ActiveConfiguration;
				if(null == config)
				{
					return null;
				}

				// Get the output path for the current configuration.
				EnvDTE.Property outputPathProperty = config.Properties.Item("OutputPath");
                if (null == outputPathProperty || outputPathProperty.Value == null)
				{
					return null;
				}

				string outputPath = outputPathProperty.Value.ToString();

				// Ususally the output path is relative to the project path, but it is possible
				// to set it as an absolute path. If it is not absolute, then evaluate its value
				// based on the project directory.
				if(!System.IO.Path.IsPathRooted(outputPath))
				{
					string projectDir = System.IO.Path.GetDirectoryName(referencedProjectFullPath);
					outputPath = System.IO.Path.Combine(projectDir, outputPath);
				}

				// Now get the name of the assembly from the project.
				// Some project system throw if the property does not exist. We expect an ArgumentException.
				EnvDTE.Property assemblyNameProperty = null;
				try
				{
					assemblyNameProperty = this.ReferencedProjectObject.Properties.Item("OutputFileName");
				}
				catch(ArgumentException)
				{
				}

				if(null == assemblyNameProperty)
				{
					return null;
				}
				// build the full path adding the name of the assembly to the output path.
				outputPath = System.IO.Path.Combine(outputPath, assemblyNameProperty.Value.ToString());

				return outputPath;
			}
		}

		private Automation.OAProjectReference projectReference;
		internal override object Object
		{
			get
			{
				if(null == projectReference)
				{
					projectReference = new Automation.OAProjectReference(this);
				}
				return projectReference;
			}
		}
		#endregion

		#region ctors
		/// <summary>
		/// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists.
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings")]
		public ProjectReferenceNode(ProjectNode root, ProjectElement element)
			: base(root, element)
		{
			this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
			Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrive referenced project path form project file");

			string guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project);

			// Continue even if project setttings cannot be read.
			try
			{
				this.referencedProjectGuid = new Guid(guidString);

				this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
				this.ProjectMgr.AddBuildDependency(this.buildDependency);
			}
			finally
			{
				Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file");

				this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name);

				Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file");
			}

			Uri uri = new Uri(this.ProjectMgr.BaseURI.Uri, this.referencedProjectRelativePath);

			if(uri != null)
			{
				this.referencedProjectFullPath = Microsoft.VisualStudio.Shell.Url.Unescape(uri.LocalPath, true);
			}
		}

		/// <summary>
		/// constructor for the ProjectReferenceNode
		/// </summary>
		public ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference)
			: base(root)
		{
			Debug.Assert(root != null && !String.IsNullOrEmpty(referencedProjectName) && !String.IsNullOrEmpty(projectReference)
				&& !String.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid.");

            if (projectReference == null)
            {
                throw new ArgumentNullException("projectReference");
            }

            this.referencedProjectName = referencedProjectName;

			int indexOfSeparator = projectReference.IndexOf('|');

			string fileName = String.Empty;

			// Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes.
			if(indexOfSeparator != -1)
			{
				string projectGuid = projectReference.Substring(0, indexOfSeparator);
				this.referencedProjectGuid = new Guid(projectGuid);
				if(indexOfSeparator + 1 < projectReference.Length)
				{
					string remaining = projectReference.Substring(indexOfSeparator + 1);
					indexOfSeparator = remaining.IndexOf('|');

					if(indexOfSeparator == -1)
					{
						fileName = remaining;
					}
					else
					{
						fileName = remaining.Substring(0, indexOfSeparator);
					}
				}
			}

			Debug.Assert(!String.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid.");

			// Did we get just a file or a relative path?
			Uri uri = new Uri(projectPath);

			string referenceDir = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, uri);

			Debug.Assert(!String.IsNullOrEmpty(referenceDir), "Can not add a project reference because the input for adding one is invalid.");

			string justTheFileName = Path.GetFileName(fileName);
			this.referencedProjectRelativePath = Path.Combine(referenceDir, justTheFileName);

			this.referencedProjectFullPath = Path.Combine(projectPath, justTheFileName);

			this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);

		}
		#endregion

		#region methods
		protected override NodeProperties CreatePropertiesObject()
		{
			return new ProjectReferencesProperties(this);
		}

		/// <summary>
		/// The node is added to the hierarchy and then updates the build dependency list.
		/// </summary>
		public override void AddReference()
		{
			if(this.ProjectMgr == null)
			{
				return;
			}
			base.AddReference();
			this.ProjectMgr.AddBuildDependency(this.buildDependency);
			return;
		}

		/// <summary>
		/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
		/// </summary>
		public override void Remove(bool removeFromStorage)
		{
			if(this.ProjectMgr == null || !this.CanRemoveReference)
			{
				return;
			}
			this.ProjectMgr.RemoveBuildDependency(this.buildDependency);
			base.Remove(removeFromStorage);
			return;
		}

		/// <summary>
		/// Links a reference node to the project file.
		/// </summary>
		protected override void BindReferenceData()
		{
			Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized");
			Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized");

			this.ItemNode = new ProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference);

			this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName);
			this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B"));
			this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
		}

		/// <summary>
		/// Defines whether this node is valid node for painting the refererence icon.
		/// </summary>
		/// <returns></returns>
		protected override bool CanShowDefaultIcon()
		{
			if(this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid)
			{
				return false;
			}

			IVsHierarchy hierarchy = null;

			hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid);

			if(hierarchy == null)
			{
				return false;
			}

			//If the Project is unloaded return false
			if(this.ReferencedProjectObject == null)
			{
				return false;
			}

			return (!String.IsNullOrEmpty(this.referencedProjectFullPath) && File.Exists(this.referencedProjectFullPath));
		}

		/// <summary>
		/// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references.
		/// </summary>
		/// <param name="errorHandler">The error handler delegate to return</param>
		/// <returns></returns>
		protected override bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler)
		{
			// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
			if(!base.CanAddReference(out errorHandler))
			{
				return false;
			}

			errorHandler = null;
			if(this.IsThisProjectReferenceInCycle())
			{
				errorHandler = new CannotAddReferenceErrorMessage(ShowCircularReferenceErrorMessage);
				return false;
			}

			return true;
		}

		private bool IsThisProjectReferenceInCycle()
		{
			return IsReferenceInCycle(this.referencedProjectGuid);
		}

		private void ShowCircularReferenceErrorMessage()
		{
			string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectContainsCircularReferences, CultureInfo.CurrentUICulture), this.referencedProjectName);
			string title = string.Empty;
			OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
			OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
			OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
			VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
		}

		/// <summary>
		/// Recursively search if this project reference guid is in cycle.
		/// </summary>
		private bool IsReferenceInCycle(Guid projectGuid)
		{
			IVsHierarchy hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid);

			IReferenceContainerProvider provider = hierarchy as IReferenceContainerProvider;
			if(provider != null)
			{
				IReferenceContainer referenceContainer = provider.GetReferenceContainer();

				Debug.Assert(referenceContainer != null, "Could not found the References virtual node");

				foreach(ReferenceNode refNode in referenceContainer.EnumReferences())
				{
					ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode;
					if(projRefNode != null)
					{
						if(projRefNode.ReferencedProjectGuid == this.ProjectMgr.ProjectIDGuid)
						{
							return true;
						}

						if(this.IsReferenceInCycle(projRefNode.ReferencedProjectGuid))
						{
							return true;
						}
					}
				}
			}

			return false;
		}
		#endregion
	}

}


text:
/* -*-C++-*-
******************************************************************************
*
* File:         MVJoinGraph.cpp
* Description:  Definition of classes for verifying the join graph is
*               fully connected, and for finding a good ordering of tables.
*
* Created:      7 March 2000
* Language:     C++
* Status:       $State: Exp $
*
*
******************************************************************************
*/

#include "Sqlcomp.h"
#include "AllItemExpr.h"
#include "AllRelExpr.h"
#include "GroupAttr.h"
#include "MVInfo.h"
#include "MVJoinGraph.h"

//============================================================================
//===========================  class MVJoinTable =============================
//============================================================================

NABoolean MVJoinTable::operator==(const MVJoinTable &other) const
{
  if(&other == this)
    return TRUE;
  else
    return FALSE;
}

//////////////////////////////////////////////////////////////////////////////
// Get all the ref constraints from this NATable, filter the ones that are to
// tables in this graph, and mark them on both tables. For example, use the
// RI on Orderes and Customers: O->C ( O is referencing C ). Because of the
// semantics of the order of the tables in the join graph, in order for RI
// optimization to be utilized, C must appear in the graph solution AFTER O.
// The result is that C has an incoming bit for table O, and O has an
// outgoing bit for table C.
// Other conditions that must be met for the RI to be usable:
// 1. C must have non-empty, insert only delta.
// 2. O must not be inner tables of left joins.
// 3. Each of the columns of the RI constraint must be covered by a predicate.
//    So if O(a,b) is referencing C(x,y) the join should use these two equal
//    predicates: (O.a = C.x) AND (O.b = C.y).
// In this method, this table is O, and otherTable is C.
Lng32 MVJoinTable::markRiConstraints(BindWA *bindWA, MVInfo *mvInfo)
{
  LIST (MVUsedObjectInfo*)& usedObjects = mvInfo->getUsedObjectsList();
  if (usedObjects[tableIndex_]->isInnerTableOfLeftJoin())
    return 0;	// O must not be inner table of a left join.

  Lng32 howManyRIs=0;
  const AbstractRIConstraintList& refConstraints =
    naTable_->getRefConstraints();

  for (CollIndex i=0; i<refConstraints.entries(); i++)
  {
    RefConstraint *const ref = (RefConstraint *const)(refConstraints[i]);
    CMPASSERT(ref->getOperatorType() == ITM_REF_CONSTRAINT);
    // Ignore self referencing RIs.
    if (ref->selfRef())
      continue;

    // Find the table the RI is referencing.
    const NAString& otherTableName =
      ref->getOtherTableName().getQualifiedNameAsString();
    MVJoinTable *otherTable =
      mvInfo->getJoinGraph()->getTableObjectFor(&otherTableName);
    if (otherTable == NULL)
      continue;	 // The other table must be on the graph.

    if (otherTable->deltaType_ != INSERTONLY_DELTA)
      continue;  // C must be insert only.

    Lng32 otherTableIndex = otherTable->getTableIndex();

    // The RI must be covered by equal predicates on the same columns
    LIST(Lng32) myCols;
    LIST(Lng32) otherCols;
    ref->getMyKeyColumns(myCols);
    ref->getOtherTableKeyColumns(bindWA, otherCols);
    CMPASSERT(myCols.entries() == otherCols.entries());

    NABoolean matchingPredicatesExist=TRUE;
    for (CollIndex currentCol=0; currentCol<myCols.entries(); currentCol++)
    {
      if (!mvInfo->isEqPredicateBetween(naTable_->getTableName(),
					myCols[currentCol],
					ref->getOtherTableName(),
					otherCols[currentCol]))
	matchingPredicatesExist = FALSE;
    }
    if (!matchingPredicatesExist)
      continue;

    // OK - we found a qualifying RI that we can use for optimization.
    // Now mark the bits.
    markRiTo(otherTableIndex);
    otherTable->markRiFrom(getTableIndex());
    howManyRIs++;
  }
  return howManyRIs;
}

//////////////////////////////////////////////////////////////////////////////
// Is there a predicate from any table in the connected set to this table?
NABoolean MVJoinTable::isOnPredicate(const MVJoinGraphState& state) const
{
  // The route bitmap is a bitmap of the connected set.
  // Mask only those tables of the route we have a predicate to.
  NABitVector coveredPredicates(predicateBitmap_);

  coveredPredicates.intersectSet(state.getRouteBitmap());
  // One covered predicate is all we need.
  return coveredPredicates.entries() > 0;
}

//////////////////////////////////////////////////////////////////////////////
// Is there an RI from any table is the connected set to this table?
NABoolean MVJoinTable::isOnRI(const MVJoinGraphState& state) const
{
  // If there are no RIs at all, skip the check.
  if (state.getNofRIs() == 0)
    return FALSE;

  // The route bitmap is a bitmap of the connected set.
  // Mask only those tables of the route we have an incoming RI from.
  NABitVector coveredIncomingRis(incomingRiBitmap_);

  coveredIncomingRis.intersectSet(state.getRouteBitmap());
  // One covered RI is all we need.
  return coveredIncomingRis.entries() > 0;
}

//////////////////////////////////////////////////////////////////////////////
// How good is this table as a candidate for the next table on the route?
// Score categories :
// 1. RI from the connected set to this table
//    This RI can be utilized now.
// 2. outgoing RIs from this table to tables in the available set.
//    These RIs can be utilized later.
// 3. incoming RIs from the available set to this table (negative score).
//    Taking this table next will not allow us to utilize the RI later.
// 4. Predicates from this table to tables in the available set.
//    Better chances for connectivity.
// This method is called O(n^3) times.
Lng32 MVJoinTable::calcHeuristics(const MVJoinGraphState& state) const
{
  // These are the weights used by the heuristic function.
  enum {  WEIGHT_ON_RI       =  100,
	  WEIGHT_OUTGOING_RI =  100,
	  WEIGHT_PREDICATE   =    1,
	  WEIGHT_INCOMING_RI = -200 };

  Lng32 score = 0;

  // Check the predicates first.
  NABitVector predicatesToAS(predicateBitmap_);
  predicatesToAS.intersectSet(state.getAvailableBitmap());

  Lng32 preds = (Lng32) predicatesToAS.entries();
  score += preds*WEIGHT_PREDICATE;       // Category 4

  // If there are no RIs, the result is based on predicates alone.
  if (state.getNofRIs() == 0)
    return score;

  // Check outgoing RIs to the available set.
  NABitVector outRisToAS(outgoingRiBitmap_);
  outRisToAS.intersectSet(state.getAvailableBitmap());

  Lng32 outRIs = (Lng32) outRisToAS.entries();
  score += outRIs*WEIGHT_OUTGOING_RI;   // Category 2

  // Check incoming RIs from the available set.
  NABitVector inRisFromAS(incomingRiBitmap_);
  inRisFromAS.intersectSet(state.getAvailableBitmap());

  Lng32 inRIs  = (Lng32) inRisFromAS.entries();
  score += inRIs*WEIGHT_INCOMING_RI;    // Category 3

  // Is this table on RI now?
  if (isOnRI(state))
    score += WEIGHT_ON_RI;		// Category 1

  return score;
}

//////////////////////////////////////////////////////////////////////////////
#ifndef NDEBUG
static void BitmapToString(const NABitVector& bm, NAString& text)
{
  CollIndex lastBit;

  bm.lastUsed(lastBit);
#pragma nowarn(1506)   // warning elimination
  for (Int32 i=lastBit; i>=0; i--)
#pragma warn(1506)  // warning elimination
  {
    if (bm.testBit(i))
      text += "1  ";
    else
      text += "0  ";
  }
}

void MVJoinTable::print(FILE* ofd, const char* indent, const char* title)const
{
  char buffer[20];
  const char *deltaTypeText = NULL;
  switch (deltaType_)
  {
    case EMPTY_DELTA     : deltaTypeText = "Empty Delta";      break;
    case INSERTONLY_DELTA: deltaTypeText = "InsertOnly Delta"; break;
    case NONEMPTY_DELTA  : deltaTypeText = "Nonempty Delta";   break;
  }
  fprintf(ofd, "Table no. %d: %s (%s),\n",
	  tableIndex_, tableName_.data(), deltaTypeText);

  NAString titleString(" ");
  CollIndex lastBit;

  predicateBitmap_.lastUsed(lastBit);
#pragma nowarn(1506)   // warning elimination
  for (Int32 i=lastBit; i>=0  ; i--)
#pragma warn(1506)  // warning elimination
  {
	snprintf( buffer, 20, "%d", i );
    titleString += buffer;
    titleString += ", ";
  }
  NAString predicateString(" ");
  NAString inRiString(" ");
  NAString outRiString(" ");
  BitmapToString(predicateBitmap_,  predicateString);
  BitmapToString(incomingRiBitmap_, inRiString);
  BitmapToString(outgoingRiBitmap_, outRiString);

  fprintf(ofd, "\tTableIndices : %s.\n", titleString.data());
  fprintf(ofd, "\tPredicates to: %s.\n", predicateString.data());
  fprintf(ofd, "\tIncoming RIs : %s.\n", inRiString.data());
  fprintf(ofd, "\tOutgoing RIs : %s.\n", outRiString.data());
}

void MVJoinTable::display() const
{
  print();
}
#endif

//============================================================================
//===========================  class MVJoinGraphSolution =======================
//============================================================================

//////////////////////////////////////////////////////////////////////////////
// Ctor. Initialize the route_ array.
MVJoinGraphSolution::MVJoinGraphSolution(Lng32 nofTables, CollHeap *heap)
  : route_(heap, nofTables),
    entries_(0),
    bitmap_(heap),
    riTables_(heap, nofTables)
{
  for (Lng32 i=0; i<nofTables; i++)
    route_.insert(i, -1);
}

//////////////////////////////////////////////////////////////////////////////
// Add a table to the route_
void MVJoinGraphSolution::pushTable(Lng32 tableIndex, NABoolean isOnRi)
{
  route_[entries_] = tableIndex;
  bitmap_.setBit(tableIndex);
  entries_++;
  if (isOnRi)
    riTables_.insert(tableIndex);
}

//////////////////////////////////////////////////////////////////////////////
// Start fresh with a new clean route.
void MVJoinGraphSolution::reset()
{
  for (Lng32 i=0; i<entries_; i++)
  {
    bitmap_.resetBit(route_[i]);
    route_[i] = -1;
  }

  entries_ = 0;
  riTables_.clear();
}

//////////////////////////////////////////////////////////////////////////////
#ifndef NDEBUG
void MVJoinGraphSolution::print(FILE* ofd, const char* indent, const char* title)const
{
  fprintf(ofd, "\nMVJoinGraphSolution (Score: %d): ", getScore());
  for (Lng32 i=0; i<entries_; i++)
    fprintf(ofd, "%d, ", route_[i]);
  fprintf(ofd, ".\n");
}

void MVJoinGraphSolution::display() const
{
  print();
}
#endif

//============================================================================
//===========================  class MVJoinGraphState ========================
//============================================================================

//////////////////////////////////////////////////////////////////////////////
// Ctor. Initialize the availableBitmap according to the available set.
MVJoinGraphState::MVJoinGraphState(Lng32              nofTables,
				   Lng32              nofRIs,
				   const MVTableSet& reorderGroup,
				   CollHeap         *heap)
  : nofTables_(nofTables),
    nofRI_(nofRIs),
    connectedSet_(heap, nofTables),
    availableSet_(reorderGroup, heap),
    availableBitmap_(heap),
    currentRoute_(nofTables, heap),
    bestRoute_(nofTables, heap)
{
  for (CollIndex i=0; i<reorderGroup.entries(); i++)
    availableBitmap_.setBit(reorderGroup[i]);
}

//////////////////////////////////////////////////////////////////////////////
// Pick the next table to be added to the route, according to the
// heuristic function.
// If this is the first table of the route, pick it from the notStartedSet_,
// otherwise, pick it from the availableSet.
// Return -1 if there are no predicates from any table in the connected set
// to any table in the available set. This means the graph is not connected.
// This method does not yet take into account left outer joins.
Lng32 MVJoinGraphState::pickNextTable(const MVJoinGraph& joinGraph,
				     NABoolean          isFirst) const
{
  Lng32 maxResult = -1000000; // Negative scores are bad but legal.
  Lng32 maxTable  = -1;

  const MVTableSet& availableTables =
    isFirst ? joinGraph.getNotStartedSet() : availableSet_;

  // Find the score for each of the available tables.
  for (CollIndex i=0; i<availableTables.entries(); i++)
  {
    Lng32 currentTableIndex = availableTables[i];
    const MVJoinTable *currentTable =
      joinGraph.getTableObjectAt(currentTableIndex);

    // If this is the first table on the route, there is nothing in the
    // connected set to have a predicate to. Otherwise, a table is
    // considered only if it has a predicate to the connected set.
    if (!isFirst && !currentTable->isOnPredicate(*this))
      continue;

    // Calculate the heuristic score for the current table.
    Lng32 currentResult = currentTable->calcHeuristics(*this);

    // Is it the best so far?
    if (currentResult > maxResult)
    {
      maxResult = currentResult;
      maxTable  = currentTableIndex;
    }
  }

  return maxTable;
}

//////////////////////////////////////////////////////////////////////////////
// Update the state according to the next table that was chosen.
void MVJoinGraphState::nextTableIs(Lng32 tableIndex, NABoolean isOnRI)
{
  // Add the table to the connected set.
  connectedSet_.insert(tableIndex);

  // Remove it from the available set.
  availableSet_.remove(tableIndex);
  availableBitmap_.resetBit(tableIndex);

  // Add it to the route.
  currentRoute_.pushTable(tableIndex, isOnRI);
}

//////////////////////////////////////////////////////////////////////////////
// Start fresh looking for a new solution.
// Reset all data members except bestRoute_.
void MVJoinGraphState::reset(const MVTableSet& reorderGroup)
{
  availableSet_ = reorderGroup;
  connectedSet_.clear();
  currentRoute_.reset();

  for (CollIndex i=0; i<reorderGroup.entries(); i++)
    availableBitmap_.setBit(reorderGroup[i]);
}

//////////////////////////////////////////////////////////////////////////////
// Is the current solution better than bestRoute_?
// If so - may the better route win.
void MVJoinGraphState::chooseBestSolution()
{
  if (bestRoute_.isEmpty()     ||
      (currentRoute_.getScore() > bestRoute_.getScore()))
    bestRoute_ = currentRoute_;
}

//============================================================================
//===========================  class MVJoinGraph =============================
//============================================================================

//////////////////////////////////////////////////////////////////////////////
// Find the table name in the hash table, get the table index and return
// the table object. This method is used primarily during the initialization
// of predicates and RIs.
MVJoinTable *MVJoinGraph::getTableObjectFor(const NAString *tableName)
{
  return tableHash_.getFirstValue(tableName);
}

//////////////////////////////////////////////////////////////////////////////
// Add a prepared table to the graph.
void MVJoinGraph::addTable(MVJoinTable *newNode)
{
  usedTables_[newNode->getTableIndex()] = newNode;
  tableHash_.insert(newNode->getTableName(), newNode);
}

//////////////////////////////////////////////////////////////////////////////
// Prepare a table object and add it to the graph.
void MVJoinGraph::addTable(Lng32           tableIndex,
			   Lng32           usedObjectsIndex,
			   const NATable *naTable)
{
  MVJoinTable *newNode = new(heap_)
    MVJoinTable(tableIndex, usedObjectsIndex, nofTables_, naTable, heap_);
  addTable(newNode);
}

//////////////////////////////////////////////////////////////////////////////
// Given a table qualified name, returns the table's name as an Ansi string
NAString MVJoinGraph::fixName(const QualifiedName& tableName) const
{
  // If the name already has double-quotes mark, that means it is already
  // in an Ansi format. if we return it ...AsAnsiString, another set of
  // double-quotes will be added, and we don't want to do that.
  if(tableName.getObjectName().contains('"'))
  {
    return tableName.getQualifiedNameAsString();
  }
  return tableName.getQualifiedNameAsAnsiString();
}

//////////////////////////////////////////////////////////////////////////////
// Mark an equal predicate between two tables.
void MVJoinGraph::markPredicateBetween(const QualifiedName& leftTable,
				       const QualifiedName& rightTable)
{
  NAString leftTableName(fixName(leftTable));
  NAString rightTableName(fixName(rightTable));

  // Find the index of the left table.
  MVJoinTable *leftTableObj  = tableHash_.getFirstValue(&leftTableName);
  Lng32   leftIndex          = leftTableObj->getTableIndex();

  // Find the index of the right table.
  MVJoinTable *rightTableObj = tableHash_.getFirstValue(&rightTableName);
  Lng32   rightIndex         = rightTableObj->getTableIndex();

  // Mark the predicate on both tables.
  leftTableObj->markPredicateTo(rightIndex);
  rightTableObj->markPredicateTo(leftIndex);
}

//////////////////////////////////////////////////////////////////////////////
// Mark the RI constraints for all the tables.
void MVJoinGraph::markRiConstraints(BindWA *bindWA, MVInfo *mvInfo)
{
  for (Lng32 i=0; i<nofTables_; i++)
    nofRI_ += usedTables_[i]->markRiConstraints(bindWA, mvInfo);
}

//////////////////////////////////////////////////////////////////////////////
// The first table was chosen, now find a solution from there.
// Return TRUE if a solution was found, FALSE if not.
NABoolean MVJoinGraph::findSolutionFrom(MVJoinGraphState& state)
{
  while (!state.isComplete())
  {
    Lng32 nextTable = state.pickNextTable(*this, FALSE);
    if (nextTable == -1)
    {
      // No predicates to tables in the available set - the graph is not
      // fully connected.
      return FALSE;
    }

    // Can we utilize an RI for optimization on this table?
    NABoolean isOnRI = usedTables_[nextTable]->isOnRI(state);
    // Update the graph state with the new table.
    state.nextTableIs(nextTable, isOnRI);
  }

  // Compare the solution we just found to the best solution so far.
  state.chooseBestSolution();

  return TRUE;
}

//////////////////////////////////////////////////////////////////////////////
// This is the DDL version of the algorithm:
//   - RIs are not used at all.
//   - Only one attempt is made to reach a solution.
//   - We only want to know if the graph is fully connected or not.
//   - In order to support left outer joins, this is still missing:
//     * Instead of one group of all tables, the tables should be divided
//       to reorder groups according to the location of the left join, where
//       an inner table of a left join is a group by itself.
//     * The algorithm should be run for each group separatly.
//     * If a group is not connected, tables in the group that are not
//       mentioned in the join predicates of the left join above them, can be
//       moved to the group above the inner table. Then run it again.
NABoolean MVJoinGraph::isFullyConnected()
{
  if (nofTables_==1)
  {
    // This is a single table MV - of course its connected.
    return TRUE;
  }

#ifndef NDEBUG
  if ( CmpCommon::getDefault(MV_DUMP_DEBUG_INFO) == DF_ON )
      display();
#endif

  // start with one group of all tables.
  for (Lng32 i=0; i<nofTables_; i++)
    reorderGroupSet_.insert(i);
  notStartedSet_ = reorderGroupSet_;
  MVJoinGraphState state(nofTables_, nofRI_, reorderGroupSet_, heap_);

  // Choose a first table to start from (according to predicates).
  Lng32 nextTable = state.pickNextTable(*this, TRUE);
  CMPASSERT(nextTable != -1);
  state.nextTableIs(nextTable, FALSE);

  // Find a solution from this table.
  NABoolean isConnected = findSolutionFrom(state);

  if (isConnected)
  {
    // The state object will be gone when we exit this method, so save
    // the solution for later (to order the tables).
    theSolution_ = state.getCurrentRoute();

#ifndef NDEBUG
  if ( CmpCommon::getDefault(MV_DUMP_DEBUG_INFO) == DF_ON )
    theSolution_.display();
#endif
  }
  return isConnected;
}

//////////////////////////////////////////////////////////////////////////////
// Mark the connected order of the tables in the MVInfo used objects list.
// (used in DDL only).
void MVJoinGraph::markOrderOfUsedObjects(MVInfoForDDL *mvInfo)
{
  const GraphRoute&	    finalRoute  = theSolution_.getRoute();
  LIST (MVUsedObjectInfo*)& usedObjects = mvInfo->getUsedObjectsList();

  if (nofTables_ == 1)
  {
    // This is a single table MV, so the algorithm was not run.
    // Just mark the table as table no. 0.
    MVUsedObjectInfo *usedInfo = usedObjects[0];
    usedInfo->setOrdinalNumber(0);
    return;
  }

  for (Lng32 i=0; i<nofTables_; i++)
  {
    // Get the tableIndex
    Lng32 tableIndex = finalRoute[i];
    // Find the index into the usedObjects list.
    Lng32 usedObjectsIndex = usedTables_[tableIndex]->getUsedObjectsIndex();
    // Get the usedObject from the list.
    MVUsedObjectInfo *usedInfo = usedObjects[usedObjectsIndex];

    usedInfo->setOrdinalNumber(i);
  }
}

//////////////////////////////////////////////////////////////////////////////
// This is the MDL version of the algorithm, used during a multi-delta refresh.
//   - RIs are used to determine the BEST order of the tables.
//   - We compute a solution from each and every table in the graph, and use
//     the number of usable RIs on the solution to determine which one wins.
void MVJoinGraph::findBestOrder()
{
  CMPASSERT(nofTables_>1);

#ifndef NDEBUG
    display();
#endif

  // start with one group of all tables.
  for (Lng32 i=0; i<nofTables_; i++)
    reorderGroupSet_.insert(i);
  notStartedSet_ = reorderGroupSet_;
  MVJoinGraphState state(nofTables_, nofRI_, reorderGroupSet_, heap_);

  NABoolean done = FALSE;
  while (!done && notStartedSet_.entries()>0)
  {
    // Choose a table to start from
    Lng32 firstTable = state.pickNextTable(*this, TRUE);
    CMPASSERT(firstTable != -1);
    state.nextTableIs(firstTable, FALSE);
    notStartedSet_.remove(firstTable);

    // Find a solution from this table.
    if (findSolutionFrom(state))
    {
      state.chooseBestSolution();
      if (state.getBestRoute().getScore() == nofRI_)
	done = TRUE;  // This is as good as it gets.
    }
    else
    {
      // If we get here the graph is not fully connected!
      CMPASSERT(FALSE);
    }

    if (!done)
      state.reset(reorderGroupSet_);
  }

  CMPASSERT(!state.getBestRoute().isEmpty());

  // The state object will be gone when we exit this method, so save
  // the solution for later.
  theSolution_ = state.getBestRoute();

#ifndef NDEBUG
  theSolution_.display();
#endif
}

//////////////////////////////////////////////////////////////////////////////
// Return the route of the solution, translated into indices to the used
// objects array.
void MVJoinGraph::getRouteOfSolution(GraphRoute& translatedRoute) const
{
  for (Lng32 i=0; i<nofTables_; i++)
  {
    Lng32 usedObjectIndex = usedTables_[i]->getUsedObjectsIndex();
    translatedRoute.insertAt(i, usedObjectIndex);
  }
}

//////////////////////////////////////////////////////////////////////////////
// Return TRUE if all the deltas are either empty or insert only.
NABoolean MVJoinGraph::isInsertOnlyRefresh() const
{
  for (Lng32 i=0; i<nofTables_; i++)
  {
    if (usedTables_[i]->isNonEmptyDelta())
      return FALSE;
  }

  return TRUE;
}

//////////////////////////////////////////////////////////////////////////////
#ifndef NDEBUG
void MVJoinGraph::print(FILE* ofd, const char* indent, const char* title)const
{
  fprintf(ofd, "\nMVJoinGraph:\n");
  for (Lng32 i=0; i<nofTables_; i++)
    usedTables_.at(i)->print(ofd);
}

void MVJoinGraph::display() const
{
  print();
}
#endif


text:
from heatclient.v1.stacks import Stack
from heatclient.v1.stacks import StackManager

from mock import MagicMock
import testscenarios
from testscenarios.scenarios import multiply_scenarios
import testtools

load_tests = testscenarios.load_tests_apply_scenarios

def mock_stack(manager, stack_name, stack_id):
    return Stack(manager, {
        "id": stack_id,
        "stack_name": stack_name,
        "links": [{
            "href": "http://192.0.2.1:8004/v1/1234/stacks/%s/%s" % (
                stack_name, stack_id),
            "rel": "self"}],
        "description": "No description",
        "stack_status_reason": "Stack create completed successfully",
        "creation_time": "2013-08-04T20:57:55Z",
        "updated_time": "2013-08-04T20:57:55Z",
        "stack_status": "CREATE_COMPLETE"
    })

class StackStatusActionTest(testtools.TestCase):

    scenarios = multiply_scenarios([
        ('CREATE', dict(action='CREATE')),
        ('DELETE', dict(action='DELETE')),
        ('UPDATE', dict(action='UPDATE')),
        ('ROLLBACK', dict(action='ROLLBACK')),
        ('SUSPEND', dict(action='SUSPEND')),
        ('RESUME', dict(action='RESUME'))
    ], [
        ('IN_PROGRESS', dict(status='IN_PROGRESS')),
        ('FAILED', dict(status='FAILED')),
        ('COMPLETE', dict(status='COMPLETE'))
    ])

    def test_status_action(self):
        stack_status = '%s_%s' % (self.action, self.status)
        stack = mock_stack(None, 'stack_1', 'abcd1234')
        stack.stack_status = stack_status
        self.assertEqual(self.action, stack.action)
        self.assertEqual(self.status, stack.status)

class StackIdentifierTest(testtools.TestCase):

    def test_stack_identifier(self):
        stack = mock_stack(None, 'the_stack', 'abcd1234')
        self.assertEqual('the_stack/abcd1234', stack.identifier)

class StackOperationsTest(testtools.TestCase):

    def test_delete_stack(self):
        manager = MagicMock()
        stack = mock_stack(manager, 'the_stack', 'abcd1234')
        stack.delete()
        manager.delete.assert_called_once_with('the_stack/abcd1234')

    def test_get_stack(self):
        manager = MagicMock()
        stack = mock_stack(manager, 'the_stack', 'abcd1234')
        stack.get()
        manager.get.assert_called_once_with('the_stack/abcd1234')

    def test_update_stack(self):
        manager = MagicMock()
        stack = mock_stack(manager, 'the_stack', 'abcd1234')
        stack.update()
        manager.update.assert_called_once_with('the_stack/abcd1234')

    def test_create_stack(self):
        manager = MagicMock()
        stack = mock_stack(manager, 'the_stack', 'abcd1234')
        stack = stack.create()
        manager.create.assert_called_once_with('the_stack/abcd1234')

class StackManagerNoPaginationTest(testtools.TestCase):

    scenarios = [
        ('total_0', dict(total=0)),
        ('total_1', dict(total=1)),
        ('total_9', dict(total=9)),
        ('total_10', dict(total=10)),
        ('total_11', dict(total=11)),
        ('total_19', dict(total=19)),
        ('total_20', dict(total=20)),
        ('total_21', dict(total=21)),
        ('total_49', dict(total=49)),
        ('total_50', dict(total=50)),
        ('total_51', dict(total=51)),
        ('total_95', dict(total=95)),
    ]

    # absolute limit for results returned
    limit = 50

    def mock_manager(self):
        manager = StackManager(None)
        manager._list = MagicMock()

        def mock_list(*args, **kwargs):
            def results():
                for i in range(0, self.total):
                    stack_name = 'stack_%s' % (i + 1)
                    stack_id = 'abcd1234-%s' % (i + 1)
                    yield mock_stack(manager, stack_name, stack_id)

            return list(results())

        manager._list.side_effect = mock_list
        return manager

    def test_stack_list_no_pagination(self):
        manager = self.mock_manager()
        results = list(manager.list(limit=self.limit))
        manager._list.assert_called_once_with(
            '/stacks?', 'stacks')

        last_result = min(self.limit, self.total)
        # paginate is not specified, so the total
        # results (up to the limit) is always returned
        self.assertEqual(last_result, len(results))

        if last_result > 0:
            self.assertEqual('stack_1', results[0].stack_name)
            self.assertEqual('stack_%s' % last_result, results[-1].stack_name)

    def test_stack_list_no_pagination_no_limit(self):
        manager = self.mock_manager()

        results = list(manager.list())
        manager._list.assert_called_once_with(
            '/stacks?', 'stacks')

        # paginate is not specified, so the total
        # results is always returned
        self.assertEqual(self.total, len(results))

        if self.total > 0:
            self.assertEqual('stack_1', results[0].stack_name)
            self.assertEqual('stack_%s' % self.total, results[-1].stack_name)

class StackManagerPaginationTest(testtools.TestCase):

    scenarios = [
        ('0_offset_0', dict(
            page_size=10,
            offset=0,
            total=0,
            results=((0, 0),)
        )),
        ('1_offset_0', dict(
            page_size=10,
            offset=0,
            total=1,
            results=((0, 1),)
        )),
        ('9_offset_0', dict(
            page_size=10,
            offset=0,
            total=9,
            results=((0, 9),)
        )),
        ('10_offset_0', dict(
            page_size=10,
            offset=0,
            total=10,
            results=((0, 10), (10, 10))
        )),
        ('11_offset_0', dict(
            page_size=10,
            offset=0,
            total=11,
            results=((0, 10), (10, 11))
        )),
        ('11_offset_10', dict(
            page_size=10,
            offset=10,
            total=11,
            results=((10, 11),)
        )),
        ('19_offset_10', dict(
            page_size=10,
            offset=10,
            total=19,
            results=((10, 19),)
        )),
        ('20_offset_10', dict(
            page_size=10,
            offset=10,
            total=20,
            results=((10, 20), (20, 20))
        )),
        ('21_offset_10', dict(
            page_size=10,
            offset=10,
            total=21,
            results=((10, 20), (20, 21))
        )),
        ('21_offset_0', dict(
            page_size=10,
            offset=0,
            total=21,
            results=((0, 10), (10, 20), (20, 21))
        )),
        ('21_offset_20', dict(
            page_size=10,
            offset=20,
            total=21,
            results=((20, 21),)
        )),
        ('95_offset_90', dict(
            page_size=10,
            offset=90,
            total=95,
            results=((90, 95),)
        )),
    ]

    # absolute limit for results returned
    limit = 50

    def mock_manager(self):
        manager = StackManager(None)
        manager._list = MagicMock()

        def mock_list(arg_url, arg_response_key):
            try:
                result = self.results[self.result_index]
            except IndexError:
                return
            self.result_index = self.result_index + 1

            offset = result[0]
            url = '/stacks?'
            url += 'limit=%s' % self.page_size
            if offset > 0:
                url += '&marker=abcd1234-%s' % offset
            self.assertEqual(url, arg_url)

            def results():

                for i in range(*result):
                    stack_name = 'stack_%s' % (i + 1)
                    stack_id = 'abcd1234-%s' % (i + 1)
                    yield mock_stack(manager, stack_name, stack_id)

            return list(results())

        manager._list.side_effect = mock_list
        return manager

    def test_stack_list_pagination(self):
        manager = self.mock_manager()

        list_params = {
            'page_size': self.page_size,
            'limit': self.limit
        }

        if self.offset > 0:
            marker = 'abcd1234-%s' % self.offset
            list_params['marker'] = marker

        self.result_index = 0
        results = list(manager.list(**list_params))

        # assert that the list method has been called enough times
        self.assertEqual(len(self.results), self.result_index)

        last_result = min(self.limit, self.total - self.offset)
        # one or more list calls have been recomposed into a single list
        self.assertEqual(last_result, len(results))

        if last_result > 0:
            self.assertEqual('stack_%s' % (self.offset + 1),
                             results[0].stack_name)
            self.assertEqual('stack_%s' % (self.offset + last_result),
                             results[-1].stack_name)


text:
/* sanitize.css v7.0.3 | CC0 License | github.com/csstools/sanitize.css */
*,
::before,
::after {
  background-repeat: no-repeat; /* 1 */
  -webkit-box-sizing: border-box;
          box-sizing: border-box; /* 2 */
}
::before,
::after {
  text-decoration: inherit; /* 1 */
  vertical-align: inherit; /* 2 */
}
html {
  cursor: default; /* 1 */
  font-family: system-ui, /* macOS 10.11-10.12 */ -apple-system, /* Windows 6+ */ Segoe UI, /* Android 4+ */ Roboto, /* Ubuntu 10.10+ */ Ubuntu, /* Gnome 3+ */ Cantarell, /* KDE Plasma 5+ */ Noto Sans, /* fallback */ sans-serif, /* macOS emoji */ "Apple Color Emoji", /* Windows emoji */ "Segoe UI Emoji", /* Windows emoji */ "Segoe UI Symbol", /* Linux emoji */ "Noto Color Emoji";
/* 2 */
  line-height: 1.15; /* 3 */
  -moz-tab-size: 4; /* 4 */
  -o-tab-size: 4;
     tab-size: 4; /* 4 */
  -ms-text-size-adjust: 100%; /* 5 */
  -webkit-text-size-adjust: 100%; /* 5 */
  word-break: break-word; /* 6 */
}
body {
  margin: 0;
}
h1 {
  font-size: 2em;
  margin: 0.67em 0;
}
hr {
  height: 0; /* 1 */
  overflow: visible; /* 2 */
}
main {
  display: block;
}
nav ol,
nav ul {
  list-style: none;
}
pre {
  font-family: /* macOS 10.10+ */ Menlo, /* Windows 6+ */ Consolas, /* Android 4+ */ Roboto Mono, /* Ubuntu 10.10+ */ Ubuntu Monospace, /* KDE Plasma 5+ */ Noto Mono, /* KDE Plasma 4+ */ Oxygen Mono, /* Linux/OpenOffice fallback */ Liberation Mono, /* fallback */ monospace;
/* 1 */
  font-size: 1em; /* 2 */
}
a {
  background-color: transparent;
}
abbr[title] {
  text-decoration: underline;
  -webkit-text-decoration: underline dotted;
          text-decoration: underline dotted;
}
b,
strong {
  font-weight: bolder;
}
code,
kbd,
samp {
  font-family: /* macOS 10.10+ */ Menlo, /* Windows 6+ */ Consolas, /* Android 4+ */ Roboto Mono, /* Ubuntu 10.10+ */ Ubuntu Monospace, /* KDE Plasma 5+ */ Noto Mono, /* KDE Plasma 4+ */ Oxygen Mono, /* Linux/OpenOffice fallback */ Liberation Mono, /* fallback */ monospace;
/* 1 */
  font-size: 1em; /* 2 */
}
small {
  font-size: 80%;
}
::-moz-selection {
  background-color: #b3d4fc; /* 1 */
  color: #000; /* 1 */
  text-shadow: none;
}
::selection {
  background-color: #b3d4fc; /* 1 */
  color: #000; /* 1 */
  text-shadow: none;
}
audio,
canvas,
iframe,
img,
svg,
video {
  vertical-align: middle;
}
audio,
video {
  display: inline-block;
}
audio:not([controls]) {
  display: none;
  height: 0;
}
img {
  border-style: none;
}
svg:not([fill]) {
  fill: currentColor;
}
svg:not(:root) {
  overflow: hidden;
}
table {
  border-collapse: collapse;
}
button,
input,
select,
textarea {
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
}
button,
input,
select {
  margin: 0;
}
button {
  overflow: visible; /* 1 */
  text-transform: none; /* 2 */
}
button,
[type="button"],
[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
}
fieldset {
  padding: 0.35em 0.75em 0.625em;
}
input {
  overflow: visible;
}
legend {
  color: inherit; /* 2 */
  display: table; /* 1 */
  max-width: 100%; /* 1 */
  white-space: normal; /* 1 */
}
progress {
  display: inline-block; /* 1 */
  vertical-align: baseline; /* 2 */
}
select {
  text-transform: none;
}
textarea {
  margin: 0; /* 1 */
  overflow: auto; /* 2 */
  resize: vertical; /* 3 */
}
[type="checkbox"],
[type="radio"] {
  padding: 0;
}
[type="search"] {
  -webkit-appearance: textfield; /* 1 */
  outline-offset: -2px; /* 2 */
}
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
  height: auto;
}
::-webkit-input-placeholder {
  color: inherit;
  opacity: 0.54;
}
::-webkit-search-decoration {
  -webkit-appearance: none;
}
::-webkit-file-upload-button {
  -webkit-appearance: button; /* 1 */
  font: inherit; /* 2 */
}
::-moz-focus-inner {
  border-style: none;
  padding: 0;
}
:-moz-focusring {
  outline: 1px dotted ButtonText;
}
details {
  display: block;
}
dialog {
  background-color: #fff;
  border: solid;
  color: #000;
  display: block;
  height: -moz-fit-content;
  height: -webkit-fit-content;
  height: fit-content;
  left: 0;
  margin: auto;
  padding: 1em;
  position: absolute;
  right: 0;
  width: -moz-fit-content;
  width: -webkit-fit-content;
  width: fit-content;
}
dialog:not([open]) {
  display: none;
}
summary {
  display: list-item;
}
canvas {
  display: inline-block;
}
template {
  display: none;
}
a,
area,
button,
input,
label,
select,
summary,
textarea,
[tabindex] {
  -ms-touch-action: manipulation; /* 1 */
  touch-action: manipulation; /* 2 */
}
[hidden] {
  display: none;
}
[aria-busy="true"] {
  cursor: progress;
}
[aria-controls] {
  cursor: pointer;
}
[aria-disabled="true"],
[disabled] {
  cursor: not-allowed;
}
[aria-hidden="false"][hidden]:not(:focus) {
  clip: rect(0, 0, 0, 0);
  display: inherit;
  position: absolute;
}
/*! Marx v3.0.6 - The classless CSS reset (perfect for Communists) | MIT License | https://github.com/mblode/marx */
main,
header,
footer,
article,
section,
aside,
details,
summary {
  margin: 0 auto;
  margin-bottom: 16px;
  width: 100%;
}
main {
  display: block;
  margin: 0 auto;
  max-width: 768px;
  padding: 0 16px 16px;
}
footer {
  border-top: 1px solid rgba(0,0,0,0.12);
  padding: 16px 0;
  text-align: center;
}
footer p {
  margin-bottom: 0;
}
hr {
  border: 0;
  border-top: 1px solid rgba(0,0,0,0.12);
  display: block;
  margin-top: 16px;
  margin-bottom: 16px;
  width: 100%;
  -webkit-box-sizing: content-box;
          box-sizing: content-box;
  height: 0;
  overflow: visible;
}
img {
  height: auto;
  max-width: 100%;
  vertical-align: baseline;
}
@media screen and (max-width: 400px) {
  article,
  section,
  aside {
    clear: both;
    display: block;
    max-width: 100%;
  }
  img {
    margin-right: 16px;
  }
}
embed,
iframe,
video {
  border: 0;
}
body {
  color: rgba(0,0,0,0.8);
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  font-size: 16px;
  line-height: 1.5;
}
p {
  margin: 0;
  margin-bottom: 16px;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  color: inherit;
  font-family: inherit;
  line-height: 1.2;
  font-weight: 500;
}
h1 {
  font-size: 40px;
  margin: 20px 0 16px;
}
h2 {
  font-size: 32px;
  margin: 20px 0 16px;
}
h3 {
  font-size: 28px;
  margin: 16px 0 4px;
}
h4 {
  font-size: 24px;
  margin: 16px 0 4px;
}
h5 {
  font-size: 20px;
  margin: 16px 0 4px;
}
h6 {
  font-size: 16px;
  margin: 16px 0 4px;
}
small {
  color: rgba(0,0,0,0.54);
  vertical-align: bottom;
}
pre {
  background: #f7f7f9;
  color: rgba(0,0,0,0.8);
  display: block;
  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
  font-size: 16px;
  margin: 16px 0;
  padding: 16px;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}
code {
  color: rgba(0,0,0,0.8);
  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
  font-size: 16px;
  line-height: inherit;
  margin: 0;
  padding: 0;
  vertical-align: baseline;
  word-break: break-all;
  word-wrap: break-word;
}
a {
  color: #007bff;
  text-decoration: none;
  background-color: transparent;
}
a:hover,
a:focus {
  color: #006fe6;
  text-decoration: underline;
}
dl {
  margin-bottom: 16px;
}
dd {
  margin-left: 40px;
}
ul,
ol {
  margin-bottom: 8px;
  padding-left: 40px;
  vertical-align: baseline;
}
blockquote {
  border-left: 2px solid rgba(0,0,0,0.8);
  font-family: Georgia, Times, "Times New Roman", serif;
  font-style: italic;
  margin: 16px 0;
  padding-left: 16px;
}
figcaption {
  font-family: Georgia, Times, "Times New Roman", serif;
}
u {
  text-decoration: underline;
}
s {
  text-decoration: line-through;
}
sup {
  font-size: 14px;
  vertical-align: super;
}
sub {
  font-size: 14px;
  vertical-align: sub;
}
mark {
  background: #ffeb3b;
}
input[type="text"],
input[type="password"],
input[type="email"],
input[type="url"],
input[type="date"],
input[type="month"],
input[type="time"],
input[type="datetime"],
input[type="datetime-local"],
input[type="week"],
input[type="number"],
input[type="search"],
input[type="tel"],
select,
textarea {
  background: #fff;
  background-clip: padding-box;
  border: 1px solid rgba(0,0,0,0.12);
  border-radius: 4px;
  color: rgba(0,0,0,0.8);
  display: block;
  width: 100%;
  padding: 8px 16px;
  line-height: 1.5;
  -webkit-transition: border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
input[type="color"] {
  background: #fff;
  border: 1px solid rgba(0,0,0,0.12);
  border-radius: 4px;
  display: inline-block;
  vertical-align: middle;
}
input:not([type]) {
  -webkit-appearance: none;
  background: #fff;
  background-clip: padding-box;
  border: 1px solid rgba(0,0,0,0.12);
  border-radius: 4px;
  color: rgba(0,0,0,0.8);
  display: block;
  width: 100%;
  padding: 8px 16px;
  line-height: 1.5;
  -webkit-transition: border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  text-align: left;
}
input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="date"]:focus,
input[type="month"]:focus,
input[type="time"]:focus,
input[type="datetime"]:focus,
input[type="datetime-local"]:focus,
input[type="week"]:focus,
input[type="number"]:focus,
input[type="search"]:focus,
input[type="tel"]:focus,
input[type="color"]:focus,
select:focus,
textarea:focus {
  background-color: #fff;
  border-color: #7fbdff;
  outline: 0;
  -webkit-box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
          box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
}
input:not([type]):focus {
  background-color: #fff;
  border-color: #7fbdff;
  outline: 0;
  -webkit-box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
          box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
  outline: 1px thin rgba(0,0,0,0.12);
}
input[type="text"][disabled],
input[type="password"][disabled],
input[type="email"][disabled],
input[type="url"][disabled],
input[type="date"][disabled],
input[type="month"][disabled],
input[type="time"][disabled],
input[type="datetime"][disabled],
input[type="datetime-local"][disabled],
input[type="week"][disabled],
input[type="number"][disabled],
input[type="search"][disabled],
input[type="tel"][disabled],
input[type="color"][disabled],
select[disabled],
textarea[disabled] {
  background-color: rgba(0,0,0,0.12);
  color: rgba(0,0,0,0.54);
  cursor: not-allowed;
  opacity: 1;
}
input:not([type])[disabled] {
  background-color: rgba(0,0,0,0.12);
  color: rgba(0,0,0,0.54);
  cursor: not-allowed;
  opacity: 1;
}
input[readonly],
select[readonly],
textarea[readonly] {
  border-color: rgba(0,0,0,0.12);
  color: rgba(0,0,0,0.54);
}
input:focus:invalid,
textarea:focus:invalid,
select:focus:invalid {
  border-color: #ea1c0d;
  color: #f44336;
}
input[type="file"]:focus:invalid:focus,
input[type="radio"]:focus:invalid:focus,
input[type="checkbox"]:focus:invalid:focus {
  outline-color: #f44336;
}
select {
  border: 1px solid rgba(0,0,0,0.12);
  vertical-align: sub;
}
select:not([size]):not([multiple]) {
  height: -webkit-calc(2.25rem + 2px);
  height: calc(2.25rem + 2px);
}
select[multiple] {
  height: auto;
}
label {
  display: inline-block;
  line-height: 2;
}
fieldset {
  border: 0;
  margin: 0;
  padding: 8px 0;
}
legend {
  border-bottom: 1px solid rgba(0,0,0,0.12);
  color: rgba(0,0,0,0.8);
  display: block;
  margin-bottom: 8px;
  padding: 8px 0;
  width: 100%;
}
textarea {
  overflow: auto;
  resize: vertical;
}
input[type=checkbox],
input[type=radio] {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
  padding: 0;
  display: inline;
}
input[type=submit],
input[type=reset],
input[type=button],
button {
  background-color: #007bff;
  border: #007bff;
  border-radius: 4px;
  color: #fff;
  padding: 8px 16px;
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  border: 1px solid transparent;
  font-size: 1rem;
  line-height: 1.5;
  -webkit-transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;
}
input[type=submit]::-moz-focus-inner,
input[type=reset]::-moz-focus-inner,
input[type=button]::-moz-focus-inner,
button::-moz-focus-inner {
  padding: 0;
}
input[type=submit]:hover,
input[type=reset]:hover,
input[type=button]:hover,
button:hover {
  background-color: #0069d9;
  border-color: #0062cc;
  color: #fff;
}
input[type=submit]:active,
input[type=reset]:active,
input[type=button]:active,
button:active {
  background-color: #0062cc;
  border-color: #005cbf;
  color: #fff;
}
input[type=submit]:focus,
input[type=reset]:focus,
input[type=button]:focus,
button:focus {
  outline: 0;
  -webkit-box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.5);
          box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.5);
}
input[type=submit]:disabled,
input[type=reset]:disabled,
input[type=button]:disabled,
button:disabled {
  opacity: 0.65;
  cursor: not-allowed;
  background-color: #007bff;
  border-color: #007bff;
  color: #fff;
}
table {
  border-top: 1px solid rgba(0,0,0,0.12);
  margin-bottom: 16px;
}
caption {
  padding: 8px 0;
}
thead th {
  border: 0;
  border-bottom: 2px solid rgba(0,0,0,0.12);
  text-align: left;
}
tr {
  margin-bottom: 8px;
}
th,
td {
  border-bottom: 1px solid rgba(0,0,0,0.12);
  padding: 16px;
  vertical-align: inherit;
}
tfoot tr {
  text-align: left;
}
tfoot td {
  color: rgba(0,0,0,0.54);
  font-size: 8px;
  font-style: italic;
  padding: 16px 4px;
}


text:
$('.favBar').on('click', '.bookmark', function() {
  var markUrl = $(this).attr('mark-url');
  var index = $.map(bTabs.tabs, function(obj, index) {
      if(obj.id == curTab) {
          return index;
      }
  })[0]
  bTabs.tabs[index].url = markUrl;
});

$('.search-right').on('click', '#bookmarkBtn', function(event) {
  $('#bookmarkName').val($('#' + curTab)[0].getTitle());
  $('.bookmarkInf').show();
});

$('#bookmarkSaveBtn').click(function (event) {
  $('.bookmarkInf').hide();
  var name = $('#bookmarkName').val();
  console.log("book");
  console.log(name);
  saveBookmark({ name: name, url: getUrlById(curTab)});
});

$('#bookmarkDeleteBtn').click(function (event) {
  $('.bookmarkInf').hide();
});

function saveBookmark(bookmark) {
  bookmarksData.bookmarks.push(bookmark);
  storage.get('bookmarks', function(error, data) {
    if (data[0].name) {
      data.push(bookmark);
      storage.set('bookmarks', data, function(error) {
        if (error) throw error;

      });
    }
    else {
      storage.set('bookmarks', [bookmark], function(error) {
        if (error) throw error;

      });
    }

  });
}

function initBookmarks() {
  storage.get('bookmarks', function(error, data) {
    if (data[0].name) {
      bookmarksData.bookmarks = data;
    }
  });
}
initBookmarks();


text:
<?php

namespace backend\grid\columns;

use yii\base\Model;
use yii\grid\DataColumn;
use yii\jui\DatePicker;

class DataDateColumn extends DataColumn
{
    public $dateFormat = 'yyyy-MM-dd';
    public $language = 'zh-cn';

    protected function renderFilterCellContent()
    {
        if (is_string($this->filter)) {
            return $this->filter;
        }

        $model = $this->grid->filterModel;

        if ($this->filter !== false && $model instanceof Model && $this->attribute !== null && $model->isAttributeActive($this->attribute)) {
            if ($model->hasErrors($this->attribute)) {
                Html::addCssClass($this->filterOptions, 'has-error');
                $error = ' ' . Html::error($model, $this->attribute, $this->grid->filterErrorOptions);
            } else {
                $error = '';
            }

            return DatePicker::widget([
                'model' => $model,
                'attribute' => $this->attribute,
                'dateFormat' => $this->dateFormat,
                'language' => $this->language,
                'options' => $this->filterInputOptions
            ]) . $error;

        } else {
            return parent::renderFilterCellContent();
        }
    }
}


text:
<?php

$data = [
    'blog_title'   => 'My Blog Title',
    'blog_heading' => 'My Blog Heading',
];

return $parser->setData($data)->render('blog_template');


text:
/**
* Given a rope with length n, how to cut the rope into m parts with length n[0], n[1], ..., n[m-1], in order to get
* the maximal product of n[0]*n[1]* ... *n[m-1]? We have to cut once at least.
* Additionally, the length of the whole length of the rope, as well as the length of each part, are in integer value.

* For example, if the length of the rope is 8, the maximal product of the part lengths is 18. In order to get the
* maximal product, the rope is cut into three parts with lengths 2, 3, and 3 respectively
*/

// Solution 1: DP: O(N^2) space O(N)
 public static int maxProductAfterCutting_solution1(int length) {
    if(length < 2) {
        return 0;
    }
    if(length == 2) {
        return 1;
    }
    if(length == 3) {
        return 2;
    }

    int[] products = new int[length + 1];
    products[0] = 0;
    products[1] = 1;
    products[2] = 2;
    products[3] = 3;

    for(int i = 4; i <= length; ++i) {
        int max = 0;
        for(int j = 1; j <= i / 2; ++j) {
            int product = products[j] * products[i - j];
            if(max < product) {
                max = product;
            }
            products[i] = max;
        }
    }

    return products[length];
}

// Solution 2: O(1), space O(1)
 public static int maxProductAfterCutting_solution2(int length) {
    if(length < 2) {
        return 0;
    }
    if(length == 2) {
        return 1;
    }
    if(length == 3) {
        return 2;
    }

    int timesOf3 = length / 3;
    if((length - timesOf3 * 3) % 2 == 1) {
        timesOf3 -= 1;
    }

    int timesOf2 = (length - timesOf3 * 3) / 2;

    return (int)(Math.pow(3, timesOf3)) * (int)(Math.pow(2, timesOf2));
}


text:
@import "./date-picker/date-table.css";
@import "./date-picker/month-table.css";
@import "./date-picker/year-table.css";
@import "./date-picker/time-spinner.css";
@import "./date-picker/picker.css";
@import "./date-picker/date-picker.css";
@import "./date-picker/date-range-picker.css";
@import "./date-picker/time-range-picker.css";


text:
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Uncas.EBS.UI.Controls
{
    /// <summary>
    /// Represents a number box.
    /// </summary>
    [ValidationProperty("Text")]
    [ToolboxData("<{0}:NumberBox runat=server></{0}:NumberBox>")]
    public class NumberBox : CompositeControl, ITextControl
    {
        private TextBox numberTextBox;

        private RegularExpressionValidator revNumber;

        /// <summary>
        /// Gets or sets a value indicating whether [auto post back].
        /// </summary>
        /// <value><c>True</c> if [auto post back]; otherwise, <c>false</c>.</value>
        public bool AutoPostBack
        {
            get
            {
                EnsureChildControls();
                return numberTextBox.AutoPostBack;
            }

            set
            {
                EnsureChildControls();
                numberTextBox.AutoPostBack = value;
            }
        }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            numberTextBox = new TextBox();
            numberTextBox.ID = "tbNumber";

            revNumber = new RegularExpressionValidator();
            revNumber.ControlToValidate = numberTextBox.ID;
            revNumber.Text = "?";
            revNumber.ToolTip = "Indtast et gyldigt tal";

            SetValidationExpression();

            this.Controls.Add(numberTextBox);

            base.CreateChildControls();
        }

        #region Properties

        private int maxValue = int.MaxValue;

        /// <summary>
        /// Gets or sets the max value.
        /// </summary>
        /// <value>The max value.</value>
        public int MaxValue
        {
            get
            {
                EnsureChildControls();
                return maxValue;
            }

            set
            {
                EnsureChildControls();
                maxValue = value;
            }
        }

        private int minValue = int.MinValue;

        /// <summary>
        /// Gets or sets the min value.
        /// </summary>
        /// <value>The min value.</value>
        public int MinValue
        {
            get
            {
                EnsureChildControls();
                return minValue;
            }

            set
            {
                EnsureChildControls();
                minValue = value;
            }
        }

        private int numberOfDigits = 9;

        /// <summary>
        /// Gets or sets the number of digits.
        /// </summary>
        /// <value>The number of digits.</value>
        public int NumberOfDigits
        {
            get
            {
                EnsureChildControls();
                return numberOfDigits;
            }

            set
            {
                EnsureChildControls();
                numberOfDigits = value;
                SetValidationExpression();
            }
        }

        /// <summary>
        /// Gets or sets the text content of a control.
        /// </summary>
        /// <value>Text content of a control.</value>
        /// <returns>
        /// The text content of a control.
        /// </returns>
        public string Text
        {
            get
            {
                EnsureChildControls();
                if (Number.HasValue)
                {
                    return numberTextBox.Text;
                }
                else
                {
                    return string.Empty;
                }
            }

            set
            {
                EnsureChildControls();
                numberTextBox.Text = value;
            }
        }

        /// <summary>
        /// Gets or sets the number.
        /// </summary>
        /// <value>The number.</value>
        public int? Number
        {
            get
            {
                EnsureChildControls();
                int result = 0;
                if (!int.TryParse(numberTextBox.Text, out result))
                {
                    return null;
                }

                if (result > maxValue)
                {
                    return maxValue;
                }

                if (result < minValue)
                {
                    return minValue;
                }

                return result;
            }

            set
            {
                EnsureChildControls();
                if (!value.HasValue)
                {
                    numberTextBox.Text = string.Empty;
                    return;
                }

                if (value.Value > maxValue)
                {
                    numberTextBox.Text
                        = maxValue.ToString
                        (CultureInfo.CurrentCulture);
                }
                else if (value.Value < minValue)
                {
                    numberTextBox.Text
                        = minValue.ToString
                        (CultureInfo.CurrentCulture);
                }
                else
                {
                    numberTextBox.Text
                        = value.Value.ToString
                        (CultureInfo.CurrentCulture);
                }
            }
        }

        #endregion

        #region Private methods

        private void SetValidationExpression()
        {
            // Default: "\d{1,9}"
            revNumber.ValidationExpression = @"\d{1," + numberOfDigits + "}";
            SetWidth();
        }

        private void SetWidth()
        {
            numberTextBox.Width = new Unit((numberOfDigits + 1) * 7);
        }

        #endregion
    }
}


text:
namespace Data_Access_Layer
{
    using System;
    using System.Collections.Generic;

    public partial class ExceptionLog
    {
        public System.DateTime ExceptionDate { get; set; }
        public string ExceptionType { get; set; }
        public string ExceptionMessage { get; set; }
        public string ExceptionStackTrace { get; set; }
        public string Username { get; set; }
        public int Id { get; set; }
        public string SystemLog { get; set; }
        public string CustomMessage { get; set; }
    }
}