text:
#pragma once

#include "iFnPub.h"
#include "point3.h"
// forward declarations
class MNMesh;
class MNNormalSpec;

// Edit Normals Selection Levels - selection is always some set of normals
// (vertex/face selLevels are just rules for hit testing - select normals by vertex, or by face.)
enum editNormalSelLevel
{
	EN_SL_OBJECT,
	EN_SL_NORMAL,
	EN_SL_VERTEX,
	EN_SL_EDGE,
	EN_SL_FACE
};

// Edit Normals Parameters:
enum editNormalParameters
{
	en_display_length,
	en_ignore_backfacing,
	en_select_by,
	en_show_handles
};

#define EDIT_NORMALS_MOD_INTERFACE Interface_ID(0x2b572ad6,0x7cf86ae2)

// "Mixin" Interface methods:
enum editNormalsModMethods { enfn_get_sel_level, enfn_set_sel_level, enfn_move,
	enfn_rotate, enfn_break, enfn_unify, enfn_reset, enfn_specify,
	enfn_make_explicit, enfn_copy, enfn_paste,
	enfn_select, enfn_get_selection, enfn_set_selection,
	enfn_convert_vertex_selection, enfn_convert_edge_selection,
	enfn_convert_face_selection, enfn_get_num_normals,
	enfn_get_num_faces, enfn_get_normal, enfn_set_normal,
	enfn_get_normal_explicit, enfn_set_normal_explicit,
	enfn_get_face_degree, enfn_get_normal_id, enfn_set_normal_id,
	enfn_get_num_vertices, enfn_get_vertex_id, enfn_get_vertex,
	enfn_get_num_edges, enfn_get_edge_id, enfn_get_edge_vertex,
	enfn_get_face_edge_side, enfn_get_edge_face, enfn_get_edge_normal,
	enfn_get_face_normal_specified, enfn_set_face_normal_specified,
	enfn_rebuild_normals, enfn_recompute_normals, enfn_average,
	enfn_average_global, enfn_average_two };

// Enum of enums, for methods which accept enum parameters
enum editNormalsModEnums { enprop_sel_level };

/*! \sa  Class MNMesh , Class MNNormalSpec\n\n
class IEditNormalsMod : public FPMixinInterface\n\n

\par Description:
This class is an interface used by the scripter and the SDK to access the Edit
Normals modifier. See the documentation for that modifier for background on the
normals and the basic operations like Break and Unify.\n\n
All but the last two of these methods are available via the scripter with
commands like:\n\n
numNormals = $.modifiers[#Edit_Normals].EditNormalsMod.GetNumNormals ()\n\n
$.modifiers[#Edit_Normals].EditNormalsMod.SetSelection #{1..numNormals}\n\n
$.modifiers[#Edit_Normals].EditNormalsMod.Unify ().\n\n
  */
#pragma warning(push)
#pragma warning(disable:4100)
class IEditNormalsMod : public FPMixinInterface
{
public:
	#pragma warning(push)
	#pragma warning(disable:4238)
	BEGIN_FUNCTION_MAP
		// Selection Level Access
		PROP_FNS(enfn_get_sel_level, EnfnGetSelLevel, enfn_set_sel_level, EnfnSetSelLevel, TYPE_INT);

		// Transforms
		FNT_1(enfn_move, TYPE_bool, EnfnMove, TYPE_POINT3_BR);
		FNT_1(enfn_rotate, TYPE_bool, EnfnRotate, TYPE_QUAT_BR);

		// Operations
		FN_3(enfn_break, TYPE_bool, EnfnBreakNormals, TYPE_BITARRAY, TYPE_INODE, TYPE_bool);
		FN_3(enfn_unify, TYPE_bool, EnfnUnifyNormals, TYPE_BITARRAY, TYPE_INODE, TYPE_bool);
		FN_2(enfn_reset, TYPE_bool, EnfnResetNormals, TYPE_BITARRAY, TYPE_INODE);
		FN_2(enfn_specify, TYPE_bool, EnfnSpecifyNormals, TYPE_BITARRAY, TYPE_INODE);
		FN_2(enfn_make_explicit, TYPE_bool, EnfnMakeNormalsExplicit, TYPE_BITARRAY, TYPE_INODE);
		FN_2(enfn_copy, TYPE_bool, EnfnCopyNormal, TYPE_INDEX, TYPE_INODE);
		FN_2(enfn_paste, TYPE_bool, EnfnPasteNormal, TYPE_BITARRAY, TYPE_INODE);
		FN_4(enfn_average, TYPE_bool, EnfnAverageNormals, TYPE_bool, TYPE_FLOAT, TYPE_BITARRAY, TYPE_INODE);
		FN_2(enfn_average_global, TYPE_bool, EnfnAverageGlobalNormals, TYPE_bool, TYPE_FLOAT);
		FN_4(enfn_average_two, TYPE_bool, EnfnAverageTwoNormals, TYPE_INODE, TYPE_INDEX, TYPE_INODE, TYPE_INDEX);

		// Selection set access
		FN_1(enfn_get_selection, TYPE_BITARRAY, EnfnGetSelection, TYPE_INODE);
		FN_2(enfn_set_selection, TYPE_bool, EnfnSetSelection, TYPE_BITARRAY_BR, TYPE_INODE);
		FN_4(enfn_select, TYPE_bool, EnfnSelect, TYPE_BITARRAY_BR, TYPE_bool, TYPE_bool, TYPE_INODE);
		VFN_3(enfn_convert_vertex_selection, EnfnConvertVertexSelection, TYPE_BITARRAY_BR, TYPE_BITARRAY_BR, TYPE_INODE);
		VFN_3(enfn_convert_edge_selection, EnfnConvertEdgeSelection, TYPE_BITARRAY_BR, TYPE_BITARRAY_BR, TYPE_INODE);
		VFN_3(enfn_convert_face_selection, EnfnConvertFaceSelection, TYPE_BITARRAY_BR, TYPE_BITARRAY_BR, TYPE_INODE);

		// Normal access
		FN_1(enfn_get_num_normals, TYPE_INT, EnfnGetNumNormals, TYPE_INODE);
		FNT_2(enfn_get_normal, TYPE_POINT3, EnfnGetNormal, TYPE_INDEX, TYPE_INODE);
		VFNT_3(enfn_set_normal, EnfnSetNormal, TYPE_INDEX, TYPE_POINT3_BR, TYPE_INODE);
		FN_2(enfn_get_normal_explicit, TYPE_bool, EnfnGetNormalExplicit, TYPE_INDEX, TYPE_INODE);
		VFN_3(enfn_set_normal_explicit, EnfnSetNormalExplicit, TYPE_INDEX, TYPE_bool, TYPE_INODE);

