text:
/**
 * @file mTecs.cpp
 *
 * @author Thomas Gubler <thomasgubler@gmail.com>
 */

#include "mTecs.h"

#include <lib/geo/geo.h>
#include <stdio.h>

namespace fwPosctrl {

mTecs::mTecs() :
	SuperBlock(NULL, "MT"),
	/* Parameters */
	_mTecsEnabled(this, "ENABLED"),
	_airspeedMin(this, "FW_AIRSPD_MIN", false),
	/* Publications */
	_status(ORB_ID(tecs_status), &getPublications()),
	/* control blocks */
	_controlTotalEnergy(this, "THR"),
	_controlEnergyDistribution(this, "PIT", true),
	_controlAltitude(this, "FPA", true),
	_controlAirSpeed(this, "ACC"),
	_flightPathAngleLowpass(this, "FPA_LP"),
	_altitudeLowpass(this, "ALT_LP"),
	_airspeedLowpass(this, "A_LP"),
	_airspeedDerivative(this, "AD"),
	_throttleSp(0.0f),
	_pitchSp(0.0f),
	_BlockOutputLimiterTakeoffThrottle(this, "TKF_THR"),
	_BlockOutputLimiterTakeoffPitch(this, "TKF_PIT", true),
	_BlockOutputLimiterUnderspeedThrottle(this, "USP_THR"),
	_BlockOutputLimiterUnderspeedPitch(this, "USP_PIT", true),
	_BlockOutputLimiterLandThrottle(this, "LND_THR"),
	_BlockOutputLimiterLandPitch(this, "LND_PIT", true),
	timestampLastIteration(hrt_absolute_time()),
	_firstIterationAfterReset(true),
	_dtCalculated(false),
	_counter(0),
	_debug(false)
{
}

mTecs::~mTecs()
{
}

int mTecs::updateAltitudeSpeed(float flightPathAngle, float altitude, float altitudeSp, float airspeed,
		float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
	/* check if all input arguments are numbers and abort if not so */
	if (!isfinite(flightPathAngle) || !isfinite(altitude) ||
			!isfinite(altitudeSp) || !isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
		return -1;
	}

	/* time measurement */
	updateTimeMeasurement();

	/* Filter altitude */
	float altitudeFiltered = _altitudeLowpass.update(altitude);

	/* calculate flight path angle setpoint from altitude setpoint */
	float flightPathAngleSp = _controlAltitude.update(altitudeSp - altitudeFiltered);

	/* Debug output */
	if (_counter % 10 == 0) {
		debug("***");
		debug("updateAltitudeSpeed: altitudeSp %.4f, altitude %.4f, altitude filtered %.4f, flightPathAngleSp %.4f", (double)altitudeSp, (double)altitude, (double)altitudeFiltered, (double)flightPathAngleSp);
	}

	/* Write part of the status message */
	_status.altitudeSp = altitudeSp;
	_status.altitude_filtered = altitudeFiltered;

	/* use flightpath angle setpoint for total energy control */
	return updateFlightPathAngleSpeed(flightPathAngle, flightPathAngleSp, airspeed,
			airspeedSp, mode, limitOverride);
}

int mTecs::updateFlightPathAngleSpeed(float flightPathAngle, float flightPathAngleSp, float airspeed,
		float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
	/* check if all input arguments are numbers and abort if not so */
	if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
			!isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
		return -1;
	}

	/* time measurement */
	updateTimeMeasurement();

	/* Filter airspeed */
	float airspeedFiltered = _airspeedLowpass.update(airspeed);

	/* calculate longitudinal acceleration setpoint from airspeed setpoint*/
	float accelerationLongitudinalSp = _controlAirSpeed.update(airspeedSp - airspeedFiltered);

	/* Debug output */
	if (_counter % 10 == 0) {
		debug("updateFlightPathAngleSpeed airspeedSp %.4f, airspeed %.4f airspeedFiltered %.4f,"
				"accelerationLongitudinalSp%.4f",
				(double)airspeedSp, (double)airspeed,
				(double)airspeedFiltered, (double)accelerationLongitudinalSp);
	}

	/* Write part of the status message */
	_status.airspeedSp = airspeedSp;
	_status.airspeed_filtered = airspeedFiltered;

	/* use longitudinal acceleration setpoint for total energy control */
	return updateFlightPathAngleAcceleration(flightPathAngle, flightPathAngleSp, airspeedFiltered,
			accelerationLongitudinalSp, mode, limitOverride);
}

int mTecs::updateFlightPathAngleAcceleration(float flightPathAngle, float flightPathAngleSp, float airspeedFiltered,
		float accelerationLongitudinalSp, tecs_mode mode, LimitOverride limitOverride)
{
	/* check if all input arguments are numbers and abort if not so */
	if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
			!isfinite(airspeedFiltered) || !isfinite(accelerationLongitudinalSp) || !isfinite(mode)) {
		return -1;
	}
	/* time measurement */
	updateTimeMeasurement();

	/* update parameters first */
	updateParams();

	/* Filter flightpathangle */
	float flightPathAngleFiltered = _flightPathAngleLowpass.update(flightPathAngle);

	/* calculate values (energies) */
	float flightPathAngleError = flightPathAngleSp - flightPathAngleFiltered;
	float airspeedDerivative = 0.0f;
	if(_airspeedDerivative.getDt() > 0.0f) {
		airspeedDerivative = _airspeedDerivative.update(airspeedFiltered);
	}
	float airspeedDerivativeNorm = airspeedDerivative / CONSTANTS_ONE_G;
	float airspeedDerivativeSp = accelerationLongitudinalSp;
	float airspeedDerivativeNormSp = airspeedDerivativeSp / CONSTANTS_ONE_G;
	float airspeedDerivativeNormError = airspeedDerivativeNormSp - airspeedDerivativeNorm;

	float totalEnergyRate = flightPathAngleFiltered + airspeedDerivativeNorm;
	float totalEnergyRateError = flightPathAngleError + airspeedDerivativeNormError;
	float totalEnergyRateSp = flightPathAngleSp + airspeedDerivativeNormSp;
	float totalEnergyRateError2 = totalEnergyRateSp - totalEnergyRate;

	float energyDistributionRate = flightPathAngleFiltered - airspeedDerivativeNorm;
	float energyDistributionRateError = flightPathAngleError - airspeedDerivativeNormError;
	float energyDistributionRateSp = flightPathAngleSp - airspeedDerivativeNormSp;
	float energyDistributionRateError2 = energyDistributionRateSp - energyDistributionRate;

	/* Debug output */
	if (_counter % 10 == 0) {
		debug("totalEnergyRateSp %.2f, totalEnergyRate %.2f, totalEnergyRateError %.2f totalEnergyRateError2 %.2f airspeedDerivativeNorm %.4f",
				(double)totalEnergyRateSp, (double)totalEnergyRate, (double)totalEnergyRateError, (double)totalEnergyRateError2, (double)airspeedDerivativeNorm);
		debug("energyDistributionRateSp %.2f, energyDistributionRate %.2f, energyDistributionRateError %.2f energyDistributionRateError2 %.2f",
				(double)energyDistributionRateSp, (double)energyDistributionRate, (double)energyDistributionRateError, (double)energyDistributionRateError2);
	}

	/* Check airspeed: if below safe value switch to underspeed mode (if not in land or takeoff mode) */
	if (mode != TECS_MODE_LAND && mode != TECS_MODE_TAKEOFF && airspeedFiltered < _airspeedMin.get()) {
		mode = TECS_MODE_UNDERSPEED;
	}

	/* Set special ouput limiters if we are not in TECS_MODE_NORMAL */
	BlockOutputLimiter *outputLimiterThrottle = &_controlTotalEnergy.getOutputLimiter();
	BlockOutputLimiter *outputLimiterPitch = &_controlEnergyDistribution.getOutputLimiter();
	if (mode == TECS_MODE_TAKEOFF) {
		outputLimiterThrottle = &_BlockOutputLimiterTakeoffThrottle;
		outputLimiterPitch = &_BlockOutputLimiterTakeoffPitch;
	} else if (mode == TECS_MODE_LAND) {
		// only limit pitch but do not limit throttle
		outputLimiterPitch = &_BlockOutputLimiterLandPitch;
	} else if (mode == TECS_MODE_LAND_THROTTLELIM) {
		outputLimiterThrottle = &_BlockOutputLimiterLandThrottle;
		outputLimiterPitch = &_BlockOutputLimiterLandPitch;
	} else if (mode == TECS_MODE_UNDERSPEED) {
		outputLimiterThrottle = &_BlockOutputLimiterUnderspeedThrottle;
		outputLimiterPitch = &_BlockOutputLimiterUnderspeedPitch;
	}

	/* Apply overrride given by the limitOverride argument (this is used for limits which are not given by
	 * parameters such as pitch limits with takeoff waypoints or throttle limits when the launchdetector
	 * is running) */
	limitOverride.applyOverride(*outputLimiterThrottle, *outputLimiterPitch);

	/* Write part of the status message */
	_status.flightPathAngleSp = flightPathAngleSp;
	_status.flightPathAngle = flightPathAngle;
	_status.flightPathAngleFiltered = flightPathAngleFiltered;
	_status.airspeedDerivativeSp = airspeedDerivativeSp;
	_status.airspeedDerivative = airspeedDerivative;
	_status.totalEnergyRateSp = totalEnergyRateSp;
	_status.totalEnergyRate = totalEnergyRate;
	_status.energyDistributionRateSp = energyDistributionRateSp;
	_status.energyDistributionRate = energyDistributionRate;
	_status.mode = mode;

	/** update control blocks **/
	/* update total energy rate control block */
	_throttleSp = _controlTotalEnergy.update(totalEnergyRateSp, totalEnergyRateError, outputLimiterThrottle);

	/* update energy distribution rate control block */
	_pitchSp = _controlEnergyDistribution.update(energyDistributionRateSp, energyDistributionRateError, outputLimiterPitch);

	if (_counter % 10 == 0) {
		debug("_throttleSp %.1f, _pitchSp %.1f, flightPathAngleSp %.1f, flightPathAngle %.1f accelerationLongitudinalSp %.1f, airspeedDerivative %.1f",
				(double)_throttleSp, (double)_pitchSp,
				(double)flightPathAngleSp, (double)flightPathAngle,
				(double)accelerationLongitudinalSp, (double)airspeedDerivative);
	}

	/* publish status messge */
	_status.update();

	/* clean up */
	_firstIterationAfterReset = false;
	_dtCalculated = false;

	_counter++;

	return 0;
}

