text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Author:  sdai
 * Created: Nov 29, 2016
 */
CREATE TABLE User(Id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, Username VARCHAR(50) NOT NULL, Credential BINARY(8192));
CREATE TABLE User_Associate(UserId BIGINT UNSIGNED NOT NULL, Name VARCHAR(50) NOT NULL, CONSTRAINT USER_ASSOCIATES_MAPPING FOREIGN KEY (UserId) REFERENCES User(Id) ON DELETE CASCADE);
CREATE TABLE User_Message(Id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, UserId BIGINT UNSIGNED NOT NULL, Type Int NOT NULL, Source VARCHAR(50), Target VARCHAR(50), Data CLOB(52428800), Attr BLOB(51200), MessageTime TIMESTAMP NOT NULL, CONSTRAINT USER_MESSAGE_MAPPING FOREIGN KEY (UserId) REFERENCES User(Id) ON DELETE CASCADE);
CREATE TABLE User_Message_Attr(PayloadId BIGINT UNSIGNED NOT NULL, Key VARCHAR(50) NOT NULL, Value CLOB(10240), CONSTRAINT USER_MESSAGE_ATTR_MAPPING FOREIGN KEY (PayloadId) REFERENCES User_Message(Id) ON DELETE CASCADE);


text:
import unittest, sys
if __name__ == '__main__':
    sys.path.extend(["../../..", "../../../.."])
from pycbio.sys.dbDict import DbDict
from pycbio.sys.testCaseBase import TestCaseBase

class DbDictTests(TestCaseBase):

    def __assertKeyValues(self, dbd, expect):
        "gets sort tuple of (key values) and compare"
        keyValues = [(k, dbd[k]) for k in dbd.keys()]
        keyValues.sort(key=lambda kv: kv[0])
        keyValues = tuple(keyValues)
        self.assertEqual(keyValues, expect)

    def testBasic(self):
        dbfile = self.getOutputFile("basic.sqlite")
        dbd = DbDict(dbfile)
        dbd["one"] = "value 1"
        dbd["two"] = "value 2"
        dbd["three"] = "value 3"
        keys = dbd.keys()
        keys.sort()
        self.__assertKeyValues(dbd, (('one', 'value 1'), ('three', 'value 3'), ('two', 'value 2')))

        dbd["two"] = "value 2.1"
        self.__assertKeyValues(dbd, (('one', 'value 1'), ('three', 'value 3'), ('two', 'value 2.1')))

        del dbd["two"]
        self.__assertKeyValues(dbd, (('one', 'value 1'), ('three', 'value 3')))

def suite():
    ts = unittest.TestSuite()
    ts.addTest(unittest.makeSuite(DbDict))
    return ts

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics.Eventing;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Text;
using System.Collections.Generic;

namespace System.Management.Automation.Tracing
{
    /// <summary>
    /// SysLog LogProvider implementation.
    /// </summary>
    internal class PSSysLogProvider : LogProvider
    {
        private static readonly SysLogProvider s_provider;

        // by default, do not include channel bits
        internal const PSKeyword DefaultKeywords = (PSKeyword)(0x00FFFFFFFFFFFFFF);

        // the default enabled channel(s)
        internal const PSChannel DefaultChannels = PSChannel.Operational;

        /// <summary>
        /// Class constructor.
        /// </summary>
        static PSSysLogProvider()
        {
            s_provider = new SysLogProvider(PowerShellConfig.Instance.GetSysLogIdentity(),
                                            PowerShellConfig.Instance.GetLogLevel(),
                                            PowerShellConfig.Instance.GetLogKeywords(),
                                            PowerShellConfig.Instance.GetLogChannels());
        }

        /// <summary>
        /// Defines a thread local StringBuilder for building event payload strings.
        /// </summary>
        /// <remarks>
        /// NOTE: do not access this field directly, use the PayloadBuilder
        /// property to ensure correct thread initialization; otherwise, a null reference can occur.
        /// </remarks>
        [ThreadStatic]
        private static StringBuilder t_payloadBuilder;

        private static StringBuilder PayloadBuilder
        {
            get
            {
                // NOTE: Thread static fields must be explicitly initialized for each thread.
                t_payloadBuilder ??= new StringBuilder(200);

                return t_payloadBuilder;
            }
        }

        /// <summary>
        /// Determines whether any session is requesting the specified event from the provider.
        /// </summary>
        /// <param name="level"></param>
        /// <param name="keywords"></param>
        /// <returns></returns>
        /// <remarks>
        /// Typically, a provider does not call this method to determine whether a session requested the specified event;
        /// the provider simply writes the event, and ETW determines whether the event is logged to a session. A provider
        /// may want to call this function if the provider needs to perform extra work to generate the event. In this case,
        ///  calling this function first to determine if a session requested the event or not, may save resources and time.
        /// </remarks>
        internal bool IsEnabled(PSLevel level, PSKeyword keywords)
        {
            return s_provider.IsEnabled(level, keywords);
        }

        /// <summary>
        /// Provider interface function for logging health event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="eventId"></param>
        /// <param name="exception"></param>
        /// <param name="additionalInfo"></param>
        internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<string, string> additionalInfo)
        {
            StringBuilder payload = PayloadBuilder;
            payload.Clear();

            AppendException(payload, exception);
            payload.AppendLine();
            AppendAdditionalInfo(payload, additionalInfo);

            WriteEvent(PSEventId.Engine_Health, PSChannel.Operational, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, payload.ToString());
        }

        /// <summary>
        /// Provider interface function for logging engine lifecycle event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="newState"></param>
        /// <param name="previousState"></param>
        internal override void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
        {
            if (IsEnabled(PSLevel.Informational, PSKeyword.Cmdlets | PSKeyword.UseAlwaysAnalytic))
            {
                StringBuilder payload = PayloadBuilder;
                payload.Clear();

                payload.AppendLine(StringUtil.Format(EtwLoggingStrings.EngineStateChange, previousState.ToString(), newState.ToString()));

                PSTask task = PSTask.EngineStart;

                if (newState == EngineState.Stopped ||
                    newState == EngineState.OutOfService ||
                    newState == EngineState.None ||
                    newState == EngineState.Degraded)
                {
                    task = PSTask.EngineStop;
                }

                WriteEvent(PSEventId.Engine_Lifecycle, PSChannel.Analytic, PSOpcode.Method, task, logContext, payload.ToString());
            }
        }

        /// <summary>
        /// Provider interface function for logging command health event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="exception"></param>
        internal override void LogCommandHealthEvent(LogContext logContext, Exception exception)
        {
            StringBuilder payload = PayloadBuilder;
            payload.Clear();

            AppendException(payload, exception);

            WriteEvent(PSEventId.Command_Health, PSChannel.Operational, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, payload.ToString());
        }

        /// <summary>
        /// Provider interface function for logging command lifecycle event.
        /// </summary>
        /// <param name="getLogContext"></param>
        /// <param name="newState"></param>
        internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
        {
            if (IsEnabled(PSLevel.Informational, PSKeyword.Cmdlets | PSKeyword.UseAlwaysAnalytic))
            {
                LogContext logContext = getLogContext();
                StringBuilder payload = PayloadBuilder;
                payload.Clear();

                if (logContext.CommandType != null)
                {
                    if (logContext.CommandType.Equals(StringLiterals.Script, StringComparison.OrdinalIgnoreCase))
                    {
                        payload.AppendLine(StringUtil.Format(EtwLoggingStrings.ScriptStateChange, newState.ToString()));
                    }
                    else
                    {
                        payload.AppendLine(StringUtil.Format(EtwLoggingStrings.CommandStateChange, logContext.CommandName, newState.ToString()));
                    }
                }

                PSTask task = PSTask.CommandStart;

                if (newState == CommandState.Stopped ||
                    newState == CommandState.Terminated)
                {
                    task = PSTask.CommandStop;
                }

                WriteEvent(PSEventId.Command_Lifecycle, PSChannel.Analytic, PSOpcode.Method, task, logContext, payload.ToString());
            }
        }

        /// <summary>
        /// Provider interface function for logging pipeline execution detail.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="pipelineExecutionDetail"></param>
        internal override void LogPipelineExecutionDetailEvent(LogContext logContext, List<string> pipelineExecutionDetail)
        {
            StringBuilder payload = PayloadBuilder;
            payload.Clear();

            if (pipelineExecutionDetail != null)
            {
                foreach (string detail in pipelineExecutionDetail)
                {
                    payload.AppendLine(detail);
                }
            }

            WriteEvent(PSEventId.Pipeline_Detail, PSChannel.Operational, PSOpcode.Method, PSTask.ExecutePipeline, logContext, payload.ToString());
        }

        /// <summary>
        /// Provider interface function for logging provider health event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="providerName"></param>
        /// <param name="exception"></param>
        internal override void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
        {
            StringBuilder payload = PayloadBuilder;
            payload.Clear();

            AppendException(payload, exception);
            payload.AppendLine();

            Dictionary<string, string> additionalInfo = new Dictionary<string, string>();

            additionalInfo.Add(EtwLoggingStrings.ProviderNameString, providerName);

            AppendAdditionalInfo(payload, additionalInfo);

            WriteEvent(PSEventId.Provider_Health, PSChannel.Operational, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, payload.ToString());
        }

        /// <summary>
        /// Provider interface function for logging provider lifecycle event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="providerName"></param>
        /// <param name="newState"></param>
        internal override void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
        {
            if (IsEnabled(PSLevel.Informational, PSKeyword.Cmdlets | PSKeyword.UseAlwaysAnalytic))
            {
                StringBuilder payload = PayloadBuilder;
                payload.Clear();

                payload.AppendLine(StringUtil.Format(EtwLoggingStrings.ProviderStateChange, providerName, newState.ToString()));

                PSTask task = PSTask.ProviderStart;

                if (newState == ProviderState.Stopped)
                {
                    task = PSTask.ProviderStop;
                }

                WriteEvent(PSEventId.Provider_Lifecycle, PSChannel.Analytic, PSOpcode.Method, task, logContext, payload.ToString());
            }
        }

