コード例 #1
0
ファイル: DefCrud.cs プロジェクト: nampn/ODental
 ///<summary>Inserts one Def into the database.  Returns the new priKey.</summary>
 internal static long Insert(Def def)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         def.DefNum=DbHelper.GetNextOracleKey("definition","DefNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(def,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     def.DefNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(def,false);
     }
 }
コード例 #2
0
ファイル: 99BottlesOfBeer.cs プロジェクト: ToJans/Matchy
        public void Setup()
        {
            verse = new Def()
                .Match(0).With(
                    "No more bottles of beer on the wall, no more bottles of beer.\n" +
                    "Go to the store and buy some more, 99 bottles of beer on the wall.\n")
                .Match<int>().With(n => string.Format(
                    "{0} of beer on the wall, {0} of beer.\n" +
                    "Take {1} down and pass it around, {2} of beer on the wall.\n"
                    , bottles[n], lastOne[n], bottles[n - 1]));

            lastOne = new Def()
                .Match(1).With("it")
                .Match<int>().With("one");

            bottles = new Def()
                .Match(0).With("no more bottles")
                .Match(1).With("1 bottle")
                .Match<int>().With(n => string.Format("{0} bottles", n));

            sing = new Def()
                .Match((int x) => x >= 0).With(x => sing[Tuple.Create(x, 0)])
                .Match((Tuple<int, int> x) => x.Item1 < x.Item2).With(x => "")
                .Match<Tuple<int, int>>().With(x => string.Format("{0}\n{1}", verse[x.Item1], sing[Tuple.Create(x.Item1 - 1, x.Item2)]));
        }
コード例 #3
0
 /// <summary>
 /// Initialize a struct from given data.
 /// </summary>
 /// <param name="meta">The metadata to attach.</param>
 /// <param name="def">The structure definition.</param>
 /// <param name="vals">Values for the fixed keys.</param>
 /// <param name="ext">Additional keys/values.</param>
 protected PersistentStructMap(IPersistentMap meta, Def def, Object[] vals, IPersistentMap ext)
     : base(meta)
 {
     _ext = ext;
     _def = def;
     _vals = vals;
 }
コード例 #4
0
ファイル: DefCrud.cs プロジェクト: nampn/ODental
 ///<summary>Inserts one Def into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(Def def,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         def.DefNum=ReplicationServers.GetKey("definition","DefNum");
     }
     string command="INSERT INTO definition (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="DefNum,";
     }
     command+="Category,ItemOrder,ItemName,ItemValue,ItemColor,IsHidden) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(def.DefNum)+",";
     }
     command+=
              POut.Int   ((int)def.Category)+","
         +    POut.Int   (def.ItemOrder)+","
         +"'"+POut.String(def.ItemName)+"',"
         +"'"+POut.String(def.ItemValue)+"',"
         +    POut.Int   (def.ItemColor.ToArgb())+","
         +    POut.Bool  (def.IsHidden)+")";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         def.DefNum=Db.NonQ(command,true);
     }
     return def.DefNum;
 }
コード例 #5
0
ファイル: Fibs.cs プロジェクト: ToJans/Matchy
 public void SetupFibs()
 {
     fib = new Def()
        .Match(0).With(0)
        .Match(1).With(1)
        .Match(2).With(1)
        .Match(aLargeInt).With(x => { throw new ArgumentOutOfRangeException("N", x, "We only support numbers up to 10."); })
        .Match<int>().With(n => fib[n - 1] + fib[n - 2])
        .Match<string>().With("You found the easter egg");
 }
コード例 #6
0
 /// <summary>
 /// Create a struct from a struct definition and values (in order) for the fixed keys.
 /// </summary>
 /// <param name="def">A struct definition</param>
 /// <param name="valseq">A sequence of values for the fixed keys (in definition order).</param>
 /// <returns>A <see cref="PersistentStructMap">PersistentStructMap</see>.</returns>
 public static PersistentStructMap construct(Def def, ISeq valseq)
 {
     object[] vals = new object[def.Keyslots.count()];
     IPersistentMap ext = PersistentHashMap.EMPTY;
     for (int i = 0; i < vals.Length && valseq != null; valseq = valseq.rest(), i++)
     {
         vals[i] = valseq.first();
     }
     if (valseq != null)
         throw new ArgumentException("Too many arguments to struct constructor");
     return new PersistentStructMap(null, def, vals, ext);
 }
コード例 #7
0
 public ProductionCode(
     EmitSyntax       emit,
     IContextCode     contextCode,
     Pipe<EmitSyntax> ldRuleArgs,
     Pipe<EmitSyntax> ldArgsStart,
     Def<Labels>      returnLabel)
 {
     this.emit        = emit;
     this.contextCode = contextCode;
     this.LdRuleArgs  = ldRuleArgs;
     this.LdArgsStart = ldArgsStart;
     this.ReturnLabel = returnLabel;
 }
コード例 #8
0
        public StackGenerator(EmitSyntax emit, Type itemType, bool nullContainer = false)
        {
            this.itemType = emit.Types.Import(itemType);
            this.stackType = emit.Types.Import(itemType.MakeArrayType());
            this.nullContainer = nullContainer;

            this.stack = emit.Locals.Generate();
            this.index = emit.Locals.Generate();
            emit
                .Local(stack, stackType)
                .Local(index, emit.Types.Int32)
                ;
        }
コード例 #9
0
ファイル: GraphRunner.cs プロジェクト: YoloDev/srclib-csharp
    /// <summary>
    /// Add a definition to the output.
    /// Also adds a ref to the def, and
    /// potentially a doc.
    /// </summary>
    /// <param name="def">The def to add.</param>
    /// <param name="symbol">The symbol the def was created from.</param>
    void AddDef(Def def, Doc doc = null)
    {
      var r = Ref.AtDef(def);
      _output.Defs.Add(def);
      _output.Refs.Add(r);

      if (doc != null)
      {
        doc.UnitType = r.DefUnitType;
        doc.Unit = r.DefUnit;
        doc.Path = r.DefPath;
        _output.Docs.Add(doc);
      }
    }
コード例 #10
0
ファイル: DefCrud.cs プロジェクト: romeroyonatan/opendental
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<Def> TableToList(DataTable table){
			List<Def> retVal=new List<Def>();
			Def def;
			for(int i=0;i<table.Rows.Count;i++) {
				def=new Def();
				def.DefNum   = PIn.Long  (table.Rows[i]["DefNum"].ToString());
				def.Category = (DefCat)PIn.Int(table.Rows[i]["Category"].ToString());
				def.ItemOrder= PIn.Int   (table.Rows[i]["ItemOrder"].ToString());
				def.ItemName = PIn.String(table.Rows[i]["ItemName"].ToString());
				def.ItemValue= PIn.String(table.Rows[i]["ItemValue"].ToString());
				def.ItemColor= Color.FromArgb(PIn.Int(table.Rows[i]["ItemColor"].ToString()));
				def.IsHidden = PIn.Bool  (table.Rows[i]["IsHidden"].ToString());
				retVal.Add(def);
			}
			return retVal;
		}
コード例 #11
0
        /// <summary>
        /// Add a definition to the output.
        /// Also adds a ref to the def, and
        /// potentially a doc.
        /// </summary>
        /// <param name="def">The def to add.</param>
        /// <param name="symbol">The symbol the def was created from.</param>
        void AddDef(Def def, Doc doc = null)
        {
            string key = def.DefKey;
            if (!keys.Contains(key))
            {
                keys.Add(key);
                var r = Ref.AtDef(def);
                _output.Defs.Add(def);
                _output.Refs.Add(r);

                if (doc != null)
                {
                    doc.UnitType = r.DefUnitType;
                    doc.Unit = r.DefUnit;
                    doc.Path = r.DefPath;
                    _output.Docs.Add(doc);
                }
            }
        }
コード例 #12
0
        public EmitSyntax EmitInitialization(EmitSyntax emit)
        {
            var types = emit.Types;

            var labels = emit.Labels;
            END = labels.Generate();
            START = labels.Generate();

            var locals = emit.Locals;
            count = locals.Generate();
            if (Index == null)
            {
                Index = locals.Generate();
                emit.Local(Index, types.Int32);
            }

            if (Value == null)
            {
                Value = locals.Generate();
                emit
                    .Local(Value, valueType)
                    .Ldc_I4(int.MinValue)
                    .Stloc(Value.GetRef());
            }

            emit
                // int count;
                .Local(count, types.Int32);

            // count = array.Length
            ldarray(emit);
            return emit
                .Ldlen()
                .Stloc(count.GetRef())

                // Index = 0
                .Ldc_I4(-1)
                .Stloc(Index.GetRef())
                // Value = -1
                .Ldc_I4(-1)
                .Stloc(Value.GetRef());
                ;
        }
コード例 #13
0
ファイル: MigracaoDEFTest.cs プロジェクト: Workker/EHR
        public void MigrarDEF()
        {
            var conexao = Conexao.CreateSessionFactoryOracle();
            DefsIntegracao defs = new DefsIntegracao(conexao.OpenSession());

            var listaDefIntegracao = defs.All<DefMigracao>();

            Defs repositorioDef = new Defs(Conexao.CreateSessionFactory().OpenSession());

            List<Def> listaDef = new List<Def>();

            foreach (var defIntegracao in listaDefIntegracao)
            {
                var def = new Def();
                def.Description = defIntegracao.Produto;

                listaDef.Add(def);
            }

            repositorioDef.SalvarLista(listaDef);
        }
コード例 #14
0
 public static void UpdateLabel(this Def def, string label)
 {
     def.label = label;
     cachedLabelCapInfo.SetValue(def, new TaggedString(""));
 }
コード例 #15
0
 // throws jjtraveler.VisitFailure
 public void testDefUse()
 {
     Def def = new Def();
     Use use = new Use();
     DefUse du = new DefUse(use, def);
     du.visit(n0);
     Assertion.AssertTrue( du.getUnused().contains("noot"));
     Assertion.AssertTrue( du.getUndefined().contains("mies"));
     Assertion.AssertEquals(1, du.getUnused().size());
     Assertion.AssertEquals(1, du.getUndefined().size());
 }
コード例 #16
0
 /// <summary>
 /// Initialize.
 /// </summary>
 /// <param name="def">The struct definition.</param>
 /// <param name="index">The index of the key to access.</param>
 public AccessorFn(Def def, int index)
 {
     _def   = def;
     _index = index;
 }