void mTecs::resetIntegrators()
{
	_controlTotalEnergy.getIntegral().setY(0.0f);
	_controlEnergyDistribution.getIntegral().setY(0.0f);
	timestampLastIteration = hrt_absolute_time();
	_firstIterationAfterReset = true;
}

void mTecs::resetDerivatives(float airspeed)
{
	_airspeedDerivative.setU(airspeed);
}

void mTecs::updateTimeMeasurement()
{
	if (!_dtCalculated) {
		float deltaTSeconds = 0.0f;
		if (!_firstIterationAfterReset) {
			hrt_abstime timestampNow = hrt_absolute_time();
			deltaTSeconds = (float)(timestampNow - timestampLastIteration) * 1e-6f;
			timestampLastIteration = timestampNow;
		}
		setDt(deltaTSeconds);

		_dtCalculated = true;
	}
}

void mTecs::debug_print(const char *fmt, va_list args)
{
	fprintf(stderr, "%s: ", "[mtecs]");
	vfprintf(stderr, fmt, args);

	fprintf(stderr, "\n");
}

void mTecs::debug(const char *fmt, ...) {

	if (!_debug) {
		return;
	}

	va_list args;

	va_start(args, fmt);
	debug_print(fmt, args);
}

} /* namespace fwPosctrl */


text:
// <copyright file="BingMainPageElementMap.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>https://automatetheplanet.com/</site>

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace TestProjectFacadeDesignPattern.Pages
{
    public partial class MainPageElements : WebElements
    {
        public MainPageElements(IWebDriver driver)
            : base(driver)
        {
        }

        public IWebElement GetSearchBox()
        {
            return Driver.FindElement(By.Id("sb_form_q"));
        }

        public IWebElement GetGoButton()
        {
            return WaitToBeClickable(By.XPath("//input[@id='sb_form_go']"));
        }

        public IWebElement GetResultsCountDiv()
        {
            return Driver.FindElement(By.Id("b_tween"));
        }

        public IWebElement GetImagesLink()
        {
            return Driver.FindElement(By.XPath("//a[text()='Images']"));
        }

        public SelectElement GetSizesSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'Size']")));
        }

        public SelectElement GetColorSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'Color']")));
        }

        public SelectElement GetTypeSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'Type']")));
        }

        public SelectElement GetLayoutSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'Layout']")));
        }

        public SelectElement GetPeopleSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'People']")));
        }

        public SelectElement GetDateSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'Date']")));
        }

        public SelectElement GetLicenseSelect()
        {
            return new SelectElement(Driver.FindElement(By.XPath("//div/ul/li/span/span[text() = 'License']")));
        }

        public IWebElement GetImageResult(int num)
        {
            return Driver.FindElement(By.LinkText($"//li[@data-idx='{num}']"));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Pages
  class UserProfile < SitePrism::Page
    set_url '/register'
    set_url_matcher /\/register$/

    element :heading, 'h1'
  end
end


text:
#include <string>

#include "H5Include.h"
#include "H5Exception.h"
#include "H5IdComponent.h"
#include "H5PropList.h"
#include "H5Object.h"
#include "H5AbstractDs.h"
#include "H5DxferProp.h"
#include "H5DataSpace.h"
#include "H5DcreatProp.h"
#include "H5CommonFG.h"
#include "H5DataType.h"
#include "H5DataSet.h"
#include "H5AtomType.h"
#include "H5IntType.h"
#include "H5EnumType.h"
#include "H5private.h"			// for HDmemset

#ifndef H5_NO_NAMESPACE
namespace H5 {
#endif

//--------------------------------------------------------------------------
// Function:	EnumType default constructor
///\brief	Default constructor: Creates a stub datatype
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType() : DataType() {}

//--------------------------------------------------------------------------
// Function:	EnumType overloaded constructor
///\brief	Creates an EnumType object using the id of an existing datatype.
///\param	existing_id - IN: Id of an existing datatype
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const hid_t existing_id ) : DataType( existing_id ) {}

//--------------------------------------------------------------------------
// Function:	EnumType copy constructor
///\brief	Copy constructor: makes a copy of the original EnumType object.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const EnumType& original ) : DataType( original ) {}

//--------------------------------------------------------------------------
// Function:	EnumType overloaded constructor
///\brief	Creates an empty enumeration datatype given a size, in bytes.
///\param	size - IN: Number of bytes in the datatype to create
///\exception	H5::DataTypeIException
// Description
// 		The DataType constructor calls the C API H5Tcreate to create
// 		the enum datatype.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( size_t size ) : DataType( H5T_ENUM, size ) {}

//--------------------------------------------------------------------------
// Function:	EnumType overloaded constructor
///\brief	Gets the enum datatype of the specified dataset.
///\param	dataset - IN: Dataset that this enum datatype associates with
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const DataSet& dataset ) : DataType()
{
   // Calls C function H5Dget_type to get the id of the datatype
   id = H5Dget_type( dataset.getId() );

   // If the datatype id is not valid, throw an exception
   if( id < 0 )
   {
      throw DataSetIException("EnumType constructor", "H5Dget_type failed");
   }
}

//--------------------------------------------------------------------------
// Function:	EnumType overloaded constructor
///\brief	Creates a new enum datatype based on an integer datatype.
///\param	data_type - IN: Base datatype
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::EnumType( const IntType& data_type ) : DataType()
{
   // Calls C function H5Tenum_create to get the id of the datatype
   id = H5Tenum_create( data_type.getId() );

   // If the datatype id is not valid, throw an exception
   if( id < 0 )
   {
      throw DataSetIException("EnumType constructor", "H5Tenum_create failed");
   }
}

//--------------------------------------------------------------------------
// Function:	EnumType::insert
///\brief	Inserts a new member to this enumeration datatype.
///\param	name  - IN: Name of the new member
///\param	value - IN: Pointer to the value of the new member
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::insert( const char* name, void *value ) const
{
   // Calls C routine H5Tenum_insert to insert the new enum datatype member.
   herr_t ret_value = H5Tenum_insert( id, name, value );
   if( ret_value < 0 )
   {
      throw DataTypeIException("EnumType::insert", "H5Tenum_insert failed");
   }
}

//--------------------------------------------------------------------------
// Function:	EnumType::insert
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function only in the type of
///		argument \a name.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::insert( const H5std_string& name, void *value ) const
{
    insert( name.c_str(), value );
}