        /// <summary>
        /// Provider interface function for logging settings event.
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="variableName"></param>
        /// <param name="value"></param>
        /// <param name="previousValue"></param>
        internal override void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue)
        {
            if (IsEnabled(PSLevel.Informational, PSKeyword.Cmdlets | PSKeyword.UseAlwaysAnalytic))
            {
                StringBuilder payload = PayloadBuilder;
                payload.Clear();

                if (previousValue == null)
                {
                    payload.AppendLine(StringUtil.Format(EtwLoggingStrings.SettingChangeNoPrevious, variableName, value));
                }
                else
                {
                    payload.AppendLine(StringUtil.Format(EtwLoggingStrings.SettingChange, variableName, previousValue, value));
                }

                WriteEvent(PSEventId.Settings, PSChannel.Analytic, PSOpcode.Method, PSTask.ExecutePipeline, logContext, payload.ToString());
            }
        }

        /// <summary>
        /// The SysLog provider does not use logging variables.
        /// </summary>
        /// <returns></returns>
        internal override bool UseLoggingVariables()
        {
            return false;
        }

        /// <summary>
        /// Writes a single event.
        /// </summary>
        /// <param name="id">Event id.</param>
        /// <param name="channel"></param>
        /// <param name="opcode"></param>
        /// <param name="task"></param>
        /// <param name="logContext">Log context.</param>
        /// <param name="payLoad"></param>
        internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad)
        {
            s_provider.Log(id, channel, task, opcode, GetPSLevelFromSeverity(logContext.Severity), DefaultKeywords,
                           LogContextToString(logContext),
                           GetPSLogUserData(logContext.ExecutionContext),
                           payLoad);
        }

        /// <summary>
        /// Writes an event.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="channel"></param>
        /// <param name="opcode"></param>
        /// <param name="level"></param>
        /// <param name="task"></param>
        /// <param name="keyword"></param>
        /// <param name="args"></param>
        internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args)
        {
            s_provider.Log(id, channel, task, opcode, level, keyword, args);
        }

        /// <summary>
        /// Writes an activity transfer event.
        /// </summary>
        internal void WriteTransferEvent(Guid parentActivityId)
        {
            s_provider.LogTransfer(parentActivityId);
        }

        /// <summary>
        /// Sets the activity id for the current thread.
        /// </summary>
        /// <param name="newActivityId">The GUID identifying the activity.</param>
        internal void SetActivityIdForCurrentThread(Guid newActivityId)
        {
            s_provider.SetActivity(newActivityId);
        }
    }
}

#endif // UNIX


text:
<?php

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
date_default_timezone_set('Europe/London');

define('EOL', ( PHP_SAPI == 'cli' ) ? PHP_EOL : '<br />');

date_default_timezone_set('Europe/London');

/** Include PHPExcel_IOFactory */
require_once dirname(__FILE__).'/../Classes/PHPExcel/IOFactory.php';

if (!file_exists("14excel5.xls")) {
    exit( "Please run 14excel5.php first.\n" );
}

echo date('H:i:s'), " Load workbook from Excel5 file", EOL;
$callStartTime = microtime(true);

$objPHPExcel = PHPExcel_IOFactory::load("14excel5.xls");

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo 'Call time to load Workbook was ', sprintf('%.4f', $callTime), " seconds", EOL;
// Echo memory usage
echo date('H:i:s'), ' Current memory usage: ', ( memory_get_usage(true) / 1024 / 1024 ), " MB", EOL;

// Save Excel 2007 file
echo date('H:i:s'), " Write to Excel2007 format", EOL;
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo date('H:i:s'), " File written to ", str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)), EOL;
echo 'Call time to write Workbook was ', sprintf('%.4f', $callTime), " seconds", EOL;
// Echo memory usage
echo date('H:i:s'), ' Current memory usage: ', ( memory_get_usage(true) / 1024 / 1024 ), " MB", EOL;

// Echo memory peak usage
echo date('H:i:s'), " Peak memory usage: ", ( memory_get_peak_usage(true) / 1024 / 1024 ), " MB", EOL;

// Echo done
echo date('H:i:s'), " Done reading file", EOL;
echo 'File has been created in ', getcwd(), EOL;


text:
<?php

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simply to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'bsdor';

// Table's primary key
$primaryKey = 'id';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier - in this case object
// parameter names
$columns = array(
	array(
		'db' => 'id',
		'dt' => 'DT_RowId',
		'formatter' => function( $d, $row ) {
			// Technically a DOM id cannot start with an integer, so we prefix
			// a string. This can also be useful if you have multiple tables
			// to ensure that the id is unique with a different prefix
			return 'row_'.$d;
		}
	),
	array( 'db' => 'nif', 'dt' => 'nif' ),
	array( 'db' => 'nombre',  'dt' => 'nombre' ),
	array( 'db' => 'apellidos','dt' => 'apellidos' ),
	array( 'db' => 'correo','dt' => 'correo' ),
	array( 'db' => 'provincia','dt' => 'provincia' ),
	array( 'db' => 'municipio','dt' => 'municipio' ),
	array( 'db' => 'direccion','dt' => 'direccion' ),
	array( 'db' => 'telefono','dt' => 'telefono' )
	);

