Context:
using System;
using Server.Items;
using Server.Spells;
namespace Server.Engines.Craft
{
    public class DefInscription : CraftSystem
    {
        public override SkillName MainSkill
        {
            get
            {
                return SkillName.Inscribe;
            }
        }
        public override int GumpTitleNumber
        {
            get
            {
                return 1044009;
            }// INSCRIPTION MENU
        }
        private static CraftSystem m_CraftSystem;
        public static CraftSystem CraftSystem
        {
            get
            {
                if (m_CraftSystem == null)
                    m_CraftSystem = new DefInscription();
                return m_CraftSystem;
            }
        }
        public override double GetChanceAtMin(CraftItem item)
        {
            return 0.0; // 0%
        }
        private DefInscription()
            : base(1, 1, 1.25)// base( 1, 1, 3.0 )
        {
        }
        public override int CanCraft(Mobile from, BaseTool tool, Type typeItem)
        {
            if (tool == null || tool.Deleted || tool.UsesRemaining < 0)
                return 1044038; // You have worn out your tool!
            else if (!BaseTool.CheckAccessible(tool, from))
                return 1044263; // The tool must be on your person to use.
            if (typeItem != null)
            {
                object o = Activator.CreateInstance(typeItem);
                if (o is SpellScroll)
                {
                    SpellScroll scroll = (SpellScroll)o;
                    Spellbook book = Spellbook.Find(from, scroll.SpellID);
                    bool hasSpell = (book != null && book.HasSpell(scroll.SpellID));
                    scroll.Delete();
                    return (hasSpell ? 0 : 1042404); // null : You don't have that spell!
                }
                else if (o is Item)
                {
                    ((Item)o).Delete();
                }
            }
            return 0;
        }
        public override void PlayCraftEffect(Mobile from)
        {
            from.PlaySound(0x249);
        }
        private static readonly Type typeofSpellScroll = typeof(SpellScroll);
        public override int PlayEndingEffect(Mobile from, bool failed, bool lostMaterial, bool toolBroken, int quality, bool makersMark, CraftItem item)
        {
            if (toolBroken)
                from.SendLocalizedMessage(1044038); // You have worn out your tool
            if (!typeofSpellScroll.IsAssignableFrom(item.ItemType)) //  not a scroll
            {
                if (failed)
                {
                    if (lostMaterial)
                        return 1044043; // You failed to create the item, and some of your materials are lost.
                    else
                        return 1044157; // You failed to create the item, but no materials were lost.
                }
                else
                {
                    if (quality == 0)
                        return 502785; // You were barely able to make this item.  It's quality is below average.
                    else if (makersMark && quality == 2)
                        return 1044156; // You create an exceptional quality item and affix your maker's mark.
                    else if (quality == 2)
                        return 1044155; // You create an exceptional quality item.
                    else
                        return 1044154; // You create the item.
                }
            }
            else
            {
                if (failed)
                    return 501630; // You fail to inscribe the scroll, and the scroll is ruined.
                else
                    return 501629; // You inscribe the spell and put the scroll in your backpack.
            }
        }
        private int m_Circle, m_Mana;
        private enum Reg { BlackPearl, Bloodmoss, Garlic, Ginseng, MandrakeRoot, Nightshade, SulfurousAsh, SpidersSilk, BatWing, GraveDust, DaemonBlood, NoxCrystal, PigIron, Bone, DragonBlood, FertileDirt, DaemonBone }
        private readonly Type[] m_RegTypes = new Type[]
        {
            typeof( BlackPearl ),
			typeof( Bloodmoss ),
			typeof( Garlic ),
			typeof( Ginseng ),
			typeof( MandrakeRoot ),
			typeof( Nightshade ),
			typeof( SulfurousAsh ),
			typeof( SpidersSilk ),
            typeof( BatWing ),
            typeof( GraveDust ),
            typeof( DaemonBlood ),
            typeof( NoxCrystal ),
            typeof( PigIron ),
			typeof( Bone ),
			typeof( DragonBlood ),
			typeof( FertileDirt ),
			typeof( DaemonBone )
        };
        private int m_Index;
        private void AddSpell(Type type, params Reg[] regs)
        {
            double minSkill, maxSkill;
            int cliloc;
            switch (m_Circle)
            {
                default:
                case 0: minSkill = -25.0; maxSkill = 25.0; cliloc = 1111691; break;
                case 1: minSkill = -10.8; maxSkill = 39.2; cliloc = 1111691; break;
                case 2: minSkill = 03.5; maxSkill = 53.5; cliloc = 1111692; break;
                case 3: minSkill = 17.8; maxSkill = 67.8; cliloc = 1111692; break;
                case 4: minSkill = 32.1; maxSkill = 82.1; cliloc = 1111693; break;
                case 5: minSkill = 46.4; maxSkill = 96.4; cliloc = 1111693; break;
                case 6: minSkill = 60.7; maxSkill = 110.7; cliloc = 1111694; break;
                case 7: minSkill = 75.0; maxSkill = 125.0; cliloc = 1111694; break;
            }
            int index = AddCraft(type, cliloc, 1044381 + m_Index++, minSkill, maxSkill, m_RegTypes[(int)regs[0]], 1044353 + (int)regs[0], 1, 1044361 + (int)regs[0]);
            for (int i = 1; i < regs.Length; ++i)
                AddRes(index, m_RegTypes[(int)regs[i]], 1044353 + (int)regs[i], 1, 1044361 + (int)regs[i]);
            AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);
            SetManaReq(index, m_Mana);
        }
        private void AddNecroSpell(int spell, int mana, double minSkill, Type type, params Reg[] regs)
        {
            int id = GetRegLocalization(regs[0]);
            int index = AddCraft(type, 1061677, 1060509 + spell, minSkill, minSkill + 1.0, m_RegTypes[(int)regs[0]], id, 1, 501627);
            for (int i = 1; i < regs.Length; ++i)
            {
                id = GetRegLocalization(regs[i]);
                AddRes(index, m_RegTypes[(int)regs[0]], id, 1, 501627);
            }
            AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);
            SetManaReq(index, mana);
        }
        private void AddMysticSpell(int id, int mana, double minSkill, Type type, params Reg[] regs)
        {
            int index = AddCraft(type, 1111671, id, minSkill, minSkill + 1.0, m_RegTypes[(int)regs[0]], GetRegLocalization(regs[0]), 1, 501627);	//Yes, on OSI it's only 1.0 skill diff'.  Don't blame me, blame OSI.
            for (int i = 1; i < regs.Length; ++i)
                AddRes(index, m_RegTypes[(int)regs[0]], GetRegLocalization(regs[i]), 1, 501627);
            AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);
            SetManaReq(index, mana);
        }
        private int GetRegLocalization(Reg reg)
        {
            int loc = 0;
            switch (reg)
            {
                case Reg.BatWing: loc = 1023960; break;
                case Reg.GraveDust: loc = 1023983; break;
                case Reg.DaemonBlood: loc = 1023965; break;
                case Reg.NoxCrystal: loc = 1023982; break;
                case Reg.PigIron: loc = 1023978; break;
                case Reg.Bone: loc = 1023966; break;
                case Reg.DragonBlood: loc = 1023970; break;
                case Reg.FertileDirt: loc = 1023969; break;
                case Reg.DaemonBone: loc = 1023968; break;
            }
            if (loc == 0)
                loc = 1044353 + (int)reg;
            return loc;
        }
        public override void InitCraftList()
        {
            m_Circle = 0;
			m_Mana = 4;
			AddSpell( typeof( ReactiveArmorScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( ClumsyScroll ), Reg.Bloodmoss, Reg.Nightshade );
			AddSpell( typeof( CreateFoodScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot );
			AddSpell( typeof( FeeblemindScroll ), Reg.Nightshade, Reg.Ginseng );
			AddSpell( typeof( HealScroll ), Reg.Garlic, Reg.Ginseng, Reg.SpidersSilk );
			AddSpell( typeof( MagicArrowScroll ), Reg.SulfurousAsh );
			AddSpell( typeof( NightSightScroll ), Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( WeakenScroll ), Reg.Garlic, Reg.Nightshade );
			m_Circle = 1;
			m_Mana = 6;
			AddSpell( typeof( AgilityScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );
			AddSpell( typeof( CunningScroll ), Reg.Nightshade, Reg.MandrakeRoot );
			AddSpell( typeof( CureScroll ), Reg.Garlic, Reg.Ginseng );
			AddSpell( typeof( HarmScroll ), Reg.Nightshade, Reg.SpidersSilk );
			AddSpell( typeof( MagicTrapScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( MagicUnTrapScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );
			AddSpell( typeof( ProtectionScroll ), Reg.Garlic, Reg.Ginseng, Reg.SulfurousAsh );
			AddSpell( typeof( StrengthScroll ), Reg.Nightshade, Reg.MandrakeRoot );
			m_Circle = 2;
			m_Mana = 9;
			AddSpell( typeof( BlessScroll ), Reg.Garlic, Reg.MandrakeRoot );
			AddSpell( typeof( FireballScroll ), Reg.BlackPearl );
			AddSpell( typeof( MagicLockScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.SulfurousAsh );
			AddSpell( typeof( PoisonScroll ), Reg.Nightshade );
			AddSpell( typeof( TelekinisisScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );
			AddSpell( typeof( TeleportScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );
			AddSpell( typeof( UnlockScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );
			AddSpell( typeof( WallOfStoneScroll ), Reg.Bloodmoss, Reg.Garlic );
			m_Circle = 3;
			m_Mana = 11;
			AddSpell( typeof( ArchCureScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot );
			AddSpell( typeof( ArchProtectionScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( CurseScroll ), Reg.Garlic, Reg.Nightshade, Reg.SulfurousAsh );
			AddSpell( typeof( FireFieldScroll ), Reg.BlackPearl, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( GreaterHealScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.MandrakeRoot, Reg.Ginseng );
			AddSpell( typeof( LightningScroll ), Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( ManaDrainScroll ), Reg.BlackPearl, Reg.SpidersSilk, Reg.MandrakeRoot );
			AddSpell( typeof( RecallScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot );
			m_Circle = 4;
			m_Mana = 14;
			AddSpell( typeof( BladeSpiritsScroll ), Reg.BlackPearl, Reg.Nightshade, Reg.MandrakeRoot );
			AddSpell( typeof( DispelFieldScroll ), Reg.BlackPearl, Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( IncognitoScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.Nightshade );
			AddSpell( typeof( MagicReflectScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SpidersSilk );
			AddSpell( typeof( MindBlastScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.Nightshade, Reg.SulfurousAsh );
			AddSpell( typeof( ParalyzeScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SpidersSilk );
			AddSpell( typeof( PoisonFieldScroll ), Reg.BlackPearl, Reg.Nightshade, Reg.SpidersSilk );
			AddSpell( typeof( SummonCreatureScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			m_Circle = 5;
			m_Mana = 20;
			AddSpell( typeof( DispelScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( EnergyBoltScroll ), Reg.BlackPearl, Reg.Nightshade );
			AddSpell( typeof( ExplosionScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );
			AddSpell( typeof( InvisibilityScroll ), Reg.Bloodmoss, Reg.Nightshade );
			AddSpell( typeof( MarkScroll ), Reg.Bloodmoss, Reg.BlackPearl, Reg.MandrakeRoot );
			AddSpell( typeof( MassCurseScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.Nightshade, Reg.SulfurousAsh );
			AddSpell( typeof( ParalyzeFieldScroll ), Reg.BlackPearl, Reg.Ginseng, Reg.SpidersSilk );
			AddSpell( typeof( RevealScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );
			m_Circle = 6;
			m_Mana = 40;
			AddSpell( typeof( ChainLightningScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( EnergyFieldScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( FlamestrikeScroll ), Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( GateTravelScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( ManaVampireScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			AddSpell( typeof( MassDispelScroll ), Reg.BlackPearl, Reg.Garlic, Reg.MandrakeRoot, Reg.SulfurousAsh );
			AddSpell( typeof( MeteorSwarmScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SulfurousAsh, Reg.SpidersSilk );
			AddSpell( typeof( PolymorphScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			m_Circle = 7;
			m_Mana = 50;
			AddSpell( typeof( EarthquakeScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.Ginseng, Reg.SulfurousAsh );
			AddSpell( typeof( EnergyVortexScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.Nightshade );
			AddSpell( typeof( ResurrectionScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.Ginseng );
			AddSpell( typeof( SummonAirElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			AddSpell( typeof( SummonDaemonScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( SummonEarthElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			AddSpell( typeof( SummonFireElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );
			AddSpell( typeof( SummonWaterElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );
			if ( Core.SE )
			{
				AddNecroSpell(  0, 23, 39.6, typeof( AnimateDeadScroll ), Reg.GraveDust, Reg.DaemonBlood );
				AddNecroSpell(  1, 13, 19.6, typeof( BloodOathScroll ), Reg.DaemonBlood );
				AddNecroSpell(  2, 11, 19.6, typeof( CorpseSkinScroll ), Reg.BatWing, Reg.GraveDust );
				AddNecroSpell(  3,  7, 19.6, typeof( CurseWeaponScroll ), Reg.PigIron );
				AddNecroSpell(  4, 11, 19.6, typeof( EvilOmenScroll ), Reg.BatWing, Reg.NoxCrystal );
				AddNecroSpell(  5, 11, 39.6, typeof( HorrificBeastScroll ), Reg.BatWing, Reg.DaemonBlood );
				AddNecroSpell(  6, 23, 69.6, typeof( LichFormScroll ), Reg.GraveDust, Reg.DaemonBlood, Reg.NoxCrystal );
				AddNecroSpell(  7, 17, 29.6, typeof( MindRotScroll ), Reg.BatWing, Reg.DaemonBlood, Reg.PigIron );
				AddNecroSpell(  8,  5, 19.6, typeof( PainSpikeScroll ), Reg.GraveDust, Reg.PigIron );
				AddNecroSpell(  9, 17, 49.6, typeof( PoisonStrikeScroll ), Reg.NoxCrystal );
				AddNecroSpell( 10, 29, 64.6, typeof( StrangleScroll ), Reg.DaemonBlood, Reg.NoxCrystal );
				AddNecroSpell( 11, 17, 29.6, typeof( SummonFamiliarScroll ), Reg.BatWing, Reg.GraveDust, Reg.DaemonBlood );
				AddNecroSpell( 12, 23, 98.6, typeof( VampiricEmbraceScroll ), Reg.BatWing, Reg.NoxCrystal, Reg.PigIron );
				AddNecroSpell( 13, 41, 79.6, typeof( VengefulSpiritScroll ), Reg.BatWing, Reg.GraveDust, Reg.PigIron );
				AddNecroSpell( 14, 23, 59.6, typeof( WitherScroll ), Reg.GraveDust, Reg.NoxCrystal, Reg.PigIron );
				AddNecroSpell( 15, 17, 79.6, typeof( WraithFormScroll ), Reg.NoxCrystal, Reg.PigIron );
				AddNecroSpell( 16, 40, 79.6, typeof( ExorcismScroll ), Reg.NoxCrystal, Reg.GraveDust );
			}
            int index;

            if (Core.ML)
            {
                index = this.AddCraft(typeof(EnchantedSwitch), 1044294, 1072893, 45.0, 95.0, typeof(BlankScroll), 1044377, 1, 1044378);
                this.AddRes(index, typeof(SpidersSilk), 1044360, 1, 1044253);
                this.AddRes(index, typeof(BlackPearl), 1044353, 1, 1044253);
                this.AddRes(index, typeof(SwitchItem), 1073464, 1, 1044253);
                this.ForceNonExceptional(index);
                this.SetNeededExpansion(index, Expansion.ML);

                index = this.AddCraft(typeof(RunedPrism), 1044294, 1073465, 45.0, 95.0, typeof(BlankScroll), 1044377, 1, 1044378);
                this.AddRes(index, typeof(SpidersSilk), 1044360, 1, 1044253);

Answer: this.AddRes(index, typeof(BlackPearl), 1044353, 1, 1044253);


Context:
/*
Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016.  All rights reserved.
Contact:
     SYSTAP, LLC DBA Blazegraph
     2501 Calvert ST NW #106
     Washington, DC 20008
     licenses@blazegraph.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
/*
 * Created on Nov 14, 2008
 */
package com.bigdata.rdf.store;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import org.apache.log4j.Logger;
import org.openrdf.model.Statement;
import com.bigdata.journal.Journal;
import com.bigdata.journal.TimestampUtility;
import com.bigdata.rdf.axioms.Axioms;
import com.bigdata.rdf.axioms.NoAxioms;
import com.bigdata.rdf.internal.IV;
import com.bigdata.rdf.model.BigdataStatement;
import com.bigdata.rdf.rio.AbstractStatementBuffer.StatementBuffer2;
import com.bigdata.rdf.rio.StatementBuffer;
import com.bigdata.rdf.rules.BackchainAccessPath;
import com.bigdata.rdf.spo.ISPO;
import com.bigdata.rdf.spo.SPO;
import com.bigdata.rdf.store.AbstractTripleStore.Options;
import com.bigdata.relation.accesspath.BlockingBuffer;
import com.bigdata.relation.accesspath.IAccessPath;
import com.bigdata.striterator.IChunkedOrderedIterator;
import cutthecrap.utils.striterators.ICloseableIterator;
/**
 * Utility class for comparing graphs for equality, bulk export, etc.
 *
 * @author Bryan Thompson
 * @version $Id$
 */
public class TripleStoreUtility {

    protected static final Logger log = Logger.getLogger(TripleStoreUtility.class);
    /**
     * Compares two RDF graphs for equality (same statements).
     *

     * Note: This does NOT handle bnodes, which much be treated as variables for
     * RDF semantics.
     *

     * Note: Comparison is performed in terms of the externalized RDF
     * {@link Statement}s rather than {@link SPO}s since different graphs use
     * different lexicons.
     *

     * Note: If the graphs differ in which entailments they are storing in their
     * data and which entailments are backchained then you MUST make them
     * consistent in this regard. You can do this by exporting one or both using
     * {@link #bulkExport(AbstractTripleStore)}, which will cause all
     * entailments to be materialized in the returned {@link TempTripleStore}.
     *
     * @param expected
     *            One graph.
     *
     * @param actual
     *            Another graph with a consistent policy for forward and
     *            backchained entailments.
     *
     * @return true if all statements in the expected graph are in the actual
     *         graph and if the actual graph does not contain any statements
     *         that are not also in the expected graph.
     */
    public static boolean modelsEqual(AbstractTripleStore expected,
            AbstractTripleStore actual) throws Exception {
        //        int actualSize = 0;
        int notExpecting = 0;
        int expecting = 0;
        boolean sameStatements1 = true;
        {
            final ICloseableIterator<BigdataStatement> it = notFoundInTarget(actual, expected);
            try {
                while (it.hasNext()) {
                    final BigdataStatement stmt = it.next();
                    sameStatements1 = false;
                    log("Not expecting: " + stmt);
                    notExpecting++;
                    //                    actualSize++; // count #of statements actually visited.
                }
            } finally {
                it.close();
            }
            log("all the statements in actual in expected? " + sameStatements1);
        }
        //        int expectedSize = 0;
        boolean sameStatements2 = true;
        {
            final ICloseableIterator<BigdataStatement> it = notFoundInTarget(expected, actual);
            try {
                while (it.hasNext()) {
                    final BigdataStatement stmt = it.next();
                    sameStatements2 = false;
                    log("    Expecting: " + stmt);
                    expecting++;
                    //                    expectedSize++; // counts statements actually visited.
                }
            } finally {
                it.close();
            }
            //          BigdataStatementIterator it = expected.asStatementIterator(expected
            //          .getInferenceEngine().backchainIterator(
            //                  expected.getAccessPath(NULL, NULL, NULL)));
            //
            //            try {
            //
            //                while(it.hasNext()) {
            //
            //                BigdataStatement stmt = it.next();
            //
            //                if (!hasStatement(actual,//
            //                        (Resource)actual.getValueFactory().asValue(stmt.getSubject()),//
            //                        (URI)actual.getValueFactory().asValue(stmt.getPredicate()),//
            //                        (Value)actual.getValueFactory().asValue(stmt.getObject()))//
            //                        ) {
            //
            //                    sameStatements2 = false;
            //
            //                    log("    Expecting: " + stmt);
            //
            //                    expecting++;
            //
            //                }
            //
            //                expectedSize++; // counts statements actually visited.
            //
            //                }
            //
            //            } finally {
            //
            //                it.close();
            //
            //            }
            log("all the statements in expected in actual? " + sameStatements2);
        }
        //        final boolean sameSize = expectedSize == actualSize;
        //
        //        log("size of 'expected' repository: " + expectedSize);
        //
        //        log("size of 'actual'   repository: " + actualSize);
        log("# expected but not found: " + expecting);
        log("# not expected but found: " + notExpecting);
        return /*sameSize &&*/sameStatements1 && sameStatements2;
    }
    public static void log(final String s) {
    	if(log.isInfoEnabled())
    		log.info(s);
    }
    /**
     * Visits expected {@link BigdataStatement}s not found in actual.
     *
     * @param expected
     * @param actual
     *
     * @return An iterator visiting {@link BigdataStatement}s present in
     *         expected but not found in actual.
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static ICloseableIterator<BigdataStatement> notFoundInTarget(//
            final AbstractTripleStore expected,//
            final AbstractTripleStore actual //
    ) throws InterruptedException, ExecutionException {
        /*
         * The source access path is a full scan of the SPO index.
         */
        final IAccessPath<ISPO> expectedAccessPath = expected.getAccessPath(
                (IV) null, (IV) null, (IV) null);
        /*
         * Efficiently convert SPOs to BigdataStatements (externalizes
         * statements).
         */
        final BigdataStatementIterator itr2 = expected
                .asStatementIterator(expectedAccessPath.iterator());
        final int capacity = 100000;
        final BlockingBuffer<BigdataStatement> buffer = new BlockingBuffer<BigdataStatement>(
                capacity);
        final StatementBuffer2<Statement, BigdataStatement> sb = new StatementBuffer2<Statement, BigdataStatement>(
                actual, true/* readOnly */, capacity) {
            /**
             * Statements not found in [actual] are written on the
             * BlockingBuffer.
             *
             * @return The #of statements that were not found.
             */
            @Override
            protected int handleProcessedStatements(final BigdataStatement[] a) {
                if (log.isInfoEnabled())
                    log.info("Given " + a.length + " statements");
                // bulk filter for statements not present in [actual].
                final IChunkedOrderedIterator<ISPO> notFoundItr = actual
                        .bulkFilterStatements(a, a.length, false/* present */);
                int nnotFound = 0;
                try {
                    while (notFoundItr.hasNext()) {
                        final ISPO notFoundStmt = notFoundItr.next();
                        if (log.isInfoEnabled())
                            log.info("Not found: " + notFoundStmt);
                        buffer.add((BigdataStatement) notFoundStmt);
                        nnotFound++;
                    }
                } finally {
                    notFoundItr.close();
                }
                if (log.isInfoEnabled())
                    log.info("Given " + a.length + " statements, " + nnotFound
                            + " of them were not found");
                return nnotFound;
            }
        };
        /**
         * Run task. The task consumes externalized statements from [expected]
         * and writes statements not found in [actual] onto the blocking buffer.
         */
        final Callable<Void> myTask = new Callable<Void>() {
                public Void call() throws Exception {
                    try {
                        while (itr2.hasNext()) {
                            // a statement from the source db.
                            final BigdataStatement stmt = itr2.next();
                            // if (log.isInfoEnabled()) log.info("Source: "
                            // + stmt);
                            // add to the buffer.
                            sb.add(stmt);
                        }
                    } finally {
                        itr2.close();
                    }
                    /*
                     * Flush everything in the StatementBuffer so that it
                     * shows up in the BlockingBuffer's iterator().
                     */
                    final long nnotFound = sb.flush();
                    if (log.isInfoEnabled())
                        log.info("Flushed: #notFound=" + nnotFound);
                    return null;
                }
        };
        /**
         * @see
         *      BlockingBuffer.close() does not unblock threads
         */
        // Wrap computation as FutureTask.
        final FutureTask<Void> ft = new FutureTask<Void>(myTask);

        // Set Future on BlockingBuffer.
        buffer.setFuture(ft);

        // Submit computation for evaluation.
        actual.getExecutorService().submit(ft);
        /*
         * Return iterator reading "not found" statements from the blocking
         * buffer.
         */
        return buffer.iterator();
    }
    /**
     * Exports all statements found in the data and all backchained entailments
     * for the db into a {@link TempTripleStore}. This may be used to
     * compare graphs purely in their data by pre-generation of all backchained
     * entailments.
     *

     * Note: This is not a general purpose bulk export as it uses only a single
     * access path, does not store justifications, and does retain the
     * {@link Axioms} model of the source graph. This method is specifically
     * designed to export "just the triples", e.g., for purposes of comparison.
     *
     * @param db
     *            The source database.
     *
     * @return The {@link TempTripleStore}.
     */
    static public TempTripleStore bulkExport(final AbstractTripleStore db) {

        final Properties properties = new Properties();

        properties.setProperty(Options.ONE_ACCESS_PATH, "true");

        properties.setProperty(Options.JUSTIFY, "false");

        properties.setProperty(Options.AXIOMS_CLASS,
                NoAxioms.class.getName());
        properties.setProperty(Options.STATEMENT_IDENTIFIERS,
                "" + db.isStatementIdentifiers());
        final TempTripleStore tmp = new TempTripleStore(properties);
        try {
			final StatementBuffer<Statement> sb = new StatementBuffer<Statement>(tmp, 100000/* capacity */,
					10/* queueCapacity */);
            final IV NULL = null;
            final IChunkedOrderedIterator<ISPO> itr1 = new BackchainAccessPath(
                    db, db.getAccessPath(NULL, NULL, NULL)).iterator();
            final BigdataStatementIterator itr2 = db.asStatementIterator(itr1);
            try {
                while (itr2.hasNext()) {
                    final BigdataStatement stmt = itr2.next();
                    sb.add(stmt);
                }
            } finally {
                itr2.close();
            }
            sb.flush();
        } catch (Throwable t) {
            tmp.close();
            throw new RuntimeException(t);
        }

        return tmp;

    }
    /**
     * Compares two {@link LocalTripleStore}s
     *
     * @param args
     *            filename filename (namespace)
     *
     * @throws Exception
     *
     * @todo namespace for each, could be the same file, and timestamp for each.
     *
     * @todo handle other database modes.
     */
    public static void main(String[] args) throws Exception {

Answer: if (args.length < 2 || args.length > 3) {


Context:
package org.ovirt.engine.core.bll;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import org.junit.Test;
import org.mockito.Mockito;
import org.ovirt.engine.core.bll.context.EngineContext;
import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolManagerStrategy;
import org.ovirt.engine.core.common.action.ImportVmTemplateParameters;
import org.ovirt.engine.core.common.businessentities.BusinessEntitiesDefinitions;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.utils.ValidationUtils;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.StorageDomainDao;
import org.ovirt.engine.core.dao.StorageDomainStaticDao;
import org.ovirt.engine.core.dao.StoragePoolDao;
import org.ovirt.engine.core.dao.VmTemplateDao;
import org.springframework.util.Assert;
public class ImportVmTemplateCommandTest {
    @Test
    public void insufficientDiskSpace() {
        // The following is enough since the validation is mocked out anyway. Just want to make sure the flow in CDA is correct.
        // Full test for the scenarios is done in the inherited class.
        final ImportVmTemplateCommand command = setupVolumeFormatAndTypeTest(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);
        doReturn(false).when(command).validateSpaceRequirements(anyList());
        assertFalse(command.canDoAction());
    }
    @Test
    public void validVolumeFormatAndTypeCombinations() throws Exception {
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.NFS);
        assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.NFS);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.ISCSI);
        assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.ISCSI);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.ISCSI);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.FCP);
        assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.FCP);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.FCP);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.LOCALFS);
        assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.LOCALFS);
        assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.LOCALFS);
    }
    @Test
    public void invalidVolumeFormatAndTypeCombinations() throws Exception {
        assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.NFS);
        assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.ISCSI);
        assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.FCP);
        assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.LOCALFS);
        assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.NFS);
        assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.ISCSI);
        assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.FCP);
        assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.LOCALFS);
        assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.NFS);
        assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.ISCSI);
        assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.FCP);
        assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.LOCALFS);
    }
    public void testValidateUniqueTemplateNameInDC() {
        ImportVmTemplateCommand command =
                setupVolumeFormatAndTypeTest(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);
        doReturn(true).when(command).isVmTemplateWithSameNameExist();
        CanDoActionTestUtils.runAndAssertCanDoActionFailure(command,
                EngineMessage.VM_CANNOT_IMPORT_TEMPLATE_NAME_EXISTS);
    }
    private void assertValidVolumeInfoCombination(VolumeFormat volumeFormat,
            VolumeType volumeType,
            StorageType storageType) {
        CanDoActionTestUtils.runAndAssertCanDoActionSuccess(
                setupVolumeFormatAndTypeTest(volumeFormat, volumeType, storageType));
    }
    private void assertInvalidVolumeInfoCombination(VolumeFormat volumeFormat,
            VolumeType volumeType,
            StorageType storageType) {
        CanDoActionTestUtils.runAndAssertCanDoActionFailure(
                setupVolumeFormatAndTypeTest(volumeFormat, volumeType, storageType),
                EngineMessage.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED);
    }
    /**
     * Prepare a command for testing the given volume format and type combination.
     *
     * @param volumeFormat
     *            The volume format of the "imported" image.
     * @param volumeType
     *            The volume type of the "imported" image.
     * @param storageType
     *            The target domain's storage type.
     * @return The command which can be called to test the given combination.
     */
    private ImportVmTemplateCommand setupVolumeFormatAndTypeTest(
            VolumeFormat volumeFormat,
            VolumeType volumeType,
            StorageType storageType) {
        ImportVmTemplateCommand command = spy(new ImportVmTemplateCommand(createParameters()){
            @Override
            public VDSGroup getVdsGroup() {
                return null;
            }
        });
        Backend backend = mock(Backend.class);
        doReturn(backend).when(command).getBackend();
        doReturn(false).when(command).isVmTemplateWithSameNameExist();
        doReturn(true).when(command).isVDSGroupCompatible();
        doReturn(true).when(command).validateNoDuplicateDiskImages(any(Iterable.class));
        mockGetTemplatesFromExportDomainQuery(volumeFormat, volumeType, command);
        mockStorageDomainStatic(command, storageType);
        doReturn(mock(VmTemplateDao.class)).when(command).getVmTemplateDao();
        doReturn(Mockito.mock(MacPoolManagerStrategy.class)).when(command).getMacPool();
        mockStoragePool(command);
        mockStorageDomains(command);
        doReturn(true).when(command).setAndValidateDiskProfiles();
        doReturn(true).when(command).setAndValidateCpuProfile();
        doReturn(true).when(command).validateSpaceRequirements(anyList());
        return command;
    }
    private static void mockStorageDomains(ImportVmTemplateCommand command) {
        final ImportVmTemplateParameters parameters = command.getParameters();
        final StorageDomainDao dao = mock(StorageDomainDao.class);
        final StorageDomain srcDomain = new StorageDomain();
        srcDomain.setStorageDomainType(StorageDomainType.ImportExport);
        srcDomain.setStatus(StorageDomainStatus.Active);
        when(dao.getForStoragePool(parameters.getSourceDomainId(), parameters.getStoragePoolId()))
                .thenReturn(srcDomain);
        final StorageDomain destDomain = new StorageDomain();
        destDomain.setStorageDomainType(StorageDomainType.Data);
        destDomain.setUsedDiskSize(0);
        destDomain.setAvailableDiskSize(1000);
        destDomain.setStatus(StorageDomainStatus.Active);
        when(dao.getForStoragePool(parameters.getDestDomainId(), parameters.getStoragePoolId()))
                .thenReturn(destDomain);
        doReturn(dao).when(command).getStorageDomainDao();
    }
    private static void mockStoragePool(ImportVmTemplateCommand command) {
        final StoragePoolDao dao = mock(StoragePoolDao.class);
        final StoragePool pool = new StoragePool();
        pool.setId(command.getParameters().getStoragePoolId());
        when(dao.get(any(Guid.class))).thenReturn(pool);
        doReturn(dao).when(command).getStoragePoolDao();
    }
    private static void mockGetTemplatesFromExportDomainQuery(VolumeFormat volumeFormat,
            VolumeType volumeType,
            ImportVmTemplateCommand command) {
        final VdcQueryReturnValue result = new VdcQueryReturnValue();
        Map<VmTemplate, List<DiskImage>> resultMap = new HashMap<VmTemplate, List<DiskImage>>();
        DiskImage image = new DiskImage();
        image.setActualSizeInBytes(2);
        image.setvolumeFormat(volumeFormat);
        image.setVolumeType(volumeType);
        resultMap.put(new VmTemplate(), Arrays.asList(image));
        result.setReturnValue(resultMap);
        result.setSucceeded(true);
        when(command.getBackend().runInternalQuery(eq(VdcQueryType.GetTemplatesFromExportDomain),
                any(VdcQueryParametersBase.class), any(EngineContext.class))).thenReturn(result);
    }
    private static void mockStorageDomainStatic(
            ImportVmTemplateCommand command,
            StorageType storageType) {
        final StorageDomainStaticDao dao = mock(StorageDomainStaticDao.class);
        final StorageDomainStatic domain = new StorageDomainStatic();
        domain.setStorageType(storageType);
        when(dao.get(any(Guid.class))).thenReturn(domain);
        doReturn(dao).when(command).getStorageDomainStaticDao();
    }
    protected ImportVmTemplateParameters createParameters() {
        VmTemplate t = new VmTemplate();
        t.setName("testTemplate");
        final ImportVmTemplateParameters p =
                new ImportVmTemplateParameters(Guid.newGuid(), Guid.newGuid(), Guid.newGuid(), Guid.newGuid(), t);
        return p;
    }
    private final String string100 = "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321" +
            "0987654321";
    @Test
    public void testValidateNameSizeImportAsCloned() {
        checkTemplateName(true, string100);
    }
    @Test
    public void testDoNotValidateNameSizeImport() {
        checkTemplateName(false, string100);
    }
    @Test
    public void testValidateNameSpecialCharImportAsCloned() {
        checkTemplateName(true, "vm_$%$#%#$");
    }
    @Test
    public void testDoNotValidateNameSpecialCharImport() {
        checkTemplateName(false, "vm_$%$#%#$");
    }
    private void checkTemplateName(boolean isImportAsNewEntity, String name) {

Answer: ImportVmTemplateParameters parameters = createParameters();


Context:
// This file has been generated by the GUI designer. Do not modify.
namespace BlinkStickClient
{
	public partial class CpuEditorWidget
	{
		private global::Gtk.VBox vbox2;

		private global::Gtk.Frame frame1;

		private global::Gtk.Alignment GtkAlignment;

		private global::Gtk.VBox vbox3;

		private global::Gtk.RadioButton radiobuttonMonitor;

		private global::Gtk.Label labelMonitorHint;

		private global::Gtk.RadioButton radiobuttonAlert;

		private global::Gtk.Label labelAlertHint;

		private global::Gtk.Alignment alignment2;

		private global::Gtk.Table table1;

		private global::Gtk.ComboBox comboboxTriggerType;

		private global::Gtk.Label labelCheck;

		private global::Gtk.Label labelMinutes;

		private global::Gtk.Label labelPercent;

		private global::Gtk.Label labelWhen;

		private global::Gtk.SpinButton spinbuttonCheckPeriod;

		private global::Gtk.SpinButton spinbuttonCpuPercent;

		private global::Gtk.Label GtkLabel2;

		private global::Gtk.Frame frame3;

		private global::Gtk.Alignment GtkAlignment1;

		private global::Gtk.HBox hbox1;

		private global::Gtk.Label labelCurrentValue;

		private global::Gtk.Button buttonRefresh;

		private global::Gtk.Label GtkLabel3;
		protected virtual void Build ()
		{
			global::Stetic.Gui.Initialize (this);
			// Widget BlinkStickClient.CpuEditorWidget
			global::Stetic.BinContainer.Attach (this);
			this.Name = "BlinkStickClient.CpuEditorWidget";
			// Container child BlinkStickClient.CpuEditorWidget.Gtk.Container+ContainerChild
			this.vbox2 = new global::Gtk.VBox ();
			this.vbox2.Name = "vbox2";
			this.vbox2.Spacing = 6;
			// Container child vbox2.Gtk.Box+BoxChild
			this.frame1 = new global::Gtk.Frame ();
			this.frame1.Name = "frame1";
			this.frame1.ShadowType = ((global::Gtk.ShadowType)(0));
			// Container child frame1.Gtk.Container+ContainerChild
			this.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
			this.GtkAlignment.Name = "GtkAlignment";
			this.GtkAlignment.LeftPadding = ((uint)(12));
			this.GtkAlignment.TopPadding = ((uint)(12));
			// Container child GtkAlignment.Gtk.Container+ContainerChild
			this.vbox3 = new global::Gtk.VBox ();
			this.vbox3.Name = "vbox3";
			this.vbox3.Spacing = 6;
			// Container child vbox3.Gtk.Box+BoxChild
			this.radiobuttonMonitor = new global::Gtk.RadioButton (global::Mono.Unix.Catalog.GetString ("Monitor"));
			this.radiobuttonMonitor.CanFocus = true;
			this.radiobuttonMonitor.Name = "radiobuttonMonitor";
			this.radiobuttonMonitor.DrawIndicator = true;
			this.radiobuttonMonitor.UseUnderline = true;
			this.radiobuttonMonitor.Group = new global::GLib.SList (global::System.IntPtr.Zero);
			this.vbox3.Add (this.radiobuttonMonitor);
			global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.radiobuttonMonitor]));
			w1.Position = 0;
			w1.Expand = false;
			w1.Fill = false;
			// Container child vbox3.Gtk.Box+BoxChild
			this.labelMonitorHint = new global::Gtk.Label ();
			this.labelMonitorHint.Name = "labelMonitorHint";
			this.labelMonitorHint.Xpad = 20;
			this.labelMonitorHint.Xalign = 0F;
			this.labelMonitorHint.LabelProp = global::Mono.Unix.Catalog.GetString ("<i>Uses pattern\'s first animation color to display 0% and second to transition to" +
			" 100%. Define a pattern with two Set Color animations for this to take effect</i" +
			">");
			this.labelMonitorHint.UseMarkup = true;
			this.labelMonitorHint.Wrap = true;
			this.vbox3.Add (this.labelMonitorHint);
			global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.labelMonitorHint]));
			w2.Position = 1;
			w2.Expand = false;
			w2.Fill = false;
			// Container child vbox3.Gtk.Box+BoxChild
			this.radiobuttonAlert = new global::Gtk.RadioButton (global::Mono.Unix.Catalog.GetString ("Alert"));
			this.radiobuttonAlert.CanFocus = true;
			this.radiobuttonAlert.Name = "radiobuttonAlert";
			this.radiobuttonAlert.DrawIndicator = true;
			this.radiobuttonAlert.UseUnderline = true;
			this.radiobuttonAlert.Group = this.radiobuttonMonitor.Group;
			this.vbox3.Add (this.radiobuttonAlert);
			global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.radiobuttonAlert]));
			w3.Position = 2;
			w3.Expand = false;
			w3.Fill = false;
			// Container child vbox3.Gtk.Box+BoxChild
			this.labelAlertHint = new global::Gtk.Label ();
			this.labelAlertHint.Name = "labelAlertHint";
			this.labelAlertHint.Xpad = 20;
			this.labelAlertHint.Xalign = 0F;
			this.labelAlertHint.LabelProp = global::Mono.Unix.Catalog.GetString ("<i>When event occurs triggers pattern playback</i>");
			this.labelAlertHint.UseMarkup = true;
			this.labelAlertHint.Wrap = true;
			this.vbox3.Add (this.labelAlertHint);
			global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.labelAlertHint]));
			w4.Position = 3;
			w4.Expand = false;
			w4.Fill = false;
			// Container child vbox3.Gtk.Box+BoxChild
			this.alignment2 = new global::Gtk.Alignment (0.5F, 0.5F, 1F, 1F);
			this.alignment2.Name = "alignment2";
			this.alignment2.LeftPadding = ((uint)(40));
			// Container child alignment2.Gtk.Container+ContainerChild
			this.table1 = new global::Gtk.Table (((uint)(2)), ((uint)(5)), false);
			this.table1.Name = "table1";
			this.table1.RowSpacing = ((uint)(6));
			this.table1.ColumnSpacing = ((uint)(6));
			// Container child table1.Gtk.Table+TableChild
			this.comboboxTriggerType = global::Gtk.ComboBox.NewText ();
			this.comboboxTriggerType.AppendText (global::Mono.Unix.Catalog.GetString ("increases above"));
			this.comboboxTriggerType.AppendText (global::Mono.Unix.Catalog.GetString ("drops below"));
			this.comboboxTriggerType.Name = "comboboxTriggerType";
			this.table1.Add (this.comboboxTriggerType);
			global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table1 [this.comboboxTriggerType]));
			w5.LeftAttach = ((uint)(1));
			w5.RightAttach = ((uint)(2));
			w5.XOptions = ((global::Gtk.AttachOptions)(4));
			w5.YOptions = ((global::Gtk.AttachOptions)(4));
			// Container child table1.Gtk.Table+TableChild
			this.labelCheck = new global::Gtk.Label ();
			this.labelCheck.Name = "labelCheck";
			this.labelCheck.Xalign = 1F;
			this.labelCheck.LabelProp = global::Mono.Unix.Catalog.GetString ("Check every");
			this.table1.Add (this.labelCheck);
			global::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelCheck]));
			w6.TopAttach = ((uint)(1));
			w6.BottomAttach = ((uint)(2));
			w6.XOptions = ((global::Gtk.AttachOptions)(4));
			w6.YOptions = ((global::Gtk.AttachOptions)(4));
			// Container child table1.Gtk.Table+TableChild
			this.labelMinutes = new global::Gtk.Label ();
			this.labelMinutes.Name = "labelMinutes";
			this.labelMinutes.Xalign = 0F;
			this.labelMinutes.LabelProp = global::Mono.Unix.Catalog.GetString ("min");
			this.table1.Add (this.labelMinutes);
			global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelMinutes]));
			w7.TopAttach = ((uint)(1));
			w7.BottomAttach = ((uint)(2));
			w7.LeftAttach = ((uint)(3));
			w7.RightAttach = ((uint)(4));
			w7.XOptions = ((global::Gtk.AttachOptions)(4));
			w7.YOptions = ((global::Gtk.AttachOptions)(4));
			// Container child table1.Gtk.Table+TableChild
			this.labelPercent = new global::Gtk.Label ();
			this.labelPercent.Name = "labelPercent";
			this.labelPercent.Xalign = 0F;
			this.labelPercent.LabelProp = global::Mono.Unix.Catalog.GetString ("%");
			this.table1.Add (this.labelPercent);
			global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelPercent]));
			w8.LeftAttach = ((uint)(3));
			w8.RightAttach = ((uint)(4));
			w8.XOptions = ((global::Gtk.AttachOptions)(4));
			w8.YOptions = ((global::Gtk.AttachOptions)(4));
			// Container child table1.Gtk.Table+TableChild
			this.labelWhen = new global::Gtk.Label ();
			this.labelWhen.Name = "labelWhen";
			this.labelWhen.Xalign = 1F;
			this.labelWhen.LabelProp = global::Mono.Unix.Catalog.GetString ("When");
			this.table1.Add (this.labelWhen);
			global::Gtk.Table.TableChild w9 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelWhen]));
			w9.XOptions = ((global::Gtk.AttachOptions)(4));
			w9.YOptions = ((global::Gtk.AttachOptions)(4));
			// Container child table1.Gtk.Table+TableChild
			this.spinbuttonCheckPeriod = new global::Gtk.SpinButton (1D, 120D, 1D);
			this.spinbuttonCheckPeriod.CanFocus = true;
			this.spinbuttonCheckPeriod.Name = "spinbuttonCheckPeriod";
			this.spinbuttonCheckPeriod.Adjustment.PageIncrement = 10D;
			this.spinbuttonCheckPeriod.ClimbRate = 1D;
			this.spinbuttonCheckPeriod.Numeric = true;
			this.spinbuttonCheckPeriod.Value = 1D;
			this.table1.Add (this.spinbuttonCheckPeriod);
			global::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table1 [this.spinbuttonCheckPeriod]));