//--------------------------------------------------------------------------
// Function:	EnumType::nameOf
///\brief	Returns the symbol name corresponding to a specified member
///		of this enumeration datatype.
///\param	value - IN: Pointer to the value of the enum datatype
///\param	size  - IN: Size for the name
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
H5std_string EnumType::nameOf( void *value, size_t size ) const
{
   char* name_C = new char[size+1];  // temporary C-string for C API
   HDmemset(name_C, 0, size+1); // clear buffer

   // Calls C routine H5Tenum_nameof to get the name of the specified enum type
   herr_t ret_value = H5Tenum_nameof( id, value, name_C, size );

   // If H5Tenum_nameof returns a negative value, raise an exception,
   if( ret_value < 0 )
   {
      delete []name_C;
      throw DataTypeIException("EnumType::nameOf", "H5Tenum_nameof failed");
   }
   // otherwise, create the string to hold the datatype name and return it
   H5std_string name(name_C);
   delete []name_C;
   return( name );
}

//--------------------------------------------------------------------------
// Function:	EnumType::valueOf
///\brief	Retrieves the value corresponding to a member of this
///		enumeration datatype, given the member's name.
///\param	name  -  IN: Name of the queried member
///\param	value - OUT: Pointer to the retrieved value
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::valueOf( const char* name, void *value ) const
{
   // Calls C routine H5Tenum_valueof to get the enum datatype value
   herr_t ret_value = H5Tenum_valueof( id, name, value );
   if( ret_value < 0 )
   {
      throw DataTypeIException("EnumType::valueOf", "H5Tenum_valueof failed");
   }
}

//--------------------------------------------------------------------------
// Function:	EnumType::valueOf
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function only in the type of
///		argument \a name.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::valueOf( const H5std_string& name, void *value ) const
{
    valueOf( name.c_str(), value );
}

//--------------------------------------------------------------------------
// Function:	EnumType::getMemberIndex
///\brief	Returns the index of a member in this enumeration datatype.
///\param	name - IN: Name of the queried member
///\return	Index of the member if it exists.  Index will have the value
///		between 0 and \c N-1, where \c N is the value returned by the
///		member function \c EnumType::getNmembers.
///\exception	H5::DataTypeIException
// Programmer   Binh-Minh Ribler - May 16, 2002
//--------------------------------------------------------------------------
int EnumType::getMemberIndex(const char *name) const
{
   int member_index = H5Tget_member_index(id, name);
   if( member_index < 0 )
   {
      throw DataTypeIException("EnumType::getMemberIndex",
                "H5Tget_member_index returns negative value");
   }
   return( member_index );
}

//--------------------------------------------------------------------------
// Function:	EnumType::getMemberIndex
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function only in the type of
///		argument \a name.
// Programmer   Binh-Minh Ribler - May 16, 2002
//--------------------------------------------------------------------------
int EnumType::getMemberIndex(const H5std_string& name) const
{
    return(EnumType::getMemberIndex(name.c_str()));
}

//--------------------------------------------------------------------------
// Function:	EnumType::getNmembers
///\brief	Returns the number of members in this enumeration datatype.
///\return	Number of members
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - May, 2004
//--------------------------------------------------------------------------
int EnumType::getNmembers() const
{
   int num_members = H5Tget_nmembers( id );
   if( num_members < 0 )
   {
      throw DataTypeIException("EnumType::getNmembers",
                "H5Tget_nmembers returns negative number of members");
   }
   return( num_members );
}

//--------------------------------------------------------------------------
// Function:	EnumType::getMemberValue
///\brief	Retrieves the value of a member in this enumeration datatype,
///		given the member's index.
///\param	memb_no - IN: Index of the queried member
///\param	value   - OUT: Pointer to the retrieved value
///\exception	H5::DataTypeIException
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::getMemberValue( unsigned memb_no, void *value ) const
{
   // Call C routine H5Tget_member_value to get the datatype member's value
   hid_t ret_value = H5Tget_member_value( id, memb_no, value );
   if( ret_value < 0 )
   {
      throw DataTypeIException("EnumType::getMemberValue", "H5Tget_member_value failed");
   }
}

//--------------------------------------------------------------------------
// Function:	EnumType destructor
///\brief	Properly terminates access to this enum datatype.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
EnumType::~EnumType() {}

#ifndef H5_NO_NAMESPACE
} // end namespace
#endif


text:
from __future__ import absolute_import

from flask_cors import CORS
from .app import create_app

if __name__ == '__main__':
    app = create_app()
    cors = CORS(app, allow_headers=('Content-Type', 'Authorization', 'Orcid-Authorization'))
    app.run('0.0.0.0', port=5000, debug=True)


text:
package com.twosigma.beaker.chart.xychart.plotitem;

/**
 * Text
 *
 */
public class Text {

}


text:
/* tslint:disable:no-unused-variable */
// directiveSelectorNameRule

import {MetronSorterComponent} from './metron-sorter.component';
import {MetronTableDirective} from '../metron-table.directive';

describe('Component: MetronSorter', () => {

  it('should create an instance', () => {
    let metronTable = new MetronTableDirective();
    let component = new MetronSorterComponent(metronTable);
    expect(component).toBeTruthy();
  });

  it('should set the variables according to sorter', () => {
    let metronTable = new MetronTableDirective();
    let sorter1 = new MetronSorterComponent(metronTable);
    let sorter2 = new MetronSorterComponent(metronTable);
    let sorter3 = new MetronSorterComponent(metronTable);

    sorter1.sortBy = 'col1';
    sorter2.sortBy = 'col2';
    sorter3.sortBy = 'col3';

    sorter1.sort();
    expect(sorter1.sortAsc).toEqual(true);
    expect(sorter1.sortDesc).toEqual(false);
    expect(sorter2.sortAsc).toEqual(false);
    expect(sorter2.sortDesc).toEqual(false);
    expect(sorter3.sortAsc).toEqual(false);
    expect(sorter3.sortDesc).toEqual(false);

    sorter1.sort();
    expect(sorter1.sortAsc).toEqual(false);
    expect(sorter1.sortDesc).toEqual(true);
    expect(sorter2.sortAsc).toEqual(false);
    expect(sorter2.sortDesc).toEqual(false);
    expect(sorter3.sortAsc).toEqual(false);
    expect(sorter3.sortDesc).toEqual(false);

    sorter2.sort();
    expect(sorter1.sortAsc).toEqual(false);
    expect(sorter1.sortDesc).toEqual(false);
    expect(sorter2.sortAsc).toEqual(true);
    expect(sorter2.sortDesc).toEqual(false);
    expect(sorter3.sortAsc).toEqual(false);
    expect(sorter3.sortDesc).toEqual(false);

    sorter2.sort();
    expect(sorter1.sortAsc).toEqual(false);
    expect(sorter1.sortDesc).toEqual(false);
    expect(sorter2.sortAsc).toEqual(false);
    expect(sorter2.sortDesc).toEqual(true);
    expect(sorter3.sortAsc).toEqual(false);
    expect(sorter3.sortDesc).toEqual(false);

    sorter3.sort();
    expect(sorter1.sortAsc).toEqual(false);
    expect(sorter1.sortDesc).toEqual(false);
    expect(sorter2.sortAsc).toEqual(false);
    expect(sorter2.sortDesc).toEqual(false);
    expect(sorter3.sortAsc).toEqual(true);
    expect(sorter3.sortDesc).toEqual(false);

    sorter3.sort();
    expect(sorter1.sortAsc).toEqual(false);
    expect(sorter1.sortDesc).toEqual(false);
    expect(sorter2.sortAsc).toEqual(false);
    expect(sorter2.sortDesc).toEqual(false);
    expect(sorter3.sortAsc).toEqual(false);
    expect(sorter3.sortDesc).toEqual(true);

  });

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CmsEngine.Data.Entities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace CmsEngine.Ui.Areas.Identity.Pages.Account.Manage
{
    public class ExternalLoginsModel : PageModel
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public ExternalLoginsModel(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public IList<UserLoginInfo> CurrentLogins { get; set; }

        public IList<AuthenticationScheme> OtherLogins { get; set; }

        public bool ShowRemoveButton { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            CurrentLogins = await _userManager.GetLoginsAsync(user);
            OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                .Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
                .ToList();
            ShowRemoveButton = user.PasswordHash != null || CurrentLogins.Count > 1;
            return Page();
        }

        public async Task<IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey);
            if (!result.Succeeded)
            {
                var userId = await _userManager.GetUserIdAsync(user);
                throw new InvalidOperationException($"Unexpected error occurred removing external login for user with ID '{userId}'.");
            }

            await _signInManager.RefreshSignInAsync(user);
            StatusMessage = "The external login was removed.";
            return RedirectToPage();
        }

        public async Task<IActionResult> OnPostLinkLoginAsync(string provider)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            // Request a redirect to the external login provider to link a login for the current user
            var redirectUrl = Url.Page("./ExternalLogins", pageHandler: "LinkLoginCallback");
            var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
            return new ChallengeResult(provider, properties);
        }

        public async Task<IActionResult> OnGetLinkLoginCallbackAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
            if (info == null)
            {
                throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
            }

            var result = await _userManager.AddLoginAsync(user, info);
            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
            }

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            StatusMessage = "The external login was added.";
            return RedirectToPage();
        }
    }
}