$sql_details = array(
	'user' => 'root',
	'pass' => '',
	'db'   => 'dorb',
	'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
	SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Configuration;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.contentitem;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.language;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.DataLayer;
using umbraco.BusinessLogic.Utils;
using umbraco.cms.presentation.Trees;
using umbraco.BusinessLogic.Actions;
using Umbraco.Core;

namespace umbraco
{
    [Tree(Constants.Applications.Settings, "stylesheets", "Stylesheets")]
	public class loadStylesheets : BaseTree
	{
        public loadStylesheets(string application) : base(application) { }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
			rootNode.NodeType = "init" + TreeAlias;
			rootNode.NodeID = "init";
            rootNode.Text = ui.Text("treeHeaders", "stylesheets");
        }

		public override void RenderJS(ref StringBuilder Javascript)
        {
            Javascript.Append(
                @"
			function openStylesheet(id) {
				UmbClientMgr.contentFrame('settings/stylesheet/editStylesheet.aspx?id=' + id);
			}
			");
        }

        protected override void CreateAllowedActions(ref List<IAction> actions)
        {
            actions.Clear();
            actions.AddRange(new IAction[] { ActionNew.Instance, ActionDelete.Instance,
                ActionSort.Instance, ContextMenuSeperator.Instance, ActionRefresh.Instance });
        }

        public override void Render(ref XmlTree tree)
        {
            foreach (StyleSheet n in StyleSheet.GetAll())
            {
                XmlTreeNode xNode = XmlTreeNode.Create(this);
                xNode.NodeID = n.Id.ToString();
                xNode.Text = n.Text;
                xNode.Action = "javascript:openStylesheet(" + n.Id + ");";
                loadStylesheetProperty styleSheetPropertyTree = new loadStylesheetProperty(this.app);
                xNode.Source = styleSheetPropertyTree.GetTreeServiceUrl(n.Id);
				xNode.HasChildren = n.HasChildren;
                xNode.Icon = "settingCss.gif";
                xNode.OpenIcon = "settingCss.gif";
                xNode.NodeType = "stylesheet"; //this shouldn't be like this, it should be this.TreeAlias but the ui.config file points to this name.

                OnBeforeNodeRender(ref tree, ref xNode, EventArgs.Empty);
                if (xNode != null)
                {
                    tree.Add(xNode);
                    OnAfterNodeRender(ref tree, ref xNode, EventArgs.Empty);
                }

            }
        }

	}

}


text:
B110: try_except_pass
---------------------

.. automodule:: bandit.plugins.try_except_pass


text:
<title>OGRE: Ogre::VertexData Class Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

Ogre::VertexData

Classes |
Public Types |
Public Member Functions |
Public Attributes |
Private Member Functions |
Private Attributes

Ogre::VertexData Class Reference

[RenderSystem]

Summary class collecting together vertex source information.
More...

#include <OgreVertexIndexData.h>

Inheritance diagram for Ogre::VertexData:

<map name="Ogre_1_1VertexData_inherit__map" id="Ogre_1_1VertexData_inherit__map">
<area shape="rect" id="node2" href="classOgre_1_1AllocatedObject.html" title="Superclass for all objects that wish to use custom memory allocators when their new / delete operator..." alt="" coords="11,5,133,35"/></map>
[legend]

List of all members.

Classes

struct  	HardwareAnimationData

 	Struct used to hold hardware morph / pose vertex data information.  More...

Public Types

typedef vector

< HardwareAnimationData >

::type 	HardwareAnimationDataList

Public Member Functions

 	VertexData (HardwareBufferManagerBase *mgr=0)

 	Constructor.

 	VertexData (VertexDeclaration *dcl, VertexBufferBinding *bind)

 	Constructor.

 	~VertexData ()

VertexData * 	clone (bool copyData=true, HardwareBufferManagerBase *mgr=0) const

 	Clones this vertex data, potentially including replicating any vertex buffers.

void 	prepareForShadowVolume (void)

 	Modifies the vertex data to be suitable for use for rendering shadow geometry.

void 	reorganiseBuffers (VertexDeclaration *newDeclaration, const BufferUsageList &bufferUsage, HardwareBufferManagerBase *mgr=0)

 	Reorganises the data in the vertex buffers according to the new vertex declaration passed in.

void 	reorganiseBuffers (VertexDeclaration *newDeclaration, HardwareBufferManagerBase *mgr=0)

 	Reorganises the data in the vertex buffers according to the new vertex declaration passed in.

void 	closeGapsInBindings (void)

 	Remove any gaps in the vertex buffer bindings.

void 	removeUnusedBuffers (void)

 	Remove all vertex buffers that never used by the vertex declaration.

void 	convertPackedColour (VertexElementType srcType, VertexElementType destType)

 	Convert all packed colour values (VET_COLOUR_*) in buffers used to another type.

void 	allocateHardwareAnimationElements (ushort count)

 	Allocate elements to serve a holder of morph / pose target data for hardware morphing / pose blending.

void * 	operator new (size_t sz, const char *file, int line, const char *func)

 	operator new, with debug line info

void * 	operator new (size_t sz)

void * 	operator new (size_t sz, void *ptr)

 	placement operator new

void * 	operator new[] (size_t sz, const char *file, int line, const char *func)

 	array operator new, with debug line info

void * 	operator new[] (size_t sz)

void 	operator delete (void *ptr)

void 	operator delete (void *ptr, void *)

void 	operator delete (void *ptr, const char *, int, const char *)

void 	operator delete[] (void *ptr)

void 	operator delete[] (void *ptr, const char *, int, const char *)

Public Attributes

VertexDeclaration * 	vertexDeclaration

 	Declaration of the vertex to be used in this operation.

VertexBufferBinding * 	vertexBufferBinding

 	The vertex buffer bindings to be used.

bool 	mDeleteDclBinding

 	Whether this class should delete the declaration and binding.

size_t 	vertexStart

 	The base vertex index to start from.

size_t 	vertexCount

 	The number of vertices used in this operation.

HardwareAnimationDataList 	hwAnimationDataList

 	VertexElements used for hardware morph / pose animation.

size_t 	hwAnimDataItemsUsed

 	Number of hardware animation data items used.

HardwareVertexBufferSharedPtr 	hardwareShadowVolWBuffer

 	Additional shadow volume vertex buffer storage.

Private Member Functions

 	VertexData (const VertexData &rhs)

 	Protected copy constructor, to prevent misuse.

VertexData & 	operator= (const VertexData &rhs)

 	Protected operator=, to prevent misuse.

Private Attributes

HardwareBufferManagerBase * 	mMgr

Detailed Description

Summary class collecting together vertex source information.

Definition at line 48 of file OgreVertexIndexData.h.

Member Typedef Documentation

          typedef vector<HardwareAnimationData>::type Ogre::VertexData::HardwareAnimationDataList

Definition at line 98 of file OgreVertexIndexData.h.

Constructor & Destructor Documentation

          Ogre::VertexData::VertexData
          (
          const VertexData &
           rhs
           )
           [private]

Protected copy constructor, to prevent misuse.

          Ogre::VertexData::VertexData
          (
          HardwareBufferManagerBase *
           mgr = 0
           )

Constructor.

Note:

This constructor creates the VertexDeclaration and VertexBufferBinding automatically, and arranges for their deletion afterwards.

Parameters:

	mgr 	Optional HardwareBufferManager from which to create resources

          Ogre::VertexData::VertexData
          (
          VertexDeclaration *
           dcl,

          VertexBufferBinding *
           bind

          )

Constructor.

Note:

This constructor receives the VertexDeclaration and VertexBufferBinding from the caller, and as such does not arrange for their deletion afterwards, the caller remains responsible for that.

Parameters:

	dcl 	The VertexDeclaration to use

	bind 	The VertexBufferBinding to use

          Ogre::VertexData::~VertexData
          (

           )

Member Function Documentation

          void Ogre::VertexData::allocateHardwareAnimationElements
          (
          ushort
           count
           )

Allocate elements to serve a holder of morph / pose target data for hardware morphing / pose blending.

Remarks:

This method will allocate the given number of 3D texture coordinate sets for use as a morph target or target pose offset (3D position). These elements will be saved in hwAnimationDataList. It will also assume that the source of these new elements will be new buffers which are not bound at this time, so will start the sources to 1 higher than the current highest binding source. The caller is expected to bind these new buffers when appropriate. For morph animation the original position buffer will be the 'from' keyframe data, whilst for pose animation it will be the original vertex data.

          VertexData* Ogre::VertexData::clone
          (
          bool
           copyData = true,

          HardwareBufferManagerBase *
           mgr = 0

          )
          		 const

Clones this vertex data, potentially including replicating any vertex buffers.

Parameters:

	copyData 	Whether to create new vertex buffers too or just reference the existing ones

	mgr 	If supplied, the buffer manager through which copies should be made

Remarks:

The caller is expected to delete the returned pointer when ready

          void Ogre::VertexData::closeGapsInBindings
          (
          void

           )

Remove any gaps in the vertex buffer bindings.

Remarks:

This is useful if you've removed elements and buffers from this vertex data and want to remove any gaps in the vertex buffer bindings. This method is mainly useful when reorganising vertex data manually.

Note:

This will cause binding index of the elements in the vertex declaration to be altered to new binding index.

          void Ogre::VertexData::convertPackedColour
          (
          VertexElementType
           srcType,

          VertexElementType
           destType

          )

Convert all packed colour values (VET_COLOUR_*) in buffers used to another type.

Parameters:

	srcType 	The source colour type to assume if the ambiguous VET_COLOUR is encountered.

	destType 	The destination colour type, must be VET_COLOUR_ABGR or VET_COLOUR_ARGB.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr,

          void *

          )
          		 [inherited]

Definition at line 101 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr,

          const char *
          ,

          int
          ,

          const char *

          )
          		 [inherited]

Definition at line 107 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr
           )
           [inherited]

Definition at line 95 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete[]
          (
          void *
           ptr,

          const char *
          ,

          int
          ,

          const char *

          )
          		 [inherited]

Definition at line 118 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete[]
          (
          void *
           ptr
           )
           [inherited]

Definition at line 112 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz,

          const char *
           file,

          int
           line,

          const char *
           func

          )
          		 [inherited]

operator new, with debug line info

Definition at line 67 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz
           )
           [inherited]

Definition at line 72 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz,

          void *
           ptr

          )
          		 [inherited]

placement operator new

Definition at line 78 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new[]
          (
          size_t
           sz,

          const char *
           file,

          int
           line,

          const char *
           func

          )
          		 [inherited]

array operator new, with debug line info

Definition at line 85 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new[]
          (
          size_t
           sz
           )
           [inherited]

Definition at line 90 of file OgreMemoryAllocatedObject.h.

          VertexData& Ogre::VertexData::operator=
          (
          const VertexData &
           rhs
           )
           [private]

Protected operator=, to prevent misuse.

          void Ogre::VertexData::prepareForShadowVolume
          (
          void

           )

Modifies the vertex data to be suitable for use for rendering shadow geometry.

Remarks:

Preparing vertex data to generate a shadow volume involves firstly ensuring that the vertex buffer containing the positions is a standalone vertex buffer, with no other components in it. This method will therefore break apart any existing vertex buffers if position is sharing a vertex buffer. Secondly, it will double the size of this vertex buffer so that there are 2 copies of the position data for the mesh. The first half is used for the original, and the second half is used for the 'extruded' version. The vertex count used to render will remain the same though, so as not to add any overhead to regular rendering of the object. Both copies of the position are required in one buffer because shadow volumes stretch from the original mesh to the extruded version.

It's important to appreciate that this method can fundamentally change the structure of your vertex buffers, although in reality they will be new buffers. As it happens, if other objects are using the original buffers then they will be unaffected because the reference counting will keep them intact. However, if you have made any assumptions about the structure of the vertex data in the buffers of this object, you may have to rethink them.

          void Ogre::VertexData::removeUnusedBuffers
          (
          void

           )

Remove all vertex buffers that never used by the vertex declaration.

Remarks:

This is useful if you've removed elements from the vertex declaration and want to unreference buffers that never used any more. This method is mainly useful when reorganising vertex data manually.

Note:

This also remove any gaps in the vertex buffer bindings.

          void Ogre::VertexData::reorganiseBuffers
          (
          VertexDeclaration *
           newDeclaration,

          const BufferUsageList &
           bufferUsage,

          HardwareBufferManagerBase *
           mgr = 0

          )

Reorganises the data in the vertex buffers according to the new vertex declaration passed in.

Note that new vertex buffers are created and written to, so if the buffers being referenced by this vertex data object are also used by others, then the original buffers will not be damaged by this operation. Once this operation has completed, the new declaration passed in will overwrite the current one.

Parameters:

	newDeclaration 	The vertex declaration which will be used for the reorganised buffer state. Note that the new declaration must not include any elements which do not already exist in the current declaration; you can drop elements by excluding them from the declaration if you wish, however.

	bufferUsages 	Vector of usage flags which indicate the usage options for each new vertex buffer created. The indexes of the entries must correspond to the buffer binding values referenced in the declaration.

	mgr 	Optional pointer to the manager to use to create new declarations and buffers etc. If not supplied, the HardwareBufferManager singleton will be used

          void Ogre::VertexData::reorganiseBuffers
          (
          VertexDeclaration *
           newDeclaration,

          HardwareBufferManagerBase *
           mgr = 0

          )

Reorganises the data in the vertex buffers according to the new vertex declaration passed in.

Note that new vertex buffers are created and written to, so if the buffers being referenced by this vertex data object are also used by others, then the original buffers will not be damaged by this operation. Once this operation has completed, the new declaration passed in will overwrite the current one. This version of the method derives the buffer usages from the existing buffers, by using the 'most flexible' usage from the equivalent sources.

Parameters:

	newDeclaration 	The vertex declaration which will be used for the reorganised buffer state. Note that the new delcaration must not include any elements which do not already exist in the current declaration; you can drop elements by excluding them from the declaration if you wish, however.

	mgr 	Optional pointer to the manager to use to create new declarations and buffers etc. If not supplied, the HardwareBufferManager singleton will be used

Member Data Documentation

          HardwareVertexBufferSharedPtr Ogre::VertexData::hardwareShadowVolWBuffer

Additional shadow volume vertex buffer storage.

Remarks:

This additional buffer is only used where we have prepared this VertexData for use in shadow volume construction, and where the current render system supports vertex programs. This buffer contains the 'w' vertex position component which will be used by that program to differentiate between extruded and non-extruded vertices. This 'w' component cannot be included in the original position buffer because DirectX does not allow 4-component positions in the fixed-function pipeline, and the original position buffer must still be usable for fixed-function rendering.

Note that we don't store any vertex declaration or vertex buffer binding here because this can be reused in the shadow algorithm.

Definition at line 145 of file OgreVertexIndexData.h.

          HardwareAnimationDataList Ogre::VertexData::hwAnimationDataList

VertexElements used for hardware morph / pose animation.

Definition at line 100 of file OgreVertexIndexData.h.

          size_t Ogre::VertexData::hwAnimDataItemsUsed

Number of hardware animation data items used.

Definition at line 102 of file OgreVertexIndexData.h.

          bool Ogre::VertexData::mDeleteDclBinding

Whether this class should delete the declaration and binding.

Definition at line 85 of file OgreVertexIndexData.h.

          HardwareBufferManagerBase* Ogre::VertexData::mMgr [private]

Definition at line 56 of file OgreVertexIndexData.h.

          VertexBufferBinding* Ogre::VertexData::vertexBufferBinding

The vertex buffer bindings to be used.

Remarks:

Note that this is created for you on construction.

Definition at line 83 of file OgreVertexIndexData.h.

          size_t Ogre::VertexData::vertexCount

The number of vertices used in this operation.

Definition at line 89 of file OgreVertexIndexData.h.

          VertexDeclaration* Ogre::VertexData::vertexDeclaration

Declaration of the vertex to be used in this operation.

Remarks:

Note that this is created for you on construction.

Definition at line 79 of file OgreVertexIndexData.h.

          size_t Ogre::VertexData::vertexStart

The base vertex index to start from.

Definition at line 87 of file OgreVertexIndexData.h.

The documentation for this class was generated from the following file:

OgreVertexIndexData.h

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Wed Nov 3 2010 19:25:03


text:
/*
 * Copyright (c) 2008-2014 MongoDB, Inc.
 *
 * 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.
 */

package com.mongodb.util.management;

import com.mongodb.util.management.jmx.JMXMBeanServer;

/**
 * This class is NOT part of the public API.  It may change at any time without notification.
 *
 * This class is used to insulate the rest of the driver from the possibility that JMX is not available,
 * as currently is the case on Android VM
 *
 * @deprecated This class will be removed in 3.x versions of the driver,
 *             so please remove it from your compile time dependencies.
 */
@Deprecated
public class MBeanServerFactory {
    static {
        MBeanServer tmp;
        try {
            tmp = new JMXMBeanServer();
        } catch (Throwable e) {
            tmp =  new NullMBeanServer();
        }

        mBeanServer = tmp;
    }

    public static MBeanServer getMBeanServer() {
        return mBeanServer;
    }

    private static final MBeanServer mBeanServer;
}


text:
import os
import shutil

# On startup, falcon can reload the depfile generated by a previous instance.
# if the depfile is missing, the output should be marked dirty even if the
# explict dependencies are up to date.

makefile = '''
{
  "rules":
    [
    {
      "inputs": [ "source1" ],
      "outputs": [ "output" ],
      "cmd": "cat source1 > output && cat source2 >> output && echo 'output: source1 source2' > deps",
      "depfile": "deps"
    }
    ]
}
'''

def run(test):
  test.create_makefile(makefile)
  test.write_file("source1", "1")
  test.write_file("source2", "2") # implicit dependency

  # Start the daemon a first time, and check that it loaded the depfile and
  # knows about source2.
  test.start()
  assert(set(["source1", "output"]) == set(test.get_dirty_targets()))
  test.build()
  assert(test.get_dirty_targets() == [])
  assert(test.get_file_content('output') == '12')
  assert(set(["source1", "source2"]) == set(test.get_inputs_of("output")))
  assert(set(["output"]) == set(test.get_outputs_of("source2")))

  # Stop the daemon.
  test.shutdown()

  # Remove the depfile
  os.remove("deps")

  # Remove the cache
  shutil.rmtree("./.falcon/cache")

  # Restart the daemon. It should notice that the depfile is not here and
  # conclude that the output is dirty.
  test.start()

  assert(set(["source1"]) == set(test.get_inputs_of("output")))
  assert(set(["output"]) == set(test.get_dirty_targets()))


text:
<?php

namespace Symfony\Bundle\FrameworkBundle;

use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddTemplatingRenderersPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RegisterKernelListenersPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddSecurityVotersPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConverterManagerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RoutingResolverPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\Form\FormConfiguration;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Bundle.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class FrameworkBundle extends Bundle
{
    /**
     * Boots the Bundle.
     */
    public function boot()
    {
        if ($this->container->has('error_handler')) {
            $this->container->get('error_handler');
        }

        FormConfiguration::clearDefaultCsrfSecrets();

        if ($this->container->hasParameter('csrf_secret')) {
            FormConfiguration::addDefaultCsrfSecret($this->container->getParameter('csrf_secret'));
            FormConfiguration::enableDefaultCsrfProtection();
        }

        $container = $this->container;

        // the session ID should always be included in the CSRF token, even
        // if default CSRF protection is not enabled
        FormConfiguration::addDefaultCsrfSecret(function () use ($container) {
            // automatically starts the session when the CSRF token is
            // generated
            $container->get('session')->start();

            return $container->get('session')->getId();
        });
    }

    public function registerExtensions(ContainerBuilder $container)
    {
        parent::registerExtensions($container);

        $container->addCompilerPass(new AddSecurityVotersPass());
        $container->addCompilerPass(new ConverterManagerPass());
        $container->addCompilerPass(new RoutingResolverPass());
        $container->addCompilerPass(new ProfilerPass());
        $container->addCompilerPass(new RegisterKernelListenersPass());
        $container->addCompilerPass(new AddTemplatingRenderersPass());
        $container->addCompilerPass(new AddConstraintValidatorsPass());
    }
}


text:
using System.Collections.Generic;
using SObject = StardewValley.Object;

namespace Pathoschild.Stardew.Common.Integrations.ProducerFrameworkMod
{
    /// The API provided by the Producer Framework Mod.
    public interface IProducerFrameworkModApi
    {
        /// Get the list of recipes.
        /// <remarks>The recipe format follow the MachineRecipeData class properties from Lookup Anything mod. There are some additional properties that are not presented on that class, these ones has the name of the content pack properties of this mod.</remarks>
        List<Dictionary<string, object?>> GetRecipes();

        /// Get the list of recipes for a machine.
        /// <param name="machine">The machine object.</param>
        /// <remarks>The recipe format follow the MachineRecipeData class properties from Lookup Anything mod. There are some additional properties that are not presented on that class, these ones has the name of the content pack properties of this mod.</remarks>
        List<Dictionary<string, object?>> GetRecipes(SObject machine);
    }
}


text:
namespace ptest {
namespace exec {

SimpleTestRunner::SimpleTestRunner(TestRunnerListener& listener)
  : m_listener(listener) {
}

SimpleTestRunner::~SimpleTestRunner() =default;

SimpleTestRunner::SimpleTestRunner(SimpleTestRunner&&) =default;

void
SimpleTestRunner::run_suite(const hiera::TestSuiteView& suite) {
  hiera::TestSuiteVisitor visitor(*this);
  m_listener.start_suite(suite);
  suite.accept(visitor);
  m_listener.finished_suite(suite);
}

void
SimpleTestRunner::run_test(const hiera::Test& test) {
  hiera::Test run_clone = test;
  m_listener.start_test(run_clone);
  try {
    run_clone.run();
  } catch (assert::AssertError& error) {
    m_listener.failed_test(test, error);
    return;
  } catch (std::exception& error) {
    m_listener.error_test(test, error);
    return;
  } catch (...) {
    m_listener.error_test(test);
    return;
  }
  m_listener.passed_test(run_clone);
}

void
SimpleTestRunner::visit(const ptest::hiera::Test& test) {
  run_test(test);
}

void
SimpleTestRunner::visit(const ptest::hiera::TestSuiteView& suite) {
  run_suite(suite);
}

} // namespace ptest::exec
} // namespace ptest


text:
""" Custom Validators

    @requires: U{B{I{gluon}} <http://web2py.com>}

    @author: Fran Boon <fran[at]aidiq.com>
    @author: Dominic König <dominic[at]aidiq.com>
    @author: sunneach

    @copyright: (c) 2010-2011 Sahana Software Foundation
    @license: MIT

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.

"""

__all__ = ["IS_LAT",
           "IS_LON",
           "IS_HTML_COLOUR",
           "THIS_NOT_IN_DB",
           "IS_UTC_OFFSET",
           "IS_UTC_DATETIME",
           "IS_ONE_OF",
           "IS_ONE_OF_EMPTY",
           "IS_NOT_ONE_OF",
           "IS_ACL"]

import time
import uuid
import re
from datetime import datetime, timedelta
from gluon.validators import Validator, IS_MATCH, IS_NOT_IN_DB, IS_IN_SET

def options_sorter(x, y):
    return (str(x[1]).upper() > str(y[1]).upper() and 1) or -1

class IS_LAT(object):
    """
    example:

    INPUT(_type="text", _name="name", requires=IS_LAT())

    latitude has to be in degrees between -90 & 90
    """
    def __init__(self,
            error_message = "Latitude/Northing should be between -90 & 90!"):
        self.minimum = -90
        self.maximum = 90
        self.error_message = error_message
    def __call__(self, value):
        try:
            value = float(value)
            if self.minimum <= value <= self.maximum:
                return (value, None)
        except ValueError:
            pass
        return (value, self.error_message)