コード例 #17
0
ファイル: Column.cs プロジェクト: narsw/Implem.Pleasanter
 internal static bool CheckExclude(
     CodeDefinition codeDefinition,
     ColumnDefinition columnDefinition)
 {
     if (codeDefinition.NotJoin && columnDefinition.JoinTableName != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.Join && columnDefinition.JoinTableName == string.Empty)
     {
         return(true);
     }
     if (codeDefinition.JoinExpression && columnDefinition.JoinExpression == string.Empty)
     {
         return(true);
     }
     if (codeDefinition.Pk && columnDefinition.Pk == 0)
     {
         return(true);
     }
     if (codeDefinition.NotPk && columnDefinition.Pk != 0)
     {
         return(true);
     }
     if (codeDefinition.Session && !columnDefinition.Session)
     {
         return(true);
     }
     if (codeDefinition.Identity && !columnDefinition.Identity)
     {
         return(true);
     }
     if (codeDefinition.NotIdentity && columnDefinition.Identity)
     {
         return(true);
     }
     if (codeDefinition.Unique && !columnDefinition.Unique)
     {
         return(true);
     }
     if (codeDefinition.NotUnique && columnDefinition.Unique)
     {
         return(true);
     }
     if (codeDefinition.NotDefault && columnDefinition.Default != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.ItemId &&
         Def.ExistsModel(columnDefinition.ModelName, o => o.ItemId > 0) &&
         columnDefinition.ColumnName != columnDefinition.ModelName + "Id")
     {
         return(true);
     }
     if (codeDefinition.NotItemId &&
         Def.ExistsModel(columnDefinition.ModelName, o => o.ItemId > 0) &&
         columnDefinition.ColumnName == columnDefinition.ModelName + "Id")
     {
         return(true);
     }
     if (codeDefinition.Calc && columnDefinition.Calc == string.Empty)
     {
         return(true);
     }
     if (codeDefinition.NotCalc && columnDefinition.Calc != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.NotWhereSpecial && columnDefinition.WhereSpecial)
     {
         return(true);
     }
     if (codeDefinition.SearchIndex && columnDefinition.SearchIndexPriority == 0)
     {
         return(true);
     }
     if (codeDefinition.NotByForm && columnDefinition.ByForm != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.Form && columnDefinition.NotForm)
     {
         return(true);
     }
     if (codeDefinition.Select && columnDefinition.NotSelect)
     {
         return(true);
     }
     if (codeDefinition.Update && columnDefinition.NotUpdate)
     {
         return(true);
     }
     if (codeDefinition.SelectColumns && columnDefinition.SelectColumns == string.Empty)
     {
         return(true);
     }
     if (codeDefinition.NotSelectColumn && columnDefinition.SelectColumns != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.ComputeColumn && columnDefinition.ComputeColumn == string.Empty)
     {
         return(true);
     }
     if (codeDefinition.NotSelectColumn && columnDefinition.ComputeColumn != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.Aggregatable && !columnDefinition.Aggregatable)
     {
         return(true);
     }
     if (codeDefinition.Computable && !columnDefinition.Computable)
     {
         return(true);
     }
     if (codeDefinition.Include != string.Empty && !codeDefinition.Include.Split(',').Contains(columnDefinition.ColumnName))
     {
         return(true);
     }
     if (codeDefinition.Exclude != string.Empty && codeDefinition.Exclude.Split(',').Contains(columnDefinition.ColumnName))
     {
         return(true);
     }
     if (codeDefinition.IncludeTypeName != string.Empty && !codeDefinition.IncludeTypeName.Split(',').Contains(columnDefinition.TypeName))
     {
         return(true);
     }
     if (codeDefinition.ExcludeTypeName != string.Empty && codeDefinition.ExcludeTypeName.Split(',').Contains(columnDefinition.TypeName))
     {
         return(true);
     }
     if (codeDefinition.IncludeTypeCs != string.Empty && !codeDefinition.IncludeTypeCs.Split(',').Contains(columnDefinition.TypeCs))
     {
         return(true);
     }
     if (codeDefinition.ExcludeTypeCs != string.Empty && codeDefinition.ExcludeTypeCs.Split(',').Contains(columnDefinition.TypeCs))
     {
         return(true);
     }
     if (codeDefinition.IncludeDefaultCs != string.Empty && !codeDefinition.IncludeDefaultCs.Split(',').Contains(columnDefinition.DefaultCs))
     {
         return(true);
     }
     if (codeDefinition.ExcludeDefaultCs != string.Empty && codeDefinition.ExcludeDefaultCs.Split(',').Contains(columnDefinition.DefaultCs))
     {
         return(true);
     }
     if (codeDefinition.Class && !columnDefinition.Class)
     {
         return(true);
     }
     if (codeDefinition.NotClass && columnDefinition.Class)
     {
         return(true);
     }
     if (codeDefinition.NotTypeCs && columnDefinition.TypeCs != string.Empty)
     {
         return(true);
     }
     if (codeDefinition.History && columnDefinition.History == 0)
     {
         return(true);
     }
     if (codeDefinition.PkHistory && columnDefinition.PkHistory == 0)
     {
         return(true);
     }
     if (codeDefinition.GridColumn && columnDefinition.GridColumn == 0)
     {
         return(true);
     }
     if (codeDefinition.FilterColumn && columnDefinition.FilterColumn == 0)
     {
         return(true);
     }
     if (codeDefinition.EditorColumn && columnDefinition.EditorColumn == 0)
     {
         return(true);
     }
     if (codeDefinition.TitleColumn && columnDefinition.TitleColumn == 0)
     {
         return(true);
     }
     if (codeDefinition.UserColumn && !columnDefinition.UserColumn)
     {
         return(true);
     }
     if (codeDefinition.NotUserColumn && columnDefinition.UserColumn)
     {
         return(true);
     }
     if (codeDefinition.EnumColumn && !columnDefinition.EnumColumn)
     {
         return(true);
     }
     if (codeDefinition.Exclude.Split(',').Contains(columnDefinition.ColumnName))
     {
         return(true);
     }
     if (codeDefinition.NotItem && Def.ExistsTable(columnDefinition.TableName, o => o.ItemId > 0))
     {
         return(true);
     }
     if (codeDefinition.ItemOnly && !Def.ExistsTable(columnDefinition.TableName, o => o.ItemId > 0))
     {
         return(true);
     }
     if (codeDefinition.GenericUi && !Def.ExistsTable(columnDefinition.TableName, o => o.GenericUi))
     {
         return(true);
     }
     if (codeDefinition.UpdateMonitor && !Def.ExistsTable(columnDefinition.TableName, o => o.UpdateMonitor))
     {
         return(true);
     }
     if (codeDefinition.ControlType != string.Empty && codeDefinition.ControlType != columnDefinition.ControlType)
     {
         return(true);
     }
     if (codeDefinition.Null && !columnDefinition.Nullable)
     {
         return(true);
     }
     if (codeDefinition.NotNull && columnDefinition.Nullable)
     {
         return(true);
     }
     if (codeDefinition.Like && !columnDefinition.Like)
     {
         return(true);
     }
     if (codeDefinition.NotBase)
     {
         if (Def.ItemModelNameCollection().Contains(columnDefinition.ModelName))
         {
             if (Def.ExistsColumnBaseItem(o =>
                                          o.ColumnName == columnDefinition.ColumnName &&
                                          !o.EachModel))
             {
                 return(true);
             }
         }
         else
         {
             if (Def.ExistsColumnBase(o =>
                                      o.ColumnName == columnDefinition.ColumnName &&
                                      !o.EachModel))
             {
                 return(true);
             }
         }
     }
     if (codeDefinition.IdentityOrPk)
     {
         if ((HasUniqueColumn(columnDefinition) && !(columnDefinition.Identity || columnDefinition.Unique)) ||
             (!HasUniqueColumn(columnDefinition) && columnDefinition.Pk == 0))
         {
             return(true);
         }
     }
     return(false);
 }
コード例 #18
0
        private static void _Trace( ModHelperDef modHelperDef, Verbosity Severity, string content, Def atFault = null, string category = null )
        {
            #if RELEASE
            if( Severity > Verbosity.Validation )
            {
                return;
            }
            #endif
            if( !_TraceFor( ref modHelperDef, Severity, atFault ) )
            {
                return;
            }
            var s = captureTarget;
            if( s == null )
            {
                s = BaseMessage();
            }
            else
            {
                s.Append( "\t" );
            }

            _BuildTrace( ref s, modHelperDef, Severity, content, atFault, category, ( captureTarget == null ) );

            if( captureTarget == null )
            {
            #if DEBUG
                Write( s.ToString() );
            #endif
                if( Severity <= Verbosity.NonFatalErrors )
                {
                    // Error
                    Verse.Log.Error( s.ToString() );
                }
                else if ( Severity == Verbosity.Warnings )
                {
                    // Warning
                    Verse.Log.Warning( s.ToString() );
                }
                else
                {
                    // Wall of text
                    Verse.Log.Message( s.ToString() );
                }
            }
            else
            {
                s.Append( "\n" );
            }
        }
コード例 #19
0
        private static bool _TraceFor( ref ModHelperDef modHelperDef, Verbosity Severity, Def atFault )
        {
            Verbosity TraceAt = Verbosity.Default;
            if(
                ( !Controller.Data.Mods.NullOrEmpty() )&&
                ( !Controller.Data.ModHelperDefs.NullOrEmpty() )
            )
            {
                if(
                    ( modHelperDef == null )&&
                    ( atFault != null )
                )
                {
                    // Try to find the mod associated with this def

                    var mod = Find_Extensions.ModByDef( atFault );

                    if( mod != null )
                    {
                        modHelperDef = Find_Extensions.ModHelperDefForMod( mod );
                    }
                }
                if( modHelperDef != null )
                {
                    TraceAt = modHelperDef.Verbosity;
                    if( modHelperDef.Verbosity > captureVerbosity )
                    {
                        captureVerbosity = modHelperDef.Verbosity;
                    }
                }
                else if ( atFault == null )
                {
                    TraceAt = captureVerbosity;
                }
                else
                {
                    TraceAt = Find_Extensions.HightestVerbosity;
                }
            }
            return ( TraceAt >= Severity );
        }
コード例 #20
0
        /// <summary>
        /// Get a fast accessor for a fixed key.
        /// </summary>
        /// <param name="def">The struct definition.</param>
        /// <param name="key">The fixed key to access.</param>
        /// <returns>An accessor function.</returns>
        public static IFn getAccessor(Def def, object key)
        {
            IMapEntry e = def.Keyslots.entryAt(key);
            if (e == null)
                throw new ArgumentException("Not a key of struct");

            int i = (int)e.val();

            return new AccessorFn(def, i);
        }