text:
Contributing To gopacket
========================

So you've got some code and you'd like it to be part of gopacket... wonderful!
We're happy to accept contributions, whether they're fixes to old protocols, new
protocols entirely, or anything else you think would improve the gopacket
library.  This document is designed to help you to do just that.

The first section deals with the plumbing:  how to actually get a change
submitted.

The second section deals with coding style... Go is great in that it
has a uniform style implemented by 'go fmt', but there's still some decisions
we've made that go above and beyond, and if you follow them, they won't come up
in your code review.

The third section deals with some of the implementation decisions we've made,
which may help you to understand the current code and which we may ask you to
conform to (or provide compelling reasons for ignoring).

Overall, we hope this document will help you to understand our system and write
great code which fits in, and help us to turn around on your code review quickly
so the code can make it into the master branch as quickly as possible.

How To Submit Code
------------------

gopacket uses the code.google.com Git version control system.  If you want to
make a new change, you'll first have to get our code:

    go get code.google.com/p/gopacket
    cd $GOROOT/src/pkg/code.google.com/p/gopacket
    git checkout -b <mynewfeature>  # create a new branch to work from
    ... code code code ...
    ./gc  # Run this to do local commits, it performs a number of checks
    ... code code code ...
    ./gc --benchmark  # Run this whenever your commit could affect performance

Nw that you're in the gopacket code directory, you can start making your initial
change.  PLEASE make sure you're using a new branch to develop whatever feature
you're working on.

Once you've got your code to a place where you're ready to have us look at it,
send an email to gopacket@googlegroups.com, detailing your change.  We'll add
you as a committer, and you can upload your feature branch to code.google.com.
From there, the other folks working on gopacket can give you code reviews with
the code.google.com code review functionality.