class IS_LON(object):
    """
    example:

    INPUT(_type="text", _name="name" ,requires=IS_LON())

    longitude has to be in degrees between -180 & 180
    """
    def __init__(self,
            error_message = "Longitude/Easting should be between -180 & 180!"):
        self.minimum = -180
        self.maximum = 180
        self.error_message = error_message
    def __call__(self, value):
        try:
            value = float(value)
            if self.minimum <= value <= self.maximum:
                return (value, None)
        except ValueError:
            pass
        return (value, self.error_message)

# -----------------------------------------------------------------------------
class IS_HTML_COLOUR(IS_MATCH):
    """
    example::

        INPUT(_type="text", _name="name", requires=IS_HTML_COLOUR())

    """

    def __init__(self, error_message="must be a 6 digit hex code!"):
        IS_MATCH.__init__(self, "^[0-9a-fA-F]{6}$", error_message)

# -----------------------------------------------------------------------------
class THIS_NOT_IN_DB(object):
    """
    Unused currently since doesn't quite work.
    See: http://groups.google.com/group/web2py/browse_thread/thread/27b14433976c0540
    """
    def __init__(self, dbset, field, this,
            error_message = "value already in database!"):
        if hasattr(dbset, "define_table"):
            self.dbset = dbset()
        else:
            self.dbset = dbset
        self.field = field
        self.value = this
        self.error_message = error_message
        self.record_id = 0
    def set_self_id(self, id):
        self.record_id = id
    def __call__(self, value):
        tablename, fieldname = str(self.field).split(".")
        field = self.dbset._db[tablename][fieldname]
        rows = self.dbset(field == self.value).select(limitby=(0, 1))
        if len(rows)>0 and str(rows[0].id) != str(self.record_id):
            return (self.value, self.error_message)
        return (value, None)

regex1 = re.compile("[\w_]+\.[\w_]+")
regex2 = re.compile("%\((?P<name>[^\)]+)\)s")

# IS_ONE_OF_EMPTY -------------------------------------------------------------------
# by sunneach 2010-02-03
# copy of nursix's IS_ONE_OF with removed 'options' method
class IS_ONE_OF_EMPTY(Validator):
    """
        Filtered version of IS_IN_DB():

        validates a given value as key of another table, filtered by the 'filterby'
        field for one of the 'filter_opts' options (=a selective IS_IN_DB())

        NB Filtering isn't active in GQL.

        For the dropdown representation:

        'label' can be a string template for the record, or a set of field
        names of the fields to be used as option labels, or a function or lambda
        to create an option label from the respective record (which has to return
        a string, of course). The function will take the record as an argument

        No 'options' method as designed to be called next to an Autocomplete field so don't download a large dropdown unnecessarily.
    """

    def __init__(
        self,
        dbset,
        field,
        label=None,
        filterby=None,
        filter_opts=None,
        not_filterby=None,
        not_filter_opts=None,
        error_message="invalid value!",
        orderby=None,
        groupby=None,
        cache=None,
        multiple=False,
        zero="",
        sort=False,
        _and=None,
        ):

        if hasattr(dbset, "define_table"):
            self.dbset = dbset()
        else:
            self.dbset = dbset
        self.field = field
        (ktable, kfield) = str(self.field).split(".")
        if not label:
            label = "%%(%s)s" % kfield
        if isinstance(label, str):
            if regex1.match(str(label)):
                label = "%%(%s)s" % str(label).split(".")[-1]
            ks = regex2.findall(label)
            if not kfield in ks:
                ks += [kfield]
            fields = ["%s.%s" % (ktable, k) for k in ks]
        else:
            ks = [kfield]
            fields =[str(f) for f in self.dbset._db[ktable]]
        self.fields = fields
        self.label = label
        self.ktable = ktable
        if not kfield or not len(kfield):
            self.kfield = "id"
        else:
            self.kfield = kfield
        self.ks = ks
        self.error_message = error_message
        self.theset = None
        self.orderby = orderby
        self.groupby = groupby
        self.cache = cache
        self.multiple = multiple
        self.zero = zero
        self.sort = sort
        self._and = _and

        self.filterby = filterby
        self.filter_opts = filter_opts
        self.not_filterby = not_filterby
        self.not_filter_opts = not_filter_opts

    def set_self_id(self, id):
        if self._and:
            self._and.record_id = id

    def set_filter(self,
                   filterby = None,
                   filter_opts = None,
                   not_filterby = None,
                   not_filter_opts = None):
        """
        This can be called from prep to apply a filter base on
        data in the record or the primary resource id.
        """
        if filterby:
            self.filterby = filterby
        if filter_opts:
            self.filter_opts = filter_opts
        if not_filterby:
            self.not_filterby = not_filterby
        if not_filter_opts:
            self.not_filter_opts = not_filter_opts

    def build_set(self):

        if self.ktable in self.dbset._db:

            _table = self.dbset._db[self.ktable]

            if self.dbset._db._dbname != "gql":
                orderby = self.orderby or ", ".join(self.fields)
                groupby = self.groupby
                dd = dict(orderby=orderby, groupby=groupby, cache=self.cache)
                if "deleted" in _table:
                    query = (_table["deleted"] == False)
                else:
                    query = (_table["id"] > 0)
                if self.filterby and self.filterby in _table:
                    if self.filter_opts:
                        query = query & (_table[self.filterby].belongs(self.filter_opts))
                    if not self.orderby:
                        dd.update(orderby=_table[self.filterby])
                if self.not_filterby and self.not_filterby in _table and self.not_filter_opts:
                    query = query & (~(_table[self.not_filterby].belongs(self.not_filter_opts)))
                    if not self.orderby:
                        dd.update(orderby=_table[self.filterby])
                records = self.dbset(query).select(*self.fields, **dd)
            else:
                import contrib.gql
                orderby = self.orderby\
                     or contrib.gql.SQLXorable("|".join([k for k in self.ks
                        if k != "id"]))
                dd = dict(orderby=orderby, cache=self.cache)
                records = \
                    self.dbset.select(self.dbset._db[self.ktable].ALL, **dd)
            self.theset = [str(r[self.kfield]) for r in records]
            #labels = []
            label = self.label
            try:
                labels = map(label, records)
            except TypeError:
                if isinstance(label, str):
                    labels = map(lambda r: label % dict(r), records)
                elif isinstance(label, (list, tuple)):
                    labels = map(lambda r: \
                                 " ".join([r[l] for l in label if l in r]),
                                 records)
                elif callable(label):
                    # Is a function
                    labels = map(label, records)
                elif "name" in _table:
                    labels = map(lambda r: r.name, records)
                else:
                    labels = map(lambda r: r[self.kfield], records)
            self.labels = labels
        else:
            self.theset = None
            self.labels = None

    #def options(self):
    #   "Removed as we don't want any options downloaded unnecessarily"

    def __call__(self, value):

        try:
            _table = self.dbset._db[self.ktable]
            deleted_q = ("deleted" in _table) and (_table["deleted"] == False) or False
            filter_opts_q = False
            if self.filterby and self.filterby in _table:
                if self.filter_opts:
                    filter_opts_q = _table[self.filterby].belongs(self.filter_opts)

            if self.multiple:
                if isinstance(value, list):
                    values = value
                elif isinstance(value, basestring) and \
                     value[0] == "|" and value[-1] == "|":
                    values = value[1:-1].split("|")
                elif value:
                    values = [value]
                else:
                    values = []

                if self.theset:
                    if not [x for x in values if not x in self.theset]:
                        return (values, None)
                    else:
                        return (value, self.error_message)
                else:
                    for v in values:
                        q = (_table[self.kfield] == v)
                        query = query is not None and query | q or q
                    if filter_opts_q != False:
                        query = query is not None and \
                                (filter_opts_q & (query)) or filter_opts_q
                    if deleted_q != False:
                        query = query is not None and \
                                (deleted_q & (query)) or deleted_q
                    if self.dbset(query).count() < 1:
                        return (value, self.error_message)
                    return (values, None)
            elif self.theset:
                if value in self.theset:
                    if self._and:
                        return self._and(value)
                    else:
                        return (value, None)
            else:
                values = [value]
                query = None
                for v in values:
                    q = (_table[self.kfield] == v)
                    query = query is not None and query | q or q
                if filter_opts_q != False:
                    query = query is not None and \
                            (filter_opts_q & (query)) or filter_opts_q
                if deleted_q != False:
                    query = query is not None and \
                            (deleted_q & (query)) or deleted_q
                if self.dbset(query).count():
                    if self._and:
                        return self._and(value)
                    else:
                        return (value, None)
        except:
            pass

        return (value, self.error_message)

# IS_ONE_OF -------------------------------------------------------------------
# added 2009-08-23 by nursix
# converted to subclass 2010-02-03 by sunneach: NO CHANGES in the method bodies
class IS_ONE_OF(IS_ONE_OF_EMPTY):

    """
    Extends IS_ONE_OF_EMPTY by restoring the 'options' method.

    """

    def options(self):

        self.build_set()
        items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)]
        if self.sort:
            items.sort(options_sorter)
        if self.zero != None and not self.multiple:
            items.insert(0,("", self.zero))
        return items

# -----------------------------------------------------------------------------
class IS_NOT_ONE_OF(IS_NOT_IN_DB):

    """
    Filtered version of IS_NOT_IN_DB()
        - understands the 'deleted' field.
        - makes the field unique (amongst non-deleted field)

    Example:
        - INPUT(_type="text", _name="name", requires=IS_NOT_ONE_OF(db, db.table))

    """

    def __call__(self, value):
        if value in self.allowed_override:
            return (value, None)
        (tablename, fieldname) = str(self.field).split(".")
        _table = self.dbset._db[tablename]
        field = _table[fieldname]
        query = (field == value)
        if "deleted" in _table:
            query = (_table["deleted"] == False) & query
        rows = self.dbset(query).select(limitby=(0, 1))
        if len(rows) > 0 and str(rows[0].id) != str(self.record_id):
            return (value, self.error_message)
        return (value, None)