Answer: w10.TopAttach = ((uint)(1));


Context:
/*
 * Copyright (c) 2003-2009 jMonkeyEngine
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.jme.scene;
import java.io.IOException;
import java.io.Serializable;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Logger;
import com.jme.intersection.CollisionResults;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.system.JmeException;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.geom.BufferUtils;
/**
 * QuadMesh defines a geometry mesh. This mesh defines a three
 * dimensional object via a collection of points, colors, normals and textures.
 * The points are referenced via a indices array. This array instructs the
 * renderer the order in which to draw the points, creating quads based on the mode set.
 *
 * @author Joshua Slack
 * @version $Id: $
 */
public class QuadMesh extends Geometry implements Serializable {
    private static final Logger logger = Logger.getLogger(QuadMesh.class
            .getName());
    private static final long serialVersionUID = 2L;
    public enum Mode {
        /**
         * Every four vertices referenced by the indexbuffer will be considered
         * a stand-alone quad.
         */
        Quads,
        /**
         * The first four vertices referenced by the indexbuffer create a
         * triangle, from there, every two additional vertices are paired with
         * the two preceding vertices to make a new quad.
         */
        Strip;
    }
    protected transient IntBuffer indexBuffer;
    protected Mode mode = Mode.Quads;
    protected int quadQuantity;
    private static Vector3f[] quads;
    /**
     * Empty Constructor to be used internally only.
     */
    public QuadMesh() {
        super();
    }
    /**
     * Constructor instantiates a new TriMesh object.
     *
     * @param name
     *            the name of the scene element. This is required for
     *            identification and comparision purposes.
     */
    public QuadMesh(String name) {
        super(name);
    }
    /**
     * Constructor instantiates a new TriMesh object. Provided
     * are the attributes that make up the mesh all attributes may be null,
     * except for vertices and indices.
     *
     * @param name
     *            the name of the scene element. This is required for
     *            identification and comparision purposes.
     * @param vertices
     *            the vertices of the geometry.
     * @param normal
     *            the normals of the geometry.
     * @param color
     *            the colors of the geometry.
     * @param coords
     *            the texture coordinates of the mesh.
     * @param indices
     *            the indices of the vertex array.
     */
    public QuadMesh(String name, FloatBuffer vertices, FloatBuffer normal,
            FloatBuffer color, TexCoords coords, IntBuffer indices) {
        super(name);
        reconstruct(vertices, normal, color, coords);
        if (null == indices) {
            logger.severe("Indices may not be null.");
            throw new JmeException("Indices may not be null.");
        }
        setIndexBuffer(indices);
        logger.info("QuadMesh created.");
    }
    /**
     * Recreates the geometric information of this TriMesh from scratch. The
     * index and vertex array must not be null, but the others may be. Every 3
     * indices define an index in the vertices array that
     * refrences a vertex of a triangle.
     *
     * @param vertices
     *            The vertex information for this TriMesh.
     * @param normal
     *            The normal information for this TriMesh.
     * @param color
     *            The color information for this TriMesh.
     * @param coords
     *            The texture information for this TriMesh.
     * @param indices
     *            The index information for this TriMesh.
     */
    public void reconstruct(FloatBuffer vertices, FloatBuffer normal,
            FloatBuffer color, TexCoords coords, IntBuffer indices) {
        super.reconstruct(vertices, normal, color, coords);
        if (null == indices) {
            logger.severe("Indices may not be null.");
            throw new JmeException("Indices may not be null.");
        }
        setIndexBuffer(indices);
    }
    public void setMode(Mode mode) {
        this.mode = mode;
    }
    public Mode getMode() {
        return mode;
    }
    public IntBuffer getIndexBuffer() {
        return indexBuffer;
    }
    public void setIndexBuffer(IntBuffer indices) {
        this.indexBuffer = indices;
        recalcQuadQuantity();
    }
    protected void recalcQuadQuantity() {
        if (indexBuffer == null) {
            quadQuantity = 0;
            return;
        }

        switch (mode) {
            case Quads:
                quadQuantity = indexBuffer.limit() / 4;
                break;
            case Strip:
                quadQuantity = indexBuffer.limit() / 2 - 1;
                break;
        }
    }
    /**
     * Returns the number of triangles contained in this mesh.
     */
    public int getQuadCount() {
        return quadQuantity;
    }
    public void setQuadQuantity(int quadQuantity) {
        this.quadQuantity = quadQuantity;
    }
    /**
     * Clears the buffers of this QuadMesh. The buffers include its indexBuffer
     * only.
     */
    public void clearBuffers() {
        super.clearBuffers();
        setIndexBuffer(null);
    }