コード例 #21
0
        public VM.CompiledScript Compile(ICharStream input)
        {
            try
            {
                LSLTreeAdaptor lslAdaptor = new LSLTreeAdaptor();


                //
                // Initial parse and AST creation
                //
                LSLLexer          lex    = new LSLLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LSLParser         p      = new LSLParser(tokens);
                p.TreeAdaptor        = lslAdaptor;
                p.TraceDestination   = _traceRedirect;
                lex.TraceDestination = _traceRedirect;
                LSLParser.prog_return r = p.prog();

                if (p.NumberOfSyntaxErrors > 0)
                {
                    _listener.Error(Convert.ToString(p.NumberOfSyntaxErrors) + " syntax error(s)");
                    return(null);
                }


                //
                // Definitions
                //
                CommonTree           t     = (CommonTree)r.Tree;
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(lslAdaptor, t);
                nodes.TokenStream = tokens;

                SymbolTable symtab = new SymbolTable(tokens, Defaults.SystemMethods.Values, DefaultConstants.Constants.Values);
                symtab.StatusListener = _listener;

                Def def = new Def(nodes, symtab);
                def.TraceDestination = _traceRedirect;
                def.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || def.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                //
                // Type and more semantic checks
                //
                Compiler.Types types = new Compiler.Types(nodes, symtab);
                types.TraceDestination = _traceRedirect;
                types.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || types.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                StringTemplateGroup templates;
                using (TextReader fr = new StreamReader(Path.Combine(_templatePath, "ByteCode.stg")))
                {
                    templates = new StringTemplateGroup(fr);
                    fr.Close();
                }

                if (_outputAstGraph)
                {
                    DotTreeGenerator dotgen = new DotTreeGenerator();
                    string           dot    = dotgen.ToDot(t);

                    TextWriter tw = new StreamWriter("ast.txt");
                    tw.WriteLine(dot);
                    tw.Close();
                }

                Analyze analyze = new Analyze(nodes, symtab);
                analyze.TraceDestination = _traceRedirect;
                analyze.Downup(t);

                nodes.Reset();

                foreach (Compiler.BranchAnalyze.FunctionBranch b in analyze.FunctionBranches.Where(pred => pred.Type != null))
                {
                    if (!b.AllCodePathsReturn())
                    {
                        if (_listener != null)
                        {
                            _listener.Error("line: " + b.Node.Line + ":" +
                                            b.Node.CharPositionInLine + " " + b.Node.Text + "(): Not all control paths return a value");
                        }
                    }
                }

                if (_listener.HasErrors() || analyze.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                //
                // Bytecode generation
                //
                Gen g = new Gen(nodes, symtab);
                g.TemplateGroup    = templates;
                g.TraceDestination = _traceRedirect;

                Gen.script_return ret = g.script();

                if (_listener.HasErrors() || g.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }

                if (ret.Template == null)
                {
                    return(null);
                }

                StringTemplate template = ret.Template;

                if (_byteCodeDebugging)
                {
                    _byteCode = template.ToString();
                }

                //
                // Bytecode compilation
                //
                AssemblerLexer    alex    = new AssemblerLexer(new ANTLRStringStream(template.ToString()));
                CommonTokenStream atokens = new CommonTokenStream(alex);
                AssemblerParser   ap      = new AssemblerParser(atokens);
                BytecodeGenerator bcgen   = new BytecodeGenerator(Defaults.SystemMethods.Values);

                ap.SetGenerator(bcgen);
                ap.TraceDestination = _traceRedirect;

                try
                {
                    ap.program();

                    if (_listener.HasErrors() || p.NumberOfSyntaxErrors > 0)
                    {
                        _listener.Error(Convert.ToString(ap.NumberOfSyntaxErrors) + " bytecode generation error(s)");
                        return(null);
                    }

                    return(bcgen.Result);
                }
                catch (GenerationException e)
                {
                    _listener.Error(e.Message);
                }

                return(null);
            }
            catch (TooManyErrorsException e)
            {
                _listener.Error(String.Format("Too many errors {0}", e.InnerException.Message));
            }
            catch (RecognitionException e)
            {
                _listener.Error("line: " + e.Line.ToString() + ":" + e.CharPositionInLine.ToString() + " " + e.Message);
            }
            catch (Exception e)
            {
                _listener.Error(e.Message);
            }

            return(null);
        }
コード例 #22
0
 private void SetArgValue(Def<Args> arg, int value)
 {
     arg.Value = value;
 }
コード例 #23
0
        private Label GetLabelValue(Def<Labels> label)
        {
            Label result;

            if (label.Value == null)
            {
                result = il.DefineLabel();
                label.Value = result;
            }
            else
            {
                result = (Label)label.Value;
            }

            return result;
        }
コード例 #24
0
 public EmitSyntax Local(Def<Locals> def, Ref<Types> typeName)
 {
     var localBuilder = il.DeclareLocal(GetTypeValue(typeName));
     def.Value = localBuilder;
     return this;
 }
コード例 #25
0
 public EmitSyntax Label(Def<Labels> label)
 {
     this.il.MarkLabel(GetLabelValue(label));
     return this;
 }
コード例 #26
0
        ///<summary>Used to check whether codes starting with T exist and are in a visible category.  If so, it moves them to the Obsolete category.  If the T code has never been used, then it deletes it.</summary>
        public static void TcodesClear()
        {
            //first delete any unused T codes
            string    command = @"SELECT CodeNum,ProcCode FROM procedurecode
				WHERE NOT EXISTS(SELECT * FROM procedurelog WHERE procedurelog.CodeNum=procedurecode.CodeNum)
				AND ProcCode LIKE 'T%'"                ;
            DataTable table   = General.GetTable(command);
            int       codenum;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                codenum = PIn.PInt(table.Rows[i]["CodeNum"].ToString());
                command = "DELETE FROM fee WHERE CodeNum=" + POut.PInt(codenum);
                General.NonQ(command);
                command = "DELETE FROM procedurecode WHERE CodeNum=" + POut.PInt(codenum);
                General.NonQ(command);
            }
            //then, move any other T codes to obsolete category
            command = @"SELECT DISTINCT ProcCat FROM procedurecode,definition 
				WHERE procedurecode.ProcCode LIKE 'T%'
				AND definition.IsHidden=0
				AND procedurecode.ProcCat=definition.DefNum"                ;
            table   = General.GetTable(command);
            int catNum = DefB.GetByExactName(DefCat.ProcCodeCats, "Obsolete");         //check to make sure an Obsolete category exists.
            Def def;

            if (catNum != 0)           //if a category exists with that name
            {
                def = DefB.GetDef(DefCat.ProcCodeCats, catNum);
                if (!def.IsHidden)
                {
                    def.IsHidden = true;
                    Defs.Update(def);
                    Defs.Refresh();
                }
            }
            if (catNum == 0)
            {
                def           = new Def();
                def.Category  = DefCat.ProcCodeCats;
                def.ItemName  = "Obsolete";
                def.ItemOrder = DefB.Long[(int)DefCat.ProcCodeCats].Length;
                def.IsHidden  = true;
                Defs.Insert(def);
                Defs.Refresh();
                catNum = def.DefNum;
            }
            for (int i = 0; i < table.Rows.Count; i++)
            {
                command = "UPDATE procedurecode SET ProcCat=" + POut.PInt(catNum)
                          + " WHERE ProcCat=" + table.Rows[i][0].ToString();
                General.NonQ(command);
            }
            //finally, set Never Used category to be hidden.  This isn't really part of clearing Tcodes, but is required
            //because many customers won't have that category hidden
            catNum = DefB.GetByExactName(DefCat.ProcCodeCats, "Never Used");
            if (catNum != 0)           //if a category exists with that name
            {
                def = DefB.GetDef(DefCat.ProcCodeCats, catNum);
                if (!def.IsHidden)
                {
                    def.IsHidden = true;
                    Defs.Update(def);
                    Defs.Refresh();
                }
            }
        }
コード例 #27
0
 protected override void OnDefAssigned()
 {
     Def.GetDragHighlightTexture(tex =>
                                 highlightMaterial = MaterialPool.MatFrom(tex, ShaderDatabase.MetaOverlay, Color.white)
                                 );
 }
コード例 #28
0
 public static ThingDefExtension Get(Def def)
 {
     return(def.GetModExtension <ThingDefExtension>() ?? defaultValues);
 }
コード例 #29
0
 public void Build(EmitSyntax emit, Pipe <EmitSyntax> ldvalue, SwitchGeneratorAction action)
 {
     this.END = emit.Labels.Generate();
     DoBuild(emit, ldvalue, action);
 }