# -----------------------------------------------------------------------------
class IS_UTC_OFFSET(Validator):
    """
    Validates a given string value as UTC offset in the format +/-HHMM

    @author: nursix

    @param error_message:   the error message to be returned

    @note:
        all leading parts of the string (before the trailing offset specification)
        will be ignored and replaced by 'UTC ' in the return value, if the string
        passes through.
    """

    def __init__(self,
        error_message="invalid UTC offset!"
        ):
        self.error_message = error_message

    @staticmethod
    def get_offset_value(offset_str):
        if offset_str and len(offset_str) >= 5 and \
            (offset_str[-5] == "+" or offset_str[-5] == "-") and \
            offset_str[-4:].isdigit():
            offset_hrs = int(offset_str[-5] + offset_str[-4:-2])
            offset_min = int(offset_str[-5] + offset_str[-2:])
            offset = 3600*offset_hrs + 60*offset_min
            return offset
        else:
            return None

    def __call__(self,value):

        if value and isinstance(value, str):
            _offset_str = value.strip()

            offset = self.get_offset_value(_offset_str)

            if offset is not None and offset>-86340 and offset <86340:
                # Add a leading 'UTC ',
                # otherwise leading '+' and '0' will be stripped away by web2py
                return ("UTC " + _offset_str[-5:], None)

        return (value, self.error_message)

# -----------------------------------------------------------------------------
#
class IS_UTC_DATETIME(Validator):
    """
    Validates a given value as datetime string and returns the corresponding
    UTC datetime.

    Example:
        - INPUT(_type="text", _name="name", requires=IS_UTC_DATETIME())

    @author: nursix

    @param format:          strptime/strftime format template string, for
                            directives refer to your strptime implementation
    @param error_message:   dict of error messages to be returned
    @param utc_offset:      offset to UTC in seconds, if not specified, the value
                            is considered to be UTC
    @param allow_future:    whether future date/times are allowed or not, if
                            set to False, all date/times beyond now+max_future
                            will fail
    @type allow_future:     boolean
    @param max_future:      the maximum acceptable future time interval in
                            seconds from now for unsynchronized local clocks

    @note:
        datetime has to be in the ISO8960 format YYYY-MM-DD hh:mm:ss, with an
        optional trailing UTC offset specified as +/-HHMM (+ for eastern, - for
        western timezones)

    """

    isodatetime = "%Y-%m-%d %H:%M:%S"

    def __init__(self,
        format=None,
        error_message=None,
        utc_offset=None,
        allow_future=True,
        max_future=900):

        self.format = format or self.isodatetime

        self.error_message = dict(
            format = "Required format: YYYY-MM-DD HH:MM:SS!",
            offset = "Invalid UTC offset!",
            future = "Future times not allowed!")

        if error_message and isinstance(error_message, dict):
            self.error_message["format"] = error_message.get("format", None) or self.error_message["format"]
            self.error_message["offset"] = error_message.get("offset", None) or self.error_message["offset"]
            self.error_message["future"] = error_message.get("future", None) or self.error_message["future"]
        elif error_message:
            self.error_message["format"] = error_message

        validate = IS_UTC_OFFSET()
        offset, error = validate(utc_offset)

        if error:
            self.utc_offset = "UTC +0000" # fallback to UTC
        else:
            self.utc_offset = offset

        self.allow_future = allow_future
        self.max_future = max_future

    def __call__(self, value):

        _dtstr = value.strip()

        if len(_dtstr) > 6 and \
            (_dtstr[-6:-4] == " +" or _dtstr[-6:-4] == " -") and \
            _dtstr[-4:].isdigit():
            # UTC offset specified in dtstr
            dtstr = _dtstr[0:-6]
            _offset_str = _dtstr[-5:]
        else:
            # use default UTC offset
            dtstr = _dtstr
            _offset_str = self.utc_offset

        offset_hrs = int(_offset_str[-5] + _offset_str[-4:-2])
        offset_min = int(_offset_str[-5] + _offset_str[-2:])
        offset = 3600 * offset_hrs + 60 * offset_min

        # Offset must be in range -1439 to +1439 minutes
        if offset < -86340 or offset > 86340:
            return (dt, self.error_message["offset"])

        try:
            (y, m, d, hh, mm, ss, t0, t1, t2) = time.strptime(dtstr, str(self.format))
            dt = datetime(y, m, d, hh, mm, ss)
        except:
            try:
                (y, m, d, hh, mm, ss, t0, t1, t2) = time.strptime(dtstr+":00", str(self.format))
                dt = datetime(y, m, d, hh, mm, ss)
            except:
                return(value, self.error_message["format"])

        if self.allow_future:
            return (dt, None)
        else:
            latest = datetime.utcnow() + timedelta(seconds=self.max_future)
            dt_utc = dt - timedelta(seconds=offset)
            if dt_utc > latest:
                return (dt_utc, self.error_message["future"])
            else:
                return (dt_utc, None)

    def formatter(self, value):

        format="%Y-%m-%d %H:%M:%S"
        offset = IS_UTC_OFFSET.get_offset_value(self.utc_offset)

        if not value:
            return "-"
        elif offset:
            dt = value + timedelta(seconds=offset)
            return dt.strftime(str(format))
        else:
            dt = value
            return dt.strftime(str(format)) + " +0000"

# -----------------------------------------------------------------------------
class IS_ACL(IS_IN_SET):

    """
    Validator for ACLs

    @attention: Incomplete! Does not validate yet, but just convert.

    @author: Dominic König <dominic@aidiq.com>

    """

    def __call__(self, value):
        """
        Validation

        @param value: the value to validate

        """

        if not isinstance(value, (list, tuple)):
            value = [value]

        acl = 0x0000
        for v in value:
            try:
                flag = int(v)
            except (ValueError, TypeError):
                flag = 0x0000
            else:
                acl |= flag

        return (acl, None)

# -----------------------------------------------------------------------------


text:
package gov.nih.nci.cabig.ctms.web.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * This base class provides two features to assist in implementing {@link Filter}s:
 *

 *
It stores the servletContext provided during {@link #init} so that it may be accessed
 *      during filter processing.  It also exposes the spring application context associated
 *      with the servlet context (if any).

 *
It provides blank implementations of the other methods in {@link Filter} so that the
 *      subclass need only implement the ones it is going to use.

 *

 * @see #getApplicationContext
 * @see #getServletContext
 * @author Rhett Sutphin
 */
public abstract class ContextRetainingFilterAdapter extends FilterAdapter {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    private ServletContext servletContext;

    protected ServletContext getServletContext() {
        return servletContext;
    }

    protected WebApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
    }
}


text:
void S3CommonReader::open(const S3Params &params) {
    this->keyReader.setS3InterfaceService(s3InterfaceService);

    S3CompressionType compressionType = s3InterfaceService->checkCompressionType(params.getS3Url());

    switch (compressionType) {
        case S3_COMPRESSION_GZIP:
            this->upstreamReader = &this->decompressReader;
            this->decompressReader.setReader(&this->keyReader);
            break;
        case S3_COMPRESSION_PLAIN:
            this->upstreamReader = &this->keyReader;
            break;
        default:
            S3_CHECK_OR_DIE(false, S3RuntimeError, "unknown file type");
    };

    this->upstreamReader->open(params);
}

// read() attempts to read up to count bytes into the buffer.
// Return 0 if EOF. Throw exception if encounters errors.
uint64_t S3CommonReader::read(char *buf, uint64_t count) {
    return this->upstreamReader->read(buf, count);
}

// This should be reentrant, has no side effects when called multiple times.
void S3CommonReader::close() {
    if (this->upstreamReader != NULL) {
        this->upstreamReader->close();
        this->upstreamReader = NULL;
    }
}


text:
package hr.fer.zemris.jcms.desktop.ispiti;