    public static Vector3f[] getQuads() {
        return quads;
    }
    public static void setQuads(Vector3f[] quads) {
        QuadMesh.quads = quads;
    }
    /**
     * Stores in the storage array the indices of quad
     * i. If i is an invalid index, or if
     * storage.length<4, then nothing happens
     *
     * @param i
     *            The index of the quad to get.
     * @param storage
     *            The array that will hold the i's indexes.
     */
    public void getQuad(int i, int[] storage) {
        if (i < getQuadCount() && storage.length >= 4) {
            IntBuffer indices = getIndexBuffer();
            storage[0] = indices.get(getVertIndex(i, 0));
            storage[1] = indices.get(getVertIndex(i, 1));
            storage[2] = indices.get(getVertIndex(i, 2));
            storage[3] = indices.get(getVertIndex(i, 3));
        }
    }
    /**
     * Stores in the vertices array the vertex values of quad
     * i. If i is an invalid quad index,
     * nothing happens.
     *
     * @param i
     * @param vertices
     */
    public void getQuad(int i, Vector3f[] vertices) {
        if (i < getQuadCount() && i >= 0) {
            for (int x = 0; x < 4; x++) {
                if (vertices[x] == null)

Answer: vertices[x] = new Vector3f();


Context:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace mRemoteNG.UI.TaskDialog
{
  public sealed partial class CommandButton : Button
  {
    //--------------------------------------------------------------------------------
    #region PRIVATE MEMBERS
    //--------------------------------------------------------------------------------
    Image imgArrow1;
    Image imgArrow2;
    const int LEFT_MARGIN = 10;
    const int TOP_MARGIN = 10;
    const int ARROW_WIDTH = 19;
    enum eButtonState { Normal, MouseOver, Down }
    eButtonState m_State = eButtonState.Normal;
    #endregion
    //--------------------------------------------------------------------------------
    #region PUBLIC PROPERTIES
    //--------------------------------------------------------------------------------
    // Override this to make sure the control is invalidated (repainted) when 'Text' is changed
    public override string Text
    {
      get { return base.Text; }
      set
      {
        base.Text = value;
        if (m_autoHeight)
          Height = GetBestHeight();
        Invalidate();
      }
    }
    // SmallFont is the font used for secondary lines
      private Font SmallFont { get; set; }
      // AutoHeight determines whether the button automatically resizes itself to fit the Text
    bool m_autoHeight = true;
    [Browsable(true)]
    [Category("Behavior")]
    [DefaultValue(true)]
    public bool AutoHeight { get { return m_autoHeight; } set { m_autoHeight = value; if (m_autoHeight) Invalidate(); } }
    #endregion
    //--------------------------------------------------------------------------------
    #region CONSTRUCTOR
    //--------------------------------------------------------------------------------
    public CommandButton()
    {
      InitializeComponent();
      Font = new Font("Segoe UI", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0);
      SmallFont = new Font("Segoe UI", 8F, FontStyle.Regular, GraphicsUnit.Point, 0);
    }

    #endregion
    //--------------------------------------------------------------------------------
    #region PUBLIC ROUTINES
    //--------------------------------------------------------------------------------
    public int GetBestHeight()
    {
      return (TOP_MARGIN * 2) + (int)GetSmallTextSizeF().Height + (int)GetLargeTextSizeF().Height;
    }
    #endregion
    //--------------------------------------------------------------------------------
    #region PRIVATE ROUTINES
    //--------------------------------------------------------------------------------
    string GetLargeText()
    {
      string[] lines = Text.Split('\n');
      return lines[0];
    }
    string GetSmallText()
    {
      if (Text.IndexOf('\n') < 0)
        return "";
      string s = Text;
      string[] lines = s.Split('\n');
      s = "";
      for (int i = 1; i < lines.Length; i++)
        s += lines[i] + "\n";
      return s.Trim('\n');
    }
    SizeF GetLargeTextSizeF()
    {
      int x = LEFT_MARGIN + ARROW_WIDTH + 5;
      SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F);  // presume RIGHT_MARGIN = LEFT_MARGIN
      Graphics g = Graphics.FromHwnd(Handle);
      SizeF textSize = g.MeasureString(GetLargeText(), Font, mzSize);
      return textSize;
    }
    SizeF GetSmallTextSizeF()
    {
      string s = GetSmallText();
      if (s == "") return new SizeF(0, 0);
      int x = LEFT_MARGIN + ARROW_WIDTH + 8; // <- indent small text slightly more
      SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F);  // presume RIGHT_MARGIN = LEFT_MARGIN
      Graphics g = Graphics.FromHwnd(Handle);
      SizeF textSize = g.MeasureString(s, SmallFont, mzSize);
      return textSize;
    }
    #endregion
    //--------------------------------------------------------------------------------
    #region OVERRIDEs
    //--------------------------------------------------------------------------------
    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        imgArrow1 = Resources.green_arrow1;
        imgArrow2 = Resources.green_arrow2;
    }
    //--------------------------------------------------------------------------------
    protected override void OnPaint(PaintEventArgs e)
    {
      e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
      e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
      LinearGradientBrush brush;
      LinearGradientMode mode = LinearGradientMode.Vertical;
      Rectangle newRect = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
      Color text_color = SystemColors.WindowText;
      Image img = imgArrow1;

      if (Enabled)
      {
        switch (m_State)
        {
          case eButtonState.Normal:
            e.Graphics.FillRectangle(SystemBrushes.Control, newRect);
                e.Graphics.DrawRectangle(Focused ? new Pen(Color.Silver, 1) : new Pen(SystemColors.Control, 1), newRect);
                text_color = Color.DarkBlue;
            break;
          case eButtonState.MouseOver:
            brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);
            e.Graphics.FillRectangle(brush, newRect);
            e.Graphics.DrawRectangle(new Pen(Color.Silver, 1), newRect);
            img = imgArrow2;
            text_color = Color.Blue;
            break;
          case eButtonState.Down:
            brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);
            e.Graphics.FillRectangle(brush, newRect);
            e.Graphics.DrawRectangle(new Pen(Color.DarkGray, 1), newRect);
            text_color = Color.DarkBlue;
            break;
        }
      }
      else
      {
        brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);
        e.Graphics.FillRectangle(brush, newRect);
        e.Graphics.DrawRectangle(new Pen(Color.DarkGray, 1), newRect);
        text_color = Color.DarkBlue;
      }
      string largetext = GetLargeText();
      string smalltext = GetSmallText();
      SizeF szL = GetLargeTextSizeF();
      //e.Graphics.DrawString(largetext, base.Font, new SolidBrush(text_color), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN), szL));
      TextRenderer.DrawText(e.Graphics, largetext, Font, new Rectangle(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN, (int)szL.Width, (int)szL.Height), text_color, TextFormatFlags.Default);
      if (smalltext != "")
      {
        SizeF szS = GetSmallTextSizeF();
        e.Graphics.DrawString(smalltext, SmallFont, new SolidBrush(text_color), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 8, TOP_MARGIN + (int)szL.Height), szS));
      }
      e.Graphics.DrawImage(img, new Point(LEFT_MARGIN, TOP_MARGIN + (int)(szL.Height / 2) - img.Height / 2));
    }
    //--------------------------------------------------------------------------------
    protected override void OnMouseLeave(EventArgs e)
    {
      m_State = eButtonState.Normal;
      Invalidate();
      base.OnMouseLeave(e);
    }
    //--------------------------------------------------------------------------------
    protected override void OnMouseEnter(EventArgs e)
    {
      m_State = eButtonState.MouseOver;
      Invalidate();
      base.OnMouseEnter(e);
    }
    //--------------------------------------------------------------------------------
    protected override void OnMouseUp(MouseEventArgs e)
    {
      m_State = eButtonState.MouseOver;
      Invalidate();
      base.OnMouseUp(e);
    }
    //--------------------------------------------------------------------------------
    protected override void OnMouseDown(MouseEventArgs e)
    {
      m_State = eButtonState.Down;
      Invalidate();
      base.OnMouseDown(e);
    }
    //--------------------------------------------------------------------------------
    protected override void OnSizeChanged(EventArgs e)
    {
      if (m_autoHeight)
      {

Answer: int h = GetBestHeight();


Context:
#
# Copyright (C) 2019  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from collections import OrderedDict, namedtuple
from pyanaconda.core.constants import PayloadRequirementType
from pyanaconda.payload.errors import PayloadRequirementsMissingApply
from pyanaconda.anaconda_loggers import get_module_logger
log = get_module_logger(__name__)
PayloadRequirementReason = namedtuple('PayloadRequirementReason', ['reason', 'strong'])
__all__ = ["PayloadRequirements", "PayloadRequirement"]
class PayloadRequirement(object):
    """An object to store a payload requirement with info about its reasons.
    For each requirement multiple reasons together with their strength
    can be stored in this object using the add_reason method.
    A reason should be just a string with description (ie for tracking purposes).
    Strength is a boolean flag that can be used to indicate whether missing the
    requirement should be considered fatal. Strength of the requirement is
    given by strength of all its reasons.
    """
    def __init__(self, req_id, reasons=None):
        self._id = req_id
        self._reasons = reasons or []
    @property
    def id(self):
        """Identifier of the requirement (eg a package name)"""
        return self._id
    @property
    def reasons(self):
        """List of reasons for the requirement"""
        return [reason for reason, strong in self._reasons]
    @property
    def strong(self):
        """Strength of the requirement (ie should it be considered fatal?)"""
        return any(strong for reason, strong in self._reasons)
    def add_reason(self, reason, strong=False):
        """Adds a reason to the requirement with optional strength of the reason"""
        self._reasons.append(PayloadRequirementReason(reason, strong))
    def __str__(self):
        return "PayloadRequirement(id=%s, reasons=%s, strong=%s)" % (self.id,
                                                                     self.reasons,
                                                                     self.strong)
    def __repr__(self):
        return 'PayloadRequirement(id=%s, reasons=%s)' % (self.id, self._reasons)
class PayloadRequirements(object):
    """A container for payload requirements imposed by installed functionality.
    Stores names of packages and groups required by used installer features,
    together with descriptions of reasons why the object is required and if the
    requirement is strong. Not satisfying strong requirement would be fatal for
    installation.
    """
    def __init__(self):
        self._apply_called_for_all_requirements = True
        self._apply_cb = None
        self._reqs = {}
        for req_type in PayloadRequirementType:
            self._reqs[req_type] = OrderedDict()
    def add_packages(self, package_names, reason, strong=True):
        """Add packages required for the reason.
        If a package is already required, the new reason will be
        added and the strength of the requirement will be updated.
        :param package_names: names of packages to be added
        :type package_names: list of str
        :param reason: description of reason for adding the packages
        :type reason: str
        :param strong: is the requirement strong (ie is not satisfying it fatal?)
        :type strong: bool
        """
        self._add(PayloadRequirementType.package, package_names, reason, strong)
    def add_groups(self, group_ids, reason, strong=True):
        """Add groups required for the reason.
        If a group is already required, the new reason will be
        added and the strength of the requirement will be updated.
        :param group_ids: ids of groups to be added
        :type group_ids: list of str
        :param reason: descripiton of reason for adding the groups
        :type reason: str
        :param strong: is the requirement strong
        :type strong: bool
        """
        self._add(PayloadRequirementType.group, group_ids, reason, strong)
    def add_requirements(self, requirements):
        """Add requirements from a list of Requirement instances.
        :param requirements: list of Requirement instances
        """
        for requirement in requirements:
            # check requirement type and add a payload requirement appropriately
            if requirement.type == "package":
                self.add_packages([requirement.name], reason=requirement.reason)
            elif requirement.type == "group":
                self.add_groups([requirement.name], reason=requirement.reason)
            else:
                log.warning("Unknown type: %s in requirement: %s, skipping.", requirement.type, requirement)
    def _add(self, req_type, ids, reason, strong):
        if not ids:
            log.debug("no %s requirement added for %s", req_type.value, reason)
        reqs = self._reqs[req_type]
        for r_id in ids:
            if r_id not in reqs:
                reqs[r_id] = PayloadRequirement(r_id)
            reqs[r_id].add_reason(reason, strong)
            self._apply_called_for_all_requirements = False
            log.debug("added %s requirement '%s' for %s, strong=%s",
                      req_type.value, r_id, reason, strong)
    @property
    def packages(self):
        """List of package requirements.
        return: list of package requirements
        rtype: list of PayloadRequirement
        """
        return list(self._reqs[PayloadRequirementType.package].values())
    @property
    def groups(self):
        """List of group requirements.
        return: list of group requirements
        rtype: list of PayloadRequirement
        """
        return list(self._reqs[PayloadRequirementType.group].values())
    def set_apply_callback(self, callback):
        """Set the callback for applying requirements.
        The callback will be called by apply() method.
        param callback: callback function to be called by apply() method
        type callback: a function taking one argument (requirements object)
        """
        self._apply_cb = callback
    def apply(self):
        """Apply requirements using callback function.
        Calls the callback supplied via set_apply_callback() method. If no
        callback was set, an axception is raised.
        return: return value of the callback
        rtype: type of the callback return value
        raise PayloadRequirementsMissingApply: if there is no callback set
        """
        if self._apply_cb:
            self._apply_called_for_all_requirements = True
            rv = self._apply_cb(self)
            log.debug("apply with result %s called on requirements %s", rv, self)
            return rv
        else:
            raise PayloadRequirementsMissingApply
    @property
    def applied(self):
        """Was all requirements applied?
        return: Was apply called for all current requirements?
        rtype: bool
        """
        return self.empty or self._apply_called_for_all_requirements
    @property
    def empty(self):
        """Are requirements empty?
        return: True if there are no requirements, else False
        rtype: bool
        """

Answer: return not any(self._reqs.values())


Context:
#!/usr/bin/python
# -*-*- encoding: utf-8 -*-*-
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'j.s@google.com (Jeff Scudder)'
import sys
import unittest
try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import atom
from gdata import test_data
import gdata.test_config as conf
class AuthorTest(unittest.TestCase):

  def setUp(self):
    self.author = atom.Author()

  def testEmptyAuthorShouldHaveEmptyExtensionsList(self):
    self.assert_(isinstance(self.author.extension_elements, list))
    self.assert_(len(self.author.extension_elements) == 0)

  def testNormalAuthorShouldHaveNoExtensionElements(self):
    self.author.name = atom.Name(text='Jeff Scudder')
    self.assert_(self.author.name.text == 'Jeff Scudder')
    self.assert_(len(self.author.extension_elements) == 0)
    new_author = atom.AuthorFromString(self.author.ToString())
    self.assert_(len(self.author.extension_elements) == 0)

    self.author.extension_elements.append(atom.ExtensionElement(
        'foo', text='bar'))
    self.assert_(len(self.author.extension_elements) == 1)
    self.assert_(self.author.name.text == 'Jeff Scudder')
    new_author = atom.AuthorFromString(self.author.ToString())
    self.assert_(len(self.author.extension_elements) == 1)
    self.assert_(new_author.name.text == 'Jeff Scudder')
  def testEmptyAuthorToAndFromStringShouldMatch(self):
    string_from_author = self.author.ToString()
    new_author = atom.AuthorFromString(string_from_author)
    string_from_new_author = new_author.ToString()
    self.assert_(string_from_author == string_from_new_author)

  def testAuthorWithNameToAndFromStringShouldMatch(self):
    self.author.name = atom.Name()
    self.author.name.text = 'Jeff Scudder'
    string_from_author = self.author.ToString()
    new_author = atom.AuthorFromString(string_from_author)
    string_from_new_author = new_author.ToString()
    self.assert_(string_from_author == string_from_new_author)
    self.assert_(self.author.name.text == new_author.name.text)

  def testExtensionElements(self):
    self.author.extension_attributes['foo1'] = 'bar'
    self.author.extension_attributes['foo2'] = 'rab'
    self.assert_(self.author.extension_attributes['foo1'] == 'bar')
    self.assert_(self.author.extension_attributes['foo2'] == 'rab')
    new_author = atom.AuthorFromString(self.author.ToString())
    self.assert_(new_author.extension_attributes['foo1'] == 'bar')
    self.assert_(new_author.extension_attributes['foo2'] == 'rab')

  def testConvertFullAuthorToAndFromString(self):
    author = atom.AuthorFromString(test_data.TEST_AUTHOR)
    self.assert_(author.name.text == 'John Doe')
    self.assert_(author.email.text == 'johndoes@someemailadress.com')
    self.assert_(author.uri.text == 'http://www.google.com')

class EmailTest(unittest.TestCase):

  def setUp(self):
    self.email = atom.Email()

  def testEmailToAndFromString(self):
    self.email.text = 'This is a test'
    new_email = atom.EmailFromString(self.email.ToString())
    self.assert_(self.email.text == new_email.text)
    self.assert_(self.email.extension_elements ==
        new_email.extension_elements)

class NameTest(unittest.TestCase):
  def setUp(self):
    self.name = atom.Name()

  def testEmptyNameToAndFromStringShouldMatch(self):
    string_from_name = self.name.ToString()
    new_name = atom.NameFromString(string_from_name)
    string_from_new_name = new_name.ToString()
    self.assert_(string_from_name == string_from_new_name)

  def testText(self):
    self.assert_(self.name.text is None)
    self.name.text = 'Jeff Scudder'
    self.assert_(self.name.text == 'Jeff Scudder')
    new_name = atom.NameFromString(self.name.ToString())
    self.assert_(new_name.text == self.name.text)

  def testExtensionElements(self):
    self.name.extension_attributes['foo'] = 'bar'
    self.assert_(self.name.extension_attributes['foo'] == 'bar')
    new_name = atom.NameFromString(self.name.ToString())
    self.assert_(new_name.extension_attributes['foo'] == 'bar')

class ExtensionElementTest(unittest.TestCase):

  def setUp(self):
    self.ee = atom.ExtensionElement('foo')

  def testEmptyEEShouldProduceEmptyString(self):
    pass

  def testEEParsesTreeCorrectly(self):
    deep_tree = atom.ExtensionElementFromString(test_data.EXTENSION_TREE)
    self.assert_(deep_tree.tag == 'feed')
    self.assert_(deep_tree.namespace == 'http://www.w3.org/2005/Atom')
    self.assert_(deep_tree.children[0].tag == 'author')
    self.assert_(deep_tree.children[0].namespace == 'http://www.google.com')
    self.assert_(deep_tree.children[0].children[0].tag == 'name')
    self.assert_(deep_tree.children[0].children[0].namespace ==
        'http://www.google.com')
    self.assert_(deep_tree.children[0].children[0].text.strip() == 'John Doe')
    self.assert_(deep_tree.children[0].children[0].children[0].text.strip() ==
        'Bar')
    foo = deep_tree.children[0].children[0].children[0]
    self.assert_(foo.tag == 'foo')
    self.assert_(foo.namespace == 'http://www.google.com')
    self.assert_(foo.attributes['up'] == 'down')
    self.assert_(foo.attributes['yes'] == 'no')
    self.assert_(foo.children == [])

  def testEEToAndFromStringShouldMatch(self):
    string_from_ee = self.ee.ToString()
    new_ee = atom.ExtensionElementFromString(string_from_ee)
    string_from_new_ee = new_ee.ToString()
    self.assert_(string_from_ee == string_from_new_ee)

    deep_tree = atom.ExtensionElementFromString(test_data.EXTENSION_TREE)
    string_from_deep_tree = deep_tree.ToString()
    new_deep_tree = atom.ExtensionElementFromString(string_from_deep_tree)
    string_from_new_deep_tree = new_deep_tree.ToString()
    self.assert_(string_from_deep_tree == string_from_new_deep_tree)

class LinkTest(unittest.TestCase):

  def setUp(self):
    self.link = atom.Link()

  def testLinkToAndFromString(self):
    self.link.href = 'test href'
    self.link.hreflang = 'english'
    self.link.type = 'text/html'
    self.link.extension_attributes['foo'] = 'bar'
    self.assert_(self.link.href == 'test href')
    self.assert_(self.link.hreflang == 'english')
    self.assert_(self.link.type == 'text/html')
    self.assert_(self.link.extension_attributes['foo'] == 'bar')
    new_link = atom.LinkFromString(self.link.ToString())
    self.assert_(self.link.href == new_link.href)
    self.assert_(self.link.type == new_link.type)
    self.assert_(self.link.hreflang == new_link.hreflang)
    self.assert_(self.link.extension_attributes['foo'] ==
        new_link.extension_attributes['foo'])
  def testLinkType(self):
    test_link = atom.Link(link_type='text/html')
    self.assert_(test_link.type == 'text/html')
class GeneratorTest(unittest.TestCase):
  def setUp(self):
    self.generator = atom.Generator()
  def testGeneratorToAndFromString(self):
    self.generator.uri = 'www.google.com'
    self.generator.version = '1.0'
    self.generator.extension_attributes['foo'] = 'bar'
    self.assert_(self.generator.uri == 'www.google.com')
    self.assert_(self.generator.version == '1.0')
    self.assert_(self.generator.extension_attributes['foo'] == 'bar')
    new_generator = atom.GeneratorFromString(self.generator.ToString())
    self.assert_(self.generator.uri == new_generator.uri)
    self.assert_(self.generator.version == new_generator.version)
    self.assert_(self.generator.extension_attributes['foo'] ==
        new_generator.extension_attributes['foo'])
class TitleTest(unittest.TestCase):
  def setUp(self):
    self.title = atom.Title()
  def testTitleToAndFromString(self):
    self.title.type = 'text'
    self.title.text = 'Less: <'
    self.assert_(self.title.type == 'text')
    self.assert_(self.title.text == 'Less: <')
    new_title = atom.TitleFromString(self.title.ToString())
    self.assert_(self.title.type == new_title.type)
    self.assert_(self.title.text == new_title.text)
class SubtitleTest(unittest.TestCase):
  def setUp(self):
    self.subtitle = atom.Subtitle()
  def testTitleToAndFromString(self):
    self.subtitle.type = 'text'
    self.subtitle.text = 'sub & title'
    self.assert_(self.subtitle.type == 'text')
    self.assert_(self.subtitle.text == 'sub & title')
    new_subtitle = atom.SubtitleFromString(self.subtitle.ToString())
    self.assert_(self.subtitle.type == new_subtitle.type)
    self.assert_(self.subtitle.text == new_subtitle.text)
class SummaryTest(unittest.TestCase):
  def setUp(self):
    self.summary = atom.Summary()
  def testTitleToAndFromString(self):
    self.summary.type = 'text'
    self.summary.text = 'Less: <'
    self.assert_(self.summary.type == 'text')
    self.assert_(self.summary.text == 'Less: <')
    new_summary = atom.SummaryFromString(self.summary.ToString())
    self.assert_(self.summary.type == new_summary.type)
    self.assert_(self.summary.text == new_summary.text)
class CategoryTest(unittest.TestCase):
  def setUp(self):

Answer: self.category = atom.Category()


Context:
"""
Builds out filesystem trees/data based on the object tree.
This is the code behind 'cobbler sync'.
Copyright 2006-2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301  USA
"""
import os
import os.path
import glob
import shutil
import time
import yaml # Howell-Clark version
import sys
import glob
import traceback
import errno
import utils
from cexceptions import *
import templar
import pxegen
import item_distro
import item_profile
import item_repo
import item_system
from Cheetah.Template import Template
import clogger
from utils import _
import cobbler.module_loader as module_loader
class BootSync:
    """
    Handles conversion of internal state to the tftpboot tree layout
    """
    def __init__(self,config,verbose=True,dhcp=None,dns=None,logger=None,tftpd=None):
        """
        Constructor
        """
        self.logger         = logger
        if logger is None:
            self.logger     = clogger.Logger()
        self.verbose      = verbose
        self.config       = config
        self.api          = config.api
        self.distros      = config.distros()
        self.profiles     = config.profiles()
        self.systems      = config.systems()
        self.settings     = config.settings()
        self.repos        = config.repos()
        self.templar      = templar.Templar(config, self.logger)
        self.pxegen       = pxegen.PXEGen(config, self.logger)
        self.dns          = dns
        self.dhcp         = dhcp
        self.tftpd        = tftpd
        self.bootloc      = utils.tftpboot_location()
        self.pxegen.verbose = verbose
        self.dns.verbose    = verbose
        self.dhcp.verbose   = verbose
        self.pxelinux_dir = os.path.join(self.bootloc, "pxelinux.cfg")
        self.grub_dir = os.path.join(self.bootloc, "grub")
        self.images_dir = os.path.join(self.bootloc, "images")
        self.yaboot_bin_dir = os.path.join(self.bootloc, "ppc")
        self.yaboot_cfg_dir = os.path.join(self.bootloc, "etc")
        self.s390_dir = os.path.join(self.bootloc, "s390x")
        self.rendered_dir = os.path.join(self.settings.webdir, "rendered")
    def run(self):
        """
        Syncs the current configuration file with the config tree.
        Using the Check().run_ functions previously is recommended
        """
        if not os.path.exists(self.bootloc):
            utils.die(self.logger,"cannot find directory: %s" % self.bootloc)
        self.logger.info("running pre-sync triggers")
        # run pre-triggers...
        utils.run_triggers(self.api, None, "/var/lib/cobbler/triggers/sync/pre/*")
        self.distros  = self.config.distros()
        self.profiles = self.config.profiles()
        self.systems  = self.config.systems()
        self.settings = self.config.settings()
        self.repos    = self.config.repos()
        # execute the core of the sync operation
        self.logger.info("cleaning trees")
        self.clean_trees()
        # Have the tftpd module handle copying bootloaders,
        # distros, images, and all_system_files
        self.tftpd.sync(self.verbose)
        # Copy distros to the webdir
        # Adding in the exception handling to not blow up if files have
        # been moved (or the path references an NFS directory that's no longer
        # mounted)
	for d in self.distros:
            try:
                self.logger.info("copying files for distro: %s" % d.name)
                self.pxegen.copy_single_distro_files(d,
                                                     self.settings.webdir,True)
                self.pxegen.write_templates(d,write_file=True)
            except CX, e:
                self.logger.error(e.value)
        # make the default pxe menu anyway...
        self.pxegen.make_pxe_menu()
        if self.settings.manage_dhcp:
            self.write_dhcp()
        if self.settings.manage_dns:
            self.logger.info("rendering DNS files")
            self.dns.regen_hosts()
            self.dns.write_dns_files()
        if self.settings.manage_tftpd:
           # xinetd.d/tftpd, basically
           self.logger.info("rendering TFTPD files")
           self.tftpd.write_tftpd_files()
           # copy in boot_files
           self.tftpd.write_boot_files()
        self.logger.info("cleaning link caches")
        self.clean_link_cache()
        if self.settings.manage_rsync:
           self.logger.info("rendering Rsync files")
           self.rsync_gen()
        # run post-triggers
        self.logger.info("running post-sync triggers")
        utils.run_triggers(self.api, None, "/var/lib/cobbler/triggers/sync/post/*", logger=self.logger)
        utils.run_triggers(self.api, None, "/var/lib/cobbler/triggers/change/*", logger=self.logger)
        return True
    def make_tftpboot(self):
        """
        Make directories for tftpboot images
        """
        if not os.path.exists(self.pxelinux_dir):
            utils.mkdir(self.pxelinux_dir,logger=self.logger)
        if not os.path.exists(self.grub_dir):
            utils.mkdir(self.grub_dir,logger=self.logger)
        grub_images_link = os.path.join(self.grub_dir, "images")
        if not os.path.exists(grub_images_link):
            os.symlink("../images", grub_images_link)
        if not os.path.exists(self.images_dir):
            utils.mkdir(self.images_dir,logger=self.logger)
        if not os.path.exists(self.s390_dir):
            utils.mkdir(self.s390_dir,logger=self.logger)
        if not os.path.exists(self.rendered_dir):
            utils.mkdir(self.rendered_dir,logger=self.logger)
        if not os.path.exists(self.yaboot_bin_dir):
            utils.mkdir(self.yaboot_bin_dir,logger=self.logger)
        if not os.path.exists(self.yaboot_cfg_dir):
            utils.mkdir(self.yaboot_cfg_dir,logger=self.logger)
    def clean_trees(self):
        """
        Delete any previously built pxelinux.cfg tree and virt tree info and then create
        directories.
        Note: for SELinux reasons, some information goes in /tftpboot, some in /var/www/cobbler
        and some must be duplicated in both.  This is because PXE needs tftp, and auto-kickstart
        and Virt operations need http.   Only the kernel and initrd images are duplicated, which is
        unfortunate, though SELinux won't let me give them two contexts, so symlinks are not
        a solution.  *Otherwise* duplication is minimal.
        """
        # clean out parts of webdir and all of /tftpboot/images and /tftpboot/pxelinux.cfg
        for x in os.listdir(self.settings.webdir):
            path = os.path.join(self.settings.webdir,x)
            if os.path.isfile(path):
                if not x.endswith(".py"):
                    utils.rmfile(path,logger=self.logger)
            if os.path.isdir(path):
                if not x in ["aux", "web", "webui", "localmirror","repo_mirror","ks_mirror","images","links","pub","repo_profile","repo_system","svc","rendered",".link_cache"] :
                    # delete directories that shouldn't exist
                    utils.rmtree(path,logger=self.logger)
                if x in ["kickstarts","kickstarts_sys","images","systems","distros","profiles","repo_profile","repo_system","rendered"]:
                    # clean out directory contents
                    utils.rmtree_contents(path,logger=self.logger)
        #
        self.make_tftpboot()
        utils.rmtree_contents(self.pxelinux_dir,logger=self.logger)
        utils.rmtree_contents(self.grub_dir,logger=self.logger)
        utils.rmtree_contents(self.images_dir,logger=self.logger)
        utils.rmtree_contents(self.s390_dir,logger=self.logger)
        utils.rmtree_contents(self.yaboot_bin_dir,logger=self.logger)
        utils.rmtree_contents(self.yaboot_cfg_dir,logger=self.logger)
        utils.rmtree_contents(self.rendered_dir,logger=self.logger)
    def write_dhcp(self):
        self.logger.info("rendering DHCP files")
        self.dhcp.write_dhcp_file()
        self.dhcp.regen_ethers()
    def sync_dhcp(self):
        restart_dhcp = str(self.settings.restart_dhcp).lower()
        which_dhcp_module = module_loader.get_module_from_file("dhcp","module",just_name=True).strip()
        if self.settings.manage_dhcp:
            self.write_dhcp()
            if which_dhcp_module == "manage_isc":
                service_name = utils.dhcp_service_name(self.api)
                if restart_dhcp != "0":
                    rc = utils.subprocess_call(self.logger, "dhcpd -t -q", shell=True)
                    if rc != 0:
                       self.logger.error("dhcpd -t failed")
                       return False
                    service_restart = "service %s restart" % service_name
                    rc = utils.subprocess_call(self.logger, service_restart, shell=True)
                    if rc != 0:

Answer: self.logger.error("%s failed" % service_name)