コード例 #30
0
ファイル: POS_statements.cs プロジェクト: royedwards/DRDNet
        ///<summary>Adds the xml for one statement.</summary>
        public static void GenerateOneStatement(XmlWriter writer, Statement stmt, Patient pat, Family fam, DataSet dataSet)
        {
            writer.WriteStartElement("Statement");
            writer.WriteStartElement("RecipientAddress");
            Patient guar = fam.ListPats[0];

            writer.WriteElementString("Name", guar.GetNameFLFormal());
            if (PrefC.GetBool(PrefName.StatementAccountsUseChartNumber))
            {
                writer.WriteElementString("Account", guar.ChartNumber);
            }
            else
            {
                writer.WriteElementString("Account", POut.Long(guar.PatNum));
            }
            writer.WriteElementString("Address1", guar.Address);
            writer.WriteElementString("Address2", guar.Address2);
            writer.WriteElementString("City", guar.City);
            writer.WriteElementString("State", guar.State);
            writer.WriteElementString("Zip", guar.Zip);
            string email      = "";
            Def    billingDef = Defs.GetDef(DefCat.BillingTypes, guar.BillingType);

            if (billingDef.ItemValue == "E")
            {
                email = guar.Email;
            }
            writer.WriteElementString("EMail", email);
            writer.WriteEndElement();            //RecipientAddress
            //Account summary-----------------------------------------------------------------------
            if (stmt.DateRangeFrom.Year < 1880)  //make up a statement date.
            {
                writer.WriteElementString("PriorStatementDate", DateTime.Today.AddMonths(-1).ToString("MM/dd/yyyy"));
            }
            else
            {
                writer.WriteElementString("PriorStatementDate", stmt.DateRangeFrom.AddDays(-1).ToString("MM/dd/yyyy"));
            }
            DateTime dueDate;

            if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
            {
                dueDate = DateTime.Today.AddDays(10);
            }
            else
            {
                dueDate = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate));
            }
            writer.WriteElementString("DueDate", dueDate.ToString("MM/dd/yyyy"));
            writer.WriteElementString("StatementDate", stmt.DateSent.ToString("MM/dd/yyyy"));
            double balanceForward = 0;

            for (int r = 0; r < dataSet.Tables["misc"].Rows.Count; r++)
            {
                if (dataSet.Tables["misc"].Rows[r]["descript"].ToString() == "balanceForward")
                {
                    balanceForward = PIn.Double(dataSet.Tables["misc"].Rows[r]["value"].ToString());
                }
            }
            writer.WriteElementString("PriorBalance", balanceForward.ToString("F2"));
            DataTable tableAccount = null;

            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                if (dataSet.Tables[i].TableName.StartsWith("account"))
                {
                    tableAccount = dataSet.Tables[i];
                }
            }
            double credits = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                credits += PIn.Double(tableAccount.Rows[i]["creditsDouble"].ToString());
            }
            writer.WriteElementString("Credits", credits.ToString("F2"));
            decimal payPlanDue = 0;
            double  amountDue  = guar.BalTotal;

            for (int m = 0; m < dataSet.Tables["misc"].Rows.Count; m++)
            {
                if (dataSet.Tables["misc"].Rows[m]["descript"].ToString() == "payPlanDue")
                {
                    payPlanDue += PIn.Decimal(dataSet.Tables["misc"].Rows[m]["value"].ToString());                  //This will be an option once more users are using it.
                }
            }
            writer.WriteElementString("PayPlanDue", payPlanDue.ToString("F2"));
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                writer.WriteElementString("EstInsPayments", "");                         //optional.
            }
            else                                                                         //this is typical
            {
                writer.WriteElementString("EstInsPayments", guar.InsEst.ToString("F2")); //optional.
                amountDue -= guar.InsEst;
            }
            InstallmentPlan installPlan = InstallmentPlans.GetOneForFam(guar.PatNum);

            if (installPlan != null)
            {
                //show lesser of normal total balance or the monthly payment amount.
                if (installPlan.MonthlyPayment < amountDue)
                {
                    amountDue = installPlan.MonthlyPayment;
                }
            }
            writer.WriteElementString("AmountDue", amountDue.ToString("F2"));
            writer.WriteElementString("PastDue30", guar.Bal_31_60.ToString("F2"));           //optional
            writer.WriteElementString("PastDue60", guar.Bal_61_90.ToString("F2"));           //optional
            writer.WriteElementString("PastDue90", guar.BalOver90.ToString("F2"));           //optional
            //Notes-----------------------------------------------------------------------------------
            writer.WriteStartElement("Notes");
            if (stmt.NoteBold != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", "Red");
                writer.WriteCData(stmt.NoteBold);
                writer.WriteEndElement();                //Note
            }
            if (stmt.Note != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteCData(stmt.Note);
                writer.WriteEndElement();        //Note
            }
            writer.WriteEndElement();            //Notes
            //Detail items------------------------------------------------------------------------------
            writer.WriteStartElement("DetailItems");
            //string note;
            string descript;
            string fulldesc;
            string procCode;
            string tth;

            //string linedesc;
            string[]      lineArray;
            List <string> lines;
            DateTime      date;
            int           seq = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                procCode  = tableAccount.Rows[i]["ProcCode"].ToString();
                tth       = tableAccount.Rows[i]["tth"].ToString();
                descript  = tableAccount.Rows[i]["description"].ToString();
                fulldesc  = procCode + " " + tth + " " + descript;
                lineArray = fulldesc.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                lines     = new List <string>(lineArray);
                //The specs say that the line limit is 30 char.  But in testing, it will take 50 char.
                //We will use 40 char to be safe.
                if (lines[0].Length > 40)
                {
                    string newline = lines[0].Substring(40);
                    lines[0] = lines[0].Substring(0, 40);       //first half
                    lines.Insert(1, newline);                   //second half
                }
                for (int li = 0; li < lines.Count; li++)
                {
                    writer.WriteStartElement("DetailItem");                    //has a child item. We won't add optional child note
                    writer.WriteAttributeString("sequence", seq.ToString());
                    writer.WriteStartElement("Item");
                    if (li == 0)
                    {
                        date = (DateTime)tableAccount.Rows[i]["DateTime"];
                        writer.WriteElementString("Date", date.ToString("MM/dd/yyyy"));
                        writer.WriteElementString("PatientName", tableAccount.Rows[i]["patient"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Date", "");
                        writer.WriteElementString("PatientName", "");
                    }
                    writer.WriteElementString("Description", lines[li]);
                    if (li == 0)
                    {
                        writer.WriteElementString("Charges", tableAccount.Rows[i]["charges"].ToString());
                        writer.WriteElementString("Credits", tableAccount.Rows[i]["credits"].ToString());
                        writer.WriteElementString("Balance", tableAccount.Rows[i]["balance"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Charges", "");
                        writer.WriteElementString("Credits", "");
                        writer.WriteElementString("Balance", "");
                    }
                    writer.WriteEndElement();                    //Item
                    writer.WriteEndElement();                    //DetailItem
                    seq++;
                }
            }
            writer.WriteEndElement();            //DetailItems
            writer.WriteEndElement();            //Statement
        }
コード例 #31
0
 /// <summary>
 /// Initialize.
 /// </summary>
 /// <param name="def">The struct definition.</param>
 /// <param name="index">The index of the key to access.</param>
 public AccessorFn(Def def, int index)
 {
     _def = def;
     _index = index;
 }
コード例 #32
0
        public static Texture2D IconTexture(this Def def)
        {
            // check cache
            if (_cachedDefIcons.ContainsKey(def.defName))
            {
                return(_cachedDefIcons[def.defName]);
            }

            // otherwise try to determine icon
            var bdef = def as BuildableDef;
            var tdef = def as ThingDef;
            var pdef = def as PawnKindDef;
            var rdef = def as RecipeDef;

            // recipes will be passed icon of first product, if defined.
            if (
                (rdef != null) &&
                (!rdef.products.NullOrEmpty())
                )
            {
                _cachedDefIcons[def.defName] = rdef.products.First().thingDef.IconTexture();
                return(_cachedDefIcons[def.defName]);
            }

            // animals need special treatment ( this will still only work for animals, pawns are a whole different can o' worms ).
            if (pdef != null)
            {
                try
                {
                    _cachedDefIcons[def.defName] = (pdef.lifeStages.Last().bodyGraphicData.Graphic.MatSouth.mainTexture as Texture2D).Crop();
                    return(_cachedDefIcons[def.defName]);
                }
                catch (Exception e)
                {
                    Log.Error("CombatExtended :: IconTexture(" + def.ToString() + ") - pawnKindDef check - resulted in the following error [defaulting to non-cropped texture]: " + e.ToString());
                    _cachedDefIcons[def.defName] = (pdef.lifeStages.Last().bodyGraphicData.Graphic.MatSouth.mainTexture as Texture2D);
                    return(_cachedDefIcons[def.defName]);
                }
            }

            // if not buildable it probably doesn't have an icon.
            if (bdef == null)
            {
                return(null);
            }

            // if def built != def listed.
            if (
                (tdef != null) &&
                (tdef.entityDefToBuild != null)
                )
            {
                try
                {
                    _cachedDefIcons[def.defName] = tdef.entityDefToBuild.IconTexture().Crop();
                    return(_cachedDefIcons[def.defName]);
                }
                catch (Exception e)
                {
                    Log.Error("CombatExtended :: IconTexture(" + def.ToString() + ") - entityDefToBuild check - resulted in the following error [defaulting to non-cropped texture]: " + e.ToString());
                    _cachedDefIcons[def.defName] = tdef.entityDefToBuild.IconTexture();
                    return(_cachedDefIcons[def.defName]);
                }
            }

            _cachedDefIcons[def.defName] = bdef.uiIcon;
            return(_cachedDefIcons[def.defName]);
        }
コード例 #33
0
ファイル: DefCrud.cs プロジェクト: nampn/ODental
 ///<summary>Updates one Def in the database.</summary>
 internal static void Update(Def def)
 {
     string command="UPDATE definition SET "
         +"Category =  "+POut.Int   ((int)def.Category)+", "
         +"ItemOrder=  "+POut.Int   (def.ItemOrder)+", "
         +"ItemName = '"+POut.String(def.ItemName)+"', "
         +"ItemValue= '"+POut.String(def.ItemValue)+"', "
         +"ItemColor=  "+POut.Int   (def.ItemColor.ToArgb())+", "
         +"IsHidden =  "+POut.Bool  (def.IsHidden)+" "
         +"WHERE DefNum = "+POut.Long(def.DefNum);
     Db.NonQ(command);
 }
コード例 #34
0
    public static void Init()
    {
        entries             = new Dictionary <string, CodexEntry>();
        unlockedEntryLookup = new Dictionary <string, List <string> >();
        Dictionary <string, CodexEntry> dictionary = new Dictionary <string, CodexEntry>();

        if (widgetTagMappings == null)
        {
            List <Tuple <string, Type> > list = new List <Tuple <string, Type> >();
            list.Add(new Tuple <string, Type>("!CodexText", typeof(CodexText)));
            list.Add(new Tuple <string, Type>("!CodexImage", typeof(CodexImage)));
            list.Add(new Tuple <string, Type>("!CodexDividerLine", typeof(CodexDividerLine)));
            list.Add(new Tuple <string, Type>("!CodexSpacer", typeof(CodexSpacer)));
            list.Add(new Tuple <string, Type>("!CodexLabelWithIcon", typeof(CodexLabelWithIcon)));
            list.Add(new Tuple <string, Type>("!CodexLabelWithLargeIcon", typeof(CodexLabelWithLargeIcon)));
            list.Add(new Tuple <string, Type>("!CodexContentLockedIndicator", typeof(CodexContentLockedIndicator)));
            list.Add(new Tuple <string, Type>("!CodexLargeSpacer", typeof(CodexLargeSpacer)));
            list.Add(new Tuple <string, Type>("!CodexVideo", typeof(CodexVideo)));
            widgetTagMappings = list;
        }
        string text = FormatLinkID("tips");

        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.TIPS, CodexEntryGenerator.GenerateTutorialNotificationEntries(), Assets.GetSprite("unknown"), false, false, UI.CODEX.TIPS));
        text = FormatLinkID("creatures");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.CREATURES, CodexEntryGenerator.GenerateCreatureEntries(), Def.GetUISpriteFromMultiObjectAnim(Assets.GetPrefab("Hatch").GetComponent <KBatchedAnimController>().AnimFiles[0], "ui", false, string.Empty), true, true, null));
        text = FormatLinkID("plants");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.PLANTS, CodexEntryGenerator.GeneratePlantEntries(), Def.GetUISpriteFromMultiObjectAnim(Assets.GetPrefab("PrickleFlower").GetComponent <KBatchedAnimController>().AnimFiles[0], "ui", false, string.Empty), true, true, null));
        text = FormatLinkID("food");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.FOOD, CodexEntryGenerator.GenerateFoodEntries(), Def.GetUISpriteFromMultiObjectAnim(Assets.GetPrefab("CookedMeat").GetComponent <KBatchedAnimController>().AnimFiles[0], "ui", false, string.Empty), true, true, null));
        text = FormatLinkID("buildings");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.BUILDINGS, CodexEntryGenerator.GenerateBuildingEntries(), Def.GetUISpriteFromMultiObjectAnim(Assets.GetPrefab("Generator").GetComponent <KBatchedAnimController>().AnimFiles[0], "ui", false, string.Empty), true, true, null));
        text = FormatLinkID("tech");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.TECH, CodexEntryGenerator.GenerateTechEntries(), Assets.GetSprite("hud_research"), true, true, null));
        text = FormatLinkID("roles");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.ROLES, CodexEntryGenerator.GenerateRoleEntries(), Assets.GetSprite("hat_role_mining2"), true, true, null));
        text = FormatLinkID("disease");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.DISEASE, CodexEntryGenerator.GenerateDiseaseEntries(), Assets.GetSprite("codexDiseases"), false, true, null));
        text = FormatLinkID("elements");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.ELEMENTS, CodexEntryGenerator.GenerateElementEntries(), null, true, false, null));
        text = FormatLinkID("geysers");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.GEYSERS, CodexEntryGenerator.GenerateGeyserEntries(), null, true, true, null));
        text = FormatLinkID("equipment");
        dictionary.Add(text, CodexEntryGenerator.GenerateCategoryEntry(text, UI.CODEX.CATEGORYNAMES.EQUIPMENT, CodexEntryGenerator.GenerateEquipmentEntries(), null, true, true, null));
        CategoryEntry item = CodexEntryGenerator.GenerateCategoryEntry(FormatLinkID("HOME"), UI.CODEX.CATEGORYNAMES.ROOT, dictionary, null, true, true, null);

        CodexEntryGenerator.GeneratePageNotFound();
        List <CategoryEntry> list2 = new List <CategoryEntry>();

        foreach (KeyValuePair <string, CodexEntry> item2 in dictionary)
        {
            list2.Add(item2.Value as CategoryEntry);
        }
        CollectYAMLEntries(list2);
        CollectYAMLSubEntries(list2);
        CheckUnlockableContent();
        list2.Add(item);
        foreach (KeyValuePair <string, CodexEntry> entry in entries)
        {
            if (entry.Value.subEntries.Count > 0)
            {
                entry.Value.subEntries.Sort((SubEntry a, SubEntry b) => a.layoutPriority.CompareTo(b.layoutPriority));
                if ((UnityEngine.Object)entry.Value.icon == (UnityEngine.Object)null)
                {
                    entry.Value.icon      = entry.Value.subEntries[0].icon;
                    entry.Value.iconColor = entry.Value.subEntries[0].iconColor;
                }
                int num = 0;
                foreach (SubEntry subEntry in entry.Value.subEntries)
                {
                    if (subEntry.lockID != null && !Game.Instance.unlocks.IsUnlocked(subEntry.lockID))
                    {
                        num++;
                    }
                }
                List <ICodexWidget> list3 = new List <ICodexWidget>();
                list3.Add(new CodexSpacer());
                list3.Add(new CodexText((string)CODEX.HEADERS.SUBENTRIES + " (" + (entry.Value.subEntries.Count - num) + "/" + entry.Value.subEntries.Count + ")", CodexTextStyle.Subtitle));
                foreach (SubEntry subEntry2 in entry.Value.subEntries)
                {
                    if (subEntry2.lockID != null && !Game.Instance.unlocks.IsUnlocked(subEntry2.lockID))
                    {
                        list3.Add(new CodexText(UI.FormatAsLink(CODEX.HEADERS.CONTENTLOCKED, UI.ExtractLinkID(subEntry2.name)), CodexTextStyle.Body));
                    }
                    else
                    {
                        list3.Add(new CodexText(subEntry2.name, CodexTextStyle.Body));
                    }
                }
                list3.Add(new CodexSpacer());
                entry.Value.contentContainers.Insert(entry.Value.customContentLength, new ContentContainer(list3, ContentContainer.ContentLayout.Vertical));
            }
            for (int i = 0; i < entry.Value.subEntries.Count; i++)
            {
                entry.Value.contentContainers.AddRange(entry.Value.subEntries[i].contentContainers);
            }
        }
        CodexEntryGenerator.PopulateCategoryEntries(list2, delegate(CodexEntry a, CodexEntry b)
        {
            if (a.name == (string)UI.CODEX.CATEGORYNAMES.TIPS)
            {
                return(-1);
            }
            if (b.name == (string)UI.CODEX.CATEGORYNAMES.TIPS)
            {
                return(1);
            }
            return(UI.StripLinkFormatting(a.name).CompareTo(UI.StripLinkFormatting(b.name)));
        });
    }