import java.awt.GridLayout;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class GenerirajZIPSaSlikama {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					if(!go()) {
						System.exit(0);
					}
				} catch (Exception e) {
					System.err.println("Dogodila se je pogreška: "+e.getMessage());
					JOptionPane.showMessageDialog(null, "Dogodila se je pogreška: "+e.getMessage(), "Pogreška", JOptionPane.ERROR_MESSAGE);
					System.exit(0);
				}
			}
		});
	}

	protected static boolean go() throws IOException {
		JFrame frame = new JFrame();
		frame.setTitle("Generiranje ZIP arhive i opisnika slika");
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		JLabel statusLabel = new JLabel();
		JProgressBar pb = new JProgressBar();
		frame.getContentPane().setLayout(new GridLayout(2, 1));
		statusLabel.setText("Biranje direktorija sa slikama...");
		frame.getContentPane().add(statusLabel);
		frame.getContentPane().add(pb);
		frame.setBounds(0, 0, 700, 100);

		frame.setVisible(true);

		JFileChooser ch = new JFileChooser();
		ch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		ch.setMultiSelectionEnabled(false);
		ch.setDialogTitle("Odaberite direktorij koji sadrži slike");
		if(ch.showOpenDialog(null)!=JFileChooser.APPROVE_OPTION) {
			return false;
		}
		File imageDir = ch.getSelectedFile();
		ch.setSelectedFiles(null);

		statusLabel.setText("Biranje RMK datoteke...");

		ch.setDialogTitle("Odaberite RMK datoteku s podatcima");
		ch.setFileSelectionMode(JFileChooser.FILES_ONLY);
		if(ch.showOpenDialog(null)!=JFileChooser.APPROVE_OPTION) {
			return false;
		}
		File rmkFile = ch.getSelectedFile();
		ch.setSelectedFiles(null);

		statusLabel.setText("Biranje ZIP arhive koju treba generirati...");

		ch.setDialogTitle("Odaberite naziv ZIP arhive koju treba stvoriti");
		ch.setFileSelectionMode(JFileChooser.FILES_ONLY);
		if(ch.showSaveDialog(null)!=JFileChooser.APPROVE_OPTION) {
			return false;
		}
		File zipFile = ch.getSelectedFile();
		ch.setSelectedFiles(null);
		String zipName = zipFile.getName().toUpperCase();
		if(!zipName.endsWith(".ZIP")) {
			zipFile = new File(zipFile.getParentFile(), zipFile.getName() + ".zip");
		}

		Set<String> validFiles = new HashSet<String>(1000);
		Map<String,String> map = new HashMap<String, String>();

		statusLabel.setText("Pregledavanje RMK datoteke");
		statusLabel.repaint();

		BufferedReader br = new BufferedReader(new FileReader(rmkFile));
		br.readLine();
		while(true) {
			String line1 = br.readLine();
			if(line1==null) break;
			br.readLine();
			String[] elems = line1.split("\t");
			int broj = elems.length;
			String zadnji = elems[broj-1];
			int pos = zadnji.indexOf(11);
			if(pos==-1) {
				throw new IOException("U RMK datoteci je pronađen redak neočekivanog formata.");
			}
			zadnji = zadnji.substring(0, pos);
			pos = zadnji.lastIndexOf('\\');
			if(pos==-1) {
				pos = zadnji.lastIndexOf('/');
			}
			if(pos==-1) {
				throw new IOException("U RMK datoteci je pronađen redak neočekivanog formata (2).");
			}
			String datoteka = zadnji.substring(pos+1);
			pos = datoteka.lastIndexOf('.');
			if(pos==-1) {
				throw new IOException("U RMK datoteci je pronađen redak neočekivanog formata (3).");
			}
			datoteka = datoteka.substring(0, pos);
			validFiles.add(datoteka);
			map.put(datoteka, elems[0]);
		}
		br.close();

		int brojZapisa = map.size();

		statusLabel.setText("Pronađeno "+brojZapisa+" zapisa. Generiram ZIP arhivu...");
		statusLabel.repaint();

		ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
		StringBuilder sb = new StringBuilder(1024*64);
		if(brojZapisa>0) {
			File[] file = imageDir.listFiles();
			int pronasaoZapis = 0;
			pb.setMinimum(0);
			pb.setMaximum(brojZapisa+1);
			pb.setValue(pronasaoZapis);
			pb.setStringPainted(true);
			pb.repaint();
			for(File f : file) {
				if(f.isDirectory()) {
					continue;
				}
				String n = f.getName();
				int pos = n.lastIndexOf('.');
				if(pos==-1) {
					continue;
				}
				n = n.substring(0, pos);
				if(!map.containsKey(n)) continue;
				pronasaoZapis++;
				String jmbag = map.get(n);
				sb.append(jmbag).append("\t").append(f.getName()).append("\tO1\t\n");
				ZipEntry e = new ZipEntry(f.getName());
				zos.putNextEntry(e);
				kopiraj(f, zos);
				zos.closeEntry();
				pb.setValue(pronasaoZapis);
				pb.repaint();
			}
		}
		ZipEntry e = new ZipEntry("opisnik.txt");
		zos.putNextEntry(e);
		zos.write(sb.toString().getBytes());
		zos.closeEntry();
		pb.setValue(pb.getMaximum());
		pb.repaint();
		zos.close();

		statusLabel.setText("Arhiva je generirana. Možete zatvoriti program.");
		return true;
	}

	private static void kopiraj(File f, OutputStream os) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
		byte[] buf = new byte[1024*32];
		while(true) {
			int n = bis.read(buf);
			if(n<1) break;
			os.write(buf,0,n);
		}
		bis.close();
	}

}


text:
package com.intellij.gwt.inspections;

import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.gwt.GwtBundle;
import com.intellij.gwt.i18n.GwtI18nManager;
import com.intellij.gwt.i18n.GwtI18nUtil;
import com.intellij.gwt.sdk.GwtVersion;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import consulo.gwt.module.extension.GoogleGwtModuleExtension;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author nik
 */
public class GwtMethodWithParametersInConstantsInterfaceInspection extends BaseGwtInspection
{
	private static final Logger LOG = Logger.getInstance("#com.intellij.gwt.inspections.GwtMethodWithParametersInConstantsInterfaceInspection");

	@Override
	@Nls
	@Nonnull
	public String getDisplayName()
	{
		return GwtBundle.message("inspection.name.method.with.parameters.in.interface.extending.constants");
	}

	@Override
	@NonNls
	@Nonnull
	public String getShortName()
	{
		return "GwtMethodWithParametersInConstantsInterface";
	}

	@RequiredReadAction
	@Override
	@Nullable
	public ProblemDescriptor[] checkClassImpl(@Nonnull GoogleGwtModuleExtension extension, @Nonnull GwtVersion version, @Nonnull final PsiClass aClass, @Nonnull final InspectionManager manager, final boolean isOnTheFly)
	{
		if(!shouldCheck(aClass))
		{
			return null;
		}

		GwtI18nManager i18nManager = GwtI18nManager.getInstance(manager.getProject());
		PropertiesFile[] files = i18nManager.getPropertiesFiles(aClass);
		if(files.length == 0 || !i18nManager.isConstantsInterface(aClass))
		{
			return null;
		}

		PsiJavaCodeReferenceElement extendsConstantsElement = findExtendsContsantsElement(aClass);

		List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
		for(PsiMethod psiMethod : aClass.getMethods())
		{
			if(psiMethod.getParameterList().getParametersCount() > 0)
			{
				ReplaceConstantsByMessagesInExtendsListQuickFix quickFix = null;
				if(extendsConstantsElement != null)
				{
					quickFix = new ReplaceConstantsByMessagesInExtendsListQuickFix(aClass, extendsConstantsElement);
				}

				problems.add(manager.createProblemDescriptor(getElementToHighlight(psiMethod), GwtBundle.message("problem.description.methods.with.parameters" +
						".are.not.allowed.in.an.interface.extending.constants"), quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
			}
		}

		return problems.toArray(new ProblemDescriptor[problems.size()]);
	}

	@Override
	public ProblemDescriptor[] checkFile(@Nonnull final PsiFile file, @Nonnull final InspectionManager manager, final boolean isOnTheFly)
	{
		if(!shouldCheck(file) || !(file instanceof PropertiesFile))
		{
			return null;
		}
		PropertiesFile propertiesFile = (PropertiesFile) file;

		GwtI18nManager i18nManager = GwtI18nManager.getInstance(manager.getProject());
		PsiClass propertiesInterface = i18nManager.getPropertiesInterface(propertiesFile);
		if(propertiesInterface == null || !i18nManager.isConstantsInterface(propertiesInterface))
		{
			return null;
		}

		List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
		PsiJavaCodeReferenceElement extendsConstantsElement = findExtendsContsantsElement(propertiesInterface);
		for(IProperty property : propertiesFile.getProperties())
		{
			if(GwtI18nUtil.getParametersCount(property.getValue()) > 0)
			{
				ReplaceConstantsByMessagesInExtendsListQuickFix quickFix = null;
				if(extendsConstantsElement != null)
				{
					quickFix = new ReplaceConstantsByMessagesInExtendsListQuickFix(propertiesInterface, extendsConstantsElement);
				}
				String message = GwtBundle.message("problem.description.properties.with.parameters.are.not.allowed.if.the.associated.interface.extends" +
						".constants");
				problems.add(manager.createProblemDescriptor(property.getPsiElement(), message, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
			}
		}

		return problems.toArray(new ProblemDescriptor[problems.size()]);
	}

	@Nullable
	private static PsiJavaCodeReferenceElement findExtendsContsantsElement(final PsiClass aClass)
	{
		PsiJavaCodeReferenceElement extendsConstantsElement = null;
		PsiReferenceList list = aClass.getExtendsList();
		if(list != null)
		{
			for(PsiJavaCodeReferenceElement element : list.getReferenceElements())
			{
				PsiElement anInterface = element.resolve();
				if(anInterface instanceof PsiClass && GwtI18nUtil.CONSTANTS_INTERFACE_NAME.equals(((PsiClass) anInterface).getQualifiedName()))
				{
					extendsConstantsElement = element;
					break;
				}
			}
		}
		return extendsConstantsElement;
	}

	private static class ReplaceConstantsByMessagesInExtendsListQuickFix extends BaseGwtLocalQuickFix
	{
		private PsiClass myInterface;
		private final PsiJavaCodeReferenceElement myExtendsConstantsElement;

		private ReplaceConstantsByMessagesInExtendsListQuickFix(final PsiClass anInterface, final PsiJavaCodeReferenceElement extendsConstantsElement)
		{
			super(GwtBundle.message("quickfix.name.inherit.0.from.messages.instead.of.constants", anInterface.getName()));
			myInterface = anInterface;
			myExtendsConstantsElement = extendsConstantsElement;
		}

		@Override
		public void applyFix(@Nonnull final Project project, @Nonnull final ProblemDescriptor descriptor)
		{
			if(ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(myInterface.getContainingFile().getVirtualFile()).hasReadonlyFiles())
			{
				return;
			}

			try
			{
				myExtendsConstantsElement.delete();
				PsiElementFactory factory = JavaPsiFacade.getInstance(myInterface.getProject()).getElementFactory();
				PsiClassType messagesType = factory.createTypeByFQClassName(GwtI18nUtil.MESSAGES_INTERFACE_NAME, myInterface.getResolveScope());
				PsiReferenceList extendsList = myInterface.getExtendsList();
				LOG.assertTrue(extendsList != null);
				extendsList.add(factory.createReferenceElementByType(messagesType));
			}
			catch(IncorrectOperationException e)
			{
				LOG.error(e);
			}
		}
	}
}


text:
import pymysql
import random
import sys

def display_ingredients(category):
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='care_products')
    cur = conn.cursor()
    cur.execute("""
    SELECT ingredient
    FROM category_ingredients
    WHERE concern='high' AND category='%s'
    ORDER BY proportion DESC
    LIMIT 10;""" % category)
    sql_output = cur.fetchall()
    cur.close()
    conn.close()
    if len(sql_output) > 0:
        displayed = [res[0] for res in sql_output]
    else:
        displayed = ['fragrance']
    return displayed

def get_id_category(category):
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='care_products')
    cur = conn.cursor()
    cur.execute("""
    SELECT id_category, category
    FROM products
    WHERE category='%s'
    GROUP BY category;""" % category)
    sql_output = cur.fetchall()
    cur.close()
    conn.close()
    id_categ = sql_output[0][0]
    categ = sql_output[0][1]
    result = str(id_categ) + '-' +  categ
    href = 'http://www.goodguide.com/products?category_id=' + result + '&sort_order=DESC'
    return href

def get_recommendations(category):
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='care_products')
    cur = conn.cursor()
    cur.execute("""
    SELECT id_prod, product, health
    FROM products
    WHERE category='%s' AND health>8
    ORDER BY health DESC
    LIMIT 25;""" % category)
    sql_output = cur.fetchall()
    cur.close()
    conn.close()
    query_ids = [res[0] for res in sql_output]
    query_products = [res[1] for res in sql_output]
    query_scores = [res[2] for res in sql_output]
    sample_size = min(len(query_products) , 5)
    sample = random.sample(range(len(query_products)), sample_size)
    results = []
    for s in sample:
        recom = {}
        recom['id'] = 'http://www.goodguide.com/products/' + query_ids[s]
        recom['name'] = query_products[s]
        recom['score'] = query_scores[s]
        results.append(recom)
    return results


text:
package common;

import java.security.SecureRandom;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;

public class RandomString {