The code review will generally be either emails or line-by-line reviews via
code.google.com.  One or more folks might review your code.  The review should
be considered "complete" when at least one of the project Owners (see
https://code.google.com/p/gopacket/people/list) gives you permission to merge to
master.  At that point, you can merge to master yourself, or you can have one of
the other committers/owners do it for you.

When doing the final merge, please try to capture any interesting comments or
discussions that came up in code review.  This will help future contributors be
able to find and reference those discussions later on.

To sum up:

* DO
    + Pull down the latest version.
    + Make a feature-specific branch.
    + Code using the style and methods discussed in the rest of this document.
    + Use the ./gc command to do local commits.
    + Send an email asking us to make you a committer (if you're new).
    + Push your new feature branch up to code.google.com.
    + Handle comments and requests from reviewers, pushing new commits up to
      your feature branch as problems are addressed.
    + Get approval from a project Owner to merge to master.
    + Merge yourself, or have another Committer/Owner do it for you.
    + Put interesting comments and discussions into commit comments.
* DON'T
    + Push directly to master.
    + Push to someone else's branch without their permission.
    + Merge your own code to master without sign-off from others on the project.
    + Rebase (please merge)
* OPTIONAL
    + Review others' code as it comes in (politely :)
    + Keep contributing!

Coding Style
------------

* Go code must be run through 'go fmt'.
* Follow http://golang.org/doc/effective_go.html as much as possible.
    + In particular, http://golang.org/doc/effective_go.html#mixed-caps.  Enums
      should be be CamelCase, with acronyms capitalized (TCPSourcePort, vs.
      TcpSourcePort or TCP_SOURCE_PORT).
* Bonus points for giving enum types a String() field.
* Any exported types or functions should have commentary
  (http://golang.org/doc/effective_go.html#commentary)

Coding Methods And Implementation Notes
---------------------------------------

### Error Handling

Many times, you'll be decoding a protocol and run across something bad, a packet
corruption or the like.  How do you handle this?  First off, ALWAYS report the
error.  You can do this either by returning the error from the decode() function
(most common), or if you're up for it you can implement and add an ErrorLayer
through the packet builder (the first method is a simple shortcut that does
exactly this, then stops any future decoding).

Often, you'll already have decode some part of your protocol by the time you hit
your error.  Use your own discretion to determine whether the stuff you've
already decoded should be returned to the caller or not:

    func decodeMyProtocol(data []byte, p gopacket.PacketBuilder) error {
      prot := &MyProtocol{}
      if len(data) < 10 {
        // This error occurred before we did ANYTHING, so there's nothing in my
        // protocol that the caller could possibly want.  Just return the error.
        return fmt.Errorf("Length %d less than 10", len(data))
      }
      prot.ImportantField1 = data[:5]
      prot.ImportantField2 = data[5:10]
      // At this point, we've already got enough information in 'prot' to
      // warrant returning it to the caller, so we'll add it now.
      p.AddLayer(prot)
      if len(data) < 15 {
        // We encountered an error later in the packet, but the caller already
        // has the important info we've gleaned so far.
        return fmt.Errorf("Length %d less than 15", len(data))
      }
      prot.ImportantField3 = data[10:15]
      return nil  // We've already added the layer, we can just return success.
    }

In general, our code follows the approach of returning the first error it
encounters.  In general, we don't trust any bytes after the first error we see.

### What Is A Layer?

The definition of a layer is up to the discretion of the coder.  It should be
something important enough that it's actually useful to the caller (IE: every
TLV value should probably NOT be a layer).  However, it can be more granular
than a single protocol... IPv6 and SCTP both implement many layers to handle the
various parts of the protocol.  Use your best judgement, and prepare to defend
your decisions during code review. ;)

### Performance

We strive to make gopacket as fast as possible while still providing lots of
features.  In general, this means:

* Focus performance tuning on common protocols (IP4/6, TCP, etc), and optimize
  others on an as-needed basis (tons of MPLS on your network?  Time to optimize
  MPLS!)
* Use fast operations.  See the toplevel benchmark_test for benchmarks of some
  of Go's underlying features and types.
* Test your performance changes!  You should use the ./gc script's --benchmark
  flag to submit any performance-related changes.  Use pcap/gopacket_benchmark
  to test your change against a PCAP file based on your traffic patterns.
* Don't be TOO hacky.  Sometimes, removing an unused struct from a field causes
  a huge performance hit, due to the way that Go currently handles its segmented
  stack... don't be afraid to clean it up anyway.  We'll trust the Go compiler
  to get good enough over time to handle this.  Also, this type of
  compiler-specific optimization is very fragile; someone adding a field to an
  entirely different struct elsewhere in the codebase could reverse any gains
  you might achieve by aligning your allocations.
* Try to minimize memory allocations.  If possible, use []byte to reference
  pieces of the input, instead of using string, which requires copying the bytes
  into a new memory allocation.
* Think hard about what should be evaluated lazily vs. not.  In general, a
  layer's struct should almost exactly mirror the layer's frame.  Anything
  that's more interesting should be a function.  This may not always be
  possible, but it's a good rule of thumb.
* Don't fear micro-optimizations.  With the above in mind, we welcome
  micro-optimizations that we think will have positive/neutral impacts on the
  majority of workloads.  A prime example of this is pre-allocating certain
  structs within a larger one:

    type MyProtocol struct {
      // Most packets have 1-4 of VeryCommon, so we preallocate it here.
      initialAllocation [4]uint32
      VeryCommon []uint32
    }

    func decodeMyProtocol(data []byte, p gopacket.PacketBuilder) error {
      prot := &MyProtocol{}
      prot.VeryCommon = proto.initialAllocation[:0]
      for len(data) > 4 {
        field := binary.BigEndian.Uint32(data[:4])
        data = data[4:]
        // Since we're using the underlying initialAllocation, we won't need to
        // allocate new memory for the following append unless we more than 16
        // bytes of data, which should be the uncommon case.
        prot.VeryCommon = append(prot.VeryCommon, field)
      }
      p.AddLayer(prot)
      if len(data) > 0 {
        return fmt.Errorf("MyProtocol packet has %d bytes left after decoding", len(data))
      }
      return nil
    }

### Slices And Data

If you're pulling a slice from the data you're decoding, don't copy it.  Just
use the slice itself.

    type MyProtocol struct {
      A, B net.IP
    }
    func decodeMyProtocol(data []byte, p gopacket.PacketBuilder) error {
      p.AddLayer(&MyProtocol{
        A: data[:4],
        B: data[4:8],
      })
      return nil
    }

The caller has already agreed, by using this library, that they won't modify the
set of bytes they pass in to the decoder, or the library has already copied the
set of bytes to a read-only location.  See DecodeOptions.NoCopy for more
information.

### Enums/Types

If a protocol has an integer field (uint8, uint16, etc) with a couple of known
values that mean something special, make it a type.  This allows us to do really
nice things like adding a String() function to them, so we can more easily
display those to users.  Check out layers/enums.go for one example, as well as
layers/icmp.go for layer-specific enums.

When naming things, try for descriptiveness over suscinctness.  For example,
choose DNSResponseRecord over DNSRR.


text:
/**
 * Module dependencies.
 */

var util = require('./util');
var Track = require('./schemas').build('metadata','Track');
var PassThrough = require('stream').PassThrough;
var debug = require('debug')('spotify-web:track');

// node v0.8.x compat
if (!PassThrough) PassThrough = require('readable-stream/passthrough');

/**
 * Module exports.
 */

exports = module.exports = Track;

/**
 * Track URI getter.
 */

Object.defineProperty(Track.prototype, 'uri', {
  get: function () {
    return util.gid2uri('track', this.gid);
  },
  enumerable: true,
  configurable: true
});

/**
 * Track Preview URL getter
 */
Object.defineProperty(Track.prototype, 'previewUrl', {
  get: function () {
    var previewUrlBase = 'http://d318706lgtcm8e.cloudfront.net/mp3-preview/'
    return this.preview.length && (previewUrlBase + util.gid2id(this.preview[0].fileId));
  },
  enumerable: true,
  configurable: true
})

/**
 * Loads all the metadata for this Track instance. Useful for when you get an only
 * partially filled Track instance from an Album instance for example.
 *
 * @param {Function} fn callback function
 * @api public
 */

Track.prototype.get =
Track.prototype.metadata = function (fn) {
  if (this._loaded) {
    // already been loaded...
    debug('track already loaded');
    return process.nextTick(fn.bind(null, null, this));
  }
  var spotify = this._spotify;
  var self = this;
  spotify.get(this.uri, function (err, track) {
    if (err) return fn(err);
    // extend this Track instance with the new one's properties
    Object.keys(track).forEach(function (key) {
      if (track.hasOwnProperty(key)) {
        self[key] = track[key];
      }
    });
    fn(null, self);
  });
};

/**
 * Begins playing this track, returns a Readable stream that outputs MP3 data.
 *
 * @api public
 */

Track.prototype.play = function () {
  // TODO: add formatting options once we figure that out
  var spotify = this._spotify;
  var stream = new PassThrough();

  // if a song was playing before this, the "track_end" command needs to be sent
  var track = spotify.currentTrack;
  if (track && track._playSession) {
    spotify.sendTrackEnd(track._playSession.lid, track.uri, track.duration);
    track._playSession = null;
  }

  // set this Track instance as the "currentTrack"
  spotify.currentTrack = track = this;

  // initiate a "play session" for this Track
  spotify.trackUri(track, function (err, res) {
    if (err) return stream.emit('error', err);
    if (!res) return stream.emit('error', new Error('response was null'));
    if (!res.uri) return stream.emit('error', new Error('response contained no "uri"'));
    debug('GET %s', res.uri);
    track._playSession = res;
    var req = spotify.agent.get(res.uri)
      .set({ 'User-Agent': spotify.userAgent })
      .end()
      .request();
    req.on('response', response);
  });

  function response (res) {
    debug('HTTP/%s %s', res.httpVersion, res.statusCode);
    if (res.statusCode == 200) {
      res.pipe(stream);
    } else {
      stream.emit('error', new Error('HTTP Status Code ' + res.statusCode));
    }
  }

  // return stream immediately so it can be .pipe()'d
  return stream;
};

/**
 * Begins playing a preview of the track, returns a Readable stream that outputs MP3 data.
 *
 * @api public
 */

Track.prototype.playPreview = function () {
  var spotify = this._spotify;
  var stream = new PassThrough();
  var previewUrl = this.previewUrl;

  if (!previewUrl) {
    process.nextTick(function() {
      stream.emit('error', new Error('Track does not have preview available'));
    });
    return stream;
  }

  debug('GET %s', previewUrl);
  var req = spotify.agent.get(previewUrl)
    .set({ 'User-Agent': spotify.userAgent })
    .end()
    .request();
  req.on('response', response);

  function response (res) {
    debug('HTTP/%s %s', res.httpVersion, res.statusCode);
    if (res.statusCode == 200) {
      res.pipe(stream);
    } else {
      stream.emit('error', new Error('HTTP Status Code ' + res.statusCode));
    }
  }

  // return stream immediately so it can be .pipe()'d
  return stream;
};

/**
 * Returns an mp3 url and handles play session correctly
 *
 * @api public
 */

Track.prototype.getStreamURL = function (callback) {
    // TODO: add formatting options once we figure that out
    var spotify = this._spotify;

    // if a song was playing before this, the "track_end" command needs to be sent
    var track = spotify.currentTrack;
    if (track && track._playSession) {
        spotify.sendTrackEnd(track._playSession.lid, track.uri, track.duration);
        track._playSession = null;
    }

    // set this Track instance as the "currentTrack"
    spotify.currentTrack = track = this;

    // initiate a "play session" for this Track
    spotify.trackUri(track, function(err, trackResponse) {
        if (err) console.log(err);
        track._playSession = trackResponse;
        callback.call(this, err, trackResponse)
    });
};


text:
<?php
if ( ! isset( $content_width ) ) $content_width = 630;
/* Set up theme defaults and registers support for various WordPress features. */
if ( ! function_exists( 'dt_init' ) ){

	function include_files_in_dir($dir, $no_more=FALSE){
	  $dir_init = $dir;
	  $dir = dirname(__FILE__).$dir;

	  if (!file_exists($dir))
		 throw new Exception("Folder $dir does not exist");

	  $files = array();

	  if ($handle = opendir( $dir )) {
		  while (false !== ($file = @readdir($handle))) {
			  if ( is_dir( $dir.$file ) && !preg_match('/^\./', $file) && !$no_more )
			  {
				 include_files_in_dir($dir_init.$file."/", TRUE);
			  }
			  else
			  {
				 if ( preg_match('/^[^~]{1}.*\.php$/', $file) ) {
					 $files[] = $dir.$file;
				 }
			  }
		  }
		  @closedir($handle);
	  }

	  sort($files);

	  foreach ($files as $file)
		 include_once $file;
	}

	function dt_init(){

		/* menu slot */
		global $dt_post_formats;
		$dt_post_formats = array( 'gallery', 'status' );
		register_nav_menu( 'primary-menu', __( 'Primary Menu', 'dt' ) );
		add_theme_support( 'post-formats', $dt_post_formats );

		if ( function_exists( 'add_theme_support' ) ) {
			/* add theme support images */
			add_theme_support( 'post-thumbnails' );
			/* add automatic feeds support */
			add_theme_support( 'automatic-feed-links' );
		}

		// Include functions/*.php
		include_files_in_dir("/functions/");

		// Include plugins/*/*.php
		include_files_in_dir("/plugins/");

		// Include settings/*.php
		//include_files_in_dir("/settings/");

		if( function_exists( 'load_theme_textdomain' ) ) {
			load_theme_textdomain( LANGUAGE_ZONE , get_template_directory(). '/languages' );
		}

		//remove in production , for demo stand only!!!
		if( function_exists( 'optionsframework_dt_presets' ) ){
			optionsframework_dt_presets();
		}

		// disable attachments comments if needed
		if( !of_get_option('misc_attachments_enable_comments', false) ) {
			// filter function in /functions/03_filters.php
			add_filter( 'comments_open', 'dt_disable_attachment_comments', 99, 2 );
		}
	}
	add_action( 'after_setup_theme', 'dt_init' );
}

// make permalinks work after theme switch
function dt_rewrite_flush() {
    flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'dt_rewrite_flush' );

remove_action( 'wp_head', 'feed_links_extra', 3);
?>


text:
/*
 *
 * ResponsiveChartArea constants
 *
 */

export const DEFAULT_ACTION = 'app/ResponsiveChartArea/DEFAULT_ACTION';


text:
require 'date'

class User
  attr_accessor :username, :blogs

  def initialize (username)
    @username = username
    @blogs = []
  end

  def add_blog (date, text)
    new_blog = Blog.new(date, self, text)
    blogs << new_blog
    @blogs = blogs.sort_by { |blog| blog.date }.reverse
    new_blog
  end
end

class Blog
  attr_accessor :text, :date, :user, :text

  def initialize (date, user, text)
    @date = date
    @user = user
    @text = text
  end

  def entry
    "#{user.username} #{date}\n#{text}"
  end

  def summary
    text.split[0..9].join (' ')
  end

  def ==(other)
    return self.date == other.date && self.user == other.user && self.text == other.text
  end
end


text:
 Gets or sets the ID of the Provisioning Template

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public string Id { get; set; }
```

### Property Value
Type: System.String

## See also
- [ProvisioningTemplate](OfficeDevPnP.Core.Framework.Provisioning.Model.ProvisioningTemplate.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)


text:
require 'spec_helper'

describe 'collectd::plugin::rabbitmq', type: :class do
  on_supported_os(baseline_os_hash).each do |os, facts|
    context "on #{os} " do
      let :facts do
        facts
      end

      context 'package ensure' do
        context ':ensure => present' do
          let(:node) { 'testhost.example.com' }
          let :params do
            {
              config: {
                'Username' => 'guest',
                'Password' => 'guest',
                'Port'     => '15672',
                'Scheme'   => 'http',
                'Host'     => 'testhost.example.com',
                'Realm'    => 'RabbitMQ Management'
              }
            }
          end

          it 'import collectd_rabbitmq.collectd_plugin in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_header').with_content(%r{Import "collectd_rabbitmq.collectd_plugin"})
          end

          it 'Load collectd_rabbitmq in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Module "collectd_rabbitmq.collectd_plugin"})
          end

          it 'default to Username guest in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Username "guest"})
          end

          it 'default to Password guest in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Password "guest"})
          end

          it 'default to Port 15672 in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Port "15672"})
          end

          it 'default to Scheme http in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Scheme "http"})
          end

          it 'Host should be set to $::fqdn python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Host "testhost.example.com"})
          end

          it 'Realm set to "RabbitMQ Management"' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Realm "RabbitMQ Management"})
          end
        end

        context 'override custom TypesDB with new value' do
          let :params do
            { custom_types_db: '/var/custom/types.db' }
          end

          it 'override custom TypesDB' do
            is_expected.to contain_file('rabbitmq.load').with_content(%r{TypesDB "/var/custom/types.db"})
          end
        end

        context 'override Username to foo' do
          let :params do
            { config: { 'Username' => 'foo' } }
          end

          it 'override Username to foo in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Username "foo"})
          end
        end

        context 'override Password to foo' do
          let :params do
            { config: { 'Password' => 'foo' } }
          end

          it 'override Username to foo in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Password "foo"})
          end
        end

        context 'override Scheme to https' do
          let :params do
            { config: { 'Scheme' => 'https' } }
          end

          it 'override Username to foo in python-config' do
            is_expected.to contain_concat_fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with_content(%r{Scheme "https"})
          end
        end
      end

      context ':ensure => absent' do
        let :params do
          { ensure: 'absent' }
        end

        it 'Will remove python-config' do
          is_expected.not_to contain_concat__fragment('collectd_plugin_python_conf_collectd_rabbitmq.collectd_plugin_config').with(ensure: 'present')
        end
      end

      # based on manage_package from dns spec but I added support for multiple providers
      describe 'with manage_package parameter' do
        ['true', true].each do |value|
          context "set to #{value}" do
            %w[present absent].each do |ensure_value|
              %w[pip yum].each do |provider|
                %w[collectd-rabbitmq collectd_rabbitmq].each do |packagename|
                  context "and ensure set to #{ensure_value} for package #{packagename} with package_provider #{provider}" do
                    let :params do
                      {
                        ensure: ensure_value,
                        manage_package: value,
                        package_name: packagename,
                        package_provider: provider
                      }
                    end

                    it do
                      is_expected.to contain_package(packagename).with(
                        'ensure' => ensure_value,
                        'provider' => provider
                      )
                    end
                  end # packagename
                end # ensure set
              end # provider
            end # present absent
          end # context set
        end # 'true', true
      end # describe with manage_package
    end
  end
end


text:
using System;
using System.Web.UI.WebControls;
using SRPApp.Classes;
using GRA.SRP.ControlRooms;
using GRA.SRP.Core.Utilities;
using GRA.SRP.DAL;
using GRA.SRP.Utilities.CoreClasses;
using System.Web;

namespace GRA.SRP.ControlRoom.Modules.Drawings
{
    public partial class PrizeDrawingAddEdit : BaseControlRoomPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            MasterPage.RequiredPermission = 4000;
            MasterPage.IsSecure = true;
            MasterPage.PageTitle = string.Format("{0}", "Manage Prize Drawing");

            if (!IsPostBack)
            {
                SetPageRibbon(StandardModuleRibbons.DrawingsRibbon());
            }

            if (!IsPostBack)
            {
                lblPK.Text = Session["DID"] == null ? "" : Session["DID"].ToString(); //Session["DID"]= string.Empty;
                dv.ChangeMode(lblPK.Text.Length == 0 ? DetailsViewMode.Insert : DetailsViewMode.Edit);
                Page.DataBind();
            }
        }

        protected void dv_DataBound(object sender, EventArgs e)
        {
            if (dv.CurrentMode == DetailsViewMode.Edit)
            {
                var ctl = (DropDownList)dv.FindControl("TID"); //this.FindControlRecursive(this, "BranchId");
                var lbl = (Label)dv.FindControl("TIDLbl");
                var i = ctl.Items.FindByValue(lbl.Text);
                if (i != null) ctl.SelectedValue = lbl.Text;
            }
        }

        protected void dv_DataBinding(object sender, EventArgs e)
        {
        }

        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Drawings/Default.aspx";
            if (e.CommandName.ToLower() == "back")
            {
                Response.Redirect(returnURL);
            }
            if (e.CommandName.ToLower() == "refresh")
            {
                try
                {
                    odsData.DataBind();
                    dv.DataBind();
                    dv.ChangeMode(DetailsViewMode.Edit);

                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null) masterPage.PageMessage = SRPResources.RefreshOK;
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback")
            {
                try
                {
                    var obj = new PrizeDrawing();
                    obj.PrizeName = ((TextBox)((DetailsView)sender).FindControl("PrizeName")).Text;
                    obj.TID = FormatHelper.SafeToInt(((DropDownList) ((DetailsView) sender).FindControl("TID")).SelectedValue);
                    obj.DrawingDateTime = FormatHelper.SafeToDateTime("");
                    obj.NumWinners = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumWinners")).Text);

                    obj.AddedDate = DateTime.Now;
                    obj.AddedUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session
                    obj.LastModDate = obj.AddedDate;
                    obj.LastModUser = obj.AddedUser;

                    if (obj.IsValid(BusinessRulesValidationMode.INSERT))
                    {
                        obj.Insert();
                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text = obj.PDID.ToString();

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.AddedOK;
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback")
            {
                try
                {
                    var obj = new PrizeDrawing();
                    int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text);
                    obj.Fetch(pk);

                    obj.PrizeName = ((TextBox)((DetailsView)sender).FindControl("PrizeName")).Text;
                    obj.TID = FormatHelper.SafeToInt(((DropDownList) ((DetailsView) sender).FindControl("TID")).SelectedValue);
                   //obj.DrawingDateTime = FormatHelper.SafeToDateTime("");
                    obj.NumWinners = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumWinners")).Text);

                    obj.LastModDate = DateTime.Now;
                    obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();
                        if (e.CommandName.ToLower() == "saveandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.SaveOK;
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "draw")
            {
                try
                {
                    var obj = new PrizeDrawing();
                    int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text);
                    obj.Fetch(pk);

                    obj.DrawingDateTime = DateTime.Now;

                    obj.LastModDate = DateTime.Now;
                    obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();

                        var num = PrizeDrawing.DrawWinners(pk, obj.NumWinners);

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = string.Format("{0} Winners have been drawn!", num);
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }

            }

            if (e.CommandName.ToLower() == "drawadd")
            {
                try
                {
                    var obj = new PrizeDrawing();
                    int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text);
                    obj.Fetch(pk);

                    obj.DrawingDateTime = DateTime.Now;

                    obj.LastModDate = DateTime.Now;
                    obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();

                        var addl = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("addl")).Text);

                        if (addl==0)
                        {
                            var mp = (IControlRoomMaster)Master;
                            mp.PageMessage = string.Format("Must enter a value greater than 0 for the Additional # To Draw!", addl);
                            return;
                        }
                        var num = PrizeDrawing.DrawWinners(pk, addl, 1);

                        odsData.DataBind();
                        dv.DataBind();
                        odsWinners.DataBind();
                        var gv2 = (GridView)((DetailsView)sender).FindControl("gv2");
                        gv2.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = string.Format("{0} Winners have been drawn!", num);
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }

            }

            if (e.CommandName.ToLower() == "deleterecord")
            {
                var key = Convert.ToInt32(e.CommandArgument);
                try
                {
                    var obj = PrizeDrawingWinners.FetchObject(key);
                    if (obj.IsValid(BusinessRulesValidationMode.DELETE))
                    {

                        try{DAL.Notifications.Delete(DAL.Notifications.FetchObject(obj.NotificationID));}catch{}
                        try { PatronPrizes.Delete(PatronPrizes.FetchObjectByDrawing(key)); }catch { }
                        obj.Delete();

                        odsWinners.DataBind();
                        var gv2 = (GridView)((DetailsView)sender).FindControl("gv2");
                        gv2.DataBind();

                        var masterPage = (IControlRoomMaster)Master;
                        if (masterPage != null) masterPage.PageMessage = SRPResources.DeleteOK;
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        if (masterPage != null) masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                        masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "pickup")
            {
                var key = Convert.ToInt32(e.CommandArgument);
                try
                {
                    var prizeDrawingWinner = PrizeDrawingWinners.FetchObject(key);
                    if (prizeDrawingWinner.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        var now = DateTime.Now;
                        string currentUser = "N/A";
                        try
                        {
                            currentUser = HttpContext.Current.User.Identity.Name;
                        }
                        catch (Exception) { }

                        try { DAL.Notifications.Delete(DAL.Notifications.FetchObject(prizeDrawingWinner.NotificationID)); }
                        catch { }
                        try { var pp = PatronPrizes.FetchObjectByDrawing(key);
                            pp.RedeemedFlag = true;
                            pp.LastModDate = now;
                            pp.LastModUser = currentUser;
                            pp.Update();
                        }
                        catch { }

                        prizeDrawingWinner.PrizePickedUpFlag = true;
                        prizeDrawingWinner.LastModDate = now;
                        prizeDrawingWinner.LastModUser = currentUser;
                        prizeDrawingWinner.Update();

                        odsWinners.DataBind();
                        var gv2 = (GridView)((DetailsView)sender).FindControl("gv2");
                        gv2.DataBind();

                        var masterPage = (IControlRoomMaster)Master;
                        if (masterPage != null) masterPage.PageMessage = "Prize has been marked a picked up!";
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in prizeDrawingWinner.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        if (masterPage != null) masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                        masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "undopickup")
            {
                var key = Convert.ToInt32(e.CommandArgument);
                try
                {
                    var prizeDrawingWinner = PrizeDrawingWinners.FetchObject(key);
                    if (prizeDrawingWinner.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        var now = DateTime.Now;
                        string currentUser = "N/A";
                        try
                        {
                            currentUser = HttpContext.Current.User.Identity.Name;
                        }
                        catch (Exception) { }

                        try
                        {
                            var pp = PatronPrizes.FetchObjectByDrawing(key);
                            this.Log().Warn("Reward for patron id {0} marked as NOT picked up by {1}",
                                pp.PID,
                                currentUser);

                            pp.RedeemedFlag = false;
                            pp.LastModDate = now;
                            pp.LastModUser = currentUser;
                            pp.Update();
                        }
                        catch { }

                        prizeDrawingWinner.PrizePickedUpFlag = false;
                        prizeDrawingWinner.LastModDate = now;
                        prizeDrawingWinner.LastModUser = currentUser;
                        prizeDrawingWinner.Update();

                        odsWinners.DataBind();
                        var gv2 = (GridView)((DetailsView)sender).FindControl("gv2");
                        gv2.DataBind();

                        var masterPage = (IControlRoomMaster)Master;
                        if (masterPage != null) masterPage.PageMessage = "Prize has been marked as available. This change was logged.";
                    }
                    else
                    {
                        var masterPage = (IControlRoomMaster)Master;
                        string message = String.Format(SRPResources.ApplicationError1, "
");
                        foreach (BusinessRulesValidationMessage m in prizeDrawingWinner.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}
{{0}}
", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}
", message);
                        if (masterPage != null) masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                        masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

        }

    }
}


text:
<?php require_once(APPPATH . 'views/header.php'); ?>
<?php  $session_data = $this->session->userdata('logged_in');
$userrole=$session_data['UserRole'];
$userstation=$session_data['UserStation'];
$userstationNo=$session_data['StationNumber'];
//$userstationNo=$session_data['StationNumber'];
$name=$session_data['FirstName'].' '.$session_data['SurName'];
//'StationNumber' => $row->StationNumber,
?>

            Archive Scanned Dekadal Form Report
             Page

 Home

Archive Scanned Dekadal Form Report

    <?php require_once(APPPATH . 'views/error.php'); ?>
    <?php

    if(is_array($displaynewFormToArchiveScannedDekadalFormReport) && count($displaynewFormToArchiveScannedDekadalFormReport)) {
        ?>

            <form action="<?php echo base_url(); ?>index.php/ArchiveScannedDekadalFormDataReportCopy/insertInformationForArchiveScannedDekadalFormReport/"  method="post" enctype="multipart/form-data">

                                Form
                                <input type="text" name="formname_dekadal" id="formname_dekadal" required class="form-control" value="<?php echo 'Dekadal Form';?>"  readonly class="form-control" >
                                <input type="hidden" name="checkduplicateEntryOnAddArchieveScannedDekadaFormDataReportCopy_hiddentextfield" id="checkduplicateEntryOnAddArchieveScannedDekadaFormDataReportCopy_hiddentextfield">

                                    Station
                                       <select name="station_ArchiveScannedDekadalFormReport" id="stationManager"   class="form-control" placeholder="Select Station">
                                    <option value="">Select Station</option>
                                    <?php
                                    if (is_array($stationsdata) && count($stationsdata)) {
                                        foreach($stationsdata as $station){?>
                                            <option value="<?php echo $station->StationName;?>"><?php echo $station->StationName;?></option>

                                        <?php }
                                    } ?>
                                </select>

                                     Station Number
                                     <input type="text" name="stationNo_ArchiveScannedDekadalFormReport"  id="stationNoManager" required class="form-control" value=""  readonly   >

                                 From Date
                                <input type="text" name="FromdateOnScannedDekadalFormReport_dekadal" id="expdate" required class="form-control"  placeholder="Enter From  Date">

                                 To Date
                                <input type="text" name="TodateOnScannedDekadalFormReport_dekadal" id="opened" required class="form-control"  placeholder="Enter To  Date">

                            Description
                            <textarea name="description_dekadal"  class="form-control" style="height:40px;" id="description_dekadal" onkeyup=""></textarea>

                                  Select file to upload:
                                <input type="file" accept="image/gif,image/jpg,image/png,image/jpeg,.pdf,.doc,.docx,.xlsx,.ppt,.pptx,.xls" name="archievescannedcopy_dekadalformdatareport" id="archievescannedcopy_dekadalformdatareport" required class="form-control" size = "40">

Lighter file is better

                    <a href="<?php echo base_url(); ?>index.php/ArchiveScannedDekadalFormDataReportCopy/" class="btn btn-danger"> BACK

                    <button type="submit" id="postScannedArchiveDekadalFormReportDetails_button" name="postScannedArchiveDekadalFormReportDetails_button" class="btn btn-primary"> SUBMIT </button>

            </form>

    <?php
    }elseif((is_array($scanneddekadalformreportidDetails) && count($scanneddekadalformreportidDetails))) {
        foreach($scanneddekadalformreportidDetails as $idDetails){

            $scannedformid = $idDetails->id;
            ?>

                <form action="<?php echo base_url(); ?>index.php/ArchiveScannedDekadalFormDataReportCopy/updateInformationForArchiveScannedDekadalFormReport" method="post" enctype="multipart/form-data">

                                        Station Name
                                        <input type="text" name="station" id="station" required class="form-control" value="<?php echo $userstation;?>"  readonly class="form-control" >
                                        <input type="hidden" name="id" id="id" required class="form-control" value="<?php echo $idDetails->id;?>"  readonly class="form-control" >

                                         Station Number
                                        <input type="text" name="stationNo" required class="form-control" id="stationNo" readonly class="form-control" value="<?php echo $userstationNo;?>" readonly="readonly" >
                                        <input type="hidden" name="stationId" required class="form-control" id="stationId" readonly class="form-control" value="<?php echo $idDetails->station;?>" readonly="readonly" >

                                     From Date
                                    <input type="text" name="FromdateOnScannedDekadalFormReport" id="date" required class="form-control" placeholder="Enter date on the scanned form " value="<?php echo $idDetails->from_date;?>" readonly class="form-control" readonly="readonly" >

                                    To Date
                                    <input type="text" name="TodateOnScannedDekadalFormReport" id="closed" required class="form-control" placeholder="Enter date on the scanned form " value="<?php echo $idDetails->to_date;?>" readonly class="form-control" readonly="readonly" >

                                Description
                                <textarea name="description" onkeyup="" class="form-control" style="height:40px;" id="description"><?php echo $idDetails->Description;?></textarea>

                                      Select file to upload:
                                    <input type="file" accept="image/gif,image/jpg,image/png,image/jpeg,.pdf,.doc,.docx,.xlsx,.ppt,.pptx,.xls"  value="<?php echo $idDetails->Description;?>" name="updatearchievescannedcopy_dekadalformdatareportcopy" id="updatearchievescannedcopy_dekadalformdatareportcopy"  class="form-control" size = "40">

Lighter file is better

                                     Previously Uploaded File
									<a href="<?php echo base_url(); ?>/index.php/SearchArchivedScannedDekadalFormDataReportCopy/ViewImageFromBrowser/<?php echo $idDetails->FileRef;?>" target = "blank"> <?php echo $idDetails->FileRef;?>

                                     <input type="hidden" name="PreviouslyUploadedFileName_dekadalformdatareportcopy" id="PreviouslyUploadedFileName_dekadalformdatareportcopy" required class="form-control"  value="<?php echo $idDetails->FileRef;?>"  readonly="readonly" readonly class="form-control">

                                    Approved
                                    <?php if($userrole=="DataOfficer" || $idDetails->Approved=='TRUE'){?>
								<select name="approval" id="approval" disabled  class="form-control" >
									<option value="<?php echo $idDetails->Approved;?>"><?php echo $idDetails->Approved;?></option>
									<option value="TRUE">TRUE</option>
									<option value="FALSE">FALSE</option>
								</select>
								<input type="hidden" name="approval" value="<?php echo $idDetails->Approved;?>">
								<?php }else{?>
								   <select name="approval" id="approval"  class="form-control" >
									<option value="<?php echo $idDetails->Approved;?>"><?php echo $idDetails->Approved;?></option>
									<option value="TRUE">TRUE</option>
									<option value="FALSE">FALSE</option>
								</select>
								<?php }?>

                <a  href="<?php echo base_url(); ?>index.php/ArchiveScannedDekadalFormDataReportCopy/" class="btn btn-danger"> BACK

                <button type="submit" name="updateScannedArchiveDekadalFormReportDetails_button" id="updateScannedArchiveDekadalFormReportDetails_button" class="btn btn-primary"> UPDATE </button>

            </form>

        <?php
        }
    }else{
        ?>

<a class="btn btn-primary no-print"
                                     href="<?php echo base_url(); ?>index.php/ArchiveScannedDekadalFormDataReportCopy/DisplayFormToArchiveScannedDekadalFormReport/">
                     Add new Scanned Dekadal Form Report

Scanned Dekadal Form Report Details

                    <?php require_once(APPPATH . 'views/error.php'); ?>

                                No.
                                Station Name
                                Station Number
                                From Date
                                To Date
								File Name
                                Description
                                Approved
                                By
                             <?php  if($userrole=="OC"|| $userrole=="ObserverArchive"||$userrole=="DataOfficer"||$userrole=="SeniorDataOfficer"){ ?>
                                    Action	<?php }?>

                            <?php
                            $count = 0;

                            if (is_array($archivedscanneddekadalformreportdetails) && count($archivedscanneddekadalformreportdetails)) {
                                foreach($archivedscanneddekadalformreportdetails as $data){

                                    $scanneddekadalformreportdetails = $data->id;
									 if($userrole =='DataOfficer' && $data->Approved =='TRUE' ){
									   $count++;
									   }else{
										   $count++;

                                    ?>

                                        <?php echo $count;?>
                                        <?php echo $data->StationName;?>
                                        <?php echo $data->StationNumber;?>
                                        <?php echo $data->from_date;?>
                                        <?php echo $data->to_date;?>

										 <a title="click to view file" href="<?php echo base_url(); ?>/index.php/SearchArchivedScannedDekadalFormDataReportCopy/ViewImageFromBrowser/<?php echo $data->FileRef; ?>"> <?php echo $data->FileRef;?>

                                        <?php echo $data->Description;?>
                                        <?php echo $data->Approved;?>
                                        <?php echo $data->SDE_SubmittedBy;?>
                                   <?php if($userrole=="OC"|| $userrole=="ObserverArchive"||$userrole=="DataOfficer"||$userrole=="SeniorDataOfficer"){ ?>

												<a class="btn btn-primary" href="<?php echo base_url() . "index.php/ArchiveScannedDekadalFormDataReportCopy/DisplayFormToArchiveScannedDekadalFormReportForUpdate/" .$data->id ;?>" style="cursor:pointer;">

 Edit

												<?php if($userrole=='SeniorDataOfficer'){?>

											<form method="post" action="<?php echo base_url() . "index.php/ArchiveScannedDekadalFormDataReportCopy/update_approval/" .$data->id;?>"> <input type="hidden" name="id" value="<?php echo $data->id; ?>" ><input type="hidden" name="approve" value="TRUE" ><button class="btn btn-success" <?php if($data->Approved=='TRUE'){ echo "disabled";}?> type="submit"  >

Approve</button></form>
												<?php }?>

                                <?php
									   }}
                            }
                          }
                            ?>

                        <button onClick="print();" class="btn btn-primary no-print"> PRINT </button>

    <?php
    }
    ?>

<?php require_once(APPPATH . 'views/footer.php'); ?>


text:
title: "npmで名前空間を持ったモジュールを公開する方法(scoped modules)"
author: azu
layout: post
date : 2015-04-30T23:47
category: JavaScript
tags:
    - npm
    - JavaScript
    - library

---

npmにモジュールを公開することは多くなってると思いますが、今までのnpmだと名前は早い者勝ちでした。

最近[npm Private Modules](https://www.npmjs.com/private-modules "npm Private Modules")というprivateで扱えるモジュールを有料でサポートしましたが、これは[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")をprivateで扱う時だけ有料でpublicで公開する時は無料で行えます。

[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")というのは、`@username/project-name` という感じで、@ユーザー名がパッケージ名に入るので異なるユーザー間では重複しません。

- [The npm Blog — solving npm's hard problem: naming packages](http://blog.npmjs.org/post/116936804365/solving-npms-hard-problem-naming-packages "The npm Blog — solving npm's hard problem: naming packages")

## 公開手順

実際に[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")をpublicに公開する手順としては、

1. `npm init --scope=<npmユーザ名>`
	- パッケージの名前が`@<npmユーザ名>/パッケージ名`になる
	- 手動で書き換えても別に問題ない
2. 適当に開発
3. `npm publish --access=public`

するだけです。

簡単に書くと[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")として作って、公開する時は`npm publish --access=public`とするだけです。(デフォルトが`--access=restricted`であるため明示する必要がある)

こうして公開したモジュールは

```
npm install @<npmユーザ名>/パッケージ名
```

という感じで、普通のモジュールと同様にインストールできます。

以下の記事で書いてたpublishのパターンも少し更新しておきました。

- [npm publishのパターン | Web Scratch](http://efcl.info/2015/04/09/npm-publish-pattern/ "npm publishのパターン | Web Scratch")

## 公開例

実際に適当なものを作ってみました。

- [@azu/github](https://www.npmjs.com/package/@azu/github)
- [azu/npm-github](https://github.com/azu/npm-github)

```
$ npm install @azu/github -g
```

という感じでインストールできることがわかると思います。
npm version 2.xが必要ですが、Node 0.12を使っていれば勝手に入ってるはず。

```
npm install -g npm
```

で、npmだけのアップデートも可能です。

## おわりに

[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")を使うことで、npmでも名前空間っぽいものが扱えるようになりました。

[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")であれば名前の重複などを気にしなくてよくなるのはいい気がします。

これの問題としては、周辺のツールがまだ未対応であったりすることがあります。
例えば、`@myorg/mypackage`という名前のモジュールをインストールすると以下のような配置でnode_modules以下にインストールされます。

```
node_modules
├── @myorg
│   └── mypackage
│       └── package.json
├── browserify
│   └──package.json
├── del
│   ├── index.js
│   └──package.json
....
```

そのため、ディレクトリが一つ深くなって再帰的に探索していないツールなどは[scoped modules](https://docs.npmjs.com/getting-started/scoped-packages "scoped modules")を無視してしまう事があります。

具体的には`tsd link`などはそういうバグがあったりしました。

- [Does `tsd link` not work? · Issue #130 · DefinitelyTyped/tsd](https://github.com/DefinitelyTyped/tsd/issues/130#issuecomment-91127150 "Does `tsd link` not work? · Issue #130 · DefinitelyTyped/tsd")