コード例 #35
0
        public override void Init()
        {
            filePath = Def.Get <string>("filePath");
            volume   = Def.Get("volume", 1f);
            string format = Def.Get("format", "OGGVORBIS");

            if (!Enum.TryParse <AudioType>(format.Trim(), true, out var formatEnum))
            {
                Core.Error($"Failed to parse audio format '{format}'.");
                Array    arr  = Enum.GetValues(typeof(AudioType));
                object[] args = arr.Cast <object>().ToArray();
                Core.Error($"Valid values are: {string.Join(", ", args)}");
                Core.Error("Note: .mp3 is NOT SUPPORTED. I recommend using .ogg (OGGVORBIS) or .wav (WAV)");
                Remove();
                return;
            }

            // Resolve the file path.
            ModContentPack mcp = Def.modContentPack;

            if (mcp == null)
            {
                string[] split = filePath.Split('/');
                split[0] = split[0].ToLowerInvariant();
                Core.Warn($"Song player program def '{Def.defName}' has been added by a patch operation. Attempting to resolve filepath...");
                var found = LoadedModManager.RunningModsListForReading.FirstOrFallback(mod => mod.PackageId.ToLowerInvariant() == split[0]);
                if (found == null)
                {
                    Core.Error($"Failed to resolve mod folder path from id '{split[0]}'. See below for how to solve this issue.");
                    Core.Error("If you mod's package ID is 'my.mod.name' and your song file is in 'MyModFolder/Songs/Song.mp3' then the correct filePath would be 'my.mod.name/Songs/Song.mp3'");
                    Remove();
                    return;
                }
                Core.Warn("Successfully resolved file path.");
                mcp = found;
            }
            filePath = Path.Combine(mcp.RootDir, filePath);

            if (clipCache.TryGetValue(filePath, out var clip))
            {
                FlagLoadedForClip(clip);
            }
            else
            {
                Task.Run(async() =>
                {
                    try
                    {
                        Core.Log($"Loading '{filePath}' as {formatEnum} ...");
                        var c     = await AudioLoader.TryLoadAsync(filePath, formatEnum);
                        clipToAdd = c; // Push to main thread, see Tick()
                        Core.Log("Done");
                    }
                    catch (Exception e)
                    {
                        Core.Error($"Failed loading song clip from '{filePath}' in format {formatEnum}", e);
                        Remove();
                    }
                });
            }

            string msg = "DSC.NowPlaying".Translate(Def.Get("credits", "Unknown"));

            Messages.Message(msg, MessageTypeDefOf.PositiveEvent);
        }
コード例 #36
0
 public void JumpTo(Def def)
 {
     JumpTo(def.GetHelpDef());
 }
コード例 #37
0
 protected virtual PersistentStructMap makeNew(IPersistentMap meta, Def def, object[] vals, IPersistentMap ext)
 {
     return(new PersistentStructMap(meta, def, vals, ext));
 }
コード例 #38
0
 public override Sprite GetSprite(string topic)
 {
     return(Def.GetUISprite(topic, "ui", true)?.first);
 }
コード例 #39
0
 ///<summary></summary>
 public FormDefEdit(Def defCur)
 {
     InitializeComponent();            // Required for Windows Form Designer support
     Lan.F(this);
     DefCur = defCur.Copy();
 }
コード例 #40
0
 public Tale_DoublePawnAndDef(Pawn firstPawn, Pawn secondPawn, Def def) : base(firstPawn, secondPawn)
 {
     this.defData = TaleData_Def.GenerateFrom(def);
 }
コード例 #41
0
		///<summary>Fills with jobs that are attached to the selected sprint and are not complete. Ordered by owner and then category.</summary>
		private void FillGridQueue() {
			gridSprintQueue.BeginUpdate();
			gridSprintQueue.ListGridColumns.Clear();
			gridSprintQueue.ListGridColumns.Add(new GridColumn("Priority",90,HorizontalAlignment.Center));
			gridSprintQueue.ListGridColumns.Add(new GridColumn("Owner",55,HorizontalAlignment.Center));
			gridSprintQueue.ListGridColumns.Add(new GridColumn("Owner Action",110));
			gridSprintQueue.ListGridColumns.Add(new GridColumn("EstHrs",60,HorizontalAlignment.Center,GridSortingStrategy.AmountParse));
			gridSprintQueue.ListGridColumns.Add(new GridColumn("ActHrs",60,HorizontalAlignment.Center,GridSortingStrategy.AmountParse));
			gridSprintQueue.ListGridColumns.Add(new GridColumn("",300));
			gridSprintQueue.ListGridRows.Clear();
			List<Job> listQueue=_listAttachedJobs.Where(x => x.PhaseCur.In(JobPhase.Concept,JobPhase.Definition,JobPhase.Quote)).ToList();
			listQueue=listQueue.OrderBy(x => x.OwnerNum!=0)
					//This is the reverse order of the actual priority of different categories of jobs
					//Purposefully put in this order so they appear correctly in the list.
					.ThenBy(x => x.Category==JobCategory.NeedNoApproval)
					.ThenBy(x => x.Category==JobCategory.Research)
					.ThenBy(x => x.Category==JobCategory.Conversion)
					.ThenBy(x => x.Category==JobCategory.HqRequest)
					.ThenBy(x => x.Category==JobCategory.InternalRequest)
					.ThenBy(x => x.Category==JobCategory.Feature)
					.ThenBy(x => x.Category==JobCategory.Query)
					.ThenBy(x => x.Category==JobCategory.ProgramBridge)
					.ThenBy(x => x.Category==JobCategory.Enhancement)
					.ThenBy(x => x.Category==JobCategory.Bug)
					.ThenBy(x => _listJobPriorities.FirstOrDefault(y => y.DefNum==x.Priority).ItemOrder).ToList();
			Dictionary<JobPhase,List<Job>> dictPhases=new Dictionary<JobPhase,List<Job>>();
			foreach(Job job in listQueue) {
				JobPhase phase=job.PhaseCur;
				if(!dictPhases.ContainsKey(phase)) {
					dictPhases[phase]=new List<Job>();
				}
				dictPhases[phase].Add(job);
			}
			//sort dictionary so actions will appear in same order
			//This is in reverse order in the code so it is correct in the UI
			dictPhases=dictPhases.OrderBy(x => x.Key==JobPhase.Concept)
					.ThenBy(x => x.Key==JobPhase.Quote)
					.ThenBy(x => x.Key==JobPhase.Definition).ToDictionary(x => x.Key,x => x.Value);
			foreach(KeyValuePair<JobPhase,List<Job>> kvp in dictPhases) {
				if(listQueue.Count==0) {
					continue;
				}
				gridSprintQueue.ListGridRows.Add(new GridRow("","","","","",kvp.Key.ToString()) { ColorBackG=Color.FromArgb(223,234,245),Bold=true });
				foreach(Job job in kvp.Value) {
					Color backColor=Color.White;
					Def jobPriority=_listJobPriorities.FirstOrDefault(y => y.DefNum==job.Priority);
					gridSprintQueue.ListGridRows.Add(
					new GridRow(
						new GridCell(jobPriority.ItemName) {
							ColorBackG=jobPriority.ItemColor,
							ColorText=(job.Priority==_listJobPriorities.FirstOrDefault(y => y.ItemValue.Contains("Urgent")).DefNum) ? Color.White : Color.Black,
						},
						new GridCell(job.OwnerNum==0 ? "-" : Userods.GetName(job.OwnerNum)),
						new GridCell(job.OwnerAction.GetDescription()),
						new GridCell(job.HoursEstimate.ToString()),
						new GridCell(job.HoursActual.ToString()),
						new GridCell(job.ToString())
						) {
						Tag=job,
						ColorBackG=backColor
					}
					);
				}
			}
			gridSprintQueue.EndUpdate();
		}