	public final static int DEFAULT_SIZE = 8;

	/**
	 * Generate a random string.
	 */
	public String nextString() {
		for (int idx = 0; idx < buf.length; ++idx)
			buf[idx] = symbols[random.nextInt(symbols.length)];
		return new String(buf);
	}

	public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	public static final String lower = upper.toLowerCase(Locale.ROOT);

	public static final String digits = "0123456789";

	public static final String alphanum = upper + lower + digits;

	private final Random random;

	private final char[] symbols;

	private final char[] buf;

	public RandomString(int length, Random random, String symbols) {
		if (length < 1)
			throw new IllegalArgumentException();
		if (symbols.length() < 2)
			throw new IllegalArgumentException();
		this.random = Objects.requireNonNull(random);
		this.symbols = symbols.toCharArray();
		this.buf = new char[length];
	}

	/**
	 * Create an alphanumeric string generator.
	 */
	public RandomString(Random random) {
		this(DEFAULT_SIZE, random, alphanum);
	}

	/**
	 * Create an alphanumeric strings from a secure generator.
	 */
	public RandomString() {
		this(new SecureRandom());
	}
}


text:
A tree is composed of three parts: A `TreeSkeleton`, a `TreeMesh` and a
`TreeLeafCloud`. The skeleton describes the topology of the tree, and here you
can inspect the positions of each individual branch and leaf (if you wanted to).
The tree mesh contains the geometry required to render the branches, but it must
be given an `Effect` from outside to render itself - it sets no effect
parameters on its own. Likewise, the tree leaf cloud contains the vertex buffer
for the leaves.

The `SimpleTree` contains all you need to render a tree, including the skeleton,
mesh, leaf cloud, textures, effects, and animation state. It will set effect
parameters in its draw calls for you.

A `TreeAnimationState` contains the rotations of each bone in a tree, and is
stored independently of the other parts, so one tree can be used in several
copies.

`TreeGenerator` is the class that generates the random tree. It produces a tree
skeleton, which can be used to create a tree mesh and a leaf cloud.

## Render States

The tree and leaf shaders set a couple of render states automatically, but they
do not change them back. Managing render states is a central aspect of any game,
and LTrees will not do it for you. Therefore, *it is your own responsibility to
restore the previous render states*. If you are having graphical issues with the
trees, it is most likely a render state issue.

## Applying Wind

You need two objects: A `WindSource` which describes the wind strength at
different times and places, and the `TreeWindAnimator` helper class.
`WindSource` is an interface so you can provide your own definition of wind
strength, but a simple implementation is included in the project.

To get started, add these two fields in your `Game` class or similar location:

``` csharp
public class Game1 : Game
{
    WindStrengthSin wind;
    TreeWindAnimator animator;
    // ...
```

Create them during initialization:

``` csharp
protected override void LoadContent()
{
    wind = new WindStrengthSin();
    animator = new TreeWindAnimator(wind);
    // ...
}
```

In the `Update` method, update the wind source so it knows what time it is, and
then use it to animate your trees:

``` csharp
protected override void Update(GameTime gameTime)
{
    wind.Update(gameTime);
    // ...
}

protected override void Draw(GameTime gameTime)
{
    foreach (SimpleTree tree in MyCollectionOfTrees)
    {
        animator.Animate(tree.Skeleton, tree.AnimationState, gameTime);
    }
    // ...
}
```

Note that the `WindStrengthSin` was designed to demonstrate the wind feature.
In practice, it can be tiresome when all the trees are blowing in such an
irregular wind. Currently, you are encouraged to write your own implementation
of `WindSource`, which also allows you to synchronize it with the wind that
affects other scenery like grass and snowflakes.

* *Caution: The `BoundingSphere` property of the `TreeMesh` is only guaranteed to
  enclose the tree in its initial animation state.*
* *Hint: Trees in your world can share the same mesh but still use different
  animation states, so they can be animated independently.*

## Using Multiple Levels-of-Detail (LOD)

A common way to improve performance is to reduce the amount of detail on models
the further they are from the camera. When sufficiently far away, you want to
display a billboard instead of rendering the tree, but that is another topic
("Impostering"). Before turning the tree into a billboard, we can decrease the
number of polygons in the trunk.

To create a low-detail model of a tree, try this:

``` csharp
TreeMesh lowPolyMesh = new TreeMesh(GraphicsDevice, tree.Skeleton, 4);
```

The third argument is the number of radial segments to use in the root branch.
The default is 8 - a value of 4 makes it look like a square, but should
hopefully not be noticeable at a distance. Note that the number of radial
segments in branches will gradually decrease towards 3 (the minimum) as the
radius gets smaller.

There is currently no way to decrease the level of detail on leaves.

## Using Features like Fog, Point Lights, and Shadows

The shaders provided in the project only allow for two directional lights,
hardware-skinned animation, and nothing else. In modern games this is
insufficient, but the exact requirements depends too strongly the individual
application, which is why serious users are encouraged to write their own
shaders and/or a replacement for `SimpleTree` to render their trees. The
reference shaders are included in the content project bundled in LTreeLibrary.

To replace the default shaders inserted by the content loader, add this
**before** loading any trees:

``` csharp
TreeProfileReader.DefaultTreeShaderAssetName = "Effects/<YourShaderHere>";
TreeProfileReader.DefaultLeafShaderAssetName= "Effects/<YourShaderHere>";
```

This way, you can still use the `TreeProfile` loaded by the content manager -
nobody says you have to call `GenerateSimpleTree` to generate your trees.
`TreeProfile` has all the properties available required to make your own
implementation.

Alternatively, you can change the effect loaded for each individual tree profile
by settings its "Trunk Effect" and/or "Leaf Effect" properties in the property
editor.

* *Note: The tree mesh contains holes and is self-intersecting, so stencil
  shadows (aka. shadow volumes) cannot be used to draw shadow. Shadow mapping
  is the recommended approach.*

## Avoiding the Content Pipeline

For those who don't like the content pipeline, an `.ltree`-file can be loaded at
runtime using the static method `TreeGenerator.CreateFromXml`. Note that this
method does not load textures or effects for you. Use the resulting
`TreeGenerator` to generate a `TreeSkeleton`, and from the skeleton create a
`TreeMesh` and a `TreeLeafCloud`.

## Creating more Tree Profiles

This is not an easy task. One way is of course to copy an existing tree profile
and simple replace the texture with new ones. To change the texture used, open
the `.ltree` file in your favourite XML editor (double-clicking it in Visual
Studio will work). Find these two lines:

```
    <TrunkTexture>...</TrunkTexture>
    <LeafTexture>...</LeafTexture>
```

Replace the inner text of these two tags with the asset names of the trunk
texture and leaf texture you want.

To understand how the structure of the tree is generated, you must know what an
L-system is (LTrees got its name from "L-system"). I suggest starting with an
[interactive example in 2D](http://lsysjs.qwert.ch). The tree generator works
like this, only in three dimensions. Think of it as moving around a crayon in
3D space, and this crayon paints tree branches in its wake. The L-system
produces a long sequence of instructions for the crayon. Instructions include to
move forward, rotate around its own X or Y axis, scale, store the current state,
restore the previously stored state, place a leaf here, place a bone here, and
so on.

A *production* contains a sequence of instructions, and the instruction *Call*
makes the crayon execute the instructions in a specified production, much like a
method call in C#. The *Child* tag instructs the crayon to remember its current
state, execute the nested instructions, and then restore the original state
again. To avoid a tree that grows into infinity without ever stopping, the
crayon knows its current *level* as part of its state. Executing a *Call*
instruction by default decreases the level by one, and if the level ever would
become negative, the crayon instead omits the call.

If you are up to the challenge, from here on you must use the existing profiles
as reference to try through trial and error to create your own profile. The
content pipeline will complain if there are syntactic errors in your profile.

## Collision Detection and Physics

To perform collision detection and physics simulation, it is required to know
the general size and shape of the tree. For simple circle-based collision
detection, `tree.Skeleton.TrunkRadius` is a good collision radius to use, as it
is the radius at the bottom of the tree.

For more advanced physics, the `TreeSkeleton` should provide sufficient
information about the tree's topology to build an appropriate representation of
it. There is no official support for breakable branches, but it might be
possible like this. Once your physics library has detected that a branch should
break, split the tree skeleton into two parts: the descendants of that branch,
and the rest. Then generate new meshes and leaf clouds for the two skeletons.
The skeleton generated from the free-broken branch should then be transformed to
the branch's original position on the tree.