		// Normal face access
		FN_1(enfn_get_num_faces, TYPE_INT, EnfnGetNumFaces, TYPE_INODE);
		FN_2(enfn_get_face_degree, TYPE_INT, EnfnGetFaceDegree, TYPE_INDEX, TYPE_INODE);
		FN_3(enfn_get_normal_id, TYPE_INDEX, EnfnGetNormalID, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		VFN_4(enfn_set_normal_id, EnfnSetNormalID, TYPE_INDEX, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FN_3(enfn_get_face_normal_specified, TYPE_bool, EnfnGetFaceNormalSpecified, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		VFN_4(enfn_set_face_normal_specified, EnfnSetFaceNormalSpecified, TYPE_INDEX, TYPE_INDEX, TYPE_bool, TYPE_INODE);

		// Vertex access
		FN_1(enfn_get_num_vertices, TYPE_INT, EnfnGetNumVertices, TYPE_INODE);
		FN_3(enfn_get_vertex_id, TYPE_INDEX, EnfnGetVertexID, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FNT_2(enfn_get_vertex, TYPE_POINT3_BV, EnfnGetVertex, TYPE_INDEX, TYPE_INODE);

		// Edge access
		FN_1(enfn_get_num_edges, TYPE_INT, EnfnGetNumEdges, TYPE_INODE);
		FN_3(enfn_get_edge_id, TYPE_INDEX, EnfnGetEdgeID, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FN_3(enfn_get_face_edge_side, TYPE_INDEX, EnfnGetFaceEdgeSide, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FN_3(enfn_get_edge_vertex, TYPE_INDEX, EnfnGetEdgeVertex, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FN_3(enfn_get_edge_face, TYPE_INDEX, EnfnGetEdgeFace, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);
		FN_4(enfn_get_edge_normal, TYPE_INDEX, EnfnGetEdgeNormal, TYPE_INDEX, TYPE_INDEX, TYPE_INDEX, TYPE_INODE);

		// Cache rebuilders - shouldn't normally be necessary - above methods do this work as needed.
		VFN_1(enfn_rebuild_normals, EnfnRebuildNormals, TYPE_INODE);
		VFN_1(enfn_recompute_normals, EnfnRecomputeNormals, TYPE_INODE);
	END_FUNCTION_MAP
	#pragma warning(pop)

	FPInterfaceDesc *GetDesc ();

	// Selection level accessors:
	/*!   \remarks "Get" accessor for selection level - one of these
	values:\n\n
	EN_SL_OBJECT, EN_SL_NORMAL, EN_SL_VERTEX, EN_SL_EDGE, EN_SL_FACE\n\n
	*/
	virtual int EnfnGetSelLevel () { return EN_SL_OBJECT; }
	/*! \remarks "Set" accessor for selection level - one of these
	values:\n\n
	EN_SL_OBJECT, EN_SL_NORMAL, EN_SL_VERTEX, EN_SL_EDGE, EN_SL_FACE\n\n
	*/
	virtual void EnfnSetSelLevel (int selLevel) { }

	// Transform commands:
	/*!   \remarks Moves the ends of currently selected normals by the
	offset indicated - then renormalizes them to unit length.\n\n
	Note that the time is currently ignored, as the Edit Normals modifier is
	not yet animatable\n\n
	*/
	virtual bool EnfnMove (Point3& offset, TimeValue t) { return false; }
	/*!   \remarks Rotates currently selected normals by the rotation
	indicated.\n\n
	Note that the time is currently ignored, as the Edit Normals modifier is
	not yet animatable\n\n
	*/
	virtual bool EnfnRotate (Quat & rotation, TimeValue t) { return false; }

	// Operations:
	/*! \remarks Breaks the indicated normals into separate normals for each
	face.\n\n
	In 3ds Max 6, the Edit normals modifier had an average function added to
	its tool set. This allows the user to average the normals across the
	surface of the object(s). The toAverage parameter was added to this method
	to provide access to this new functionality.

	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	bool toAverage=false \n\n
	Default is false. When true, this parameter causes the normals to be
	averaged across the surface of the object(s). */
	/*! In 3ds Max 6, the Edit normals modifier had an average function added
	to its tool set. This  allows the user to average the normals across the
	surface of the objects(s). This method and the next four methods were added
	to an existing interface to provide access to this new functionality.
	\remarks Breaks the indicated normals into separate normals for each face.
	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.) */
	virtual bool EnfnBreakNormals (BitArray *normalSelection=NULL, INode *pNode=NULL, bool toAverage=false) { return false; }
	/*! \remarks Unifies the indicated normals so there's at most one normal
	per vertex. (Basically, causes normals to be shared across faces at a
	vertex.)\n\n
	In 3ds Max 6, the Edit normals modifier had an average function added to
	its tool set. This allows the user to average the normals across the
	surface of the objects(s). The toAverage parameter was added to this method
	to provide access to this new functionality.
	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	bool toAverage=false \n\n
	Default is false. When true, this parameter causes the normals to be
	averaged across the surface of the object(s). */
	virtual bool EnfnUnifyNormals (BitArray *normalSelection=NULL, INode *pNode=NULL, bool toAverage=false) { return false; }
	/*!   \remarks Makes the indicated normals completely non-explicit
	and unspecified. Generates a rebuild \& computation to determine the
	topology and direction of the newly unspecified normals.
	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals
	in.\n\n
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnResetNormals (BitArray *normalSelection=NULL, INode *pNode=NULL) { return false; }
	/*!   \remarks Specifies the normals indicated to be fixed to the
	faces they're currently used by.
	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnSpecifyNormals (BitArray *normalSelection=NULL, INode *pNode=NULL) { return false; }
	/*!   \remarks Make the indicated normals explicit, so they won't be
	based on underlying face normals.
	\par Parameters:
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnMakeNormalsExplicit (BitArray *normalSelection=NULL, INode *pNode=NULL) { return false; }
	/*!   \remarks Copies the indicated normal into the Edit Normals
	modifier's copy/paste buffer.
	\par Parameters:
	int normalID\n\n
	The ID of the normal we want to copy.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnCopyNormal (int normalID, INode *pNode=NULL) { return false; }
	/*!   \remarks Pastes the normal currently in the Edit Normals
	modifier's copy/paste buffer into the normals indicated, making them
	specified and explicit.
	\par Parameters:
	BitArray *normalSelection = NULL\n\n
	An optional selection set to use. If NULL, the current selection is
	used.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnPasteNormal (BitArray *normalSelection=NULL, INode *pNode=NULL) { return false; }
	/*! \remarks Added in 3ds Max 6 SDK.
	\par Parameters:
	bool useThresh=false\n\n
	float threshhold=0.0f\n\n
	BitArray *normalSelection=NULL\n\n
	An optional selection set to use. If NULL, the current selection is used.
	 */
	virtual bool EnfnAverageNormals (bool useThresh=false, float threshold=0.0f, BitArray *normalSelection=NULL, INode *pNode=NULL) { return false; }
	/*! \remarks Added in 3ds Max 6 SDK.
	\par Parameters:
	bool useThresh=false\n\n
	float threshhold=0.0f */
	virtual bool EnfnAverageGlobalNormals (bool useThresh=false, float threshold=0.0f) { return false; }
	/*! \remarks Added in 3ds Max 6 SDK.
	\par Parameters:
	INode *pNode1\n\n
	int normID1\n\n
	INode *pNode2\n\n
	int normID2\n\n
	*/
	virtual bool EnfnAverageTwoNormals (INode *pNode1, int normID1, INode *pNode2, int normID2) { return false; }

	// Selection accessors
	/*!   \remarks Returns a pointer to the current selection.
	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual BitArray *EnfnGetSelection (INode *pNode=NULL) { return NULL; }
	/*!   \remarks Sets the normal selection to the selection given.
	\par Parameters:
	BitArray\&selection\n\n
	The desired selection\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  True if the selection was changed; false if the new selection was
	the same as the old selection.\n\n
	  */
	virtual bool EnfnSetSelection (BitArray & selection, INode *pNode=NULL) { return false; }
	/*!   \remarks Selects, deselects, or inverts the selection of the
	normals indicated.
	\par Parameters:
	BitArray\&selection\n\n
	The normals whose selection we are trying to change.\n\n
	bool invert=false\n\n
	If true, indicates that the normals in \<selection\> should have their
	selection status inverted\n\n
	bool select=true\n\n
	If \<invert\> is true, this is ignored. Otherwise, if true, the normals
	indicated should be selected; if false, they should be deselected.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  True if the selection changed, false otherwise.\n\n
	*/
	virtual bool EnfnSelect (BitArray & selection, bool invert=false, bool select=true, INode *pNode=NULL) { return false; }
	/*!   \remarks Converts a vertex selection into a selection of
	normals, by setting bits on normals based at selected faces.
	\par Parameters:
	BitArray \& vertexSelection\n\n
	The vertex selection we're converting\n\n
	BitArray \& normalSelection\n\n
	The output normal selection\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  True if the selection changed, false otherwise.\n\n
	*/
	virtual void EnfnConvertVertexSelection (BitArray & vertexSelection, BitArray & normalSelection, INode *pNode=NULL) { }
	/*!   \remarks Converts an edge selection into a selection of
	normals, by setting bits for normals used on either end and either side of
	selected edges.
	\par Parameters:
	BitArray \& edgeSelection\n\n
	The edge selection we're converting\n\n
	BitArray \& normalSelection\n\n
	The output normal selection\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnConvertEdgeSelection (BitArray & edgeSelection, BitArray & normalSelection, INode *pNode=NULL) { }
	/*!   \remarks Converts a face selection into a selection of normals,
	by setting bits on normals used by selected faces.
	\par Parameters:
	BitArray \& faceSelection\n\n
	The face selection we're converting\n\n
	BitArray \& normalSelection\n\n
	The output normal selection\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	  */
	virtual void EnfnConvertFaceSelection (BitArray & faceSelection, BitArray & normalSelection, INode *pNode=NULL) { }

	// Accessors for the normals:
	/*!   \remarks Returns the current number of normals.
	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetNumNormals (INode *pNode=NULL) { return 0; }
	// Direct access to the normals themselves:
	/*!   \remarks Returns a pointer to the normal indicated.
	\par Parameters:
	int normalID\n\n
	The index of the normal\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	TimeValue t=0\n\n
	This is currently unused - but might be important if we add animation
	capabilities to Edit Normals in the future.\n\n
	*/
	virtual Point3 *EnfnGetNormal (int normalID, INode *pNode=NULL, TimeValue t=0) { return NULL; }
	/*!   \remarks Sets the indicated normal to a specific value. NOTE
	that this does not set the "explicitness" of this normal. If the normal is
	not made\n\n
	explicit, it will be restored to its default value the next time
	non-explicit normals are recomputed.
	\par Parameters:
	int normalID\n\n
	The index of the normal\n\n
	Point3 \& direction\n\n
	The desired normal direction. If not already normalized to a length of
	1,\n\n
	this method will normalize it.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	TimeValue t=0\n\n
	This is currently unused - but might be important if we add animation
	capabilities to Edit Normals in the future.\n\n
	*/
	virtual void EnfnSetNormal (int normalID, Point3 &direction, INode *pNode=NULL, TimeValue t=0) { }
	// Control whether a given normal is built from smoothing groups or set to an explicit value
	/*!   \remarks Controls whether a given normal is built from
	smoothing groups or set to an explicit value (Also makes the normal
	specified for all faces using this normal.)
	\par Parameters:
	int normalID\n\n
	The index of the normal\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	  */
	virtual bool EnfnGetNormalExplicit (int normID, INode *pNode=NULL) { return false; }
	// (Also makes the normal specified for all faces using this normal.)
	/*!   \remarks Makes the indicated normal explicit (or not). If
	setting the normal to explicit, it will also be set to "specified" on all
	faces using it. If\n\n
	setting it to non-explicit, the modifier recomputes all non-explicit
	normals to bring it up to date.
	\par Parameters:
	int normalID\n\n
	The index of the normal\n\n
	bool value\n\n
	True to make this normal explicit, false to make it non-explicit.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnSetNormalExplicit (int normID, bool value, INode *pNode=NULL) { }

	// Normals can be used by multiple faces, even at different vertices.
	// So we require access to both face and normal information.
	// Access to the normals that are assigned to each face:
	/*!   \remarks Returns the number of faces in the normal
	specification..
	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetNumFaces (INode *pNode=NULL) { return 0; }
	/*!   \remarks Returns the degree of the face indicated. (3 for
	triangle, 4 for quad, etc.)
	\par Parameters:
	int face\n\n
	The desired face.  INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetFaceDegree (int face, INode *pNode=NULL) { return 0; }
	/*!   \remarks Gets the index of the normal in the indicated corner
	of the indicated face
	\par Parameters:
	int face\n\n
	The desired face.\n\n
	int corner\n\n
	The desired corner, in the range of 0 to EnfnGetFaceDegree(face)-1.
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetNormalID (int face, int corner, INode *pNode=NULL) { return 0; }
	/*!   \remarks Sets the index of the normal in the indicated corner
	of the indicated\n\n
	face
	\par Parameters:
	int face\n\n
	The desired face.\n\n
	int corner\n\n
	The desired corner, in the range of 0 to EnfnGetFaceDegree(face)-1.\n\n
	int normalID\n\n
	The index of the desired normal\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnSetNormalID (int face, int corner, int normalID, INode *pNode=NULL) { }

	// Control whether a corner of a face uses an specified normal ID, or builds normals based on smoothing groups.
	/*!   \remarks Indicates whether a particular corner of a particular
	face is specified\n\n
	to use a specific normal or not.
	\par Parameters:
	int face\n\n
	The desired face.\n\n
	int corner\n\n
	The desired corner, in the range of 0 to EnfnGetFaceDegree(face)-1.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual bool EnfnGetFaceNormalSpecified (int face, int corner, INode *pNode=NULL) { return false; }
	/*!  \n\n
	  \remarks Controls whether a corner of a face uses a specific normal
	ID, or builds normals based on smoothing groups. If called to set a
	corner\n\n
	to unspecified, it generates a rebuild of nonspecified normals and a
	recomputation of nonexplicit normals at next update.
	\par Parameters:
	int face\n\n
	The desired face.\n\n
	int corner\n\n
	The desired corner, in the range of 0 to EnfnGetFaceDegree(face)-1.\n\n
	bool specified\n\n
	True to specify, false to set as unspecified.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnSetFaceNormalSpecified (int face, int corner, bool specified, INode *pNode=NULL) { }

	// Access to vertices - often important for proper normal handling to have access to the vertex the normal is based on.
	/*!   \remarks Returns the number of vertices in the current mesh
	cache..\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetNumVertices (INode *pNode=NULL) {return 0; }
	/*!   \remarks Returns the vertex used in a corner of a face, in the
	current mesh cache. (Useful for determining the "base" of the normal used
	in that corner of\n\n
	that face.)\n\n

	\par Parameters:
	int face\n\n
	The desired face.\n\n
	int corner\n\n
	The desired corner, in the range of 0 to EnfnGetFaceDegree(face)-1.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetVertexID (int face, int corner, INode *pNode=NULL) { return 0; }
	/*!   \remarks Returns the location of the vertex indicated (in the
	current mesh cache).\n\n

	\par Parameters:
	int vertexID\n\n
	The desired vertex.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	TimeValue t=0\n\n
	This is currently unused - but might be important if we add animation
	capabilities to Edit Normals in the future.\n\n
	*/
	virtual Point3 EnfnGetVertex (int vertexID, INode *pNode=NULL, TimeValue t=0) { return Point3(0,0,0); }

	// Access to edges
	/*!   \remarks Returns the number of edges in the current mesh
	cache.\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetNumEdges (INode *pNode=NULL) { return 0; }
	/*!   \remarks Returns the index of the edge used on a particular
	side of a particular face, in the current mesh cache\n\n

	\par Parameters:
	int faceIndex\n\n
	The desired face.\n\n
	int side\n\n
	The desired side, in the range of 0 to EnfnGetFaceDegree(faceIndex)-1.\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetEdgeID (int faceIndex, int sideIndex, INode *pNode=NULL) { return 0; }
	/*!   \remarks Tells you which side of the face a given edge is on.
	(Can be useful for getting normal and vertex information around the
	edge.)\n\n

	\par Parameters:
	int faceIndex\n\n
	The desired face.\n\n
	int edgeIndex\n\n
	The desired edge\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  The side of the face, in the range of 0 to
	EnfnGetFaceDegree(faceIndex)-1, or -1 if the edge was not found on this
	face\n\n
	*/
	virtual int EnfnGetFaceEdgeSide (int faceIndex, int edgeIndex, INode *pNode=NULL) { return 0; }
	/*!   \remarks Returns the vertex at the end of the edge.\n\n

	\par Parameters:
	int edgeIndex\n\n
	The desired edge.\n\n
	int end\n\n
	The desired end - either 0 or 1\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual int EnfnGetEdgeVertex (int edgeIndex, int end, INode *pNode=NULL) { return 0; }
	/*!   \remarks Tells you what face is on a particular side of a
	particular edge.\n\n

	\par Parameters:
	int edgeIndex\n\n
	The index of the edge in the MNMesh's edge array.\n\n
	int side\n\n
	Indicates which side of the edge you want the face from. (Values: 0 or
	1.)\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  The index of the desired face, or -1 if there's an error or if
	there is no face on that side.\n\n
	  */
	virtual int EnfnGetEdgeFace (int edgeIndex, int side, INode *pNode=NULL) { return 0; }
	/*!   \remarks Returns the normal associated with a particular end
	and side of this edge.\n\n

	\par Parameters:
	int edgeIndex\n\n
	The index of the edge in the MNMesh's edge array.\n\n
	int end\n\n
	Indicates which end of the edge should be used. (Values: 0 or 1.)\n\n
	int side\n\n
	Indicates which side of the edge should be used - the edge may have
	different normals used by the faces on either side. (Values: 0 or 1.)\n\n
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n

	\return  The index of the desired normal..\n\n
	*/
	virtual int EnfnGetEdgeNormal (int edgeIndex, int end, int side, INode *pNode=NULL) { return 0; }

	// Rebuild all non-specified normals from smoothing groups
	// Note that this can change the number of normals in some cases, and often changes their order.
	/*!   \remarks Forces the modifier to rebuild all non-specified
	normals from the face smoothing groups. Note that this can change the
	number of normals in some cases, and often changes their order.\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnRebuildNormals (INode *pNode=NULL) { }
	// Recompute - computes nonexplicit normals from face normals.
	/*!   \remarks Forces the modifier to recompute all non-explicit
	normals.\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	*/
	virtual void EnfnRecomputeNormals (INode *pNode=NULL) { }

	// Direct accessors to MNMesh and MNNormalSpec classes - unpublished for now.
	/*!   \remarks Returns a pointer to the cached copy of the MNMesh
	held by the EditNormalsModData. This is a "stripped-down" copy of the last
	mesh that was output by the modifier. It contains no maps, vertex or edge
	data, or normals. It's mainly used as a temporary "parent" to the
	localdata's MNNormalSpec in operations such as Display.\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	TimeValue t=0\n\n
	This is currently unused - but might be important if we add animation
	capabilities to Edit Normals in the future.\n\n
	  */
	virtual MNMesh *EnfnGetMesh (INode *pNode=NULL, TimeValue t=0) { return NULL; }
	/*!   \remarks Returns a pointer to the MNNormalSpec used by the
	EditNormalsModData. This MNNormalSpec is not part of any particular MNMesh,
	rather it's used as the local data of the EditNormalsMod to indicate what
	normals should be applied to the mesh coming up the pipe. Its "parent"
	pointer is generally set to NULL, and should be set to a mesh like the one
	you get from EnfnGetMesh before you do certain operations. (See class
	MNNormalSpec for details on which methods require an accurate "parent"
	pointer.\n\n

	\par Parameters:
	INode *pNode = NULL\n\n
	If the Edit Normals modifier is instanced across several nodes, this
	parameter can be used to indicate which node you mean to modify normals in.
	If you want to modify normals in all nodes, you must make a separate call
	for each node. If NULL, it assumes you want to modify normals in the
	"first" node. (This is fine if the modifier is only applied to one node, as
	is usually the case.)\n\n
	TimeValue t=0\n\n
	This is currently unused - but might be important if we add animation
	capabilities to Edit Normals in the future. */
	virtual MNNormalSpec *EnfnGetNormals (INode *pNode=NULL, TimeValue t=0) { return NULL; }
};
#pragma warning(pop) // C4100


text:
package org.apache.lucene.util.fst;

import java.io.IOException;

import org.apache.lucene.util.packed.PackedInts;
import org.apache.lucene.util.packed.PagedGrowableWriter;

// Used to dedup states (lookup already-frozen states)
final class NodeHash<T> {

  private PagedGrowableWriter table;
  private long count;
  private long mask;
  private final FST<T> fst;
  private final FST.Arc<T> scratchArc = new FST.Arc<>();
  private final FST.BytesReader in;

  public NodeHash(FST<T> fst, FST.BytesReader in) {
    table = new PagedGrowableWriter(16, 1<<27, 8, PackedInts.COMPACT);
    mask = 15;
    this.fst = fst;
    this.in = in;
  }

  private boolean nodesEqual(Builder.UnCompiledNode<T> node, long address) throws IOException {
    fst.readFirstRealTargetArc(address, scratchArc, in);
    if (scratchArc.bytesPerArc != 0 && node.numArcs != scratchArc.numArcs) {
      return false;
    }
    for(int arcUpto=0;arcUpto<node.numArcs;arcUpto++) {
      final Builder.Arc<T> arc = node.arcs[arcUpto];
      if (arc.label != scratchArc.label ||
          !arc.output.equals(scratchArc.output) ||
          ((Builder.CompiledNode) arc.target).node != scratchArc.target ||
          !arc.nextFinalOutput.equals(scratchArc.nextFinalOutput) ||
          arc.isFinal != scratchArc.isFinal()) {
        return false;
      }

      if (scratchArc.isLast()) {
        if (arcUpto == node.numArcs-1) {
          return true;
        } else {
          return false;
        }
      }
      fst.readNextRealArc(scratchArc, in);
    }

    return false;
  }

  // hash code for an unfrozen node.  This must be identical
  // to the frozen case (below)!!
  private long hash(Builder.UnCompiledNode<T> node) {
    final int PRIME = 31;
    //System.out.println("hash unfrozen");
    long h = 0;
    // TODO: maybe if number of arcs is high we can safely subsample?
    for(int arcIdx=0;arcIdx<node.numArcs;arcIdx++) {
      final Builder.Arc<T> arc = node.arcs[arcIdx];
      //System.out.println("  label=" + arc.label + " target=" + ((Builder.CompiledNode) arc.target).node + " h=" + h + " output=" + fst.outputs.outputToString(arc.output) + " isFinal?=" + arc.isFinal);
      h = PRIME * h + arc.label;
      long n = ((Builder.CompiledNode) arc.target).node;
      h = PRIME * h + (int) (n^(n>>32));
      h = PRIME * h + arc.output.hashCode();
      h = PRIME * h + arc.nextFinalOutput.hashCode();
      if (arc.isFinal) {
        h += 17;
      }
    }
    //System.out.println("  ret " + (h&Integer.MAX_VALUE));
    return h & Long.MAX_VALUE;
  }

  // hash code for a frozen node
  private long hash(long node) throws IOException {
    final int PRIME = 31;
    //System.out.println("hash frozen node=" + node);
    long h = 0;
    fst.readFirstRealTargetArc(node, scratchArc, in);
    while(true) {
      //System.out.println("  label=" + scratchArc.label + " target=" + scratchArc.target + " h=" + h + " output=" + fst.outputs.outputToString(scratchArc.output) + " next?=" + scratchArc.flag(4) + " final?=" + scratchArc.isFinal() + " pos=" + in.getPosition());
      h = PRIME * h + scratchArc.label;
      h = PRIME * h + (int) (scratchArc.target^(scratchArc.target>>32));
      h = PRIME * h + scratchArc.output.hashCode();
      h = PRIME * h + scratchArc.nextFinalOutput.hashCode();
      if (scratchArc.isFinal()) {
        h += 17;
      }
      if (scratchArc.isLast()) {
        break;
      }
      fst.readNextRealArc(scratchArc, in);
    }
    //System.out.println("  ret " + (h&Integer.MAX_VALUE));
    return h & Long.MAX_VALUE;
  }

  public long add(Builder<T> builder, Builder.UnCompiledNode<T> nodeIn) throws IOException {
    //System.out.println("hash: add count=" + count + " vs " + table.size() + " mask=" + mask);
    final long h = hash(nodeIn);
    long pos = h & mask;
    int c = 0;
    while(true) {
      final long v = table.get(pos);
      if (v == 0) {
        // freeze & add
        final long node = fst.addNode(builder, nodeIn);
        //System.out.println("  now freeze node=" + node);
        assert hash(node) == h : "frozenHash=" + hash(node) + " vs h=" + h;
        count++;
        table.set(pos, node);
        // Rehash at 2/3 occupancy:
        if (count > 2*table.size()/3) {
          rehash();
        }
        return node;
      } else if (nodesEqual(nodeIn, v)) {
        // same node is already here
        return v;
      }

      // quadratic probe
      pos = (pos + (++c)) & mask;
    }
  }

  // called only by rehash
  private void addNew(long address) throws IOException {
    long pos = hash(address) & mask;
    int c = 0;
    while(true) {
      if (table.get(pos) == 0) {
        table.set(pos, address);
        break;
      }

      // quadratic probe
      pos = (pos + (++c)) & mask;
    }
  }

  private void rehash() throws IOException {
    final PagedGrowableWriter oldTable = table;

    table = new PagedGrowableWriter(2*oldTable.size(), 1<<30, PackedInts.bitsRequired(count), PackedInts.COMPACT);
    mask = table.size()-1;
    for(long idx=0;idx<oldTable.size();idx++) {
      final long address = oldTable.get(idx);
      if (address != 0) {
        addNew(address);
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
AmazonWebServices
=================

Amazon Web Services Code Samples


text:
import os
import sys
import json
import shutil
import tempfile
from datetime import datetime

from cloudify.workflows import local
from cloudify.utils import LocalCommandRunner

from dsl_parser.parser import parse_from_path
from dsl_parser import constants as dsl_constants

from cloudify_cli import constants, env, exceptions, utils
from cloudify_cli.logger import get_logger
from cloudify_cli.config.config import CloudifyConfig

_ENV_NAME = 'local'

def initialize_blueprint(blueprint_path,
                         name,
                         storage=None,
                         install_plugins=False,
                         inputs=None,
                         resolver=None):
    logger = get_logger()

    logger.info('Initializing blueprint...')
    if install_plugins:
        _install_plugins(blueprint_path=blueprint_path)

    config = CloudifyConfig()
    return local.init_env(
        blueprint_path=blueprint_path,
        name=name,
        inputs=inputs,
        storage=storage,
        ignored_modules=constants.IGNORED_LOCAL_WORKFLOW_MODULES,
        provider_context=config.local_provider_context,
        resolver=resolver,
        validate_version=config.validate_definitions_version)

def _is_old_local_profile(storage_dir):
    try:
        entries = os.listdir(storage_dir)
    except (IOError, OSError):
        return False
    return (
        entries
        and 'blueprints' not in entries
        and 'deployments' not in entries
    )

def _update_local_profile(storage_dir):
    backup_dirname = '{0}_backup_{1}'.format(
        os.path.basename(storage_dir),
        datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S')
    )
    backup_target = os.path.join(
        os.path.dirname(storage_dir),
        backup_dirname,
    )
    shutil.copytree(storage_dir, backup_target)
    blueprints_dir = os.path.join(storage_dir, 'blueprints')
    deployments_dir = os.path.join(storage_dir, 'deployments')
    for blueprint_id in os.listdir(storage_dir):
        source_blueprint_dir = os.path.join(storage_dir, blueprint_id)
        with open(os.path.join(source_blueprint_dir, 'data')) as f:
            data = json.load(f)
        target_blueprint_dir = os.path.join(blueprints_dir, blueprint_id)
        target_resources_dir = os.path.join(target_blueprint_dir, 'resources')
        os.makedirs(target_blueprint_dir)

        blueprint_fn = os.path.join(target_blueprint_dir, 'blueprint.json')
        blueprint_data = data.copy()
        blueprint_data['id'] = blueprint_id
        blueprint_data['resources'] = target_resources_dir
        with open(blueprint_fn, 'w') as f:
            json.dump(blueprint_data, f)

        shutil.copy(
            os.path.join(source_blueprint_dir, 'payload'),
            os.path.join(target_blueprint_dir, 'payload'),
        )
        shutil.copytree(
            os.path.join(source_blueprint_dir, 'resources'),
            target_resources_dir,
        )
        target_deployment_dir = os.path.join(deployments_dir, blueprint_id)
        os.makedirs(target_deployment_dir)

        shutil.copy(
            os.path.join(source_blueprint_dir, 'executions'),
            os.path.join(target_deployment_dir, 'executions.json'),
        )

        source_instances_dir = os.path.join(
            source_blueprint_dir, 'node-instances')
        target_instances_dir = os.path.join(
            target_deployment_dir, 'node-instances')
        os.makedirs(target_instances_dir)
        for instance_fn in os.listdir(source_instances_dir):
            shutil.copy(
                os.path.join(source_instances_dir, instance_fn),
                os.path.join(target_instances_dir, instance_fn + '.json')
            )
        shutil.copytree(
            os.path.join(source_blueprint_dir, 'work'),
            os.path.join(target_deployment_dir, 'work'),
        )

        deployment_fn = os.path.join(target_deployment_dir, 'deployment.json')
        deployment_data = data.copy()
        deployment_data['id'] = blueprint_id
        deployment_data['blueprint_id'] = blueprint_id
        deployment_data['nodes'] = {
            n['id']: n for n in deployment_data['plan']['nodes']
        }
        with open(deployment_fn, 'w') as f:
            json.dump(deployment_data, f)

        shutil.rmtree(source_blueprint_dir)

def storage_dir():
    storage = os.path.join(env.PROFILES_DIR, _ENV_NAME)
    if _is_old_local_profile(storage):
        _update_local_profile(storage)
    return storage

def list_blueprints():
    blueprints = []
    storage = get_storage()
    try:
        bp_names = storage.blueprint_ids()
    except IOError as e:
        if e.errno != 2:  # file not found
            raise
        bp_names = []
    for bp_id in bp_names:
        bp = storage.get_blueprint(bp_id)
        blueprints.append({
            'id': bp_id,
            'description': bp['plan']['description'],
            'main_file_name': bp['blueprint_filename'],
            'created_at': bp['created_at'],
        })
    return blueprints

def get_storage():
    return local.FileStorage(storage_dir=storage_dir())

def load_env(blueprint_id):
    env = local.load_env(name=blueprint_id or 'local', storage=get_storage())
    if env is None:
        error = exceptions.CloudifyCliError('Please initialize a blueprint')
        error.possible_solutions = ["Run `cfy init BLUEPRINT_PATH`"]
        raise error
    return env

def blueprint_exists(blueprint_id):
    storage = local.FileStorage(storage_dir=storage_dir())
    return storage.get_blueprint(blueprint_id) is not None

def remove(blueprint_id):
    storage = get_storage()
    storage.remove_deployment(blueprint_id)
    storage.remove_blueprint(blueprint_id)

def _install_plugins(blueprint_path):
    requirements = create_requirements(blueprint_path=blueprint_path)
    logger = get_logger()

    if requirements:
        # Validate we are inside a virtual env
        if not utils.is_virtual_env():
            raise exceptions.CloudifyCliError(
                'You must be running inside a '
                'virtualenv to install blueprint plugins')

        runner = LocalCommandRunner(logger)
        # Dump the requirements to a file and let pip install it.
        # This will utilize pip's mechanism of cleanup in case an installation
        # fails.
        tmp_path = tempfile.mkstemp(suffix='.txt', prefix='requirements_')[1]
        utils.dump_to_file(collection=requirements, file_path=tmp_path)
        command_parts = [sys.executable, '-m', 'pip', 'install', '-r',
                         tmp_path]
        runner.run(command=' '.join(command_parts), stdout_pipe=False)
    else:
        logger.info('There are no plugins to install')

def create_requirements(blueprint_path):
    parsed_dsl = parse_from_path(dsl_file_path=blueprint_path)

    requirements = _plugins_to_requirements(
        blueprint_path=blueprint_path,
        plugins=parsed_dsl[dsl_constants.DEPLOYMENT_PLUGINS_TO_INSTALL])

    for node in parsed_dsl['nodes']:
        requirements.update(_plugins_to_requirements(
            blueprint_path=blueprint_path,
            plugins=node['plugins']))
    return requirements

def _plugins_to_requirements(blueprint_path, plugins):

    sources = set()
    for plugin in plugins:
        if plugin[dsl_constants.PLUGIN_INSTALL_KEY]:
            source = plugin[dsl_constants.PLUGIN_SOURCE_KEY]
            if not source:
                continue
            if '://' in source:
                # URL
                sources.add(source)
            else:
                # Local plugin (should reside under the 'plugins' dir)
                plugin_path = os.path.join(
                    os.path.abspath(os.path.dirname(blueprint_path)),
                    'plugins',
                    source)
                sources.add(plugin_path)
    return sources


text:
.respimg-inspector-overlay::before {
	display: none;
	padding: 20px;
	font-family: monospace;
	font-size: 9px;
	color: #fff;
	content: "tag: " attr(data-el-tag) " - width: " attr(data-img-width) "px - height: " attr(data-img-height) "px - natural width: " attr(data-img-natural-width) "px - natural height: " attr(data-img-natural-height) "px";
}

.respimg-inspector-overlay:hover::before {
	display: block;
}

.respimg-inspector-warning {
	background-color: rgba(252, 176, 49, .7);
}

.respimg-inspector-bad {
	background-color: rgba(252, 86, 61, .7);
}

.respimg-inspector-good {
	background-color: rgba(185, 237, 67, .7);
}


text:
#ifndef GESTURES_DEVICE_H_
#define GESTURES_DEVICE_H_

#include "int_array.h"
#include "input_event_array.h"

int init_uinput(int_array_t *keys);
int destroy_uinput(int fd);
void send_events(int fd, input_event_array_t *input_events);

#endif // GESTURES_DEVICE_H_


text:
var install = require('./install')
var purge   = require('./purge')
var link    = require('./link')

module.exports = init

function init(root, config, events, done) {
  link(root, config, events, function(err) {
    if (err) return done(err)

    install(root, config, events, function(err) {
      if (err) return done(err)

      purge(root, config, events, done)
    })
  })
}


text:
author: sivel
categories:
- Code
- One Liner
- PHP
- Snippet
- WordPress
date: '2010-10-06'
description: WordPress One Liner to Customize Author Permalink Redeux
slug: wordpress-one-liner-to-customize-author-permalink-redeux
title: WordPress One Liner to Customize Author Permalink Redeux
type: post
---

Nearly 2 years ago I wrote a [one liner][1] for someone in the WordPress IRC channel to [change the author permalink structure][2]. At the time I had not taken the time to really understand WP_Rewrite and as such didn't understand the implications of flushing the rewrite rules on each page load.

It is sufficient to say that since then, I have taken the time to understand it better and I am fully aware of the negative implications of performing flushes every time someone hits your site. For one thing the default behavior of `flush_rules()` is to also update the .htaccess file as well as updating the serialized array in your wp_options table that contain the internal WordPress rewrites. Assuming you are using a nasty permalink structure that starts with something like `%category%` or `%postname%` that serialized array can grow exponentially with the number of pages you have 1.

To make a long story sort, I have known that I should have changed the code for almost as long as the post has been published, but I was too lazy to do anything about it. It took a few carefully placed pokes and prods to get me moving, and as such I have updated the post to reflect the removal of using `flush_rules()`.

    Notes:

      Otto explained this a bit more in depth at http://ottopress.com/2010/category-in-permalinks-considered-harmful/ #

 [1]: http://sivel.net/category/code/one-liner/
 [2]: http://sivel.net/2008/12/author-permalink-one-liner/


text:
package com.tyq.jiemian.ui.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tyq.greendao.HaveRead;
import com.tyq.jiemian.R;
import com.tyq.jiemian.bean.User;
import com.tyq.jiemian.databinding.ActivityMainBinding;
import com.tyq.jiemian.ui.fragment.CollectFragment;
import com.tyq.jiemian.ui.fragment.EntertainmentFragment;
import com.tyq.jiemian.ui.fragment.MainFragment;
import com.tyq.jiemian.ui.fragment.TechnologicalFragment;
import com.tyq.jiemian.ui.fragment.ZhiHuFragment;
import com.tyq.jiemian.utils.DBUtils;
import com.tyq.jiemian.utils.UserProxy;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ImageView photo_iv;
    private TextView login_text;
    private ActionBarDrawerToggle mDrawerToggle;
    private ActivityMainBinding dataBinding;
    private EntertainmentFragment entertainmentFragment;
    private TechnologicalFragment technologicalFragment;
    private ZhiHuFragment zhiHuFragment;
    private MainFragment mainFragment;
    private CollectFragment collectFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initView();
        switchFragment(0);

    }

    public void switchFragment(int fragmentIndex) {
        entertainmentFragment = (EntertainmentFragment) getSupportFragmentManager().findFragmentById(R.id.entertainment);
        technologicalFragment = (TechnologicalFragment) getSupportFragmentManager().findFragmentById(R.id.technological);
        zhiHuFragment = (ZhiHuFragment) getSupportFragmentManager().findFragmentById(R.id.zhihu);
        mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.main_fragment);
        collectFragment = (CollectFragment) getSupportFragmentManager().findFragmentById(R.id.collect);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.hide(mainFragment);
        fragmentTransaction.hide(entertainmentFragment);
        fragmentTransaction.hide(technologicalFragment);
        fragmentTransaction.hide(zhiHuFragment);
        fragmentTransaction.hide(collectFragment);

        switch (fragmentIndex) {
            default:
                fragmentTransaction.show(mainFragment);
                break;
            case 1:
                fragmentTransaction.show(technologicalFragment);
                technologicalFragment.onTabSelected();
                break;
            case 2:
                fragmentTransaction.show(entertainmentFragment);
                entertainmentFragment.onTabSelected();
                break;
            case 3:
                fragmentTransaction.show(zhiHuFragment);
                zhiHuFragment.onTabSelected();
                break;
            case 4:
                fragmentTransaction.show(collectFragment);
                collectFragment.onTabSelected();
                break;
        }
        fragmentTransaction.commit();
    }

    private void initView() {

        setSupportActionBar(dataBinding.toolbar);
        dataBinding.toolbar.setNavigationIcon(R.drawable.menu);

        mDrawerToggle = new ActionBarDrawerToggle(this, dataBinding.drawLayout, dataBinding.toolbar, R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        dataBinding.drawLayout.addDrawerListener(mDrawerToggle);

        setupDrawerContent();
    }

    private void setupDrawerContent() {
        View header = LayoutInflater.from(this).inflate(R.layout.navigation_header, null);
        photo_iv = (ImageView) header.findViewById(R.id.photo_iv);
        photo_iv.setOnClickListener(v -> {

            if (!UserProxy.isLogin(MainActivity.this)) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            } else {
                startActivity(new Intent(MainActivity.this, PersonalActivity.class));
            }

        });
        login_text = (TextView) header.findViewById(R.id.login_tv);

        dataBinding.navigationView.addHeaderView(header);
        dataBinding.navigationView.setNavigationItemSelectedListener(item -> {

            switch (item.getItemId()) {
                case R.id.nav_home:
                    switchFragment(0);
                    dataBinding.toolbar.setTitle("首页");
                    break;
                case R.id.nav_technological:
                    switchFragment(1);
                    dataBinding.toolbar.setTitle("科技");
                    break;
                case R.id.nav_entertainment:
                    dataBinding.toolbar.setTitle("娱乐");
                    switchFragment(2);
                    break;
                case R.id.nav_settings:
                    startActivity(new Intent(MainActivity.this,SettingActivity.class));
                    break;
                case R.id.nav_personal:
                    startActivity(new Intent(MainActivity.this, PersonalActivity.class));
                    break;
                case R.id.nav_robot:
                    startActivity(new Intent(MainActivity.this,TRClientActivity.class));
                case R.id.nav_zhihu:
                    switchFragment(3);
                    dataBinding.toolbar.setTitle("知乎日报");
                    break;
                case R.id.nav_collect:
                    switchFragment(4);
                    dataBinding.toolbar.setTitle("我的收藏");
                    break;
            }
            item.setChecked(true);
            dataBinding.drawLayout.closeDrawers();
            return true;

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserProxy.isLogin(this)) {
            User user = UserProxy.getCurrentUser(this);
            if (null != user) {
                login_text.setText(user.getUsername());
            }
        }else{
            login_text.setText(R.string.null_login);
        }
    }
}


text:
package org.simpleflatmapper.util;

public interface BooleanProvider {
    boolean getBoolean();
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
        <XML>
            <Content>UPDATE</Content>
            <Clip>
                <ClipName>PRPEINF0485</ClipName>
                <TipoContenido>PROMOS ESPECIALES</TipoContenido>
                <Contenido><![CDATA[ COBERTURA GAZA]]></Contenido>
                <OriginalTitle></OriginalTitle>
                <Description> </Description>
                <Notes>a</Notes>
                <DurPrev></DurPrev>
                <Chapter></Chapter>
                <EndDate></EndDate>
                <EPG></EPG>
                <EPG_Content> </EPG_Content>
                <Segments>

                <Segment>
                    <SegTitle>1-1 INFORMATIVAS - COBERTURA GAZA</SegTitle>
                    <MediaID>PRPEINF0485</MediaID>
                    <Duration>00:00:39.00</Duration>
                    <SegNumber>1</SegNumber>
                    <ClipGroup>PROMO</ClipGroup>
                    <Description> </Description>
                </Segment>
            </Segments></Clip></XML>


text:
namespace Azure.Messaging.EventGrid.SystemEvents
{
    /// <summary> Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewCancelled event. </summary>
    public partial class WebSlotSwapWithPreviewCancelledEventData
    {
        /// <summary> Initializes a new instance of WebSlotSwapWithPreviewCancelledEventData. </summary>
        internal WebSlotSwapWithPreviewCancelledEventData()
        {
        }

        /// <summary> Initializes a new instance of WebSlotSwapWithPreviewCancelledEventData. </summary>
        /// <param name="appEventTypeDetail"> Detail of action on the app. </param>
        /// <param name="name"> name of the web site that had this event. </param>
        /// <param name="clientRequestId"> The client request id generated by the app service for the site API operation that triggered this event. </param>
        /// <param name="correlationRequestId"> The correlation request id generated by the app service for the site API operation that triggered this event. </param>
        /// <param name="requestId"> The request id generated by the app service for the site API operation that triggered this event. </param>
        /// <param name="address"> HTTP request URL of this operation. </param>
        /// <param name="verb"> HTTP verb of this operation. </param>
        internal WebSlotSwapWithPreviewCancelledEventData(AppEventTypeDetail appEventTypeDetail, string name, string clientRequestId, string correlationRequestId, string requestId, string address, string verb)
        {
            AppEventTypeDetail = appEventTypeDetail;
            Name = name;
            ClientRequestId = clientRequestId;
            CorrelationRequestId = correlationRequestId;
            RequestId = requestId;
            Address = address;
            Verb = verb;
        }

        /// <summary> Detail of action on the app. </summary>
        public AppEventTypeDetail AppEventTypeDetail { get; }
        /// <summary> name of the web site that had this event. </summary>
        public string Name { get; }
        /// <summary> The client request id generated by the app service for the site API operation that triggered this event. </summary>
        public string ClientRequestId { get; }
        /// <summary> The correlation request id generated by the app service for the site API operation that triggered this event. </summary>
        public string CorrelationRequestId { get; }
        /// <summary> The request id generated by the app service for the site API operation that triggered this event. </summary>
        public string RequestId { get; }
        /// <summary> HTTP request URL of this operation. </summary>
        public string Address { get; }
        /// <summary> HTTP verb of this operation. </summary>
        public string Verb { get; }
    }
}


text:
set -eu

echo Starting custom installation step

# These commands fail on Windows, but we don't really care.

mkdir -p "${DESTDIR}${MESON_INSTALL_PREFIX}/diiba/daaba"
touch "${DESTDIR}${MESON_INSTALL_PREFIX}/diiba/daaba/file.dat"

echo Finishing custom install step


text:
A geometria do cilindro é uma bem fácil de fazer.
Basta iterar da base até o topo criando os vértices e depois iterar novamente para criar as faces.

## Normais

Quando queremos iluminar o clindro temos que calcular as normais,
sendo que as das faces de baixo apontam todas para -z,
as da face de cima apontam todas para +z,
e as outras apontam na mesma direção que o próprio vértice em relação à origem.

## Texturização

Já para a texturização começam os problemas maiores.
A texturização da lateral do cilindro é bem tranquila,
basta mapear a textura linearmente usando coordenadas polares para u,
e coordenadas euclidianas para v.

É na base e no topo do cilindro que está 90% do trabalho.
O mapeamento das texturas nessas faces não pode ser linear.

### Mapeamento simples do círculo

Uma das formas de mapear consta em simplesmente ignorar a linearidade,
e mapear em forma de triângulos na textura, o que irá jogar fora uma parte
da textura.

![img-texture-mapping-circle.png](img-texture-mapping-circle.png)

Infelizmente isso não produz um resultado bom pois a textura fica
com várias descontinuidades ao ser mapeada:

![img-texture-mapping-circle-2.png](img-texture-mapping-circle-2.png)

**Veja o exemplo:** [Problemas com a face circular](9a-texture-wrong)

### Mapeamento com um anel e um círculo pequeno concêntricos

Tentei então fazer o mapeamento considerando a parte externa do círculo
como sendo um anel, cobrindo o centro do anel com um círculo menor,
de tal forma que as descontinuidades não pudessem ser percebidas.

![img-texture-mapping-circle-3.png](img-texture-mapping-circle-3.png)

Isso também tem problemas, agora a textura fica distorcida por causa
da forma com que os triângulos são mapeados:

![img-texture-mapping-circle-4.png](img-texture-mapping-circle-4.png)

**Veja o exemplo:** [Tentativa de correção com divisão em anel + círculo pequeno](9b-texture-wrong-2)

### Mapeamento com vários anéis e um círculo pequeno concêntricos

A melhor solução foi criar uma série de anéis concêntricos com um círculo
pequeno no centro. Isso ainda deixou alguns traços de distorção, como pode ser visto abaixo:

![img-texture-mapping-circle-5.png](img-texture-mapping-circle-5.jpg)

**Veja o exemplo:** [Correção com divisão em anéis de potências de fração](9c-texture)

### Mapeamento com vários anéis e um círculo pequeno concêntricos e textura alinhada

É possível mitigar essas distorções alinhando as divisões da textura com
os triângulos, o que elimina completamente o problema.

![img-texture-mapping-circle-6.png](img-texture-mapping-circle-6.png)

**Versão final:** [Texturizando o cilindro](9-cylider-texture)

Entretanto, nem toda textura é bonitinha como as que usei aqui.
No caso de texturas complicadas o jeito é subdividir em mais
e mais partes até que o problema seja imperceptível.

# Texture mapping

- [Texture](https://threejs.org/docs/#api/en/textures/Texture.repeat) @threejs.org
    - [three.js - webgl - basis texture loader](https://threejs.org/examples/#webgl_loader_texture_basis)
    - [Código no github](https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_texture_basis.html)
- [A brief introduction to texture mapping](https://discoverthreejs.com/book/1-first-steps/4-textures-intro/) @discoverthreejs.com
    - [Código no codesandbox](https://codesandbox.io/s/github/looeee/discoverthree.com-examples/tree/master/1-first-steps/4-textures-intro?from-embed)
- [Add Texture to custom three.js Geometry](https://stackoverflow.com/questions/55461909/add-texture-to-custom-three-js-geometry)

# UV Map Grids

Eu usei algumas texturas que não são minhas nestes exemplos.
Aqui estão algumas informações sobre como econtrá-las.

Pesquisas no Google por imagens:

- [Google image search: uv test texture](https://www.google.com/search?tbm=isch&q=uv+test+texture)
- [Google image search: uv map texture](https://www.google.com/search?tbm=isch&q=uv+map+texture)
- [Google image search: uv_test_bw](https://www.google.com/search?tbm=isch&q=uv_test_bw)

Sites com images para testes de mapeamento de texturas:

- [Texture Coordinates #UV Map Grids](http://wiki.polycount.com/wiki/Texture_Coordinates#UV_Map_Grids) @wiki.polycount.com
- [UV Checker Texture](https://www.oxpal.com/uv-checker-texture.html) @www.oxpal.com

# Texturização avançada

- [Dica Rápida: Como Renderizar para uma Textura Em Three.js](https://gamedevelopment.tutsplus.com/pt/tutorials/quick-tip-how-to-render-to-a-texture-in-threejs--cms-25686)
    - [Código no codepen](https://codepen.io/tutsplus/pen/eJGzzK)
- [Using ShaderToy shaders as texture](https://threejsfundamentals.org/threejs/lessons/threejs-shadertoy.html)


text:
require 'spec_helper'

describe "gitlab::packages" do
  let(:chef_run) { ChefSpec::Runner.new.converge("gitlab::packages") }

  describe "under ubuntu" do
    ["12.04", "10.04"].each do |version|
      let(:chef_run) { ChefSpec::Runner.new(platform: "ubuntu", version: version).converge("gitlab::packages") }

      before do
        # stubbing git commands because packages recipe requires gitlab::git
        stub_command("test -f #{Chef::Config['file_cache_path']}/git-2.0.0.zip").and_return(true)
        stub_command("git --version | grep 2.0.0").and_return(true)
        stub_command("git --version >/dev/null").and_return(true)
      end

      it "includes recipes from external cookbooks" do
        expect(chef_run).to include_recipe("apt::default")
        expect(chef_run).to_not include_recipe("yum::epel")
        expect(chef_run).to include_recipe("gitlab::git")
        expect(chef_run).to include_recipe("redisio::install")
        expect(chef_run).to include_recipe("redisio::enable")
      end

      it "installs all default packages" do
        packages = chef_run.node['gitlab']['packages']
        packages.each do |pkg|
          expect(chef_run).to install_package(pkg)
        end
      end

      it "should not install package git" do
        expect(chef_run).to_not install_package("git")
      end
    end
  end

  describe "under centos" do
    ["5.8", "6.4"].each do |version|
      let(:chef_run) { ChefSpec::Runner.new(platform: "centos", version: version).converge("gitlab::packages") }

      before do
        # stubbing git commands because packages recipe requires gitlab::git
        stub_command("test -f #{Chef::Config['file_cache_path']}/git-2.0.0.zip").and_return(true)
        stub_command("git --version | grep 2.0.0").and_return(true)
        stub_command("git --version >/dev/null").and_return(true)
      end

      it "includes recipes from external cookbooks" do
        expect(chef_run).to_not include_recipe("apt::default")
        expect(chef_run).to include_recipe("yum-epel::default")
        expect(chef_run).to include_recipe("gitlab::git")
        expect(chef_run).to include_recipe("redisio::install")
        expect(chef_run).to include_recipe("redisio::enable")
      end

      it "installs all default packages" do
        packages = chef_run.node['gitlab']['packages']
        packages.each do |pkg|
          expect(chef_run).to install_package(pkg)
        end
      end

      it "should not install package git" do
        expect(chef_run).to_not install_package("git")
      end
    end
  end
end


text:
/****************************************************************
 * org.omni.bean.support
 * 2015-8-7
 * E-Mail:omni_wx@163.com
 ***************************************************************/
package org.omni.bean.support;

import org.omni.exception.BaseRuntimeException;

// TODO: Auto-generated Javadoc
/**
 * The Class NoBeanDescriptorException.
 *
 * @author 王兴
 * @since v1.0
 * @date 2015-8-7
 */
public class NoBeanDescriptorException extends BaseRuntimeException {

	/**
	 * 构造一个新的 no bean descriptor exception 对象.
	 *
	 * @param message the message
	 */
	public NoBeanDescriptorException(String message) {
		super(message);
	}

	/**
	 * 构造一个新的 no bean descriptor exception 对象.
	 *
	 * @param message the message
	 * @param t the t
	 */
	public NoBeanDescriptorException(String message, Throwable t) {
		super(message, t);
	}
}


text:
package com.sonaive.v2ex.sync;

/**
 * Created by liutao on 12/25/14.
 */
public class ExceptionEvent {
    public String errMessage;

    public ExceptionEvent(String errMessage) {
        this.errMessage = errMessage;
    }
}


text:
package bt.torrent.selector;

import bt.torrent.PieceStatistics;

import java.util.Arrays;
import java.util.BitSet;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

public class RandomizedRarestFirstSelector extends RarestFirstSelector {
    private final Random random;
    private int[] iterationOrder = null;

    public RandomizedRarestFirstSelector() {
        this(null);
    }

    /**
     * Package local constructor for unit tests
     * @param random the random source
     */
    RandomizedRarestFirstSelector(Random random) {
        this.random = random;
    }

    @Override
    public void initSelector(int numPieces) {
        super.initSelector(numPieces);
        if (iterationOrder == null) {
            iterationOrder = generateIterationOrder(numPieces);
        }
    }

    private int[] generateIterationOrder(int numPieces) {
        int[] order = new int[numPieces];
        Arrays.setAll(order, i -> i);
        ShuffleUtils.shuffle(order, random == null ? ThreadLocalRandom.current() : this.random);
        return order;
    }

    @Override
    protected int getIterationIdx(int i) {
        return iterationOrder[i];
    }

    @Override
    public IntStream getNextPieces(BitSet relevantChunks, PieceStatistics pieceStatistics) {
        if (iterationOrder == null || pieceStatistics.getPiecesTotal() != iterationOrder.length) {
            throw new IllegalStateException("Selector was not initialized");
        }

        return super.getNextPieces(relevantChunks, pieceStatistics);
    }
}


text:
require "rails_helper"
require "generators/administrate/routes/routes_generator"
require "support/generator_spec_helpers"
require "support/constant_helpers"

describe Administrate::Generators::RoutesGenerator, :generator do
  before { stub_generator_dependencies }

  after { reset_routes }

  describe "routes" do
    it "populates default dashboards based on current ActiveRecord models" do
      routes = file("config/routes.rb")

      run_generator

      [:customers, :line_items, :orders, :products].each do |model|
        expect(routes).to contain("resources :#{model}")
      end
    end

    it "does not populate routes when no models exist" do
      routes = file("config/routes.rb")
      allow(ActiveRecord::Base).to receive(:descendants).and_return([])

      run_generator

      expect(routes).not_to contain("namespace :admin")
    end

    it "skips namespaced models with a warning" do
      routes = file("config/routes.rb")

      output = run_generator

      expect(routes).not_to contain("blog")
      expect(routes).not_to contain("post")

      expect(output).to include <<~MSG
        WARNING: Unable to generate a dashboard for Blog::Post.
                 Administrate does not yet support namespaced models.
      MSG
    end

    it "skips models that aren't backed by the database with a warning" do
      begin
        class ModelWithoutDBTable < ActiveRecord::Base; end
        routes = file("config/routes.rb")

        output = run_generator

        expect(routes).not_to contain("model_without_db_table")
        expect(output).to include("WARNING: Unable to generate a dashboard " \
          "for ModelWithoutDBTable.")
      ensure
        remove_constants :ModelWithoutDBTable
      end
    end

    it "skips models that don't have a named constant" do
      ActiveRecord::Migration.suppress_messages do
        ActiveRecord::Schema.define { create_table(:foos) }
      end
      _unnamed_model = Class.new(ActiveRecord::Base) do
        def self.table_name
          :foos
        end
      end

      run_generator

      routes = file("config/routes.rb")
      expect(routes).to have_correct_syntax
    end

    it "skips abstract models without a warning" do
      stub_generator_dependencies
      routes = file("config/routes.rb")

      begin
        class AbstractModel < ActiveRecord::Base
          self.abstract_class = true
        end

        output = run_generator

        expect(routes).not_to contain("abstract_model")
        expect(output).not_to include("WARNING: Unable to generate a "\
          "dashboard for AbstractModel")
      end
    end
  end

  it "creates a root route for the admin namespace" do
    routes = file("config/routes.rb")

    run_generator

    expect(routes).to contain('root to: "customers#index')
  end
end


text:
Because I lack **scruples** and some would even say **compassion**.
But that's just the image that I present to the world, because it **elicits** fear and respect, but it's not who I am.
Who cares about each **inning**, it's the final score that counts.
You you just want me to **leap off** a cliff and hope for a soft landing beneath?
> nobody except us.

It's **retribution**.
I stay awake at night thinking how much it would crush them, seeing their father **hauled off**.

## E 12
Frank found himself **shut out**.
**Exile**. I've managed to isolate the president to anyone, including myself.
**Counterterrorism** Director, that's a big **step up** from White House **Liaison**.
Not bad for a man **on the run**.
> why fight a losing battle.

## E 11
Underwood's **roadkill**, not you.
You're **fidgeting**.
To create some **ruckus** if nothing was going on?
**perjure** myself?
Should I find a way to **tip off** Dunbar? -

## E 10
They're upping the **ante**.
Probably the one that's **call all the shots**.  - No, I can **hold out** a little while longer.
What you're **insinuating** is not only wrong, it's **libelous**.
I neither have the time **nor** the **inclination** to negotiate with you!
I'm not trying to **pull strings**, but you could show a little gratitude.
I'm your **failsafe**, sir, but I can't be if you don't let me.
I'm not even here, long **layover** on my way to California.

## E 9
This hurt us both, but this is not my wound to **suture**.
We'll **put this behind us**, like we always done.
**defamation** & **slander**
Got a extra **apron** in the back.
If you're going to threaten me, you don't have to go to the trouble of **veiling** it.
**glock** pistol
I don't know anything about professional photography, I'm just a **flack**.
> dark was the night, gets me every night.

I'm your lobbyist, not your **henchman**.
Is there anything you wanna take? A **memento** or something?

## E 8
She and I don't talk, we had a **falling out**.
You seem **fixated** on this bridge, is something else going on here?
A bridge, that's a **drop in the bucket**.
I have no **ulterior** motive here.
We'll find time when the tension **subside**.
**square one**.
The **backstabbing** **vomit-inducing** bitch.
I want to **insulate** you from this.
You have people who are **looking out for** you: me, Linda,  your wife.
He wants to meet, but on his **turf** this time.
Come on, **live a little**, Frank.
**keep your ear to the ground**.

## E 7
You are **out of line**, Frank.
He's **got an axe to grind with me** and with the president.
You think he's **funneling** the money somehow?
I'm sorry I **lashed out** at you, Frank.
No, I was disrespectful and that was **uncalled** for.
My temper's **gotten away from me** these days.
The White House. All day long it's **buzzing**. And at this hour it's so... **desolate**.
You're such a **flirt**.
Arrange a **cushy** job offer for him somewhere.
He **stacked** congress. The majority I **whipped**.
there was **in black and white**.
what exactly **are you up to**?
When he was governor, it wasn't a **cakewalk**, but it was nothing like this.

## E 5
I'm totally **blanked**.
You won't need a **restraining order**.
I need to disrupt the **nuptials** and prevent a second marriage.
You don't think that's a little, I don't know, **brash**?
**Ward** isn't making things any easier. She wants a **notch in her belt**.
You can **conjure up** little gray men in 51 Area if you really want to.
I did my part, now **put it to bed**, Doug.

## E 4
Let's let this **grow on its own**.
I'm not big on **favors**.
That's a meeting they couldn't **sweep under the rug**.
Don't **inflate** your status, Mr. Stamper. You're nothing but a **errand boy**.
I don't want any more **back-channeling**.
You're using them for your own **personal ends**.
I won't **shed a tear**.
Your president will **ascribe** the failure to you. - I will take the risk.
I'm in the frontline and I can tell you **firsthand** that we're dealing with regime that is not being **forthright** and will **seize upon** the **faintest whiff of trepidation**.

## E 3
There are two types of vice presidents: **doormats** and **matadors**.
I want you to find him and **put him away**.
What's the **holdup**?
I'd stay away with **specifics**.
You want somebody to hold your hand and say it's OK to go on this fucking **goose chase**.
The tea party is a strong voice, and you're its **bullhorn**.
Maybe we shouldn't **point fingers** until there's a problem.
**Quorum** call
The president wanted to go **ballistic**, but I calmed him down.
I said don't worry, Frank would **pull this out**.
Did you? I don't blame you for being **two-faced**, Raymond.

## E 2
If he's not too busy trying to **sodomize** me.
The last thing we want to do is **rock the boat**.
I just mentioned **offhanded**.
I promised the president a **soft touch**. I can't intentionally break my promise.
We can't have an editor looking more **disheveled** than his reporters.
They know that I need **plausible** **deniability** for diplomatic purposes. - Why didn't you immediately **recant**?
In my experience with Chinese, **backpedaling** makes us look weak.
My contacts in Beijing tell me the minister of commerce is in a **tizzy**.
Either I **turn my back on** Cathy or I **stand behind** her.
And that walker doesn't **flinch** at the lack of respect it implies?
Let's **put this to bed**, Wes.
I'm guessing **Appropriations**. There is no way I can top that.
I want more than **ways and means**.
I've given you all I can. Whatever you decide is your **prerogative**.
The People's Republic of China will not be threatened by **derisive** and **unsubstantiated** claims.
I thought he might **balk** at talking a **handout** from me.

## E 1
**cuff links**
The problem with Buchwalter is, he's too **abrasive**. **No charm**.
I had to put my **hostess** on **waitstaff** duty.
I think there is a **foul play**.
Let's start this new chapter with a **clean slate**.
That sounds like a **cagey**, bullshit non-answer to me.
I'm on the **sidelines** for this one, Terry.
I can't imagine what **you're after**.
Service background, clean history, **photogenic**.


text:
arduino-gateway
===============

Simple C programm for Linux with MIPS hardware (fritzbox router) to pass a message on serial usb from network


text:
package org.basex.qt3ts.op;

import org.basex.tests.bxapi.*;
import org.basex.tests.qt3ts.*;

/**
 * Tests for the string-equal operation (not actually defined as such in F+O).
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Leo Woerteler
 */
@SuppressWarnings("all")
public class OpStringEqual extends QT3TestSet {

  /**
   *  A test whose essence is: `'equals' eq 'equals'`. .
   */
  @org.junit.Test
  public void kStringEqual1() {
    final XQuery query = new XQuery(
      "'equals' eq 'equals'",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  A test whose essence is: `'' eq ''`. .
   */
  @org.junit.Test
  public void kStringEqual2() {
    final XQuery query = new XQuery(
      "'' eq ''",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  A test whose essence is: `not('nada' eq 'equalness')`. .
   */
  @org.junit.Test
  public void kStringEqual3() {
    final XQuery query = new XQuery(
      "not('nada' eq 'equalness')",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  A test whose essence is: `'not' ne 'equal'`. .
   */
  @org.junit.Test
  public void kStringEqual4() {
    final XQuery query = new XQuery(
      "'not' ne 'equal'",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  A test whose essence is: `not('equal' ne 'equal')`. .
   */
  @org.junit.Test
  public void kStringEqual5() {
    final XQuery query = new XQuery(
      "not('equal' ne 'equal')",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  Compare two values returned from fn:lower-case(). .
   */
  @org.junit.Test
  public void k2StringEqual1() {
    final XQuery query = new XQuery(
      "declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; declare variable $vB as xs:string := (\"b string\", current-time(), string(<e>content</e>))[1] treat as xs:string; (lower-case($vA) eq lower-case($vB))",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  Compare two values returned from fn:upper-case(). .
   */
  @org.junit.Test
  public void k2StringEqual2() {
    final XQuery query = new XQuery(
      "declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; declare variable $vB as xs:string := (\"b string\", current-time(), string(<e>content</e>))[1] treat as xs:string; (upper-case($vA) eq upper-case($vB))",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  Compare two non-matching values returned from fn:lower-case(). .
   */
  @org.junit.Test
  public void k2StringEqual3() {
    final XQuery query = new XQuery(
      "declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; declare variable $vB as xs:string := (\"no match\", current-time(), string(<e>content</e>))[1] treat as xs:string; (lower-case($vA) eq lower-case($vB))",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }

  /**
   *  Compare two non-matching values returned from fn:upper-case(). .
   */
  @org.junit.Test
  public void k2StringEqual4() {
    final XQuery query = new XQuery(
      "declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; declare variable $vB as xs:string := (\"no match\", current-time(), string(<e>content</e>))[1] treat as xs:string; (upper-case($vA) eq upper-case($vB))",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }

  /**
   *  Compare two non-matching values returned from fn:lower-case() and fn:upper-case(). .
   */
  @org.junit.Test
  public void k2StringEqual5() {
    final XQuery query = new XQuery(
      "declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; declare variable $vB as xs:string := (\"b string\", current-time(), string(<e>content</e>))[1] treat as xs:string; (upper-case($vA) eq lower-case($vB))",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }

  /**
   *  Compare two non-matching values returned from fn:lower-case() and fn:upper-case(). .
   */
  @org.junit.Test
  public void k2StringEqual6() {
    final XQuery query = new XQuery(
      "\n" +
      "        declare variable $vA as xs:string := (\"B STRING\", current-time(), string(<e>content</e>))[1] treat as xs:string; \n" +
      "        declare variable $vB as xs:string := (\"b string\", current-time(), string(<e>content</e>))[1] treat as xs:string; \n" +
      "        (lower-case($vA) eq upper-case($vB))\n" +
      "      ",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }

  /**
   *  test string comparison .
   */
  @org.junit.Test
  public void cbclStringEqual001() {
    final XQuery query = new XQuery(
      "not(string(current-time()) eq \"now\")",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  test string comparison .
   */
  @org.junit.Test
  public void cbclStringEqual002() {
    final XQuery query = new XQuery(
      "not(string(current-time()) ne \"now\")",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }

  /**
   *  test string comparison .
   */
  @org.junit.Test
  public void cbclStringEqual003() {
    final XQuery query = new XQuery(
      "\n" +
      "        not(xs:untypedAtomic(current-time()) eq xs:untypedAtomic(\"now\"))\n" +
      "      ",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(true)
    );
  }

  /**
   *  test string comparison .
   */
  @org.junit.Test
  public void cbclStringEqual004() {
    final XQuery query = new XQuery(
      "\n" +
      "        not(xs:untypedAtomic(current-time()) ne xs:untypedAtomic(\"now\"))\n" +
      "      ",
      ctx);
    try {
      result = new QT3Result(query.value());
    } catch(final Throwable trw) {
      result = new QT3Result(trw);
    } finally {
      query.close();
    }
    test(
      assertBoolean(false)
    );
  }
}