コード例 #42
0
        static bool IsThisMod(Def def)
        {
            var rjwContent = LoadedModManager.RunningMods.Single(pack => pack.Name == "RimJobWorld");

            return(rjwContent.AllDefs.Contains(def));
        }
コード例 #43
0
 public Tale_SinglePawnAndDef(Pawn pawn, Def def) : base(pawn)
 {
     this.defData = TaleData_Def.GenerateFrom(def);
 }
コード例 #44
0
 private void FetchNext(EmitSyntax emit, Def<Labels> END_OF_INPUT)
 {
     emit
         .Ldloc(Index.GetRef())
         .Ldc_I4_1()
         .Add()
         .Stloc(Index.GetRef())
         // ++Index
         // if (Index == count) goto END
         .Ldloc(Index.GetRef())
         .Ldloc(count.GetRef())
         .Beq(END_OF_INPUT.GetRef())
         .Do(ldarray)
         .Ldloc(Index.GetRef())
         .Ldelem(valueType)
         .Stloc(Value.GetRef())
         ;
 }
コード例 #45
0
 public Instance(IStateMachineTarget master, Def def) : base(master, def)
 {
 }
コード例 #46
0
        public INfaVM Label(Def<Labels> label)
        {
            emit.Label(label);
            if (!indexToLabel.Contains(label))
            {
                indexToLabel.Add(label);
            }

            return this;
        }
コード例 #47
0
        ///<summary>Adds the xml for one statement.</summary>
        public static void GenerateOneStatement(XmlWriter writer, Statement stmt, Patient pat, Family fam, DataSet dataSet)
        {
            writer.WriteStartElement("EisStatement");
            writer.WriteAttributeString("OutputFormat", "StmOut_Blue6Col");
            writer.WriteAttributeString("CreditCardChoice", PrefC.GetString(PrefName.BillingElectCreditCardChoices));
            writer.WriteStartElement("Patient");
            Patient guar = fam.ListPats[0];

            writer.WriteElementString("Name", guar.GetNameFLFormal());
            writer.WriteElementString("Account", guar.PatNum.ToString());
            writer.WriteElementString("Address1", guar.Address);
            writer.WriteElementString("Address2", guar.Address2);
            writer.WriteElementString("City", guar.City);
            writer.WriteElementString("State", guar.State);
            writer.WriteElementString("Zip", guar.Zip);
            string email      = "";
            Def    billingDef = DefC.GetDef(DefCat.BillingTypes, guar.BillingType);

            if (billingDef.ItemValue == "E")
            {
                email = guar.Email;
            }
            writer.WriteElementString("EMail", email);
            //Account summary-----------------------------------------------------------------------
            writer.WriteStartElement("AccountSummary");
            if (stmt.DateRangeFrom.Year < 1880)           //make up a statement date.
            {
                writer.WriteElementString("PriorStatementDate", DateTime.Today.AddMonths(-1).ToString("MM/dd/yyyy"));
            }
            else
            {
                writer.WriteElementString("PriorStatementDate", stmt.DateRangeFrom.AddDays(-1).ToString("MM/dd/yyyy"));
            }
            DateTime dueDate;

            if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
            {
                dueDate = DateTime.Today.AddDays(10);
            }
            else
            {
                dueDate = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate));
            }
            writer.WriteElementString("DueDate", dueDate.ToString("MM/dd/yyyy"));
            writer.WriteElementString("StatementDate", stmt.DateSent.ToString("MM/dd/yyyy"));
            double balanceForward = 0;

            for (int r = 0; r < dataSet.Tables["misc"].Rows.Count; r++)
            {
                if (dataSet.Tables["misc"].Rows[r]["descript"].ToString() == "balanceForward")
                {
                    balanceForward = PIn.Double(dataSet.Tables["misc"].Rows[r]["value"].ToString());
                }
            }
            writer.WriteElementString("PriorBalance", balanceForward.ToString("F2"));
            writer.WriteElementString("RunningBalance", "");      //for future use
            writer.WriteElementString("PerPayAdj", "");           //optional
            writer.WriteElementString("InsPayAdj", "");           //optional
            writer.WriteElementString("Adjustments", "");         //for future use
            writer.WriteElementString("NewCharges", "");          //optional
            writer.WriteElementString("FinanceCharges", "");      //for future use
            DataTable tableAccount = null;

            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                if (dataSet.Tables[i].TableName.StartsWith("account"))
                {
                    tableAccount = dataSet.Tables[i];
                }
            }
            double credits = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                credits += PIn.Double(tableAccount.Rows[i]["creditsDouble"].ToString());
            }
            writer.WriteElementString("Credits", credits.ToString("F2"));
            //on a regular printed statement, the amount due at the top might be different from the balance at the middle right.
            //This is because of payment plan balances.
            //But in e-bills, there is only one amount due.
            //Insurance estimate is already subtracted, and payment plan balance is already added.
            double amountDue = guar.BalTotal;

            //add payplan due amt:
            for (int m = 0; m < dataSet.Tables["misc"].Rows.Count; m++)
            {
                if (dataSet.Tables["misc"].Rows[m]["descript"].ToString() == "payPlanDue")
                {
                    amountDue += PIn.Double(dataSet.Tables["misc"].Rows[m]["value"].ToString());
                }
            }
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                writer.WriteElementString("EstInsPayments", "");               //optional.
                writer.WriteElementString("PatientShare", amountDue.ToString("F2"));
                //this is ambiguous.  It seems to be AmountDue, but it could possibly be 0-30 days aging
                writer.WriteElementString("CurrentBalance", amountDue.ToString("F2"));
            }
            else                                                                         //this is typical
            {
                writer.WriteElementString("EstInsPayments", guar.InsEst.ToString("F2")); //optional.
                amountDue -= guar.InsEst;
                writer.WriteElementString("PatientShare", amountDue.ToString("F2"));
                writer.WriteElementString("CurrentBalance", amountDue.ToString("F2"));
            }
            writer.WriteElementString("PastDue30", guar.Bal_31_60.ToString("F2")); //optional
            writer.WriteElementString("PastDue60", guar.Bal_61_90.ToString("F2")); //optional
            writer.WriteElementString("PastDue90", guar.BalOver90.ToString("F2")); //optional
            writer.WriteElementString("PastDue120", "");                           //optional
            writer.WriteEndElement();                                              //AccountSummary
            //Notes-----------------------------------------------------------------------------------
            writer.WriteStartElement("Notes");
            if (stmt.NoteBold != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", "Red");               //ColorToHexString(Color.DarkRed));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.NoteBold);
                writer.WriteEndElement();                //Note
            }
            if (stmt.Note != "")
            {
                writer.WriteStartElement("Note");
                //writer.WriteAttributeString("FgColor",ColorToHexString(Color.Black));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.Note);
                writer.WriteEndElement();        //Note
            }
            writer.WriteEndElement();            //Notes
            //Detail items------------------------------------------------------------------------------
            writer.WriteStartElement("DetailItems");
            //string note;
            string descript;
            string fulldesc;
            string procCode;
            string tth;

            //string linedesc;
            string[]      lineArray;
            List <string> lines;
            DateTime      date;
            int           seq = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                procCode  = tableAccount.Rows[i]["ProcCode"].ToString();
                tth       = tableAccount.Rows[i]["tth"].ToString();
                descript  = tableAccount.Rows[i]["description"].ToString();
                fulldesc  = procCode + " " + tth + " " + descript;
                lineArray = fulldesc.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                lines     = new List <string>(lineArray);
                //The specs say that the line limit is 30 char.  But in testing, it will take 50 char.
                //We will use 40 char to be safe.
                if (lines[0].Length > 40)
                {
                    string newline = lines[0].Substring(40);
                    lines[0] = lines[0].Substring(0, 40);       //first half
                    lines.Insert(1, newline);                   //second half
                }
                for (int li = 0; li < lines.Count; li++)
                {
                    writer.WriteStartElement("DetailItem");                    //has a child item. We won't add optional child note
                    writer.WriteAttributeString("sequence", seq.ToString());
                    writer.WriteStartElement("Item");
                    if (li == 0)
                    {
                        date = (DateTime)tableAccount.Rows[i]["DateTime"];
                        writer.WriteElementString("Date", date.ToString("MM/dd/yyyy"));
                        writer.WriteElementString("PatientName", tableAccount.Rows[i]["patient"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Date", "");
                        writer.WriteElementString("PatientName", "");
                    }
                    writer.WriteElementString("Description", lines[li]);
                    if (li == 0)
                    {
                        writer.WriteElementString("Charges", tableAccount.Rows[i]["charges"].ToString());
                        writer.WriteElementString("Credits", tableAccount.Rows[i]["credits"].ToString());
                        writer.WriteElementString("Balance", tableAccount.Rows[i]["balance"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Charges", "");
                        writer.WriteElementString("Credits", "");
                        writer.WriteElementString("Balance", "");
                    }
                    writer.WriteEndElement();                    //Item
                    writer.WriteEndElement();                    //DetailItem
                    seq++;
                }

                /*The code below just didn't work because notes don't get displayed on the statement.
                 * linedesc=lines[0];
                 * note="";
                 * if(linedesc.Length>30) {
                 *      note=linedesc.Substring(30);
                 *      linedesc=linedesc.Substring(0,30);
                 * }
                 * for(int l=1;l<lines.Length;l++) {
                 *      if(note!="") {
                 *              note+="\r\n";
                 *      }
                 *      note+=lines[l];
                 * }
                 *
                 * if(note!="") {
                 *      writer.WriteStartElement("Note");
                 *      //we're not going to specify colors here since they're optional
                 *      writer.WriteCData(note);
                 *      writer.WriteEndElement();//Note
                 * }*/
            }
            writer.WriteEndElement();            //DetailItems
            writer.WriteEndElement();            //Patient
            writer.WriteEndElement();            //EisStatement
        }
コード例 #48
0
ファイル: DefExtensions.cs プロジェクト: vishalswami/RimWorld
 public static void DrawColouredIcon(this Def def, Rect canvas)
 {
     GUI.color = def.IconColor();
     GUI.DrawTexture(canvas, def.IconTexture(), ScaleMode.ScaleToFit);
     GUI.color = Color.white;
 }
コード例 #49
0
 /// <summary>
 /// Create a structure from the given data.
 /// </summary>
 /// <param name="meta"></param>
 /// <param name="def"></param>
 /// <param name="vals"></param>
 /// <param name="ext"></param>
 /// <returns></returns>
 /// <remarks>
 /// This method is used instead of the PersistentStructMap constructor by
 /// all methods that return a new PersistentStructMap.  This is done
 /// to allow subclasses to override this method to return instances of their own class from 
 /// all PersistentStructMap methods.
 /// </remarks>
 protected virtual PersistentStructMap makeNew(IPersistentMap meta, Def def, object[] vals, IPersistentMap ext)
 {
     return new PersistentStructMap(meta, def, vals, ext);
 }
コード例 #50
0
        public static object ReadSyncObject(ByteReader data, SyncType syncType)
        {
            MpContext context = data.MpContext();
            Map       map     = context.map;
            Type      type    = syncType.type;

            try
            {
                if (typeof(object) == type)
                {
                    return(null);
                }

                if (type.IsByRef)
                {
                    return(null);
                }

                if (syncWorkersEarly.TryGetValue(type, out SyncWorkerEntry syncWorkerEntryEarly))
                {
                    object res = null;

                    if (syncWorkerEntryEarly.shouldConstruct || type.IsValueType)
                    {
                        res = Activator.CreateInstance(type);
                    }

                    syncWorkerEntryEarly.Invoke(new ReadingSyncWorker(data), ref res);

                    return(res);
                }

                if (syncType.expose)
                {
                    if (!typeof(IExposable).IsAssignableFrom(type))
                    {
                        throw new SerializationException($"Type {type} can't be exposed because it isn't IExposable");
                    }

                    byte[] exposableData = data.ReadPrefixedBytes();
                    return(ReadExposable.MakeGenericMethod(type).Invoke(null, new[] { exposableData, null }));
                }

                if (typeof(ISynchronizable).IsAssignableFrom(type))
                {
                    var obj = Activator.CreateInstance(type);

                    ((ISynchronizable)obj).Sync(new ReadingSyncWorker(data));
                    return(obj);
                }

                if (type.IsEnum)
                {
                    Type enumType = Enum.GetUnderlyingType(type);

                    return(ReadSyncObject(data, enumType));
                }

                if (type.IsArray && type.GetArrayRank() == 1)
                {
                    Type   elementType = type.GetElementType();
                    ushort length      = data.ReadUShort();
                    Array  arr         = Array.CreateInstance(elementType, length);
                    for (int i = 0; i < length; i++)
                    {
                        arr.SetValue(ReadSyncObject(data, elementType), i);
                    }
                    return(arr);
                }

                if (type.IsGenericType)
                {
                    if (type.GetGenericTypeDefinition() == typeof(List <>))
                    {
                        ListType specialList = ReadSync <ListType>(data);
                        if (specialList == ListType.MapAllThings)
                        {
                            return(map.listerThings.AllThings);
                        }

                        if (specialList == ListType.MapAllDesignations)
                        {
                            return(map.designationManager.allDesignations);
                        }

                        Type   listType = type.GetGenericArguments()[0];
                        ushort size     = data.ReadUShort();
                        IList  list     = (IList)Activator.CreateInstance(type, size);
                        for (int j = 0; j < size; j++)
                        {
                            list.Add(ReadSyncObject(data, listType));
                        }

                        return(list);
                    }

                    if (type.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                    {
                        Type element = type.GetGenericArguments()[0];
                        return(ReadSyncObject(data, typeof(List <>).MakeGenericType(element)));
                    }

                    if (type.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        bool isNull = data.ReadBool();
                        if (isNull)
                        {
                            return(null);
                        }

                        bool hasValue = data.ReadBool();
                        if (!hasValue)
                        {
                            return(Activator.CreateInstance(type));
                        }

                        Type nullableType = type.GetGenericArguments()[0];
                        return(Activator.CreateInstance(type, ReadSyncObject(data, nullableType)));
                    }
                }

                // Def is a special case until the workers can read their own type
                if (typeof(Def).IsAssignableFrom(type))
                {
                    ushort shortHash = data.ReadUShort();
                    if (shortHash == 0)
                    {
                        return(null);
                    }

                    Def def = (Def)GetDefByIdMethod.MakeGenericMethod(type).Invoke(null, new object[] { shortHash });
                    if (def == null)
                    {
                        throw new Exception($"Couldn't find {type} with short hash {shortHash}");
                    }

                    return(def);
                }

                // Where the magic happens
                if (syncWorkers.TryGetValue(type, out var syncWorkerEntry))
                {
                    object res = null;

                    if (syncWorkerEntry.shouldConstruct || type.IsValueType)
                    {
                        res = Activator.CreateInstance(type);
                    }

                    syncWorkerEntry.Invoke(new ReadingSyncWorker(data), ref res);

                    return(res);
                }

                throw new SerializationException("No reader for type " + type);
            }
            catch (Exception e)
            {
                MpLog.Error($"Error reading type: {type}, {e}");
                throw;
            }
        }
コード例 #51
0
 public static void DrawLink( ref Vector2 cur, Rect container, Def def )
 {
 }
コード例 #52
0
 private void SetArgValue(Def <Args> arg, int value)
 {
     arg.Value = value;
 }
コード例 #53
0
 /// <summary>
 /// Create a struct from a struct definition and a sequence of alternating keys and values.
 /// </summary>
 /// <param name="def">The struct definition</param>
 /// <param name="keyvals">A sequence of alternating keys and values.</param>
 /// <returns>A <see cref="PersistentStructMap">PersistentStructMap</see>.</returns>
 public static PersistentStructMap create(Def def, ISeq keyvals)
 {
     object[] vals = new object[def.Keyslots.count()];
     IPersistentMap ext = PersistentHashMap.EMPTY;
     for (; keyvals != null; keyvals = keyvals.rest().rest())
     {
         if (keyvals.rest() == null)
             throw new ArgumentException(String.Format("No value supplied for key: {0}", keyvals.first()));
         object k = keyvals.first();
         object v = keyvals.rest().first();
         IMapEntry me = def.Keyslots.entryAt(k);
         if (me != null)
             vals[Util.ConvertToInt(me.val())] = v;
         else
             ext = ext.assoc(k, v);
     }
     return new PersistentStructMap(null, def, vals, ext);
 }
コード例 #54
0
 public EmitSyntax Label(Def <Labels> label)
 {
     this.il.MarkLabel(GetLabelValue(label));
     return(this);
 }
コード例 #55
0
ファイル: DefCrud.cs プロジェクト: nampn/ODental
 ///<summary>Updates one Def in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
 internal static void Update(Def def,Def oldDef)
 {
     string command="";
     if(def.Category != oldDef.Category) {
         if(command!=""){ command+=",";}
         command+="Category = "+POut.Int   ((int)def.Category)+"";
     }
     if(def.ItemOrder != oldDef.ItemOrder) {
         if(command!=""){ command+=",";}
         command+="ItemOrder = "+POut.Int(def.ItemOrder)+"";
     }
     if(def.ItemName != oldDef.ItemName) {
         if(command!=""){ command+=",";}
         command+="ItemName = '"+POut.String(def.ItemName)+"'";
     }
     if(def.ItemValue != oldDef.ItemValue) {
         if(command!=""){ command+=",";}
         command+="ItemValue = '"+POut.String(def.ItemValue)+"'";
     }
     if(def.ItemColor != oldDef.ItemColor) {
         if(command!=""){ command+=",";}
         command+="ItemColor = "+POut.Int(def.ItemColor.ToArgb())+"";
     }
     if(def.IsHidden != oldDef.IsHidden) {
         if(command!=""){ command+=",";}
         command+="IsHidden = "+POut.Bool(def.IsHidden)+"";
     }
     if(command==""){
         return;
     }
     command="UPDATE definition SET "+command
         +" WHERE DefNum = "+POut.Long(def.DefNum);
     Db.NonQ(command);
 }
コード例 #56
0
        private float ValueFactorFromRace(Def def)
        {
            var extraRaceProps = def.GetModExtension <ExtendedRaceProperties>() ?? ExtendedRaceProperties.defaultValues;

            return(extraRaceProps.adrenalineGainFactorNatural);
        }
コード例 #57
0
 public Instance(Chore <Instance> chore, Def def)
     : base((IStateMachineTarget)chore, def)
 {
     chore.AddPrecondition(IsBagged, null);
 }
コード例 #58
0
ファイル: DefExtensions.cs プロジェクト: vishalswami/RimWorld
        public static Color IconColor(this Def def)
        {
            bool  flag = DefExtensions._cachedIconColors.ContainsKey(def);
            Color result;

            if (flag)
            {
                result = DefExtensions._cachedIconColors[def];
            }
            else
            {
                BuildableDef bdef  = def as BuildableDef;
                ThingDef     tdef  = def as ThingDef;
                PawnKindDef  pdef  = def as PawnKindDef;
                RecipeDef    rdef  = def as RecipeDef;
                bool         flag2 = rdef != null;
                if (flag2)
                {
                    bool flag3 = !rdef.products.NullOrEmpty <ThingDefCountClass>();
                    if (flag3)
                    {
                        DefExtensions._cachedIconColors.Add(def, rdef.products.First <ThingDefCountClass>().thingDef.IconColor());
                        return(DefExtensions._cachedIconColors[def]);
                    }
                }
                bool flag4 = pdef != null;
                if (flag4)
                {
                    DefExtensions._cachedIconColors.Add(def, pdef.lifeStages.Last <PawnKindLifeStage>().bodyGraphicData.color);
                    result = DefExtensions._cachedIconColors[def];
                }
                else
                {
                    bool flag5 = bdef == null;
                    if (flag5)
                    {
                        DefExtensions._cachedIconColors.Add(def, Color.white);
                        result = DefExtensions._cachedIconColors[def];
                    }
                    else
                    {
                        bool flag6 = tdef != null && tdef.entityDefToBuild != null;
                        if (flag6)
                        {
                            DefExtensions._cachedIconColors.Add(def, tdef.entityDefToBuild.IconColor());
                            result = DefExtensions._cachedIconColors[def];
                        }
                        else
                        {
                            bool flag7 = bdef.graphic != null;
                            if (flag7)
                            {
                                DefExtensions._cachedIconColors.Add(def, bdef.graphic.color);
                                result = DefExtensions._cachedIconColors[def];
                            }
                            else
                            {
                                bool flag8 = tdef != null && tdef.MadeFromStuff;
                                if (flag8)
                                {
                                    ThingDef stuff = GenStuff.DefaultStuffFor(tdef);
                                    DefExtensions._cachedIconColors.Add(def, stuff.stuffProps.color);
                                    result = DefExtensions._cachedIconColors[def];
                                }
                                else
                                {
                                    DefExtensions._cachedIconColors.Add(def, Color.white);
                                    result = DefExtensions._cachedIconColors[def];
                                }
                            }
                        }
                    }
                }
            }
            return(result);
        }
コード例 #59
0
        public ILNfaCompiler(AstNode node, EmitSyntax emit, ILCompilerSettings settings)
        {
            this.Scanner = new StemScanner();

            this.emit = emit;
            this.settings = settings;

            var labels = emit.Labels;
            NEXT_THREAD     = labels.Generate();
            RESUME_ALL      = labels.Generate();
            NEXT_INPUT      = labels.Generate();
            THREAD_SUSPEND  = labels.Generate();
            THREAD_DISPATCH = labels.Generate();

            var LABEL0      = labels.Generate();
            var LABEL1      = labels.Generate();
            var POSTCOMPILEINIT = labels.Generate();
            var POSTCOMPILEINIT_BACK = labels.Generate();

            var locals = emit.Locals;
            slots        = locals.Generate();
            labelIndexToLocation = locals.Generate();
            intTmp       = locals.Generate();
            threadTmp    = locals.Generate();

            INfaVM code = this;

            this.inputPump = new ArrayLoopGenerator(
                       valueType: emit.Types.Int32,
                       ldarray:   settings.LdInput,
                       body:
                           il => il
                               .Do(matchedStack.Clear)
                               .Br(RESUME_ALL.GetRef())
                        );

            this.runningStack   = new StackGenerator(emit, typeof(Thread));
            this.suspendedStack = new StackGenerator(emit, typeof(Thread));
            this.matchedStack   = new StackGenerator(emit, typeof(Thread));
            this.tmpStack       = new StackGenerator(emit, typeof(Thread), nullContainer: true);

            emit
                .Local(intTmp, emit.Types.Int32)
                .Local(slots, emit.Types.Import(typeof(int[])))
                .Local(labelIndexToLocation, emit.Types.Import(typeof(int[])))
                .Br(POSTCOMPILEINIT.GetRef())
                .Label(POSTCOMPILEINIT_BACK)
                .Local(threadTmp, emit.Types.Import(typeof(Thread)))
                .Ldloca(threadTmp.GetRef())
                .Initobj(emit.Types.Import(typeof(Thread)))
                .Do(inputPump.EmitInitialization)
                ;

            new RegularNfaVMCompiler().Compile(node, code);

            int LabelCount = Math.Max(1, indexToLabel.Count);

            this.runningStack.SetSize(LabelCount);
            this.suspendedStack.SetSize(LabelCount);
            this.matchedStack.SetSize(LabelCount);
            this.tmpStack.SetSize(LabelCount);

            emit
                .Label(POSTCOMPILEINIT)
                .Do(runningStack.Init)
                .Do(suspendedStack.Init)
                .Do(matchedStack.Init)
                .Do(tmpStack.Init)
                .Ldc_I4(slotCount)
                .Newarr(emit.Types.Int32)
                .Stloc(slots.GetRef())

                .Ldc_I4(LabelCount)
                .Newarr(emit.Types.Int32)
                .Stloc(labelIndexToLocation.GetRef())
                // Fill labelIndexToLocation with -1 :
                .Ldc_I4(LabelCount).Stloc(intTmp.GetRef())

                .Label(LABEL1)
                .Ldloc(intTmp.GetRef())
                .Ldc_I4_0()
                .Beq(LABEL0.GetRef())
                .Ldloc(intTmp.GetRef())
                .Ldc_I4(1)
                .Sub()
                .Stloc(intTmp.GetRef())
                .Ldloc(labelIndexToLocation.GetRef())
                .Ldloc(intTmp.GetRef())
                .Ldc_I4(int.MinValue)
                .Stelem_I4()
                .Br(LABEL1.GetRef())
                .Label(LABEL0)
                .Br(POSTCOMPILEINIT_BACK.GetRef());

            // Save thread as suspended (stack should already contain label index to suspend)
            emit.Label(THREAD_SUSPEND);
            StThreadValueByRuntimeLabelIndex();
            emit
                // Don't add thread if same thread (same label index
                // with current input location) already exists in a list.
                .Ldloc(labelIndexToLocation.GetRef())
                .Ldloca(threadTmp.GetRef())
                .Ldfld(LabelIndexField)
                .Ldelem_I4()
                .Ldloc(inputPump.Index.GetRef())
                .Beq(NEXT_THREAD.GetRef())

                // Mark label index as visited
                .Ldloc(labelIndexToLocation.GetRef())
                .Ldloca(threadTmp.GetRef())
                .Ldfld(LabelIndexField)
                .Ldloc(inputPump.Index.GetRef())
                .Stelem_I4()
                ;

            suspendedStack.PushFrom(emit, threadTmp);

            emit
                .Br(NEXT_THREAD.GetRef())

                .Label(RESUME_ALL)
                .Swap(suspendedStack.Stack, runningStack.Stack, tmpStack.Stack)
                .Swap(suspendedStack.Index, runningStack.Index, tmpStack.Index)
                .Label(NEXT_THREAD)
                ;

            runningStack
                .StackLoop(
                    emit,
                    (emit2, thread) =>
                    {
                        emit2
                            .Ldloca(thread.GetRef())
                            .Ldfld(LabelIndexField)
                            .Label(THREAD_DISPATCH)
                            .Switch(indexToLabel.Select(def => def.GetRef()).ToArray())
                            .Br(settings.FAILURE.GetRef());
                    })
                    ;
            emit
                .Br(NEXT_INPUT.GetRef())
                ;

            emit
                .Label(NEXT_INPUT)
                ;

            inputPump.EmitLoopPass(emit, false);

            emit
                // Check if there are matched threads:
                .Do(matchedStack.LdCount)
                .Ldc_I4_0()
                .Beq(settings.FAILURE.GetRef())
                .Br(settings.SUCCESS.GetRef());
        }
コード例 #60
0
        public static void WriteSyncObject(ByteWriter data, object obj, SyncType syncType)
        {
            MpContext context = data.MpContext();
            Type      type    = syncType.type;

            LoggingByteWriter log = data as LoggingByteWriter;

            log?.LogEnter(type.FullName + ": " + (obj ?? "null"));

            if (obj != null && !type.IsAssignableFrom(obj.GetType()))
            {
                throw new SerializationException($"Serializing with type {type} but got object of type {obj.GetType()}");
            }

            try
            {
                if (typeof(object) == type)
                {
                    return;
                }

                if (type.IsByRef)
                {
                    return;
                }

                if (syncWorkersEarly.TryGetValue(type, out var syncWorkerEntryEarly))
                {
                    syncWorkerEntryEarly.Invoke(new WritingSyncWorker(data), ref obj);

                    return;
                }

                if (syncType.expose)
                {
                    if (!typeof(IExposable).IsAssignableFrom(type))
                    {
                        throw new SerializationException($"Type {type} can't be exposed because it isn't IExposable");
                    }

                    IExposable exposable = obj as IExposable;
                    data.WritePrefixedBytes(ScribeUtil.WriteExposable(exposable));

                    return;
                }

                if (typeof(ISynchronizable).IsAssignableFrom(type))
                {
                    ((ISynchronizable)obj).Sync(new WritingSyncWorker(data));

                    return;
                }

                if (type.IsEnum)
                {
                    Type enumType = Enum.GetUnderlyingType(type);

                    WriteSyncObject(data, Convert.ChangeType(obj, enumType), enumType);

                    return;
                }

                if (type.IsArray && type.GetArrayRank() == 1)
                {
                    Type  elementType = type.GetElementType();
                    Array arr         = (Array)obj;

                    if (arr.Length > ushort.MaxValue)
                    {
                        throw new Exception($"Tried to serialize a {elementType}[] with too many ({arr.Length}) items.");
                    }

                    data.WriteUShort((ushort)arr.Length);
                    foreach (object e in arr)
                    {
                        WriteSyncObject(data, e, elementType);
                    }

                    return;
                }

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
                {
                    ListType specialList = ListType.Normal;
                    Type     listType    = type.GetGenericArguments()[0];

                    if (listType == typeof(Thing) && obj == Find.CurrentMap.listerThings.AllThings)
                    {
                        context.map = Find.CurrentMap;
                        specialList = ListType.MapAllThings;
                    }
                    else if (listType == typeof(Designation) && obj == Find.CurrentMap.designationManager.allDesignations)
                    {
                        context.map = Find.CurrentMap;
                        specialList = ListType.MapAllDesignations;
                    }

                    WriteSync(data, specialList);

                    if (specialList == ListType.Normal)
                    {
                        IList list = (IList)obj;

                        if (list.Count > ushort.MaxValue)
                        {
                            throw new Exception($"Tried to serialize a {type} with too many ({list.Count}) items.");
                        }

                        data.WriteUShort((ushort)list.Count);
                        foreach (object e in list)
                        {
                            WriteSyncObject(data, e, listType);
                        }
                    }

                    return;
                }

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    bool isNull = obj == null;
                    data.WriteBool(isNull);
                    if (isNull)
                    {
                        return;
                    }

                    bool hasValue = (bool)obj.GetPropertyOrField("HasValue");
                    data.WriteBool(hasValue);

                    Type nullableType = type.GetGenericArguments()[0];
                    if (hasValue)
                    {
                        WriteSyncObject(data, obj.GetPropertyOrField("Value"), nullableType);
                    }

                    return;
                }

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    IEnumerable e           = (IEnumerable)obj;
                    Type        elementType = type.GetGenericArguments()[0];
                    var         listType    = typeof(List <>).MakeGenericType(elementType);
                    IList       list        = (IList)Activator.CreateInstance(listType);

                    foreach (var o in e)
                    {
                        if (list.Count > ushort.MaxValue)
                        {
                            throw new Exception($"Tried to serialize a {type} with too many ({list.Count}) items.");
                        }
                        list.Add(o);
                    }

                    WriteSyncObject(data, list, listType);

                    return;
                }

                // special case
                if (typeof(Def).IsAssignableFrom(type))
                {
                    Def def = obj as Def;
                    data.WriteUShort(def != null ? def.shortHash : (ushort)0);

                    return;
                }

                // Where the magic happens
                if (syncWorkers.TryGetValue(type, out var syncWorkerEntry))
                {
                    syncWorkerEntry.Invoke(new WritingSyncWorker(data), ref obj);

                    return;
                }

                log?.LogNode("No writer for " + type);
                throw new SerializationException("No writer for type " + type);
            }
            catch (Exception e)
            {
                MpLog.Error($"Error writing type: {type}, obj: {obj}, {e}");
                throw;
            }
            finally
            {
                log?.LogExit();
            }
        }